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
262 changes: 155 additions & 107 deletions CHANGELOG.md

Large diffs are not rendered by default.

58 changes: 29 additions & 29 deletions CLAUDE.md

Large diffs are not rendered by default.

169 changes: 90 additions & 79 deletions README.md

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions src/agentic_cli/cli/agents_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
``completed (partial)``), its run, its title, the tokens it used, and how
long it ran (or has been running). ``/agents <id>`` shows one instance
(``researcher-2``) or one run (``researcher-2#1``): its type, its parent,
its title, then each run's status, the first lines of its result, its error
and its tokens by model.
its title, then each run's status, the fields of its brief its parent filled
(its objective, deliverable, constraints, what was known, when it is done),
the first lines of its result, its error and its tokens by model.

The runs are the manager's records (``BaseWorkflowManager.agent_runs``,
``workflow/agents/runs.py``) and the tokens its usage ledger's
Expand All @@ -30,6 +31,7 @@
from agentic_cli.cli.commands import Command, CommandCategory
from agentic_cli.cli.usage_tracker import format_tokens, format_usage
from agentic_cli.workflow.agents import RUN_COMPLETED, RUN_STARTED
from agentic_cli.workflow.agents.brief import BRIEF_FIELDS
from agentic_cli.workflow.agents.runs import run_number

if TYPE_CHECKING:
Expand Down Expand Up @@ -143,6 +145,9 @@ def _one(records: list["RunRecord"], ledger: "UsageLedger") -> Panel:
now = _now()
for record in records:
table.add_row(f"Run {_run_number(record)}", f"{_status(record)} · {_duration(record, now)}")
for name in BRIEF_FIELDS:
if record.brief.get(name):
table.add_row(f" {_label(name)}", Text(record.brief[name]))
if record.result:
table.add_row(" Result", Text(_first_lines(record.result)))
if record.error:
Expand Down Expand Up @@ -185,6 +190,11 @@ def _status(record: "RunRecord") -> str:
return record.status


def _label(field: str) -> str:
"""A brief field's label: ``done_when`` is ``Done when``."""
return field.replace("_", " ").capitalize()


def _run_number(record: "RunRecord") -> str:
"""The run's number within its instance: ``#1`` of ``researcher-2#1``."""
return "#" + run_number(record.ref.run or "")
Expand Down
12 changes: 7 additions & 5 deletions src/agentic_cli/tools/_core/delegation.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""The declaration of ``task``, the tool a coordinator delegates with.

On the Deep Agents backend, a coordinator delegates to its sub-agents through a
``task`` tool that Deep Agents' ``SubAgentMiddleware`` builds. It has no
backend-neutral implementation, so only its contract is declared here: the
name, the description and the permission declaration. The backend binds the
object it builds to this declaration (``bind_tool_identity``), which is how the
On both backends a coordinator delegates to its sub-agents through the
framework's ``task`` tool (``workflow/agents/delegate.py``), which each backend
builds in its own form: ADK's ``workflow/adk/task_tool.py::TaskTool``, Deep
Agents' ``workflow/deepagents/task_tool.py::build_task_tool``. It has no
backend-neutral callable, so only its contract is declared here: the name, the
description and the permission declaration. Each backend binds the object it
builds to this declaration (``bind_tool_identity``), which is how the
permission gate knows it.

Delegation itself needs no permission: each tool the sub-agent calls is gated
Expand Down
51 changes: 0 additions & 51 deletions src/agentic_cli/workflow/adk/branches.py

This file was deleted.

27 changes: 3 additions & 24 deletions src/agentic_cli/workflow/adk/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
turn at it. Their text is the reply, the conversation they hold is the
user's, and a conversation their model no longer takes is the turn's
error; only the root's is summarized, and only the root carries the memory
index. A single-turn sub-agent is a tool of its parent's (every agent
built from configs but the root is one): its text is its work, and the
agents under it run inside its call.
index. Agents built from configs have no ADK sub-agents: the root is the
one that replies, and each of its sub-agents runs on a runner of its own
(``GoogleADKWorkflowManager._run_agent``).
- **The agents with after-tool callbacks of their own**
(``own_after_tool_agents``, a native ADK YAML app's): ADK runs them only
when no plugin answered the call, so the result cap leaves these agents'
Expand Down Expand Up @@ -162,27 +162,6 @@ def reply_agents(root: Any) -> frozenset[str]:
return frozenset(names)


def delegated_agents(root: Any) -> dict[str, frozenset[str]]:
"""Each agent in ``root``'s tree that delegates, and the sub-agents it delegates to.

A delegation is a single-turn sub-agent: its parent calls it like a tool
named after it and reads its answer as the result (the event processor
names each such call's run). Only the agent's own count: a call another
agent makes of that name runs no sub-agent (ADK answers an unknown tool).
Empty for a tree that delegates nowhere.
"""
delegating: dict[str, frozenset[str]] = {}
for agent in walk(root):
own = frozenset(
sub_agent.name
for sub_agent in getattr(agent, "sub_agents", None) or ()
if _mode(sub_agent) == _SINGLE_TURN
)
if own:
delegating[agent.name] = own
return delegating


def own_after_tool_agents(root: Any) -> frozenset[str]:
"""The agents in ``root``'s tree with after-tool callbacks of their own."""
return frozenset(
Expand Down
33 changes: 19 additions & 14 deletions src/agentic_cli/workflow/adk/call_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@

ADK makes an ``EventActions`` for each model call and hands that object to
all three of its model callbacks (before, after, on error), so a call is
timed under its identity, as the fit guard keeps its copy of a request:
parallel delegations to one sub-agent share their invocation and their
agent's name, and a clock kept by either timed one call from another's
request. The clock holds the object, so its id goes to no other call while
this one is out. A failed call keeps its clock: a plugin after the one that
timed under its identity, as the fit guard keeps its copy of a request: a
clock kept by invocation or agent name could time one call from another
call's request. The clock holds the object, so its id goes to no other call
while this one is out. A failed call keeps its clock: a plugin after the one that
reads it may answer the error (the overflow handler), and that answer reaches
``after_model_callback`` like any response. Each run lets go of what another
invocation left: an error nobody answered, and a call cancelled mid-request,
which before google-adk 2.14 fires no callback.
``after_model_callback`` like any response. As each run ends (ADK's
``after_run_callback``, a stopped one's too, or ``on_run_error_callback``)
it lets go of what it left: an error nobody answered, and a call cancelled
mid-request, which before google-adk 2.14 fires no callback. Only its own:
two runs of one sub-agent type share their runner's clock at once.

``CallClock`` is that clock; the raw log (``LLMLoggingPlugin``) keeps one.
Every app times every call with two plugins sharing another (the manager's
Expand Down Expand Up @@ -77,10 +78,10 @@ def elapsed(self, callback_context: "CallbackContext", *, done: bool) -> float |
clock = clocks.pop(id(actions), None) if done else clocks.get(id(actions))
return None if clock is None else (time.perf_counter() - clock.started) * 1000

def keep_only(self, invocation: str | None) -> None:
"""Let go of every clock another invocation left (turns run one at a time)."""
def forget(self, invocation: str | None) -> None:
"""Let go of every clock ``invocation`` left; another run's stay."""
self._clocks = {
key: clock for key, clock in self._clocks.items() if clock.invocation == invocation
key: clock for key, clock in self._clocks.items() if clock.invocation != invocation
}

def clear(self) -> None:
Expand Down Expand Up @@ -137,10 +138,14 @@ async def on_model_error_callback(
# reaches after_model_callback, timed, and lets it go.
return None

async def before_run_callback(
self, *, invocation_context: "InvocationContext"
async def after_run_callback(self, *, invocation_context: "InvocationContext") -> None:
self.clock.forget(invocation_context.invocation_id)
return None

async def on_run_error_callback(
self, *, invocation_context: "InvocationContext", error: Exception
) -> None:
self.clock.keep_only(invocation_context.invocation_id)
self.clock.forget(invocation_context.invocation_id)
return None


Expand Down
58 changes: 9 additions & 49 deletions src/agentic_cli/workflow/adk/compaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
``AgentCliSummarizer`` is that summarizer:

- **The main agent only.** ``MainAgentPlugin`` records the agent that is
running (``running_agent()``), and nothing is written for another one. A
delegated sub-agent's check would compact the shared session under it: one
that sees only its request then lost its brief and looped (100 requests in
one turn, offline). A sub-agent too big for its own model is the fit guard's.
running (``running_agent()``), and nothing is written for another one (a
native ADK YAML app's agent the root transferred to). A sub-agent runs on
a runner of its own, whose app summarizes nothing: one too big for its own
model is the fit guard's.
- **The range** (``summary_range``) keeps the newest ``keep`` tokens word for
word and cuts where a user turn starts, never between a call and its
result, never inside the current turn. It is chosen before anything is
Expand Down Expand Up @@ -78,7 +78,6 @@

from agentic_cli.logging import Loggers
from agentic_cli.workflow import live_events
from agentic_cli.workflow.adk.branches import branch_run, parent_branch_run
from agentic_cli.workflow.adk.model_factory import generate_text
from agentic_cli.workflow.context import (
ESTIMATE_MARGIN,
Expand All @@ -91,7 +90,6 @@
usage_fields,
)
from agentic_cli.workflow.events import WorkflowEvent
from agentic_cli.workflow.sessions import get_active_turn, set_active_run
from agentic_cli.workflow.summary_prompt import SUMMARY_PREFIX, summary_prompt
from agentic_cli.workflow.usage import PURPOSE_SUMMARIZATION, UsageLedgers, adk_usage_event

Expand All @@ -102,7 +100,6 @@

from agentic_cli.config import BaseSettings
from agentic_cli.models import ProviderKind, ResolvedModel
from agentic_cli.workflow.agents.runs import AgentRuns
from agentic_cli.workflow.context import ContextBudget

logger = Loggers.workflow()
Expand Down Expand Up @@ -137,58 +134,21 @@ def running_agent() -> str | None:
class MainAgentPlugin(BasePlugin):
"""Records the running agent before ADK runs it, for ``running_agent()``.

Given the manager's runs, it also makes the sub-agent run the agent is
the active run (``workflow.sessions.get_active_run``) as it starts: the
run its branch names (``workflow/adk/branches.py``), None for the root;
the agent's model calls, tool calls, permission checks and questions see
it. ADK runs a delegated sub-agent inside its parent's call
(``run_node``, in that call's own task), so as the sub-agent ends, or
fails, its parent's run is made the active one again: the call's
after-tool callbacks are the parent's. It is set by value, the parent's
run from the branch, so no token from the start's context is needed.
Since it is first in the chain and its after-agent callback returns
nothing, every later plugin's ``after_agent_callback`` (awaited after it,
in the same context), and a native app agent's own after-agent
callbacks, see the parent's run, not the ending agent's.

``running_agent()`` keeps the sub-agent's name in that call's task until
the task ends; only the summarizer reads it, at an agent's model call,
which never runs in a tool call's task.
First in every chain (the conversation's runner's and each sub-agent
type's), so every later plugin runs after it. The record stays in the
task the agent runs in until that task ends; only the summarizer reads
it, at an agent's model call.
"""

def __init__(self, runs: "AgentRuns | None" = None) -> None:
def __init__(self) -> None:
super().__init__(name="main_agent")
self._runs = runs

async def before_agent_callback(
self, *, agent: "BaseAgent", callback_context: "CallbackContext"
) -> None:
_running_agent.set(agent.name)
if self._runs is not None:
branch = getattr(callback_context, "branch", None)
set_active_run(branch_run(self._runs, get_active_turn(), branch))
return None

async def after_agent_callback(
self, *, agent: "BaseAgent", callback_context: "CallbackContext"
) -> None:
self._parents_again(callback_context)
return None

async def on_agent_error_callback(
self, *, agent: "BaseAgent", callback_context: "CallbackContext", error: Exception
) -> None:
# ADK calls it for an exception that leaves the agent, before
# re-raising it (a delegation's tool answers "Error running
# sub-agent: ..."); after_agent_callback is not called then.
self._parents_again(callback_context)

def _parents_again(self, callback_context: "CallbackContext") -> None:
"""Make the run that made this agent's delegation the active one again."""
if self._runs is not None:
branch = getattr(callback_context, "branch", None)
set_active_run(parent_branch_run(self._runs, get_active_turn(), branch))


class NoAfterTurnCompactionRunner(Runner):
"""ADK's runner without its compaction pass after each turn.
Expand Down
14 changes: 13 additions & 1 deletion src/agentic_cli/workflow/adk/context_cache_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
or hangs, would pay a failed create (up to its 60-second bound) at every step.
``ContextCachePlugin`` ends caching for the rest of an agent's turn once a call
that could have made a cache ends without one; the next turn tries again.
Its state is kept by invocation and let go of as that run ends, well
(``after_run_callback``) or failing (``on_run_error_callback``, after which
ADK runs no ``after_run_callback``): a sub-agent run is an invocation of its
type's runner, and two runs of one type share this plugin at once.
"""

from __future__ import annotations
Expand Down Expand Up @@ -65,7 +69,15 @@ async def after_model_callback(
return None

async def after_run_callback(self, *, invocation_context: InvocationContext) -> None:
invocation = invocation_context.invocation_id
self._forget(invocation_context.invocation_id)

async def on_run_error_callback(
self, *, invocation_context: InvocationContext, error: Exception
) -> None:
self._forget(invocation_context.invocation_id)

def _forget(self, invocation: str) -> None:
"""Let go of what ``invocation`` kept; another run's stays."""
self._spent = {key for key in self._spent if key[0] != invocation}
self._could_cache = {
key: value for key, value in self._could_cache.items() if key[0] != invocation
Expand Down
Loading
Loading