Skip to content

feat(shell): run compound read-only commands under the same allowlist - #4037

Closed
kovtcharov wants to merge 5 commits into
amd:mainfrom
kovtcharov:claude/compound-shell-commands
Closed

kovtcharov wants to merge 5 commits into
amd:mainfrom
kovtcharov:claude/compound-shell-commands

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

The shell tool refused &&, || and ;, so looking something up and checking it cost three or four agent calls where one would do — and each extra call re-sends a ~12K-token prompt, which is where 53% of GAIA's spend goes. Two benchmark runs of 14 tasks hit 4 outright operator refusals, spent about 7 steps recovering from them, and used 100 steps for work Claude Code did in 82. Chained lines now run, under exactly the security model a single command already gets: every command on the line is validated before any of it runs, one refused command refuses the whole line, and one approval covers the line.

Stacked on #4019 — the first commit here is that PR's pipe fix, which this builds on. Merge it first, or review the second commit on its own.

Test plan

  • python -m pytest tests/unit/test_shell_compound_commands.py -q — 46 new tests against real subprocesses in tmp_path: each connector's semantics, a pipeline inside a chained line, cd, refusals, timeouts, and the confirm/refuse/grant tiers
  • python -m pytest tests/unit/test_shell_guardrails.py tests/unit/test_shell_pipelines.py tests/unit/test_skill_binary_grants.py tests/unit/test_shell_rewrite_redirect.py tests/unit/test_powershell_command_injection.py -q
  • python -m pytest tests/unit -q
  • On Windows, run something like cd src && dir from gaia chat and confirm it works — each pipeline is handed to cmd.exe separately, which is the platform path no CI machine here covers
  • Run gaia eval agent against the committed baseline before merging: the tool's model-facing docstring changed, and that is not covered by unit tests
🔍 Technical details

Parse. _split_connectors splits the raw line on &&, ||, ; outside double quotes — the same quote model _outside_double_quotes already uses, odd-count caveat included, so the splitter and the operator blocklist cannot disagree about where a segment ends. Single quotes deliberately do not protect an operator, because cmd.exe does not honour them: grep 'a||b' f splits here and dies on the unbalanced quote rather than reaching cmd.exe as two commands nothing validated. Each part is then operator-scanned, shlex-split and pipeline-split by the existing _split_pipeline, giving a _Step(text, segments, connector). _parse_line is shared by the refusal path and skill_grant_covers_call, so the tiers answer the same question about what a segment is.

Tiers. _shell_command_refusal runs _validate_command over every segment of every step, unchanged; a REFUSE anywhere returns before the executor starts, stamped executed: False. A CONFIRM-tier segment leaves the line un-refused so it reaches one prompt, which renders the whole command argument. skill_grant_covers_call now loops every segment of every step: gh issue list && gh issue view 1 is covered, gh issue list && rm -rf x and gh issue list | head are not.

Execution. Sequential and in-process: _connector_runs implements sh's rule, and a skipped step leaves the exit code standing so false && a || b runs b. Each step goes through the existing _run_pipeline/argv path, so no line reaches a shell on POSIX. On Windows each pipeline is handed to cmd.exe as its own string; the compound line never is. The whole line shares one timeout deadline, and a timeout kills the current pipeline and starts no later step.

cd. Allowed only as a bare cd <dir>: never a pipeline stage, never a flag, exactly one operand. Targets are resolved and validated in a pre-pass before anything runs, held to the same bar as working_directory, and each step's arguments are path-checked against its own resulting directory — so cd sub && cat ../../secret is still refused.

Still refused: >, >>, <, backticks, $(), a background &, inline VAR=value (via the allowlist), and — new — newlines, which cmd.exe reads as a command separator and nothing refused before.

Reporting. return_code is the last command that ran and the result gains steps: [{command, return_code}]. has_errors additionally covers a failure no || handled, so pytest -q; ls cannot report a failing suite as a passing check via the verification footer. A missing executable mid-line is reported as exit 127 rather than claiming nothing ran; when nothing did run, executed: False is unchanged.

Rate limiting: one line costs one slot, because it is one model step — that is the whole point of the change, and it is stated in the tool's docstring.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

This lets the shell tool run a && b, a || b, a; b and cd x && y on one line, validating every command on the line against the same read-only allowlist before any of it runs. The security model holds up well — I went looking for a way to smuggle an unvalidated command past the splitter and didn't find one, and the change quietly closes a real Windows hole along the way. One correctness bug blocks it.

cd is applied even when the line says it shouldn't run. The directory for each step is decided up front, before anything executes, so a cd sitting behind && or || still moves the commands after it even when that cd is skipped. Two things go wrong: a later command silently runs in the wrong directory and returns confident wrong output, and a line whose cd names a directory that doesn't exist is refused outright even when nothing would ever have run it. I reproduced both against this branch. The tightest fix is to allow cd only as the first command on a line — which is the only form the docs show anyway — so "decided up front" and "what actually runs" can't disagree.

The eval wasn't run. The tool's model-facing docstring changed, which is on the list of changes that require gaia eval agent against the committed baseline before merge. Every box in the test plan is still unchecked, including that one and the Windows cd src && dir check that no CI machine here covers.

Real-world evidence

No evidence-bundle.md — the automated evidence stage didn't run on this PR, and the description carries no captured output, only an unchecked test plan.

I exercised the mixin directly in this checkout instead (real subprocesses, temp dir). Connectors, pipes-inside-chains, quoted operators and cd src && pwd all behaved as described. The same run is what surfaced the cd bug:

$ cat missing.txt && cd sub || ls      →  stdout: 'inner.txt\n'      (a shell lists the parent: 'sub\ntop.txt')
$ cat missing.txt && cd nope ; ls      →  error: Directory not found: nope   (a shell prints the ls)

pytest isn't installed on this runner, so the PR's own 46 new tests were not executed here — treat the suite as unverified by me.

🔍 Technical details

🟡 cd is resolved unconditionally, ignoring the connector that gates it (src/gaia/agents/tools/shell_tools.py:1502)

The pre-pass walks every step and applies each cd to walk_cwd regardless of whether that step will run:

for step in steps:
    step_cwds.append(walk_cwd)
    if step.is_cd:
        walk_cwd, error = self._resolve_cd_target(step.segments[0][1], walk_cwd)
        if error:
            return error

At runtime _connector_runs may skip the cd, but step_cwds is already frozen. Reproduced on this branch with a bare ShellToolsMixin host and a real tmpdir:

  • cat missing.txt && cd sub || ls → ls ran in sub and returned inner.txt. sh runs it in the parent and returns sub top.txt. Nothing in the result says the directory moved; the model gets a plausible wrong answer.
  • cat missing.txt && cd nope ; ls → refused with Directory not found: nope, executed: False. sh never evaluates that cd and prints the ls.

Not a sandbox escape — _resolve_cd_target still runs the target through _path_allowed, and _path_traversal_refusal still checks each step's arguments against whatever cwd it was given. It's a wrong-answer bug in a tool whose output the model treats as ground truth.

Recommended fix — accept cd only as the first step. A leading cd is unconditional by construction, so the pre-pass becomes exactly right and no runtime cwd tracking is needed. It also matches every example in docs/spec/shell-tools-mixin.mdx and the tool docstring (cd <dir> && b). In _cd_shape_refusal, or at the top of the walk:

for index, step in enumerate(steps):
    step_cwds.append(walk_cwd)
    if step.is_cd:
        if index:
            return {
                **NOT_EXECUTED,
                "status": "error",
                "error": "cd must be the first command on the line.",
                "has_errors": True,
                "hint": "Write 'cd <dir> && <command>', or pass working_directory.",
            }
        walk_cwd, error = self._resolve_cd_target(step.segments[0][1], walk_cwd)
        if error:
            return error

The alternative — resolving cd lazily inside the execution loop and path-checking each step's arguments against the cwd it actually gets — preserves a && cd b && c but moves the path-traversal refusal after the first command has already run, which trades this bug for a weaker "nothing ran" guarantee. The first-step restriction is the cheaper one.

Either way, tests/unit/test_shell_compound_commands.py should gain the two lines above as cases — the existing cd tests all put cd first, which is exactly why this slipped through.

🟡 Eval not run for a changed tool docstring; no captured evidence on the PR

run_shell_command's docstring is what the model reads to decide how to use the tool, and it gained five lines of new syntax. CLAUDE.md lists tool docstrings under the changes that require gaia eval agent against the committed baseline before merge, and the PR's own test plan names it — unchecked, along with the Windows cd src && dir item. Worth landing the eval diff (and the Windows run, which no CI machine here covers) in the description before merge.

🟢 Two docs still say chaining is refused

Both now contradict the shipped behaviour:

  • docs/plans/skill-format.mdx:393 — "command chaining and redirection (&&, ;, >, backticks, $()) are rejected before the policy runs"
  • tests/agent_ui_test_plan.md:1418 — "Pipes (|) are allowed but dangerous chaining is not"
The existing shell guardrails still apply on top: redirection and command
substitution (`>`, backticks, `$()`) are rejected before the policy runs, and
each segment of every chained pipeline is validated separately.

🟢 A skipped step is invisible in steps

steps only lists commands that ran, so a && b with a failing a reports one entry and b simply isn't there. That's defensible, but docs/spec/shell-tools-mixin.mdx:52 reads as if every command appears. One clause ("each command that ran") would settle it.

Strengths

  • The newline fix is a real Windows vulnerability closed in passing. Before this, ls\nrm -rf / shlex-split to a single segment whose base command was the allowlisted ls, and the raw string — newline intact — went to cmd.exe with shell=True, which reads it as two commands. Adding [\r\n] to DANGEROUS_SHELL_OPERATORS kills that, and test_a_newline_is_not_a_connector pins it.
  • The splitter and the operator blocklist share one quote model. _split_connectors deriving honour_quotes from the same even-count rule _outside_double_quotes uses is what keeps the two from scanning different text. I probed the disagreement cases — odd quote counts, echo "a && b; c" && echo done, grep 'a||b' f — and they all either parse identically or fail closed on the unbalanced quote. Declining to honour single quotes because cmd.exe doesn't is the right call and the reasoning is written down where the next reader will find it.
  • _parse_line shared between the refusal path and _call_is_pre_authorized is the right structural move: the two tiers now cannot disagree about what a segment is, which is precisely the class of bug that makes an allowlist leak.
  • Pipeline exit status is rightmost-failure with a SIGPIPE exemption, so pytest | tail can't launder a failing suite and | head doesn't invent one. That distinction is easy to get wrong and the tests cover both directions.
  • Tests run real subprocesses in tmp_path rather than mocking subprocess — which is the only reason the pipeline-vs-argv regression in test_skill_binary_grants.py was catchable at all.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Heads-up for whoever merges last: this PR touches shell_tools.py alongside five others, and the combination needs real resolution rather than a clean-looking auto-merge. I've resolved it on an integration branch, so the rules below are tested rather than guessed.

Interacts with: #4019 (pipes — this is stacked on it), #4020, #4023, #3808, #3791, #3765.

🔍 Technical details

The one that actually matters — #3808's tiers. Once a command outside ALLOWED_COMMANDS is TIER_CONFIRM rather than refused, a chained line has to carry the strongest tier any of its segments earned. Returning the first block instead puts rm notes.txt on the prompt and then runs git -c core.pager=… status behind it on a yes. _shell_command_refusal therefore scans every segment, returns immediately on a TIER_REFUSE, and only falls back to the first TIER_CONFIRM — which it returns with its steps, since the executor runs them once the prompt is answered.

Per-PR rules used:

Three r4 tests changed, because the behaviour they pinned is the behaviour this PR changes: cat a && rm b is no longer "a shape the runner cannot execute" (it is now a confirmable line), and cat "a.txt" ; id no longer refuses on the operator — ; is a connector and id is validated on its own. Replacements pin the same intent: cat a & rm b for the unexecutable shape, and cat a && git -c core.pager=evil.sh status for "a refused command hidden behind a confirmable one stays refused, even with full access".

Kalin Ovtcharov and others added 5 commits September 21, 2026 04:14
On macOS and Linux every piped shell command returned wrong output with
status "success". The validator drops the `|` tokens and the executor then
ran the segments as one argv, so `cat notes.txt | sort` ran as
`cat notes.txt sort` and `grep a x.txt | wc -l` returned "x.txt" instead of
a count. Windows was unaffected because it goes through cmd.exe.

Validated segments are now chained as separate processes, still without a
shell. The exit code is the rightmost failing stage, so `pytest | tail`
cannot turn a failing suite into a verified pass; an upstream stage killed
by SIGPIPE (`| head`) is not a failure. Every stage's stderr is kept, and a
timeout kills the whole pipeline.

test_a_pipeline_is_not_run_as_argv only pinned the shell flag, so it passed
while the bug was live; it now checks that the stages are chained.
Agents reach for `python -m pytest` first, and the shell refused it with
"only read-only commands are allowed" - no hint that pytest exists behind
the coding skill. In a 14-task benchmark run on main that dead end was hit
5 times; the agent gave up on the tests and twice reported them as passing.

`python -m pytest` is now judged as `pytest`: same grant, same flag and path
policy, no extra prompt. Without the grant it gets pytest's "load that skill
first" refusal. The typed spelling is what runs, because `-m` puts the
working directory on the import path, so a checkout that was never
installed imports without a pytest.ini workaround. Only the exact
`python|python3|py -m pytest` shape maps; `-c`, a script, another module or
an interpreter flag stays refused.

An inline `PYTHONPATH=. pytest` was refused as an unknown command named
"pythonpath=."; it now says inline environment assignments are unsupported.
A shell command over the rate limit (3 per 10 s, 10 per minute) was refused
with "wait N seconds", so the model spent a whole step sending the same
command again after the same wait. In a benchmark run the refused command was
the recovery itself - `python -m pytest` right after bare `pytest` failed to
import the project - in 2 of 14 tasks.

The tool now waits for the window and then runs the command, reporting
waited_seconds. The rate stays exactly as capped; a wait longer than
max_rate_limit_wait_seconds (60 s) is still refused.
The shell tool refused `&&`, `||` and `;` outright, so work that is one call
elsewhere — `cd src && ls`, `pytest -q | tail -5; grep -rn parse_` — cost GAIA
three or four. Two benchmark runs of 14 tasks hit 4 operator refusals and about
7 recovery steps, and used 100 steps where Claude Code used 82; every extra step
re-sends a ~12K-token prompt, and fresh input is 53% of the cost.

A line is now split into its pipelines, and every segment of every pipeline goes
through the same tiered validation as before, before any of it runs: one refused
command refuses the whole line, one confirm-tier command raises a single prompt
showing the whole line, and a skill grant covers the line only when it covers
every segment. The steps then run sequentially in-process with sh's semantics —
`&&` on success, `||` on failure, `;` regardless — through the existing pipeline
runner, so no line reaches a shell on POSIX and Windows gets one pipeline per
cmd.exe call instead of the line. `cd <dir>` is allowed as a bare one-argument
command, path-validated like `working_directory`, and moves only the rest of its
own line.

Redirection, command substitution, a background `&` and inline `VAR=value` are
still refused; newlines now are too, which they were not before, and cmd.exe
reads one as a command separator. The line costs the rate limiter one command
because it is one model step, and a failure no `||` handled still sets
`has_errors`, so `pytest -q; ls` cannot report a failing suite as a passing
check.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #4023 (shell-rate-limit-paces). Merge after #4023.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The cd-behind-a-connector bug flagged in the first review is still present. Two cases still fail:

  1. cat missing.txt && cd nope ; ls — refused with "Directory not found: nope" even though the && would skip cd nope entirely and ls should run.
  2. cat missing.txt && cd sub || ls — ls runs inside sub instead of the original directory, because the skipped cd sub already shifted step_cwds for everything after it.

The new tests only put cd first (cd sub && ls), which is always unconditional — they can't catch this class of failure. The fix the first review recommended — refuse cd anywhere except the first step — would also eliminate both cases: a first-step cd has no connector, so the pre-pass and the runtime are always in sync.

🔍 Technical details

src/gaia/agents/tools/shell_tools.py:1538-1547 — the pre-pass walks every step and applies each cd to walk_cwd before execution, ignoring the connector that will gate it:

for step in steps:
    step_cwds.append(walk_cwd)
    if step.is_cd:
        walk_cwd, error = self._resolve_cd_target(...)
        if error:
            return error   # ← fires even when && would have skipped the cd

Suggested fix — check position in _parse_line (or at the top of the pre-pass):

for index, step in enumerate(steps):
    step_cwds.append(walk_cwd)
    if step.is_cd:
        if index != 0:
            return [], {
                **NOT_EXECUTED,
                "status": "error",
                "error": "cd must be the first command on the line.",
                "has_errors": True,
                "hint": "Write 'cd <dir> && <command>', or pass working_directory.",
            }
        walk_cwd, error = self._resolve_cd_target(...)
        if error:
            return error

Two tests to add to tests/unit/test_shell_compound_commands.py:

def test_cd_behind_failing_and_is_not_resolved(notes):
    # 'cd nope' is gated by &&; the failing cat means it never runs
    (notes / "sub").mkdir()
    result = _run("cat missing.txt && cd nope ; ls", notes)
    assert result["status"] == "success", result
    assert "notes.txt" in result["stdout"]

def test_cd_behind_failing_and_does_not_shift_later_steps(notes):
    (notes / "sub").mkdir()
    (notes / "sub" / "only-here.txt").write_text("x\n")
    result = _run("cat missing.txt && cd sub || ls", notes, host=_Confined(notes))
    assert result["status"] == "success", result
    assert "notes.txt" in result["stdout"]   # ran in root, not sub
    assert "only-here.txt" not in result["stdout"]

The tool docstring also changed (line 1466–1470), which per CLAUDE.md requires a gaia eval agent run against the committed baseline. That was flagged before and is still open.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Everything functional in this PR is already on main, so there is nothing left to merge.

It landed as part of #4049, which squash-merged the tip of the stack this branch sits in and carried every commit below it along. GitHub does not auto-close the lower PRs in a stack when the tip is squashed, which is why this stayed open — and why it has been showing a conflict against a main that already contains its work.

Merging it now would actively hurt: the only thing it still adds is an outdated paragraph of the run_shell_command docstring that contradicts current behaviour — it tells the model VAR=value is refused, when main now allows a scoped environment assignment.

Closing as superseded. No work is lost; reopen if you disagree.

🔍 Technical details

Verified rather than assumed — merged origin/main into this branch taking main's side, then diffed the result against main:

git checkout -B probe <branch> && git merge origin/main --no-edit -X theirs
git diff --stat origin/main HEAD

Residual: a stale docstring block in src/gaia/agents/tools/shell_tools.py only. The allowlist behaviour it describes is superseded by the version main carries.

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

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants