Delegation routing and execution
Delegation turns a bounded task from a primary agent into an isolated child run. The system chooses a route for each task, starts the child with its own session and controls, reports live activity, and returns a bounded result or a clear recovery state. See also Delegated agent workflows.
Delegation request
The delegate_task request is the control point for both new work and live child control. A request can contain one task or a batch. Each task carries its own goal and context, so a child does not rely on the primary agent's conversation history.
The request path applies shared limits before it creates any child:
- A spawn pause blocks new children but does not stop children already running.
- The concurrency limit bounds parallel children inside a call.
- The spawn-depth limit bounds nested delegation. A child becomes an orchestrator only when depth and the orchestrator switch allow it.
- The configured iteration limit is authoritative for child work.
- A one-shot session can have its own total child budget.
list, steer, and stop are synchronous control actions. They do not create new work and bypass the spawn path's pause, depth, and background rules.
References: tools/delegate_tool.py• L551-626 tools/delegate_tool_config.py• L85-177 tools/delegate_tool_registry.py• L264-310
Backend and model routes
The delegation backend answers how each task reaches a model. delegation.backend selects one registered strategy. The built-in default strategy uses the delegation configuration for every task. Other strategies can add task parameters and return a model, provider, endpoint, service tier, fallback chain, or profile route. The strategy selects the route only; core keeps child lifecycle and result handling.
Backend selection is tied to the delegate_task definition built for the session. A saved backend normally takes effect in a new session. An immediate switch rebuilds the tool definition and route together so the task schema and the active backend do not drift apart. An unavailable or unknown backend fails closed instead of silently using another backend.
Each task route follows these broad rules:
| Route choice | Child behavior |
|---|---|
| No provider, endpoint, or model override | Inherit the parent's usable route and credentials. |
| Provider or endpoint override | Build a complete child route for that target and derive its transport mode. |
| Model override | Use the selected model and its route-owned fallback policy. |
| Profile route | Run as the named profile with that profile's model, credentials, policy, and fallback settings. |
| Invalid task parameter or route | Refuse that task while runnable siblings continue. |
Pinned routes do not borrow the parent's fallback chain or endpoint-specific routing filters unless the route declares them. A provider change also causes the child to derive the correct wire mode for that provider. This prevents a child from pairing one provider with another provider's endpoint or protocol.
References: agent/delegation_provider.py• L1-33 agent/delegation_registry.py• L35-134 agent/delegation_backends.py• L1-132 tools/delegate_tool_routes.py• L233-332 tools/delegate_tool_config.py• L425-444 tools/delegate_tool_config.py• L519-621 plugins/…/__init__.py• L1-37
Child-run isolation
Child construction gives each task a fresh agent context, session identity, terminal task, and focused prompt. The child receives the task goal and supplied context. It does not load the parent's conversation files or memory as normal context. It inherits the parent's usable tool capability unless the child role and safety rules remove tools.
The child keeps lineage back to the parent. This lineage supports ownership checks, nested-run depth, interrupt propagation, and result attribution. A profile route binds the target profile for construction, credential use, and conversation. The parent remains in its own profile after the child finishes.
The child starts with a live transcript when the best-effort live-log path is available. This transcript is an operational view for watching work. The child session record and returned summary remain the sources for the run result.
References: tools/delegate_tool.py• L203-360 tools/delegate_tool_child_run.py• L793-822 tools/delegation_live_log.py• L1-18 tools/delegate_tool_routes.py• L118-153
Synchronous execution
Synchronous execution keeps the parent turn responsible for the child result. A batch runs its children in parallel up to the configured limit, waits for all children in that unit, then assembles results in task order. A child that completes first can produce a progress line, but the combined result is returned only after the unit is finalized.
The execution path records a structured entry for each task. The entry distinguishes normal completion, iteration-budget exhaustion, interruption, failure, and timeout. A summary can exist even when the child used all iterations, so exit_reason and truncated carry that distinction.
This flow shows how a synchronous request becomes child results.
flowchart LR
A[Parent delegate_task request] --> B[Validate limits and routes]
B --> C[Build isolated children]
C --> D[Run children in parallel]
D --> E[Collect structured entries]
E --> F[Redact and bound summaries]
F --> G[Return results to parent turn]
References: tools/delegate_tool_dispatch.py• L122-226 tools/delegate_tool_child_run.py• L595-695 tools/delegate_tool.py• L362-426
Background execution
Background execution detaches the child unit from the current parent turn and returns a dispatch handle. The child result later enters the originating session as a new completion event. A batch is one completion unit by default. When independent completions are enabled, tasks in the same group finish together and ungrouped tasks finish as separate units, while all units from one call share one capacity slot.
The system uses background work only when the session has a consumer that can receive a later result. Finite or stateless sessions run the batch synchronously instead. If the background pool is full, the request also falls back to synchronous execution instead of queuing unbounded work.
Background delivery follows this sequence:
- Capture the parent session and routing identity before child construction changes session context.
- Persist a dispatch record and reserve a background slot.
- Run the child unit on the daemon executor.
- Persist the terminal event and place it on the shared completion queue.
- Let the gateway or TUI claim, route, and acknowledge the completion for the owning session.
sequenceDiagram
participant P as Parent turn
participant D as Async dispatcher
participant W as Child worker
participant Q as Completion queue
participant S as Owning session
P->>D: dispatch child unit
D-->>P: delegation id
D->>W: run isolated children
W->>D: structured result
D->>Q: durable completion event
Q->>S: claim and deliver new turn
S-->>Q: acknowledge delivery
References: tools/delegate_tool_dispatch.py• L249-478 tools/async_delegation.py• L811-899 tools/async_delegation.py• L966-1042 gateway/run_notifications.py• L1457-1538
Lifecycle controls
The live registry gives each child an identity, ownership record, status, and control boundary. The primary agent, or an authorized owning UI session, can list children, steer one, or request an interrupt. Steering is queued for the next child iteration boundary. It does not cut an active tool call. If no delivery boundary remains, the completion records the text as missed steering.
Stopping is cooperative. It asks the child and any descendants to stop at a safe boundary, then returns the child's partial assistant text as an interrupted result. Session stop, session close, and explicit lifecycle cleanup also reach detached background units so a session does not leave work without a return address.
The public lifecycle service gives plugins a separate handle-based interface. Its handles are capability-checked and parent-owned. It supports launch, status, wait, cancel, steer, result, and reconnect checks. It is process-local: a process restart cannot reconnect to a live child or start a replacement.
References: tools/delegate_tool_registry.py• L92-157 tools/delegate_tool_child_run.py• L102-138 tui_gateway/methods_subagents.py• L19-128 tui_gateway/session_lifecycle.py• L509-515 tui_gateway/session_lifecycle.py• L818-825 agent/subagent_lifecycle.py• L269-399
Progress reporting
Progress turns child activity into a shared view for the parent, gateway, TUI, and other clients. Lifecycle events identify spawn acceptance, start, progress, tool activity, thinking, streamed text, and completion. Each event carries enough child identity to rebuild the spawn tree and route controls to the right branch.
Live transcripts provide a tail-able record for operators. The TUI can read a bounded tail while the child runs. The live registry also exposes the current tool and tool count. These views are observability aids; they do not replace the final result or authorize a foreign session to control a child.
References: tools/delegate_tool_progress.py• L97-132 tools/delegate_tool_progress.py• L287-421 tui_gateway/…/events.py• L622-660 tui_gateway/methods_subagents.py• L105-128 tools/delegation_live_log.py• L91-175
Result collection
Result collection converts a child conversation into a parent-safe task entry. The entry contains the final summary, status, exit reason, call and token measures, cost, tool trace, and the selected route when a backend supplied one. Failures carry a classified reason when the child loop provides one.
An optional output schema is a result contract, not a reason to discard work. The child gets one bounded correction retry. If the answer still fails validation, the raw summary returns with schema_valid: false and schema errors so the parent can judge it. Large summaries are trimmed to protect the parent's context, with the full text spilled to a readable cache file when possible.
Finalization also records memory notification, lifecycle stop hooks, child cost rollup, file-change warnings, and background-process accounting. Child resources are then closed, credentials are released, kernels are shut down, and the child leaves the parent's active-child set.
References: tools/delegate_tool_child_run.py• L520-561 tools/delegate_tool_child_run.py• L595-695 tools/delegate_tool_results.py• L163-209 tools/delegate_tool_results.py• L281-428 tools/delegate_tool_child_run.py• L1044-1146
Recovery and failure handling
Delegation treats route errors, child errors, stalled work, owner loss, and delivery failure as different conditions. A route error can refuse one task without blocking its siblings. A child error becomes a failed result. A frozen child is interrupted after a progress-based quiet period and can be force-finalized as stalled. A configured child timeout measures inactivity rather than total run time.
Background state is durable enough to recover the completion, not to continue the child after process exit. The ledger records dispatch and completion state. If the owner process disappears, recovery marks the unit unknown and includes any child results recorded before the loss. Startup replay and periodic orphan sweeps offer pending completions again. Delivery claims, bounded retries, and terminal drop states prevent duplicate or endless delivery.
When a child has no API call at timeout, the system writes a diagnostic with the child configuration, prompt and tool sizes, activity state, and thread stacks. This gives an operator a path to distinguish setup or transport failure from a slow model response.
References: tools/delegate_tool_child_run.py• L206-257 tools/delegate_tool_child_run.py• L841-1021 tools/async_delegation.py• L282-331 tools/async_delegation.py• L334-445 tools/async_delegation.py• L1081-1198
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the session-pinned delegation backend and its task schema in step. A route change without a tool-definition rebuild can refuse valid task parameters.
- Keep route-owned provider, endpoint, protocol mode, credential pool, and fallback policy aligned. A partial override can send a child to an endpoint that does not serve its provider.
- Keep async dispatch, durable ledger rows, completion claims, and owner-session routing aligned. A new completion field or state must survive restart replay and delivery retry.
- Keep child lifecycle event names and payload identity fields aligned with the gateway contract and generated client types.
- Keep every stop and close path connected to detached background units. A foreground-only interrupt leaves work running after its session ends.
- Keep child cleanup after result accounting. Moving cleanup earlier can hide handed-off processes, unread completions, or the child's final resource state.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Selected backend is missing or unavailable | No child starts, and the request does not silently switch routes. | Backend availability check fails closed. |
| Task uses a parameter not declared by the session's backend | That task is refused while valid siblings can run. | Backend schema and route validation use the same session-pinned backend. |
| Background work has no later-result consumer or the pool is full | The request runs synchronously and returns its result in the current turn. | Async admission checks session delivery support and capacity. |
| Child makes no progress past the idle or in-tool threshold | The child is interrupted and may end as a stalled result. | Progress tokens, heartbeat monitoring, and a grace window. |
| Owning process exits during a background unit | The outcome becomes unknown, with already recorded child results retained. | Durable ledger recovery and bounded replay. |
| Session stop or close removes the return address | Detached children are interrupted and return partial interrupted results. | Session lifecycle calls the async interruption path. |
| Output exceeds the parent context budget | The parent receives a bounded head-and-tail summary instead of an oversized prompt. | Summary budget and optional full-output spill file. |
Key files
| File | Why to read it |
|---|---|
| tools/delegate_tool.py | Main request validation, route use, child construction, and batch handoff. |
| tools/delegate_tool_routes.py | Per-task backend route resolution and profile routing. |
| tools/delegate_tool_config.py | Delegation limits and child credential, transport, reasoning, and fallback resolution. |
| agent/delegation_provider.py | Contract between a delegation backend and core lifecycle code. |
| agent/delegation_backends.py | Saved versus session-pinned backend behavior. |
| tools/delegate_tool_dispatch.py | Synchronous fan-out, background units, capacity fallback, and result aggregation. |
| tools/delegate_tool_child_run.py | One child run's heartbeat, timeout, result entry, and cleanup lifecycle. |
| tools/async_delegation.py | Background registry, durable completion, delivery claims, recovery, and stall handling. |
| tools/delegate_tool_progress.py | Child event relay and progress identity used by clients. |
| tools/delegate_tool_results.py | Summary limits, schema result handling, hooks, memory notification, and cost rollup. |
| tools/delegate_tool_registry.py | Live child ownership and list, steer, and stop controls. |
| gateway/run_notifications.py | Gateway completion routing and delivery for background results. |
| tui_gateway/methods_subagents.py | Session-scoped live child views and control RPCs. |
| agent/subagent_lifecycle.py | Public plugin lifecycle interface and its process-local handle rules. |