Skip to content

feat(shell): forward a Shell alias's stdin to its command - #397

Merged
abhisheksp merged 25 commits into
mainfrom
feature/shell/stdin-to-hosted-shell
Nov 13, 2026
Merged

abhisheksp merged 25 commits into
mainfrom
feature/shell/stdin-to-hosted-shell

Conversation

@abhisheksp

@abhisheksp abhisheksp commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

What / why. A command run through the zsh, bash, or sh alias received empty stdin. A harness hook (for example, a Claude Code hook in exec form, {"command":"bash","args":["/path/hook.sh"]}) gets its event JSON on stdin, so no hook could read its input. This PR forwards finite stdin to the hosted Shell. It also fixes three Shell defects that a hook script hits:

  • $(cat) and ( ... ) read no stdin;
  • { false; } > f reported 0;
  • ! before a compound was ignored;

Before and after.

On main, the alias sends the command text but not its stdin, so a hook reads nothing:

flowchart LR
  subgraph cage["Agent sandbox"]
    H["Claude Code hook: bash hook.sh, event JSON on stdin"] --> A["bash alias"]
  end
  subgraph tcb["Trusted process"]
    B["Broker"] --> S["Shell runs hook.sh"]
  end
  A -->|"command text only"| B
  S -->|"input=$(cat) reads empty"| X["hook cannot see the event"]
Loading

With this PR, the alias streams stdin after the Call, and the broker caps it:

flowchart LR
  subgraph cage["Agent sandbox"]
    H["Claude Code hook: bash hook.sh, event JSON on stdin"] --> A["bash alias"]
  end
  subgraph tcb["Trusted process"]
    B["Broker: caps at limits.shell.max_stdin (64 KiB default)"] --> S["Shell runs hook.sh"]
  end
  A -->|"Call, then Input frames, then InputEof"| B
  S -->|"input=$(cat) reads the event"| P["fs:* and shell:* decisions as before"]
  S -->|"exit 2"| K["Claude Code blocks the tool call"]
Loading

How.

  • Alias: streams a piped or file stdin to the broker after the Call; a terminal gets EOF. It forwards every byte, so the writer never blocks.
  • Broker: caps stdin per command at the new [limits.shell] max_stdin (a positive byte count, 64 KiB by default; 0 is a load error because the cap bounds the stdin the trusted process holds), and per connection at that × the programs per connection. Unread stdin waits in one buffer of at most max_stdin bytes, however many frames brought it, and reaches the Shell in frames of at most one 48 KiB chunk. Past the cap it feeds exactly max_stdin bytes, discards the rest one frame at a time, withholds EOF, sends no Denied, and does not stop the Call: a command that ignores its input succeeds, and a reader past the cap waits for the Shell deadline and fails, with a stderr note that its input was cut.
  • Refusals are unchanged by the cap: an overlong frame is still refused (Denied, Signal, stdin left open), and every later Input is dropped, so a waiting read never completes after a refusal. Only well-formed frames over the byte cap are cut silently.
  • Shell fixes (recorded in crates/shell/UPSTREAM.md): $(...) and ( ... ) read the caller's stdin; { ...; } > f keeps its status; ! inverts a compound. Lua reads outside stdin as empty, as on main.

New primitive or interface? No new frame types or fields, and PROTOCOL_VERSION is unchanged. One additive box.toml key, [limits.shell] max_stdin, approved by the maintainer; a record that sets it is stamped record version 33, so an older build refuses the box instead of resuming it with the default cap. Two behaviors change and can be observed: Shell aliases now forward stdin, and the broker caps it.

Security change? No new authority. stdin is data. A command that turns it into code (eval "$(cat)") or into a path (cat "$(cat)") is still decided by policy (a_command_evaluated_from_stdin_is_decided_by_policy, a_file_read_named_on_stdin_needs_its_own_permit). Every read stays in the contained alias; there is no host /dev/stdin mapping. The alias still refuses no-args and -s.

Scope and costs:

  • Only commands the Shell runs itself receive stdin. Tool leaves still get Stdio::null(), and the Python and MCP aliases are unchanged.
  • A command that reads a stdin that never reaches EOF waits until the Shell deadline (30 s by default).
  • The max_stdin limit applies only to stdin piped into the alias from outside the Shell (hooks, or programs that start bash with input). Pipes inside a command are not affected.
  • Bytes past the cap still cross the socket and are discarded in the trusted process until the Call exits: CPU, not memory. With shell.timeout = false, a reader past the cap waits until its caller stops it, like any blocked read.
  • The alias reads stdin whether or not the command does, so it consumes bytes a POSIX shell would leave, such as the rest of an inherited file.
  • If a cancelled Call drops a substitution, the borrowed stdin is dropped with it, so a later Call on the same Program reads no stdin. An alias opens one Program per Call, so it is not affected.
  • Overlap with feat(box): let a tool replace python3 so a project's own Python runs #389: that PR also changes strands-box-sock-alias.rs (the Python aliases forward a Shell command when a tool replaces python3) and the external-command branch in crates/shell/src/exec.rs. A trial merge of feat(box): let a tool replace python3 so a project's own Python runs #389 onto this branch conflicts in both files. Whichever PR lands second resolves them. The two changes touch different branches of the alias.

Related Issues

None filed. This is part of supporting harness hooks in a box.

Type of Change

New feature (plus three Shell bug fixes)

Testing

  • cargo test -p strands-shell --all-features: 2018 passed, 0 failed (x86_64 Linux and macOS).
  • cargo test -p strands-box --all-features on x86_64 Linux: lib failures equal main's x86 baseline (Linux containment there is ARM64 only). The MCP exchange test modern_cancelled_large_ids_reach_the_byte_limit_before_the_count_limit is a timing flake: it passed 2 of 3 reruns.
  • cargo fmt --all --check. Clippy shows 0 warnings in crates/box, and the count in crates/shell is unchanged (17).
  • Each new test fails without its change: checked for the alias tests, the broker tests, and the Shell redirect, negation, stdin-borrow, lua, and errexit tests.
  • macOS (aarch64) at the final head:
    • cargo test -p strands-shell --all-features: 2018 passed, 0 failed.
    • The alias bin (46 tests) and the broker host tests (60) pass.
    • box_cardinality: e5a_stdin_reaches_a_shell_command passes. The piped value arrives, which inverts the old experiment.
    • e2b_a_non_yielding_request_does_not_delay_a_concurrent_one is a load flake that also fails on main under the full suite (1 of 2 runs on main; 3 of 3 alone on this branch; the suite passes with --test-threads=1).
    • The full workspace suite run before the review fixes failed only in telemetry tests that also flake on main, plus e5a, inverted since.
  • macOS end to end, Claude Code 2.1.292 against a local stand-in model API, with a box running exec-form hooks:
    • SessionStart got its event JSON on stdin, and its stdout reached the model.
    • PreToolUse input=$(cat) read the event, and exit 2 blocked the tool call.
    • PostToolUse ran. { false; } > f; echo $? printed 1, and if ! { false; } > f took the then-branch.
    • Bash tool calls completed in about 1 s each, with Claude Code's held-open stdin.
  • macOS, the stdin limit with a real Claude Code event (2.1.292), at ea22ab1: a Write of 100,000 bytes gives a PostToolUse event of 200,793 bytes. Two exec-form hooks ran: one ignores stdin, and one runs cat > big.json.
    • Default limit (65,536): the ignoring hook ran (marker written). The reader got exactly 65,536 bytes, waited for the Shell deadline, and failed. Claude Code's transcript shows the note stdin is more than 65536 bytes; the command received only the first 65536.
    • max_stdin = 262144: the reader got the whole event (200,793 bytes, tool_input.content 100,000), with no cut note, and the run took 4 s.
    • Boxy cannot set max_stdin yet. This run used a local Boxy build that passes the key through; it is not part of any PR.
  • Not run: the containment suite outside CI.

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR
  • I have added tests that prove the change works
  • I have updated the documentation (docs/user/shell.md, docs/design/decisions.md, crates/box/AGENTS.md, crates/shell/UPSTREAM.md)
  • My changes generate no new warnings

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

## Problem

A command run through the `zsh`, `bash`, or `sh` alias gets empty stdin.
A harness hook reads its event JSON on stdin, so no hook can read its
input. The hosted Shell also loses stdin in `$(...)` and `( ... )`,
reports status 0 for `{ false; } > f`, and ignores `!` before a compound
command, so a guard such as `if ! (cmd) > f` takes the wrong branch.

## Solution

The Shell alias classifies fd 0 with `fstat`. It streams a pipe, a
regular file, or a socket as `Input` frames after the `Call`, then sends
`InputEof`. It returns at `Exit`, so a stdin that its writer keeps open
holds no command. Over 64 KiB, or on a read error, it signals the Call
and exits 125. No frame type or protocol field changes. The Python and
MCP aliases and tool leaves do not change.

The broker refuses an `Input` over one chunk before it decodes it. It
caps stdin per Program and per connection. A refusal signals the
running Call and refuses each later Call on that Program.

In the vendored Shell: a substitution and a subshell borrow the
caller's stdin; a redirected group keeps its status; `!` inverts a
compound (`parser::Item::Negated`); `set -e` exempts an inverted
command; and `lua` reads stdin only when the script names it.

## Tests

- Alias: `a_finite_pipe_is_read_byte_for_byte`,
  `oversized_stdin_is_refused_and_stdin_at_the_limit_is_not`,
  `a_socket_backed_stdin_is_read`,
  `a_read_error_is_refused_rather_than_sent_as_empty_input`,
  `stdin_is_classified_by_its_descriptor`,
  `the_alias_streams_its_stdin_after_the_call`,
  `a_stdin_held_open_does_not_hold_a_command_that_finishes`,
  `oversized_stdin_interrupts_the_call_and_fails`.
- Broker (`host.rs`): `a_command_gets_its_full_stdin_before_the_call`,
  `input_sent_after_the_call_reaches_the_running_command`,
  `a_command_that_never_reads_its_stdin_finishes`,
  `oversized_input_is_refused_at_the_broker_and_the_call_does_not_run`,
  `an_overlong_input_frame_is_refused_and_the_call_does_not_run`,
  `a_refused_input_stops_the_running_call_before_it_acts`,
  `a_connections_input_is_capped_across_its_programs`,
  `a_command_evaluated_from_stdin_is_decided_by_policy`,
  `a_file_read_named_on_stdin_needs_its_own_permit`.
- Shell: the redirected-group, `negation_*`, stdin-borrow, lua, and
  errexit tests in `tests/shell_integration.rs`. Each fails without
  its change.
- Gates on x86_64 Linux: fmt, owned clippy 0, vendored clippy
  unchanged, shell suite green. Box lib failures equal main's x86
  baseline; `modern_cancelled_large_ids_reach_the_byte_limit...` is a
  timing flake that passed 2 of 3 reruns.
- Not run here: the containment suite. macOS runs are in the PR.
@abhisheksp abhisheksp changed the title feat(shell): Forward a Shell alias's stdin to its command feat(shell): forward a Shell alias's stdin to its command Nov 11, 2026
Comment thread crates/shell/src/exec.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

One blocking problem. When the alias refuses oversized stdin or fails to read it, it still sends EOF, so a running command can finish on a truncated prefix of its input. That breaks the guarantee this PR writes into crates/box/AGENTS.md. I reproduced it with a broker test, and the fix is one line (see the inline comment). There is also a non-blocking errexit gap in the ! handling.

Details Assumptions and rules checked that held
  • An fd 0 that is /dev/null, a TTY, a directory or closed (EBADF) is classified Absent and gets an immediate InputEof, as it did before this PR.
  • With a held-open pipe, a command that never reads stdin returns at Exit, because the reader thread does not block the process from exiting.
  • Oversized stdin that arrives before the Call starts is caught by the is_cancelled() check at the start of run_call, so the Call does not run.
  • The broker refuses an encoded Input frame that is too long before it decodes it. The per-Program and per-connection caps hold. A Call after a refusal is denied.
  • MCP Input/InputEof keep their own match arms and are not affected by the new budgets. Python still denies input.
  • Item::Negated is handled in every exhaustive Item match (exec, capture, heredoc resolution). No wildcard arm hides an inner command from execution.
  • Lua's names_stdin: the sandbox exposes only io.read/io.lines for stdin (io.lines(filename) is refused), so the substring check covers every way a script can reach stdin.
  • Root AGENTS.md: the change to the frozen broker-protocol behavior is disclosed as approved. PROTOCOL_VERSION is unchanged and no frame shapes change. Tool leaves keep Stdio::null(), so no workload-named program gets stdin outside its sandbox.

Streaming after the Call, rather than collecting stdin to EOF first, is the right call for held-open harness stdin.

Comment thread crates/shell/src/exec.rs Resolved
Comment thread crates/box/src/run/broker/program.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

Reviewed at head 5663ddc. The only change since 5fb40f5 is the inverted E5a test. The alias and broker framing hold up. The blocker is in the Shell: a hosted, non-builtin command run before the stdin read drops that stdin. The hook gets empty input and exits 0, or, when input arrives later, the broker kills the Call. Both cases are reproduced in the inline comments.

Checked and held
  • Alias refusal path (Signal then InputEof): the cancel won 60 of 60 runs, at 48 KiB and at 3 B, and the Call never wrote its output on partial input.
  • classify_stdin: /dev/null, a terminal, and a closed fd get InputEof. A held-open pipe with no data does not hold back a command that ignores stdin.
  • Broker caps: oversized encoded and decoded frames, the per-Program budget, and the per-connection cap (counted across closed Programs, and the alias uses one connection per call) all refuse as described.
  • lua names_stdin: the vendored io table exposes only read and lines for stdin, so the heuristic covers every reachable reader.
  • ! on compounds, and set -e exempting ! cmd and ! { …; }: these match bash.
  • exec 0<file and exec 0<&- inside ( ) or $( ) do not leak to the parent.
  • MCP and Python input arms are unchanged, and the protocol behavior change is disclosed as approved.

Once the stdin hand-back is fixed, the four Shell fixes and the streaming design look solid.

Comment thread crates/shell/src/builtins/lua.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

I reviewed the changes from 5663ddc to c651eab. The stdin hand-back, Closed input, the alias's no-EOF refusal and Close are all fixed. One path is still open: on a transport disconnect, the broker closes stdin, so a Call can act on partial input (see the host.rs comment). Kevin's io . read spacing thread on lua.rs is also still open, because names_stdin didn't change.

Checked and held at c651eab
  • Stage-0 stdin hand-back: after builtins, functions, hosted commands, command-not-found, host-binary refusals, background jobs, redirect-only and assignment-only stages, and 0<&-, the next reader still gets the unread stdin.
  • reads_stdin covers every fd-0 Redirect variant (Read, ReadWrite, DupRead, HereDoc). Here-documents keep the outer stdin aside.
  • On a Closed send, input is dropped and the Call goes on. Full and OverBudget still refuse it and signal the Call.
  • An alias refusal sends Signal without InputEof, and the write half stays open until Exit. Sending Close mid-input wrote no partial output in 20 of 20 runs.
  • ! turns errexit off around the inner item, and set -e; ! { false; echo in; }; echo after matches bash.

Comment thread crates/shell/src/builtins/lua.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

Reviewed at head dde0d17. Since my review of 5663ddc, c651eab fixed both of my earlier findings and the alias InputEof race. dde0d17 replaces the Lua text check with a lazy, async io.read. Two blockers remain, both posted inline. The async read breaks reads inside a coroutine or a C callback when input arrives late. The disconnect path still closes stdin after the signal.

Checked and held
  • Stdin hand-back: x=$(jq -n 1); cat, (echo a | cat); cat, d=$(dirname …); x=$(cat), x=$(printf inner | cat); cat, and cmd </dev/null; cat now match bash. A stage that redirects fd 0, including 0<&-, sets the caller's stdin aside and restores it.
  • A late Input after the Shell dropped its receiver is now dropped, and the Call is not killed (late_input_for_a_command_that_does_not_read_is_dropped).
  • On a refusal or read error, the alias sends Signal with no InputEof and waits for Exit while the write half stays open. The Close arm only signals.
  • Lua at the top level (io . read, local r = io.read, io.lines(), pcall(io.read)) with late input works, and lua -e 'print(1)' does not wait on a held-open stdin.
  • set -e; ! { false; echo in; }; echo after matches bash.

The stdin hand-back fix is thorough, and the new regression table test pins it well.

@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

Reviewed at head 716eab4. It differs from dde0d17 only in the stdin cap: past 64 KiB, the alias now forwards the cap, drains the rest and sends no end-of-file, where before it sent Signal. This helps hooks that ignore stdin. But a reading hook now waits in the Call, so the unfixed disconnect close_stdin() turns a harness hook timeout into acting on the truncated prefix. That's posted inline as a blocker. The Lua async io.read blocker from the last round is also unchanged.

Checked and held at 716eab4
  • Input of exactly the cap ends in InputEof. Past the cap, exactly limit bytes are forwarded, with no InputEof and no Signal (stdin_past_the_limit_is_cut_at_the_limit_with_no_end_of_file).
  • A writer that sends 1 MiB is drained and never blocks or gets EPIPE. drain handles Interrupted and WouldBlock, and a held-open stdin does not stop the alias from returning at Exit.
  • A command that does not read stdin exits 0 past the cap. A reading command that stays connected until the Shell deadline does not write its output.
  • A read error still sends Signal with no InputEof and exits 125.

Comment thread crates/box/src/run/broker/host.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

Reviewed at head f5043da (changes since dde0d17: 716eab4 drains past the cap, f5043da relays output asynchronously and ignores InputEof after a refusal). Two blockers remain:

  • Disconnect path (new inline comment on host.rs, with a repro): the cap now parks reading Calls with no end-of-file, so a harness kill commonly makes the Call act on the 64 KiB prefix.
  • Lua async io.read in coroutines and C callbacks: still open from the lua.rs:524 thread. That code is unchanged since dde0d17.
Checked and held
  • Past the cap: exactly 64 KiB is forwarded, then no InputEof and no Signal. Input exactly at the cap still ends in end-of-file. A command that does not read finishes, and the drain keeps the writer from blocking or getting EPIPE.
  • InputEof after a refusal: input_refused belongs to the Program and is never reset. Later Calls on that Program are refused anyway, so ignoring the EOF loses nothing.
  • Async stdout/stderr relay: each chunk is written and flushed before the next frame is read, so output order across both streams is kept. An EPIPE on stdout still surfaces as an error.

@github-actions

Copy link
Copy Markdown

Assessment: Approve once the open threads from other reviewers are resolved. No new findings at d12f6a1.

d12f6a1 only changes docs. It fixes the stale crates/box/AGENTS.md sentence I flagged at 4fecfb5, and the PR description no longer says a full stdin channel is refused.

Checked and held at d12f6a1
  • AGENTS.md agrees with itself: line 694 (one merged buffer of at most max_stdin) and line 708 (the same per-Program buffer, sent in frames of at most MAX_CHUNK_BYTES) now describe the same design.
  • The stated reason is accurate: ChannelReader::poll_read in crates/shell/src/os.rs calls remainder.drain(..n), which shifts the rest of the frame on each read.
  • Description numbers match the code: "one 48 KiB chunk" matches MAX_CHUNK_BYTES = 48 * 1024 in protocol.rs.
  • No code changes since 4fecfb5: the earlier checks still apply (frame bound, EOF order, 4 MiB while read in 3.8 s, memory, reader gone).

A cancelled Call left the compound that starts a pipeline running with the caller's stdin. An abort guard now stops it. The alias also fails when a stdin write fails, the connection limit test checks the cut, and the shell page no longer promises that a writer never gets a broken pipe.
kevin-orellana
kevin-orellana previously approved these changes Nov 12, 2026
@github-actions

Copy link
Copy Markdown

Assessment: Approve. 6b4e451 makes one real Shell fix, and I left one test-coverage comment on it (non-blocking).

Checked at 6b4e451 and held
  • Abort guard (CompoundPipeline): when the Call finishes normally, handle.await runs first and the abort does nothing. When the Call is cancelled (deadline, refusal, Close, disconnect), the compound is aborted and its ProcessGroup drops with it. Without the guard, a Shell-level probe acts on part of its input; at HEAD it doesn't.
  • Other places that borrow stdin: pipeline stages are already covered by the Tasks guard at exec.rs:4040. The captured CompoundPipeline arm runs its compound inline. A background job is created with fork() and gets no fds, so it holds no stdin.
  • Alias stdin write failure: the broker keeps reading after Exit, so a command that finished can't race into a failure through EPIPE. A write stalled for 5 s already ends the connection through the broker's own 5 s writer timeout, so recording the error changes only which message the alias reports.
  • Connection-limit test addition: it asserts that no end-of-file arrives and that out is never written after the interrupt.
  • docs/user/shell.md: the new broken-pipe sentence is accurate. Forwarding ends when the alias exits, and a writer that keeps writing after that can get EPIPE.

Comment thread crates/box/src/run/broker/host.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Approve. 71ca11c adds the Shell-level test I asked for, and it now pins the abort guard from 6b4e451. I have no new findings.

Checked at 71ca11c and held
  • The new test pins the fix: a_cancelled_compound_pipeline_never_acts_after_its_run_is_dropped passes at HEAD and passed 5 of 5 reruns. With the os::Tasks guard removed, it fails with left: "RACTED", right: "R".
  • It can't pass without reaching the read: it requires ready, so a run cancelled before read first makes it fail instead of passing without testing anything. It also compares the whole stdout in one check.
  • The broker test is fine to keep: a_cancelled_compound_pipeline_never_acts_on_part_of_its_input doesn't pin the guard. It still checks that a refusal, a Close, or a disconnect never sends end-of-file to the Program.

@abhisheksp
abhisheksp enabled auto-merge (squash) November 13, 2026 00:28
@abhisheksp
abhisheksp merged commit 88e8c19 into main Nov 13, 2026
21 of 23 checks passed
@abhisheksp
abhisheksp deleted the feature/shell/stdin-to-hosted-shell branch November 13, 2026 00:53
ferdingler added a commit that referenced this pull request Nov 13, 2026
…against the upstream Shell

The vendored Shell files that #397 changed are deleted here. #397's Shell tests
move to crates/shell/tests/main_shell_semantics.rs and the broker tests, and its
two Lua stdin tests move to the broker. The tests for #397's Shell fixes fail
until the upstream Shell fixes land.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area - Shell/Monty enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants