Skip to content

feat: let a kernel decide each command Shell runs - #204

Merged
ferdingler merged 7 commits into
strands-agents:mainfrom
ferdingler:feat/command-exec-hook
Nov 11, 2026
Merged

ferdingler merged 7 commits into
strands-agents:mainfrom
ferdingler:feat/command-exec-hook

Conversation

@ferdingler

@ferdingler ferdingler commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Strands Box has a policy rule that decides each command an agent runs. For example, an operator can allow cat and grep but not rm. Today Box can't do that on top of upstream Shell, because builtins like rm or echo run inside Shell and never reach the kernel, so the kernel has no point where it can say no. The same goes for commands that run from inside another one, like eval, source, a trap, find -exec, xargs or Lua's os.execute.

This PR adds two optional methods on the kernel, and both get the same CommandRequest: the program, the expanded arguments and the working directory. Before a pipeline starts, Shell asks the kernel about each stage it runs itself. If the kernel refuses any stage, nothing in the pipeline runs and Shell prints the reason and returns 126. builtin echo is asked about as echo, since that's what runs. After a command finishes, Shell tells the kernel its status. That call is async and can fail, because a kernel might write it somewhere durable; if it fails, Shell can't undo the command, so it prints the error and the command ends with 125. A command that was allowed but never started, because its redirect failed or another stage was refused, isn't reported. Commands that go to the command fallback from #190 are not asked, because the fallback already gets them. The defaults allow everything and record nothing, so a kernel that doesn't implement them sees no change.

Evidence from Box

Box's vendored copy of Shell has this today, and Box uses it for its shell:exec policy action. It asks before every pipeline stage, asks for all stages before any of them runs (so cat secret | curl … doesn't read the file before the second stage is refused), and records each command's exit status so a policy can write rules over past commands. Like Box, it doesn't ask about eval, source, exec or command under their own names, only about the commands they run. This PR covers those same things and nothing more. Box also passes per-argument flags for telemetry redaction; I left those out, and the request type lets us add them later without breaking anyone.

Related Issues

None.

Documentation PR

None. The two new methods and the request type have rustdoc.

Type of Change

New feature

Testing

I tested it with a custom kernel that records every call and refuses the programs I give it. An allowed command runs and the kernel sees the expanded arguments, the working directory and the status, including for each stage of a pipeline, a function and an sh script. A refused command doesn't run, its output is the reason, and it's never reported as finished. A refused stage stops the stages before it too. rm is still asked about when it comes from eval, a function, xargs, find -exec, $(…), source, sh, Lua and an exit trap. builtin in front of a command is still asked about as that command, whether it's in a later stage, quoted, from a variable, nested, or inside eval. A failed status report changes the status and is printed. A command nobody implements isn't asked about. I broke the check, the fallback filter and the builtin handling on purpose and the tests caught each one. The existing Rust suite passes on Linux with no new clippy warnings. I didn't run the Python or Node suites, since the bindings don't change.

  • I ran the relevant test suites for the bindings I touched (cargo test --workspace --all-targets, pytest tests/python, npm test)
  • If I touched Rust, I ran cargo fmt and cargo clippy

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

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

@ferdingler
ferdingler marked this pull request as ready for review November 9, 2026 21:37
@ferdingler
ferdingler requested a review from a team as a code owner November 9, 2026 21:37
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent review please

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ferdingler Changes requested: you can get past check_command by putting builtin in front of a command.

builtin lua -e 'os.remove("/tmp/x")' asks the kernel about builtin, never about lua. With a kernel that denies {lua, rm}, it exits 0 and deletes the file. The same works for every ordinary builtin (find, xargs, echo, cd, trap, …), in a pipeline stage and nested (builtin builtin …). Allowlists and the PR's "deny rm" example aren't affected, but a denylist naming any builtin is. The inline suggestion is a 4-line loop; I tested it.

Non-blocking: the rustdoc describes more coverage than the code has, and there's a question about whether the hook should take a context struct. This adds two public Kernel methods, and the PR has no needs-api-review label.

What I verified · Questions · Appendix

Verified at 9346d01

  • cargo test --locked --workspace --all-targets: all green (1548 shell_integration, 5 command_check, and the rest).
  • cargo clippy --all-targets: no warnings on changed lines.
  • I wrote 37 adversarial repro tests against a recording/denying kernel. The only failures were the builtin bypass and the missing command_finished below.
  • With the suggested fix applied, the bypass repros pass, and so do command_check (5/5) and shell_integration (1548/1548).

What holds: no redirect is applied and no earlier stage runs before a refusal. Aliases, shebang/multicall scripts, PATH= overrides and & jobs are all checked. command X, exec X and eval are unwrapped, so the kernel sees X. A function with an allowed name can't run a denied body. runs_in_shell matches the dispatch at exec.rs:3317-3320 and :3407.

Questions (non-blocking)

  1. Should eval, source, exec and command be asked about under their own names? Today a "no dynamic code" policy can't be written. If leaving them out is intended, the doc should say so.
  2. Why is check_command async but command_finished sync? Is Box's policy engine async?

Appendix: non-blocking

  • Tests only assert Finished for a single builtin. Pipeline stage statuses (the handles.push((i, …)) mapping), functions and sh scripts aren't asserted, though they behave correctly when I probed them.
  • The status passed to command_finished can differ from what the shell finally returns, because callers adjust it afterwards (settle_host_writes at exec.rs:2916-2925, the output limit at :2888-2899).
  • runs_in_shell is now the third copy of the "Shell runs this itself" check (exec.rs:3016-3020, :3317-3320). Using it in all three places would stop a future addition from slipping past the check.
  • The refusal message goes through shell_proc.err_msg (exec.rs:3062), so it ignores the command's own 2> redirect.
  • Not a problem, for context: eval '…' > f and { …; } > f truncate f before the inner refusal, which is what real shells do. Lua os.remove/io.open are kernel file operations, not commands.

Comment thread src/exec.rs Resolved
Comment thread src/os.rs Resolved
Comment thread src/os.rs Resolved
… to both hooks

Address the review on strands-agents#204: unwrap `builtin NAME` in every stage before the
check, pass one `CommandRequest` to `check_command` and `command_finished`,
make `command_finished` async and fallible (status 125 on `Err`), and state in
the rustdoc which commands are not asked and which are not reported.
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent addressed all your comments. Please confirm

@strandly-the-agent strandly-the-agent left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Withdrawn. I approved this on my own review before the new public API had been reviewed. Its note about pairing a check with its finish by address was also wrong. My review below replaces this one.

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ferdingler I'm withdrawing my approval. The earlier findings are fixed, but the new public API needs two small changes and sign-off from a maintainer.

Earlier findings: the 🔴 builtin bypass is fixed. With the strip disabled, three of your new tests fail, and none of my 30+ probes got a command past the check. The 🟡 doc overclaim is fixed. My CommandRequest suggestion is done.

Public API changed, and there's no needs-api-review label. This delta adds pub struct CommandRequest (with program(), args(), cwd() and command_line()). It also changes both Kernel hook signatures, and makes command_finished async and fallible: an Err turns the stage's status into 125. I shouldn't be the only approval on that. I don't think it needs an API meeting, since it follows the existing check_url and CommandContext patterns, but a maintainer should decide on the 125 contract.

  • 🟡 command_line() turns echo a b and echo 'a b' into the same string. It's free to drop now and a breaking change to drop later (inline).
  • 🟡 A kernel can't pair a check with its finish. Shell moves the request after check_command, so even its address changes. My earlier note that comparing addresses works was wrong, sorry (inline).
  • Question: should a failed record change a command that already ran to 125? While the store is down, set -e; … stops at set itself, if echo hi; then … takes the else branch, and a && b never runs b. If Box wants "not recorded means failed", please say so in the doc.
Routing · verified · appendix

Passes run on the delta 9346d01..37a98ac (299 lines: a new public type, both trait signatures, and new failure behaviour, so the full pipeline):

  • Correctness / docs / tests (default tier): approve. Every rustdoc sentence matches the code, all five old finished(...) call sites are converted with the same statuses, and the new tests fail when the fix is reverted.
  • API bar-raiser (advanced tier): accept with conditions, no meeting. Raised the two 🟡 above and the 125 question.
  • Adversarial (advanced tier timed out at 900 s, so I re-ran it on the default tier, focused on the record-failure path): 12 scripts covering traps, !, while, subshells, &/wait, eval, nested functions, find -exec and xargs. No panics, hangs, lost stdout, missing finishes or double reports.

Verified at 37a98ac: cargo test --locked --workspace --all-targets passes 2076/2076 (command_check 13, shell_integration 1548). cargo fmt --check is clean. Stable clippy 1.99 reports nothing on changed lines; its 8 lints predate this PR. Probe output: strands-agents/shell/pr/204/followup-probes.txt, api-probe-output.txt.

Appendix: non-blocking

  • CommandRequest only derives Debug. Your own test copies all three fields by hand twice (tests/command_check.rs:35-39, :50-54). #[derive(Clone, Debug, PartialEq, Eq)] would be an additive change.
  • os.rs:1164: "For builtin NAME, Shell asks about NAME" only holds when NAME is a builtin. builtin cat is asked about as builtin, as your test asserts.
  • Only the single-builtin path tests a failed record. Removing report_finished from the pipeline loop (exec.rs:3555) or the function arms (:3262, :3275) would not fail any test.
  • In a pipeline, the "could not record" lines land in captured_stderr (:3555) before the stages' own stderr is appended (:3568).
  • Inside find -exec and xargs, the inner command's "could not record" line is dropped. report_finished (:3239) runs after clear_err_tx() (:3218). That's the stderr drop in find/xargs that predates this PR, and #227 and #213 already fix it.
  • x=$(false); echo $? printing 0 predates this PR, and #232 covers it.

Comment thread src/os.rs Resolved
Comment thread src/os.rs Resolved
@ferdingler

Copy link
Copy Markdown
Collaborator Author

Thanks for the second pass. Pushed f1b1a3b for the two inline ones. On the rest:

  • 125 on a failed record: Intended, and it matches what Box does today. An unrecorded command shouldn't look like a clean success to &&, if or set -e. The doc already says the status becomes 125.
  • builtin NAME wording: fixed, it now says this holds when NAME is a builtin.
  • Clone/PartialEq/Eq: Skipping for now. Nothing needs them, and they're additive later.
  • Extra test for 125 on pipeline and function paths: Skipping. The 125 behaviour is pinned on the single-command path, and I'd rather keep this PR tight.
  • Stderr ordering and the find/xargs record message: Agreed these predate this PR. They're covered by the PRs you linked.
  • Maintainer sign-off: Signing off on the new API as a maintainer: CommandRequest and its accessors, check_command, command_finished, and 125 on a failed record.

@ferdingler
ferdingler merged commit 3123f7f into strands-agents:main Nov 11, 2026
30 checks passed

@alaaszxc086-a11y alaaszxc086-a11y left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants