Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,48 @@ the start of the entry's title.

### Added

- **The main agent's requests list its open sub-agents, when it can continue
them.** With `SubAgentPolicy(follow_ups=True)` a main agent with sub-agents
(it has `message_agent`) is told which of its own sub-agents are open: a
roster after the memory index, `<agents>`, the line `Your sub-agents in
this conversation (message_agent continues one):`, then one line per
idle, stopped or running instance, newest first, `- <id> (<type>,
<status>): <title>` and ` — <the first line of its last result>`, then
`</agents>`; at most 2,000 characters, the oldest lines left out, never
cut (`agentic_cli.workflow.agents.roster`: `roster_text`, `ROSTER_OPEN`,
`ROSTER_CLOSE`, `ROSTER_HEADER`, `ROSTER_MAX`, provisional). It is a
snapshot per conversation, taken and dropped where the memory index's is
(the conversation opened, a summary written, `/compact`), so the head of
the request stays the same for prompt caching; the tool results and
notices in the conversation carry what changed since. On ADK it is a user
content of its own after the index (`RosterPlugin`): the fit guard never
drops it and folds the index, the roster and a summary into the first user
text, in that order, and the overflow retry keeps it; on Deep Agents the
text block after the index's in the first human message
(`RosterMiddleware`), counted by the summarization. With the policy's
defaults, and when every sub-agent is closed, there is none. A manager
reaches it through `_roster_wanted(root)` and `_roster_now()`;
`_forget_memory_index` drops it with the index's.
- **A sub-agent instance's brief survives its growing transcript, on both
backends.** A follow-up's own message is not its instance's brief, so a
long transcript could lose the brief from the requests: on Deep Agents a
summary of the instance's thread stood for it, on ADK the fit guard could
leave it out of a follow-up's request. An instance's first run now marks
its message as the brief, and it is kept in every later request. On Deep
Agents the instance's own summarization (on its model, against its
budget) writes each summary that stands for the brief as a message that
opens with the brief's text (`summarization.brief_message`, `is_brief`,
`brief_of`); on ADK, where summaries stay the main agent's, the fit guard
and the overflow retry keep the brief whatever they leave out, the turns
after it joining it as the run's task message does (the event that set
`adk/sessions.py::BRIEF_KEY`, `agentic_cli.brief`, in the child session:
`fit_guard_plugin.brief_of`; `drop_turns(brief=)`). The difference is the
libraries': Deep Agents' summary also stands for a follow-up's own message
once it is older than what a summary keeps word for word, where ADK's
trim keeps it. An instance's summary that would stand for less than a fifth
of its trigger is not written (the brief restated in each summary can keep
a long brief near the trigger), as ADK's is not. The main agent's
summaries are unchanged.
- **A parent's tools that continue its sub-agents, `message_agent`,
`stop_agent` and `check_agents`, on both backends, with
`SubAgentPolicy(follow_ups=True)`.** Every agent with sub-agents gets them
Expand Down
17 changes: 9 additions & 8 deletions CLAUDE.md

Large diffs are not rendered by default.

15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,9 @@ ADK integrations:
`context_summarize_at` of the input budget and `context_max_tokens`),
keeping the current turn and the newest 12% of that word for word; a
sub-agent's run, on its own child session, is never summarized. The fit guard leaves the
oldest turns out of a request still over its agent's budget, and a
oldest turns out of a request still over its agent's budget (never the memory index, the
roster of sub-agents or a summary that open the main agent's, nor a sub-agent instance's
brief, the message its first run started from), and a
request the provider refuses as too long is summarized or trimmed and
retried once, then ends in one clear error (see
[Context management](#context-management)). A native ADK YAML app gets
Expand Down Expand Up @@ -406,7 +408,9 @@ What it supports:
the model's input budget (95% of its context window, less its
`max_tokens`) and `context_max_tokens` (200,000 tokens), keeping the newest
12% of that word for word. A model whose window is unknown counts as
128,000 tokens. A request the provider refuses as too long is summarized
128,000 tokens. A sub-agent instance's summary opens with its brief (the
message its first run started from), so the brief survives every summary
of its thread. A request the provider refuses as too long is summarized
and retried once; a conversation that still does not fit ends the turn
with one error naming the model. A sub-agent's fails only its run, as on
ADK: the user is warned `<agent>: the request no longer fits <model>'s
Expand Down Expand Up @@ -1418,7 +1422,12 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.",
user's to continue. A run that did not complete fully (partial, failed,
cancelled) names the tasks it left open in its envelope (`open_tasks`),
so its parent can continue it; a message sent to a run that ended before
reading it reaches its instance's next run.
reading it reaches its instance's next run. The main agent's requests then
also list its open sub-agents, after the memory index: `<agents>`, one line
each, newest first (`- researcher-2 (researcher, idle): Find X. — X is 42.`),
`</agents>`, at most 2,000 characters. The list is taken once and kept, as
the memory index is, so the prompt stays cached: it is taken again when the
conversation is opened, after a summary and after `/compact`.
- **What the agent graph refuses.** `inherit_context` is for sub-agents only, and
only for the main agent's own sub-agents that have none of their own. A
coordinator cannot have a tool of its own named `task` (nor, with
Expand Down
131 changes: 93 additions & 38 deletions src/agentic_cli/workflow/adk/fit_guard_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@
- Over the agent's budget B, it drops the oldest whole turns from this
request (``drop_turns``) until it is under the agent's trigger: a turn
starts at a user's text, never at a tool result or right after a call, so
a call keeps its result; the newest turn stays, and so do the memory index
and a summary that open the conversation (``protected_head``). The first
a call keeps its result; the newest turn stays, and so do the memory index,
the roster of the main agent's sub-agents and a summary that open the
conversation (``protected_head``). The first
kept user content starts with a note, ``FIT_NOTE``, as a part of its own:
no new message, so no provider sees one more user message in a row. The
session is untouched: the next request starts from the whole history again.
- In a sub-agent run's request (``keep_task``: a sub-agent type's chain) the
run's task message, its invocation's user content, is never left out
run's task message, its invocation's user content, and its instance's
brief (the event of its child session whose state delta set ``BRIEF_KEY``:
``brief_of``; a follow-up's message is not the brief) are never left out
either: a message steered to the run after a tool result starts a turn,
and the turns between the task message and the first kept one go; that
turn's opening content joins the task message, after the note, as one
Expand All @@ -28,8 +31,8 @@
turn.
- When the newest turn alone is over the budget, nothing it could drop would
help: the request goes as it is, and the overflow handler answers.
- As its last step, what opens the conversation (the memory index, a summary:
each a user content of its own) is folded into the next content when that
- As its last step, what opens the conversation (the memory index, the roster, a
summary: each a user content of its own) is folded into the next content when that
is a user's text, as parts before its own (``fold_summary``): a strict chat
template refuses two user messages in a row.

Expand All @@ -50,7 +53,7 @@

from __future__ import annotations

from collections.abc import Mapping
from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, NamedTuple

from google.adk.plugins.base_plugin import BasePlugin
Expand All @@ -60,12 +63,15 @@
from agentic_cli.memory import INDEX_OPEN
from agentic_cli.workflow import live_events
from agentic_cli.workflow.context import ESTIMATE_MARGIN, chars_per_token
from agentic_cli.workflow.adk.sessions import BRIEF_KEY
from agentic_cli.workflow.agents.roster import ROSTER_OPEN
from agentic_cli.workflow.events import WorkflowEvent
from agentic_cli.workflow.summary_prompt import SUMMARY_PREFIX

if TYPE_CHECKING:
from google.adk.agents.callback_context import CallbackContext
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event
from google.adk.events.event_actions import EventActions
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
Expand Down Expand Up @@ -130,7 +136,8 @@ async def before_model_callback(
list(llm_request.contents), config.model_copy() if config is not None else None
))
task = callback_context.user_content if self._keep_task else None
self._fit(llm_request, agent, budget, kind, task)
brief = brief_of(callback_context.session.events) if self._keep_task else None
self._fit(llm_request, agent, budget, kind, task, brief)
llm_request.contents = fold_summary(llm_request.contents)
return None

Expand Down Expand Up @@ -179,17 +186,20 @@ def _release(self, callback_context: "CallbackContext") -> None:
def _fit(
self, llm_request: "LlmRequest", agent: str, budget: "ContextBudget",
kind: "ProviderKind", task: types.Content | None = None,
brief: types.Content | None = None,
) -> None:
"""Leave the oldest turns out of ``llm_request`` when it is over the budget.

``task``, a sub-agent run's task message, is never left out.
``task``, a sub-agent run's task message, and ``brief``, its
instance's, are never left out.
"""
estimate = estimate_request_tokens(llm_request, kind)
if estimate <= budget.budget:
return
overhead = overhead_tokens(llm_request, kind)
contents, dropped = drop_turns(
llm_request.contents, target_tokens=budget.trigger - overhead, kind=kind, task=task
llm_request.contents, target_tokens=budget.trigger - overhead, kind=kind, task=task,
brief=brief,
)
if not dropped or overhead + _tokens(_contents_chars(contents), kind) > budget.budget:
# The newest turn alone is over: the overflow handler answers.
Expand Down Expand Up @@ -228,13 +238,13 @@ def overhead_tokens(llm_request: "LlmRequest", kind: "ProviderKind") -> int:


def fold_summary(contents: list[types.Content]) -> list[types.Content]:
"""``contents`` with what opens them (the index, a summary) folded into the next one.
"""``contents`` with what opens them (the index, the roster, a summary) folded into the next one.

The index and a summary are user contents of their own. Their parts go
The index, the roster and a summary are user contents of their own. Their parts go
before those of the user's text that follows, the index's first, so no
provider sees two user messages in a row. When no user text follows (a
tool result, a model's turn), an index and a summary become one content.
A lone index or summary before no user text is left as it is. ``contents``
tool result, a model's turn), they become one content.
A lone index, roster or summary before no user text is left as it is. ``contents``
are never changed in place.
"""
head = protected_head(contents)
Expand All @@ -252,16 +262,16 @@ def fold_summary(contents: list[types.Content]) -> list[types.Content]:

def drop_turns(
contents: list[types.Content], *, target_tokens: float, kind: "ProviderKind",
task: types.Content | None = None,
task: types.Content | None = None, brief: types.Content | None = None,
) -> tuple[list[types.Content], int]:
"""``contents`` without their oldest whole turns, under ``target_tokens`` if it can be.

A turn starts at a user content with a text and no tool result, after a
content that made no call: so a call and its result stay together. Turns
go oldest first, the oldest whatever the target (the caller knows the
request is too big), until the rest, with the note, is under the target;
the newest turn always stays, and so do the index and a summary that open
the conversation. The first kept user content gets ``FIT_NOTE`` as a part
the newest turn always stays, and so do the index, the roster and a
summary that open the conversation. The first kept user content gets ``FIT_NOTE`` as a part
before its own; ``contents`` themselves are left as they are.

``task`` is a sub-agent run's task message (its invocation's user
Expand All @@ -270,6 +280,13 @@ def drop_turns(
first kept one's opening content joins it, after the note, as one user
content. An inheriting run's history before it goes first.

``brief`` is the run's instance's brief, which stays as the task message
does (a follow-up's task message is its own message, and the brief the
turn before it): what is kept opens with the first of them, the note,
the other when the cut went past it too, then the first kept turn's
opening content. One content when they are the same message (a first
run's).

Each content is measured once; what goes is subtracted from a running
sum.

Expand All @@ -282,7 +299,7 @@ def drop_turns(
starts = [i for i in range(len(body)) if _starts_turn(body, i)]
if not starts or starts[-1] == 0:
return contents, 0
kept = _task_at(body, task)
kept = sorted({at for at in (_brief_at(body, brief), _task_at(body, task)) if at is not None})
sizes = [len(content.model_dump_json(exclude_none=True)) for content in contents]
remaining = sum(sizes) + _NOTE_CHARS
sizes = sizes[len(head):]
Expand All @@ -291,13 +308,14 @@ def drop_turns(
previous = 0
for dropped, cut in enumerate(cuts, start=1):
remaining -= sum(sizes[previous:cut])
if kept is not None and previous <= kept < cut:
remaining += sizes[kept] # the task message stays
# The brief and the task message stay.
remaining += sum(sizes[at] for at in kept if previous <= at < cut)
previous = cut
if _tokens(remaining, kind) < target_tokens:
break
if kept is not None and kept < cut:
return [*head, _joined(body[kept], body[cut]), *body[cut + 1:]], dropped
before = [body[at] for at in kept if at < cut]
if before:
return [*head, _joined(before, body[cut]), *body[cut + 1:]], dropped
return [*head, _noted(body[cut]), *body[cut + 1:]], dropped


Expand All @@ -306,7 +324,7 @@ def keep_newest_turns(
) -> tuple[list[types.Content], int]:
"""``contents`` from their ``turns``-th newest turn on, cut as ``drop_turns`` cuts.

The index and a summary that open them stay, and the first kept user
The index, the roster and a summary that open them stay, and the first kept user
content gets ``FIT_NOTE``. For a retry after a summary: the turns the
summary kept, what every later call sends besides it.

Expand All @@ -329,25 +347,57 @@ def _noted(content: types.Content) -> types.Content:
*(content.parts or [])]})


def _joined(task: types.Content, content: types.Content) -> types.Content:
"""``content`` after ``task`` and ``FIT_NOTE``, as one user content."""
return content.model_copy(update={"parts": [*(task.parts or []),
types.Part.from_text(text=FIT_NOTE),
*(content.parts or [])]})
def _joined(kept: Sequence[types.Content], content: types.Content) -> types.Content:
"""``content`` after the first of ``kept``, ``FIT_NOTE`` and the rest of
``kept``, as one user content."""
first, *rest = kept
return content.model_copy(update={"parts": [
*(first.parts or []),
types.Part.from_text(text=FIT_NOTE),
*(part for other in rest for part in other.parts or []),
*(content.parts or []),
]})


def _user_contents_like(contents: list[types.Content], like: types.Content | None) -> list[int]:
"""Where the user contents with ``like``'s parts are in ``contents``."""
if like is None:
return []
return [
i for i, content in enumerate(contents)
if content.role == "user" and content.parts == like.parts
]


def _task_at(contents: list[types.Content], task: types.Content | None) -> int | None:
"""Where ``task`` (a run's task message) is in ``contents``: the last user
content with its parts; None for none."""
if task is None:
return None
found = [
i for i, content in enumerate(contents)
if content.role == "user" and content.parts == task.parts
]
found = _user_contents_like(contents, task)
return found[-1] if found else None


def _brief_at(contents: list[types.Content], brief: types.Content | None) -> int | None:
"""Where ``brief`` (an instance's first message) is in ``contents``: the
first user content with its parts; None for none."""
found = _user_contents_like(contents, brief)
return found[0] if found else None


def brief_of(events: Sequence["Event"]) -> types.Content | None:
"""The brief of the instance whose child session holds ``events``: the
content of the first event whose state delta set ``BRIEF_KEY`` (its first
run's message), or None.

A copied conversation (an inheriting instance's) carries no state delta,
so a parent's brief is never taken for the child's.
"""
for event in events:
delta = event.actions.state_delta if event.actions is not None else None
if delta and BRIEF_KEY in delta:
return event.content
return None


def _starts_turn(contents: list[types.Content], i: int) -> bool:
if not _users_text(contents[i]):
return False
Expand Down Expand Up @@ -380,13 +430,18 @@ def is_memory_index(content: types.Content) -> bool:
return content.role == "user" and bool(first and first.text) and first.text.startswith(INDEX_OPEN)


def is_roster(content: types.Content) -> bool:
"""Whether ``content`` is the roster of sub-agents the main agent's requests carry."""
first = content.parts[0] if content.parts else None
return content.role == "user" and bool(first and first.text) and first.text.startswith(ROSTER_OPEN)


def protected_head(contents: list[types.Content]) -> list[types.Content]:
"""What opens ``contents`` and is never dropped: the index, then a summary."""
"""What opens ``contents`` and is never dropped: the index, the roster, then a summary."""
count = 0
if count < len(contents) and is_memory_index(contents[count]):
count += 1
if count < len(contents) and is_summary(contents[count]):
count += 1
for opens in (is_memory_index, is_roster, is_summary):
if count < len(contents) and opens(contents[count]):
count += 1
return contents[:count]


Expand Down
Loading
Loading