Agent protocol
An agent provider implements these JSON-RPC methods. Every method takes an object with agentId (the host adds it) plus the fields below. A JavaScript plugin registers an agent with api.agents.register (ui-plugins.md, Agents): the host calls the handler of the same name on it (list_options or listOptions), and emit(event) sends the agent/event notifications below. The official providers (Codex, Claude Code, OpenCode and ACP) are such plugins; see "Providers in JavaScript" below. No provider is a native program (process-plugins.md).
| Method | Params | Result |
|---|---|---|
agent/initialize |
{ hostFeatures? } (Host features, below) |
AgentInfo |
agent/list_options |
{ workspace } |
{ options: ConfigOption[] } |
agent/list_commands |
{ sessionId } |
{ commands: SlashCommand[] } |
agent/list_sessions |
{ workspace } |
{ sessions: [{ id, title?, createdAt?, updatedAt? }] } |
agent/read_session |
{ workspace, sessionId, version?, tasks? } |
{ items: TranscriptItem[], aliases?: { itemId, nativeItemId }[], echoes?: NativeEcho[], streamed?: { nativeItemId, streamedItemId }[], version?, omittedTasks? }; a provider may leave a settled subagent's transcript unread unless tasks names it: its task item comes with no items, its id in omittedTasks, and the host keeps the items it has; identities are positively observed native metadata. version is what the provider saw of its record (a file's size and time, an update stamp), taken before reading; the host passes back the one from its last reconciled read, and a provider that sees the same answers { items: [], version } without reading, and one that changes how it maps its record makes its versions differ from the old ones so each session is read again once. A user message carries the images its record keeps as image blocks with data; the host stores them as files (docs/adr/0003), and a message whose record keeps no image keeps the images it was sent with |
agent/create_session |
{ workspace, options, tools?, instructions? } |
{ sessionId } |
agent/resume_session |
{ sessionId, workspace, options, tools?, instructions?, requireResume? } |
{} or, with requireResume: true, { unavailable: string } on definitive native history unavailability only |
agent/close_session |
{ sessionId } |
{} |
agent/suspend_session |
{ sessionId } |
{} — stop the session's process and keep it resumable (Processes) |
agent/stop_process |
{ processId } |
{} — stop a shared server the provider reported (Processes) |
agent/prompt |
{ sessionId, input: { blocks, itemId?, context?: ContextPacket, delivery?: { inputId, attemptId, intent: send | steer | queue } } } |
{ runId, receipt?: InputReceipt }; itemId identifies the user row for rollback, while delivery identifies the exact delivery attempt |
agent/cancel |
{ sessionId, reason?: stop | steer } |
{}; simulated-steer cancellation must not manufacture native completion on timeout |
agent/cancel_task |
{ sessionId, taskId } |
{} — stops one subagent; only with capabilities.cancelTask |
agent/withdraw |
{ sessionId, inputId } |
{ withdrawn } — takes back the steer delivered as inputId before the agent picks it up; withdrawn: false when it already did. Only with capabilities.withdraw, backed by a native operation |
agent/set_option |
{ sessionId, optionId, value } |
{ options: ConfigOption[] } (full snapshot) |
agent/respond_to_approval |
{ approvalId, optionId } |
{}, or { notPending: true } when the approval no longer waits (withdrawn, answered in another client, or ended with its turn); the host then treats it as answered instead of showing an error |
agent/respond_to_question |
{ questionId, answer: { values, cancelled } } |
{}, or { notPending: true } when the question no longer waits (withdrawn or ended with its turn); the host does not read the result, so either answer resolves the question without an error |
agent/authenticate |
{ method } |
{} |
agent/logout |
{} |
|
agent/list_skills |
{ workspace } |
{ skills: [{ name, description, source, manualOnly }] } — only with capabilities.skills; a prompt then carries { type: "skill", name, input } blocks |
agent/rollback |
{ sessionId, itemId } |
{} — forget that user message and everything after it; only with capabilities.rollback |
agent/fork_session |
{ sessionId, workspace, options, tools?, instructions?, itemId? } |
{ sessionId } (the copy); only with capabilities.fork. itemId names a user message as rollback does, and the copy keeps only what came before it; it is sent only with capabilities.forkAt |
agent/compact |
{ sessionId } |
{} — the agent reports the work as a compacting event when it begins and a compacted event when it ends; only with capabilities.compact |
agent/usage_limits |
{ limits: UsageLimits | null } — a fresh read of the account's limits. The host keeps one shared copy per agent and asks only when nothing has reported them for five minutes, or for a usage-limit recovery check; concurrent asks share one call. A failed read keeps the copy and doubles the wait before the next periodic read, up to an hour, so return an error (not empty windows) when the provider's own usage service did not answer. Limits the provider learns on its own go to the host as a usage_limits event instead, which also counts as fresh |
|
agent/update |
{} — upgrade the agent's own program with the installer that owns it (AgentInfo.maintenance) |
|
agent/mcp_read_resource |
{ sessionId, server, uri, toolCallId? } |
the MCP ReadResourceResult ({ contents }) of a resource of an MCP server the session's agent connects to; only with capabilities.mcpApps (MCP Apps, below) |
agent/mcp_call_tool |
{ sessionId, server, name, arguments, toolCallId? } |
the MCP CallToolResult of a tool of such a server, called for an MCP App and kept out of the model's context; only with capabilities.mcpApps |
A method an agent does not implement fails with "does not answer"; the host treats that like the capability being off. An agent with no slash commands answers list_commands with an empty list.
read_session.aliases is additive; existing { items } responses still work. itemId is the original host transcript id and nativeItemId is the id in this response's native history. Correlate them through actual native metadata or an ID chosen at submission and observed in history. Matching text, prompt ordinal position, and a synthetic delivery/consumption token are not identity evidence. Persist correlations in the provider when the native protocol does not persist them. One exception covers an agent whose replay carries no ids at all (ACP's session/load without messageId): the provider may record, in order, the id it gave each row it streamed or read, and give a later replay's rows those ids when the replay fits the record row by row, each with the same kind, the same id for tools and for rows the agent named, and every user row containing the text it was sent with. The first row that does not fit ends the matching and the record stays as it was, so the host reports the history as unalignable instead of guessing (alignHistory in acp/map.ts). Aliases are scoped to the supplying session attachment; conflicts fail the entire reconciliation without changing history/checkpoints. Known native records revise their original host records, retaining host ids; missing native rows do not delete archive records from this or other sessions. The native order wins: records move to where the agent's history has them, a new record lands where the agent wrote it, and a row only the host has (a notice, another session's record) keeps following the row it followed. Unalignable legacy history is reported rather than silently replaced.
The host takes the ids a provider's live events give rows as that provider's native ids, so a history read must name each row a run streamed the way the run did. A provider whose record names rows differently (Claude streams a block as <message id>:<block> and stores it as <record uuid>:<block>) returns streamed: each history row's nativeItemId with the streamedItemId a run gives it, both read from the record itself. The host binds the history id to the row a run here streamed; a row no run here streamed is matched as usual. A copy an earlier read appended for want of this link is folded back into the streamed row. A history row no run would stream (a plan the run shows only in the plan panel, a stop the host announces itself) is left out: placed among known rows it could only fail the read.
Labelled context and native recovery
capabilities.context is { labelled, ordinaryFiles, commands }. Do not advertise capabilities a provider cannot safely deliver. Create/resume must not invoke inference. requireResume: true forbids silent fresh-session substitution; the host's selected policy owns recovery. Return unavailable only for a native missing-history diagnostic, never auth/transport errors or compaction. Without the flag, preserve older hosts' failure behavior instead of returning an object they could mistake for a successful resume.
ContextPacket is { id, instructions, text, artifacts }. Continuation guidance is separate from untrusted historical reference text. Native ingress may encode both as user-role text, but must not claim it is foreign native assistant/tool history. Deliver with the actual human request, never a context-only model turn. Artifact paths stay on-demand text; do not turn them into eagerly inlined files or resources, or widen native sandbox grants.
InputReceipt has evidence, optional nativeInputId and optional context: { contextId, evidence, nativeInputId? }. Context evidence is independent of input evidence. context_received reports { attemptId, receipt }; context_rejected reports { attemptId, contextId, reason } and requires positive non-admission. Local writes are not admission; admission is not model consumption. Unknown delivery blocks blind replay across restart.
Persist positively correlated ingress identities and return them as read_session.echoes: { nativeItemId, attemptId, origin }, where origin is { kind: "input", inputId }, { kind: "context", contextId }, or { kind: "combined", inputId, contextId }. These prevent context ingress from becoming another human archive record. Body equality and newly generated replay IDs are not correlation. Unsupported ID-less protocols remain fail-closed.
tools are the plugin tools this session may call (MCP Tool shapes) and instructions is text the agent must follow on top of its own (plugin rules, and the code mode guide). Both come again on every create, resume and fork, because not every agent keeps them. Declare the tools in the agent's own way and pass each call to the host with the request host/tools.call { agentId, sessionId?, workspace?, name, input, callId? }; it answers an MCP CallToolResult and never fails the turn. See tools.md. An agent that takes extra tools only as an MCP server it connects to (OpenCode, ACP agents) gets one from the host: host/mcp.serve { agentId, sessionId?, workspace?, tools, url? } answers { url }, a streamable HTTP MCP server on the loopback address whose tools/call runs like host/tools.call (name workspace without sessionId when one server serves every session of a folder: the host then finds the calling chat by the running turn). Serving again with that url replaces what it serves; host/mcp.close { url } stops it, and it stops when the plugin unloads.
input.blocks are ContentBlocks: { type: "text", text }, { type: "image", mimeType, data } (base64), { type: "file_ref", path } (a path that ends with a slash names a folder).
Model choices may supply group (the provider's display name) and reasoningLevels (the reasoning choices valid for that model). If any model supplies levels, the catalog is per-model: an empty list means no reasoning control for that model. Keep the reasoning ConfigOption in the catalog even when the initially selected model has no levels, so draft chats can switch models before creating a session. The host resolves its choices against the selected model before applying stored effort or creating a session; incompatible effort becomes null (provider default). Agents with a single reasoning list can leave all model-level lists empty.
Any choice may supply aliases: earlier values that now mean that choice. When an agent stops offering a value in favor of another (Claude Code maps the CLI's opus to claude-opus-5-5[1m]), it lists the old value as an alias of the new choice, and the host maps a chat's stored value and remembered defaults to it instead of falling back to the catalog default.
Any choice may supply icon (inline SVG; currentColor follows the text), which the composer draws in the picker and on the pill while the choice is chosen, and transient: true for a choice that holds for its chat only: the host does not remember it for new chats, which open with the choice remembered before it.
The composer lists every option an agent publishes in one settings menu, approval included: a select as a row that opens its choices, a toggle as a row with a switch, listed after the selects in the order the agent publishes its toggles. An option may supply its own icon (inline SVG) for its row; without one the row shows its chosen value's icon, else a mark for its category. A toggle that is on also shows its icon on the menu's trigger. An option with transient: true holds for its chat only, whatever its value, as a transient choice does. Claude Code's Ultracode switch has both: it runs many agents per turn, and the CLI never keeps it either.
AgentInfo.maintenance says whether the agent's own program is out of date: { installedVersion, latestVersion, manager, canUpdate, command }. Report latestVersion only when it is newer than installedVersion and the installer that owns the binary can deliver it. canUpdate means agent/update installs it; when nothing provably owns the binary, command may give a shell line the user runs in a terminal instead (the program's own update command). The app lists every enabled agent that is behind in the list of the sidebar's update button, and waits for the agent's runs to end before it calls agent/update, so update may stop the running process.
AgentInfo.promptKeywords lists words the agent reacts to in a prompt, { word, label, description }, such as Claude Code's ultracode, which turns that one turn into a dynamic workflow. The agent acts on the word itself; the prompt draws the word in rainbow colours wherever it stands as a word of its own, and the pointer over it shows the description (the label without one).
AgentInfo.registry is true for an agent that comes from a provider's registry of extra agents (the agents a provider discovers at runtime and serves through agents/list, rather than the one it is built for); Settings lists such agents under More agents. It is left out (false) for every other agent.
The chat model picker uses provider groups, searches names, IDs and groups, and stores favorites by agent and complete model ID in plugin storage.
Events
While a run is active the plugin sends the notification agent/event with an AgentEvent:
{ sessionId, runId?, taskId?, event: <kind>, ...fields }
taskId names the subagent the event belongs to (see Subagents below).
An empty sessionId is an event for the whole agent, not one chat: a notice shows as an app notice, usage_limits updates the account, skills_changed makes the host call list_skills again for every workspace an open chat of the agent is in and send the new list to those chats, and sessions_changed makes it import that folder's sessions again; other kinds are ignored. Events a session sends before create_session (or a handoff's preparation) answers are kept and applied once the host registers the session, so a provider may emit a new session's options and notices at once. A session no chat owns (one made only to read options, say) should send nothing: the host drops its metadata quietly and logs anything else as a lost event.
event |
Fields |
|---|---|
text_delta |
itemId, text, `mode: append |
reasoning_delta |
itemId, text, mode |
tool_call_started |
ToolCall fields |
tool_call_updated |
id, and any of name (an agent that names the tool only after announcing the call), status, title, kind, input, outputDelta, content, locations, calls |
approval |
id, title, toolCall?, `options: [{ id, name, kind: allow_once |
question |
id, message?, url? (external HTTP(S) action), responseMode?: tool (default) or message, `fields: [{ id, label, description?, kind: text |
plan |
`entries: [{ content, status: pending |
usage |
usedTokens (what the context holds now, not a sum over the turn's requests), contextWindow? (the chat header shows the share left once it is known), costUsd?, inputTokens?, cachedInputTokens?, outputTokens?, reasoningTokens?, categories? (what fills the window, in the agent's order: { name, tokens, parts? } such as the system prompt, tools and messages; never the free space), autoCompactAt? (the tokens in use at which the agent compacts on its own) |
session_info |
title? |
config_options |
options: [ConfigOption] (full snapshot) |
commands |
commands: [SlashCommand] |
skills |
skills: [Skill]: the session's full list, which replaces the last |
skills_changed |
none; with an empty sessionId, says a skill was installed, changed or removed. Send it when the agent's own watcher reports a change, or watch the skill folders yourself (api.fs.watch) when it has none, so a new skill shows without a restart |
sessions_changed |
workspace, the folder; with an empty sessionId, says the agent has a session there that it may not have listed before, one started in its own app or command line. The host calls list_sessions for that folder, when it is a workspace, and brings in the new sessions as chats. Watch where the agent stores its sessions (api.fs.watch) and send it when a new one appears, not on every write, and not for a session this plugin created |
notice |
`level: info |
compacting |
none; the agent began summarizing the conversation to free context, from /compact, agent/compact or on its own. The chat shows it as running until a compacted ends it; a run that finishes first drops it |
compacted |
summary?: the summary that replaced the earlier messages, which the chat shows when the row is opened |
task |
TaskInfo (see Subagents) |
message_received |
itemId, from, fromSession?, blocks: a message another agent sent this one (see Messages between agents) |
run_started |
none; the envelope's runId names the new run |
run_finished |
`outcome: { status: completed |
input_rejected |
inputId, attemptId, reason; positive native non-admission, emitted before rejecting the prompt call; never for an uncertain transport write |
input_consumed |
inputId, nativeInputId?; correlated native model pickup, not a locally buffered line or API admission alone |
usage_limits |
windows? (each { id, label, usedPercent, resetsAt?, windowMinutes?, model?, blocked? }, where model names the one model a window counts, such as a weekly Fable allowance, and puts it beside the prompt next to the account's own windows), resetCredits?, recovery? (UsageRecovery, below). The limits and each window may also carry fields of the provider's own, for a meter only its subscription has: the host keeps them, saves them and hands them on unchanged in AgentInfo.usageLimits, so a view that knows the field can show it. The generated types leave such fields out, so a plugin declares its own, such as UsageWindow & { imagesLeft: number } |
usage_blocked |
recovery: UsageRecovery; run-scoped proven quota interruption, which may still be followed by native retries/grace |
A run must end with exactly one run_finished.
A run starts when the host calls prompt. When the agent begins a turn that nobody prompted (for example, it answers a background task that ended), it sends run_started with a new runId first. The host then shows the chat as running, cancel reaches the turn, and the transcript is not replaced while it streams. A prompted run never sends run_started.
Host features
agent/initialize names in hostFeatures what the host understands beyond what every host reads. A provider sends a listed feature's events or values only when its host lists it, because an older host refuses a whole event it cannot read and the plugins in a user's Plugins folder can run on an older app. An older host sends no list.
mcpApps: themcp_apptool content and themcp_read_resourceandmcp_call_toolmethods (MCP Apps, below).planCancelled: thecancelledplan status.
New optional fields (name on tool_call_updated, secret, default and when on question fields) need no feature: an older host ignores a field it does not know.
MCP Apps
An MCP server can declare an interactive page for a tool: the tool's _meta.ui.resourceUri names a ui:// resource of text/html;profile=mcp-app (the MCP Apps extension, SEP-1865, io.modelcontextprotocol/ui). When a tool call of such a tool is announced, the provider adds a { type: "mcp_app", server, tool, resourceUri } content block to it, and the tool's MCP CallToolResult as result once the call ends; the call's input is the tool's arguments. The chat shows the page under the call in a sandboxed web view and keeps the text content as the call's fallback.
- The page is read through the agent: the host calls
agent/mcp_read_resourcewith the session, the server and the URI when the page opens. A provider whose agent cannot read its MCP servers' resources may still show a page that a tool's result embeds as a resource (uristarting withui://): it puts the page inhtmland the resource's_meta.uiinmeta, and leavescapabilities.mcpAppsoff. - The page talks to the host over the MCP Apps
postMessageprotocol. The host answersui/initializewith the app's theme, sendsui/notifications/tool-inputandui/notifications/tool-result, passestools/callandresources/readtoagent/mcp_call_toolandagent/mcp_read_resource, sendsui/messageto the chat as the user's message, opensui/open-linkin the browser, and keeps the lastui/update-model-contextfor the chat's next prompt. agent/mcp_call_toolrefuses a tool whose_meta.ui.visibilityleaves outappwhen the agent reports it, and lets the agent's own permission rules decide the call as they decide the model's own calls where the agent can. Its result never reaches the model.- The page runs offline: the host keeps it to the restrictive default content security policy the extension prescribes, which it may do whatever the resource's
cspdeclares.
Steering, delivery evidence and usage recovery
capabilities.steer means a native continuation-boundary submission. Keep the active runId for such a steer; do not start a second turn while the first start is in flight. The host adds a native steer to the transcript at its input_consumed, where the agent records it (or at run_finished when the run never picked it up), so send input_consumed before the reply it starts. Without native steering, the host cancels with reason steer and reserves a same-session replacement after actual completion and host settlement. capabilities.simulatedSteer remains accepted for compatibility. Provider-specific mapping belongs in the provider, never shared host/kernel code. Explicit after-run queues stay host-held; a provider must not also enqueue them in a second native inbox.
An omitted receipt is weak evidence. A successful write is not proof of native admission or consumption. Include native correlation ids where supported, emit input_consumed only when the native protocol establishes pickup, and fence delayed completions/receipts against their run/input identities. Providers lacking that evidence leave it unknown, visible and non-replayable. Never advertise amendment or withdrawal of already-admitted input without a native operation. A provider whose agent can drop a steer it has not picked up yet advertises capabilities.withdraw and answers withdraw; the host then removes the input, and it never joins the transcript.
UsageRecovery is { availability: allowed | blocked | unknown | unsupported, observedAt, source, reason, identity?, scope?, resetsAt? }. Identity must identify the effective native account/configuration, not just an agent name or utilization. Missing permission/identity/reset evidence stays unknown. Select the latest exhausted relevant reset; if any relevant window lacks a deadline, omit it. Warnings, purchased-overage permission, output-token caps, authentication errors, generic 429s, and a full usage meter alone are not quota interruption evidence.
Emit usage_blocked with the actual run id, without stopping tools or retries. Only a failed native run followed by host settlement can arm recovery. Fresh availability reads must validate the same identity/scope and preserve blocked evidence instead of replacing it with sparse/null updates. A provider without a native quota reporting contract exposes the limitation, not guessed reset times.
Subagents
An agent with capabilities.subagents reports every subagent it starts with a task event carrying the full TaskInfo snapshot, sent again whenever something about it changes:
{ id, title, status: queued|running|waiting|idle|completed|failed|cancelled,
kind?: agent|terminal, command?, output?, outputDelta?,
toolCallId?, // the tool call that started it; the UI nests it there
parentTaskId?, // the subagent that started this one, at any depth
name?, model?, effort?, prompt?,
background?, // it can outlive the turn that started it
activity?, // what it is doing now, such as the last tool
summary?, // latest progress while running, the result once done
startedAt?, endedAt?, usage?: Usage, toolUses?,
phase?, // the workflow phase an agent of a workflow runs in
workflow?: { phases: [{ title }], result?, logs? } }
A background command uses the same lifecycle with kind: "terminal" and command set to its command line. Omitting kind still means an agent. Providers publish running before the parent turn ends and send a final completed, failed or cancelled snapshot when the command actually ends. The tool call returning or its parent turn finishing does not finish the task. Live terminal tasks protect their process from idle suspension, process-limit eviction and plugin reload, just as live agents do.
outputDelta appends new terminal bytes, including ANSI escapes. output replaces the captured output with a snapshot, useful for file tails and final native output. An update without either preserves the previous output. The host consumes deltas into the stored snapshot and keeps only the last 256 KiB on a UTF-8 character boundary. Providers should bound their own buffers too. Captured output is retained in the mutable transcript projection, so it survives restarting the app. Immutable archive revisions omit these bytes; output ticks cannot accumulate copies of the tail or change a pinned history snapshot. Restoring history restores task metadata rather than historical logs. The chat lists terminals with agents and opens their output in a read-only monospace view with ANSI colours; the shell terminal primitive requires a PTY.
These are optional fields on the existing task event, rather than a new event kind. Older hosts deserialize unknown task fields by ignoring them, so updated providers still protect background commands there as ordinary tasks. Those hosts cannot retain the new terminal metadata or output, and therefore show the legacy task view. No API-version gate or new colour token is needed.
- Every event the subagent produces (text, reasoning, tools, approvals, questions, usage) carries its
taskIdin the envelope. The host keeps those items inside the task, at any depth. approvalandquestionevents with ataskIdstay pending on the chat (the chat is what waits); the host sets theirtaskIdso the UI can say which subagent asks.usagewith ataskIdis the subagent's; it never replaces the chat's context meter.plan,run_startedandrun_finishedwith ataskIdare ignored: a subagent's plan and turns are its own.idleis a subagent that finished its work but can be given more;waitingis one blocked on the user.read_sessionreturns each subagent as ataskitem ({ role: "task", task: TaskInfo, items }) at the place it started, with its own transcript inside, read from the agent's own record of that subagent.cancelstops the run and every subagent in it.cancel_taskstops one subagent and leaves the run going; the task then ends ascancelled.
Plugins show subagents too: a tool's ctx.subagent (tools.md) and a prompt a plugin runs through an agent with models.use (api.models.prompt) are task items of the chat under the tool call, with ids the host gives (sub-..., and sub-.../<id> for a subagent of such a prompt's session). The host answers cancel_task for them itself, and passes a nested one on as cancel_task of the hidden session. To a provider such a prompt is an ordinary session: create_session (with no tools), one prompt, its events, then close_session; its approvals and questions reach the user through the chat it shows in, and come back as respond_to_approval and respond_to_question like any other.
Workflows
A task with workflow set runs a script of agents in phases (Claude Code's dynamic workflows). It is one task, published under the tool call that started it; name is the script's own name, prompt its source, background true. Every agent it starts is a task of its own with the workflow as parentTaskId and its phase in phase, so a reader that knows nothing of workflows still sees a tree of subagents.
workflow.phaseslists the phases in the script's order, including the ones no agent has reached; an agent'sphasenames one of them.queuedis an agent that was started but waits for an earlier phase or a free slot. It counts as work in hand, likerunningandwaiting.workflow.resultis what the script returned (any JSON value) andworkflow.logswhat it logged; both arrive when the run ends.summaryis the result as one line of text.- Agents of a workflow stop with it:
cancel_taskon the workflow stops the run; on one of its agents it fails. - The agents' own transcripts are events tagged with their task ids, like any subagent's. They can arrive later than the agent's status: Claude Code writes them to files the plugin follows.
ToolCall:
{ id, name, tool?, kind: read|edit|delete|move|search|execute|think|fetch|task|other,
title, status: pending|running|completed|failed|cancelled, input,
content: [ { type: "text", text }
| { type: "diff", path, oldText?, newText?, diff? }
| { type: "terminal", command, cwd?, output, exitCode? }
| { type: "mcp_app", server, tool, resourceUri, html?, meta?, result? } ],
locations: [{ path, line? }],
calls?: [{ tool, status, input? }],
message?: { to, text } }
tool is the plugin tool's own name (execute) when the call is to a tool a plugin gives every agent (tools.md), which its agent knows under another name (mcp__divergence__execute, divergence_execute): the provider sets it, and the chat shows it in place of name.
calls is the host's, never a provider's: the calls a code mode program made, in the order they started, which the host adds to the execute row while the program runs (tools.md, Code mode). A provider that announces the call again keeps them.
message is what the call sent when it is a message to another agent (see Messages between agents).
TranscriptItem (history): { id, createdAt?, role: "user", blocks, from?, fromSession? }, { role: "assistant", text }, { role: "reasoning", text }, { role: "tool", call }, { role: "plan", plan }, { role: "notice", text }.
Messages between agents
An agent can message another one that runs beside it, such as another Claude Code session on the same machine (SendMessage). Both chats show the message:
- The sender's tool call carries
message: { to, text }, with the recipient by the name it goes by. The chat shows the call as the message it sent, on a row of its own, and a call that could not deliver it as failed, with the reason incontent. - The recipient takes the message as input. When it arrives, its provider sends
message_receivedwith the id its history gives the message, the sender's name infrom, the sender's own session with the same agent infromSessionwhen the provider can tell which one it is, and the message inblocks, before the reply it starts; a turn the message starts opens withrun_startedlike any other. The host adds a user row withfromandfromSessionset. Its history returns the same row (role: "user"withfromand, when known,fromSession), which is never one of the user's own prompts: it cannot be edited or forked before, and a handoff labels it as another agent's.
A message from the agent's own subagent belongs to the subagent's task, not here.
Background questions
A question with responseMode: "message" does not pause the run. The host keeps it available across turn completion until answered or dismissed. Every pending question marks the chat as waiting_question, even while the agent keeps working or after its turn ends. Pending approvals take priority as waiting_approval. After the last request is resolved, the chat returns to its running, idle or failed status.
The fields use the same choices and free-text controls as ordinary questions. Answers become a normal user message (field answers in display order, separated by blank lines), steering an active run when the provider advertises capabilities.steer, or starting a new turn when idle. Dismissal only resolves the card. These questions do not call agent/respond_to_question; the host emits question_resolved after successful delivery. Pending cards are session state, not restored after app restart.
Processes
The host keeps one pool of the agents' long-running processes for every agent (Settings > Agents: a limit, 20 by default, and an idle time, 10 minutes by default). A provider reports each process it keeps running, and the host decides which to stop. A provider that reports nothing is outside the pool, and the host never stops its processes. All of this is optional and does not change PLUGIN_API_VERSION.
A report is the notification agent/process:
{ "agentId": "claude", "processId": "claude-process-19a…-3", "state": "started",
"sessions": ["<native session id>"], "shared": false, "external": false }
state:startedwhen the process is up (send it once, after the process answers its handshake),sessionswhen the set of sessions it serves changes,stoppedwhen it exits for any reason (an exit the pool asked for, a crash, a shutdown). Onstoppedthe host ends the tool calls and subagents its sessions' chats still show running, ascancelled: nothing will finish them. It does not at the end of a turn, so a command or subagent that outlives its turn still reports its own end.sessions: the full current list of the native session ids (thesessionIds the host knows) the process serves. Empty for a shared server that has none loaded yet, and instopped.shared: false: one process per session. It takes one pool slot, and the host stops it withsuspend_session.shared: true: one server for many sessions. It takes one slot in total, and the host stops it withstop_process, and only when no one-session process can be stopped.external: true: a server the user runs (one the provider found, or a configured URL). It takes no slot and the host never stops it.processId: unique per launch; a restarted process is a new id. Short helper processes (a model-list probe, an auth check, a history read) are not reported.
The host stops only idle processes: none of their sessions has a running turn, a running subagent or background task, an open approval or question, a run that is settling, or a preparation under way. Over the limit it stops the least recently used one; a one-session process whose chat is not on screen is also suspended after the idle time. Shared servers have no idle stop. After a stop, the chats of those sessions are detached, and the host calls resume_session before their next prompt.
agent/suspend_session { sessionId }: stop the session's process and keep everything a resume needs (saved state, the native id, what the last history read saw). The nextresume_sessionstarts it again on the same conversation. It is notclose_session, which also forgets the session; a provider withoutsuspend_sessionis never suspended (the host does not fall back toclose_session).agent/stop_process { processId }: stop a shared server through the provider's usual exit path; its sessions become unloaded and are resumed on their next use. An id of a process that already exited stops nothing.
Send the reports with the SDK's reportProcess(handle, report) (agent.js), where handle is what api.agents.register returned or the handler's context; on a host older than the pool it does nothing.
Providers in JavaScript
A provider is a sandboxed plugin like any other: it starts its agent's program through the broker, reads the program's output as streams, and emits agent events. plugins/codex/ is the reference for a program that speaks JSON-RPC; plugins/claude/ for one with a line protocol of its own (Claude Code's stream-json), plugin tools served as an MCP server over that protocol, and the agent's own records read from disk; plugins/opencode-v2/ for a program that is an HTTP server (opencode serve, reached with api.net and a localhost:* grant, its events read as server-sent events) and plugin tools given through the host's loopback MCP server (host/mcp.serve); plugins/acp/ for a provider whose agents are only known at run time (the ACP registry, downloaded and cached in plugin storage, plus the user's custom.json in the plugin's data folder), each started through process.any (a path, npx or uvx), and for the client side of a protocol with requests in both directions (fs/*, terminal/*, permissions and elicitations the agent asks the client for).
- Manifest.
"main": "main.js",contributes.agentsfor the agents it always serves ({ id, name, icon? };iconnames an SVG file in the plugin's folder, which the app shows from its first frame, while the plugin still starts: until it registers the agent, the agent is listed as starting, and calls for it wait), and exactly the permissions it uses, each with its reason:agents.provide;processnaming its CLI (and the installers it asks about updates, such asnpmandbrew);envfor the variables it reads;netfor a host it opens or fetches (localhost:*for a server it starts on a port of its choosing);fs.readfor the folders where the agent keeps its own records (Claude Code's~/.claude/**), andworkspacewhen it reads project files. - Registration.
api.agents.register(definition)inactivate, with one handler per method above; it returns{ emit }. The host lists a plugin's agents once, when it has loaded. A provider that learns of more agents later (accounts in its storage, which answers only once the plugin is connected, or a registry it downloads) registers them; the runtime tells the host (host/agents.changed), which lists them again.api.agents.unregister(id)takes one back the same way, and the host stops it (the ACP plugin drops a registry agent the registry no longer lists). A definition may carryicon(inline SVG) anddescription: the host shows them for an agent that has not been started yet (one the user has not turned on), until itsinitializeanswers. When an agent learns afterinitializethat its answer is out of date (it needs a sign-in, which most ACP agents say only atsession/new), the plugin callshost/agents.changedwith{ agentIds: [id] }and the host asks it again. - Handlers run in the plugin's runtime: they may await host calls and the program, but must not busy-loop (the 10 s limit,
ui-plugins.md).promptanswers with the run id at once; the run goes on in events and ends with exactly onerun_finished. - Plugin tools. Declare
toolsto the agent in its own way and pass each call withapi.host.tools.call({ agentId, sessionId, name, input, callId })(callHostToolin the SDK turns a failure into an error result). A plugin cannot listen on a port, so an agent that connects to MCP servers gets the host's:api.host.call("host/mcp.serve", { agentId, workspace, tools })answers theurlto give the agent (OpenCode:POST /mcpwith aremoteserver; it names each tooldivergence_<tool>; an ACP agent: anhttpentry ofmcpServersinsession/new,session/loadandsession/resume, only when itsinitializeanswer saysmcpCapabilities.http, else the chat gets a notice that the tools are not available). The address is on this machine's loopback, so an agent server on another computer cannot use it. - Instructions.
instructionsfrom create, resume and fork go to the agent as extra system text (CodexdeveloperInstructions, OpenCode'ssystemon each prompt). ACP has no system prompt, so the ACP plugin sends them as a marked text block ahead of a session's first prompt and leaves that block out of a replayed history. In code mode they carry the tool catalog (tools.md, Code mode). When the catalog changes while a session is attached (a plugin reloaded, a tool turned on or off), the host tells the agent with the session's next prompt: its first text block is a<divergence-instructions>block with what was added, changed or removed, or the whole catalog again, and the transcript keeps the user's text without it. A provider passes it on as part of the prompt and leaves it out of a replayed history (stripInstructionsanduserBlocksOnlyinsdk/context.ts). - Sign-in. A browser opens only because the user asked:
api.openUrlworks for a provider (anhttporhttpslink) while the user signs in to one of its agents from settings, that is while the host'sagent/authenticatecall is out; it resolves{ opened: false, reason }for a link it kept closed, which the sign-in should report with the link. A sign-in link an agent asks for at any other time (an ACP URL elicitation, a URL an agent prints) goes to the chat as a notice the user follows. - Installed version.
api.process.which(program)(on the wirehost/process.which) answers{ path, realPath }for a program the plugin may run; the real path proves which installer owns it (installerOfin the SDK). - Files.
api.fs.read,listandstatanswer within thefs.readgrants. The broker checks the path a call resolves to, links followed, so a file reached through a link out of the granted folders is refused; read the agent's records best effort (a refusal or a missing file is "nothing there") rather than failing the call. A file an agent appends to can be followed by its size (stat) and read from the byte offset already seen (read(path, { encoding: "binary" })). - State. What a provider must remember across restarts (such as the host item each prompt became) goes in plugin storage (
api.host.storage), keyed by session. A file the user edits goes in the plugin's data folder (api.paths.data, thedatascope of itsfsgrants), such as the ACP plugin'scustom.json. What a native provider (before the port) kept in<data dir>/agents/<folder>/is moved there aslegacy/the first time the JavaScript plugin that replaced it loads; the Claude, Codex and OpenCode plugins read it once into their storage. - Ids.
crypto.randomUUID()makes the version 4 UUIDs a CLI may require for a session id.
The provider SDK (plugins/sdk/)
The SDK ships with the official plugins. An official plugin imports it by its path beside the plugin (import { spawnJsonRpc } from "../sdk/process.js"): the host sends the plugin's files under <folder>/ and the SDK's under sdk/, so the import resolves in the runtime as it does for node --test on disk, and saving the SDK reloads the plugins that use it. Only an SDK the installation shipped (or an unchanged copy of it) is mounted into an official plugin.
| Module | What it has |
|---|---|
jsonrpc.js |
JsonRpcConnection (requests with timeouts, cancellation by AbortSignal with an optional cancel notification, notifications, server requests answered through a Responder with ok, err or discard, a closed connection failing what is still out), lines and pump for newline-delimited JSON over a stream |
process.js |
spawnJsonRpc(api, program, args, { cwd, env, name, defaultTimeout, onRequest, onNotification, onExit }): a child's stdio as a JSON-RPC peer, writes kept in order, the stderr tail kept for onExit, shutdown() (TERM, then KILL); spawnLines(api, program, args, { cwd, env, name, onLine, onExit }): the same for a child with a line protocol of its own (send(message) writes one JSON line); run(api, program, args, { env, timeout }) for a program's whole output |
sse.js |
parseSse(chunks) for any body stream, sse(api, url, init) over api.net.fetch, sseJson |
agent.js |
events.* builders for every event kind, agentEvent, outcome, newId, uuid (crypto.randomUUID), permissionMode (the four shared modes; preferred(reviewer) is the mode of a chat that has not chosen one, Auto with a reviewer and Auto-accept edits without), callHostTool, reportProcess (an agent/process report, Processes) |
mcp.js |
handleMcp(api, { agentId, sessionId, tools }, message): an MCP tool server (initialize, ping, tools/list, tools/call through host/tools.call) for agents that take extra tools only as MCP servers and relay the messages; MCP_SERVER (divergence, so the agent names a tool mcp__divergence__<tool>) |
sessions.js |
SessionWatch: watches the folder an agent keeps one transcript per session in, and reports the folder of a session it has not listed and the plugin did not create with sessions_changed, once; transcriptFolder(head) reads the "cwd" a transcript's first records name |
diff.js |
unifiedDiff(path, oldText, newText): a unified diff with three lines of context, for agents that report an edit as replaced text |
maintenance.js |
which (api.process.which, nulls when refused), installerOf, npmPrefix, latestNpm, latestBrew, isNewer |
testing.js |
fakes for node --test: fakeApi (a spawned program is a scripted FakePeer, host calls and process.which a function, fs as given, paths.data, net.fetch answered by onFetch with fakeResponses, openUrl recorded and answered by onOpenUrl, agents.register and unregister recorded), diskFs (an api.fs over the real disk, with the paths a grant would refuse), memoryStorage (plugin storage for onHost), FakeStream (also a streamed response body, such as server-sent events), settle |
Tests: node --import ./plugins/testing/register.mjs --test plugins/sdk/*.test.ts plugins/codex/*.test.ts plugins/claude/*.test.ts plugins/opencode-v2/*.test.ts plugins/acp/*.test.ts. The live tests are cargo test -p divergence-host --test e2e -- --ignored: they build the plugin host and run real prompts through the plugins, among them a Codex turn that runs a shell command and calls a plugin tool, a Claude Code turn on Haiku that calls a plugin tool through its MCP control channel, and an OpenCode 2 turn on its free big-pickle model that calls a plugin tool through the host's loopback MCP server (opencode_v2_calls_a_plugin_tool; run it by name: it puts ~/.local/bin/opencode, or DIVERGENCE_E2E_OPENCODE2, first on the login PATH), and an ACP turn (Kilo on a free model of its gateway, or DIVERGENCE_E2E_ACP_AGENT and DIVERGENCE_E2E_ACP_MODEL) that calls a plugin tool through the same loopback server (acp_calls_a_plugin_tool; acp_initializes_and_lists_its_options spends no usage).
Source: plugins/docs/agent-protocol.md in the Divergence repository, built with this site.