Skip to content

slashed

Class info

Re-exported classes

Class Module Description
BaseCommand slashed.base Abstract base class for commands.
CallbackCompleter slashed.completers Completer that calls a function to get completions dynamically.
CallbackOutputWriter slashed.output Output writer that directly delegates printing to a callback function.
ChainedCompleter slashed.completers Combines multiple completers.
ChoiceCompleter slashed.completers Provides completion from a fixed set of choices.
Command slashed.base Concrete command that can be created directly.
CommandContext slashed.base Context passed to command handlers.
CommandError slashed.exceptions Base exception for command-related errors.
CommandExecutedEvent slashed.events Event emitted when a command is executed.
CommandOutputEvent slashed.events Event emitted when a command is executed.
CommandRegisteredEvent slashed.events Event emitted when a command is registered.
CommandRegistry slashed.registry Collect commands for later registration.
CommandResult slashed.base Result from command execution.
CommandRouter slashed.router Generic command router supporting context-based routing.
CommandStore slashed.store Central store for command management and history.
CommandUnregisteredEvent slashed.events Event emitted when a command is unregistered.
CompletionContext slashed.completion Context for completion operations.
CompletionItem slashed.completion Single completion suggestion.
CompletionProvider slashed.completion Base class for completion providers.
DefaultOutputWriter slashed.output Default output implementation using rich if available.
EnvVarCompleter slashed.completers Environment variable completion.
ExitCommandError slashed.exceptions Special exception to signal clean Session exit.
KeywordCompleter slashed.completers Completes keyword arguments.
MultiValueCompleter slashed.completers Completes multiple values separated by a delimiter.
OutputWriter slashed.base Interface for command output.
ParsedCommand slashed.base Complete parsed command.
ParsedCommandArgs slashed.base Arguments parsed from a command string.
ParsedRoute slashed.router Parsed routing information.
PathCompleter slashed.completers Provides filesystem path completions.
QueueOutputWriter slashed.output Output writer that puts messages in queue.
Route slashed.router Route configuration.
RouteInfo slashed.router Information about a route for display.
ShellExecutor slashed.shell_executor Executes bash-like command lines with pipes and chaining.
Short slashed.annotations Marker for parameter shorthand.
SlashedCommand slashed.commands Base class for declarative commands.
TransformOutputWriter slashed.output Output writer that transforms messages before printing via another writer.

🛈 DocStrings

Slashed: main package.

Slash commands and autocompletions.

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

CallbackCompleter

Bases: CompletionProvider

Completer that calls a function to get completions dynamically.

The callback can return either strings or CompletionItems.

Example

def complete_tools(ctx: CompletionContext) -> Iterator[str]: tools = ["hammer", "screwdriver", "wrench"] return (t for t in tools if t.startswith(ctx.current_word))

command = Command( name="use-tool", description="Use a tool", completer=CallbackCompleter(complete_tools) )

Source code in src/slashed/completers.py
class CallbackCompleter(CompletionProvider):
    """Completer that calls a function to get completions dynamically.

    The callback can return either strings or CompletionItems.

    Example:
        def complete_tools(ctx: CompletionContext) -> Iterator[str]:
            tools = ["hammer", "screwdriver", "wrench"]
            return (t for t in tools if t.startswith(ctx.current_word))

        command = Command(
            name="use-tool",
            description="Use a tool",
            completer=CallbackCompleter(complete_tools)
        )
    """

    def __init__(
        self,
        callback: (
            Callable[[CompletionContext[Any]], Iterable[str | CompletionItem]]
            | Callable[[CompletionContext[Any]], Awaitable[Iterable[str | CompletionItem]]]
        ),
        kind: CompletionKind | None = None,
    ) -> None:
        self._callback = callback
        self._kind = kind
        self._is_async = inspect.iscoroutinefunction(callback)

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        try:
            result = self._callback(context)

            # Narrow type and handle async/sync appropriately
            if is_awaitable(result):
                items = await result
            else:
                items = cast(Iterable[str | CompletionItem], result)

            for item in items:
                if isinstance(item, str):
                    yield CompletionItem(text=item, kind=self._kind)
                else:
                    yield item
        except Exception as e:  # noqa: BLE001
            logger.debug("Completion callback error: %s", e)

CallbackOutputWriter

Bases: OutputWriter

Output writer that directly delegates printing to a callback function.

The callback can be either sync or async and is fully responsible for how the message is displayed/written.

Examples:

# Async callback
async def log_to_file(msg: str, file: str) -> None:
    with open(file, "a") as f:
        f.write(msg)

# Sync callback
def print_to_console(msg: str, prefix: str) -> None:
    print(f"{prefix}: {msg}")

writer1 = CallbackOutputWriter(log_to_file, "output.log")
writer2 = CallbackOutputWriter(print_to_console, prefix="Debug")
Source code in src/slashed/output.py
class CallbackOutputWriter(OutputWriter):
    """Output writer that directly delegates printing to a callback function.

    The callback can be either sync or async and is fully responsible for how
    the message is displayed/written.

    Examples:
        ```python
        # Async callback
        async def log_to_file(msg: str, file: str) -> None:
            with open(file, "a") as f:
                f.write(msg)

        # Sync callback
        def print_to_console(msg: str, prefix: str) -> None:
            print(f"{prefix}: {msg}")

        writer1 = CallbackOutputWriter(log_to_file, "output.log")
        writer2 = CallbackOutputWriter(print_to_console, prefix="Debug")
        ```
    """

    def __init__(
        self,
        callback: Callable[..., Any | Awaitable[Any]],
        *args: Any,
        **kwargs: Any,
    ) -> None:
        """Initialize with callback and its arguments."""
        self._callback = callback
        self._args = args
        self._kwargs = kwargs

    async def print(self, message: str) -> None:
        """Write message using callback."""
        result = self._callback(message, *self._args, **self._kwargs)
        if inspect.isawaitable(result):
            await result

__init__

__init__(callback: Callable[..., Any | Awaitable[Any]], *args: Any, **kwargs: Any) -> None

Initialize with callback and its arguments.

Source code in src/slashed/output.py
def __init__(
    self,
    callback: Callable[..., Any | Awaitable[Any]],
    *args: Any,
    **kwargs: Any,
) -> None:
    """Initialize with callback and its arguments."""
    self._callback = callback
    self._args = args
    self._kwargs = kwargs

print async

print(message: str) -> None

Write message using callback.

Source code in src/slashed/output.py
async def print(self, message: str) -> None:
    """Write message using callback."""
    result = self._callback(message, *self._args, **self._kwargs)
    if inspect.isawaitable(result):
        await result

ChainedCompleter

Bases: CompletionProvider

Combines multiple completers.

Source code in src/slashed/completers.py
class ChainedCompleter(CompletionProvider):
    """Combines multiple completers."""

    def __init__(self, *providers: CompletionProvider) -> None:
        """Initialize chained completer.

        Args:
            providers: Completion providers to chain
        """
        self.providers = providers

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get completions from all providers."""
        for provider in self.providers:
            async for item in provider.get_completions(context):
                yield item

__init__

__init__(*providers: CompletionProvider) -> None

Initialize chained completer.

Parameters:

Name Type Description Default
providers CompletionProvider

Completion providers to chain

()
Source code in src/slashed/completers.py
def __init__(self, *providers: CompletionProvider) -> None:
    """Initialize chained completer.

    Args:
        providers: Completion providers to chain
    """
    self.providers = providers

get_completions async

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get completions from all providers.

Source code in src/slashed/completers.py
async def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get completions from all providers."""
    for provider in self.providers:
        async for item in provider.get_completions(context):
            yield item

ChoiceCompleter

Bases: CompletionProvider

Provides completion from a fixed set of choices.

Source code in src/slashed/completers.py
class ChoiceCompleter(CompletionProvider):
    """Provides completion from a fixed set of choices."""

    def __init__(
        self,
        choices: Sequence[str] | dict[str, str],
        ignore_case: bool = True,
    ) -> None:
        """Initialize choice completer.

        Args:
            choices: Sequence of choices or mapping of choice -> description
            ignore_case: Whether to do case-insensitive matching
        """
        self.ignore_case = ignore_case
        if isinstance(choices, dict):
            self.choices = list(choices.keys())
            self.descriptions = choices
        else:
            self.choices = list(choices)
            self.descriptions = {}

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get matching choices."""
        word = context.current_word
        if self.ignore_case:
            word = word.lower()
            matches = (c for c in self.choices if c.lower().startswith(word))
        else:
            matches = (c for c in self.choices if c.startswith(word))

        for choice in matches:
            meta = self.descriptions.get(choice)
            yield CompletionItem(text=choice, metadata=meta, kind="choice")

__init__

__init__(choices: Sequence[str] | dict[str, str], ignore_case: bool = True) -> None

Initialize choice completer.

Parameters:

Name Type Description Default
choices Sequence[str] | dict[str, str]

Sequence of choices or mapping of choice -> description

required
ignore_case bool

Whether to do case-insensitive matching

True
Source code in src/slashed/completers.py
def __init__(
    self,
    choices: Sequence[str] | dict[str, str],
    ignore_case: bool = True,
) -> None:
    """Initialize choice completer.

    Args:
        choices: Sequence of choices or mapping of choice -> description
        ignore_case: Whether to do case-insensitive matching
    """
    self.ignore_case = ignore_case
    if isinstance(choices, dict):
        self.choices = list(choices.keys())
        self.descriptions = choices
    else:
        self.choices = list(choices)
        self.descriptions = {}

get_completions async

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get matching choices.

Source code in src/slashed/completers.py
async def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get matching choices."""
    word = context.current_word
    if self.ignore_case:
        word = word.lower()
        matches = (c for c in self.choices if c.lower().startswith(word))
    else:
        matches = (c for c in self.choices if c.startswith(word))

    for choice in matches:
        meta = self.descriptions.get(choice)
        yield CompletionItem(text=choice, metadata=meta, kind="choice")

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)

CommandError

Bases: Exception

Base exception for command-related errors.

Source code in src/slashed/exceptions.py
class CommandError(Exception):
    """Base exception for command-related errors."""

CommandExecutedEvent dataclass

Event emitted when a command is executed.

Source code in src/slashed/events.py
@dataclass
class CommandExecutedEvent[TData]:
    """Event emitted when a command is executed."""

    command: str
    context: CommandContext[TData]
    success: bool
    result: Any | None = None
    error: Exception | None = None

CommandOutputEvent dataclass

Event emitted when a command is executed.

Source code in src/slashed/events.py
@dataclass
class CommandOutputEvent[TData]:
    """Event emitted when a command is executed."""

    output: str
    context: CommandContext[TData]

CommandRegisteredEvent dataclass

Event emitted when a command is registered.

Source code in src/slashed/events.py
@dataclass
class CommandRegisteredEvent:
    """Event emitted when a command is registered."""

    command: BaseCommand

CommandRegistry

Collect commands for later registration.

Source code in src/slashed/registry.py
class CommandRegistry:
    """Collect commands for later registration."""

    def __init__(self) -> None:
        """Initialize registry."""
        self.commands: list[CommandEntry] = []

    def command(
        self,
        *,
        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: Callable[[], bool] | None = None,
    ) -> Callable[[TCommandFunc], TCommandFunc]:
        """Decorator to collect a command for later registration."""

        def decorator(func: TCommandFunc) -> TCommandFunc:
            cmd_name = name or getattr(func, "__name__", "command").replace("_", "-")
            entry = CommandEntry(
                name=cmd_name,
                func=func,
                description=description,
                category=category,
                usage=usage,
                help_text=help_text,
                completer=completer,
                condition=condition,
            )
            self.commands.append(entry)
            return func

        return decorator

    def register_to(self, store: CommandStore) -> None:
        """Register all collected commands to a store."""
        for entry in self.commands:
            store.add_command(
                name=entry.name,
                fn=entry.func,
                description=entry.description,
                category=entry.category,
                usage=entry.usage,
                help_text=entry.help_text,
                completer=entry.completer,
                condition=entry.condition,
            )

__init__

__init__() -> None

Initialize registry.

Source code in src/slashed/registry.py
def __init__(self) -> None:
    """Initialize registry."""
    self.commands: list[CommandEntry] = []

command

command(
    *,
    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: Callable[[], bool] | None = None,
) -> Callable[[TCommandFunc], TCommandFunc]

Decorator to collect a command for later registration.

Source code in src/slashed/registry.py
def command(
    self,
    *,
    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: Callable[[], bool] | None = None,
) -> Callable[[TCommandFunc], TCommandFunc]:
    """Decorator to collect a command for later registration."""

    def decorator(func: TCommandFunc) -> TCommandFunc:
        cmd_name = name or getattr(func, "__name__", "command").replace("_", "-")
        entry = CommandEntry(
            name=cmd_name,
            func=func,
            description=description,
            category=category,
            usage=usage,
            help_text=help_text,
            completer=completer,
            condition=condition,
        )
        self.commands.append(entry)
        return func

    return decorator

register_to

register_to(store: CommandStore) -> None

Register all collected commands to a store.

Source code in src/slashed/registry.py
def register_to(self, store: CommandStore) -> None:
    """Register all collected commands to a store."""
    for entry in self.commands:
        store.add_command(
            name=entry.name,
            fn=entry.func,
            description=entry.description,
            category=entry.category,
            usage=entry.usage,
            help_text=entry.help_text,
            completer=entry.completer,
            condition=entry.condition,
        )

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

CommandRouter

Generic command router supporting context-based routing.

Class Type Parameters:

Name Bound or Constraints Description Default
TGlobalContext

Type of the global context

required
TRouteContext

Type of route-specific contexts

required
Example
router = CommandRouter(global_context, command_store)
router.add_route("db", db_context, "Database commands")
router.add_route("fs", fs_context, "Filesystem operations")

# Execute with routing
await router.execute("@db list-tables", output)
await router.execute("@fs list-files", output)

# Execute with default context
await router.execute("help", output)
Source code in src/slashed/router.py
class CommandRouter[TGlobalContext, TRouteContext]:
    """Generic command router supporting context-based routing.

    Type Parameters:
        TGlobalContext: Type of the global context
        TRouteContext: Type of route-specific contexts

    Example:
        ```python
        router = CommandRouter(global_context, command_store)
        router.add_route("db", db_context, "Database commands")
        router.add_route("fs", fs_context, "Filesystem operations")

        # Execute with routing
        await router.execute("@db list-tables", output)
        await router.execute("@fs list-files", output)

        # Execute with default context
        await router.execute("help", output)
        ```
    """

    def __init__(
        self,
        global_context: TGlobalContext,
        commands: CommandStore,
    ) -> None:
        """Initialize router.

        Args:
            global_context: Default context for unrouted commands
            commands: Command store for execution
        """
        self.global_context = global_context
        self.commands = commands
        self._default_context: TRouteContext | None = None
        self._routes: dict[str, Route[TRouteContext]] = {}
        # Per task / thread, so concurrent temporary_context blocks don't see each other.
        self._temporary_context: ContextVar[tuple[TRouteContext] | None] = ContextVar(
            f"slashed_router_context_{id(self)}", default=None
        )

    @property
    def _active_context(self) -> TRouteContext | None:
        if (temporary := self._temporary_context.get()) is not None:
            return temporary[0]
        return self._default_context

    def add_route(
        self,
        prefix: str,
        context: TRouteContext,
        description: str = "",
        allowed_commands: set[str] | None = None,
    ) -> None:
        """Add a routable context.

        Args:
            prefix: Route prefix (without @)
            context: Context for this route
            description: Route description
            allowed_commands: Optional set of allowed command names

        Raises:
            ValueError: If route prefix already exists
        """
        if prefix in self._routes:
            msg = f"Route '{prefix}' already exists"
            raise ValueError(msg)

        route = Route(
            prefix=prefix,
            context=context,
            description=description,
            allowed_commands=allowed_commands,
        )
        self._routes[prefix] = route
        logger.debug("Added route: %s (%s)", prefix, description)

    def set_active_context(self, context: TRouteContext | None) -> None:
        """Set default context for unrouted commands.

        Args:
            context: Context to set as active, or None to use global
        """
        self._default_context = context

    @contextmanager
    def temporary_context(self, context: TRouteContext) -> Generator[None]:
        """Temporarily switch context.

        Args:
            context: Context to use temporarily

        Example:
            ```python
            with router.temporary_context(db_context):
                await router.execute("list-tables", output)
            ```
        """
        token = self._temporary_context.set((context,))
        try:
            yield
        finally:
            self._temporary_context.reset(token)

    def list_routes(self) -> list[RouteInfo]:
        """List available routes with descriptions.

        Returns:
            List of route information
        """
        return [
            RouteInfo(
                prefix=route.prefix,
                description=route.description,
                active=route.context == self._active_context,
            )
            for route in self._routes.values()
        ]

    async def show_routes(self, output: OutputWriter) -> None:
        """Display available routes.

        Args:
            output: Output writer to use
        """
        await output.print("\nAvailable routes:")
        for route in self._routes.values():
            active = " (active)" if route.context == self._active_context else ""
            await output.print(f"@{route.prefix}: {route.description}{active}")

    def _parse_route_internal(self, command: str) -> ParsedRoute[TGlobalContext | TRouteContext]:
        """Internal method for initial route parsing."""
        if not command.startswith("@"):
            # No route - check if command is restricted to a route
            command_name = command.split(maxsplit=1)[0]

            # If we have an active context, check if it matches any route context
            if self._active_context:
                for route in self._routes.values():
                    if route.context == self._active_context:
                        # We're in the right context,
                        # allow the command if it's in allowed_commands
                        if not route.allowed_commands or command_name in route.allowed_commands:
                            return ParsedRoute[TGlobalContext | TRouteContext](
                                context=self._active_context,
                                command=command,
                            )
                        break  # Found matching route but command not allowed

            # No matching active context, check if command is restricted
            for route in self._routes.values():
                if route.allowed_commands and command_name in route.allowed_commands:
                    # Command is restricted to a route but no route specified
                    msg = f"Command '{command_name}' requires a route prefix"
                    raise CommandError(msg)

            return ParsedRoute[TGlobalContext | TRouteContext](
                context=self._active_context or self.global_context,
                command=command,
            )

        prefix, _, rest = command.partition(" ")
        route_name = prefix.lstrip("@")

        if not rest:
            msg = "Missing command after route prefix"
            raise CommandError(msg)

        if route_name not in self._routes:
            msg = f"Unknown route: {route_name}"
            raise CommandError(msg)

        route = self._routes[route_name]
        command_name = rest.split()[0]

        if not route.can_execute(command_name):
            msg = f"Command '{command_name}' not allowed for route @{route_name}"
            raise CommandError(msg)

        unified_route: Route[TGlobalContext | TRouteContext] = route  # type: ignore
        return ParsedRoute[TGlobalContext | TRouteContext](
            context=route.context,
            command=rest,
            route=unified_route,
        )

    def parse_global_command(self, command: str) -> ParsedRoute[TGlobalContext]:
        """Parse a command using global context.

        Args:
            command: Command string without routing prefix

        Returns:
            Parsed route with global context

        Raises:
            CommandError: If command uses routing prefix
        """
        if command.startswith("@"):
            msg = "Routing prefix not allowed for global commands"
            raise CommandError(msg)

        # Check if command is restricted to a route
        command_name = command.split(maxsplit=1)[0]
        for route in self._routes.values():
            if route.allowed_commands and command_name in route.allowed_commands:
                # Command is restricted to a route but no route specified
                msg = f"Command '{command_name}' requires a route prefix"
                raise CommandError(msg)

        return ParsedRoute(context=self.global_context, command=command)

    def parse_routed_command(self, command: str) -> ParsedRoute[TRouteContext]:
        """Parse a command with routing prefix.

        Args:
            command: Command string with @prefix

        Returns:
            Parsed route with route-specific context

        Raises:
            CommandError: If command doesn't use routing or route is invalid
        """
        if not command.startswith("@"):
            msg = "Missing route prefix"
            raise CommandError(msg)

        parsed = self._parse_route_internal(command)
        if isinstance(parsed.context, type(self.global_context)):
            msg = "Unexpected global context for routed command"
            raise RuntimeError(msg)  # noqa: TRY004

        # We know it's TRouteContext at this point
        context = parsed.context
        if not isinstance(context, type(self._routes[next(iter(self._routes))].context)):
            msg = "Invalid context type for routed command"
            raise RuntimeError(msg)  # noqa: TRY004

        return ParsedRoute[TRouteContext](
            context=context,
            command=parsed.command,
            route=parsed.route,  # type: ignore  # We know it's the right type
        )

    async def execute(
        self,
        command: str,
        output: OutputWriter,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """Execute command with appropriate context."""
        parsed = self._parse_route_internal(command)
        ctx = self.commands.create_context(
            parsed.context,
            output_writer=output,
            metadata=metadata,
        )
        await self.commands.execute_command(parsed.command, ctx)

    async def execute_global(
        self,
        command: str,
        output: OutputWriter,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """Execute command with global context."""
        parsed = self.parse_global_command(command)
        ctx = self.commands.create_context(
            parsed.context,
            output_writer=output,
            metadata=metadata,
        )
        await self.commands.execute_command(parsed.command, ctx)

    async def execute_routed(
        self,
        command: str,
        output: OutputWriter,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """Execute command with route-specific context."""
        parsed = self.parse_routed_command(command)
        ctx = self.commands.create_context(
            parsed.context,
            output_writer=output,
            metadata=metadata,
        )
        await self.commands.execute_command(parsed.command, ctx)

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get completions including route prefixes."""
        word = context.current_word
        text = context._document.text

        # Complete route prefixes
        if word.startswith("@"):
            prefix = word[1:]
            for route in self._routes.values():
                if route.prefix.startswith(prefix):
                    yield CompletionItem(
                        text=f"@{route.prefix}",
                        metadata=route.description,
                        kind="route",
                    )
            return

        # Get route-specific completions
        try:
            # If we're after a route prefix, use that context
            parts = text.split()
            if parts and parts[0].startswith("@"):
                route_name = parts[0][1:]
                if route_name in self._routes:
                    route = self._routes[route_name]
                    # Create completion context with route context
                    route_ctx = self.commands.create_context(
                        route.context,
                        output_writer=context.command_context.output,
                    )
                    route_completion_ctx = CompletionContext(
                        document=context._document,
                        command_context=route_ctx,
                    )
                    # Use the command completer
                    if command := self.commands._commands.get(word):
                        if completer := command.get_completer():
                            async for item in completer.get_completions(route_completion_ctx):
                                yield item
                    # Or suggest commands
                    else:
                        commands = self.commands.list_commands()
                        for cmd in commands:
                            if (
                                not route.allowed_commands or cmd.name in route.allowed_commands
                            ) and cmd.name.startswith(word):
                                yield CompletionItem(
                                    text=cmd.name,
                                    metadata=cmd.description,
                                    kind="command",
                                )
            else:
                # Global context completions
                ctx = self.commands.create_context(
                    self._active_context or self.global_context,
                    output_writer=context.command_context.output,
                )
                global_completion_ctx = CompletionContext(
                    document=context._document,
                    command_context=ctx,
                )
                # First try command completer if we have a word
                if word and (command := self.commands._commands.get(word)):
                    if completer := command.get_completer():
                        async for item in completer.get_completions(global_completion_ctx):
                            yield item
                # Otherwise suggest commands
                else:
                    for cmd in self.commands.list_commands():
                        # In global context, only show commands not restricted to routes
                        if cmd.name.startswith(word) and not any(
                            route.allowed_commands and cmd.name in route.allowed_commands
                            for route in self._routes.values()
                        ):
                            yield CompletionItem(
                                text=cmd.name,
                                metadata=cmd.description,
                                kind="command",
                            )

        except CommandError:
            # Ignore routing errors during completion
            pass

__init__

__init__(global_context: TGlobalContext, commands: CommandStore) -> None

Initialize router.

Parameters:

Name Type Description Default
global_context TGlobalContext

Default context for unrouted commands

required
commands CommandStore

Command store for execution

required
Source code in src/slashed/router.py
def __init__(
    self,
    global_context: TGlobalContext,
    commands: CommandStore,
) -> None:
    """Initialize router.

    Args:
        global_context: Default context for unrouted commands
        commands: Command store for execution
    """
    self.global_context = global_context
    self.commands = commands
    self._default_context: TRouteContext | None = None
    self._routes: dict[str, Route[TRouteContext]] = {}
    # Per task / thread, so concurrent temporary_context blocks don't see each other.
    self._temporary_context: ContextVar[tuple[TRouteContext] | None] = ContextVar(
        f"slashed_router_context_{id(self)}", default=None
    )

add_route

add_route(
    prefix: str,
    context: TRouteContext,
    description: str = "",
    allowed_commands: set[str] | None = None,
) -> None

Add a routable context.

Parameters:

Name Type Description Default
prefix str

Route prefix (without @)

required
context TRouteContext

Context for this route

required
description str

Route description

''
allowed_commands set[str] | None

Optional set of allowed command names

None

Raises:

Type Description
ValueError

If route prefix already exists

Source code in src/slashed/router.py
def add_route(
    self,
    prefix: str,
    context: TRouteContext,
    description: str = "",
    allowed_commands: set[str] | None = None,
) -> None:
    """Add a routable context.

    Args:
        prefix: Route prefix (without @)
        context: Context for this route
        description: Route description
        allowed_commands: Optional set of allowed command names

    Raises:
        ValueError: If route prefix already exists
    """
    if prefix in self._routes:
        msg = f"Route '{prefix}' already exists"
        raise ValueError(msg)

    route = Route(
        prefix=prefix,
        context=context,
        description=description,
        allowed_commands=allowed_commands,
    )
    self._routes[prefix] = route
    logger.debug("Added route: %s (%s)", prefix, description)

execute async

execute(command: str, output: OutputWriter, metadata: dict[str, Any] | None = None) -> None

Execute command with appropriate context.

Source code in src/slashed/router.py
async def execute(
    self,
    command: str,
    output: OutputWriter,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Execute command with appropriate context."""
    parsed = self._parse_route_internal(command)
    ctx = self.commands.create_context(
        parsed.context,
        output_writer=output,
        metadata=metadata,
    )
    await self.commands.execute_command(parsed.command, ctx)

execute_global async

execute_global(command: str, output: OutputWriter, metadata: dict[str, Any] | None = None) -> None

Execute command with global context.

Source code in src/slashed/router.py
async def execute_global(
    self,
    command: str,
    output: OutputWriter,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Execute command with global context."""
    parsed = self.parse_global_command(command)
    ctx = self.commands.create_context(
        parsed.context,
        output_writer=output,
        metadata=metadata,
    )
    await self.commands.execute_command(parsed.command, ctx)

execute_routed async

execute_routed(command: str, output: OutputWriter, metadata: dict[str, Any] | None = None) -> None

Execute command with route-specific context.

Source code in src/slashed/router.py
async def execute_routed(
    self,
    command: str,
    output: OutputWriter,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Execute command with route-specific context."""
    parsed = self.parse_routed_command(command)
    ctx = self.commands.create_context(
        parsed.context,
        output_writer=output,
        metadata=metadata,
    )
    await self.commands.execute_command(parsed.command, ctx)

get_completions async

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get completions including route prefixes.

Source code in src/slashed/router.py
async def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get completions including route prefixes."""
    word = context.current_word
    text = context._document.text

    # Complete route prefixes
    if word.startswith("@"):
        prefix = word[1:]
        for route in self._routes.values():
            if route.prefix.startswith(prefix):
                yield CompletionItem(
                    text=f"@{route.prefix}",
                    metadata=route.description,
                    kind="route",
                )
        return

    # Get route-specific completions
    try:
        # If we're after a route prefix, use that context
        parts = text.split()
        if parts and parts[0].startswith("@"):
            route_name = parts[0][1:]
            if route_name in self._routes:
                route = self._routes[route_name]
                # Create completion context with route context
                route_ctx = self.commands.create_context(
                    route.context,
                    output_writer=context.command_context.output,
                )
                route_completion_ctx = CompletionContext(
                    document=context._document,
                    command_context=route_ctx,
                )
                # Use the command completer
                if command := self.commands._commands.get(word):
                    if completer := command.get_completer():
                        async for item in completer.get_completions(route_completion_ctx):
                            yield item
                # Or suggest commands
                else:
                    commands = self.commands.list_commands()
                    for cmd in commands:
                        if (
                            not route.allowed_commands or cmd.name in route.allowed_commands
                        ) and cmd.name.startswith(word):
                            yield CompletionItem(
                                text=cmd.name,
                                metadata=cmd.description,
                                kind="command",
                            )
        else:
            # Global context completions
            ctx = self.commands.create_context(
                self._active_context or self.global_context,
                output_writer=context.command_context.output,
            )
            global_completion_ctx = CompletionContext(
                document=context._document,
                command_context=ctx,
            )
            # First try command completer if we have a word
            if word and (command := self.commands._commands.get(word)):
                if completer := command.get_completer():
                    async for item in completer.get_completions(global_completion_ctx):
                        yield item
            # Otherwise suggest commands
            else:
                for cmd in self.commands.list_commands():
                    # In global context, only show commands not restricted to routes
                    if cmd.name.startswith(word) and not any(
                        route.allowed_commands and cmd.name in route.allowed_commands
                        for route in self._routes.values()
                    ):
                        yield CompletionItem(
                            text=cmd.name,
                            metadata=cmd.description,
                            kind="command",
                        )

    except CommandError:
        # Ignore routing errors during completion
        pass

list_routes

list_routes() -> list[RouteInfo]

List available routes with descriptions.

Returns:

Type Description
list[RouteInfo]

List of route information

Source code in src/slashed/router.py
def list_routes(self) -> list[RouteInfo]:
    """List available routes with descriptions.

    Returns:
        List of route information
    """
    return [
        RouteInfo(
            prefix=route.prefix,
            description=route.description,
            active=route.context == self._active_context,
        )
        for route in self._routes.values()
    ]

parse_global_command

parse_global_command(command: str) -> ParsedRoute[TGlobalContext]

Parse a command using global context.

Parameters:

Name Type Description Default
command str

Command string without routing prefix

required

Returns:

Type Description
ParsedRoute[TGlobalContext]

Parsed route with global context

Raises:

Type Description
CommandError

If command uses routing prefix

Source code in src/slashed/router.py
def parse_global_command(self, command: str) -> ParsedRoute[TGlobalContext]:
    """Parse a command using global context.

    Args:
        command: Command string without routing prefix

    Returns:
        Parsed route with global context

    Raises:
        CommandError: If command uses routing prefix
    """
    if command.startswith("@"):
        msg = "Routing prefix not allowed for global commands"
        raise CommandError(msg)

    # Check if command is restricted to a route
    command_name = command.split(maxsplit=1)[0]
    for route in self._routes.values():
        if route.allowed_commands and command_name in route.allowed_commands:
            # Command is restricted to a route but no route specified
            msg = f"Command '{command_name}' requires a route prefix"
            raise CommandError(msg)

    return ParsedRoute(context=self.global_context, command=command)

parse_routed_command

parse_routed_command(command: str) -> ParsedRoute[TRouteContext]

Parse a command with routing prefix.

Parameters:

Name Type Description Default
command str

Command string with @prefix

required

Returns:

Type Description
ParsedRoute[TRouteContext]

Parsed route with route-specific context

Raises:

Type Description
CommandError

If command doesn't use routing or route is invalid

Source code in src/slashed/router.py
def parse_routed_command(self, command: str) -> ParsedRoute[TRouteContext]:
    """Parse a command with routing prefix.

    Args:
        command: Command string with @prefix

    Returns:
        Parsed route with route-specific context

    Raises:
        CommandError: If command doesn't use routing or route is invalid
    """
    if not command.startswith("@"):
        msg = "Missing route prefix"
        raise CommandError(msg)

    parsed = self._parse_route_internal(command)
    if isinstance(parsed.context, type(self.global_context)):
        msg = "Unexpected global context for routed command"
        raise RuntimeError(msg)  # noqa: TRY004

    # We know it's TRouteContext at this point
    context = parsed.context
    if not isinstance(context, type(self._routes[next(iter(self._routes))].context)):
        msg = "Invalid context type for routed command"
        raise RuntimeError(msg)  # noqa: TRY004

    return ParsedRoute[TRouteContext](
        context=context,
        command=parsed.command,
        route=parsed.route,  # type: ignore  # We know it's the right type
    )

set_active_context

set_active_context(context: TRouteContext | None) -> None

Set default context for unrouted commands.

Parameters:

Name Type Description Default
context TRouteContext | None

Context to set as active, or None to use global

required
Source code in src/slashed/router.py
def set_active_context(self, context: TRouteContext | None) -> None:
    """Set default context for unrouted commands.

    Args:
        context: Context to set as active, or None to use global
    """
    self._default_context = context

show_routes async

show_routes(output: OutputWriter) -> None

Display available routes.

Parameters:

Name Type Description Default
output OutputWriter

Output writer to use

required
Source code in src/slashed/router.py
async def show_routes(self, output: OutputWriter) -> None:
    """Display available routes.

    Args:
        output: Output writer to use
    """
    await output.print("\nAvailable routes:")
    for route in self._routes.values():
        active = " (active)" if route.context == self._active_context else ""
        await output.print(f"@{route.prefix}: {route.description}{active}")

temporary_context

temporary_context(context: TRouteContext) -> Generator[None]

Temporarily switch context.

Parameters:

Name Type Description Default
context TRouteContext

Context to use temporarily

required
Example
with router.temporary_context(db_context):
    await router.execute("list-tables", output)
Source code in src/slashed/router.py
@contextmanager
def temporary_context(self, context: TRouteContext) -> Generator[None]:
    """Temporarily switch context.

    Args:
        context: Context to use temporarily

    Example:
        ```python
        with router.temporary_context(db_context):
            await router.execute("list-tables", output)
        ```
    """
    token = self._temporary_context.set((context,))
    try:
        yield
    finally:
        self._temporary_context.reset(token)

CommandStore

Central store for command management and history.

Source code in src/slashed/store.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class CommandStore:
    """Central store for command management and history."""

    command_executed = Signal(CommandExecutedEvent)
    output = Signal(str)

    def __init__(
        self,
        history_file: JoinablePathLike | None = None,
        *,
        event_handler: CommandStoreEventHandler | None = None,
        commands: Sequence[type[SlashedCommand] | BaseCommand] | None = None,
        enable_system_commands: bool = False,
    ) -> None:
        """Initialize command store.

        Args:
            history_file: Optional path to history file
            event_handler: Optional event handler for command execution events
            commands: Optional list of commands to register
            enable_system_commands: Whether to enable system execution commands.
                                  Disabled by default for security.
        """
        self._commands = EventedDict[str, BaseCommand]()
        self._contexts = ContextRegistry()
        self.event_handler = event_handler
        self._command_history: list[str] = []
        self._history_needs_newline = False
        self._history_path = UPath(history_file) if history_file else None
        self._enable_system_commands = enable_system_commands
        self._initialized = False
        if self._history_path:
            self._history_path.parent.mkdir(parents=True, exist_ok=True)
        for cmd in commands or []:
            self.register_command(cmd)

    @property
    def command_events(self) -> DictEvents:
        return self._commands.events

    def _initialize_sync(self) -> None:
        """Initialize the store synchronously."""
        if self._initialized:
            return

        # Load history
        try:
            if self._history_path and self._history_path.exists():
                text = self._history_path.read_text("utf-8")
                self._command_history = [_decode_history_line(i) for i in text.splitlines()]
                self._history_needs_newline = bool(text) and not text.endswith("\n")
                if len(self._command_history) > 2 * MAX_HISTORY:
                    self._command_history = self._command_history[-MAX_HISTORY:]
                    lines = "".join(json.dumps(i) + "\n" for i in self._command_history)
                    self._history_path.write_text(lines, encoding="utf-8")
                    self._history_needs_newline = False
        except Exception:
            logger.exception("Failed to load command history")
            self._command_history = []

        # Register commands
        self.register_builtin_commands()
        self._initialized = True

    async def initialize(self) -> None:
        """Initialize the store (async wrapper for backward compatibility)."""
        self._initialize_sync()

    def add_to_history(self, command: str) -> None:
        """Add command to history."""
        if not command.strip():
            return

        self._command_history.append(command)
        if self._history_path:
            # One JSON string per line: appending is O(1) and keeps multi-line entries.
            line = json.dumps(command) + "\n"
            if self._history_needs_newline:
                line = "\n" + line
            try:
                with self._history_path.open("a", encoding="utf-8") as f:
                    f.write(line)
            except NotImplementedError, ValueError:  # filesystems without append mode
                lines = "".join(json.dumps(i) + "\n" for i in self._command_history)
                self._history_path.write_text(lines, encoding="utf-8")
            self._history_needs_newline = False

    def get_history(self, limit: int | None = None, newest_first: bool = True) -> list[str]:
        """Get command history."""
        history = self._command_history
        if newest_first:
            history = history[::-1]
        return history[:limit] if limit else history

    def create_context[TContextData](
        self,
        data: TContextData | None,
        output_writer: OutputWriter | Callable[..., Any] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> CommandContext[TContextData]:
        """Create a command execution context.

        Args:
            data: Custom context data
            output_writer: Optional custom output writer
            metadata: Additional metadata

        Returns:
            Command execution context
        """
        if callable(output_writer):
            writer: OutputWriter = CallbackOutputWriter(output_writer)
        else:
            writer = output_writer or DefaultOutputWriter()
        meta = metadata or {}
        return CommandContext(output=writer, data=data, command_store=self, metadata=meta)

    def create_completion_context[TContextData](
        self,
        document: Document,
        command_context: CommandContext[TContextData] | None = None,
    ) -> CompletionContext[TContextData]:
        """Create a completion context."""
        return CompletionContext(document, command_context)

    # Context management methods
    def register_context(
        self,
        data: object,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """Register a typed context.

        Example:
            ```python
            @dataclass
            class DBContext:
                connection: str
                timeout: int = 30

            store = CommandStore()
            store.register_context(DBContext("mysql://..."))
            ```
        """
        self._contexts.register(data, metadata)

    def get_context[T](self, context_type: type[T]) -> T:
        """Get a typed context.

        Example:
            ```python
            db_ctx = store.get_context(DBContext)
            # db_ctx is properly typed as DBContext
            ```
        """
        return self._contexts.get(context_type)

    def unregister_context(self, context_type: type) -> None:
        """Unregister a context type."""
        self._contexts.unregister(context_type)

    def clear(self) -> None:
        """Clear all commands and contexts from the store."""
        self._commands.clear()
        self._contexts = ContextRegistry()
        self._command_history.clear()
        # if self._history_path and self._history_path.exists():
        #     self._history_path.write_text("")
        self._initialized = False

    async def execute_command_auto(
        self,
        command_str: str,
        fallback_context: Any | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> Any:
        """Execute command with automatic context matching.

        Args:
            command_str: Command to execute
            fallback_context: Optional context to use if no match found
            metadata: Additional metadata for context

        Example:
            ```python
            # Will automatically use DBContext for database commands
            # and UIContext for UI commands
            await store.execute_command_auto("query 'select * from users'")
            ```

        Raises:
            CommandError: If no matching context is found and no fallback provided
        """
        parsed = parse_command(command_str)
        command = self.get_command(parsed.name)
        if not command:
            msg = f"Unknown command: {parsed.name}"
            raise CommandError(msg)

        # Try to find matching context
        if reg := self._contexts.match_command(command):
            ctx: CommandContext[Any] = self.create_context(reg.data, metadata=reg.metadata)
        elif fallback_context is not None:
            ctx = self.create_context(fallback_context, metadata=metadata)
        else:
            msg = f"No matching context found for command {command.name}"
            raise CommandError(msg)

        return await self.execute_command(command_str, ctx)

    def register_command(
        self,
        command: type[SlashedCommand] | BaseCommand,
        *,
        replace: bool = False,
    ) -> None:
        """Register a new command.

        Args:
            command: Command class (SlashedCommand subclass) or command instance
            replace: If True, replace existing command with same name.
                    If False, raise ValueError if command exists.

        Raises:
            ValueError: If command with same name exists and replace=False
        """
        # If given a class, instantiate it
        if isinstance(command, type):
            command = command()

        if not command.is_available():
            return
        if command.name in self._commands and not replace:
            msg = f"Command {command.name!r} already registered"
            raise ValueError(msg)
        self._commands[command.name] = command

    def unregister_command(self, name: str) -> None:
        """Remove a command.

        Args:
            name: Name of command to remove
        """
        if name in self._commands:
            del self._commands[name]
            logger.debug("Unregistered command: %s", name)

    def get_command(self, name: str) -> BaseCommand | None:
        """Get command by name.

        Args:
            name: Name of command to get

        Returns:
            Command if found, None otherwise
        """
        return self._commands.get(name)

    def list_commands(
        self,
        category: str | None = None,
        ctx: CommandContext[Any] | None = None,
    ) -> list[BaseCommand]:
        """List all commands, optionally filtered by category and visibility.

        Args:
            category: Optional category to filter by
            ctx: Optional context for visibility filtering

        Returns:
            List of commands
        """
        commands: list[BaseCommand] = list(self._commands.values())
        if category:
            commands = [cmd for cmd in commands if cmd.category == category]
        if ctx is not None:
            commands = [cmd for cmd in commands if cmd.is_visible(ctx)]
        return commands

    def get_categories(self) -> list[str]:
        """Get list of available command categories.

        Returns:
            Sorted list of unique categories
        """
        return sorted({cmd.category for cmd in self._commands.values()})

    def get_commands_by_category(
        self,
        ctx: CommandContext[Any] | None = None,
    ) -> dict[str, list[BaseCommand]]:
        """Get commands grouped by category.

        Args:
            ctx: Optional context for visibility filtering

        Returns:
            Dict mapping categories to lists of commands
        """
        result: dict[str, list[BaseCommand]] = {}
        for cmd in self._commands.values():
            if ctx is not None and not cmd.is_visible(ctx):
                continue
            result.setdefault(cmd.category, []).append(cmd)
        return result

    async def execute_command[TContextData](
        self,
        command_str: str,
        ctx: CommandContext[TContextData],
    ) -> Any:
        """Execute a command from string input.

        Args:
            command_str: Full command string (without leading slash)
            ctx: Command execution context

        Raises:
            CommandError: If command parsing or execution fails
        """
        self.add_to_history(command_str)
        try:
            try:
                words = shlex.split(command_str)
            except ValueError as e:
                msg = f"Invalid command syntax: {e}"
                raise CommandError(msg) from e
            if not words:
                msg = "Empty command"
                raise CommandError(msg)  # noqa: TRY301

            # Get the command
            command = self.get_command(words[0])
            if not command:
                msg = f"Unknown command: {words[0]}"
                raise CommandError(msg)  # noqa: TRY301
            if command.raw_args:
                parsed = ParsedCommand(words[0], ParsedCommandArgs(args=words[1:], kwargs={}))
            else:
                parsed = parse_command(command_str)

            # Check for --help flag, but only handle it if command doesn't use it
            if "help" in parsed.args.kwargs:
                # The user's function, not the generic execute(ctx, args, kwargs) wrapper
                sig = inspect.signature(
                    command.get_callable(), annotation_format=annotationlib.Format.FORWARDREF
                )
                help_param = sig.parameters.get("help")

                # Only show our help if command doesn't handle help parameter
                if not help_param:
                    sections = [
                        f"Command: /{command.name}",
                        f"Category: {command.category}",
                        "",
                        "Description:",
                        command.description,
                        "",
                    ]
                    if command.usage:
                        sections.extend([
                            "Usage:",
                            f"/{command.name} {command.usage}",
                            "",
                        ])
                    if command.help_text:
                        sections.extend(["Help:", command.help_text])
                    await ctx.print("\n".join(sections))
                    return None

            msg = "Executing command: %s (args=%s, kwargs=%s)"
            logger.debug(msg, parsed.name, parsed.args.args, parsed.args.kwargs)
            # Execute it with all args, letting command handle help if it wants to
            result = await command.execute(ctx, parsed.args.args, parsed.args.kwargs)
            event = CommandExecutedEvent(
                command=command_str,
                context=ctx,
                success=True,
                result=result,
            )
            if self.event_handler:
                await self.event_handler(event)
            self.command_executed.emit(event)
        except CommandError as e:
            event = CommandExecutedEvent(
                command=command_str,
                context=ctx,
                success=False,
                error=e,
            )
            if self.event_handler:
                await self.event_handler(event)
            self.command_executed.emit(event)
            raise
        except Exception as e:
            msg = f"Command execution failed: {e}"
            event = CommandExecutedEvent(
                command=command_str,
                context=ctx,
                success=False,
                error=e,
            )
            if self.event_handler:
                await self.event_handler(event)
            self.command_executed.emit(event)
            raise CommandError(msg) from e
        else:
            return result

    async def execute_command_with_context[T](
        self,
        command_str: str,
        context: T | None = None,
        output_writer: OutputWriter | Callable[..., Any] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> Any:
        """Execute a command with a custom context.

        Args:
            command_str: Command string to execute (without leading slash)
            context: Custom context data
            output_writer: Optional custom output writer
            metadata: Additional metadata
        """
        ctx = self.create_context(
            context,
            output_writer=output_writer,
            metadata=metadata,
        )
        return await self.execute_command(command_str, ctx)

    async def execute_shell[TContextData](
        self,
        command_line: str,
        ctx: CommandContext[TContextData],
    ) -> CommandResult:
        """Execute a shell-like command line with pipes and chaining.

        This method supports bash-like syntax:
        - Pipes: cmd1 | cmd2 | cmd3
        - AND chaining: cmd1 && cmd2 (run cmd2 only if cmd1 succeeds)
        - OR chaining: cmd1 || cmd2 (run cmd2 only if cmd1 fails)
        - Sequential: cmd1 ; cmd2 (run both regardless)

        Args:
            command_line: Full command line (may contain |, &&, ||, ;)
            ctx: Command execution context

        Returns:
            CommandResult with stdout, stderr, and exit_code

        Example:
            ```python
            result = await store.execute_shell(
                "cat data.txt | grep error | head -5",
                ctx,
            )
            print(result.stdout)  # First 5 lines containing 'error'
            ```
        """
        from slashed.shell_executor import ShellExecutor

        executor = ShellExecutor(self)
        return await executor.execute(command_line, ctx)

    async def execute_shell_with_context[T](
        self,
        command_line: str,
        context: T | None = None,
        output_writer: OutputWriter | Callable[..., Any] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> CommandResult:
        """Execute a shell-like command line with a custom context.

        Convenience method that creates a context and executes the command line.

        Args:
            command_line: Full command line (may contain |, &&, ||, ;)
            context: Custom context data
            output_writer: Optional custom output writer
            metadata: Additional metadata

        Returns:
            CommandResult with stdout, stderr, and exit_code
        """
        ctx = self.create_context(
            context,
            output_writer=output_writer,
            metadata=metadata,
        )
        return await self.execute_shell(command_line, ctx)

    def register_builtin_commands(self) -> None:
        """Register default system commands."""
        from slashed.builtin import get_builtin_commands

        logger.debug("Registering builtin commands")
        for command in get_builtin_commands():
            self.register_command(command)

        # System commands only if enabled
        if self._enable_system_commands:
            for command in get_system_commands():
                self.register_command(command)

    def add_command(
        self,
        name: str,
        fn: str | ExecuteFunc,
        *,
        description: str | None = None,
        category: str = "general",
        usage: str | None = None,
        help_text: str | None = None,
        completer: str | CompletionProvider | Callable[[], CompletionProvider] | None = None,
        condition: Callable[[], bool] | None = None,
    ) -> None:
        """Add a command with flexible configuration options.

        Args:
            name: Command name
            fn: Import path (str) or callable for command execution
            description: Command description (defaults to fn's docstring)
            category: Command category
            usage: Optional usage string
            help_text: Optional help text
            completer: Import path, completion provider, or factory callable
            condition: Optional function to check if command is available
        """
        # Import fn if string
        if isinstance(fn, str):
            try:
                module_path, attr_name = fn.rsplit(".", 1)
                module = import_module(module_path)
                fn_obj: ExecuteFunc = getattr(module, attr_name)
            except Exception as e:
                msg = f"Failed to import fn function from {fn}: {e}"
                raise ValueError(msg) from e
        else:
            fn_obj = fn
        # Import completer if string
        if isinstance(completer, str):
            try:
                module_path, attr_name = completer.rsplit(".", 1)
                module = import_module(module_path)
                completer_obj = getattr(module, attr_name)
            except Exception as e:
                msg = f"Failed to import completer from {completer}: {e}"
                raise ValueError(msg) from e
        else:
            completer_obj = completer
        # Use docstring as description if not provided
        if description is None and callable(fn_obj):
            description = fn_obj.__doc__ or "No description"

        # Create and register command
        command = Command(
            name=name,
            description=description or "No description",
            execute_func=fn_obj,
            category=category,
            usage=usage,
            help_text=help_text,
            completer=completer_obj,
            condition=condition,
        )
        self.register_command(command)

    def command(
        self,
        *,
        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: Callable[[], bool] | None = None,
    ) -> Callable[[TCommandFunc], TCommandFunc]:
        """Decorator to register a function as a command.

        Args:
            name: 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 function to check if command is available

        Example:
            ```python
            @store.command(category="tools")
            async def hello(ctx: CommandContext, name: str = "World"):
                '''Say hello to someone.'''
                await ctx.print(f"Hello {name}!")
            ```
        """

        def decorator(func: TCommandFunc) -> TCommandFunc:
            cmd_name = name or getattr(func, "__name__", "command").replace("_", "-")
            cmd_description = description or func.__doc__ or "No description"
            self.add_command(
                name=cmd_name,
                fn=func,
                description=cmd_description,
                category=category,
                usage=usage,
                help_text=help_text,
                completer=completer,
                condition=condition,
            )
            return func

        return decorator

__init__

__init__(
    history_file: JoinablePathLike | None = None,
    *,
    event_handler: CommandStoreEventHandler | None = None,
    commands: Sequence[type[SlashedCommand] | BaseCommand] | None = None,
    enable_system_commands: bool = False,
) -> None

Initialize command store.

Parameters:

Name Type Description Default
history_file JoinablePathLike | None

Optional path to history file

None
event_handler CommandStoreEventHandler | None

Optional event handler for command execution events

None
commands Sequence[type[SlashedCommand] | BaseCommand] | None

Optional list of commands to register

None
enable_system_commands bool

Whether to enable system execution commands. Disabled by default for security.

False
Source code in src/slashed/store.py
def __init__(
    self,
    history_file: JoinablePathLike | None = None,
    *,
    event_handler: CommandStoreEventHandler | None = None,
    commands: Sequence[type[SlashedCommand] | BaseCommand] | None = None,
    enable_system_commands: bool = False,
) -> None:
    """Initialize command store.

    Args:
        history_file: Optional path to history file
        event_handler: Optional event handler for command execution events
        commands: Optional list of commands to register
        enable_system_commands: Whether to enable system execution commands.
                              Disabled by default for security.
    """
    self._commands = EventedDict[str, BaseCommand]()
    self._contexts = ContextRegistry()
    self.event_handler = event_handler
    self._command_history: list[str] = []
    self._history_needs_newline = False
    self._history_path = UPath(history_file) if history_file else None
    self._enable_system_commands = enable_system_commands
    self._initialized = False
    if self._history_path:
        self._history_path.parent.mkdir(parents=True, exist_ok=True)
    for cmd in commands or []:
        self.register_command(cmd)

add_command

add_command(
    name: str,
    fn: str | ExecuteFunc,
    *,
    description: str | None = None,
    category: str = "general",
    usage: str | None = None,
    help_text: str | None = None,
    completer: str | CompletionProvider | Callable[[], CompletionProvider] | None = None,
    condition: Callable[[], bool] | None = None,
) -> None

Add a command with flexible configuration options.

Parameters:

Name Type Description Default
name str

Command name

required
fn str | ExecuteFunc

Import path (str) or callable for command execution

required
description str | None

Command description (defaults to fn's docstring)

None
category str

Command category

'general'
usage str | None

Optional usage string

None
help_text str | None

Optional help text

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

Import path, completion provider, or factory callable

None
condition Callable[[], bool] | None

Optional function to check if command is available

None
Source code in src/slashed/store.py
def add_command(
    self,
    name: str,
    fn: str | ExecuteFunc,
    *,
    description: str | None = None,
    category: str = "general",
    usage: str | None = None,
    help_text: str | None = None,
    completer: str | CompletionProvider | Callable[[], CompletionProvider] | None = None,
    condition: Callable[[], bool] | None = None,
) -> None:
    """Add a command with flexible configuration options.

    Args:
        name: Command name
        fn: Import path (str) or callable for command execution
        description: Command description (defaults to fn's docstring)
        category: Command category
        usage: Optional usage string
        help_text: Optional help text
        completer: Import path, completion provider, or factory callable
        condition: Optional function to check if command is available
    """
    # Import fn if string
    if isinstance(fn, str):
        try:
            module_path, attr_name = fn.rsplit(".", 1)
            module = import_module(module_path)
            fn_obj: ExecuteFunc = getattr(module, attr_name)
        except Exception as e:
            msg = f"Failed to import fn function from {fn}: {e}"
            raise ValueError(msg) from e
    else:
        fn_obj = fn
    # Import completer if string
    if isinstance(completer, str):
        try:
            module_path, attr_name = completer.rsplit(".", 1)
            module = import_module(module_path)
            completer_obj = getattr(module, attr_name)
        except Exception as e:
            msg = f"Failed to import completer from {completer}: {e}"
            raise ValueError(msg) from e
    else:
        completer_obj = completer
    # Use docstring as description if not provided
    if description is None and callable(fn_obj):
        description = fn_obj.__doc__ or "No description"

    # Create and register command
    command = Command(
        name=name,
        description=description or "No description",
        execute_func=fn_obj,
        category=category,
        usage=usage,
        help_text=help_text,
        completer=completer_obj,
        condition=condition,
    )
    self.register_command(command)

add_to_history

add_to_history(command: str) -> None

Add command to history.

Source code in src/slashed/store.py
def add_to_history(self, command: str) -> None:
    """Add command to history."""
    if not command.strip():
        return

    self._command_history.append(command)
    if self._history_path:
        # One JSON string per line: appending is O(1) and keeps multi-line entries.
        line = json.dumps(command) + "\n"
        if self._history_needs_newline:
            line = "\n" + line
        try:
            with self._history_path.open("a", encoding="utf-8") as f:
                f.write(line)
        except NotImplementedError, ValueError:  # filesystems without append mode
            lines = "".join(json.dumps(i) + "\n" for i in self._command_history)
            self._history_path.write_text(lines, encoding="utf-8")
        self._history_needs_newline = False

clear

clear() -> None

Clear all commands and contexts from the store.

Source code in src/slashed/store.py
def clear(self) -> None:
    """Clear all commands and contexts from the store."""
    self._commands.clear()
    self._contexts = ContextRegistry()
    self._command_history.clear()
    # if self._history_path and self._history_path.exists():
    #     self._history_path.write_text("")
    self._initialized = False

command

command(
    *,
    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: Callable[[], bool] | None = None,
) -> Callable[[TCommandFunc], TCommandFunc]

Decorator to register a function as a command.

Parameters:

Name Type Description Default
name str | None

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 Callable[[], bool] | None

Optional function to check if command is available

None
Example
@store.command(category="tools")
async def hello(ctx: CommandContext, name: str = "World"):
    '''Say hello to someone.'''
    await ctx.print(f"Hello {name}!")
Source code in src/slashed/store.py
def command(
    self,
    *,
    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: Callable[[], bool] | None = None,
) -> Callable[[TCommandFunc], TCommandFunc]:
    """Decorator to register a function as a command.

    Args:
        name: 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 function to check if command is available

    Example:
        ```python
        @store.command(category="tools")
        async def hello(ctx: CommandContext, name: str = "World"):
            '''Say hello to someone.'''
            await ctx.print(f"Hello {name}!")
        ```
    """

    def decorator(func: TCommandFunc) -> TCommandFunc:
        cmd_name = name or getattr(func, "__name__", "command").replace("_", "-")
        cmd_description = description or func.__doc__ or "No description"
        self.add_command(
            name=cmd_name,
            fn=func,
            description=cmd_description,
            category=category,
            usage=usage,
            help_text=help_text,
            completer=completer,
            condition=condition,
        )
        return func

    return decorator

create_completion_context

create_completion_context(
    document: Document, command_context: CommandContext[TContextData] | None = None
) -> CompletionContext[TContextData]

Create a completion context.

Source code in src/slashed/store.py
def create_completion_context[TContextData](
    self,
    document: Document,
    command_context: CommandContext[TContextData] | None = None,
) -> CompletionContext[TContextData]:
    """Create a completion context."""
    return CompletionContext(document, command_context)

create_context

create_context(
    data: TContextData | None,
    output_writer: OutputWriter | Callable[..., Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> CommandContext[TContextData]

Create a command execution context.

Parameters:

Name Type Description Default
data TContextData | None

Custom context data

required
output_writer OutputWriter | Callable[..., Any] | None

Optional custom output writer

None
metadata dict[str, Any] | None

Additional metadata

None

Returns:

Type Description
CommandContext[TContextData]

Command execution context

Source code in src/slashed/store.py
def create_context[TContextData](
    self,
    data: TContextData | None,
    output_writer: OutputWriter | Callable[..., Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> CommandContext[TContextData]:
    """Create a command execution context.

    Args:
        data: Custom context data
        output_writer: Optional custom output writer
        metadata: Additional metadata

    Returns:
        Command execution context
    """
    if callable(output_writer):
        writer: OutputWriter = CallbackOutputWriter(output_writer)
    else:
        writer = output_writer or DefaultOutputWriter()
    meta = metadata or {}
    return CommandContext(output=writer, data=data, command_store=self, metadata=meta)

execute_command async

execute_command(command_str: str, ctx: CommandContext[TContextData]) -> Any

Execute a command from string input.

Parameters:

Name Type Description Default
command_str str

Full command string (without leading slash)

required
ctx CommandContext[TContextData]

Command execution context

required

Raises:

Type Description
CommandError

If command parsing or execution fails

Source code in src/slashed/store.py
async def execute_command[TContextData](
    self,
    command_str: str,
    ctx: CommandContext[TContextData],
) -> Any:
    """Execute a command from string input.

    Args:
        command_str: Full command string (without leading slash)
        ctx: Command execution context

    Raises:
        CommandError: If command parsing or execution fails
    """
    self.add_to_history(command_str)
    try:
        try:
            words = shlex.split(command_str)
        except ValueError as e:
            msg = f"Invalid command syntax: {e}"
            raise CommandError(msg) from e
        if not words:
            msg = "Empty command"
            raise CommandError(msg)  # noqa: TRY301

        # Get the command
        command = self.get_command(words[0])
        if not command:
            msg = f"Unknown command: {words[0]}"
            raise CommandError(msg)  # noqa: TRY301
        if command.raw_args:
            parsed = ParsedCommand(words[0], ParsedCommandArgs(args=words[1:], kwargs={}))
        else:
            parsed = parse_command(command_str)

        # Check for --help flag, but only handle it if command doesn't use it
        if "help" in parsed.args.kwargs:
            # The user's function, not the generic execute(ctx, args, kwargs) wrapper
            sig = inspect.signature(
                command.get_callable(), annotation_format=annotationlib.Format.FORWARDREF
            )
            help_param = sig.parameters.get("help")

            # Only show our help if command doesn't handle help parameter
            if not help_param:
                sections = [
                    f"Command: /{command.name}",
                    f"Category: {command.category}",
                    "",
                    "Description:",
                    command.description,
                    "",
                ]
                if command.usage:
                    sections.extend([
                        "Usage:",
                        f"/{command.name} {command.usage}",
                        "",
                    ])
                if command.help_text:
                    sections.extend(["Help:", command.help_text])
                await ctx.print("\n".join(sections))
                return None

        msg = "Executing command: %s (args=%s, kwargs=%s)"
        logger.debug(msg, parsed.name, parsed.args.args, parsed.args.kwargs)
        # Execute it with all args, letting command handle help if it wants to
        result = await command.execute(ctx, parsed.args.args, parsed.args.kwargs)
        event = CommandExecutedEvent(
            command=command_str,
            context=ctx,
            success=True,
            result=result,
        )
        if self.event_handler:
            await self.event_handler(event)
        self.command_executed.emit(event)
    except CommandError as e:
        event = CommandExecutedEvent(
            command=command_str,
            context=ctx,
            success=False,
            error=e,
        )
        if self.event_handler:
            await self.event_handler(event)
        self.command_executed.emit(event)
        raise
    except Exception as e:
        msg = f"Command execution failed: {e}"
        event = CommandExecutedEvent(
            command=command_str,
            context=ctx,
            success=False,
            error=e,
        )
        if self.event_handler:
            await self.event_handler(event)
        self.command_executed.emit(event)
        raise CommandError(msg) from e
    else:
        return result

execute_command_auto async

execute_command_auto(
    command_str: str, fallback_context: Any | None = None, metadata: dict[str, Any] | None = None
) -> Any

Execute command with automatic context matching.

Parameters:

Name Type Description Default
command_str str

Command to execute

required
fallback_context Any | None

Optional context to use if no match found

None
metadata dict[str, Any] | None

Additional metadata for context

None
Example
# Will automatically use DBContext for database commands
# and UIContext for UI commands
await store.execute_command_auto("query 'select * from users'")

Raises:

Type Description
CommandError

If no matching context is found and no fallback provided

Source code in src/slashed/store.py
async def execute_command_auto(
    self,
    command_str: str,
    fallback_context: Any | None = None,
    metadata: dict[str, Any] | None = None,
) -> Any:
    """Execute command with automatic context matching.

    Args:
        command_str: Command to execute
        fallback_context: Optional context to use if no match found
        metadata: Additional metadata for context

    Example:
        ```python
        # Will automatically use DBContext for database commands
        # and UIContext for UI commands
        await store.execute_command_auto("query 'select * from users'")
        ```

    Raises:
        CommandError: If no matching context is found and no fallback provided
    """
    parsed = parse_command(command_str)
    command = self.get_command(parsed.name)
    if not command:
        msg = f"Unknown command: {parsed.name}"
        raise CommandError(msg)

    # Try to find matching context
    if reg := self._contexts.match_command(command):
        ctx: CommandContext[Any] = self.create_context(reg.data, metadata=reg.metadata)
    elif fallback_context is not None:
        ctx = self.create_context(fallback_context, metadata=metadata)
    else:
        msg = f"No matching context found for command {command.name}"
        raise CommandError(msg)

    return await self.execute_command(command_str, ctx)

execute_command_with_context async

execute_command_with_context(
    command_str: str,
    context: T | None = None,
    output_writer: OutputWriter | Callable[..., Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> Any

Execute a command with a custom context.

Parameters:

Name Type Description Default
command_str str

Command string to execute (without leading slash)

required
context T | None

Custom context data

None
output_writer OutputWriter | Callable[..., Any] | None

Optional custom output writer

None
metadata dict[str, Any] | None

Additional metadata

None
Source code in src/slashed/store.py
async def execute_command_with_context[T](
    self,
    command_str: str,
    context: T | None = None,
    output_writer: OutputWriter | Callable[..., Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> Any:
    """Execute a command with a custom context.

    Args:
        command_str: Command string to execute (without leading slash)
        context: Custom context data
        output_writer: Optional custom output writer
        metadata: Additional metadata
    """
    ctx = self.create_context(
        context,
        output_writer=output_writer,
        metadata=metadata,
    )
    return await self.execute_command(command_str, ctx)

execute_shell async

execute_shell(command_line: str, ctx: CommandContext[TContextData]) -> CommandResult

Execute a shell-like command line with pipes and chaining.

This method supports bash-like syntax: - Pipes: cmd1 | cmd2 | cmd3 - AND chaining: cmd1 && cmd2 (run cmd2 only if cmd1 succeeds) - OR chaining: cmd1 || cmd2 (run cmd2 only if cmd1 fails) - Sequential: cmd1 ; cmd2 (run both regardless)

Parameters:

Name Type Description Default
command_line str

Full command line (may contain |, &&, ||, ;)

required
ctx CommandContext[TContextData]

Command execution context

required

Returns:

Type Description
CommandResult

CommandResult with stdout, stderr, and exit_code

Example
result = await store.execute_shell(
    "cat data.txt | grep error | head -5",
    ctx,
)
print(result.stdout)  # First 5 lines containing 'error'
Source code in src/slashed/store.py
async def execute_shell[TContextData](
    self,
    command_line: str,
    ctx: CommandContext[TContextData],
) -> CommandResult:
    """Execute a shell-like command line with pipes and chaining.

    This method supports bash-like syntax:
    - Pipes: cmd1 | cmd2 | cmd3
    - AND chaining: cmd1 && cmd2 (run cmd2 only if cmd1 succeeds)
    - OR chaining: cmd1 || cmd2 (run cmd2 only if cmd1 fails)
    - Sequential: cmd1 ; cmd2 (run both regardless)

    Args:
        command_line: Full command line (may contain |, &&, ||, ;)
        ctx: Command execution context

    Returns:
        CommandResult with stdout, stderr, and exit_code

    Example:
        ```python
        result = await store.execute_shell(
            "cat data.txt | grep error | head -5",
            ctx,
        )
        print(result.stdout)  # First 5 lines containing 'error'
        ```
    """
    from slashed.shell_executor import ShellExecutor

    executor = ShellExecutor(self)
    return await executor.execute(command_line, ctx)

execute_shell_with_context async

execute_shell_with_context(
    command_line: str,
    context: T | None = None,
    output_writer: OutputWriter | Callable[..., Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> CommandResult

Execute a shell-like command line with a custom context.

Convenience method that creates a context and executes the command line.

Parameters:

Name Type Description Default
command_line str

Full command line (may contain |, &&, ||, ;)

required
context T | None

Custom context data

None
output_writer OutputWriter | Callable[..., Any] | None

Optional custom output writer

None
metadata dict[str, Any] | None

Additional metadata

None

Returns:

Type Description
CommandResult

CommandResult with stdout, stderr, and exit_code

Source code in src/slashed/store.py
async def execute_shell_with_context[T](
    self,
    command_line: str,
    context: T | None = None,
    output_writer: OutputWriter | Callable[..., Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> CommandResult:
    """Execute a shell-like command line with a custom context.

    Convenience method that creates a context and executes the command line.

    Args:
        command_line: Full command line (may contain |, &&, ||, ;)
        context: Custom context data
        output_writer: Optional custom output writer
        metadata: Additional metadata

    Returns:
        CommandResult with stdout, stderr, and exit_code
    """
    ctx = self.create_context(
        context,
        output_writer=output_writer,
        metadata=metadata,
    )
    return await self.execute_shell(command_line, ctx)

get_categories

get_categories() -> list[str]

Get list of available command categories.

Returns:

Type Description
list[str]

Sorted list of unique categories

Source code in src/slashed/store.py
def get_categories(self) -> list[str]:
    """Get list of available command categories.

    Returns:
        Sorted list of unique categories
    """
    return sorted({cmd.category for cmd in self._commands.values()})

get_command

get_command(name: str) -> BaseCommand | None

Get command by name.

Parameters:

Name Type Description Default
name str

Name of command to get

required

Returns:

Type Description
BaseCommand | None

Command if found, None otherwise

Source code in src/slashed/store.py
def get_command(self, name: str) -> BaseCommand | None:
    """Get command by name.

    Args:
        name: Name of command to get

    Returns:
        Command if found, None otherwise
    """
    return self._commands.get(name)

get_commands_by_category

get_commands_by_category(ctx: CommandContext[Any] | None = None) -> dict[str, list[BaseCommand]]

Get commands grouped by category.

Parameters:

Name Type Description Default
ctx CommandContext[Any] | None

Optional context for visibility filtering

None

Returns:

Type Description
dict[str, list[BaseCommand]]

Dict mapping categories to lists of commands

Source code in src/slashed/store.py
def get_commands_by_category(
    self,
    ctx: CommandContext[Any] | None = None,
) -> dict[str, list[BaseCommand]]:
    """Get commands grouped by category.

    Args:
        ctx: Optional context for visibility filtering

    Returns:
        Dict mapping categories to lists of commands
    """
    result: dict[str, list[BaseCommand]] = {}
    for cmd in self._commands.values():
        if ctx is not None and not cmd.is_visible(ctx):
            continue
        result.setdefault(cmd.category, []).append(cmd)
    return result

get_context

get_context(context_type: type[T]) -> T

Get a typed context.

Example
db_ctx = store.get_context(DBContext)
# db_ctx is properly typed as DBContext
Source code in src/slashed/store.py
def get_context[T](self, context_type: type[T]) -> T:
    """Get a typed context.

    Example:
        ```python
        db_ctx = store.get_context(DBContext)
        # db_ctx is properly typed as DBContext
        ```
    """
    return self._contexts.get(context_type)

get_history

get_history(limit: int | None = None, newest_first: bool = True) -> list[str]

Get command history.

Source code in src/slashed/store.py
def get_history(self, limit: int | None = None, newest_first: bool = True) -> list[str]:
    """Get command history."""
    history = self._command_history
    if newest_first:
        history = history[::-1]
    return history[:limit] if limit else history

initialize async

initialize() -> None

Initialize the store (async wrapper for backward compatibility).

Source code in src/slashed/store.py
async def initialize(self) -> None:
    """Initialize the store (async wrapper for backward compatibility)."""
    self._initialize_sync()

list_commands

list_commands(
    category: str | None = None, ctx: CommandContext[Any] | None = None
) -> list[BaseCommand]

List all commands, optionally filtered by category and visibility.

Parameters:

Name Type Description Default
category str | None

Optional category to filter by

None
ctx CommandContext[Any] | None

Optional context for visibility filtering

None

Returns:

Type Description
list[BaseCommand]

List of commands

Source code in src/slashed/store.py
def list_commands(
    self,
    category: str | None = None,
    ctx: CommandContext[Any] | None = None,
) -> list[BaseCommand]:
    """List all commands, optionally filtered by category and visibility.

    Args:
        category: Optional category to filter by
        ctx: Optional context for visibility filtering

    Returns:
        List of commands
    """
    commands: list[BaseCommand] = list(self._commands.values())
    if category:
        commands = [cmd for cmd in commands if cmd.category == category]
    if ctx is not None:
        commands = [cmd for cmd in commands if cmd.is_visible(ctx)]
    return commands

register_builtin_commands

register_builtin_commands() -> None

Register default system commands.

Source code in src/slashed/store.py
def register_builtin_commands(self) -> None:
    """Register default system commands."""
    from slashed.builtin import get_builtin_commands

    logger.debug("Registering builtin commands")
    for command in get_builtin_commands():
        self.register_command(command)

    # System commands only if enabled
    if self._enable_system_commands:
        for command in get_system_commands():
            self.register_command(command)

register_command

register_command(command: type[SlashedCommand] | BaseCommand, *, replace: bool = False) -> None

Register a new command.

Parameters:

Name Type Description Default
command type[SlashedCommand] | BaseCommand

Command class (SlashedCommand subclass) or command instance

required
replace bool

If True, replace existing command with same name. If False, raise ValueError if command exists.

False

Raises:

Type Description
ValueError

If command with same name exists and replace=False

Source code in src/slashed/store.py
def register_command(
    self,
    command: type[SlashedCommand] | BaseCommand,
    *,
    replace: bool = False,
) -> None:
    """Register a new command.

    Args:
        command: Command class (SlashedCommand subclass) or command instance
        replace: If True, replace existing command with same name.
                If False, raise ValueError if command exists.

    Raises:
        ValueError: If command with same name exists and replace=False
    """
    # If given a class, instantiate it
    if isinstance(command, type):
        command = command()

    if not command.is_available():
        return
    if command.name in self._commands and not replace:
        msg = f"Command {command.name!r} already registered"
        raise ValueError(msg)
    self._commands[command.name] = command

register_context

register_context(data: object, metadata: dict[str, Any] | None = None) -> None

Register a typed context.

Example
@dataclass
class DBContext:
    connection: str
    timeout: int = 30

store = CommandStore()
store.register_context(DBContext("mysql://..."))
Source code in src/slashed/store.py
def register_context(
    self,
    data: object,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Register a typed context.

    Example:
        ```python
        @dataclass
        class DBContext:
            connection: str
            timeout: int = 30

        store = CommandStore()
        store.register_context(DBContext("mysql://..."))
        ```
    """
    self._contexts.register(data, metadata)

unregister_command

unregister_command(name: str) -> None

Remove a command.

Parameters:

Name Type Description Default
name str

Name of command to remove

required
Source code in src/slashed/store.py
def unregister_command(self, name: str) -> None:
    """Remove a command.

    Args:
        name: Name of command to remove
    """
    if name in self._commands:
        del self._commands[name]
        logger.debug("Unregistered command: %s", name)

unregister_context

unregister_context(context_type: type) -> None

Unregister a context type.

Source code in src/slashed/store.py
def unregister_context(self, context_type: type) -> None:
    """Unregister a context type."""
    self._contexts.unregister(context_type)

CommandUnregisteredEvent dataclass

Event emitted when a command is unregistered.

Source code in src/slashed/events.py
@dataclass
class CommandUnregisteredEvent:
    """Event emitted when a command is unregistered."""

    name: str

CompletionContext

Context for completion operations.

Class Type Parameters:

Name Bound or Constraints Description Default
TCommandData

Type of the data in the associated CommandContext. Used when completions need to access the command context data.

required
Source code in src/slashed/completion.py
class CompletionContext[TCommandData]:
    """Context for completion operations.

    Type Parameters:
        TCommandData: Type of the data in the associated CommandContext. Used when
                     completions need to access the command context data.
    """

    def __init__(
        self,
        document: Document,
        command_context: CommandContext[TCommandData] | None = None,
    ) -> None:
        """Initialize completion context.

        Args:
            document: Current document being completed
            command_context: Optional command execution context
        """
        self._document = document
        self._command_context = command_context
        self._command_name: str | None = None
        self._args: list[str] = []
        self._current_word: str = ""
        self._arg_position: int = 0
        self._parse_document()

    @property
    def command_context(self) -> CommandContext[TCommandData]:
        """Get command execution context.

        Returns:
            Command context

        Raises:
            RuntimeError: If command context is not set
        """
        if self._command_context is None:
            msg = "No command context available"
            raise RuntimeError(msg)
        return self._command_context

    def has_command_context(self) -> bool:
        """Check if command context is available."""
        return self._command_context is not None

    def _parse_document(self) -> None:
        """Parse document into command and arguments."""
        text = self._document.text.lstrip()

        if not text.startswith("/"):
            self._command_name = None
            self._args = []
            self._current_word = self._document.get_word_before_cursor()
            self._arg_position = 0
            return

        parts = text[1:].split()
        self._command_name = parts[0] if parts else None
        self._args = parts[1:]
        self._current_word = self._document.get_word_before_cursor()
        self._arg_position = len(text[: self._document.cursor_position].split()) - 1
        logger.info(
            "Parsed command %s with args %s. Current word: %s (position %d)",
            self._command_name,
            self._args,
            self._current_word,
            self._arg_position,
        )

    @property
    def command_name(self) -> str | None:
        """Get current command name if any."""
        return self._command_name

    @property
    def current_word(self) -> str:
        """Get word being completed."""
        return self._current_word

    @property
    def arg_position(self) -> int:
        """Get current argument position."""
        return self._arg_position

    @property
    def command_args(self) -> list[str]:
        """Get current command arguments."""
        return self._args

arg_position property

arg_position: int

Get current argument position.

command_args property

command_args: list[str]

Get current command arguments.

command_context property

command_context: CommandContext[TCommandData]

Get command execution context.

Returns:

Type Description
CommandContext[TCommandData]

Command context

Raises:

Type Description
RuntimeError

If command context is not set

command_name property

command_name: str | None

Get current command name if any.

current_word property

current_word: str

Get word being completed.

__init__

__init__(document: Document, command_context: CommandContext[TCommandData] | None = None) -> None

Initialize completion context.

Parameters:

Name Type Description Default
document Document

Current document being completed

required
command_context CommandContext[TCommandData] | None

Optional command execution context

None
Source code in src/slashed/completion.py
def __init__(
    self,
    document: Document,
    command_context: CommandContext[TCommandData] | None = None,
) -> None:
    """Initialize completion context.

    Args:
        document: Current document being completed
        command_context: Optional command execution context
    """
    self._document = document
    self._command_context = command_context
    self._command_name: str | None = None
    self._args: list[str] = []
    self._current_word: str = ""
    self._arg_position: int = 0
    self._parse_document()

has_command_context

has_command_context() -> bool

Check if command context is available.

Source code in src/slashed/completion.py
def has_command_context(self) -> bool:
    """Check if command context is available."""
    return self._command_context is not None

CompletionItem dataclass

Single completion suggestion.

Source code in src/slashed/completion.py
@dataclass
class CompletionItem:
    """Single completion suggestion."""

    text: str
    """Text to insert"""

    display: str | None = None
    """Optional display text (defaults to text)"""

    metadata: str | None = None
    """Additional information to show"""

    kind: CompletionKind | None = None
    """Type of completion item"""

    sort_text: str | None = None
    """Optional text to use for sorting (defaults to text)"""

display class-attribute instance-attribute

display: str | None = None

Optional display text (defaults to text)

kind class-attribute instance-attribute

kind: CompletionKind | None = None

Type of completion item

metadata class-attribute instance-attribute

metadata: str | None = None

Additional information to show

sort_text class-attribute instance-attribute

sort_text: str | None = None

Optional text to use for sorting (defaults to text)

text instance-attribute

text: str

Text to insert

CompletionProvider

Bases: ABC

Base class for completion providers.

Source code in src/slashed/completion.py
class CompletionProvider(ABC):
    """Base class for completion providers."""

    @abstractmethod
    def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get completion suggestions."""

get_completions abstractmethod

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get completion suggestions.

Source code in src/slashed/completion.py
@abstractmethod
def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get completion suggestions."""

DefaultOutputWriter

Bases: OutputWriter

Default output implementation using rich if available.

Source code in src/slashed/output.py
class DefaultOutputWriter(OutputWriter):
    """Default output implementation using rich if available."""

    def __init__(self, **console_kwargs: Any) -> None:
        """Initialize output writer.

        Args:
            **console_kwargs: Optional kwargs passed to rich.Console constructor
        """
        try:
            from rich.console import Console

            self._console: Console | None = Console(**console_kwargs)
        except ImportError:
            self._console = None

    async def print(self, message: str) -> None:
        """Write message to output.

        Uses rich.Console if available, else regular print().
        """
        if self._console is not None:
            self._console.print(message)
        else:
            print(message, file=sys.stdout)

__init__

__init__(**console_kwargs: Any) -> None

Initialize output writer.

Parameters:

Name Type Description Default
**console_kwargs Any

Optional kwargs passed to rich.Console constructor

{}
Source code in src/slashed/output.py
def __init__(self, **console_kwargs: Any) -> None:
    """Initialize output writer.

    Args:
        **console_kwargs: Optional kwargs passed to rich.Console constructor
    """
    try:
        from rich.console import Console

        self._console: Console | None = Console(**console_kwargs)
    except ImportError:
        self._console = None

print async

print(message: str) -> None

Write message to output.

Uses rich.Console if available, else regular print().

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

    Uses rich.Console if available, else regular print().
    """
    if self._console is not None:
        self._console.print(message)
    else:
        print(message, file=sys.stdout)

EnvVarCompleter

Bases: CompletionProvider

Environment variable completion.

Source code in src/slashed/completers.py
class EnvVarCompleter(CompletionProvider):
    """Environment variable completion."""

    def __init__(
        self,
        prefixes: Sequence[str] | None = None,
        include_values: bool = True,
    ) -> None:
        """Initialize environment variable completer.

        Args:
            prefixes: Optional prefixes to filter variables
            include_values: Whether to show current values
        """
        self.prefixes = prefixes
        self.include_values = include_values

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get environment variable completions."""
        word = context.current_word.lstrip("$")

        for key, value in os.environ.items():
            if self.prefixes and not any(key.startswith(p) for p in self.prefixes):
                continue

            if key.startswith(word):
                meta = value[:50] + "..." if self.include_values else None
                yield CompletionItem(text=f"${key}", metadata=meta, kind="env")

__init__

__init__(prefixes: Sequence[str] | None = None, include_values: bool = True) -> None

Initialize environment variable completer.

Parameters:

Name Type Description Default
prefixes Sequence[str] | None

Optional prefixes to filter variables

None
include_values bool

Whether to show current values

True
Source code in src/slashed/completers.py
def __init__(
    self,
    prefixes: Sequence[str] | None = None,
    include_values: bool = True,
) -> None:
    """Initialize environment variable completer.

    Args:
        prefixes: Optional prefixes to filter variables
        include_values: Whether to show current values
    """
    self.prefixes = prefixes
    self.include_values = include_values

get_completions async

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get environment variable completions.

Source code in src/slashed/completers.py
async def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get environment variable completions."""
    word = context.current_word.lstrip("$")

    for key, value in os.environ.items():
        if self.prefixes and not any(key.startswith(p) for p in self.prefixes):
            continue

        if key.startswith(word):
            meta = value[:50] + "..." if self.include_values else None
            yield CompletionItem(text=f"${key}", metadata=meta, kind="env")

ExitCommandError

Bases: CommandError

Special exception to signal clean Session exit.

Source code in src/slashed/exceptions.py
class ExitCommandError(CommandError):
    """Special exception to signal clean Session exit."""

KeywordCompleter

Bases: CompletionProvider

Completes keyword arguments.

Source code in src/slashed/completers.py
class KeywordCompleter(CompletionProvider):
    """Completes keyword arguments."""

    def __init__(
        self,
        keywords: dict[str, Any],
        value_provider: CompletionProvider | None = None,
    ) -> None:
        """Initialize keyword completer.

        Args:
            keywords: Mapping of keyword names to descriptions/types
            value_provider: Optional provider for keyword values
        """
        self.keywords = keywords
        self.value_provider = value_provider

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get keyword completions."""
        word = context.current_word

        # Complete keyword names
        if word.startswith("--"):
            prefix = word[2:]
            for name, desc in self.keywords.items():
                if name.startswith(prefix):
                    yield CompletionItem(f"--{name}", metadata=str(desc), kind="keyword")
            return

        # Complete keyword values if provider exists
        if self.value_provider and context.arg_position > 0:
            prev_arg = context.command_args[context.arg_position - 1]
            if prev_arg.startswith("--"):
                async for item in self.value_provider.get_completions(context):
                    yield item

__init__

__init__(keywords: dict[str, Any], value_provider: CompletionProvider | None = None) -> None

Initialize keyword completer.

Parameters:

Name Type Description Default
keywords dict[str, Any]

Mapping of keyword names to descriptions/types

required
value_provider CompletionProvider | None

Optional provider for keyword values

None
Source code in src/slashed/completers.py
def __init__(
    self,
    keywords: dict[str, Any],
    value_provider: CompletionProvider | None = None,
) -> None:
    """Initialize keyword completer.

    Args:
        keywords: Mapping of keyword names to descriptions/types
        value_provider: Optional provider for keyword values
    """
    self.keywords = keywords
    self.value_provider = value_provider

get_completions async

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get keyword completions.

Source code in src/slashed/completers.py
async def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get keyword completions."""
    word = context.current_word

    # Complete keyword names
    if word.startswith("--"):
        prefix = word[2:]
        for name, desc in self.keywords.items():
            if name.startswith(prefix):
                yield CompletionItem(f"--{name}", metadata=str(desc), kind="keyword")
        return

    # Complete keyword values if provider exists
    if self.value_provider and context.arg_position > 0:
        prev_arg = context.command_args[context.arg_position - 1]
        if prev_arg.startswith("--"):
            async for item in self.value_provider.get_completions(context):
                yield item

MultiValueCompleter

Bases: CompletionProvider

Completes multiple values separated by a delimiter.

Source code in src/slashed/completers.py
class MultiValueCompleter(CompletionProvider):
    """Completes multiple values separated by a delimiter."""

    def __init__(
        self,
        provider: CompletionProvider,
        delimiter: str = ",",
        strip: bool = True,
    ) -> None:
        """Initialize multi-value completer.

        Args:
            provider: Base provider for individual values
            delimiter: Value separator
            strip: Whether to strip whitespace from values
        """
        self.provider = provider
        self.delimiter = delimiter
        self.strip = strip

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get completions for current value."""
        # Use full text instead of just current_word for splitting
        full_text = context._document.text
        values = full_text.split(self.delimiter)

        # Current value is what's being typed
        current = context.current_word
        if self.strip:
            current = current.strip()

        # Create modified context with just the current value
        mod_context = copy(context)
        mod_context._current_word = current

        # Build prefix from previous values if we have more than one value
        prefix = ""
        if len(values) > 1:
            prefix = self.delimiter.join(values[:-1])
            prefix = f"{prefix}{self.delimiter}"
            if self.strip:
                prefix = f"{prefix} "

        # Get completions and add prefix
        async for item in self.provider.get_completions(mod_context):
            item = copy(item)  # Don't modify original item
            if prefix:
                item.text = f"{prefix}{item.text}"
            yield item

__init__

__init__(provider: CompletionProvider, delimiter: str = ',', strip: bool = True) -> None

Initialize multi-value completer.

Parameters:

Name Type Description Default
provider CompletionProvider

Base provider for individual values

required
delimiter str

Value separator

','
strip bool

Whether to strip whitespace from values

True
Source code in src/slashed/completers.py
def __init__(
    self,
    provider: CompletionProvider,
    delimiter: str = ",",
    strip: bool = True,
) -> None:
    """Initialize multi-value completer.

    Args:
        provider: Base provider for individual values
        delimiter: Value separator
        strip: Whether to strip whitespace from values
    """
    self.provider = provider
    self.delimiter = delimiter
    self.strip = strip

get_completions async

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get completions for current value.

Source code in src/slashed/completers.py
async def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get completions for current value."""
    # Use full text instead of just current_word for splitting
    full_text = context._document.text
    values = full_text.split(self.delimiter)

    # Current value is what's being typed
    current = context.current_word
    if self.strip:
        current = current.strip()

    # Create modified context with just the current value
    mod_context = copy(context)
    mod_context._current_word = current

    # Build prefix from previous values if we have more than one value
    prefix = ""
    if len(values) > 1:
        prefix = self.delimiter.join(values[:-1])
        prefix = f"{prefix}{self.delimiter}"
        if self.strip:
            prefix = f"{prefix} "

    # Get completions and add prefix
    async for item in self.provider.get_completions(mod_context):
        item = copy(item)  # Don't modify original item
        if prefix:
            item.text = f"{prefix}{item.text}"
        yield item

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]

ParsedRoute dataclass

Parsed routing information.

Source code in src/slashed/router.py
@dataclass
class ParsedRoute[TContext]:
    """Parsed routing information."""

    context: TContext
    command: str
    route: Route[TContext] | None = None

PathCompleter

Bases: CompletionProvider

Provides filesystem path completions.

Source code in src/slashed/completers.py
class PathCompleter(CompletionProvider):
    """Provides filesystem path completions."""

    def __init__(
        self,
        file_patterns: list[str] | None = None,
        *,
        directories: bool = True,
        files: bool = True,
        show_hidden: bool = False,
        expanduser: bool = True,
        base_path: JoinablePathLike | None = None,
    ) -> None:
        """Initialize path completer.

        Args:
            file_patterns: Optional glob patterns to filter files
            directories: Whether to include directories
            files: Whether to include files
            show_hidden: Whether to show hidden files
            expanduser: Whether to expand user directory (~)
            base_path: Optional base path to resolve relative paths against
        """
        self.file_patterns = file_patterns
        self.directories = directories
        self.files = files
        self.show_hidden = show_hidden
        self.expanduser = expanduser
        self.base_path = UPath(base_path).resolve() if base_path else None

    async def get_completions(
        self,
        context: CompletionContext[Any],
    ) -> AsyncIterator[CompletionItem]:
        """Get path completions."""
        word = context.current_word or "."

        try:
            # Handle absolute paths
            if UPath(word).is_absolute():
                path = UPath(word)
            # Handle user paths
            elif self.expanduser and word.startswith("~"):
                path = UPath(word).expanduser()
            # Handle relative paths
            else:
                # If base_path is set, resolve relative to it
                base = self.base_path or UPath.cwd()
                path = (base / word).resolve()

            # If path doesn't exist, use its parent for listing
            if not path.exists():
                completion_dir = path.parent
                prefix = path.name
            else:
                completion_dir = path
                prefix = ""

            # List directory contents
            for entry in completion_dir.iterdir():
                # Skip hidden unless enabled
                if not self.show_hidden and entry.name.startswith("."):
                    continue

                # Skip if doesn't match prefix
                if prefix and not entry.name.startswith(prefix):
                    continue

                # Apply type filters
                if entry.is_dir():
                    if not self.directories:
                        continue
                elif entry.is_file():
                    if not self.files:
                        continue
                    if self.file_patterns and not any(
                        entry.match(pattern) for pattern in self.file_patterns
                    ):
                        continue

                # Get relative path if using base_path
                if self.base_path:
                    try:
                        display = str(entry.relative_to(self.base_path))  # pyright: ignore[reportArgumentType]
                    except ValueError:
                        display = str(entry)
                else:
                    display = str(entry)

                # Create completion
                name = str(entry)
                if entry.is_dir():
                    name = f"{name}{os.sep}"
                    kind = "directory"
                else:
                    kind = utils.get_file_kind(entry)
                meta = utils.get_metadata(entry)
                yield CompletionItem(text=name, display=display, kind=kind, metadata=meta)

        except Exception as e:  # noqa: BLE001
            # Log error but don't raise
            logger.debug("Path completion error: %s", e)

__init__

__init__(
    file_patterns: list[str] | None = None,
    *,
    directories: bool = True,
    files: bool = True,
    show_hidden: bool = False,
    expanduser: bool = True,
    base_path: JoinablePathLike | None = None,
) -> None

Initialize path completer.

Parameters:

Name Type Description Default
file_patterns list[str] | None

Optional glob patterns to filter files

None
directories bool

Whether to include directories

True
files bool

Whether to include files

True
show_hidden bool

Whether to show hidden files

False
expanduser bool

Whether to expand user directory (~)

True
base_path JoinablePathLike | None

Optional base path to resolve relative paths against

None
Source code in src/slashed/completers.py
def __init__(
    self,
    file_patterns: list[str] | None = None,
    *,
    directories: bool = True,
    files: bool = True,
    show_hidden: bool = False,
    expanduser: bool = True,
    base_path: JoinablePathLike | None = None,
) -> None:
    """Initialize path completer.

    Args:
        file_patterns: Optional glob patterns to filter files
        directories: Whether to include directories
        files: Whether to include files
        show_hidden: Whether to show hidden files
        expanduser: Whether to expand user directory (~)
        base_path: Optional base path to resolve relative paths against
    """
    self.file_patterns = file_patterns
    self.directories = directories
    self.files = files
    self.show_hidden = show_hidden
    self.expanduser = expanduser
    self.base_path = UPath(base_path).resolve() if base_path else None

get_completions async

get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]

Get path completions.

Source code in src/slashed/completers.py
async def get_completions(
    self,
    context: CompletionContext[Any],
) -> AsyncIterator[CompletionItem]:
    """Get path completions."""
    word = context.current_word or "."

    try:
        # Handle absolute paths
        if UPath(word).is_absolute():
            path = UPath(word)
        # Handle user paths
        elif self.expanduser and word.startswith("~"):
            path = UPath(word).expanduser()
        # Handle relative paths
        else:
            # If base_path is set, resolve relative to it
            base = self.base_path or UPath.cwd()
            path = (base / word).resolve()

        # If path doesn't exist, use its parent for listing
        if not path.exists():
            completion_dir = path.parent
            prefix = path.name
        else:
            completion_dir = path
            prefix = ""

        # List directory contents
        for entry in completion_dir.iterdir():
            # Skip hidden unless enabled
            if not self.show_hidden and entry.name.startswith("."):
                continue

            # Skip if doesn't match prefix
            if prefix and not entry.name.startswith(prefix):
                continue

            # Apply type filters
            if entry.is_dir():
                if not self.directories:
                    continue
            elif entry.is_file():
                if not self.files:
                    continue
                if self.file_patterns and not any(
                    entry.match(pattern) for pattern in self.file_patterns
                ):
                    continue

            # Get relative path if using base_path
            if self.base_path:
                try:
                    display = str(entry.relative_to(self.base_path))  # pyright: ignore[reportArgumentType]
                except ValueError:
                    display = str(entry)
            else:
                display = str(entry)

            # Create completion
            name = str(entry)
            if entry.is_dir():
                name = f"{name}{os.sep}"
                kind = "directory"
            else:
                kind = utils.get_file_kind(entry)
            meta = utils.get_metadata(entry)
            yield CompletionItem(text=name, display=display, kind=kind, metadata=meta)

    except Exception as e:  # noqa: BLE001
        # Log error but don't raise
        logger.debug("Path completion error: %s", e)

QueueOutputWriter

Bases: DefaultOutputWriter

Output writer that puts messages in queue.

Source code in src/slashed/output.py
class QueueOutputWriter(DefaultOutputWriter):
    """Output writer that puts messages in queue."""

    def __init__(self, queue: asyncio.Queue[str]) -> None:
        self.queue = queue

    async def print(self, message: str) -> None:
        await self.queue.put(message)

Route dataclass

Route configuration.

Source code in src/slashed/router.py
@dataclass
class Route[TContext]:
    """Route configuration."""

    prefix: str
    """Route prefix without @ symbol"""

    context: TContext
    """Context for this route"""

    description: str
    """Route description"""

    allowed_commands: set[str] | None = None
    """Optional set of allowed commands for this route"""

    def can_execute(self, command: str) -> bool:
        """Check if command is allowed for this route.

        Args:
            command: Command name to check

        Returns:
            True if command is allowed, False otherwise
        """
        return not self.allowed_commands or command in self.allowed_commands

allowed_commands class-attribute instance-attribute

allowed_commands: set[str] | None = None

Optional set of allowed commands for this route

context instance-attribute

context: TContext

Context for this route

description instance-attribute

description: str

Route description

prefix instance-attribute

prefix: str

Route prefix without @ symbol

can_execute

can_execute(command: str) -> bool

Check if command is allowed for this route.

Parameters:

Name Type Description Default
command str

Command name to check

required

Returns:

Type Description
bool

True if command is allowed, False otherwise

Source code in src/slashed/router.py
def can_execute(self, command: str) -> bool:
    """Check if command is allowed for this route.

    Args:
        command: Command name to check

    Returns:
        True if command is allowed, False otherwise
    """
    return not self.allowed_commands or command in self.allowed_commands

RouteInfo dataclass

Information about a route for display.

Source code in src/slashed/router.py
@dataclass
class RouteInfo:
    """Information about a route for display."""

    prefix: str
    description: str
    active: bool

ShellExecutor

Executes bash-like command lines with pipes and chaining.

This executor handles shell syntax like pipes (|), AND (&&), OR (||), and sequential (;) operators. It delegates individual command execution to the CommandStore.

Example
executor = ShellExecutor(store)
result = await executor.execute("cat file.txt | grep error", ctx)
Source code in src/slashed/shell_executor.py
class ShellExecutor:
    """Executes bash-like command lines with pipes and chaining.

    This executor handles shell syntax like pipes (|), AND (&&), OR (||),
    and sequential (;) operators. It delegates individual command execution
    to the CommandStore.

    Example:
        ```python
        executor = ShellExecutor(store)
        result = await executor.execute("cat file.txt | grep error", ctx)
        ```
    """

    def __init__(self, store: CommandStore) -> None:
        """Initialize the shell executor.

        Args:
            store: Command store for resolving and executing commands
        """
        self.store = store

    async def execute(
        self,
        command_line: str,
        ctx: CommandContext[Any],
    ) -> CommandResult:
        """Execute a full command line (may have pipes, &&, ||, etc.).

        Args:
            command_line: The command line to execute
            ctx: Command context

        Returns:
            Result of the command line execution
        """
        try:
            parts = bashlex.parse(command_line)
        except bashlex.errors.ParsingError as e:
            return CommandResult(stderr=f"Parse error: {e}", exit_code=1)

        if not parts:
            return CommandResult()

        # Execute each top-level part (usually just one)
        result = CommandResult()
        for part in parts:
            result = await self._execute_node(part, ctx)

        return result

    async def _execute_node(
        self,
        node: bashlex.ast.node,
        ctx: CommandContext[Any],
    ) -> CommandResult:
        """Execute an AST node.

        Args:
            node: The AST node to execute
            ctx: Command context

        Returns:
            Result of execution
        """
        match node.kind:  # pyright: ignore[reportAttributeAccessIssue]  # ty: ignore[missing-attribute]
            case "command":
                return await self._execute_command(node, ctx)
            case "pipeline":
                return await self._execute_pipeline(node, ctx)
            case "list":
                return await self._execute_list(node, ctx)
            case "compound":
                # For now, don't support compound commands (if/for/while)
                return CommandResult(
                    stderr="Compound commands (if/for/while) not supported",
                    exit_code=1,
                )
            case _:
                return CommandResult(
                    stderr=f"Unknown node kind: {node.kind}",  # pyright: ignore[reportAttributeAccessIssue]  # ty: ignore[missing-attribute]
                    exit_code=1,
                )

    async def _execute_command(
        self,
        node: bashlex.ast.node,
        ctx: CommandContext[Any],
    ) -> CommandResult:
        """Execute a simple command node.

        Args:
            node: Command AST node
            ctx: Command context

        Returns:
            Result of command execution
        """
        # Extract words from the command (skip redirections, assignments for now)
        words: list[str] = []
        for part in node.parts:  # pyright: ignore[reportAttributeAccessIssue]  # ty: ignore[missing-attribute]
            if part.kind == "word":  # pyright: ignore[reportAttributeAccessIssue]
                words.append(part.word)  # pyright: ignore[reportAttributeAccessIssue]
            elif part.kind == "redirect":
                # TODO: Handle redirections
                pass
            elif part.kind == "assignment":  # pyright: ignore[reportAttributeAccessIssue]
                # TODO: Handle assignments
                pass

        if not words:
            return CommandResult()

        cmd_name = words[0]
        raw_args = words[1:]
        # Get the command
        command = self.store.get_command(cmd_name)
        if not command:
            stderr = f"Unknown command: {cmd_name}"
            return CommandResult(stderr=stderr, exit_code=127)  # std "command not found" exit code
        # Parse arguments into positional args and kwargs
        # bashlex already did the shell parsing, now we just need to
        # separate --flag value pairs from positional arguments
        args: list[str] = []
        kwargs: dict[str, str] = {}
        i = 0
        if command.raw_args:
            args, raw_args = list(raw_args), []
        while i < len(raw_args):
            arg = raw_args[i]
            if arg.startswith("--") and i + 1 < len(raw_args):
                # Long flag: --name value
                kwargs[arg[2:]] = raw_args[i + 1]
                i += 2
            elif arg.startswith("-") and len(arg) == 2 and arg[1].isalpha():  # noqa: PLR2004
                # Short flag: -x value
                if i + 1 < len(raw_args):
                    kwargs[arg[1:]] = raw_args[i + 1]
                    i += 2
                else:
                    args.append(arg)
                    i += 1
            else:
                args.append(arg)
                i += 1

        # Execute with stdin from context
        try:
            result = await command.execute(ctx, args, kwargs)
            return _normalize_result(result)
        except CommandError as e:
            return CommandResult(stderr=str(e), exit_code=1)
        except Exception as e:  # noqa: BLE001
            return CommandResult(stderr=f"Error: {e}", exit_code=1)

    async def _execute_pipeline(
        self,
        node: bashlex.ast.node,
        ctx: CommandContext[Any],
    ) -> CommandResult:
        """Execute a pipeline (cmd1 | cmd2 | cmd3).

        Args:
            node: Pipeline AST node
            ctx: Command context

        Returns:
            Result of the last command in pipeline
        """
        # Extract commands from pipeline (skip pipe operators)
        commands = [p for p in node.parts if p.kind == "command"]  # pyright: ignore[reportAttributeAccessIssue]  # ty: ignore[missing-attribute]
        if not commands:
            return CommandResult()

        # Execute pipeline, threading stdout through stdin
        current_stdin = ctx.stdin
        result = CommandResult()
        for i, cmd in enumerate(commands):
            # Create context with current stdin
            pipe_ctx = replace(ctx, stdin=current_stdin)
            # Execute command
            result = await self._execute_command(cmd, pipe_ctx)
            # If not the last command, use stdout as next stdin
            if i < len(commands) - 1:
                current_stdin = result.stdout
                # Clear stdout for intermediate commands (only last command's stdout matters)
                # But we keep stderr accumulated
            else:
                # Last command - its stdout is the pipeline's stdout
                pass

        return result

    async def _execute_list(
        self,
        node: bashlex.ast.node,
        ctx: CommandContext[Any],
    ) -> CommandResult:
        """Execute a list (cmd1 && cmd2 || cmd3 ; cmd4).

        Unlike pipelines where stdout flows between commands, in a list
        each command's stdout is accumulated in the final result.

        Args:
            node: List AST node
            ctx: Command context

        Returns:
            Combined result with accumulated stdout/stderr
        """
        accumulated_stdout: list[str] = []
        accumulated_stderr: list[str] = []
        result = CommandResult()
        pending_operator: str | None = None

        for part in node.parts:  # pyright: ignore[reportAttributeAccessIssue]  # ty: ignore[missing-attribute]
            if part.kind == "operator":  # pyright: ignore[reportAttributeAccessIssue]
                pending_operator = part.op  # pyright: ignore[reportAttributeAccessIssue]
            elif part.kind in ("command", "pipeline"):
                # Check if we should execute based on previous result and operator
                should_execute = True

                if pending_operator == "&&":
                    # Only execute if previous succeeded
                    should_execute = result.exit_code == 0
                elif pending_operator == "||":
                    # Only execute if previous failed
                    should_execute = result.exit_code != 0
                # For ";" or None, always execute

                if should_execute:
                    if part.kind == "command":  # pyright: ignore[reportAttributeAccessIssue]
                        result = await self._execute_command(part, ctx)
                    else:
                        result = await self._execute_pipeline(part, ctx)

                    # Accumulate output
                    if result.stdout:
                        accumulated_stdout.append(result.stdout)
                    if result.stderr:
                        accumulated_stderr.append(result.stderr)

                pending_operator = None

        # Return combined result
        return CommandResult(
            stdout="".join(accumulated_stdout),
            stderr="".join(accumulated_stderr),
            exit_code=result.exit_code,  # Exit code of last executed command
        )

__init__

__init__(store: CommandStore) -> None

Initialize the shell executor.

Parameters:

Name Type Description Default
store CommandStore

Command store for resolving and executing commands

required
Source code in src/slashed/shell_executor.py
def __init__(self, store: CommandStore) -> None:
    """Initialize the shell executor.

    Args:
        store: Command store for resolving and executing commands
    """
    self.store = store

execute async

execute(command_line: str, ctx: CommandContext[Any]) -> CommandResult

Execute a full command line (may have pipes, &&, ||, etc.).

Parameters:

Name Type Description Default
command_line str

The command line to execute

required
ctx CommandContext[Any]

Command context

required

Returns:

Type Description
CommandResult

Result of the command line execution

Source code in src/slashed/shell_executor.py
async def execute(
    self,
    command_line: str,
    ctx: CommandContext[Any],
) -> CommandResult:
    """Execute a full command line (may have pipes, &&, ||, etc.).

    Args:
        command_line: The command line to execute
        ctx: Command context

    Returns:
        Result of the command line execution
    """
    try:
        parts = bashlex.parse(command_line)
    except bashlex.errors.ParsingError as e:
        return CommandResult(stderr=f"Parse error: {e}", exit_code=1)

    if not parts:
        return CommandResult()

    # Execute each top-level part (usually just one)
    result = CommandResult()
    for part in parts:
        result = await self._execute_node(part, ctx)

    return result

Short dataclass

Marker for parameter shorthand.

Use with Annotated to define single-character shortcuts for command parameters.

Example
from typing import Annotated
from slashed import SlashedCommand, Short

class MyCommand(SlashedCommand):
    name = "greet"

    async def execute_command(
        self,
        name: str,
        verbose: Annotated[bool, Short("v")] = False,
        output: Annotated[str, Short("o")] = "stdout",
    ):
        ...

Now the command can be invoked as: - /greet John --verbose true - /greet John -v true - /greet John -o file.txt -v true

Source code in src/slashed/annotations.py
@dataclass(frozen=True, slots=True)
class Short:
    """Marker for parameter shorthand.

    Use with Annotated to define single-character shortcuts for command parameters.

    Example:
        ```python
        from typing import Annotated
        from slashed import SlashedCommand, Short

        class MyCommand(SlashedCommand):
            name = "greet"

            async def execute_command(
                self,
                name: str,
                verbose: Annotated[bool, Short("v")] = False,
                output: Annotated[str, Short("o")] = "stdout",
            ):
                ...
        ```

        Now the command can be invoked as:
        - `/greet John --verbose true`
        - `/greet John -v true`
        - `/greet John -o file.txt -v true`
    """

    char: str
    """Single character shorthand (without the dash)."""

    def __post_init__(self) -> None:
        """Validate the shorthand character."""
        if len(self.char) != 1:
            msg = f"Short must be a single character, got: {self.char!r}"
            raise ValueError(msg)
        if not self.char.isalpha():
            msg = f"Short must be an alphabetic character, got: {self.char!r}"
            raise ValueError(msg)

char instance-attribute

char: str

Single character shorthand (without the dash).

__post_init__

__post_init__() -> None

Validate the shorthand character.

Source code in src/slashed/annotations.py
def __post_init__(self) -> None:
    """Validate the shorthand character."""
    if len(self.char) != 1:
        msg = f"Short must be a single character, got: {self.char!r}"
        raise ValueError(msg)
    if not self.char.isalpha():
        msg = f"Short must be an alphabetic character, got: {self.char!r}"
        raise ValueError(msg)

SlashedCommand

Bases: BaseCommand

Base class for declarative commands.

Allows defining commands using class syntax with explicit parameters:

Example

class AddWorkerCommand(SlashedCommand): '''Add a new worker to the pool.'''

name = "add-worker"
category = "tools"

async def execute_command(
    self,
    ctx: CommandContext,  # Optional depending on implementation
    worker_id: str,       # required param (no default)
    host: str,            # required param (no default)
    port: int = 8080,     # optional param (has default)
):
    await ctx.print(f"Adding worker {worker_id} at {host}:{port}")

Context-free command

class VersionCommand(SlashedCommand): '''Show version information.'''

name = "version"

async def execute_command(self, major: int, minor: int = 0):
    return f"v{major}.{minor}"
Source code in src/slashed/commands.py
class SlashedCommand(BaseCommand):
    """Base class for declarative commands.

    Allows defining commands using class syntax with explicit parameters:

    Example:
        class AddWorkerCommand(SlashedCommand):
            '''Add a new worker to the pool.'''

            name = "add-worker"
            category = "tools"

            async def execute_command(
                self,
                ctx: CommandContext,  # Optional depending on implementation
                worker_id: str,       # required param (no default)
                host: str,            # required param (no default)
                port: int = 8080,     # optional param (has default)
            ):
                await ctx.print(f"Adding worker {worker_id} at {host}:{port}")

        # Context-free command
        class VersionCommand(SlashedCommand):
            '''Show version information.'''

            name = "version"

            async def execute_command(self, major: int, minor: int = 0):
                return f"v{major}.{minor}"
    """

    name: str
    """Command name"""

    category: str = "general"
    """Command category"""

    description: str = ""
    """Optional description override"""

    usage: str | None = None
    """Optional usage override"""

    help_text: str = ""
    """Optional help text override"""

    def __init__(self) -> None:
        """Initialize command instance."""
        self.description = self.description or inspect.getdoc(self.__class__) or "No description"
        self.help_text = type(self).help_text or self.description

    def __init_subclass__(cls) -> None:
        """Process command class at definition time.

        Validates required attributes and generates description/usage from metadata.
        """
        super().__init_subclass__()

        if not hasattr(cls, "name"):
            msg = f"Command class {cls.__name__} must define 'name' attribute"
            raise TypeError(msg)

        # Get description from docstring if not explicitly set on this class
        if "description" not in cls.__dict__:
            # Check if this class has its own docstring (not inherited)
            own_doc = cls.__dict__.get("__doc__")
            if own_doc:
                cls.description = own_doc
            # Otherwise inherit parent's description (already set from parent's __init_subclass__)
            # If no parent description exists, use "No description"
            elif not hasattr(cls, "description") or not cls.description:
                cls.description = "No description"

        # Generate usage from execute signature if not explicitly set on THIS class
        if "usage" not in cls.__dict__:
            usage_params = extract_usage_params(cls.execute_command, skip_first=True)
            cls.usage = " ".join(usage_params)

    @abstractmethod
    async def execute_command(self, *args: Any, **kwargs: Any) -> Any:
        """Execute the command logic.

        This method should be implemented with explicit parameters.
        Parameters without default values are treated as required.

        Args:
            args: Command arguments (may include context as first param)
            kwargs: Command keyword arguments
        """

    def get_callable(self) -> Callable[..., Any]:
        """The ``execute_command`` method, whose signature defines the parameters."""
        return self.execute_command

    async def execute(
        self,
        ctx: CommandContext[Any],
        args: list[str],
        kwargs: dict[str, str],
    ) -> Any:
        """Execute command by binding command-line arguments to method parameters."""
        method = type(self).execute_command
        call_args, coerced_kwargs = parse_args(method, ctx, args, kwargs, skip_first=True)
        return await self.execute_command(*call_args, **coerced_kwargs)

category class-attribute instance-attribute

category: str = 'general'

Command category

description class-attribute instance-attribute

description: str = self.description or inspect.getdoc(self.__class__) or 'No description'

Optional description override

help_text class-attribute instance-attribute

help_text: str = type(self).help_text or self.description

Optional help text override

name instance-attribute

name: str

Command name

usage class-attribute instance-attribute

usage: str | None = None

Optional usage override

__init__

__init__() -> None

Initialize command instance.

Source code in src/slashed/commands.py
def __init__(self) -> None:
    """Initialize command instance."""
    self.description = self.description or inspect.getdoc(self.__class__) or "No description"
    self.help_text = type(self).help_text or self.description

__init_subclass__

__init_subclass__() -> None

Process command class at definition time.

Validates required attributes and generates description/usage from metadata.

Source code in src/slashed/commands.py
def __init_subclass__(cls) -> None:
    """Process command class at definition time.

    Validates required attributes and generates description/usage from metadata.
    """
    super().__init_subclass__()

    if not hasattr(cls, "name"):
        msg = f"Command class {cls.__name__} must define 'name' attribute"
        raise TypeError(msg)

    # Get description from docstring if not explicitly set on this class
    if "description" not in cls.__dict__:
        # Check if this class has its own docstring (not inherited)
        own_doc = cls.__dict__.get("__doc__")
        if own_doc:
            cls.description = own_doc
        # Otherwise inherit parent's description (already set from parent's __init_subclass__)
        # If no parent description exists, use "No description"
        elif not hasattr(cls, "description") or not cls.description:
            cls.description = "No description"

    # Generate usage from execute signature if not explicitly set on THIS class
    if "usage" not in cls.__dict__:
        usage_params = extract_usage_params(cls.execute_command, skip_first=True)
        cls.usage = " ".join(usage_params)

execute async

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

Execute command by binding command-line arguments to method parameters.

Source code in src/slashed/commands.py
async def execute(
    self,
    ctx: CommandContext[Any],
    args: list[str],
    kwargs: dict[str, str],
) -> Any:
    """Execute command by binding command-line arguments to method parameters."""
    method = type(self).execute_command
    call_args, coerced_kwargs = parse_args(method, ctx, args, kwargs, skip_first=True)
    return await self.execute_command(*call_args, **coerced_kwargs)

execute_command abstractmethod async

execute_command(*args: Any, **kwargs: Any) -> Any

Execute the command logic.

This method should be implemented with explicit parameters. Parameters without default values are treated as required.

Parameters:

Name Type Description Default
args Any

Command arguments (may include context as first param)

()
kwargs Any

Command keyword arguments

{}
Source code in src/slashed/commands.py
@abstractmethod
async def execute_command(self, *args: Any, **kwargs: Any) -> Any:
    """Execute the command logic.

    This method should be implemented with explicit parameters.
    Parameters without default values are treated as required.

    Args:
        args: Command arguments (may include context as first param)
        kwargs: Command keyword arguments
    """

get_callable

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

The execute_command method, whose signature defines the parameters.

Source code in src/slashed/commands.py
def get_callable(self) -> Callable[..., Any]:
    """The ``execute_command`` method, whose signature defines the parameters."""
    return self.execute_command

TransformOutputWriter

Bases: OutputWriter

Output writer that transforms messages before printing via another writer.

Unlike CallbackOutputWriter, this doesn't handle the actual output. Instead, it transforms the message and delegates printing to a base writer. Use this for adding prefixes, timestamps, or other message modifications.

Example
async def add_timestamp(msg: str, fmt: str = "%H:%M:%S") -> str:
    from datetime import datetime
    return f"[{datetime.now().strftime(fmt)}] {msg}"

writer = TransformOutputWriter(add_timestamp, base_writer=console_writer)
Source code in src/slashed/output.py
class TransformOutputWriter(OutputWriter):
    """Output writer that transforms messages before printing via another writer.

    Unlike CallbackOutputWriter, this doesn't handle the actual output.
    Instead, it transforms the message and delegates printing to a base writer.
    Use this for adding prefixes, timestamps, or other message modifications.

    Example:
        ```python
        async def add_timestamp(msg: str, fmt: str = "%H:%M:%S") -> str:
            from datetime import datetime
            return f"[{datetime.now().strftime(fmt)}] {msg}"

        writer = TransformOutputWriter(add_timestamp, base_writer=console_writer)
        ```
    """

    def __init__(
        self,
        transform: Callable[..., Awaitable[str]],
        *args: Any,
        base_writer: OutputWriter | None = None,
        **kwargs: Any,
    ) -> None:
        """Initialize with transform function and base writer."""
        self._transform = transform
        self._args = args
        self._kwargs = kwargs
        self._base_writer = base_writer or DefaultOutputWriter()

    async def print(self, message: str) -> None:
        """Transform and write message."""
        transformed = await self._transform(message, *self._args, **self._kwargs)
        await self._base_writer.print(transformed)

__init__

__init__(
    transform: Callable[..., Awaitable[str]],
    *args: Any,
    base_writer: OutputWriter | None = None,
    **kwargs: Any,
) -> None

Initialize with transform function and base writer.

Source code in src/slashed/output.py
def __init__(
    self,
    transform: Callable[..., Awaitable[str]],
    *args: Any,
    base_writer: OutputWriter | None = None,
    **kwargs: Any,
) -> None:
    """Initialize with transform function and base writer."""
    self._transform = transform
    self._args = args
    self._kwargs = kwargs
    self._base_writer = base_writer or DefaultOutputWriter()

print async

print(message: str) -> None

Transform and write message.

Source code in src/slashed/output.py
async def print(self, message: str) -> None:
    """Transform and write message."""
    transformed = await self._transform(message, *self._args, **self._kwargs)
    await self._base_writer.print(transformed)

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)