Skip to content

Agent and automation architecture

This page is the architecture analysis for the agents/automation module. It complements the implementation pages by focusing on how custom agents, subagents, experimental Agent Teams, tasks, slash commands, auto-mode, and hosted review compose without owning a different runtime rather than re-listing each constant.

Scope: custom agents from --agents, the model-visible Agent tool, background agents (claude agents), Agent messaging, Agent Teams, task tools (TaskCreate/TaskGet/TaskList/TaskUpdate), tool/Workflow concurrency, task scheduling/completion, interruption and queued steering, subagent lifecycle hooks, slash-command automation, auto-mode, ultrareview hosted review, and cron/timed tasks. Implementation specifics live in the linked focused pages.

Module purpose

This module owns delegation and scheduled automation around the main session. It does not own model turns or tool execution; it composes them by:

  1. Letting users define agents (inline JSON or claude agents).
  2. Letting the model launch ordinary workers through Agent, or gated named teammates through the same tool, and coordinate shared planning state through task tools.
  3. Letting plugins/keybindings/skills trigger slash-command automation.
  4. Letting auto-mode classify and consent to common actions.
  5. Letting hosted ultrareview invoke multi-agent code review.

Architecture thesis

Agents and automation are orchestration over the existing runtime, not parallel runtimes. The same composition root, context loop, tool/permission boundary, and session envelope are reused; this module adds (a) task stores as shared state, (b) an experimental team roster/mailbox layer, (c) lifecycle hooks distinct from tool hooks, (d) a slash-command/keybinding/skill triggering surface, and (e) optional hosted backends.

Source anchors

Semantic aliasString or symbolArchitectural meaning
AgentsCommandFamilyH.command("agents")Background agents command family registered on the root.
InlineAgentsFlag--agents <json>Inline custom-agent injection at session start.
TaskCreateToolvar LX="TaskCreate"Task-tool constants used by orchestration.
TaskGetToolvar DQ="TaskGet"Task status/result retrieval constant.
TaskListToolvar UZ="TaskList"Task listing constant.
TaskUpdateToolvar J0="TaskUpdate"Task update constant.
AgentToolAgent, run_in_background, isConcurrencySafe()Launches a subagent synchronously or, by default, as a registered background task.
AgentMessageRouterSendMessage, vfo(), y6e(), writeToMailbox()Resolves a recipient, preserves identity pins, and dispatches through the target’s queue, mailbox, socket, or remote-events transport.
AgentTeamsGateisAgentSwarmsEnabled(), CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS, tengu_amber_flintEnables the session’s implicit team and named-teammate branch.
TeamCoordinationStoreconfig.json, inboxes/<agent>.json, ~/.claude/tasks/<team>/Coordinates roster identity, locked mailbox delivery, and shared task records.
ToolUseConcurrencyY3g(), J3g(), CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCYGroups consecutive concurrency-safe calls and runs up to 10 by default.
PromptPriorityQueueOQn={now:0,next:1,later:2}, queued_commandSeparates immediate aborting input, cooperative mid-turn steering, and deferred work.
WorkflowLimiterMN(), _Yg(os.cpus().length)FIFO workflow-agent concurrency limiter.
SubagentContextClassifieragentType==="subagent"Runtime classifier distinguishing subagent context.
SubagentLifecycleHooksSubagentStart, SubagentStopSubagent lifecycle hook events.
TaskLifecycleHooksTaskCreated, TaskCompletedTask lifecycle hook events.
TaskNotificationFrametask_notificationOutbound frame carrying long-running task progress.
LongRunningMonitorContractEach stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime.Long-running monitor process specification.
UltraReviewCommandH.command("ultrareview [target]")Hosted multi-agent review command.
AutoModeCommandH.command("auto-mode")Auto-mode inspection/critique command.
AutoModePolicyConsent[auto-mode] hasAutoModeOptIn=true policy defaultMode=auto implies consentAuto-mode consent precedence: policy implies opt-in.
AutoModeConsentSources[auto-mode] hasAutoModeOptIn=...skipAutoPermissionPrompt: user=... local=... flag=... policy=...Auto-mode multi-source consent computation.
SlashCommandKeybindingscommand:help, command:compactKeybinding actions that execute slash commands.
PluginSlashCommandSchemaslash command namePlugin schema turning command files into slash commands.
SkillSlashDispatchvia Skill tool or slash commandSkill dispatch can be triggered by slash commands.
SkillShellExecutionPolicydisableSkillShellExecutionPolicy boundary for slash-command/skill shell execution.
PromptSuggestionFrameprompt_suggestionPredicted-next-prompt frame; relevant to automation/auto-mode UX.

Internal decomposition

flowchart TD
Root[Root composition] --> AgentsCmd[claude agents]
Root --> AgentsFlag[--agents JSON]
Root --> Ultra[ultrareview]
Root --> AutoCmd[auto-mode command]
Root --> Slash[Slash command registry]
Session[Active session] --> Tasks[Task store]
Session --> AgentTool[Agent tool]
Session --> Team[Implicit team context]
Session --> Hooks[Subagent + task hooks]
Session --> Slash
Session --> AutoConsent[Auto-mode consent classifier]
Tasks --> TaskTools[TaskCreate / TaskGet / TaskList / TaskUpdate]
AgentTool --> ToolScheduler[concurrency-safe tool scheduler]
AgentTool --> Team
Team --> Teammates[in-process / tmux / iTerm2 teammates]
Team --> TeamIpc[roster + inbox files]
Teammates --> Tasks
ToolScheduler --> Subagent[Subagent runtime context]
TaskTools --> Tasks
Subagent --> SubLoop[Context/model loop with agentType=subagent]
Subagent --> Notifications[task notifications]
Notifications --> PriorityQueue[now / next / later queue]
PriorityQueue --> SubLoop
Hooks --> SubStart[SubagentStart / SubagentStop]
Hooks --> TaskLife[TaskCreated / TaskCompleted]
Slash --> Plugin[Plugin slash commands]
Slash --> Skill[Skill dispatch]
Slash --> Keybind[Keybinding command:*]
Slash --> Policy[disableSkillShellExecution]
Ultra --> Preflight[/v1/ultrareview/preflight]
Ultra --> Hosted[Hosted multi-agent run]
AutoCmd --> Inspect[defaults/config inspection]
AutoCmd --> Critique[AI critique of custom rules]
AutoConsent --> Permission[Permission boundary]
Sub-componentResponsibility
Custom agent injectionParses --agents JSON and merges with plugin/marketplace agents.
Background agents commandManages long-running agent jobs; reuses session/MCP/plugin/permission defaults.
Task storeShared state holding task records; addressed by TaskCreate/TaskGet/TaskList/TaskUpdate.
Agent launcherResolves the agent definition/model/permissions, then runs synchronously or registers a background worker. Consecutive Agent tool uses are concurrency-safe.
Agent Teams layerUnder the explicit experimental gate, turns eligible named Agent calls into asynchronous teammates and coordinates identity/messages/tasks through a session-local roster plus locked files.
Priority/steering queueDelivers user, peer, completion, cron, and control-originated work at now, next, or later; eligible next work can fold in between tool batches.
Workflow schedulerAdds deterministic parallel/pipeline control with a FIFO agent-slot limiter and shared abort/token budgets.
Subagent runtime contextA session-loop projection where agentType==="subagent" changes prompt boundaries and hook routing.
Lifecycle hooksSubagentStart/SubagentStop for subagents, TaskCreated/TaskCompleted for task records.
Slash command dispatcherResolves plugin command files, skill metadata, keybindings into commands.
auto-mode classifierComputes consent (user/local/flag/policy) and dispatches to the permission boundary.
Hosted review (ultrareview)Sends preflight, then invokes a hosted multi-agent run; mirrors results locally.
Task notification monitorOptional long-running process that emits <task_notification> frames per stdout line for the model.

Public interface

Inputs

SurfaceEffect
--agents <json>Inline custom agent definitions for the current session.
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS or raw argv --agent-teams; teammateMode / hidden --teammate-modeEnables Agent Teams and selects in-process, tmux, iterm2, or auto execution.
claude agents ... (with --setting-sources, --add-dir, --plugin-dir, --settings, --mcp-config, --strict-mcp-config, --permission-mode, --dangerously-skip-permissions, --model)Background-agent dispatch with session defaults.
ultrareview [target]Hosted multi-agent code-review entry.
auto-mode subcommandsInspect classifier defaults and critique custom rules.
Plugin slash commands (/plugin:about, …)Plugin-defined commands surfaced through the dispatcher.
Skill metadata / Skill toolSkill-based dispatch path.
Keybinding actions (command:help, command:compact)UI-driven slash command invocation.
Managed setting disableSkillShellExecutionTrust gate for inline shell in skills/custom slash commands.
Managed setting disableAgentViewHides the agent UI surface.

Outputs

OutputConsumer
task_notification framesHeadless multiplexer / SDK / TUI.
prompt_suggestion framesUX; relevant to auto-mode discoverability.
Subagent and task hook callsHook scripts/commands, telemetry.
Hosted review resultsLocal renderer / preflight metadata.
Auto-mode telemetry (tengu_auto_mode_decision, tengu_auto_mode_denial_limit_exceeded, tengu_auto_mode_fallback_to_ask, tengu_auto_mode_opt_in)Telemetry sink.

Internal collaborators

CollaboratorContract
Runtime lifecycleRegisters agents, ultrareview, auto-mode, and slash-command surfaces on the root command.
Context/model loopRuns subagent and task contexts as projections; emits prompt_suggestion after each turn.
Tool/permission runtimeReceives auto-mode consent decisions; runs task tools through the same boundary as built-ins.
Sessions moduleStores agent/transcript state; Agent Teams adds separate roster, mailbox, and shared-task files but does not establish durable whole-team restoration after clean exit.
MCP/plugins/hooksPlugins contribute agents, skills, slash commands, and hooks; hosted review may coordinate with MCP.
Ops moduleReceives auto-mode/task/subagent telemetry; surfaces hosted-review failures via doctor.
Remote bridgeLong-running tasks and hosted review interoperate with remote variants via the same envelope.

Design decisions

  1. Tasks are shared state, not the worker launcher. TaskCreate/TaskGet/TaskList/TaskUpdate coordinate status, owners, and dependencies. Agent or Workflow starts model execution; updating a task does not itself preempt a provider call.
  2. Subagent is a context flag, not a separate loop. agentType==="subagent" changes prompt boundaries and hook routing within the existing context/model loop; this avoids forking the runtime.
  3. Lifecycle hooks are split. SubagentStart/Stop describe runtime context; TaskCreated/Completed describe persistent records. Splitting them lets hook scripts react to either dimension without conflation.
  4. Slash commands are a dispatcher, not a parser. Slash inputs flow from multiple sources (plugin files, skill metadata, keybindings) into one dispatcher, which routes through the existing runtime; this keeps the model’s view stable regardless of trigger.
  5. auto-mode is multi-source consent. Opt-in is computed from policy → user → local → flag, with the policy defaultMode=auto implying opt-in. This lets ops set default behavior without per-user changes.
  6. Hosted review is opt-in and explicit. ultrareview exists as its own command; it does not silently activate during normal turns.
  7. Notification monitor is well-scoped. The long-running process documented at byte 0x112031 runs for the session lifetime and emits one <task_notification> per stdout line — a narrow, predictable contract.
  8. Background agents reuse session flags. claude agents accepts the same --setting-sources, --add-dir, --plugin-dir, --settings, --mcp-config, --permission-mode, --model so deploys do not invent a parallel configuration surface.
  9. Auto-mode telemetry classifies decisions. tengu_auto_mode_decision, _denial_limit_exceeded, _fallback_to_ask, _malformed_tool_input, _opt_in cover the visible state machine so operators can audit behavior.
  10. Concurrency and backgrounding are different layers. The tool scheduler limits simultaneously executing concurrency-safe handlers; an asynchronously launched Agent can remain alive after its handler releases that slot. Workflow agents have an additional FIFO limiter.
  11. Insertion is boundary-based. next messages can steer a recursive model loop after a tool batch, while now can abort the active headless/SDK turn and later waits. Agent mailbox messages likewise wait for the next agent boundary rather than mutating an in-flight request.
  12. Agent Teams is a session-local overlay, not a durable team service. The lead registers its generated team for clean-exit pane/worktree/team-directory cleanup. Narrow transcript-backed teammate respawn exists inside an active team, but teammate cron is rejected and whole-team startup restore is not present.

Orchestration patterns

PatternWhen used
Inline custom agent (--agents)Lightweight, session-only agent set; common in scripted runs.
Background agentsLong-running or repeated work that should outlive a single session command.
Subagent via Task toolsModel-driven delegation inside a turn; subagent runs in the same process.
Agent TeamsExperimental flat-roster collaboration: named teammates share task records and mailboxes and may run in-process or in terminal panes.
Slash command + skillHuman-/keybinding-/plugin-triggered automation that is not model-initiated.
Auto-modeReduce per-action approval prompts when consent is established; explicit opt-in path.
ultrareviewHosted multi-agent code review with preflight checks; opt-in and explicit.

Failure modes

FailureBehavior
--agents payload invalidStartup error before mode dispatch.
Task tool input malformedBoundary rejection with structured error; auto-mode logs tengu_auto_mode_malformed_tool_input if applicable.
Subagent runs over a turn/budget capResult frame uses the same error subtypes as the main loop.
Subagent hook denyThe deny path propagates with the standard PermissionDenied semantics.
Agent Teams gate or pane backend unavailableWith the gate off, named Agents remain ordinary Agents. Explicit tmux/iTerm2 failures reject teammate spawn; only auto can fall back in-process.
Auto-mode hits denial limittengu_auto_mode_denial_limit_exceeded is emitted; behavior falls back to ask.
Hosted review preflight rejectionUX surfaces the reason; no hosted run begins.
Slash command resolves to nothingDispatcher reports the unknown command without invoking model.
Managed policy disables skills’ shell executionEligible user/project/plugin shell forms become a placeholder. Policy-sourced skills retain permission-checked local expansion; MCP prompts perform no local shell expansion.

Extension points

ExtensionHow it plugs in
New agent kindProvide through --agents JSON, plugin schema, or claude agents registration; do not invent a parallel session loop.
New task fieldExtend task store metadata; orchestrators interact through the same TaskCreate/TaskUpdate constants.
New slash command sourceContribute via plugin schema or keybinding action; dispatcher handles routing.
Custom auto-mode ruleUse auto-mode config plus AI critique path; do not bypass the permission boundary.
Custom hosted review backendCompose at preflight; reuse the local rendering path.

Caveats

  • Multiple task protocols coexist. The local Agent Teams record layout is documented in Agent Teams; SDK/MCP task waiting and stream frames are separate mechanisms.
  • task_notification is a system-frame subtype; consumers should treat unknown task-notification fields as forward-compatible.
  • ultrareview references both local UX (/ultrareview, /review) and a hosted preflight route; behavior here is bounded by hosted availability and policy.

Created and maintained by Yingting Huang.