Skip to content

feat(shell): one persistent shell session per task so cwd and env survive - #3400

Closed
kovtcharov-amd wants to merge 5 commits into
mainfrom
kalin/shell-session-3380-clean
Closed

kovtcharov-amd wants to merge 5 commits into
mainfrom
kalin/shell-session-3380-clean

Conversation

@kovtcharov-amd

@kovtcharov-amd kovtcharov-amd commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

An agent that ran cd build and then a build got the wrong directory: every run_shell_command call started from the process working directory, so a cd in 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 a cd carries to the next separate call. get_shell_state reads that directory back instead of the agent guessing it, and reset_shell_session returns 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 export and source have 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 a pwd/environment dump back out. That round-trip is what produced the AWKPATH/AWKLIBPATH pollution, the Windows env case-folding bug, and the set_shell_variable tool whose value never interpolated. All of it is gone. shell_session.py is 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 or cd; main's step walk still does. The session is a state carrier: it supplies the starting directory and absorbs the result main already computes.

Two seams worth a reviewer's eye:

  • A cd into 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.
  • A cd moves the session only when it actually ran. The pre-flight walk resolves every cd on the line before anything executes, so checkpointing it directly would apply a cd that &&/|| skipped, or that a timeout cut the line before reaching. ls <missing> && cd build must leave the session where it was.

An explicit working_directory argument stays a one-shot override and never touches the session.

get_shell_state / reset_shell_session are added to the shell bundle in both profiles. The flagship's registered tool count moves 81 → 83, reconciled across gaia-agent.yaml, __init__.py, CAPABILITY_MATRIX.md, the capability-matrix gate and docs/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: a cd surviving to the next call, the next call actually running there, a one-shot working_directory leaving the session alone, reset, a path-policy-denied cd refused, and a short-circuited cd not moving the session.
  • The three short-circuit tests fail on the previous checkpoint logic and pass on this one — verified by reverting the one-line change and re-running.
  • 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.

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

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Request changes

This makes shell commands share one session per agent, so a cd or a variable set in one call is still in effect for the next — a real improvement, carefully built, and unusually well tested for a change this close to the security boundary. Two things need fixing before merge, both caught by running it.

Setting a variable and then using it in a command doesn't work on Linux or macOS. The new set_shell_variable tool reports success, and get_shell_state shows the variable, but a later echo $VAR prints the literal name instead of the value — because every command's arguments are re-quoted before the shell sees them (which is the right call for security, and the reason ~, * and $VAR no longer expand). Only programs that read the environment directly get the value. The PR's own new test asserts the opposite and fails on Linux, and a second test in the same file asserts the quoting that makes it fail — so the two contradict each other. Decide which behaviour you want and make the tests and the tool's description agree.

The session invents environment changes nobody made. On Linux, every single command comes back reporting AWKPATH and AWKLIBPATH as session changes, on a host where nothing set them — an artifact of how the environment is captured. They are then carried forward and re-exported to every later command, and shown to the model as if the agent had changed them. One-line fix.

Also worth a look before merge: when a cd lands outside the agent's allowed directories, the session asks the path policy in its "and prompt the user if not" mode. On an interactive CLI that pops a security prompt after the command already ran, and answering "always" permanently widens what the agent may read — including for a bare cd, which walks the session to the user's home directory. Asking without the prompt is almost certainly what was meant.

Real-world evidence

An 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: cd persisting across calls, relative arguments validated against the session's directory (cat ../inside.txt after a cd build), the whitelist and operator refusals unchanged, reset_shell_session restoring the start state, a one-shot working_directory leaving the session where it was, and a 3-second timeout leaving no find process behind. The granted-CLI path was confirmed to still receive argv: x|whoami, $HOME and ; rm -rf / all arrived as data. Per-command overhead was 2–4 ms.

🔍 Technical details

Evidence, verbatim from the run:

$ run_shell_command(command='cd build')   → session_cwd .../build
$ run_shell_command(command='cat notes.txt')
{ "stdout": "planted fact: violet-otter-92\n", "return_code": 0, "status": "success" }

$ run_shell_command(command='cd /etc')    # host exposing only _is_path_allowed
{ "status": "success", "session_cwd": "/tmp/gaia_evidence_q26di2p2",
  "warning": "Directory change to '/etc' was not applied: …" }

$ session.run_argv(['echo', 'x|whoami', '$HOME', '; rm -rf /'])
{ "return_code": 0, "stdout": "x|whoami $HOME ; rm -rf /\n" }

pgrep -x find BEFORE: []   →  timeout=3, timed_out: true  →  pgrep AFTER: []

Not exercised on this lane: the Windows cmd.exe batch path (_batch_quote, set-parsing, taskkill), the Agent UI rendering of the three tools, and the ShellSessionBusy/ShellSessionClosed tool responses. gaia chat --list-tools — the user-visible surface where the new tools appear — needs Lemonade and is pending the strix-halo lane. So the verdict on the Windows branch and the UI rests on static review alone.

I reproduced both findings independently against shell_session.py:

raw     : 'kept\n'          # session.run('echo $GAIA_X')
printenv: 'kept\n'
divergence after `echo hi`: {'AWKLIBPATH': '…/gawk', 'AWKPATH': '.:/usr/share/awk', 'GAIA_X': 'kept'}

🔴 set_shell_variable is unusable from a command on POSIX, and two tests disagree about it

_requote_for_posix (src/gaia/agents/tools/shell_tools.py:282) shlex.quotes every validated token, so echo $GAIA_TOOL_VAR reaches sh as echo '$GAIA_TOOL_VAR'. That is deliberate and correct — test_the_posix_shell_gets_argv_back_not_a_string_to_expand pins exactly this (("echo $HOME", "echo '$HOME'")). But test_a_variable_set_through_the_tool_reaches_later_commands (tests/unit/test_shell_tools_session.py:75) asserts the value comes back, which can only hold on the Windows branch where the original string goes to cmd.exe. On Linux it fails deterministically:

E   AssertionError: assert 'kept' in '$GAIA_TOOL_VAR\n'
1 failed, 17 passed

The variable is delivered to the child — printenv GAIA_X returns it, and so would git, make, or anything else reading its own environment. Only shell-level interpolation is suppressed. Two ways out:

  1. Keep the quoting (recommended). Make the test assert what actually holds — e.g. printenv GAIA_TOOL_VAR — and say so in set_shell_variable's docstring, since the model will otherwise reach for echo $VAR and conclude the tool is broken. Something like: "Later commands receive the variable in their environment. Shell-level $VAR expansion is off by design, so read it with printenv NAME rather than echo $NAME."
  2. Allow expansion for session-known names only. More surface, and it re-opens the question the quoting closes; I would not.

Either way the spec/shell-tools-mixin.mdx "Persistent Session" section should say expansion is off, next to where it already explains the re-quoting.

🟡 gawk's own variables become permanent session overrides (src/gaia/agents/tools/shell_session.py:64)

The POSIX state dump reads awk's ENVIRON, and gawk injects AWKPATH / AWKLIBPATH into it. _absorb_state sees two names absent from _baseline_env, records them as overrides, and _build_script then exports them on every subsequent command — so the session drifts a little further from the parent with each call, and get_shell_state reports changes the agent never made. Reproduced on a clean session with a single echo hi.

_VOLATILE_ENV_NAMES = frozenset(
    {
        "_",
        "PWD",
        "OLDPWD",
        "SHLVL",
        "PS1",
        "PS2",
        "RANDOM",
        "SECONDS",
        "LINENO",
        "PROMPT",
        "CD",
        "ERRORLEVEL",
        "CMDCMDLINE",
        "CMDEXTVERSION",
        # gawk puts these into its own ENVIRON, so the state dump reports them
        # as session changes on a host where nothing set them.
        "AWKPATH",
        "AWKLIBPATH",
        "__GAIA_RC",
    }
)

Worth a regression test alongside test_inherited_variables_are_not_reported_as_changes: assert session.environment() == {} after a plain echo, rather than the current < len(os.environ) / 4 bound, which passes with the pollution present.

🟡 The cwd guard prompts the user, and approval widens the path policy (src/gaia/agents/tools/shell_tools.py:353)

validator.is_path_allowed defaults to prompt_user=True (src/gaia/security.py:375), so _absorb_state calling the guard can reach _prompt_user_for_access — which prints a security warning and, on y/always, adds the directory to allowed_paths (persisting it for always). That fires from state absorption after the command has run, for a decision the user is being asked to make about bookkeeping.

The reachable case is a bare cd: no arguments means nothing for the per-argument path check to see, the shell moves to $HOME, and absorption then asks the user whether the agent may have their home directory. Non-interactive contexts auto-deny, so this only bites the CLI — but that is the interactive surface. A guard should decide, not negotiate:

        validator = getattr(self, "path_validator", None)
        if validator is not None:
            # prompt_user=False: this is bookkeeping after the command already
            # ran, not an access request the user asked to arbitrate.
            def guard(path: str) -> bool:
                return validator.is_path_allowed(path, prompt_user=False)

            return guard

🟢 Nits

  • ShellToolsMixin's "Tools provided" list is missing set_shell_variable (src/gaia/agents/tools/shell_tools.py:317); the mdx spec lists all three.
  • close_shell_session() is wired only into ChatAgent.__del__. Any other host composing the mixin leaves its gaia_shell_* temp directory behind — cheap to also hook wherever the mixin's own teardown lives.

Strengths

  • The security reasoning at the two seams is the best part of this PR, and it holds up under testing. Re-quoting the validated tokens so sh gets back exactly the argv it had before is the right instinct — a session needs a shell, and this pays for it without letting the shell re-read anything the checks read literally. Same for keeping the granted-CLI path on run_argv.
  • Not keeping a resident child is the correct call, and the docstring explains why (a timed-out command inside a shared shell is precisely the corruption at issue) rather than just what.
  • The tests run real subprocesses where a mock would have proved nothing, and _env_key's Windows case-folding comment names a bug that would have been genuinely hard to find later.
  • The # nosec entries are specific and justified, and the now-unreachable B602 suppression was removed with the shell=True call it covered.

@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

🟡 The prior review's AWKPATH/AWKLIBPATH finding is still open. The fix mechanism is in place (_VOLATILE_ENV_NAMES) but the two variables awk injects into its own process environment are not listed there. On a Linux host where those names are not pre-set in the system environment, every command will continue to report them as session changes, replay them into the next script, and show them to the model as if the agent changed them. The new test (test_inherited_variables_are_not_reported_as_changes) allows up to 25% of the parent's env as spurious divergence, so one or two false positives pass silently.

The set_shell_variable test contradiction (the other "Request changes" finding) is cleanly resolved — the contradicting assertion is gone, the docstring now says $NAME stays literal, and a new test confirms non-interpolation.

🔍 Technical details

shell_session.py:64 — _VOLATILE_ENV_NAMES is the right place for this. Add the two names gawk injects:

_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 tests/unit/test_shell_session.py:118 should be tightened from < len(os.environ) / 4 to == 0 (or <= 2 if other env vars legitimately change on certain platforms) so this class of regression is actually caught.

The prior review evidenced this with awk 'BEGIN { for (k in ENVIRON) … }' — gawk inserts AWKPATH and AWKLIBPATH into the child's environment via setenv(3) before running the script, so they appear in ENVIRON even though the shell never set them. Without the fix they persist on every subsequent call.

@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Skill audit

Skill Verdict Claimed tier Cleared tiers Findings Rules
hub/agents/gaia/npm ✅ ALLOW experimental experimental 1 high body.injection.credential_request

✅ 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 skill-audit-reports artifact from this run. Offending source text is withheld from CI everywhere — reproduce it locally with gaia skill audit <dir> --show-snippets.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

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 main deliberately removed.

ShellSession.run() writes each command to a temp script and sources it under /bin/sh. Since this branch diverged, main switched to running argv directly with no shell on POSIX (#3593), and that rewrite was explicitly staged to land separately. Replaying this branch's exec block on top reintroduces the shell — along with three silent behaviour drops: stderr redirections and inline env assignments get re-flattened into the command text after main lifted them out into structured fields, and per-step exit bookkeeping collapses into a single shell exit code.

The feature itself (persistent cwd/env across calls) is still wanted, and main already has most of what it needs. But the coherent path is to reduce ShellSession to a cwd+env state holder feeding main's argv pipeline — which deletes most of the script-generation code here and invalidates the tests pinning those internals. That's authoring a different PR, not resolving a conflict, so nothing was pushed and the attempted merge was aborted.

Flagging for a maintainer call on whether to rework or close in favour of a fresh branch.

🔍 Technical details
  • main moved +1318/−367 in src/gaia/agents/tools/shell_tools.py since this branch's merge base; the branch is +392/−138 against the older shape.
  • segments, cmd_parts, and cmd_base no longer exist in run_shell_command — they now live in _validate_shell_command and _run_step. The branch's exec block references all three.
  • _requote_for_posix(step.segments) drops 2>&1 / 2>/dev/null (lifted into step.stderr_modes by _take_stderr_redirections) and VAR=x cmd prefixes (lifted into step.envs by _take_env_assignments).
  • It handles a single pipeline, not a line: rebuilding a && b || c means re-emitting the exact metacharacters the validator exists to exclude, and loses unhandled_failure / ran / attach_check / pipefail / SIGPIPE tracking.
  • Suggested scope if reworked: keep _resolve_cd_target and the per-line step_cwds walk from main, persist that state across calls, and drop _build_script / _absorb_state / the awk ENVIRON readback / the cmd.exe batch path.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

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 &&/||/;, walks the parts itself, tracks which ones ran and what they returned, and feeds that into the check that decides whether a claimed test run really happened. This branch goes the other way and hands the whole line to a real shell that persists between calls — which is the point of a persistent session, since a real shell already does connectors and cd for free. Both are reasonable; they cannot both own the execution path.

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

git merge origin/main gives 13 hunks over 5 files. Four of the files are mechanical; src/gaia/agents/tools/shell_tools.py is not.

The integration point this branch depends on is gone. On main, _validate_shell_command returns steps — a list of connector-split steps, each carrying its own .segments — and the tool body iterates for step, step_cwd in zip(steps, step_cwds) calling _run_step. There is no single whole-command segments in that scope any more (shell_tools.py:1891, :1911). This branch's _requote_for_posix(segments) and lone_granted_segment = len(segments) == 1 and ... both read that variable, so they have nothing to bind to.

That matters beyond the name: _requote_for_posix joins with " | " only. Applied to a connector-split command it would turn a && b into a | b. And lone_granted_segment is the security seam — it's what keeps a skill-granted CLI on the argv path so an argument built from untrusted text can't become a second command. Re-deriving it from steps is a judgement call about the guarantee, not a rename.

Main also added around the same block: attach_check / check_from_command, unhandled_failure (so pytest -q; ls can't report a failing suite as passing), _COMMAND_NOT_FOUND handling mid-line, and waited_seconds. A session-based path has to decide what each of those means when a real shell is doing the chaining.

Git's own auto-merge is a good illustration of why this can't be hunk-picked: the non-conflicting region it produced references result.cwd and session.cwd from this branch alongside last_code and duration from main, in one dict.

The other four files, for whoever picks this up:

  • hub/agents/gaia/python/gaia-agent.yaml and gaia_agent/__init__.py — tools_count is 71 here and 80 on main; merge-base is 68, this branch adds 3 tools and main adds 12, so the merged value is 83, not either literal. reconcile_tools_count() fails the build on a wrong one.
  • docs/spec/shell-tools-mixin.mdx (2 hunks), tests/unit/test_skill_binary_grants.py (3 hunks) — routine.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

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 &&, || and ; itself, walks the working directory per step, scopes environment assignments per step, and feeds each step's return code into the verification-scope check. This branch replaces that entire execution tail with one call into a persistent shell session. So resolving the conflict means deciding who owns connectors and cd — GAIA's step engine, or the shell. That's an author decision, not something a merge commit should make quietly on your behalf.

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 cd result main already computes. What this PR exists for still works — cwd and env survive between tool calls — connectors and verification scope survive with it, and it deletes the /bin/sh question outright, because nothing is ever handed to an interpreter on POSIX. The cost is most of shell_session.py's script generation and state round-trip.

One claim about this PR is circulating and it is false, so nobody re-litigates it: this does not reintroduce /bin/sh that #3593 removed. #3593 removed no interpreter — it is a validation change, and its own description says the argv rewrite lands separately. /bin/sh has never appeared in shell_tools.py in its entire history. This branch does newly run a POSIX shell, but it re-quotes every validated token first and skill-granted binaries still run as argv, so on the security axis it holds up.

#3685 is stacked on this branch, so whichever way this goes, the decision lands on two PRs.

🔍 Technical details

Merge tested for real in a scratch worktree, rerere disabled: base main, head 179199b03, merge-base 38bc3669b — 208 commits behind / 6 ahead, 13 files, +1590/-170. Five files conflict; four are tractable (two are tools_count: 71 vs 80, and that one needs a real recount since this PR adds three session tools on top of main's 80).

The one that isn't tractable is the execution tail of run_shell_command — 96 lines on this side against 84 on main's. Main's side is the _Step loop with _connector_runs, per-step step_cwd, step.envs, stderr modes, _COMMAND_NOT_FOUND, partial output on TimeoutExpired, and check_from_command / attach_check. This side is session.run(exec_command). Everything above the conflict (steps, step_cwds, _path_traversal_refusal) auto-merges from main, which leaves main's steps computed and then ignored.

Main's connector engine landed in #4049 — after this branch was cut — and this branch has no _Step class and no connector support at all, which is why nothing here fails when connectors go missing.

The trap in a naive resolution toward this side: _requote_for_posix shlex.quotes every token and re-joins only on |, so main's &&, ; and 2>/dev/null would reach the shell as quoted literals — connectors silently become arguments. No test here would catch it, because there are no connector tests on a branch that predates connectors.

On the /bin/sh claim: #3593 is merge commit 10d62d19b; its shell_tools.py diff touches only validation helpers (_powershell_body_escape, _shell_syntax_spans, allowlist tables) — no shell=, Popen, or subprocess.run line. git log -S"/bin/sh" -- src/gaia/agents/tools/shell_tools.py returns zero commits. Main's POSIX-argv property comes from use_shell = os.name == "nt" and ..., which predates #3593 and was only ever moved (by #4049), never introduced by it.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

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. main gained a multi-step execution engine after this branch was cut, and this branch replaces that whole execution tail. Resolving that merge toward the branch would silently turn &&, ; and 2>/dev/null into quoted arguments — and no existing test would catch it. Worth a deliberate look rather than a routine conflict resolution.

🔍 Technical details

Failing test, on py3.10 / 3.11 / 3.12:

tests/unit/test_shell_session.py::TestEnvironmentPersists::test_inherited_variables_are_not_reported_as_changes
AssertionError: {'COLUMNS': '80', 'LINES': '24'}

_VOLATILE_ENV_NAMES in src/gaia/agents/tools/shell_session.py:65 already covers the same category — _, PWD, OLDPWD, SHLVL, RANDOM, SECONDS, LINENO, plus AWKPATH/AWKLIBPATH for gawk. bash sets COLUMNS/LINES itself when it sizes the terminal, so adding both to that frozenset fixes all three lanes.

Attribution check: tests/unit/test_shell_session.py does not exist on origin/main and is added by this branch (merge-base 38bc3669bc, head 179199b038), so the failure is branch-introduced rather than inherited — it is not one of the environmental red classes.

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.
@kovtcharov-amd
kovtcharov-amd force-pushed the kalin/shell-session-3380-clean branch from 179199b to df6a23e Compare September 23, 2026 09:58
…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.
@github-actions

Copy link
Copy Markdown
Contributor

🟡 One doc still says cd only moves within its own line — that's the behavior before this PR. The updated gaia.mdx correctly describes the new persistence, but docs/spec/shell-tools-mixin.mdx wasn't touched and now contradicts it. The two new tools (get_shell_state, reset_shell_session) are also unmentioned there.

The three bugs from the first review are all gone: set_shell_variable was removed entirely, the AWKPATH/environment pollution is gone (cwd-only tracking avoids the subprocess round-trip that produced it), and the cwd guard is now a plain bool predicate that never prompts the user. The redesign is a real improvement.

🔍 Technical details

docs/spec/shell-tools-mixin.mdx:46 still reads:

| `cd <dir> && a` | `cd` moves the rest of **its own line**, and nothing else |

docs/guides/gaia.mdx:112 now says the opposite:

A cd on a chain's last line carries to the next separate call…

Fix: update the table row in the spec to match gaia.mdx, and add a short "Persistent session" row (or paragraph) that names get_shell_state and reset_shell_session — the same facts gaia.mdx already carries.

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.
@itomek

itomek commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

Rebased onto main and fixed the two things still open, plus one the stale branch was hiding.

  • The spec doc now matches the behaviour. docs/spec/shell-tools-mixin.mdx still said a cd moves its own line and nothing else, and never mentioned the two new tools. It now has a "Persistent session" section covering both, and the composition table row is corrected.
  • A cd that never ran was still moving the session. ls <missing> && cd build left the next call in build, even though && skipped the cd. Fixed, with three regression tests.
  • The tool-count gates were never updated. They only stayed green because the branch was 45 commits behind main. Merging as-was would have turned main red.

The PR description was still describing the first design (set_shell_variable, a real /bin/sh, shlex.quote, a per-session lock) — none of which survives in the current code. Rewritten to describe what actually ships.

🔍 Technical details

Short-circuited cd. The checkpoint at the end of run_shell_command used walk_cwd — the pre-flight walk, which applies every cd on the line unconditionally before anything executes. A cd the connectors skipped, or that a timeout cut the line before reaching, was therefore still absorbed. Reproduced before the fix:

$ ls <missing> && cd <sub>
STEPS : [{'command': 'ls ".../nope"', 'return_code': 2}]   # only ls ran
BEFORE: /.../kalins-open-prs
AFTER : /.../sub                                            # session moved anyway

Now tracked as ran_cwd, advanced only inside the step.is_cd branch that the connector check actually let through. Tests: TestOnlyACdThatRanMovesTheSession — the && skip, the || reach (which should move it), and a cd followed by a failing command (which should stay moved). The first fails on the old logic and passes on the new; verified by reverting the one-line change.

Merge resolution. main added capture_skill (8 skill-library tools); this branch adds get_shell_state / reset_shell_session (61 in the chat full profile). Merged total is 83, confirmed by test_manifest_tools_count_matches_real_registry against the real registry. _EXPECTED_TOOLS_TOTAL in test_capability_matrix.py and the generated CAPABILITY_MATRIX.md were both still at 81 and are updated; gaia-agent.yaml, __init__.py, gaia.mdx and the npm CHANGELOG conflicts were the same count on four more surfaces.

close_shell_session() is defined but has no caller — left as-is, but worth either wiring to task teardown or dropping.

Verified: 633 pass / 3 skipped across test_shell_session*, test_shell_guardrails, test_chat_tool_bundles and the full hub/agents/gaia/python/tests/; util/lint.py --black --isort clean.

@itomek

itomek commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

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 — test_chat_system_prompt_owner.py::test_cloud_provider_receives_native_system_prompt. #3899 retired the OpenAI provider and deleted the module, but left the test importing it. Reproduced on a pristine origin/main worktree with nothing from this branch in it.

Once #4183 lands, this PR needs one more main merge to pick it up, and the lane should go green.

🔍 Technical details
$ git worktree add /tmp/mainchk origin/main
$ cd /tmp/mainchk && pytest tests/unit/test_chat_system_prompt_owner.py -q
FAILED test_cloud_provider_receives_native_system_prompt[openai] - ModuleNotFoundError: No module named 'gaia.llm.providers.openai_provider'
FAILED test_cloud_provider_receives_native_system_prompt[claude] - (same)
2 failed, 14 passed

git cat-file -e origin/main:src/gaia/llm/providers/openai_provider.py → does not exist in 'origin/main', deleted by 60656af2 (#3899). The import is at function scope and runs for both parameters, which is why the Claude case fails too.

All three of this PR's failing jobs carry exactly these two lines and no others (py3.10 107744105407, py3.12 107744105387, macOS 107744105868). The other 41 checks pass.

@itomek itomek 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.

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.

@itomek

itomek commented Sep 28, 2026

Copy link
Copy Markdown
Collaborator

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.

@itomek itomek self-assigned this Sep 28, 2026
@itomek

itomek commented Sep 28, 2026

Copy link
Copy Markdown
Collaborator

Landed on main as part of #4408 (merge commit 2927f1a1), which carried this change together with the other two PRs that rewrite the same refusal branch in the shell tool.

Every commit from this branch is an ancestor of what merged — git merge-base --is-ancestor confirms it — so nothing here was dropped or rewritten. Closing.

@itomek itomek closed this Sep 28, 2026
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 28, 2026
… 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]>
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.

feat(shell): one persistent shell per task so cwd and env survive

2 participants