Runtimes and CLI
A runtime is an adapter that turns one request into a stream of events by driving an agent. The platform defines the port in packages/agent-types; adapters implement it; every adapter is wrapped by the decorator stack. The only production adapters are ClaudeRuntime (the readonly profile, in the API and the session workers) and SandboxRuntime (the sandbox profiles, in the factory worker). Both drive the Claude Code CLI as a subprocess through the Claude Agent SDK (@anthropic-ai/claude-agent-sdk).
The runtime port
Capabilitiesis{fileTools: boolean}; the source says it is "extended additively when a runtime needs more; no speculative flags".RuntimeRequest.requireslists capability names the caller needs. A runtime that lacks one answersunsupported_capability.RuntimeContexthas no environment field: adapters own their subprocess environment.grantscarries gateway-compiled MCP grants for the turn (absent means no MCP tools).requestIdis opaque; retrying callers append#<attempt>.
Events and status
| Event | Fields |
|---|---|
text_delta | text |
tool_call | id, name, input |
tool_result | id, output, isError |
result | result: {text, usage, status} (terminal, exactly one, last) |
RuntimeStatus is one vocabulary: success, aborted, agent_limit, timeout, agent_failed, disabled, budget_exhausted, internal_error, invalid_request, unsupported_capability. Every non-success value is also an ErrorCode, so there is no mapping table in the runtime. The HTTP mapping is "Table S" on REST API. usage is {inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, costUsd?}.
Profiles
ProfileName | Runs in | Tools | Notes |
|---|---|---|---|
readonly | ClaudeRuntime (API, session workers) | Read, Glob, Grep | path-confined by a pre-tool hook |
sandbox-spike | SandboxRuntime in a per-job container | Bash, Read, Glob, Grep, Edit, Write | P2.5 spike set |
factory-planner | SandboxRuntime | Read, Glob, Grep | writes plan.md |
factory-coder | SandboxRuntime | Bash, Read, Glob, Grep, Edit, Write | writes patch.diff |
factory-reviewer | SandboxRuntime | Read, Glob, Grep | writes review.json |
ClaudeRuntime refuses every profile other than readonly with unsupported_capability; the factory and spike profiles run only in apps/sandbox-runner inside the per-job container. The sandbox side is on Sandbox roles and Sandbox security.
ClaudeRuntime (packages/agent-runtime-claude)
Public entry: ClaudeRuntime, createClaudeRuntime, constants GATEWAY_UNAVAILABLE, MAX_TTL_MS, REVOKE_TIMEOUT_MS, SESSION_ROLE_POLICY, sweepStaleHomes, and the types ClaudeRuntimeDeps, GatewayMode, QueryFn. SDK types stay out of the public API by convention. The subpath @agentforge/agent-runtime-claude/mapping exports mapMessage and mapResult for apps/sandbox-runner only, because its signatures carry SDK types; the API never imports it.
capabilities is {fileTools: true}. ClaudeRuntimeDeps is a query function plus exactly one of:
| Mode | Dependency | Use |
|---|---|---|
| key mode | apiKey (direct to Anthropic) | tests with a mocked query; refused by every production config |
| gateway mode | gateway: {baseUrl, control, ttlMarginMs, maxOutputTokens} | production for the API and the workers (FL-1, FL-2) |
run() sequence
Early exits yield a terminal result with zero cost: unsupported_capability, aborted, invalid_request (text invalid grants, workspace refused: <reason> or timeoutMs + ttlMarginMs must be <= 900 s), and internal_error with text gateway_unavailable when registration fails (nothing was spent; the HTTP status message is not forwarded).
The SDK options for readonly
readonlyOptions fixes these options (source comments mark two behaviours as unverified, below):
| Option | Value |
|---|---|
model | req.model |
cwd | ctx.workspace |
tools | Read, Glob, Grep only |
allowedTools | those three plus the turn's granted MCP hook tools |
disallowedTools | every SDK built-in tool name not in the read set, plus Task (belt and braces) |
permissionMode | dontAsk, with permissionPrompts: 'none' |
settingSources | [] (no user, project or local settings) |
persistSession | false |
maxTurns, maxBudgetUsd | ctx.limits |
env | replaces process.env entirely (see below) |
strictMcpConfig and mcpServers.agentforge | only with grants: an HTTP MCP server at the granted URL |
hooks.PreToolUse | the path-confinement hook, no matcher, onFailure: 'block' |
The CLI environment is closed: PATH, HOME (a fresh temporary directory), then the auth variables. In key mode that is ANTHROPIC_API_KEY. In gateway mode it is ANTHROPIC_BASE_URL (the gateway data URL), ANTHROPIC_API_KEY set to the per-turn job token, CLAUDE_CODE_MAX_OUTPUT_TOKENS, and the four flags CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, DISABLE_TELEMETRY, DISABLE_ERROR_REPORTING, DISABLE_AUTOUPDATER, all 1. With MCP grants the job token is also exported as AGENTFORGE_JOB_TOKEN and the MCP header references ${AGENTFORGE_JOB_TOKEN}, so the token never appears in argv (which is world-readable through ps). The gateway's model and path allowlists were frozen for this exact environment (SB-ENV1), which is why CLAUDE_CODE_MAX_OUTPUT_TOKENS must not exceed the gateway cap (GATEWAY_MAX_OUTPUT_TOKENS, default 8192): a larger max_tokens is refused with 403.
Tool and workspace confinement
packages/agent-runtime-claude/src/tool-policy.ts confines the readonly profile.
- Workspace audit (
auditWorkspace, once per run, never cached): walks the workspace without following symlinks. It refuses the workspace when any symlink (dangling or not) resolves outside it, when the walk exceeds 20,000 entries (maxEntries), or when the workspace cannot be read. The result carrieshasSymlinks. - Pre-tool hook (
preToolUseHookcallingtoolDenyReason): denies any tool not in the allowed set (the three read tools plus grantedmcp__agentforge__*names). MCP tools are allowed through an explicit branch before path logic; the gateway re-checks grants. ForRead,file_pathmust stay inside the workspace; forGlobandGrep,path,pattern(Glob) andglob(Grep) must too. - Path rules: any
..anywhere, any backslash, a leading~, an empty or non-string value is denied. Paths are resolved withrealpathof the deepest existing ancestor and a dangling symlink target is followed; a dangling target containing..is denied. For globs only the static prefix is resolved; if the workspace has any symlink, a wildcard in the first segment, in a non-final segment, or**is denied. - The hook fails closed twice: a policy error becomes a deny, and a hook failure is blocked by the CLI through
onFailure: 'block'. On allow it returns no decision so the rest of the permission pipeline still applies.
Gateway-mode constants
| Constant | Value | Meaning |
|---|---|---|
MAX_TTL_MS | 900000 | the gateway's own TTL bound |
GATEWAY_TTL_MARGIN_MS (apps) | 60000 | job token TTL = timeoutMs + margin (300 s turn gives 360 s) |
REVOKE_TIMEOUT_MS | 1000 | bound of the finally revoke; the TTL and the settled ledger row are the backstop |
SESSION_ROLE_POLICY | session-readonly | role policy every session turn registers with |
GATEWAY_UNAVAILABLE | gateway_unavailable | result text of a turn whose registration failed; the session activity turns it into a retryable failure |
HOME_SWEEP_MS | 5000 | delay of the second HOME removal, for a CLI child that outlived the stream |
sweepStaleHomes | removes agentforge-claude-home-* older than 3,600,000 ms | startup sweep after a SIGKILL; never throws |
The API holds the API control token and the worker holds the worker token; the gateway pins registrations made with the API token to role session-readonly, to request ids of the form api/<uuid> and to ledger rows without a job id. See Job tokens and policies.
Result mapping
mapResult maps the SDK result message: subtype success with no error gives success and the result text; error_max_turns and error_max_budget_usd give agent_limit; subtype success with is_error true (the turn ended on an API error, for example a gateway 429) and every other subtype give agent_failed. Usage is summed over modelUsage when present, else taken from the top-level usage, with costUsd from total_cost_usd. mapMessage turns assistant text blocks into text_delta, tool_use blocks into tool_call, and user tool_result blocks into tool_result; all other SDK message types are ignored. The SDK emits no result on abort, so an abort or a silently dead CLI yields a synthesized aborted or agent_failed result from the adapter.
Unverified in the source
The source comments record items not confirmed by a real run: whether allowedTools auto-approves paths outside cwd (q1, hence the hook), whether canUseTool stays unused under dontAsk (q2, hence permissionPrompts: 'none'), and that the CLI fires the PreToolUse hook for Glob and Grep and the denial text the model sees (q3). For session turns, whether the CLI sends a beta or field outside the gateway's frozen allowlist was an open check (FL-RT5) in the fleet design.
SandboxRuntime (apps/worker/src/sandbox)
The factory worker's runtime for the profiles sandbox-spike, factory-planner, factory-coder, factory-reviewer. It is implemented in the worker app, not in the adapter package. It also reports capabilities: {fileTools: true}. In short, per run it registers a gateway job under the role policy factory-<role>, creates an isolated per-job Docker network, a tmpfs workspace volume and a keeper container, streams the workspace in, runs the sandbox image with the runner reading one JSON job spec on stdin, treats stdout as untrusted NDJSON events, polls the kill switch (default every 2000 ms), tars exactly one out file back through the keeper, and tears everything down. The details, the argv contract, resource limits and the keeper model are on Sandbox roles and Sandbox.
FakeRuntime
FakeRuntime (packages/agent-core/src/testing) is a configurable runtime used by decorator and API tests. It records every call (request, context, ms until abort) and its behavior option selects normal (tool call, tool result, text, result), throw, hang, ignore-abort, empty. costUsd defaults to 0.01 and is clamped to maxBudgetUsd (giving agent_limit) unless enforceBudget is false; extraResult emits a second result as a protocol violation for negative tests.
Conformance suite
runRuntimeConformance(name, options) registers a vitest suite that every runtime adapter must pass. options.make(scenario) returns a runtime for the scenario normal, hang (emits one non-terminal event, then runs until aborted) or expensive (would exceed maxBudgetUsd if not stopped).
| Check | Requirement |
|---|---|
eventsAndUsage | events match the union, exactly one terminal result, Usage parses, status success |
abortWithinOneSecond | after an abort at 100 ms the stream ends within 1000 ms with status aborted |
refusesUnsupportedProfile | an unknown profile (default never-a-profile) yields unsupported_capability |
refusesMissingCapability | only registered when the runtime lacks a capability: a requires it cannot satisfy yields unsupported_capability |
enforcesOrRefusesBudget | with maxBudgetUsd = 0.001 the status is agent_limit or unsupported_capability |
consumerBreakAbortsAndSettles | breaking out of the stream aborts the inner within 1 s and the ledger row is settled aborted (checked through withBudget and a FakeLedgerStore) |
The suite is run against FakeRuntime (packages/agent-core/test/conformance.test.ts) and against ClaudeRuntime with a mocked query (packages/agent-runtime-claude/test/runtime.test.ts). The SandboxRuntime has its own test files in apps/worker/test (sandbox.test.ts, sandbox-p3.test.ts).
Not verified
Everything here is read from source. The real-key behaviour of the CLI with the gateway (FL-RT5 betas and fields, FL-RT6 worst-case debit versus reservation) is tracked as evidence to collect in docs/design-worker-fleet.md.
Sources
packages/agent-types/src/index.ts(AgentRuntime,Capabilities,RuntimeRequest,RuntimeContext,RuntimeEvent,RuntimeStatus,ProfileName,assertSingleTerminalResult)packages/agent-runtime-claude/src/runtime.ts(ClaudeRuntime,readonlyOptions,mapResult,mapMessage,sweepStaleHomes,createClaudeRuntime)packages/agent-runtime-claude/src/tool-policy.ts(auditWorkspace,toolDenyReason,preToolUseHook,READONLY_TOOLS)packages/agent-runtime-claude/src/index.ts,packages/agent-runtime-claude/src/mapping.tspackages/agent-core/src/testing/conformance.ts,packages/agent-core/src/testing/fake-runtime.tsapps/worker/src/sandbox/contract.ts,apps/worker/src/sandbox/sandbox-runtime.tsapps/sandbox-runner/src/runner.ts(ROLE_TOOLS,sandboxOptions)apps/api/src/runtime.ts,apps/worker/src/runtime.tsdocs/design-worker-fleet.md(sections (a), (e))