Skip to content

fix(shell): allow the two stderr redirections that write nothing - #4041

Closed
kovtcharov wants to merge 6 commits into
amd:mainfrom
kovtcharov:claude/allow-safe-stderr-redirection
Closed

kovtcharov wants to merge 6 commits into
amd:mainfrom
kovtcharov:claude/allow-safe-stderr-redirection

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

The shell tool refused any >, which meant it also refused the two redirections that write nothing. Across seven benchmark runs of 14 tasks on four models, 19 of the 21 operator refusals were one of them — and they are how every model asks for a test run (pytest -q 2>&1 | tail -20, ls tests/ 2>/dev/null). Each refusal cost the call plus a median of one more to recover, ~5% of all tool calls; the refusal even told the model to use write_file, which is no help for a stderr redirect. In one measured run it caused a false claim: the agent's attempt to test a patch in a scratch copy was blocked, and it reported a later test run against unpatched code as if it had covered the patch.

Refused command form Count Creates or truncates a file?
2>/dev/null 11 No
2>&1 8 No
>> append 1 Yes
> write 1 Yes

Both now work; every other redirection stays refused, 2> to any other path included.

Stacked on #4037 (claude/compound-shell-commands) — it rewrites the same parsing path, so this builds on it rather than conflicting with it. Review #4037 first; this PR's own diff is the last commit.

Test plan

  • pytest tests/unit/test_shell_stderr_redirection.py — new file: both forms run, 2>&1 feeds the merged stream to the next pipeline stage, a discarded stderr still reports a non-zero exit, and 16 other redirection spellings are refused with no file created
  • pytest tests/unit/test_shell_*.py tests/unit/test_skill_binary_grants.py tests/unit/test_powershell_command_injection.py — 503 passed
  • python tests/verify_shell_security.py — chaining, pipes and path traversal unchanged
  • Full pytest tests/unit — only the 24 failures already failing on main for this machine
  • gaia eval agent --category tool_selection — the tool docstring changed
  • Windows: pytest tests/unit/test_shell_stderr_redirection.py is POSIX-only; the cmd.exe path needs a manual check (ls nosuchdir 2>/dev/null, git status 2>&1 | findstr branch)
🔍 Technical details

Why the security surface does not widen. Both forms are recognised as exact standalone tokens (2>&1, 2>/dev/null), never as a general 2>PATH, and never inside double quotes. They are lifted out of the line before the operator scan and become a flag on the pipeline segment that wrote them, so what runs is the same allowlist-validated argv as before. The flags are destinations for a stream the tool already captures — subprocess.STDOUT and subprocess.DEVNULL — so neither opens a path, creates or truncates a file, or runs anything. 2> to any other path, 1>, >, >>, <, &>, >&, backticks, $(), & and newlines are refused exactly as before, and a token glued to anything (2>&1x, 2>&1>out.txt) matches nothing and is refused too.

A merged segment writes stderr down its own stdout pipe, which is what puts it in front of the next stage's grep. Return codes are untouched by either flag, so the pipefail rule still fails a line whose stderr was discarded. On Windows a step is already a cmd.exe string, so the redirection travels in it (spelled 2>nul) rather than as a capture flag — cmd.exe owns that pipeline, so only it can route a middle segment's stderr.

The refusal message and hint now name the two allowed forms instead of pointing a stderr redirect at write_file, and docs/spec/shell-tools-mixin.mdx lists them in the composition table.

@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 chained lines (&&, ||, ;), real pipelines, cd, and the two stderr redirections that write nothing. The design is careful — every command on a line is allowlist-checked before any of it runs, and the argv/pipeline path never touches a shell on POSIX — and the test suite is unusually thorough. Two parsing edge cases and one project gate are what hold it up.

A pipe inside single quotes confuses which command a 2>/dev/null belongs to. The tool counts pipes with a text scan that treats single quotes as ordinary characters, but it counts commands with a parser that treats them as quoting. When the two disagree, a redirection lands on the wrong command — or on no command at all, so a perfectly ordinary command gets refused with a message about a redirection "not attached to a command". I reproduced both outcomes. Worth fixing before merge because the refusal is exactly the kind of dead end this PR exists to remove.

A cd that never runs still moves the commands after it. The working directory for each step is worked out up front, walking past every cd on the line regardless of whether the connectors will actually reach it. So on a line where an early failure skips the cd, the later commands still run in the new directory — not what a shell does, and not what the agent asked for. The same up-front walk also refuses the whole line when a cd target is missing, even when that cd would have been skipped. Either behaviour may be a deliberate simplification, but it isn't stated anywhere and isn't tested; please pin it down one way or the other.

Two gates from the test plan are still open. The tool's description string changed, which the project rules put squarely in the "run the agent eval first" bucket — gaia eval agent --category tool_selection is unchecked. The Windows path is also the one place where the redirection is re-spelled and handed to a shell, and it has no automated coverage at all (the new tests skip on Windows). Both are called out honestly in the description; they just need to happen before this lands.

Note this PR is stacked, so the diff under review carries three commits, not one. The review covers all three.

Real-world evidence

N/A — no evidence bundle was produced for this run, and this change has no CLI/API/MCP/Agent-UI surface of its own; it changes a tool the agent calls. The PR's own evidence is the pytest suite (503 passed), which I could not re-run here (pytest is not installed in this checkout), so those results are taken as reported. The two parser findings above were verified by executing the new parsing helpers directly, not from reading alone. The verdict rests on static review plus that direct check — the agent-level behaviour (does the model now successfully use 2>&1 instead of burning a turn on a refusal?) is exactly what the pending tool_selection eval would show, and is unproven here.

🔍 Technical details

🟡 Important

1. Stderr redirection is attributed to the wrong pipeline segment when a single-quoted argument contains a spaced pipe (src/gaia/agents/tools/shell_tools.py:437)

_take_stderr_redirections locates segment boundaries with _BARE_PIPE over the raw text, masking only double-quoted spans (_double_quoted). _split_pipeline, which actually defines the segments, works on shlex.split output — and shlex honours single quotes. Reproduced against the PR head:

>>> _take_stderr_redirections("grep 'a | b' f 2>/dev/null")
("grep 'a | b' f ", {1: '2>/dev/null'})          # 1 segment exists, mode indexed at 1
>>> _take_stderr_redirections("grep 'a | b' f 2>/dev/null | wc -l")
("grep 'a | b' f  | wc -l", {1: '2>/dev/null'})  # lands on `wc`, not `grep`

The first reaches _parse_line's any(index >= len(segments)) guard (shell_tools.py:656) and is refused with "A stderr redirection here is not attached to a command." The second silently discards wc's stderr instead of grep's. Return codes are unaffected either way, so there's no laundering of a failure and no security impact — but it is a wrong refusal and a silent misroute.

The fix belongs in the pipe scan only; leave _split_connectors's deliberate "single quotes don't protect an operator" rule alone, and leave _STDERR_REDIRECTION alone (a '2>&1' glued to a quote already fails its lookbehind). Mask single-quoted spans when locating pipes, guarded on an even quote count the same way _double_quoted is:

    quoted = _double_quoted(text)
    shielded = _single_quoted(text) if text.count("'") % 2 == 0 else [False] * len(text)
    pipes = [
        m.start()
        for m in _BARE_PIPE.finditer(text)
        if not quoted[m.start()] and not shielded[m.start()]
    ]

(with _single_quoted mirroring _double_quoted on '). An odd single-quote count fails shlex.split downstream anyway, so the guard costs nothing. Worth a regression test alongside test_the_redirection_applies_to_its_own_segment_only.

2. The cd walk is unconditional, so a skipped cd still relocates later steps (src/gaia/agents/tools/shell_tools.py:1649)

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)

This runs before execution and ignores connectors, while the execution loop below gates each step on _connector_runs. So ls nosuchfile && cd sub; pwd runs pwd in sub/ even though the cd was skipped — sh runs it in the original directory. The same walk also makes ls && cd nope refuse the entire line up front ("Directory not found", executed: False), where a shell would have run ls first.

Both are defensible as a conservative simplification — resolving cd up front is what lets _path_traversal_refusal check each step's arguments against the right directory, and the missing-directory refusal is arguably better than a half-run line. Neither is documented or tested, though: docs/spec/shell-tools-mixin.mdx:46 says only "cd moves the rest of its own line", which reads as shell semantics. Either gate the walk on the connectors, or state the divergence in the spec table and the tool docstring and add a test pinning it (test_shell_compound_commands.py has test_cd_moves_the_commands_after_it but nothing for a skipped cd).

3. Required eval gate not run for a tool-docstring change

run_shell_command's description changed substantially (shell_tools.py:1573), and tests/unit/test_shell_stderr_redirection.py:172 asserts the model is told about the two forms. Per CLAUDE.md → "Run agent evals when changing LLM-affecting code paths", tool docstrings and the JSON tool schema are on the must-run list; gaia eval agent --category tool_selection is unchecked in the test plan. Compare against the baseline for the machine's model before merge (tests/fixtures/eval_baselines/<model>/). Related: the Windows manual check is also unchecked, and it is the only path where the redirection is re-spelled (_as_cmd_redirections → 2>nul, shell_tools.py:450) and handed to a shell — the new tests are skipif win32, so nothing covers it.

🟢 Minor

4. A pipeline that times out loses its partial stdout (shell_tools.py:741) — _run_pipeline re-raises TimeoutExpired with output=exc.output, but Popen.communicate generally raises without populating output; subprocess.run gets partial output only because it re-communicates after killing. So the single-command path returns partial stdout on timeout and the pipeline path returns "". stderr is preserved via _read_all(errs), so only stdout is affected.

5. Chained lines weaken the rate limiter's per-command accounting (shell_tools.py:1738) — one line now costs one slot however many commands it chains, and nothing caps the step count. The shared line deadline bounds the damage and every command is allowlist-validated read-only, so this is an observation rather than a finding; a len(steps) cap would make the intent explicit if unbounded chaining wasn't the goal.

6. import shutil inside _run_step (shell_tools.py:828) — carried over verbatim from the old inline block; now that it lives in a module-level function there's no reason not to hoist it with the other imports.

Strengths

  • The security argument is made in the code, not just the PR body. Lifting 2>&1/2>/dev/null out before the operator scan and turning them into subprocess.STDOUT/DEVNULL flags means no path is ever opened by name — the allowlist-validated argv is byte-identical to before. The 16-case REFUSED parametrize, including the sorted(os.listdir(workdir)) == before assertion that no refused command created a file, is the right way to prove it.
  • _run_pipeline's pipefail semantics are the non-obvious correct choice. Returning the rightmost failing stage means pytest | tail can't report a failing suite as a passing check, and the SIGPIPE exemption for upstream stages keeps | head from being read as a failure. That's the difference between a pipeline feature and a false-confidence generator.
  • Refusing a chained line whole, before any of it runs (_shell_command_refusal), with executed: False on every refusal — the model can't learn to smuggle a refused command in behind a permitted one, and the skill-grant tier reuses the same _parse_line so the two tiers can't drift on what a segment is.
  • Docs were updated alongside, including the composition table and the Windows/POSIX split in docs/spec/shell-tools-mixin.mdx — and tests/verify_shell_security.py was rewritten rather than left asserting the old "chaining is refused" behaviour.

Kalin Ovtcharov and others added 6 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.
Across seven benchmark runs of 14 tasks on four models, 19 of the 21 shell
operator refusals were `2>/dev/null` or `2>&1` — neither of which creates a
file. They are how every model asks for a test run (`pytest -q 2>&1 | tail -20`,
`ls tests/ 2>/dev/null`), each refusal cost the call plus a median of one more
to recover (43 wasted tool calls, ~5% of all of them), and the refusal's own
hint said to use `write_file`, which is not advice for a stderr redirect. One
measured case became a false claim: the agent could not test a patch in a
scratch copy, and reported a later run against unpatched code as if it had
covered the patch.

Both forms are now lifted out of the line before the operator scan and recorded
as a flag on the segment that wrote them — exact standalone tokens only, and
never inside double quotes. `2>&1` points that segment's stderr at its own
stdout pipe, so a later stage's `grep` sees it; `2>/dev/null` points it at the
null device. Neither names a file, and on POSIX neither reaches a shell: they
are destinations for a stream this process already captures. On Windows the
step is a cmd.exe string, so the redirection travels in it, spelled `2>nul`.

Everything else stays refused: `2>` to any other path, `1>`, `>`, `>>`, `<`,
`&>`, `>&`, backticks, `$()`, `&`, and newlines. Return codes are untouched, so
discarding stderr cannot turn a failing command into a passing one.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #4037 (compound-shell-commands). Merge after #4037.

@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