Skip to content

feat(agent): delegate a bounded subtask to a fresh child agent - #4384

Closed
kovtcharov wants to merge 16 commits into
amd:mainfrom
kovtcharov:feat/delegate-subtask
Closed

kovtcharov wants to merge 16 commits into
amd:mainfrom
kovtcharov:feat/delegate-subtask

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

On a real repository, two thirds of the agent's tool calls before its first edit are exploration, and every one of those results is re-sent to the model on every later step. This adds delegate_task: the agent hands a bounded subtask (a structured brief: goal, scope, done-when, return format) to a fresh child of the same agent, with the same model, tools and system prompt, and gets back only a short result plus evidence — files changed with line counts, commands run, the last test command and its summary, steps, tokens — while the child's whole context is discarded. The child's full transcript is archived in the session store and can be paged with read_tool_output. Child tokens are added to the parent's totals, so any saving reported is net. Off by default; GAIA_DELEGATE=1 turns it on, adds a short system-prompt paragraph on when to delegate, and a child cannot delegate further.

Stacked: merge after #4376 (shell offered in code repositories, which adds the always-on tool hook this uses) and #4379 (chunk index, which pages the archived transcript). The branch contains both.
It now also carries #4397's commits (context eviction) and the session findings ledger, so the merge order is #4376 → #4379 → #4397 → #4384.

Session findings ledger. Workers no longer start blind: every worker gets a digest of everything read, searched, run and changed in the session so far, plus a session_findings tool to fetch any of it exactly, instead of re-reading the same files the parent or an earlier worker already did.

Measured, honestly. On TheRock (DeepSeek V4.1 Flash, the heaviest task, three runs per arm, same judge and meter) delegation on came out inside the run-to-run spread of delegation off: mean 47 vs 51 steps, 3.36M vs 3.65M tokens, $0.126 vs $0.112, quality 4.25 both. The model delegated in only two of six enabled runs, and DeepSeek's cached-input price makes re-sent context a quarter of its bill, so there is little for delegation to save on that model. On the Jan long-horizon feature task it delegated twice and completed the feature (20/20 hidden tests, 0 regressions), at higher cost than the run without it. This PR is therefore an opt-in capability with a verified mechanism, not a cost claim. The economic case is on models where re-sent context dominates cost (GLM, Kimi); that has not been measured.

Test plan

  • pytest tests/unit/agents plus the flagship wiring tests — 1579 passed, 50 skipped on main; 23 delegate tests: fresh child conversation, byte-identical system prompt apart from the enabled-only fragment, no delegate tool in the child, step budget enforced and reported, evidence from a real temp git repo with numstat, child errors surface as an error result, parent conversation grows only by the small result (≤ 8,000 chars; a long answer comes back chunk-indexed with its own archive), child tokens accumulate into the parent, tool offered only when enabled
  • black, isort, flake8, pylint clean on changed files
  • Live: TheRock tr-7998-cb on DeepSeek V4.1 Flash, 3 runs on / 3 off, judged; Jan lh-7836 on / off, judged (numbers above)

Kalin Ovtcharov and others added 7 commits September 25, 2026 15:57
Every tool result is re-sent on every later step, and on a real 144K-line
repository accumulated results were 83% of the conversation. An over-budget
result now reaches the model as the parts that fit plus an index of the rest,
split where the document splits: functions and methods, headings, JSON
records, a search's files, test sections, diff hunks, paragraphs. Each index
entry is an exact offset/length that read_tool_output returns verbatim, so
nothing is lost and no new tool is needed. check_result and the other result
fields stay in view.

A remote model reached through Lemonade gets its own budget (8,000/6,000
chars) sized by re-send cost; 46% of the benchmark's result bytes sat above
8,000. Local NPU/GPU budgets are unchanged. Replaying 12 benchmark
transcripts offline, tool-result characters re-sent fall 29.7% (23.9% if
every condensed result is read back once).

The message backstop now caps at the threshold the gate passes, not the
smaller target, so results between the two are no longer cut unarchived; a
read_tool_output page is never condensed again.
…n view

Index entries could be longer than the 8,000-char page read_tool_output
allowed, so the model was told to make a call that failed: a 1 MB Python file
had every entry over the limit, and a 50,000-char stdout line was one. A read
now takes any length, returns at most one page, and reports `remaining` with
`next_offset` to continue, so every entry reads back exactly.

When one line too long to split is most of a result, the result keeps its
head and tail in view with the middle indexed, instead of showing only the
first line. Search matches with no file group under "(no file)" instead of
crashing, and a text `context` is one line, not one per character.

On NPU, a non-string tool result between 20,000 and 30,000 chars now reaches
the model whole, where the message backstop used to cut it to 20,000 without
archiving it; that path wants an NPU eval before merge.
On a live GLM run the model ignored the index and paged through whole archived
outputs 8,000 chars at a time, re-sending every file on top of its condensed
copy, because the reader advertised offset/limit with 8,000 as the page size.
Index entries are now numbered, read_tool_output(artifact, entry=n) returns
exactly that part, and every condensed result carries a `fetch` line saying
so. The docstring leads with the entry, lets limit default to the entry's
length, and says paging through a whole output is almost never needed.
offset/limit still work; an entry number outside the index is an error that
names the valid range.
The 8,000-char cloud threshold made files of 20-30K chars, which the model
needs whole to edit, arrive indexed; it then read them back one entry per
round trip, so steps rose and tokens did not fall (GLM, 4 tasks: 8.39M vs
8.29M; DeepSeek's worst task: 77 vs 72 steps, 20 entry reads). A remote model
reached through Lemonade again gets truncation_budget(None), as before. The
index, numbered entry reads, the fetch field, paging and the message-backstop
change stay: the index now applies only to results over the device threshold,
where it keeps every omitted byte reachable.
…sitory

Coding tasks in a repository ran without a shell, because the flagship's tool
loader admitted run_shell_command only when the request's wording was close to
the tool's description. "Skip gfx90a tests on PRs unless labeled" is not, so
every grep and sed went through run_python, one command per call.

Shell availability now follows the working context: when the session's project
root (the one the project map already resolves) is a code repository,
run_shell_command joins CORE for the life of the loader. It is fixed at
construction, so the offered prefix is stable from the first turn. Outside a
repository selection is unchanged, and the shell's approval gate is untouched.
An explicit project root pointing at a non-repository directory still rendered
"run_shell_command accepts: ..." in the project map, because the map asked the
tool registry whether the agent owns the shell rather than the per-turn filter
whether it was offered. That is the guaranteed failed call has_shell_tool
exists to prevent.

Also makes the negative shell test deterministic. It asserted "no repository"
by chdir-ing into tmp_path and trusting the upward walk to find nothing before
$HOME — on a runner whose TMPDIR sits under a checkout the walk finds a
repository and the assertion flips. The no-project case now stubs the root; the
non-repository case covers both ways a root is supplied.

The npm CHANGELOG promised the behaviour without saying which root it follows.
A sidecar's working directory is the daemon's, not the user's, so the entry now
names GAIA_PROJECT_ROOT the way SKILL.md section 11 already does.
On a real repository two-thirds of the flagship's tool calls before its first
edit are exploration, and every one of those results is re-sent on every later
step. delegate_task hands such a subtask to a child agent whose whole context
is discarded when it finishes; the parent's conversation grows only by a small
result plus evidence, and the full transcript stays readable through
read_tool_output.

The child is a fresh instance of the same agent class with the same config
(model, backend, working directory, tools, permissions, system prompt), a
fresh conversation, its own step budget, a silent console, and no delegate
tool of its own (depth 1). A child exception or provider failure comes back as
an error result, never retried; a child that runs out of steps returns what it
has with hit_step_limit set. The child's tokens are added to the parent's turn
totals as a delegated stats entry and tracked separately in delegated_tokens,
so any saving is measured with the child's cost included.

Off by default on the flagship: GaiaAgentConfig.delegate_enabled or
GAIA_DELEGATE=1 turns it on, and when on it is always offered regardless of
per-turn tool selection. GAIA_DELEGATE_MAX_STEPS sizes the child's budget
(default 40).
@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 26, 2026
Kalin Ovtcharov added 3 commits September 25, 2026 18:48
…n is on

With delegate_task offered on every turn, a live run still never called it:
the model explored a repository with 40 shell commands itself. The tool's
docstring alone does not change behaviour, so the mixin now contributes a
short system-prompt fragment through the same get_*_system_prompt discovery
every other mixin uses: delegate the investigation before editing an
unexplored repository, delegate any subtask whose output is a short answer,
write a complete brief because the worker has no memory of the conversation,
and do the edits and final verification yourself.

The fragment renders only while delegation is enabled, so the prompt is
byte-identical with it off, and the child (depth 1, delegation disabled)
never carries it.
…r excerpt

Three live runs delegated once each with a good brief, but the parent got
nothing usable back and re-explored the repository itself, so the arm came
out worse than baseline. The child's 6-7K answer was elided to ~200 chars to
fit a 3,800-char cap, and the excerpt's artifact pointed at the 137K child
transcript, so the parent paged the transcript twice, gave up, and started
over.

The answer is the deliverable. The returned dict may now be one
read_tool_output page (8,000 chars) and the answer is kept whole up to
6,500 chars. A longer one is archived under its own handle and returned as a
chunk index of that archive (shown parts plus numbered entries), so artifact
always resolves to the answer; the transcript stays in its own field, labelled
as the worker's full log for drilling only. commands_run drops the shell
tool's "cd <workdir> &&" prefix and is capped at 12 so it cannot crowd out
the answer.
…nt can trust

A live run delegated the investigation, received a 7K answer, and then made
33 exploration calls anyway before editing: for an edit task the parent has
to read the files it edits regardless, so delegating only the understanding
saves nothing. The split that can save is the opposite one: the worker reads,
edits and runs the tests for one bounded component, and the parent plans,
reviews each worker's evidence, and runs the final verification.

The prompt fragment and the tool docstring now say exactly that, and the
evidence carries what trusting a worker needs: files_changed lists each file
with added/removed line counts from git diff --numstat (names only outside a
repository; an untracked file counts every line as added), and tests reports
how many checks ran plus the last one's command, pass/fail and summary lines,
capped at 600 characters. The 8,000-character result budget is unchanged.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

First-pass review, no push — this is a draft with a live benchmark and a stacked base, so I left the branch alone.

The design holds up: a child of the same class with a fresh conversation, no delegate tool of its own, a depth guard that beats the env var, and the child's tokens folded into the parent so a reported saving is net. The 19 unit tests exercise the things that actually matter — byte-identical system prompt, no delegate tool on the child, step budget enforced, evidence taken from a real temp git repo, the parent's conversation growing only by the small result. All 19 pass locally.

Three things to settle before this leaves draft.

The worker's tool description is about five times the size every other tool holds to, and CI can't see it. Main just landed a 400-character budget on tool descriptions, because the whole schema set is re-sent on every model call for the life of the session. delegate_task's docstring is roughly 1,940 characters — around 485 tokens paid on every step of every turn. The budget check can't catch it: it inspects the flagship's default tool set, and delegation is off by default, so the tool simply isn't there to measure. Anyone who turns delegation on pays that cost silently. Most of it is guidance that belongs in the delegation system prompt (which only loads when delegation is on and is charged once, not per tool schema) rather than in the schema.

The worker's answer is capped at 6,500 characters no matter how much room the parent actually has. That is the right number for a local model, but on a cloud model the parent's own budget is over 120,000 characters — so the deliverable gets condensed into an index the parent has to page back, for no reason. The rest of this stack is built on per-model budgets; this one number is fixed. Worth deriving it from the parent's budget instead.

The eval gate is open, and it clearly applies here. This adds a tool, edits KNOWN_TOOLS, and adds a prompt fragment to the flagship — three of the categories CLAUDE.md names as requiring gaia eval agent before merge. The TheRock delegation-on-vs-off run in your test plan measures the saving, which is a different question from whether the flagship still behaves correctly with the extra tool and prompt in front of it. Both are needed.

Also worth knowing: main has moved and this branch now conflicts in two files. Both look mechanical rather than a design collision — a changelog entry and a KNOWN_TOOLS insertion, which is exactly the shared registry file where a bad auto-merge is easy to miss.

🔍 Technical details

🟡 1. delegate_task description vs. main's budget (src/gaia/agents/tools/delegate_tools.py:157)

@tool stores f.__doc__ whole as the schema description (tools.py:205), Args block included. Measured:

$ python -c "import ast; ..."   # ast.get_docstring(node, clean=False) == __doc__
raw len 1940

against MAX_TOOL_DESCRIPTION_CHARS = 400 (src/gaia/agents/base/tools.py:35, added on main). For scale, run_shell_command is 598 and needed a named entry in TOOL_DESCRIPTION_ALLOWANCES to get there.

Why CI stays green: util/check_tool_descriptions.py walks flagship_tool_schemas(), which builds the skeleton from a default GaiaAgentConfig — delegate_enabled = False, GAIA_DELEGATE unset — so _resolve_delegate_enabled() is false, register_delegate_tools() never runs, and the tool is absent from the schema set. The check passes by not looking.

The per-arg descriptions are fine (done_when ~75 chars, return_format ~90, both under the 160 cap). The overage is all in the prose body. The "two kinds of subtask" paragraph and the "NO memory of this conversation" paragraph restate DELEGATE_SYSTEM_PROMPT, which is already loaded whenever the tool exists — that is the natural home for them, and it is charged once per turn rather than once per schema render.

🟡 2. ANSWER_WHOLE_CHARS / RESULT_BUDGET_CHARS are constants, not budgets (delegate_tools.py:38-42)

RESULT_BUDGET_CHARS = 8000
ANSWER_WHOLE_CHARS = 6500

_bounded condenses whenever the answer exceeds 6,500. Agent._truncation_budget() returns (30000, 20000) on NPU, (60000, 40000) on GPU, and (183105, 122070) on the Claude path — and #4379 (this stack's base) exists precisely so a result is measured against the model in front of it. Suggest target = self._truncation_budget()[1] with 8,000 as the floor, so the local behaviour is unchanged and a cloud parent keeps the answer whole.

Note this interacts with #1: condense_result is what _bounded falls through to, and the parent's own _handle_large_tool_result will not re-condense a result already under its threshold — so a cloud parent today gets an indexed answer it had ample room to receive whole.

🟡 3. Eval gate — required, unsatisfied

Per CLAUDE.md "Changes that REQUIRE an eval run before merge", this PR hits three:

  • tool registration (registry.py KNOWN_TOOLS, register_delegate_tools)
  • a tool docstring (the JSON tool schema sent to Lemonade)
  • a mixin prompt fragment (DELEGATE_SYSTEM_PROMPT via _get_mixin_prompts)

GAIA_DELEGATE defaults off, which limits the blast radius but does not remove it: _workspace_core_tools() adds delegate_task to the always-on core set whenever delegation resolves on, so a delegating session's turn schema changes shape. Run with delegation on and off; the off run should be a no-change confirmation.

🟢 Merge state

git merge origin/main conflicts in two files:

file nature
hub/agents/gaia/npm/CHANGELOG.md competing entries — mechanical
src/gaia/agents/registry.py KNOWN_TOOLS insertion — mechanical, but this is the shared registry file, so check for a silently duplicated block after resolving, not just for conflict markers

Nine other files auto-merged, including src/gaia/agents/base/agent.py and gaia_agent/agent.py. I aborted rather than resolving — the stack's base (#4376, #4379) has to land first, and #4379's head moved this session (a summary-line fix, a Windows path fix, and the read_tool_output docstring trimmed for the same budget check discussed above).

Strengths

  • _resolve_delegate_enabled makes depth final before consulting the env var, so GAIA_DELEGATE=1 in the environment cannot give a child a delegate tool — the recursion guard is not defeatable by configuration.
  • _enforce_delegate_toggle correctly treats @tool's process-global _TOOL_REGISTRY as the hazard it is, and pops the inherited tool out of the instance snapshot rather than trusting registration order.
  • Evidence is taken from a before/after snapshot of the working tree, with git status --porcelain where there is a repo and an mtime scan where there isn't — so a file the worker claims it changed and one it did change are different facts, and the parent is shown the second.
  • _mtime_snapshot raises past _MTIME_SCAN_CAP instead of silently returning a partial scan, which would have produced quietly wrong files_changed.
  • _child_tokens reuses the agent's own token summers rather than re-deriving them, so a reported saving is measured the same way the parent's stats are.

Verified locally

  • pytest tests/unit/agents/test_delegate_tools.py — 19 passed
  • hub/agents/gaia/python/tests/test_delegate_wiring.py needs gaia_agent importable; not installed in this worktree, so it errors at import here. Same pattern as test_github_skill_visible.py, so not a PR defect — CI installs the package.

Kalin Ovtcharov and others added 5 commits September 26, 2026 01:29
…btask

Offered the choice, the model never delegates: every measured run opened
with the same four shell commands and spent a third to a half of its tokens
exploring before its first edit, whatever the prompt said. Recursive
composition has to be a mode the harness enforces, not a tool the model may
pick.

GAIA_DELEGATE=orchestrate (config delegate_mode="orchestrate"; 1/true/on
still mean "tool") offers the parent exactly delegate_task and
read_tool_output on every turn: no tool loader, so no load_tools escape
hatch, and any other tool call returns an error without running. The
ORCHESTRATION prompt fragment replaces the DELEGATION one and lays out the
shape: one investigate subtask, one implement subtask per component, one
verify subtask. Children keep the full ordinary tool set and cannot
delegate, as before.

delegate_task takes an optional kind (investigate | implement | verify,
default implement), recorded in the result, the archived transcript and the
delegated stats entry so a run can be broken down by subtask kind. A parent
starts at most delegate_max_children workers (default 12,
GAIA_DELEGATE_MAX_CHILDREN); the next call returns an error telling it to
finish with the evidence it has. Malformed GAIA_DELEGATE and delegate_mode
values now fail at construction instead of quietly meaning "off".
…n record

A judge reading an orchestrated run could not see what the workers did: the
child transcripts lived only in the in-memory artifact store, gone when the
run ended, and the parent's log held nothing but the delegate result dicts.
The parent then wrote "re-ran just now: 61 passed" for a test run a worker
had made, and was scored as untruthful.

After each delegation the parent's turn log now gets a
type="delegated_transcript" system entry carrying the kind, the brief, the
archive handle, the step count and the child's full conversation, so a
transcript written from outcome["conversation"] shows every command a worker
ran and its output. Like the stats entries it is a log record only: the
model's messages are a separate list, and a test pins that the entry never
reaches them. The orchestrate prompt and the tool docstring now say the
worker's run is the worker's — name which one ran what and quote its
evidence, never "I ran".
On a 144K-line repository the context the agent re-sends each step reaches
130-195K tokens, 83% of it old tool results the model has already acted on.
Whether dropping them saves money depends on the provider's cached-versus-
uncached input price: every eviction changes the prompt prefix, so the next
call re-reads everything after the eviction point uncached once. Simulated
on real per-step counts, Kimi K2.7 (cached $0.19/M vs $0.95/M) saves 27%,
GLM-5.3 Flash 11%, and DeepSeek V4.1 Flash (0.006 vs 0.30) loses.

This is not the context compaction the roadmap rules out ("memory + RAG
handles long conversations"): nothing is summarised or dropped. An evicted
result is archived whole in the agent's ArtifactStore and its message in the
list sent to the model becomes a one-line stub naming the read_tool_output
call that fetches it; a result that already arrived as a chunk index keeps
its handle and index. The turn's conversation log is never touched. It is
off by default.

context_eviction is off | on | auto (GAIA_CONTEXT_EVICTION wins). auto is
on only for a cloud model whose cached/uncached input price ratio, from the
table in gaia.llm.cache_pricing, is at least 0.1; a local or unknown model
is off, said once at info level, never guessed. Eviction fires at the head
of a step only when the previous step's measured prompt_tokens exceed
context_eviction_threshold_tokens (60000, GAIA_EVICT_THRESHOLD) and the
results older than context_eviction_keep_steps (8, GAIA_EVICT_KEEP) add up
to context_eviction_min_batch_tokens (30000, GAIA_EVICT_MIN_BATCH); then all
of them go in one batch and stay evicted, so the prefix is deterministic
afterwards. read_tool_output pages and delegate_task results are never
evicted; user and assistant messages are never changed. Each batch adds
evicted_results and evicted_tokens_est to that step's stats record and logs
one info line. Malformed env values or arguments fail at construction.
Kimi K3 lists at $3.00 input, $0.30 cached, $15 output on Fireworks (2026-09-26), a
0.10 ratio, so auto eviction turns on for it.
… workers

In orchestrate mode each worker starts from zero: on the measured runs the
four to six investigation workers per task each spent about ten steps
re-reading the same files, tripling the cost of the exploration.

Whenever delegation is on, the parent and every child now share one
SessionLedger (gaia.agents.base.session_ledger) and one artifact store. The
ledger records, deterministically and with no model in the loop, what every
tool result of the session established: files read (path, size, and for text
of 2K+ chars the chunk index's outline with line ranges, the full text archived
under the ledger's own index), searches with per-file hit counts (the search
tool and grep/rg commands), checks with their runner summary, files changed,
and each worker's report. Entries name the step and who found them, and dedup
on (kind, path or pattern). Eviction never touches it.

It reaches the model two ways. Every child brief opens with the digest under a
fixed header, after the system prompt and before the brief, so children spawned
from one ledger state share a byte-identical prefix for provider caching; the
digest carries no handles or timestamps, so identical findings render to
identical bytes. And a session_findings(query) tool on the parent and every
worker (part of the orchestrator's set, never condensed or evicted, capped at
8,000 chars) returns the digest, or the matching entries with their artifact
handle and entry numbers so read_tool_output(artifact, entry=n) fetches the
exact part instead of re-reading. The mode paragraphs, the tool docstring and
a one-line worker fragment say to check it before reading or searching.
@github-actions github-actions Bot added llm LLM backend changes performance Performance-critical changes labels Sep 26, 2026
@kovtcharov
kovtcharov marked this pull request as ready for review September 26, 2026 22:57
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This adds opt-in subtask delegation to the flagship agent: a fresh worker agent does a bounded job and hands back a short result plus evidence. The stacked context-eviction and session-findings work is also in the diff. Everything is off by default, env/config values that don't parse fail loudly, the SDK docs cover the new behaviour, and the PR is honest that it makes no cost claim yet. Nothing here changes behaviour for existing users.

One thing to fix before delegation is used outside a terminal:

  • Workers can't get permission to edit files or run commands in the Agent UI or TUI. A worker runs with a silent console that has no way to reach the user. It inherits only the parent's "auto-approve everything" flag, not the TUI's bypass mode or the user's "always allow" grants. So an implement worker's edits and shell calls are denied every time, unless GAIA_AUTO_APPROVE_TOOLS=1 is set, which the live benchmarks most likely had. The copied full_access attribute doesn't exist anywhere in the codebase. Either pass the parent's real permission state through (bypass plus session grants, or route the worker's approval prompts to the parent's handler), or document that delegation needs auto-approve outside an interactive terminal.

Real-world evidence

N/A: no evidence bundle for this run. Delegation is off by default and changes no CLI, REST or MCP surface. The PR description reports live TheRock and Jan benchmark runs, but those don't show the Agent UI/TUI permission path above. The verdict rests on static review. I couldn't run the new tests here (pytest isn't installed in this runner).

🔍 Technical details

🟡 Important

  • 🟡 Worker permission inheritance is incomplete (src/gaia/agents/tools/delegate_tools.py:553). _spawn_child copies only auto_approve_gated_tools and full_access. full_access isn't defined anywhere in src/gaia (grep -rn full_access src/gaia finds only this line). test_delegate_wiring.py:69 sets it by hand, so that test proves nothing. The worker gets output_handler=None, which gives it a SilentConsole. With no TTY, TerminalConfirmationMixin.confirm_tool_execution denies every call in TOOLS_REQUIRING_CONFIRMATION (write_file, edit_file, run_shell_command, run_python, …). What goes wrong:

    • TUI with /bypass: console.bypass_permissions isn't copied, so the worker loses both the approval and the shell-guardrail lift.
    • Agent UI (SSE handler): no human is reachable, so every gated call is denied.
    • "Always allow" grants: _session_grants stay on the parent's console.

    Minimal fix:

            for name in ("auto_approve_gated_tools", "bypass_permissions"):
    

    Session grants and interactive approval (forwarding confirm_tool_execution to self.console) need a design decision. Add a test that a worker's gated call succeeds under a parent in bypass mode.

🟢 Minor

  • 🟢 The orchestrator prompt contradicts itself (delegate_tools.py:104-117). ORCHESTRATE_SYSTEM_PROMPT says "your only tools are delegate_task and read_tool_output", then tells the model to "call session_findings". ORCHESTRATOR_TOOLS does include session_findings. docs/sdk/core/agent-system.mdx:510 repeats the two-tool claim. Name all three in both places. This is prompt-affecting, so run an eval before relying on orchestrate mode.
    yourself: your only tools are delegate_task, read_tool_output and \
    session_findings. Every unit of \
    
  • 🟢 The hub package docs don't mention the new public config. GaiaAgentConfig gains delegate_* and context_eviction* fields and the GAIA_DELEGATE* / GAIA_CONTEXT_EVICTION / GAIA_EVICT_* env vars. hub/agents/gaia/npm/CHANGELOG.md covers only the always-on shell change. Add a CHANGELOG line for delegation and eviction (and a SPEC/README mention of the env vars), per the repo's rule that every doc describing a change is updated together.
  • 🟢 The worker cap never resets (delegate_tools.py:404). delegated_tokens["children"] counts across the whole session. After 12 workers in a long Agent UI chat, every later turn is told "finish now with the evidence you already have". This matches the documented "per session" limit, so it's intended. A per-turn cap may suit multi-turn chats better.
  • 🟢 Paths with spaces or non-ASCII characters (_git_snapshot, delegate_tools.py:716). Without -z, git status --porcelain quotes such paths. The stat then fails, the mtime is None, and files_changed reports the quoted form. Use --porcelain -z for exact paths.

Strengths

  • Fails loudly throughout: bad env values, a missing workdir and a failing git all raise with actionable messages. A worker's backend failure comes back as an error result instead of a fake success.
  • Worker tokens are folded into the parent's totals and stats, so any reported saving is net. The worker's full transcript is archived and pageable instead of dropped.
  • Depth is capped at one in two independent ways (delegate_depth forces off, and _enforce_delegate_toggle removes the tool the process-wide registry leaked into the worker's tool set). The system prompt stays byte-identical when the feature is off, and a wiring test locks that in.

@kovtcharov-amd kovtcharov-amd 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.

Architecture review, no push. This adds real new surface area (a flagship agent spawning a full child agent instance), so I read the mechanism directly rather than just the description, and pulled fresh CI logs to separate real failures from noise. Recommending this stay in human/architecture review before merge — not because the design is bad, but because of open review threads plus an unmerged dependency.

Recursion is capped correctly, twice over. _child_config sets delegate_mode="off" and bumps delegate_depth; _resolve_delegate_mode checks depth before consulting GAIA_DELEGATE, so the env var can't re-enable delegation for a worker even if it's set process-wide. _enforce_delegate_toggle additionally strips delegate_task from the child's instance tool snapshot, closing the path where @tool's process-global registry could otherwise leak the tool into a new instance. A worker cannot delegate — verified in src/gaia/agents/tools/delegate_tools.py:223-243,564-580.

"Bounded" means steps and worker count, not filesystem/network scope. The child is type(self)(config=...) — same class, same tools, same shell/file access, same process — sharing the parent's artifact store and session ledger by design (for the findings-reuse feature). The only containment is delegate_max_steps (default 40), a 3600s tool-call timeout, and delegate_max_children (default 12, hard-errors once exhausted). The scope field in a brief is a natural-language instruction to the worker, not an enforced boundary — a worker can touch anything the parent could. That's a reasonable trust model for a single-user coding agent (no privilege boundary is crossed — the worker never exceeds what the parent's own session already permits) but "bounded subtask" reads like a sandbox claim; worth being explicit in the docs that the bound is cost/step, not scope.

Permission inheritance is fail-closed, not an escalation risk, but it silently breaks the feature outside auto-approve. _spawn_child copies only auto_approve_gated_tools and a full_access attribute that doesn't exist anywhere in src/gaia (dead code from copy/paste — confirmed via grep -rn full_access src/gaia, one hit, this line). It does not copy bypass_permissions (TUI) or session grants, and the child gets output_handler=None → SilentConsole, which denies every gated call with no human to ask. Net effect: a worker's edits/shell calls are denied by default in the TUI or Agent UI unless the parent already runs with blanket auto-approve — already flagged in the bot review with a concrete one-line fix; I independently confirmed the mechanism and agree it should block merge, since it means delegation is untested in the two primary interactive surfaces.

Fresh CI signal — mix of real and stale-relative-to-main:

  • Real, in this stack: Run Code Quality Checks fails because read_tool_output's tool schema is 806 chars against the new 400-char budget — the same category of bug already flagged for delegate_task (1940 chars) in the first-pass review, so this is systemic across the stack, not a one-off. Unit Tests (Windows smoke) fails on test_chunk_index.py::test_search_groups_by_file_and_leads_with_each_files_first_match (assert False) — a real test failure in the #4379 code this branch carries.
  • Stale-relative-to-main, not this PR's fault: test_no_removed_lemonade_cli.py::test_pending_entries_still_need_their_fix fails on both Linux and macOS — main has already fixed entries this branch's copy still lists as pending. Test Gaia Agent fails because gaia_agent.stdio in this branch has no describe_start_hint attribute, which main's test now expects — looks like divergence from a stdio.py refactor on main since this branch was cut, not something the delegate feature broke.

Also confirmed by reading the diff directly: the orchestrator prompt contradiction the bot flagged is real — ORCHESTRATOR_TOOLS includes session_findings (delegate_tools.py:64) but ORCHESTRATE_SYSTEM_PROMPT (delegate_tools.py:108-123) tells the model "your only tools are delegate_task and read_tool_output" before telling it to call session_findings two sentences later.

Blocking dependency, not just conflicts. This branch is stacked on #4397 (context eviction), which is still open and itself CONFLICTING — so #4384 can't be brought to a clean mergeable state independent of that PR landing first. #4376 and #4379, the other two stack members, are already merged into main, so the remaining conflict surface is smaller than "24 files" suggests, but the #4397 dependency means this can't be rebased to green on its own right now.

Net: sound recursion/budget design, one unresolved security-adjacent gap (permission inheritance) already flagged with a fix, a real (if narrow) CI regression in tool-description budgets, and a hard dependency on an unmerged, still-conflicting PR. Recommend this wait for #4397 to land and for the permission-inheritance and eval-gate items to be resolved before another merge attempt — not something to wave through in a triage pass.

@itomek

itomek commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator

Closing this. The two PRs it was stacked on landed on their own while it sat here — the chunk index as #4379, the shell-in-a-repo change as #4376 — and main has since fixed things in those same files that this branch still carries in their pre-merge form. The Windows smoke failure is one of them: the exact path-separator bug main already fixed.

The measurement is the best part of this PR and why I'm stopping rather than pushing it through. You reported straight that delegation-on landed inside the run-to-run spread of delegation-off, and that the model delegated in only two of six enabled runs — which says the feature isn't paying for itself yet on the model you measured. The plumbing is well built: net token accounting with the child's cost folded in, file changes from a real before/after snapshot rather than the worker's say-so, and a depth guard the env var can't defeat.

Re-land delegation as a small PR off current main — the tool, the ledger and their tests, without the eviction work that already has a home in #4397. Resolving the conflicts here means taking main's side of the chunk-index files wholesale anyway, so those delegation files are the whole real diff either way. Two things to fix on the way: the new tool descriptions are well over the schema budget and the lint check can't see them, and with delegation on, a chat agent built after a delegating flagship inherits a delegate tool it shouldn't have.

Nothing is lost. The branch is on your fork and stays exactly where it is; this reopens in one click.

🔍 Technical details

Merge state. 41 behind main, 16 ahead, mergeStateStatus: DIRTY. git merge-tree --write-tree --name-only origin/main pr4384 gives five conflicted files, two of them add/add:

file nature
src/gaia/agents/base/chunk_index.py add/add — main has it via #4379
tests/unit/agents/test_chunk_index.py add/add — same
src/gaia/agents/base/agent.py content
docs/sdk/core/agent-system.mdx content
tests/unit/test_project_map.py content

An add/add is the tell that the base merged independently rather than the branch drifting.

What main already has. Six of the sixteen commits:

Tool descriptions. ast.get_docstring(node, clean=False) on this branch's delegate_tools.py: delegate_task 2556 chars, session_findings 798, against MAX_TOOL_DESCRIPTION_CHARS = 500 (src/gaia/agents/base/tools.py:35, raised from 400 in 4a0a069dd). The lint job reports exactly one error — read_tool_output: description is 806 chars — and never sees the other two, because delegation is off by default so they never enter the default schema set. Main's read_tool_output docstring is 387 chars.

Registry leak. DelegateToolsMixin owns _enforce_delegate_toggle and sits in GaiaAgent's bases only (gaia_agent/agent.py:67,262). ChatAgent's bases (gaia_agent_chat/agent.py:274-288) don't include it, so nothing pops delegate_task back out of the process-global _TOOL_REGISTRY that @tool writes into. The mixin's own docstring names the hazard — "any agent built after a delegating one would otherwise snapshot the parent's tool as its own" — the guard just isn't reachable from outside the mixin.

Still unique to this branch — whole-tree greps on main, all empty: delegate_task, session_ledger/SessionLedger, cache_pricing. The one context_eviction hit is test_stdio.py:1633, which is SessionHistory turn trimming, a different mechanism.

CI, split fairly. Yours: Run Code Quality Checks (the 806-char docstring) and Unit Tests (Windows smoke), which fails test_chunk_index.py::test_search_groups_by_file_and_leads_with_each_files_first_match — the separator bug above. Not yours: macOS smoke and Linux unit both fail test_no_removed_lemonade_cli.py::test_pending_entries_still_need_their_fix, closed on main in 322cb9f28, and the Linux job also hit the old 30-minute cap that 83e53b7f3 raised to 45. Test Gaia Agent errors on describe_start_hint, which is byte-identical between this branch and main.

@itomek itomek closed this Sep 29, 2026
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 29, 2026
…ted (amd#4465)

A long session re-sends every tool result in full on every step, so the
context the model is charged for grows without bound — a big `grep`
early in a session keeps costing on every turn after it. This swaps
results the model has already moved past for a one-line stub, keeping
the full text in the artifact store and reachable through
`read_tool_output` if the model wants it back.

Off by default. `auto` only fires where the saving is worth more than
the re-read, using the provider's cached-input price ratio, and a mode
it doesn't recognise raises rather than quietly falling back.

Replaces amd#4397. Every commit from that branch is an ancestor here,
authorship intact.

### Test plan

- [x] `pytest tests/unit/agents/` — **1982 passed, 50 skipped, 0
failed**
- [x] Purely additive: `git diff --stat origin/main...HEAD` is **7
files, +984/−0**
- [x] Off by default confirmed in source: `context_eviction: str =
"off"` (`agent.py:1364`), and `context_eviction_from_env()` returns
`None` when `GAIA_CONTEXT_EVICTION` is unset
- [ ] `gaia eval agent` — this changes what context reaches the model,
so CLAUDE.md's eval gate applies before this is relied on in anger

<details>
<summary>🔍 Technical details</summary>

**Why now.** Three open PRs were shipping byte-identical copies of this
module — amd#4384 and amd#4399 alongside amd#4397. Those two are closed; this is
the surviving copy, and the only one carrying the multi-turn fix.

**The bug that was blocking it is fixed.** The first review found that
eviction stopped working after turn one: the agent remembered which
results it had evicted by `tool_call_id`, but the next turn reloaded
saved history with those results back at full size and still marked
"already evicted", so they were never re-stubbed. `18a7917b2` ("keep
evicting stale tool results past a session's first turn") fixes it, and
the suite covers it.

**Ancestry**, with original authorship preserved by merge rather than
squash:

```
$ for c in 18a7917 f4924e3 2c21f48; do git merge-base --is-ancestor $c HEAD && echo "$c ANCESTOR"; done
18a7917 ANCESTOR
f4924e3 ANCESTOR
2c21f48 ANCESTOR
```

**One thing to watch.** `cache_pricing.py` hardcodes vendor list prices
captured 2026-09-26. Nothing detects drift. The design is deliberate
under the no-silent-fallbacks rule — an unknown model logs once and
stays off rather than guessing a ratio — but whether a hand-maintained
price table belongs in-tree is worth a separate decision.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
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 llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants