Repository navigation
Description
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 buildThe 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
$CMDmay only turn out to becargoat 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.
Metadata
Metadata
Assignees
Labels
Type
Fields
Language
Activity
ferdingler commentedon Oct 31, 2026
Here's an alternative to adding a method to the
Kerneltrait: a small builder option that registers a fallback command.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:
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?ferdingler commentedon Oct 31, 2026
Proposed Solution
Implement only an optional
Kernelhook for v1. This covers Strands Box's need to run commands that Shell does not implement. Box already implementsKerneland forwards host spawning throughCallKernel::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
Kerneltrait and a handler contract:Box's kernel implements
CommandFallbackand overridescommand_fallback()to returnSome(self). Itsrunmethod decides whether to handle the command, applies Box's policy, and delegates to its sandbox or interpreter. The existing construction path remains: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 + SyncandSendfuture 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 freshProcessvalues, so the handler needs no separate inheritance rules.Command context and results.
CommandContextkeeps 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. Itsstdio()method returns separate mutable borrows of asynchronous byte streams backed by existingFdReader/FdWriterhandles. 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.stdoutandOutput.stderrremain strings.Ok(Some(status))Ok(None)command not founddiagnostic and return 127.Err(error)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:./scriptcan become/usr/bin/pythonplus the script path. Preserve that full name. Do not invoke the hook fortype,command -v, or because an existing command rejects its arguments. This change does not addenv programsupport.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
JoinHandlealso 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 toVfsKernel, 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
Processwould 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
mainate77c26b, 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_kernelandShell::run, and rerun unchanged-client checks for Rust, Python, and Node. Leave the builder API and language callback bridges for separate proposals.ferdingler commentedon Nov 2, 2026
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.