Repository navigation
feat(shell): one persistent shell session per task so cwd and env survive - #3400
kovtcharov-amd wants to merge 5 commits into
Conversation
Request changesThis makes shell commands share one session per agent, so a Setting a variable and then using it in a command doesn't work on Linux or macOS. The new The session invents environment changes nobody made. On Linux, every single command comes back reporting Also worth a look before merge: when a Real-world evidenceAn evidence run exercised the tools the way the agent's tool-call layer does — real hosts, real subprocesses — and both findings above come from it, not from reading the diff. What it showed working: 🔍 Technical detailsEvidence, verbatim from the run: Not exercised on this lane: the Windows I reproduced both findings independently against 🔴
|
2c70b95 to
ae2e9b3
Compare
|
🟡 The prior review's The 🔍 Technical details
_VOLATILE_ENV_NAMES = frozenset(
{
"_",
"PWD",
"OLDPWD",
"SHLVL",
"PS1",
"PS2",
"RANDOM",
"SECONDS",
"LINENO",
"PROMPT",
"CD",
"ERRORLEVEL",
"CMDCMDLINE",
"CMDEXTVERSION",
"__GAIA_RC",
+ "AWKPATH", # gawk sets these in its own process env before BEGIN runs
+ "AWKLIBPATH",
}
)The test at The prior review evidenced this with |
Skill audit
✅ All audited skills cleared the tier they claim. Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the |
|
This one can't be un-conflicted by hand any more — merging it as written would put a shell back into the command exec path that
The feature itself (persistent cwd/env across calls) is still wanted, and Flagging for a maintainer call on whether to rework or close in favour of a fresh branch. 🔍 Technical details
|
|
This one can't be un-conflicted mechanically — main and this branch now hold two different answers to the same question, and someone has to pick one. Main grew a shell emulator: it splits a command line on So this isn't a rebase away. It needs a decision on which model survives, and then this branch's session re-fitted onto it. I've left the branch untouched rather than push a resolution that guesses. Worth knowing: eight open PRs touch this file and the other seven are all currently conflict-free, so this is the one being outrun. The longer it waits the bigger the re-fit gets. 🔍 Technical details
The integration point this branch depends on is gone. On main, That matters beyond the name: Main also added around the same block: Git's own auto-merge is a good illustration of why this can't be hunk-picked: the non-conflicting region it produced references The other four files, for whoever picks this up:
|
|
This can't be merged as-is, and the blocker isn't the conflict markers — it's that main and this branch now solve the same problem two different ways. After this branch was cut, main grew a multi-step execution engine: it handles A direction that keeps both: keep main's step engine, and use the session purely as a state carrier. It supplies the starting directory and the accumulated environment to the step runner, and absorbs the One claim about this PR is circulating and it is false, so nobody re-litigates it: this does not reintroduce #3685 is stacked on this branch, so whichever way this goes, the decision lands on two PRs. 🔍 Technical detailsMerge tested for real in a scratch worktree, The one that isn't tractable is the execution tail of Main's connector engine landed in #4049 — after this branch was cut — and this branch has no The trap in a naive resolution toward this side: On the |
|
Across a re-verified sweep of all 104 open PRs, this is one of only two carrying a CI failure that is actually real — and it's a one-line fix. A brand-new shell session reports bash's own terminal-size variables as if the user had changed them, so the test asserting that a clean session diverged nothing fails on every Python version. The session already suppresses bash's other self-managed variables; these two were simply missed and belong in the same place. The other red lanes here carry no information — they're the Anthropic weekly spend cap (#4080), which resets on its own. The riskier part of this PR isn't the test. 🔍 Technical detailsFailing test, on py3.10 / 3.11 / 3.12:
Attribution check: |
Every run_shell_command call started from the process cwd, so a `cd build` in one call was invisible to the next -- an agent working through a build/test loop had to re-derive its location every turn. A ShellSession now tracks that one thing across separate calls: the working directory a chain's cd's leave it in. Reconciles #3380's original persistent-session design (a real shell running a generated script, its cwd/environment parsed back out of a state-dump file) against main's since-added multi-step connector engine (&&/||/; parsed and executed per-step as argv, never through a shell). Those two are incompatible: the old design needs a real shell to capture state FROM, and handing a command string to one is exactly what the connector engine's argv-only execution exists to avoid (it is also what lets a skill-granted CLI run on untrusted text without a shell ever seeing it). So this keeps the connector engine untouched byte-for-byte -- validation, per-step execution, the granted-CLI carve-out, none of it changes -- and reduces ShellSession to a plain cwd holder that checkpoints the walked terminal directory after a clean run. Scope, deliberately narrower than the original design: cwd only. No generic `export`/venv-activation persistence -- that needs a real shell to observe the change from, which the security model here doesn't allow back in. A future PR can revisit explicit variable persistence (`set_shell_variable`) once the two independently-maintained env-var blocklists in this codebase (main's inline-assignment denylist vs. the one the original design shipped) are unified rather than duplicated a third time. Adds get_shell_state (read the session's cwd) and reset_shell_session (return to the starting directory). A cwd from a timed-out chain is never checkpointed: the pre-flight walk resolves every `cd` on the line before anything runs, so its terminal value can already reflect a `cd` that comes after the step that never finished.
179199b to
df6a23e
Compare
…istry The new tools from the shell-session reconciliation were never added to a bundle, so they were unreachable via load_tools and CI's coverage guard (test_core_and_bundles_cover_doc_registry_exactly / test_core_and_bundles_cover_the_flagship_registry_exactly) correctly failed on both the chat and flagship agents. Registry size grows 80 -> 82; updates the manifest's tools_count, the registry's own declared count, the doc guide's tool table and counts, and adds the missing CHANGELOG entry for the underlying feature.
|
🟡 One doc still says The three bugs from the first review are all gone: 🔍 Technical details
Fix: update the table row in the spec to match |
Resolves the tool-count conflict main and this branch each moved: main added capture_skill (8 skill-library tools), this branch adds get_shell_state and reset_shell_session (61 in the chat full profile). Merged total is 83, which the real-registry gate confirms. The hard-coded _EXPECTED_TOOLS_TOTAL and the generated CAPABILITY_MATRIX.md were both still at 81 — this branch never updated them, so the merge would have gone red on main.
The checkpoint used the pre-flight walk, which resolves every cd on the line before anything runs. A cd that `&&`/`||` skipped therefore still moved the session: `ls <missing> && cd build` left the next call in `build` even though the `cd` never ran. Track the cwd the executed steps reached instead. Also documents the persistent session in the shell-tools spec, which still said a cd moves its own line and nothing else.
|
Rebased onto
The PR description was still describing the first design ( 🔍 Technical detailsShort-circuited Now tracked as Merge resolution.
Verified: 633 pass / 3 skipped across |
|
The three red Unit Tests lanes are not this PR. They are main's, and #4183 fixes them. Every lane fails on the same two tests, and only those two — Once #4183 lands, this PR needs one more 🔍 Technical details
All three of this PR's failing jobs carry exactly these two lines and no others (py3.10 |
itomek
left a comment
There was a problem hiding this comment.
Approving. The feature is real and the redesign is the right one — this is a 100-line pure-Python directory holder, not the script-generating session the early reviews were written against, so none of the /bin/sh, AWKPATH or Windows-env-folding objections apply to what actually ships.
What was fixed on top of the branch, with evidence in the two comments above: a cd that &&/|| skipped was still moving the session (real, reproduced, now covered by three tests), the tool-count gates were stale and would have turned main red on merge, the shell-tools spec contradicted the new behaviour, and the description still described the abandoned design. The three red Unit Tests lanes were main's, fixed separately in #4183 and now green here.
Not merging — that call is the author's. Leaving it open.
🔍 Remaining nit
close_shell_session() in shell_tools.py has no caller anywhere in the tree. Its docstring says "tear the session down at task end", but nothing calls it at task end, so a long-lived agent host keeps the session forever. Either wire it to teardown or drop the method — not a merge blocker either way.
CI at time of writing: 43 pass, 0 fail, 8 skipped. The two outstanding lanes are the self-hosted eval jobs (gaia_* judged categories, rag_quality + context_retention + tool_selection) — one queued on runner availability for over an hour, one running. Neither has reported a failure.
|
Folded into #4408, which carries this change together with the other two PRs that rewrite the same refusal branch in the shell tool. Landing any two of the three without the third leaves the guard describing behaviour that no longer exists, so they are being reviewed and tested as one story. Nothing here is dropped. The replay is in #4408's merge commits, and anywhere the two PRs disagreed with each other or with main, the resolution is named in the commit message and called out in the PR description. This PR will be closed once #4408 merges. |
|
Landed on Every commit from this branch is an ancestor of what merged — |
… refuse, one name for full access (amd#4408) Three open PRs rewrite the same refusal branch in the agent's shell tool, and landing any two without the third leaves guard messages describing behaviour that no longer exists. This folds all three into one branch so the shell story can be reviewed and tested as one thing. **What a user gets.** The agent stops refusing work you are sitting right there to approve: `git commit`, `npm test`, `rm notes.txt` are now shown to you and run once you say yes, instead of coming back as a flat "not allowed". A `cd` survives to the next command, so `cd build && cmake ..` followed by `make` works the way it reads. And the coding skill loads on a machine where `pytest` lives only in a virtualenv, which is most machines. Replaces amd#3791, amd#3400 and amd#3808. ### The one decision a reviewer should confirm amd#3400 and amd#3808 forked 143 and 184 commits back, and main moved under both. Where the two disagreed about behaviour, **main's newer design won** and amd#3808's older expectations were updated: - **`git push` stays refused outright** rather than becoming confirmable — amd#3374 made push/reset/rebase refusals that the `git` grant itself will not run. - **Full access keeps the developer command set** rather than lifting the allowlist entirely, so `rm` and `touch` stay out. amd#3808's own later commit ("keep unattended runs narrow; leave shell lifting to amd#3394") is what settled this. If either call is wrong, it is a small edit here rather than a re-merge. <details> <summary>🔍 Technical details</summary> **Merge shape.** `amd#3791` (the only mergeable member) anchors; `amd#3400` and `amd#3808` were merged onto it in that order, each as a `--no-ff` merge whose message records its own resolutions. **One name for full access.** Main carried `console.bypass_permissions` and amd#3808 added `console.full_access` for the same session-wide grant — the naive merge shipped both, which would have been a live bug (`full_access_active()` reading one while `PermissionState` wrote the other). Collapsed onto `full_access`, keeping main's semantics and amd#3808's name: | before | after | |---|---| | `console.bypass_permissions` | `console.full_access` | | `ShellToolsMixin.bypass_gates_active` | `full_access_active` | | `client.PermissionBypasser` (Go) | `client.FullAccessSetter` | | `SetBypassPermissions` (Go) | `SetFullAccess` | | `PermissionState.set_bypass` | `set_full_access` | | stdio control verb `bypass` | `full_access` | The HTTP route keeps its original `/v1/{agent}/sessions/{id}/bypass` spelling — renaming it would break every already-published sidecar. `--bypass-permissions` and the `bypass` control verb stay accepted as retired spellings. **Superseded, deliberately not carried over from amd#3808:** `_resolve_git_subcommand` and `SAFE_GIT_COMMANDS` (main moved `git` into `BINARY_POLICIES` with a read-only ungranted floor), its git-subcommand branch, and its SPEC claim that `/tool_decision` and the session toggle are stdio-only (contract 2.14 gave HTTP both). **`shell_session` is a new bundle, not two more members of `shell`.** Folding `get_shell_state` / `reset_shell_session` into `shell` put it at 7 members, over `MAX_BUNDLE_MEMBERS` — a cap that exists so one pull-in cannot exhaust the dynamic-tool slots. Registered tool count 86 → 88, with `gaia-agent.yaml`, `gaia_agent/__init__.py`, `CAPABILITY_MATRIX.md` and the guide updated together. **Two fixes that fell out of the merge rather than out of any of the three PRs:** - Under full access a shell keyword (`for`, `while`) was reported as "not in the developer command set" instead of being named as control flow. `_validate_bypass_command` now names it, because no mode can run it. - `wait_for_condition` refused a confirmable predicate in front of the prompt — the same dead end the confirm tier exists to remove. **One stale test corrected:** `test_a_pipe_is_refused_for_its_binary_not_for_the_pipe` asserted the exact grant-id refusal for `pytest`, which amd#3791 replaces with a "not installed" refusal wherever `pytest` is not on `PATH`. It passed in CI only because CI has `pytest` on `PATH` — exactly the hidden-state masking CLAUDE.md warns about. It now holds in both machine states. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Ovtcharov <[email protected]> Co-authored-by: f <f@f> Co-authored-by: Kalin Ovtcharov <[email protected]>
An agent that ran
cd buildand then a build got the wrong directory: everyrun_shell_commandcall started from the process working directory, so acdin one call was invisible to the next. No system prompt could fix that — the state simply was not there to observe. Commands now share one session per agent, so acdcarries to the next separate call.get_shell_statereads that directory back instead of the agent guessing it, andreset_shell_sessionreturns it to where the task started.Scope is deliberately narrow: the working directory only. Nothing is handed to a real shell — each segment still runs as argv — so
exportandsourcehave no interpreter to persist state from, and this design does not reopen that question.Closes #3380.
🔍 Technical details
This is a redesign of the original branch, not the version the early reviews describe. The first iteration ported the C++ toolbelt's
ShellSession(#2810): it generated a per-command shell script, ran it, and parsed apwd/environment dump back out. That round-trip is what produced theAWKPATH/AWKLIBPATHpollution, the Windows env case-folding bug, and theset_shell_variabletool whose value never interpolated. All of it is gone.shell_session.pyis now 100 lines of pure Python holding a directory — no subprocess, no script generation, no/bin/sh, nothing to orphan.That also settles the conflict with
main's multi-step execution engine. The session does not own connectors orcd;main's step walk still does. The session is a state carrier: it supplies the starting directory and absorbs the resultmainalready computes.Two seams worth a reviewer's eye:
cdinto a directory the path policy refuses is not absorbed (_session_cwd_guard→_path_allowed). Without it, persistence would be a way to reach a forbidden directory and then read files there by bare name, which the per-argument check never sees.cdmoves the session only when it actually ran. The pre-flight walk resolves everycdon the line before anything executes, so checkpointing it directly would apply acdthat&&/||skipped, or that a timeout cut the line before reaching.ls <missing> && cd buildmust leave the session where it was.An explicit
working_directoryargument stays a one-shot override and never touches the session.get_shell_state/reset_shell_sessionare added to theshellbundle in both profiles. The flagship's registered tool count moves 81 → 83, reconciled acrossgaia-agent.yaml,__init__.py,CAPABILITY_MATRIX.md, the capability-matrix gate anddocs/guides/gaia.mdx.Test plan
python -m pytest tests/unit/test_shell_session.py tests/unit/test_shell_session_persistence.py -q— 14 pass. Real host, real subprocesses,tmp_path: acdsurviving to the next call, the next call actually running there, a one-shotworking_directoryleaving the session alone, reset, a path-policy-deniedcdrefused, and a short-circuitedcdnot moving the session.python -m pytest tests/unit/test_shell_guardrails.py tests/unit/test_chat_tool_bundles.py hub/agents/gaia/python/tests/ -q— 633 pass, 3 skipped. The guardrails are untouched; the bundle drift gate and the flagship's tool-count gates carry the new tools.python util/lint.py --black --isort— pass.