Sub-agents
A sub-agent is a second agent loop that a running agent starts through the agent tool. It has its own context (fresh, or a fork of its parent's), its own limits on tools and permissions, and often a cheaper model. Only its final report comes back. The parent stays focused: a codebase search that reads forty files costs the parent one tool result instead of forty, and independent work, such as reviewing three modules, runs in parallel.
The code lives in subagent.zig (profiles, the tool, children), on top of Turn.zig (the asynchronous loop) and Scope.zig (per-agent context and policy).
The agent tool
agent is on the turn-1 tool list whenever the current agent may spawn (about 330 tokens; "subagents": false removes it):
| Input | Meaning |
|---|---|
task |
complete instructions; a fresh sub-agent sees nothing else |
description |
3–6 words shown to the user |
type |
an agent profile (default general) |
context |
fresh (default) or fork |
background |
return at once; the report arrives later as a message |
isolation |
worktree: work in a separate git worktree |
output_schema |
a JSON Schema the final report must match |
to + task |
a follow-up for an agent this session started |
to + stop: true |
stop that agent |
Several agent calls in one step run in parallel, like any tool calls, and their results are recorded in request order.
The report. The child's final assistant text, inside a taint frame (it was written after reading untrusted data, so it is evidence for the parent, not instructions), followed by a footer outside the frame:
<untrusted-data source="agent:explore">
The retry decision is in src/llm.zig:378-407 (Op.finished) ...
</untrusted-data>
[agent explore · end_turn · 14 steps · 61k in (48k cached) / 3.2k out · $0.04 · id s_18eca4…]A child that reaches its step budget gets one more step, without tools, to write its report (stop reason max_steps). A failed or cancelled child returns is_error with whatever text it produced. With output_schema, the child is told to end with JSON matching the schema, and the footer notes when the report is not valid JSON.
The child's system prompt starts with a sub-agent preamble (the parent sees only the final message; there is no one to ask; end with a self-contained report giving paths and line numbers, what changed, how it was verified, what is unresolved), then the usual taint policy, <env> (including the child's effective permissions), AGENTS.md and plugin prompt sections, and finally the profile's instructions.
Agent profiles
A profile is a named recipe for a child, written as Markdown with a frontmatter block:
---
description: Reviews a diff for correctness bugs
tools: [read, bash, mcp__github__*]
mode: read-only
model: openai/gpt-6.2-sol
effort: low
max_steps: 30
---
You review; you never edit. Quote the lines you rely on.| Field | Default | Meaning |
|---|---|---|
name |
file stem | [a-z0-9_-]+ |
description |
required | listed in the agent tool's description |
tools |
the parent's tools | allowlist; * globs match MCP and plugin tools. Plugin and MCP tools named exactly are pre-activated in the child's session |
mode |
inherit |
a ceiling: read-only < ask < auto |
model, effort |
inherit |
the main cost lever |
max_steps |
50 | the child's step budget |
spawn |
false |
may it start sub-agents (still bounded by subagent_max_depth) |
context |
fresh |
default context mode |
isolation |
none |
worktree by default |
background |
false |
run in the background by default |
network |
true |
false turns network off for its shell and MCP children |
| body | — | appended to the child's system prompt |
Profiles come from built-ins, then ~/.config/oi/agents/*.md, then .oi/agents/*.md; a later one replaces an earlier one of the same name. Plugins add more with oi.registerAgent({name, description, prompt, tools, mode, model, effort, max_steps, context, isolation, background, spawn, network}); they belong to the plugin's handle and are swept when it unloads. Profiles load when the kernel opens and on /reload, so the agent tool's description stays byte-stable for a session's prompt cache. A project profile is a repo-controlled prompt, at the same trust level as the project's AGENTS.md; it cannot raise permissions.
Built-ins:
general: the parent's tools (minusagent), permissions and model.explore:read,grep,glob,bash,tool_search,codemode,web_fetchandweb_search, read-only, low effort, 40 steps. A read-only agent normally gets no shell.exploredoes, because a read-only profile has no write roots: its shell runs in the OS sandbox with nothing writable but$TMPDIR, so read-only holds whatever the command does. Without an OS sandbox (Windows,sandbox=off) it has no shell.
Context: fresh and fork
fresh: the child's session starts empty. Its first event is the task as a user message.fork: the child's session is created with its head on the parent's assistant event that contains theagentcall.Store.pathwalks parent ids across sessions, so the child's context is the parent's whole conversation without a single copied event. Its first own event is the result of that call: "you are now a forked sub-agent; your task is …". The other tool calls of the same assistant turn get "handled by the parent" results. A fork uses the parent's model, system prompt and tool list byte for byte, so its first request is a prompt-cache hit on everything the parent already sent. Theagenttool stays listed (to keep that prefix identical) but dispatch refuses it at the depth limit.
Foreground, background and follow-ups
- Foreground (default): the parent's tool call settles when the child finishes.
- Background: the call returns at once with the agent's id. When the child finishes, its report is delivered to the parent session as an
agent_reportevent: at the parent's next step boundary when the parent is running, or by starting a turn on an idle parent. The model sees it as<agent-report id=… agent=… status=…>with the report taint-framed. One-shot (-p) and line mode wait for background agents (and the session's reaction) before returning. The terminal UI keeps them running while the prompt is idle, and the daemon and ACP server do so between requests. A background child's cancel token chains to the kernel's root token, not to the parent's turn, so cancelling the parent's foreground work leaves it running. - Follow-ups:
agent {to: id, task}sends a running child a message, appended as asteerevent at its next step boundary. A finished child's session continues with a new turn.agent {to: id, stop: true}cancels it; its partial report follows.
When a parent is compacted, the summary request lists its running background agents, so the summary keeps track of reports still to come.
Worktree isolation
With isolation: "worktree" the child runs in a new git worktree, <data>/worktrees/<repo>/<child id> on branch oi/<child id>, with that worktree as its cwd and only write root. When it finishes, the report gets the worktree's commits and git diff --stat, and a worktree without changes is removed together with its branch. Parallel writers should use worktrees or disjoint files.
Permissions and approvals
A child's effective policy is computed from its chain of scopes:
parent ask |
parent auto |
parent read-only |
|
|---|---|---|---|
profile inherit / auto |
ask | auto | read-only |
profile ask |
ask | ask | read-only |
profile read-only |
read-only | read-only | read-only |
The mode is evaluated live, so Shift+Tab in the terminal UI applies to running children too. The tool allowlist intersects down the chain and is enforced twice: tools outside it are left out of the child's tool list, and dispatch refuses them ("write is not available to the explore agent"), so a guessed tool name still fails. Write roots only shrink (except a worktree agent's, which are its fresh worktree), and network only turns off.
Approvals from a child go to the same client, labelled with the agent ([explore · find retry logic] bash: rg -n backoff src/). They are asynchronous: other agents keep running while one waits, a cancelled agent's request is withdrawn, and "always allow" saves a permission rule that applies kernel-wide and in later sessions. before_tool hooks (plugin and shell) see every child call with session_id, agent, depth and parent_session_id, so a policy can be stricter for children. stop hooks run for children too (the payload names the agent). Permission rules apply to children as to their parent, inside the child's narrower ceiling.
Limits, cancellation and cost
subagent_max_parallel(default 6): running children kernel-wide; the rest wait in a FIFO and show as queued.subagent_max_depth(default 1): children cannot spawn children unless a profile setsspawn: trueand the depth allows it. At the limit theagenttool is not offered (except to forks), and dispatch refuses it.- Loop only: Codemode scripts and plugins cannot call
agent. budget_usd: a root turn stops at its next step boundary once the estimated cost of its tree passes the budget (stop reasonbudget); its children stop at theirs.- Cancellation: cancelling a turn (Ctrl+C or Esc twice in the UI, ACP
session/cancel,POST /session/{id}/cancel) cancels the foreground children it waits on, and their model streams, shell commands and Codemode scripts stop./agents stop <id|all>stops background children. - Cost: a child's usage is added to its parent's turn when it finishes, so turn footers and
TurnResultshow the tree's cost. Eachtool_resultof anagentcall records the child's id and usage.
Storage
A child is an ordinary session in the store with three extra columns: parent_session, spawn_event (the parent's agent_spawn event) and agent. On the parent's path:
assistant tool_use {id: t1, name: agent, input: {type: explore, task: …}}
agent_spawn {call_id: t1, child: s_c1, agent: explore, description, context, background, worktree, model}
tool_result {tool_use_id: t1, content: <framed report + footer>, child: s_c1, usage: {steps, tokens_in, tokens_out, cache_read, cost_usd}}
agent_report {agent_id, agent, description, status, report, footer, usage} (background)oi sessions, -c and /resume list root sessions only. oi log <session> shows agent_spawn events in the tree and lists the session's sub-agents; oi log <child> shows a child's own tree (a fork's tree hangs off its parent's event). Rewinding the parent past a call leaves the child on the abandoned branch. Checkpoints (format version 3) export a session with all its descendants and the file snapshots they recorded, and import restores the links. Rewinding the parent restores the files its sub-agents changed, too. Replay answers recorded agent calls from the recording, re-delivers recorded background reports at the same points, and with --deep re-runs each child's loop from its own recorded session.
Clients
Every kernel update carries its session's lineage: parent_session_id, parent_tool_id (the parent's agent call), root_session_id, agent and depth. Children emit agent_start (with the task), agent_end (with the stop reason and usage) and agent_status (queued); root turns emit turn_start and turn_end.
- Terminal UI. An
agentcall renders as a◆block with one live status line: the child's latest tool call and count while it runs, its stop reason, tokens and cost at the end. A child's text stays out of the transcript./agentslists profiles and the session's sub-agents with their state. - Line mode and
-p. One dim line per child start, tool call and finish, indented by depth. - ACP v2. Each child is a child session.
subagent_updateannounces it on the parent (title, description,capabilities.cancel, state) before anything carries its id. The parent'sagenttool call getssessioncontent linking to it, and the task is reported as asession_messagefrom the parent. The child's messages, tool calls andstate_updates use its own sessionId, its idle state is mirrored onto the parent'ssubagent_update, and running background children are listed in the parent'sstate_update.background. Permission requests carry the asking child's sessionId. A child accepts onlysession/cancel; prompts and config changes are refused with-32602. The parent'susage_updatecost includes its descendants. - HTTP + SSE. Events carry the lineage fields;
GET /events?session=<root>includes the root's sub-agents;GET /session/{id}/childrenlists them with their state. - C ABI. The callback's
struct oi_updatecarries the lineage fields;oi_session_infoandoi_session_childrenread the links;oi_set_approvalinstalls an approval callback that also receives children's requests.
How other harnesses do it
Surveyed in late November 2026; Vercel fx is the closest analogue, as another native Zig harness.
| Harness | How the parent calls a child | Context | Background | Depth | Child approvals | Storage |
|---|---|---|---|---|---|---|
| Claude Code | Agent {description, prompt, subagent_type, model?, run_in_background?, isolation?} |
fresh; fork inherits history and cache | yes; default for custom agents | 3 | shown in the parent, labelled | one JSONL per child |
| Codex CLI | spawn_agent plus a mailbox (send_message, wait_agent, list_agents, interrupt_agent) |
forks all turns by default | yes | 1 | shown in the parent's overlay | thread |
| OpenCode | subagent {agent, description, prompt, model?, sessionID?} |
fresh | always | 1 | the child's own rules | session with parentID |
| fx | subagent run / message / stop / close |
own conversation | yes | 2 | shown in the parent; grants shared | inside the parent session |
DeepSeek dsh |
subagent plus control tools; optional outputSchema |
spawn or fork | yes | 1 | rejected automatically | durable session plus a catalog over the parent's events |
| Gemini CLI | one tool per agent | fresh | — | no nesting | policy engine | — |
| Cursor | Task | fresh | opt-in | 2 | inherited | ~/.cursor/subagents |
| Goose | delegate |
session context | parallel, max 10 | no nesting | autonomous mode only | inline |
| Pi | example extension; a process per child | fresh | parallel, 4 at a time | — | — | tool details |
What oi shares with most of them: children are ordinary sessions linked to their parent; fresh and fork modes, with forks keeping the cached prefix byte-identical; permissions that only narrow; depth 1 and a concurrency cap by default; reports rather than transcripts; and background children whose reports arrive as messages instead of being polled. ACP v2 models exactly this shape, which is why oi rpc maps children onto ACP child sessions one to one.
What is particular to oi: forks are copy-free because a session's head can point into another session's event tree; the explore agent's read-only shell is enforced by the OS sandbox rather than by instructions; approvals are shown to the user rather than rejected, which is safe because no oi tool lets a child block on a question to the user; and replay --deep compares plugin policy inside recorded children.
Testing
The mock provider routes script lines by agent: a line with "agent": "explore" answers that sub-agent's requests, and lines without it answer the root. "delay_ms" settles a response later, so parallel children and concurrent sessions finish in a known order. agent_tests.zig covers interleaved root turns, policy narrowing, parallel children in request order with usage roll-up, cancellation reaching every child, the concurrency queue, and asynchronous approvals. The "Sub-agents" section of tests/e2e.sh covers the CLI end to end: parallel children, a refused write, fork prefixes, background delivery, the depth limit, profile files and step budgets, worktrees, oi log, checkpoints, replay --deep and plugin profiles, plus ACP child sessions in the ACP section.