Skip to content

base

Class info

Classes

Name Children Inherits
BaseCommand
slashed.base
Abstract base class for commands.
Command
slashed.base
Concrete command that can be created directly.
    CommandContext
    slashed.base
    Context passed to command handlers.
      CommandResult
      slashed.base
      Result from command execution.
        OutputWriter
        slashed.base
        Interface for command output.
        ParsedCommand
        slashed.base
        Complete parsed command.
          ParsedCommandArgs
          slashed.base
          Arguments parsed from a command string.

            🛈 DocStrings

            Base interfaces for the command system.

            BaseCommand

            Bases: ABC

            Abstract base class for commands.

            Source code in src/slashed/base.py
            class BaseCommand(ABC):
                """Abstract base class for commands."""
            
                name: str
                """Command name"""
            
                description: str
                """Command description"""
            
                category: str
                """Command category"""
            
                usage: str | None
                """Command usage"""
            
                _help_text: str | None
                """Optional help text"""
            
                raw_args: bool = False
                """Pass the words after the command name unparsed, as positional arguments.
            
                For commands forwarding an argv (``/exec git -C dir status``): no ``--flag value``
                parsing and no ``--help`` interception.
                """
            
                def get_callable(self) -> Callable[..., Any]:
                    """The callable whose signature defines the command's parameters."""
                    return self.execute
            
                def is_available(self) -> bool:
                    """Check if command is currently available.
            
                    Override or use condition predicate to implement dynamic availability.
                    """
                    return True
            
                def is_visible(self, ctx: CommandContext[Any]) -> bool:
                    """Check if command should be visible in command listings.
            
                    Override to implement context-dependent visibility. This is called
                    when listing commands to filter which ones should be shown to the user.
            
                    Args:
                        ctx: The command context, providing access to context data
            
                    Returns:
                        True if command should be listed, False to hide it
                    """
                    return True
            
                def get_completer(self) -> CompletionProvider | None:
                    """Get completion provider for this command if supported."""
                    return None
            
                def format_usage(self) -> str | None:
                    """Format usage string."""
                    if not self.usage:
                        return None
                    return f"Usage: /{self.name} {self.usage}"
            
                @property
                def help_text(self) -> str:
                    """Get help text, falling back to description if not set."""
                    return self._help_text or self.description
            
                @abstractmethod
                async def execute(
                    self, ctx: CommandContext[Any], args: list[str], kwargs: dict[str, str]
                ) -> Any:
                    """Execute the command with parsed arguments."""
                    ...
            

            category instance-attribute

            category: str
            

            Command category

            description instance-attribute

            description: str
            

            Command description

            help_text property

            help_text: str
            

            Get help text, falling back to description if not set.

            name instance-attribute

            name: str
            

            Command name

            raw_args class-attribute instance-attribute

            raw_args: bool = False
            

            Pass the words after the command name unparsed, as positional arguments.

            For commands forwarding an argv (/exec git -C dir status): no --flag value parsing and no --help interception.

            usage instance-attribute

            usage: str | None
            

            Command usage

            execute abstractmethod async

            execute(ctx: CommandContext[Any], args: list[str], kwargs: dict[str, str]) -> Any
            

            Execute the command with parsed arguments.

            Source code in src/slashed/base.py
            @abstractmethod
            async def execute(
                self, ctx: CommandContext[Any], args: list[str], kwargs: dict[str, str]
            ) -> Any:
                """Execute the command with parsed arguments."""
                ...
            

            format_usage

            format_usage() -> str | None
            

            Format usage string.

            Source code in src/slashed/base.py
            def format_usage(self) -> str | None:
                """Format usage string."""
                if not self.usage:
                    return None
                return f"Usage: /{self.name} {self.usage}"
            

            get_callable

            get_callable() -> Callable[..., Any]
            

            The callable whose signature defines the command's parameters.

            Source code in src/slashed/base.py
            def get_callable(self) -> Callable[..., Any]:
                """The callable whose signature defines the command's parameters."""
                return self.execute
            

            get_completer

            get_completer() -> CompletionProvider | None
            

            Get completion provider for this command if supported.

            Source code in src/slashed/base.py
            def get_completer(self) -> CompletionProvider | None:
                """Get completion provider for this command if supported."""
                return None
            

            is_available

            is_available() -> bool
            

            Check if command is currently available.

            Override or use condition predicate to implement dynamic availability.

            Source code in src/slashed/base.py
            def is_available(self) -> bool:
                """Check if command is currently available.
            
                Override or use condition predicate to implement dynamic availability.
                """
                return True
            

            is_visible

            is_visible(ctx: CommandContext[Any]) -> bool
            

            Check if command should be visible in command listings.

            Override to implement context-dependent visibility. This is called when listing commands to filter which ones should be shown to the user.

            Parameters:

            Name Type Description Default
            ctx CommandContext[Any]

            The command context, providing access to context data

            required

            Returns:

            Type Description
            bool

            True if command should be listed, False to hide it

            Source code in src/slashed/base.py
            def is_visible(self, ctx: CommandContext[Any]) -> bool:
                """Check if command should be visible in command listings.
            
                Override to implement context-dependent visibility. This is called
                when listing commands to filter which ones should be shown to the user.
            
                Args:
                    ctx: The command context, providing access to context data
            
                Returns:
                    True if command should be listed, False to hide it
                """
                return True
            

            Command

            Bases: BaseCommand

            Concrete command that can be created directly.

            Class Type Parameters:

            Name Bound or Constraints Description Default
            TContext

            Type of the context data. Defaults to Any for flexibility. Use explicit type parameter for type-safe commands.

            Any
            Example
            # Untyped command (backward compatible)
            cmd = Command(my_func, name="test")
            
            # Typed command with context data type
            cmd: Command[MyContext] = Command(
                my_func,
                name="test",
            )
            
            Source code in src/slashed/base.py
            class Command[TContext = Any](BaseCommand):
                """Concrete command that can be created directly.
            
                Type Parameters:
                    TContext: Type of the context data. Defaults to Any for flexibility.
                              Use explicit type parameter for type-safe commands.
            
                Example:
                    ```python
                    # Untyped command (backward compatible)
                    cmd = Command(my_func, name="test")
            
                    # Typed command with context data type
                    cmd: Command[MyContext] = Command(
                        my_func,
                        name="test",
                    )
                    ```
                """
            
                _execute_func: CommandFunc
                _visible: VisibilityPredicate[TContext] | None
            
                def __init__(
                    self,
                    execute_func: CommandFunc,
                    *,
                    name: str | None = None,
                    description: str | None = None,
                    category: str = "general",
                    usage: str | None = None,
                    help_text: str | None = None,
                    completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
                    condition: ConditionPredicate | None = None,
                    visible: VisibilityPredicate[TContext] | None = None,
                ) -> None:
                    """Initialize command.
            
                    Args:
                        execute_func: Function to execute command
                        name: Optional command name (defaults to function name)
                        description: Command description (defaults to function docstring)
                        category: Command category
                        usage: Optional usage string (auto-generated if None)
                        help_text: Optional help text (defaults to description)
                        completer: Optional completion provider or factory
                        condition: Optional predicate to check command availability
                        visible: Optional predicate to check command visibility in listings
                    """
                    self.name = name or getattr(execute_func, "__name__", "unknown").replace("_", "-")
                    self.description = description or execute_func.__doc__ or "No description"
                    self.category = category
                    self.usage = usage or _generate_usage(execute_func)
                    self._help_text = help_text or self.description
                    self._execute_func = execute_func
                    self._completer = completer
                    self._condition = condition
                    self._visible = visible
            
                def get_callable(self) -> Callable[..., Any]:
                    """The wrapped function, whose signature defines the parameters."""
                    return self._execute_func
            
                def is_available(self) -> bool:
                    """Check if command is available based on condition."""
                    if self._condition is not None:
                        return self._condition()
                    return True
            
                def is_visible(self, ctx: CommandContext[TContext]) -> bool:
                    """Check if command should be visible based on visibility predicate."""
                    if self._visible is not None:
                        return self._visible(ctx)
                    return True
            
                async def execute(
                    self,
                    ctx: CommandContext[TContext],
                    args: list[str] | None = None,
                    kwargs: dict[str, str] | None = None,
                ) -> Any:
                    """Execute the command using provided function."""
                    args = args or []
                    kwargs = kwargs or {}
            
                    call_args, coerced_kwargs = parse_args(self._execute_func, ctx, args, kwargs)
                    result = self._execute_func(*call_args, **coerced_kwargs)
            
                    if inspect.isawaitable(result):
                        return await result
                    return result
            
                @classmethod
                def from_raw(
                    cls,
                    func: Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]],
                    *,
                    name: str | None = None,
                    description: str | None = None,
                    category: str = "general",
                    usage: str | None = None,
                    help_text: str | None = None,
                    completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
                    condition: ConditionPredicate | None = None,
                    visible: VisibilityPredicate[Any] | None = None,
                ) -> Command[Any]:
                    """Create a command from a raw-style function.
            
                    Use this for functions that expect the traditional (ctx, args, kwargs) signature,
                    such as when wrapping external command sources.
            
                    Args:
                        func: Function with signature (ctx, args: list[str], kwargs: dict[str, str])
                        name: Optional command name (defaults to function name)
                        description: Command description (defaults to function docstring)
                        category: Command category
                        usage: Optional usage string
                        help_text: Optional help text
                        completer: Optional completion provider or factory
                        condition: Optional predicate to check command availability
                        visible: Optional predicate to check command visibility
            
                    Example:
                        ```python
                        async def handle_external(ctx, args, kwargs):
                            await external_system.execute(args, kwargs)
            
                        cmd = Command.from_raw(handle_external, name="external")
                        ```
                    """
            
                    # Simple wrapper - execute() handles awaitable detection
                    def wrapper(ctx: CommandContext[Any], *args: str, **kwargs: str) -> Any:
                        return func(ctx, list(args), kwargs)
            
                    # Preserve metadata for name/description inference
                    wrapper.__name__ = getattr(func, "__name__", "unknown")
                    wrapper.__doc__ = func.__doc__
            
                    return cls(
                        wrapper,
                        name=name,
                        description=description,
                        category=category,
                        usage=usage,
                        help_text=help_text,
                        completer=completer,
                        condition=condition,
                        visible=visible,
                    )
            
                def get_completer(self) -> CompletionProvider | None:
                    """Get completion provider."""
                    match self._completer:
                        case None:
                            return None
                        case CompletionProvider() as completer:
                            return completer
                        case Callable() as factory:
                            return factory()
                        case _:
                            typ = type(self._completer)
                            msg = f"Completer must be CompletionProvider or callable, not {typ}"
                            raise TypeError(msg)
            

            __init__

            __init__(
                execute_func: CommandFunc,
                *,
                name: str | None = None,
                description: str | None = None,
                category: str = "general",
                usage: str | None = None,
                help_text: str | None = None,
                completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
                condition: ConditionPredicate | None = None,
                visible: VisibilityPredicate[TContext] | None = None,
            ) -> None
            

            Initialize command.

            Parameters:

            Name Type Description Default
            execute_func CommandFunc

            Function to execute command

            required
            name str | None

            Optional command name (defaults to function name)

            None
            description str | None

            Command description (defaults to function docstring)

            None
            category str

            Command category

            'general'
            usage str | None

            Optional usage string (auto-generated if None)

            None
            help_text str | None

            Optional help text (defaults to description)

            None
            completer CompletionProvider | Callable[[], CompletionProvider] | None

            Optional completion provider or factory

            None
            condition ConditionPredicate | None

            Optional predicate to check command availability

            None
            visible VisibilityPredicate[TContext] | None

            Optional predicate to check command visibility in listings

            None
            Source code in src/slashed/base.py
            def __init__(
                self,
                execute_func: CommandFunc,
                *,
                name: str | None = None,
                description: str | None = None,
                category: str = "general",
                usage: str | None = None,
                help_text: str | None = None,
                completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
                condition: ConditionPredicate | None = None,
                visible: VisibilityPredicate[TContext] | None = None,
            ) -> None:
                """Initialize command.
            
                Args:
                    execute_func: Function to execute command
                    name: Optional command name (defaults to function name)
                    description: Command description (defaults to function docstring)
                    category: Command category
                    usage: Optional usage string (auto-generated if None)
                    help_text: Optional help text (defaults to description)
                    completer: Optional completion provider or factory
                    condition: Optional predicate to check command availability
                    visible: Optional predicate to check command visibility in listings
                """
                self.name = name or getattr(execute_func, "__name__", "unknown").replace("_", "-")
                self.description = description or execute_func.__doc__ or "No description"
                self.category = category
                self.usage = usage or _generate_usage(execute_func)
                self._help_text = help_text or self.description
                self._execute_func = execute_func
                self._completer = completer
                self._condition = condition
                self._visible = visible
            

            execute async

            execute(
                ctx: CommandContext[TContext],
                args: list[str] | None = None,
                kwargs: dict[str, str] | None = None,
            ) -> Any
            

            Execute the command using provided function.

            Source code in src/slashed/base.py
            async def execute(
                self,
                ctx: CommandContext[TContext],
                args: list[str] | None = None,
                kwargs: dict[str, str] | None = None,
            ) -> Any:
                """Execute the command using provided function."""
                args = args or []
                kwargs = kwargs or {}
            
                call_args, coerced_kwargs = parse_args(self._execute_func, ctx, args, kwargs)
                result = self._execute_func(*call_args, **coerced_kwargs)
            
                if inspect.isawaitable(result):
                    return await result
                return result
            

            from_raw classmethod

            from_raw(
                func: Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]],
                *,
                name: str | None = None,
                description: str | None = None,
                category: str = "general",
                usage: str | None = None,
                help_text: str | None = None,
                completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
                condition: ConditionPredicate | None = None,
                visible: VisibilityPredicate[Any] | None = None,
            ) -> Command[Any]
            

            Create a command from a raw-style function.

            Use this for functions that expect the traditional (ctx, args, kwargs) signature, such as when wrapping external command sources.

            Parameters:

            Name Type Description Default
            func Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]]

            Function with signature (ctx, args: list[str], kwargs: dict[str, str])

            required
            name str | None

            Optional command name (defaults to function name)

            None
            description str | None

            Command description (defaults to function docstring)

            None
            category str

            Command category

            'general'
            usage str | None

            Optional usage string

            None
            help_text str | None

            Optional help text

            None
            completer CompletionProvider | Callable[[], CompletionProvider] | None

            Optional completion provider or factory

            None
            condition ConditionPredicate | None

            Optional predicate to check command availability

            None
            visible VisibilityPredicate[Any] | None

            Optional predicate to check command visibility

            None
            Example
            async def handle_external(ctx, args, kwargs):
                await external_system.execute(args, kwargs)
            
            cmd = Command.from_raw(handle_external, name="external")
            
            Source code in src/slashed/base.py
            @classmethod
            def from_raw(
                cls,
                func: Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]],
                *,
                name: str | None = None,
                description: str | None = None,
                category: str = "general",
                usage: str | None = None,
                help_text: str | None = None,
                completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
                condition: ConditionPredicate | None = None,
                visible: VisibilityPredicate[Any] | None = None,
            ) -> Command[Any]:
                """Create a command from a raw-style function.
            
                Use this for functions that expect the traditional (ctx, args, kwargs) signature,
                such as when wrapping external command sources.
            
                Args:
                    func: Function with signature (ctx, args: list[str], kwargs: dict[str, str])
                    name: Optional command name (defaults to function name)
                    description: Command description (defaults to function docstring)
                    category: Command category
                    usage: Optional usage string
                    help_text: Optional help text
                    completer: Optional completion provider or factory
                    condition: Optional predicate to check command availability
                    visible: Optional predicate to check command visibility
            
                Example:
                    ```python
                    async def handle_external(ctx, args, kwargs):
                        await external_system.execute(args, kwargs)
            
                    cmd = Command.from_raw(handle_external, name="external")
                    ```
                """
            
                # Simple wrapper - execute() handles awaitable detection
                def wrapper(ctx: CommandContext[Any], *args: str, **kwargs: str) -> Any:
                    return func(ctx, list(args), kwargs)
            
                # Preserve metadata for name/description inference
                wrapper.__name__ = getattr(func, "__name__", "unknown")
                wrapper.__doc__ = func.__doc__
            
                return cls(
                    wrapper,
                    name=name,
                    description=description,
                    category=category,
                    usage=usage,
                    help_text=help_text,
                    completer=completer,
                    condition=condition,
                    visible=visible,
                )
            

            get_callable

            get_callable() -> Callable[..., Any]
            

            The wrapped function, whose signature defines the parameters.

            Source code in src/slashed/base.py
            def get_callable(self) -> Callable[..., Any]:
                """The wrapped function, whose signature defines the parameters."""
                return self._execute_func
            

            get_completer

            get_completer() -> CompletionProvider | None
            

            Get completion provider.

            Source code in src/slashed/base.py
            def get_completer(self) -> CompletionProvider | None:
                """Get completion provider."""
                match self._completer:
                    case None:
                        return None
                    case CompletionProvider() as completer:
                        return completer
                    case Callable() as factory:
                        return factory()
                    case _:
                        typ = type(self._completer)
                        msg = f"Completer must be CompletionProvider or callable, not {typ}"
                        raise TypeError(msg)
            

            is_available

            is_available() -> bool
            

            Check if command is available based on condition.

            Source code in src/slashed/base.py
            def is_available(self) -> bool:
                """Check if command is available based on condition."""
                if self._condition is not None:
                    return self._condition()
                return True
            

            is_visible

            is_visible(ctx: CommandContext[TContext]) -> bool
            

            Check if command should be visible based on visibility predicate.

            Source code in src/slashed/base.py
            def is_visible(self, ctx: CommandContext[TContext]) -> bool:
                """Check if command should be visible based on visibility predicate."""
                if self._visible is not None:
                    return self._visible(ctx)
                return True
            

            CommandContext dataclass

            Context passed to command handlers.

            Class Type Parameters:

            Name Bound or Constraints Description Default
            TData

            Type of the data available to commands. Access via get_data() for type-safe operations.

            required
            Source code in src/slashed/base.py
            @dataclass
            class CommandContext[TData]:
                """Context passed to command handlers.
            
                Type Parameters:
                    TData: Type of the data available to commands. Access via get_data()
                           for type-safe operations.
                """
            
                output: OutputWriter
                data: TData | None
                command_store: CommandStore
                metadata: dict[str, Any] = field(default_factory=dict)
                stdin: str = ""  # Input from pipe (previous command's stdout)
            
                async def print(self, message: str) -> None:
                    """Write a message to output."""
                    self.command_store.output.emit(message)
                    if self.command_store.event_handler:
                        event = CommandOutputEvent(context=self, output=message)
                        await self.command_store.event_handler(event)
                    await self.output.print(message)
            
                def get_data(self) -> TData:
                    """deprecated: Use context instead."""
                    return self.context
            
                @property
                def context(self) -> TData:
                    """Get context data, asserting it's not None.
            
                    Returns:
                        The context data
            
                    Raises:
                        RuntimeError: If data is None
                    """
                    if self.data is None:
                        msg = "Context data is None"
                        raise RuntimeError(msg)
                    return self.data
            

            context property

            context: TData
            

            Get context data, asserting it's not None.

            Returns:

            Type Description
            TData

            The context data

            Raises:

            Type Description
            RuntimeError

            If data is None

            get_data

            get_data() -> TData
            

            deprecated: Use context instead.

            Source code in src/slashed/base.py
            def get_data(self) -> TData:
                """deprecated: Use context instead."""
                return self.context
            

            print async

            print(message: str) -> None
            

            Write a message to output.

            Source code in src/slashed/base.py
            async def print(self, message: str) -> None:
                """Write a message to output."""
                self.command_store.output.emit(message)
                if self.command_store.event_handler:
                    event = CommandOutputEvent(context=self, output=message)
                    await self.command_store.event_handler(event)
                await self.output.print(message)
            

            CommandResult dataclass

            Result from command execution.

            This represents the output of a command that can be piped to another command. Separate from ctx.print() which is for user-facing status messages.

            Attributes:

            Name Type Description
            stdout str

            Standard output (data that can be piped)

            stderr str

            Standard error (error messages)

            exit_code int

            Exit code (0 = success, non-zero = failure)

            Source code in src/slashed/base.py
            @dataclass
            class CommandResult:
                """Result from command execution.
            
                This represents the output of a command that can be piped to another command.
                Separate from ctx.print() which is for user-facing status messages.
            
                Attributes:
                    stdout: Standard output (data that can be piped)
                    stderr: Standard error (error messages)
                    exit_code: Exit code (0 = success, non-zero = failure)
                """
            
                stdout: str = ""
                stderr: str = ""
                exit_code: int = 0
            
                def __bool__(self) -> bool:
                    """Return True if command succeeded (exit_code == 0)."""
                    return self.exit_code == 0
            

            __bool__

            __bool__() -> bool
            

            Return True if command succeeded (exit_code == 0).

            Source code in src/slashed/base.py
            def __bool__(self) -> bool:
                """Return True if command succeeded (exit_code == 0)."""
                return self.exit_code == 0
            

            OutputWriter

            Bases: Protocol

            Interface for command output.

            Source code in src/slashed/base.py
            class OutputWriter(Protocol):
                """Interface for command output."""
            
                async def print(self, message: str) -> None:
                    """Write a message to output."""
                    ...
            

            print async

            print(message: str) -> None
            

            Write a message to output.

            Source code in src/slashed/base.py
            async def print(self, message: str) -> None:
                """Write a message to output."""
                ...
            

            ParsedCommand dataclass

            Complete parsed command.

            Source code in src/slashed/base.py
            @dataclass
            class ParsedCommand:
                """Complete parsed command."""
            
                name: str
                args: ParsedCommandArgs
            

            ParsedCommandArgs dataclass

            Arguments parsed from a command string.

            Source code in src/slashed/base.py
            @dataclass
            class ParsedCommandArgs:
                """Arguments parsed from a command string."""
            
                args: list[str]
                kwargs: dict[str, str]
            

            extract_usage_params

            extract_usage_params(func: Callable[..., Any], *, skip_first: bool = False) -> list[str]
            

            Extract usage parameters from a function's signature.

            Parameters:

            Name Type Description Default
            func Callable[..., Any]

            The function to extract usage from

            required
            skip_first bool

            If True, skip the first parameter (for methods with 'self')

            False
            Source code in src/slashed/base.py
            def extract_usage_params(func: Callable[..., Any], *, skip_first: bool = False) -> list[str]:
                """Extract usage parameters from a function's signature.
            
                Args:
                    func: The function to extract usage from
                    skip_first: If True, skip the first parameter (for methods with 'self')
                """
                sig = inspect.signature(func, annotation_format=annotationlib.Format.FORWARDREF)
                params = list(sig.parameters.items())
            
                if skip_first and params:
                    params = params[1:]
            
                # Check if first parameter is a context
                if params and _is_context_param(params[0][0], func):
                    params = params[1:]
            
                usage_params = []
                for name, param in params:
                    if param.default == inspect.Parameter.empty:
                        usage_params.append(f"<{name}>")
                    else:
                        usage_params.append(f"[--{name} <value>]")
                return usage_params
            

            parse_args

            parse_args(
                func: Callable[..., Any],
                ctx: CommandContext[Any],
                args: list[str],
                kwargs: dict[str, str],
                *,
                skip_first: bool = False,
            ) -> tuple[list[Any], dict[str, Any]]
            

            Parse parameters and return positional and keyword arguments with type coercion.

            Parameters:

            Name Type Description Default
            func Callable[..., Any]

            The function to parse arguments for

            required
            ctx CommandContext[Any]

            The command context

            required
            args list[str]

            Positional arguments from command line

            required
            kwargs dict[str, str]

            Keyword arguments from command line

            required
            skip_first bool

            If True, skip the first parameter (for methods with 'self')

            False

            Returns:

            Type Description
            tuple[list[Any], dict[str, Any]]

            Tuple of (positional_args, keyword_args) with values coerced to annotated types

            Source code in src/slashed/base.py
            def parse_args(
                func: Callable[..., Any],
                ctx: CommandContext[Any],
                args: list[str],
                kwargs: dict[str, str],
                *,
                skip_first: bool = False,
            ) -> tuple[list[Any], dict[str, Any]]:
                """Parse parameters and return positional and keyword arguments with type coercion.
            
                Args:
                    func: The function to parse arguments for
                    ctx: The command context
                    args: Positional arguments from command line
                    kwargs: Keyword arguments from command line
                    skip_first: If True, skip the first parameter (for methods with 'self')
            
                Returns:
                    Tuple of (positional_args, keyword_args) with values coerced to annotated types
                """
                # Get resolved type hints (handles 'from __future__ import annotations' and Annotated)
                type_hints = _get_resolved_hints(func)
            
                # Expand shorthand kwargs (e.g., -v -> --verbose) using Annotated[..., Short("v")]
                shorthand_map = _get_shorthand_map(func)
                kwargs = _expand_shorthand_kwargs(kwargs, shorthand_map)
            
                sig = inspect.signature(func, annotation_format=annotationlib.Format.FORWARDREF)
                params_list = list(sig.parameters.items())
                if skip_first and params_list:
                    params_list = params_list[1:]
                parameters = dict(params_list)
            
                # Check if we need to pass context
                param_names = list(parameters.keys())
                has_ctx = param_names and _is_context_param(param_names[0], func)
            
                # Prepare parameters for matching, excluding context if present
                if has_ctx:
                    ctx_param_name = param_names[0]
                    parameters_for_matching = {k: v for k, v in parameters.items() if k != ctx_param_name}
                    call_args: list[str | CommandContext[Any]] = [ctx]
                else:
                    parameters_for_matching = parameters
                    call_args = []
            
                # Check for variadic parameters (*args, **kwargs)
                has_var_positional = any(
                    p.kind == inspect.Parameter.VAR_POSITIONAL for p in parameters_for_matching.values()
                )
                has_var_keyword = any(
                    p.kind == inspect.Parameter.VAR_KEYWORD for p in parameters_for_matching.values()
                )
            
                # If function accepts *args and **kwargs, just pass everything through
                if has_var_positional and has_var_keyword:
                    call_args.extend(args)
                    return call_args, kwargs
            
                # Get parameters BEFORE VAR_POSITIONAL (regular positional params)
                # and parameters AFTER VAR_POSITIONAL (keyword-only params)
                pre_var_positional: list[tuple[str, inspect.Parameter]] = []
                post_var_positional: list[tuple[str, inspect.Parameter]] = []
                found_var_positional = False
            
                for name, param in parameters_for_matching.items():
                    if param.kind == inspect.Parameter.VAR_POSITIONAL:
                        found_var_positional = True
                    elif param.kind == inspect.Parameter.VAR_KEYWORD:
                        continue  # Skip **kwargs
                    elif found_var_positional:
                        post_var_positional.append((name, param))
                    else:
                        pre_var_positional.append((name, param))
            
                # param_list for backwards compatibility - only non-variadic params
                param_list = pre_var_positional + post_var_positional
                [name for name, param in param_list if param.default == inspect.Parameter.empty]
            
                # When there's VAR_POSITIONAL, positional args after the pre_var params go to *args
                # Only check for too many args if there's no VAR_POSITIONAL
                if not has_var_positional:
                    max_positional = len(param_list)
                    if len(args) > max_positional:
                        param_names_list = [name for name, _ in param_list]
                        msg = (
                            f"Too many positional arguments. Expected at most {max_positional} "
                            f"({param_names_list}), got {len(args)}"
                        )
                        raise CommandError(msg)
            
                # Check for conflicts - only for pre_var_positional params
                # Args beyond pre_var_positional count go to *args, not to keyword-only params
                num_regular_positional = min(len(args), len(pre_var_positional))
                positional_param_names = [name for name, _ in pre_var_positional[:num_regular_positional]]
                conflicts = set(positional_param_names) & set(kwargs.keys())
                if conflicts:
                    msg = f"Arguments provided both positionally and as keywords: {list(conflicts)}"
                    raise CommandError(msg)
            
                # Check if required args are provided either as positional or keyword
                # For pre_var_positional params: can be filled by positional args or kwargs
                # For post_var_positional params (keyword-only): MUST be provided as kwargs
                required_pre = [name for name, p in pre_var_positional if p.default == inspect.Parameter.empty]
                required_post = [
                    name for name, p in post_var_positional if p.default == inspect.Parameter.empty
                ]
            
                missing_pre = [
                    name for idx, name in enumerate(required_pre) if name not in kwargs and len(args) <= idx
                ]
                missing_post = [name for name in required_post if name not in kwargs]
                missing = missing_pre + missing_post
            
                if missing:
                    msg = f"Missing required arguments: {missing}"
                    raise CommandError(msg)
            
                # Validate keyword arguments exist in signature (skip if function has **kwargs)
                if not has_var_keyword:
                    for name in kwargs:
                        if name not in parameters_for_matching:
                            msg = f"Unknown argument: {name}"
                            raise CommandError(msg)
            
                # Coerce positional arguments to their annotated types
                # When there's VAR_POSITIONAL, only args up to pre_var_positional count get coerced
                # to named params. The rest go directly to *args.
                coerced_args: list[Any] = []
                coercible_params = pre_var_positional if has_var_positional else param_list
                for idx, arg_value in enumerate(args):
                    if idx < len(coercible_params):
                        param_name, _param = coercible_params[idx]
                        annotation = type_hints.get(param_name, inspect.Parameter.empty)
                        coerced_args.append(_coerce_value(arg_value, annotation, param_name))
                    else:
                        # Extra args - either go to *args or were already caught as too many
                        coerced_args.append(arg_value)
            
                # Coerce keyword arguments to their annotated types
                coerced_kwargs: dict[str, Any] = {}
                for name, value in kwargs.items():
                    if name in parameters_for_matching:
                        annotation = type_hints.get(name, inspect.Parameter.empty)
                        coerced_kwargs[name] = _coerce_value(value, annotation, name)
                    else:
                        coerced_kwargs[name] = value
            
                # Add positional arguments and kwargs
                call_args.extend(coerced_args)
                return call_args, coerced_kwargs
            

            parse_command

            parse_command(cmd_str: str) -> ParsedCommand
            

            Parse command string into name and arguments.

            Parameters:

            Name Type Description Default
            cmd_str str

            Command string without leading slash

            required

            Returns:

            Type Description
            ParsedCommand

            Parsed command with name and arguments

            Raises:

            Type Description
            CommandError

            If command syntax is invalid

            Source code in src/slashed/base.py
            def parse_command(cmd_str: str) -> ParsedCommand:
                """Parse command string into name and arguments.
            
                Args:
                    cmd_str: Command string without leading slash
            
                Returns:
                    Parsed command with name and arguments
            
                Raises:
                    CommandError: If command syntax is invalid
                """
                try:
                    parts = shlex.split(cmd_str)
                except ValueError as e:
                    msg = f"Invalid command syntax: {e}"
                    raise CommandError(msg) from e
            
                if not parts:
                    msg = "Empty command"
                    raise CommandError(msg)
            
                name = parts[0]
                args = []
                kwargs = {}
            
                i = 1
                while i < len(parts):
                    part = parts[i]
                    if part.startswith("--"):
                        # Long-form argument: --name value
                        if i + 1 < len(parts):
                            kwargs[part[2:]] = parts[i + 1]
                            i += 2
                        else:
                            msg = f"Missing value for argument: {part}"
                            raise CommandError(msg)
                    elif part.startswith("-") and len(part) == 2 and part[1].isalpha():  # noqa: PLR2004
                        # Short-form argument: -x value
                        if i + 1 < len(parts):
                            kwargs[part[1:]] = parts[i + 1]  # Store with single char key
                            i += 2
                        else:
                            msg = f"Missing value for argument: {part}"
                            raise CommandError(msg)
                    else:
                        args.append(part)
                        i += 1
                args_obj = ParsedCommandArgs(args=args, kwargs=kwargs)
                return ParsedCommand(name=name, args=args_obj)