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
44 changes: 44 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,50 @@ the start of the entry's title.

### Added

- **`SubAgentPolicy` and `AgentLimits`: an app's sub-agent policy and a
run's limits** (`agentic_cli.workflow`, and `agentic_cli.workflow.agents`
with `DEFAULT_LIMITS`). Frozen dataclasses. `SubAgentPolicy` holds an
app's numbers for its sub-agents: `max_active` (4, the runs working at
once in a conversation, at any depth), `max_runs_per_turn` (20, the runs
one turn may start) and `limits`, every run's `AgentLimits`
(`DEFAULT_LIMITS`, `AgentLimits(max_model_calls=100)`, unless the app sets
its own). A policy's own `limits` replace `DEFAULT_LIMITS` whole:
`SubAgentPolicy(limits=AgentLimits(timeout=60))` has no model-call limit,
while `AgentLimits(timeout=60).over(DEFAULT_LIMITS)` keeps the 100 calls.
`AgentLimits` holds a run's `max_model_calls`, `timeout` (seconds) and
`max_tokens` (input plus output), each None for no limit of its own, and
`over(base)` lays one over another field by field: a field left None
takes the base's. So an agent type's field left None keeps the policy's
limit, and a type may set its own, higher or lower, but cannot remove a
limit the policy sets. Construction refuses, with a `ValueError` naming
the field, a limit that is not a positive int (a timeout: a positive,
finite number; `True` and `False` are no numbers here) and a policy whose
`limits` is not an `AgentLimits`.
- **`AgentConfig.brief_required` and `AgentConfig.limits`.**
`brief_required` (default `("objective",)`) names the brief fields the
agent asks a delegation to fill: `objective`, `deliverable`,
`constraints`, `known`, `done_when` or `title` (a brief always has its
title and its objective); `limits` (default None) is the agent's own
`AgentLimits`, over the policy's field by field. Both come after
`inherit_context`, so a positional `AgentConfig(...)` still binds, and
the framework's agent YAML takes them: `brief_required: [objective,
deliverable]`, `limits: {max_model_calls: 30, timeout: 600, max_tokens:
200000}` (each limit read as written, so `true` or `'30'` is refused, as
is a key that is no limit). `validate_agent_graph` raises
`AgentGraphError` for a `brief_required` that is not a tuple or list of
those names, a `limits` that is not an `AgentLimits`, and either set on
the root, which is never delegated to.
- **`subagents=`: the sub-agent policy, given to the app, a manager or the
factory.** `BaseCLIApp`, `BaseWorkflowManager` (the ADK, Deep Agents and
LangGraph managers pass it on) and `create_workflow_manager_from_settings`
take `subagents=` (keyword; a `SubAgentPolicy`, None for
`SubAgentPolicy()`). A manager keeps it for its life, a model switch
included: `BaseWorkflowManager.subagent_policy` (read-only, provisional).
Every manager an app builds gets the app's (`WorkflowController(subagents=)`),
a conversation's on another backend included. Anything else is a
`TypeError` where it is passed: the factory's before any backend is
imported, the app's before it builds anything. LangGraph's delegation
does not read it.
- **A sub-agent's questions and permission prompts name it, on both
backends.** `UserInputRequest.run` is the sub-agent run that asks (a
`RunRef`; None for the root's own), filled by `request_user_input` from
Expand Down
13 changes: 7 additions & 6 deletions CLAUDE.md

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion src/agentic_cli/cli/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
from agentic_cli.config import BaseSettings
from agentic_cli.logging import Loggers, configure_logging, log_lines_to
from agentic_cli.workflow.adk.log_filters import install_log_filters
from agentic_cli.workflow.agents.policy import as_policy
from agentic_cli.workflow.factory import check_backend, orchestrator_of
from agentic_cli.workflow.session_readers import reader_backends
from agentic_cli.workflow.settings import OrchestratorType
Expand All @@ -80,6 +81,7 @@
from agentic_cli.cli.job_monitor import JobMonitor
from agentic_cli.settings_persistence import SettingsSaveResult
from agentic_cli.workflow import GoogleADKWorkflowManager, EventType, WorkflowEvent
from agentic_cli.workflow.agents.policy import SubAgentPolicy
from agentic_cli.workflow.base_manager import BaseWorkflowManager
from agentic_cli.workflow.context import CompactResult
from agentic_cli.workflow.sessions import SessionInfo
Expand Down Expand Up @@ -341,6 +343,8 @@ def __init__(
agent_configs: list["AgentConfig"],
settings: BaseSettings,
session_id: str | None = None,
*,
subagents: "SubAgentPolicy | None" = None,
) -> None:
"""Initialize the CLI application.

Expand All @@ -352,11 +356,16 @@ def __init__(
library use and tests); without it a fresh id is generated.
``main()`` takes ``--continue`` and ``--resume <id>``
instead (``session_start``).
subagents: How the sub-agents run (a ``SubAgentPolicy``; None is
``SubAgentPolicy()``): every workflow manager the app builds
gets it, a new conversation's on another backend included.

Raises:
TypeError: The app still defines ``get_styles()``, which
TypeError: ``subagents`` is neither a ``SubAgentPolicy`` nor
None, or the app still defines ``get_styles()``, which
``get_theme(name)`` replaced.
"""
policy = as_policy(subagents)
if any("get_styles" in vars(cls) for cls in type(self).__mro__ if cls is not object):
raise TypeError(_GET_STYLES_REMOVED)

Expand Down Expand Up @@ -394,6 +403,7 @@ def __init__(
self._workflow_controller = WorkflowController(
agent_configs=agent_configs,
settings=settings,
subagents=policy,
)
self._workflow_controller.usage_tracker = self._usage_tracker
self._message_processor = MessageProcessor()
Expand Down
13 changes: 13 additions & 0 deletions src/agentic_cli/cli/workflow_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from typing import TYPE_CHECKING, AsyncIterator

from agentic_cli.logging import Loggers
from agentic_cli.workflow.agents.policy import as_policy

# Re-export the factory for backward compatibility
from agentic_cli.workflow.factory import create_workflow_manager_from_settings # noqa: F401
Expand All @@ -27,6 +28,7 @@
if TYPE_CHECKING:
from agentic_cli.cli.usage_tracker import UsageTracker
from agentic_cli.config import BaseSettings
from agentic_cli.workflow.agents.policy import SubAgentPolicy
from agentic_cli.workflow.base_manager import BaseWorkflowManager
from agentic_cli.workflow.config import AgentConfig
from thinking_prompt import ThinkingPromptSession
Expand Down Expand Up @@ -145,13 +147,22 @@ def __init__(
self,
agent_configs: list["AgentConfig"],
settings: "BaseSettings",
*,
subagents: "SubAgentPolicy | None" = None,
) -> None:
"""Initialize the workflow controller.

Args:
agent_configs: List of agent configurations for the workflow
settings: Application settings instance
subagents: The sub-agent policy every manager it builds gets
(the first start's, and each ``switch_backend``'s); None is
``SubAgentPolicy()``.

Raises:
TypeError: ``subagents`` is neither a ``SubAgentPolicy`` nor None.
"""
self._subagents = as_policy(subagents)
self._settings = settings
self._agent_configs = agent_configs
self._app_name = settings.app_name
Expand All @@ -170,6 +181,7 @@ def _create_workflow() -> "BaseWorkflowManager":
app_name=self._app_name,
orchestrator=self.backend,
session_store=self.store,
subagents=self._subagents,
)

self._create_fn = _create_workflow
Expand Down Expand Up @@ -696,6 +708,7 @@ async def _swap_orchestrator(self, backend: str) -> None:
app_name=self._app_name,
orchestrator=backend,
session_store=self.store,
subagents=self._subagents,
)
lend = getattr(old_workflow, "lend_services", None)
loan = lend() if callable(lend) else None
Expand Down
3 changes: 3 additions & 0 deletions src/agentic_cli/workflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
WorkflowEvent,
)
from agentic_cli.workflow.config import AgentConfig
from agentic_cli.workflow.agents.policy import AgentLimits, SubAgentPolicy
from agentic_cli.workflow.model_settings import ModelSettings, ThinkingSettings
from agentic_cli.workflow.mcp import MCPServerConfig
from agentic_cli.workflow.factory import create_workflow_manager_from_settings
Expand Down Expand Up @@ -82,6 +83,8 @@ def __getattr__(name: str):
"translate_adk_yaml",
# Config
"AgentConfig",
"SubAgentPolicy",
"AgentLimits",
"ModelSettings",
"ThinkingSettings",
"MCPServerConfig",
Expand Down
16 changes: 1 addition & 15 deletions src/agentic_cli/workflow/adk/delegation.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,28 +59,14 @@
from agentic_cli.logging import Loggers
from agentic_cli.tools._core.delegation import TASK_TOOL
from agentic_cli.tools.registry import bind_tool_identity, get_registry
from agentic_cli.workflow.agents.brief import INHERITED_CONTEXT_NOTE
from agentic_cli.workflow.config import AgentConfig, AgentGraphError

if TYPE_CHECKING:
from google.adk.agents import LlmAgent

logger = Loggers.workflow()

#: The end of an inheriting sub-agent's instruction: whose conversation it
#: reads, and which message is its task (Deep Agents' ``_FORK_TASK_PREAMBLE``,
#: told the way ADK shows that conversation). Sent as written, as the whole
#: prompt is (``manager._as_written``).
INHERITED_CONTEXT_NOTE = (
"You are a sub-agent: another agent has handed you a task. The conversation "
"before the task is that agent's, shown so you know what has been established: "
"the user's messages in it were addressed to that agent, not to you, and what "
"that agent did is quoted, its call handing you this task included. Do not "
"carry out those messages yourself or answer as that agent. Your task is the "
"request that follows the conversation: complete it directly, and use the "
"specific facts, figures and identifiers already established in the "
"conversation rather than answering generically."
)


def subagent_fields(config: AgentConfig) -> dict[str, Any]:
"""The ``LlmAgent`` fields that make ``config``'s agent a delegated sub-agent.
Expand Down
6 changes: 6 additions & 0 deletions src/agentic_cli/workflow/adk/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@

from agentic_cli.models import Provider, ResolvedModel, RoleMap
from agentic_cli.workflow.adk.build import ADKBuild
from agentic_cli.workflow.agents.policy import SubAgentPolicy
from agentic_cli.workflow.sessions import SessionRef


Expand Down Expand Up @@ -210,6 +211,8 @@ def __init__(
model: str | None = None,
on_event: Callable[[WorkflowEvent], WorkflowEvent | None] | None = None,
adk_config_path: str | None = None,
*,
subagents: SubAgentPolicy | None = None,
) -> None:
"""Initialize the workflow manager.

Expand All @@ -230,6 +233,8 @@ def __init__(
differs: the app runs as one built from configs
(``workflow/adk/build.py``). Library-only for now: no
``BaseCLIApp`` starts such an app.
subagents: How the sub-agents run (``subagent_policy``); None is
``SubAgentPolicy()`` (see ``BaseWorkflowManager``).
"""
if adk_config_path and agent_configs:
# ADK builds the agents from the YAML: configs beside it would be
Expand All @@ -246,6 +251,7 @@ def __init__(
app_name=app_name,
model=model,
on_event=on_event,
subagents=subagents,
)
_check_app_name(self.app_name)
self._adk_config_path = adk_config_path
Expand Down
41 changes: 40 additions & 1 deletion src/agentic_cli/workflow/agent_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
instruction_file: prompts/researcher.md
tools: [web_search]
inherit_context: false # true: also see the coordinator's conversation
brief_required: [objective, deliverable] # what a delegation must fill
limits: {max_model_calls: 30, timeout: 600} # over the policy's, per field

A top-level bare list of agents (without the ``agents:`` key) is also accepted.
Tool entries stay as strings here and are resolved to callables when the
Expand All @@ -32,13 +34,41 @@
from typing import Any

import yaml
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator

from agentic_cli.workflow.agents.policy import AgentLimits
from agentic_cli.workflow.config import AgentConfig
from agentic_cli.workflow.mcp import MCPServerConfig
from agentic_cli.workflow.model_settings import ModelSettings


class LimitsSpec(BaseModel):
"""YAML schema for an agent's ``limits`` (mapped to ``AgentLimits``).

Strict: a value is read as the YAML wrote it, so ``true`` is no count and
``'30'`` no number. ``AgentLimits`` refuses a limit that is not positive.
"""

model_config = ConfigDict(extra="forbid", strict=True)

max_model_calls: int | None = None
timeout: float | None = None
max_tokens: int | None = None

@model_validator(mode="after")
def _are_limits(self) -> "LimitsSpec":
self.to_limits()
return self

def to_limits(self) -> AgentLimits:
"""These limits as an ``AgentLimits``."""
return AgentLimits(
max_model_calls=self.max_model_calls,
timeout=self.timeout,
max_tokens=self.max_tokens,
)


class AgentSpec(BaseModel):
"""YAML schema for a single agent (validated, then mapped to AgentConfig)."""

Expand All @@ -60,6 +90,9 @@ class AgentSpec(BaseModel):
sub_agents: list[str] = Field(default_factory=list)
include_state_tools: bool = True
inherit_context: bool = False
# None: AgentConfig's own default.
brief_required: list[str] | None = None
limits: LimitsSpec | None = None


class AgentsFile(BaseModel):
Expand Down Expand Up @@ -131,6 +164,11 @@ def load_agents_from_yaml(path: str | Path) -> list[AgentConfig]:

configs: list[AgentConfig] = []
for spec in spec_file.agents:
delegation: dict[str, Any] = {}
if spec.brief_required is not None:
delegation["brief_required"] = tuple(spec.brief_required)
if spec.limits is not None:
delegation["limits"] = spec.limits.to_limits()
configs.append(
AgentConfig(
name=spec.name,
Expand All @@ -144,6 +182,7 @@ def load_agents_from_yaml(path: str | Path) -> list[AgentConfig]:
skills=list(spec.skills),
include_state_tools=spec.include_state_tools,
inherit_context=spec.inherit_context,
**delegation,
)
)
return configs
Expand Down
9 changes: 7 additions & 2 deletions src/agentic_cli/workflow/agents/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Sub-agents, as the framework keeps them: their runs.
"""Sub-agents, as the framework keeps them: their runs, and how they run.

A sub-agent run is one piece of work a sub-agent does for its parent: one
delegation (its parent's tool call). ``runs`` names each run within its
conversation and records it from its ``AGENT_RUN`` events.
conversation and records it from its ``AGENT_RUN`` events; ``policy`` holds
an app's sub-agent policy and a run's limits.
"""

from agentic_cli.workflow.agents.policy import DEFAULT_LIMITS, AgentLimits, SubAgentPolicy
from agentic_cli.workflow.agents.runs import (
RESULT_MAX,
RUN_CANCELLED,
Expand All @@ -24,7 +26,9 @@
)

__all__ = [
"AgentLimits",
"AgentRuns",
"DEFAULT_LIMITS",
"RESULT_MAX",
"RUN_CANCELLED",
"RUN_COMPLETED",
Expand All @@ -35,6 +39,7 @@
"RUN_STARTED",
"RunRecord",
"SUBAGENT_ERROR_PREFIX",
"SubAgentPolicy",
"TITLE_MAX",
"result_head",
"run_label",
Expand Down
Loading
Loading