Skip to content

Subagents (Containment, Admission, Budgets & Exit Gates) ​

Want a step-by-step tutorial first?

Start with the Hands-On Guide to Subagents for practical prompts, /subagent-config setup, parallel multi_task fan-outs, quorum reviews, live steering, resuming, and token-breakdown audits.

Uncontrolled subagents are one of the fastest ways for an autonomous session to go sideways: a worker spawns invisible nested agents using its own vendor CLI, burns through an unbounded token or dollar budget, ignores concurrency caps, or finishes cleanly while its summary vanishes into a truncated stdout buffer.

Kompile treats subagent delegation as a strictly governed execution contract enforced identically across native (kompile), managed CLI (claude, codex, gemini, opencode, agy, pi, qwen), and server-backed runners.


1. Delegation Primitives ​

ToolPatternWhen to use
taskSingle child workerFocused research, module implementation, or targeted audit
multi_taskParallel fan-outIndependent subtasks (e.g. auditing multiple packages, tests + docs)
quorum_taskMulti-voter consensusIndependent verification / review where agreement across voters matters
task_transcriptLive & historical inspectionRead-only parent/child task tree and output tails from .kompile/task-registry/
subagent_resumeCross-agent continuationResume any durable child conversation (subagent-…) with the same or another agent

Every child launch records its parent, live process log, and transcript under .kompile/task-registry/. Inside kompile chat, you can press ↓ from a blank prompt to browse running and recent subagents in the Process & Subagent Browser below the input box — press Enter to inspect a child's live transcript, type to send it a direct follow-up, or press Delete to cancel it (see Monitors & Process/Subagent Browser).


2. Fail-Closed Vendor Containment (SubagentContainment) ​

Blocking Kompile's own MCP delegation tools inside a child (SubagentDelegationGuard) is only half the problem: external vendor CLIs ship their own native sub-agent tools that never pass through Kompile's MCP server.

Kompile enforces fail-closed containment across every supported vendor:

VendorNative delegation tools blockedLaunch-time control applied by Kompile
Claude CodeTask, Agent--disallowedTools strips both tools at launch
Codexspawn_agent, send_input, resume_agent, wait_agent, close_agent-c features.multi_agent=false -c features.multi_agent_v2=false
Gemini CLIExperimental sub-agentsexperimental.enableAgents=false injected via system settings (outranks user & workspace settings)
OpenCodetaskpermission.task=deny via OPENCODE_CONFIG_CONTENT plus guard plugin (blocks per-agent overrides)
Antigravity (agy)invoke_subagent, define_subagent, manage_subagents, browser_subagent, send_message, schedule, swarmKompile-owned PreToolUse deny hook loaded via --add-dir (.agents/hooks.json)
PiExtension-added sub-agents--no-extensions (only Kompile's explicit -e MCP adapter loads)
Qwen Codeagent--exclude-tools agent
Unknown vendor(unverified)Refused as a child — Kompile will not launch a vendor whose native delegation surface it cannot contain

Launch-time controls are backed by stream-level enforcement (SubagentContainment.violation): if a child's output stream ever shows a forbidden native delegation tool anyway, the harness terminates it immediately.


3. Two-Layer Admission & Route Policy (SubagentAdmission) ​

Before any child launches, SubagentAdmission enforces non-blocking admission across the JVM:

  1. Route validation — checks glob model bans (e.g. banning expensive models for subagents via /subagent-config ban *opus*) and applies saved failover routes when a route hits quota limits or errors.
  2. Session token tally (SubagentSessionTally) — rejects launches once the parent session's subagents have spent defaultSessionTokenBudget billed-equivalent tokens.
  3. Process-wide cap (maxConcurrent) — bounds total active children across all chats in the process.
  4. Per-session cap (maxConcurrentPerSession) — ensures one session's multi_task fan-out cannot starve other sessions sharing the host.

All limits persist in ~/.kompile/config/subagent-config.json and are tuned live with /subagent-config:

text
/subagent-config status
/subagent-config max 4                  # process-wide concurrency cap (0 disables, unlimited clears)
/subagent-config ban *opus*             # glob-ban models for subagents
/subagent-config budget 500000          # per-run billed-equivalent token budget
/subagent-config ceiling 120000         # per-request context ceiling (off disables)
/subagent-config time 15                # per-run active model-turn limit in minutes (off disables)
/subagent-config failover               # configure fallback routes & thinking effort
/subagent-config autoresume             # auto-resume a worker that died without posting its report

4. The Four-State Budget Machine (SubagentBudget) ​

Every subagent lane feeds five limits into a single monotonic enforcement state machine evaluated between model turns:

LimitWhat it measures
Token budgetCumulative usage — default BILLED_EQUIVALENT = input + cache_write + output + 0.1 * cache_read (mirroring Sonnet-class cache-read pricing), or RAW
Active runtimeTime spent inside model turns only (tool execution and idle waits do not count), carried across resumes
Session totalParent session's shared SubagentSessionTally
Context ceilingSize of the last request's context window (relaxed automatically after compaction)
Cost budgetCumulative USD on priced requests (PER_TOKEN only; unpriced/plan requests never move it)

State Transitions ​

text
  NORMAL (< 90% of all limits)
     │
     ▼  any limit reaches 90%
  WARN
     │  next outbound turn carries a reminder to wrap up & post progress report
     ▼  any limit reaches 100%, OR projected next request + 2 finalize turns cross budget
  CHECKPOINT (wind-down)
     │  all tools DENIED except: write, edit, progress
     ├─ child posts progress report ─▶ clean stop (BUDGET_EXHAUSTED)
     ▼  token/runtime/session limit exceeds 115% margin without a report
  HARD_STOP
        immediate stop (BUDGET_EXCEEDED_NO_REPORT — orchestrator salvages transcript)

Notice why CHECKPOINT reserves FINALIZE_REQUESTS = 2 (the progress post + the final reply): a subagent running out of budget gets a graceful wind-down window to save its work and post its structured summary rather than dying mid-thought.


5. Mandatory Progress-Report Exit Gate (SubagentReportGate) ​

A subagent's final chat message can be dropped, truncated, or buried during compaction. Kompile enforces a shared exit gate on every task, multi_task, and quorum_task worker:

  1. Every child receives a standing instruction to call progress with action=post (findings, changes, open items, blockers) before exiting.
  2. If the child attempts to finish without posting a report, Kompile holds its exit and re-prompts it (up to MAX_REMINDERS = 2):
    • Native (kompile) children continue in the same in-process conversation.
    • Managed CLI children (claude, codex, gemini, opencode) are resumed in their own CLI session.
    • Server-backed children receive a follow-up carrying their final answer.
  3. Posted reports land in the parent session's throwaway report log (~/.kompile/conversations/<sessionId>.progress.jsonl, newest 50 kept) tagged with source=subagent and run_id=<task-id>.

Inspect results and token efficiency anytime:

text
/progress-reports [n]              # latest n reports (main + subagents)
/progress-reports-subagents [n]    # latest n subagent reports only
/subagent-breakdown <id>           # where the child spent tokens: startup, skills, tool schemas, results

Released under the Apache-2.0 License.