Skip to content

[FEATURE] Let an embedder run commands Shell doesn't implement #188

Closed

Description

@ferdingler

Binding

Shell core / Not binding-specific

Problem Statement

Strands Shell only runs commands it implements itself. For other commands, like git, cargo, npm or python, Shell answers "command not found" with status 127. That's a good default, but an app that embeds Shell has no way to provide their own implementation of those commands. The only place to step in is after the whole script returns, and by then it's too late.

Take these as examples:

echo "hello" | cargo run
cargo build && cargo test
x=$(git rev-parse HEAD)
rm out.txt; cargo build

The program needs Shell's pipes, and the rest of the script needs its real exit status. By the time the app sees the 127, the rest of the script already ran without it. Running the script again would repeat side effects like the rm.

Proposed Solution

When no builtin command matches a name, Shell asks the embedder before giving up:

  • Shell pauses at that one command and hands the embedder the program name, its arguments, the working directory, the environment, and the command's stdin/stdout/stderr.
  • The embedder runs it however it wants and returns an exit status. Shell carries on as if it were any other command.
  • The embedder can also decline, and then Shell keeps today's "command not found" and 127.
  • With no handler installed, nothing changes.

I think the natural place is an optional method on Kernel, with a default that declines, since the kernel is already where Shell hands every file and network effect to the embedder.

Use Case

Strands Box runs Shell for an AI agent it doesn't trust. Agents need real tools like git, cargo and python. Box decides whether each program may run, then runs it in its own sandbox, or runs python in an embedded interpreter. Today Box does this through a patch in its own copy of Shell, and it's one of the last things keeping Box from using upstream directly.

The same hook would work for anyone who wants Shell's safe builtins plus a short, controlled list of real programs.

Alternatives Solutions

  • Handle the 127 after the script returns. This doesn't work, because of the pipes, &&, $(…) and side effects above.
  • Run the whole script somewhere else when it mentions a host program. The builtins would then lose Shell's virtual filesystem. Splitting the script up front doesn't work either, because $CMD may only turn out to be cargo at run time.
  • Make the program look like one of Shell's own commands. This is possible today through the multicall and shebang handling, but it depends on undocumented behaviour.

Additional Context

Open questions where I'd like maintainers' input:

  • Should a running program get Shell's virtual stdin/stdout as streams, or as file handles the embedder reads and writes?
  • How should a timeout or cancel reach a program that's running?
  • Should the handler see aliases and functions already expanded? I think yes.

Activity

  1. ferdingler commented on Oct 31, 2026

    @ferdingler
    CollaboratorAuthor

    Here's an alternative to adding a method to the Kernel trait: a small builder option that registers a fallback command.

    let shell = Shell::builder()
        .fallback_command(|ctx, args| async move {
            // ctx: cwd, env, stdin/stdout/stderr
            // return Some(status) if handled, None for "command not found"
        })
        .build();

    When nothing matches (no builtin, function, alias or Shell command), Shell calls the fallback with the name, its arguments, the working directory, the environment and the command's stdin/stdout/stderr, and carries on with the status it returns. If the fallback declines, or none is set, you get today's "command not found" and 127.

    What I like about it:

    • It's opt-in in one place, and you don't need to write a custom kernel to use it.
    • The handler can be a closure, so it carries its own state. For Box, that's our policy and the sandbox we launch programs in.
    • It's close to how Shell already registers its own commands internally, just exposed at run time instead of compile time.

    The same idea could also work per name, like .command("git", handler), with the fallback as the catch-all for anyone who wants to keep it explicit. Box could work with either. What do you think?

  2. ferdingler commented on Oct 31, 2026

    @ferdingler
    CollaboratorAuthor

    Proposed Solution

    Implement only an optional Kernel hook for v1. This covers Strands Box's need to run commands that Shell does not implement. Box already implements Kernel and forwards host spawning through CallKernel::spawn_host, so it can connect the hook to its runner. Defer the builder convenience API and the forwarding adapter that Shell would need to support it.

    Existing kernels default to no handler and retain their current behavior. A kernel that supplies a handler also opts into concurrent stderr draining and cancellation of foreground tasks when execution is dropped. The first release exposes this capability in native Rust; Python, Node.js, and WASM retain their existing APIs.

    Interface. Add a defaulted method to the existing Kernel trait and a handler contract:

    // New method on Kernel; existing implementations inherit this default.
    fn command_fallback(&self) -> Option<&dyn CommandFallback> {
        None
    }
    
    #[async_trait::async_trait]
    pub trait CommandFallback: Send + Sync {
        async fn run(
            &self,
            ctx: &mut CommandContext,
        ) -> std::io::Result<Option<i32>>;
    }

    Box's kernel implements CommandFallback and overrides command_fallback() to return Some(self). Its run method decides whether to handle the command, applies Box's policy, and delegates to its sandbox or interpreter. The existing construction path remains:

    let mut shell = Shell::with_kernel(box_kernel);
    let output = shell.run("echo hello | cargo run && git status").await;

    Shell owns expansion, pipelines, redirection, and control flow. Pipeline stages can invoke the handler concurrently, so the handler owns synchronization of shared state. Preserve the existing Kernel: Send + Sync and Send future conventions.

    The optional capability distinguishes no handler installed from a handler declining this command. Keep its presence stable for the kernel's lifetime; make per-command decisions inside run. Shell can then preserve existing execution behavior when the capability is absent. The shared kernel already travels through nested execution, including Lua calls that create fresh Process values, so the handler needs no separate inheritance rules.

    Command context and results. CommandContext keeps its fields private. Accessors expose the final program name, arguments, virtual working directory, Shell environment, and absolute execution deadline. Arguments exclude the program name; the environment includes command-local assignments. Its stdio() method returns separate mutable borrows of asynchronous byte streams backed by existing FdReader/FdWriter handles. Each stream is optional. Unavailable or closed descriptors stay unavailable; Shell never substitutes host stdin, stdout, or stderr.

    The handler receives streams after redirection and processes them incrementally. Stream adapters support explicit input closure and output shutdown, so downstream commands can observe end of output before the handler returns. Borrowing the context keeps ownership with Shell: after a decline or error, it writes diagnostics through the original redirected stderr, if still open. Captured Output.stdout and Output.stderr remain strings.

    Handler result Shell behavior
    Ok(Some(status)) Use that status, including 127, with no synthesized error.
    Ok(None) Emit today's command not found diagnostic and return 127.
    Err(error) Write the execution error to the command's stderr and return 1, matching existing command errors.

    Decline before using or closing streams, or starting external work. If policy rejects a command the handler supports, return a handled failure, such as Ok(Some(126)). Neither failure nor a returned 127 triggers another attempt or a replay of the script.

    Dispatch. Invoke the hook at the final missing-command branch in run_pipeline, after existing command and virtual executable resolution. Preserve builtin, function, registered-command, multicall, and shebang precedence. The hook sees expanded arguments and any interpreter rewrite: ./script can become /usr/bin/python plus the script path. Preserve that full name. Do not invoke the hook for type, command -v, or because an existing command rejects its arguments. This change does not add env program support.

    Streaming and cancellation. The current pipeline drains stderr one stage at a time, which can deadlock a downstream program that writes stderr before reading stdin. Dropping a stage's JoinHandle also leaves its task running. For kernels with a handler, drain stderr concurrently and abort foreground tasks when their owning execution is dropped. Include compound-pipeline producers and tasks that drain output. Preserve stage order when assembling captured stderr. Keep legacy draining and task ownership when the capability is absent.

    Bound each handler future by the existing absolute deadline. Expiry drops the future, reports a timeout, and returns 1. Dropping foreground Rust execution also drops its handler future. The handler must yield while waiting and ensure cancellation terminates and reaps any external work it starts. Dropping a future alone cannot kill a child process. Explicit background jobs retain their existing semantics.

    Compatibility and scope. Keep ShellBuilder, Shell::with_kernel, existing execution signatures, Output, configuration snapshots, and command registration types unchanged. Add no fields to VfsKernel, whose public struct literals are part of the Rust API. The default kernel has no fallback. Python and Node require no new callback options or runtime bridges; WASM callback support remains outside this release.

    The handler owns process, filesystem, and network policy for anything it launches. It receives virtual paths and the Shell environment, with no implicit host-path mapping, inherited host environment, or resolved HTTP credentials. Shell adds no host process launcher; its built-in network guards do not automatically sandbox an external program.

    A builder API can follow if callers using the default virtual filesystem need it. A per-name registry adds collision and discovery rules that Box does not need for this feature. Storing the handler on Process would require propagation wherever code creates a fresh process. The kernel hook uses Box's existing integration point and keeps the first change focused.

    Validation. The earlier throwaway prototype, based on Shell main at e77c26b, included both the kernel capability and builder convenience. Its tests exercised dispatch, streams, and lifecycle behavior intended for this proposal. The kernel-only implementation still needs its own validation. The prototype tests cover the issue's four examples, command precedence, interpreter rewriting, nested Lua execution, statuses, argument and environment preservation, and redirected diagnostics. Streaming tests cover binary pipes, backpressure, early closure, timeout, and cancellation through compound pipelines. They also verify unchanged behavior without a handler.

    On Linux, that prototype passed 1,910 Rust tests (including 14 prototype tests), 68 Python tests, and 41 Node tests, plus formatting and TypeScript checks. Clippy completed with warnings. The runners were in-memory substitutes; these results do not validate actual sandbox isolation, child termination, or other platforms.

    Implement the kernel capability, command context, and required dispatch/lifecycle handling. Port the relevant prototype tests to exercise Shell::with_kernel and Shell::run, and rerun unchanged-client checks for Rust, Python, and Node. Leave the builder API and language callback bridges for separate proposals.

  3. added
    enhancement
    on Nov 2, 2026
  4. added theissue type on Nov 2, 2026
  5. ferdingler commented on Nov 2, 2026

    @ferdingler
    CollaboratorAuthor

    The kernel hook shipped in #190, so I'm closing this. The builder option and the Python/Node/WASM bridges can follow as their own issues if someone needs them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Fields

    Language

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions