# ACP: Agent Client Protocol

zelk serves standard ACP through [`core/acp`](https://github.com/barevoidco/zelk/blob/main/core/acp/README.md),
and the CLI serves it on stdio with `zelk acp`, or to many clients at once
with `zelk acp -listen` (Serving many clients, below).

## Pinned version

- **Protocol version 1**, as defined by the schema of the official
  TypeScript SDK `@agentclientprotocol/sdk` **1.9.0**, the client the interop
  test runs against (`cmd/zelk/testdata/acpinterop/package-lock.json`).
- zelk answers `initialize` with protocol version 1 whatever the client asks
  for; a client that can't speak version 1 disconnects, as ACP specifies.

## Capability mapping

| ACP | zelk | Notes |
|---|---|---|
| `initialize` | agent info, `loadSession: true`, images and embedded context in prompts | No authentication methods: the host authenticates the transport. |
| `session/new` | a new session ID; the session's log starts with its first prompt | `cwd` must be the agent's workspace root: an agent's environment is fixed when it is made. |
| `mcpServers`, `mcpCapabilities.http` | `zelk.WithACPClient`: an agent built with `WithMCP` of the client's servers | Opt-in. A stdio server starts in the host's environment, under its launcher; its command must be an absolute path. HTTP servers are reached through the host's client. Names become server names (`mcp__name__tool`). Without the opt-in, a session with servers is refused, never served without them. `zelk acp` opts in. |
| `session/load` | `Session.History` with compacted turns, replayed as `session/update`s before the response | User messages, assistant text, tool calls and their results. Harness notes and reasoning aren't replayed. |
| `session/list` (`agentCapabilities.sessionCapabilities.list`) | the store's sessions (`acp.Lister`) | Conversations a client could load here: in the agent's workspace (and the `cwd` asked for, if any), with a log this version reads; not subagents. Most recently updated first, with `title` and `updatedAt`, 100 to a page; the cursor is an offset, so a session made between pages shifts the list by one. |
| `session/fork` (proposal; advertised as `agentCapabilities.sessionCapabilities.fork`, beside `list`) | `Agent.Fork` with point 0 (`acp.Forker`) | A new session with the source's conversation as it stands, active at once; nothing is replayed. The source is unchanged. Forking from a given message, which the proposal leaves for later, isn't offered. |
| `session/prompt` | `UserMessage` on a new execution; events and live deltas streamed as updates | One prompt at a time per session. Text, embedded text resources and images (inline base64 PNG, JPEG, GIF or WebP, scaled to fit as a pasted one is, attached as `image N`); audio isn't advertised. A session whose model doesn't take images refuses a prompt with one, saying so, and so does one waiting for an answer. |
| `agent_message_chunk`, `agent_thought_chunk` | text and reasoning deltas | If a client falls behind and deltas are dropped, the turn's whole text is sent when it ends. |
| `tool_call`, `tool_call_update` | `EffectStarted` and the tool's recorded result | Kind from the tool (`Read` → read, `Bash` → execute, …); output bounded to 16 KiB per update. |
| `plan` | `TodoWrite` | Every entry has medium priority. |
| `available_commands_update`, a `/compact [focus]` prompt | `zelk.Compact` | The prompt runs a compaction in place of a message, with the rest of the text as the summary's focus, and ends with "The conversation is compacted."; a session with nothing to compact fails the prompt saying so, and one waiting for an answer refuses it. |
| `available_commands_update`, a `/status` prompt | `Agent.Overview` (`acp.Overviewer`) | Sent after `session/new`'s response and during `session/load`. `/status` answers with the session's overview (model, effort and mode, the run, how the last one ended, tasks, background work, where the log and notes are kept), the same text `zelk status` and the TUI show, as an agent message; it starts no run and calls no model. |
| `available_commands_update`, a `/name args` prompt | `Agent.SkillCommands`, `Session.InvokeSkill` (`acp.Skiller`) | The agent's skills and command files the user may run, after `/status` and `/compact`, with `argument-hint` as the input hint; one named like those two isn't offered. A prompt naming one invokes it with the rest as its arguments, which its placeholders take; a `` !`command` `` line its permissions ask about is asked with `session/request_permission`, as a shell call of its own that no update names; with an image it is refused, as a skill takes none. Any other `/word` is an ordinary message. |
| stop reason and a closing agent message | `present.End` | A run that didn't succeed, or succeeded leaving checks failing, ends with its explanation (cause, what the report left open, how to go on) as an agent message; `end_turn` alone doesn't say an incomplete run is incomplete. A failed run fails the prompt with the same text. |
| `session/request_permission` | approvals and plan approvals, asked when the session suspends | Allow once; always allow (one choice granting every suggested rule); deny; a cancelled request cancels the action. Approving a plan switches back to the mode the session left for plan mode when the client allows it, else to the first allowed mode that isn't `plan`. |
| `elicitation/create` (form) | `AskUserQuestion`, live MCP forms | To a client advertising `elicitation.form`, within the prompt: a single or multiple choice per question, plus a free-text field; an empty field or a declined form is recorded as the user declining. MCP forms forward their original schema and server-labelled untrusted message; replies are validated. |
| `fs/read_text_file`, `fs/write_text_file`, `terminal/*` | `acp.ClientEnv` over the host's environment | Opt-in (`acp.WithClientFS`, `acp.WithClientTerminal`; `zelk acp -client-fs -client-terminal`; a managed policy with `"client_terminal": false` overrides `-client-terminal`), used only while the client of the session's execution is connected and offers them; otherwise, and once it disconnects, the host's environment. |
| `session/cancel` | `Interrupt` | The prompt ends with `cancelled`. |
| `session/set_mode`, config option `mode` | `SetPermissionMode` | Only the agent's allowed modes are offered. |
| config option `model` | `SetModel` | The models `zelk.ACP` was given; the switch applies at the next safe boundary. |
| stop reasons | run outcomes | `success`, `incomplete`, `unverified`, `blocked` → `end_turn`; `max_turns` → `max_turn_requests`; `max_budget` → `max_tokens`; `refused` → `refusal`; `interrupted` → `cancelled`. Cancellation also ends pending permission and elicitation waits and resumes the suspended session with an interrupt, without dispatching its pending action. `error`, `invalid_structured_output` and `quota_exceeded` fail the prompt with a JSON-RPC error (`-32603`) whose message says why and how to go on, and whose `data` has `outcome` and, for a model's failure, `errorKind` (`auth`, `quota`, `rate_limited`, `context_overflow`, …), for a client to tell failures apart without reading the text. A prompt whose run fails to start or to finish, as one whose provider can't be reached does, fails the same way, with `outcome` `error`. ACP v1 has no stop reason for a failure; v2's `error` stop reason will carry the same once zelk serves v2. |
| disconnect | detach | Runs go on; a pending approval stays pending in the session's log until a client takes the session up (`session/load`, then a prompt, which asks again). |

## Serving many clients

`zelk acp -listen ADDR` serves until it is stopped (a signal), to any
number of clients at once, all on one agent in the directory it started
in. A session one client starts can be loaded by another; a prompt keeps
running when its client leaves, as on stdio, and the next client to load
the session takes it up. One prompt runs in a session at a time: a second
client's prompt to a busy session is refused. So sessions outlive the
editor that started them.

| `-listen` | Who may connect | Framing |
|---|---|---|
| `unix:PATH` | the user: the socket is mode 0600 (on Windows, a descriptor that grants only the user, which zelk checks on both sides, and a connecting peer's Windows user is verified too), made in a private directory beside it and linked into place, so no one connects before its mode is set and two zelks starting together can't both take the path. That directory's path is no longer than `acp.sock` beside it, so a path the system's socket cap (104 bytes on macOS, 108 on Linux and Windows) takes works; one with a shorter name near the cap is refused, saying why. A socket that refuses connections, left by a zelk that died, is replaced; one a zelk serves on, or one that can't be checked, is refused. It is removed on exit, unless another zelk has replaced it: zelk keeps its own link to the socket in that private directory while serving, so no later socket can take its inode and pass for it. Zelks starting and stopping on one path take turns through a lock file beside it, `PATH.lock`, which stays: a zelk starting while another starts or stops there is refused, saying so. | newline-delimited JSON-RPC, as on stdio |
| `ws://127.0.0.1:PORT` (or `localhost`, `[::1]`) | a client that sends `Authorization: Bearer TOKEN`, with the token from `-token-file` (default `acp-token` in the state directory, made 0600 with 32 random bytes if missing; a file that is there must be the user's own regular file, not a link, that no one else may read or write), names a loopback `Host`, and sends no `Origin`: no web page can connect, and no other machine can reach it. | the WebSocket profile of ACP's remote transport draft |

The WebSocket follows the draft's WebSocket profile (the
[Streamable HTTP and WebSocket transport RFD](https://github.com/agentclientprotocol/agent-client-protocol/blob/main/docs/rfds/streamable-http-websocket-transport.mdx)):
the handshake is `GET /acp` with `Upgrade: websocket` (any other path is
404), answered `101` with an `Acp-Connection-Id`; each text frame is one
JSON-RPC message, pretty-printed or not (a frame that isn't one is
answered with one parse error), binary frames are ignored, and the client sends
`initialize` first, as on stdio. The draft lets a server offer only the
WebSocket profile, as zelk does: its Streamable HTTP profile (POST and
SSE streams over HTTP/2) isn't served. The draft leaves authentication to
the server; the token is zelk's. Where the draft has the server clean up
a connection's sessions on disconnect, zelk keeps them: they are in its
store, and a disconnect is a detach, as on stdio.

Editors start their agent as a command on stdio. `zelk acp -connect
unix:PATH` is that command for a served socket: it relays standard input
and output to it, and ends when the editor closes its side and the server
has answered, or the server goes. It takes no other flags: the serving
zelk has them.

```sh
zelk acp -listen unix:$XDG_RUNTIME_DIR/zelk-acp.sock -state ~/.local/state/zelk &
# the editor's agent command:
zelk acp -connect unix:$XDG_RUNTIME_DIR/zelk-acp.sock
```

## Limitations

- **Live MCP elicitation.** A server form inside an MCP tool call cannot
  suspend. It uses the connected editor's form channel and recorded input
  timeout; cancellation, expiry and disconnect answer cancel. Clients without
  forms decline immediately. Callback and suspend agents advertise form support
  on their shared MCP connections; deny/headless agents do not. The call's context
  routes each form to its callback or connected ACP client, even when sessions
  share an agent. Calls and resource reads retain one MCP connection and server
  session. Concurrent calls stay concurrent: HTTP forms belong to their response
  stream's call; stdio and other uncorrelated requests decline when zero or
  several tool calls are in flight, as the elicitation spec permits.
  Only flat primitive schemas are supported; unsupported schemas and URL mode
  decline. The normal tool intent/result is logged, without separate input
  audit records. No server form is attributed to the model or answered by a
  later prompt.
- **Questions to clients without forms.** A client that doesn't advertise
  form elicitation sees an `AskUserQuestion` as an agent message ending the
  turn, and the user's next prompt answers it. URL elicitation isn't used.
- **Client fs and terminal capabilities** are used only where the host opts
  in, since they lack revision tokens and full process semantics:
  - Whether a file exists is the disk's to say; the client gives the
    content, its unsaved buffer's if it has one. A write checks the file's
    revision just before writing, not atomically with it, and takes text
    only. Paths are checked lexically against the workspace, so file access
    through the client is at most advisory.
  - A client terminal takes no input, keeps only the output the client
    retains, and runs outside the host's launcher: the environment's
    enforcement for commands drops to none. Protocol servers, such as MCP
    stdio servers, never run in one.
  - Glob and Grep always read the disk.
- **Client MCP servers** are connected only where the host opts in
  (`zelk.WithACPClient`): a stdio server is a command the client chose, run
  on the host. The SSE transport isn't supported. A session keeps the tools
  of the servers it started with; loading it with other servers fails, since
  its recorded tools would be missing.
- **Not served:** `session/resume`,
  `session/close`, `session/delete`, providers. They answer method-not-found.
- **zelk extensions** are for cooperating clients only; a standard client
  sees none of them (see below).
- An agent served over ACP must suspend for human input
  (`zelk.WithInputSuspend`); `zelk.ACP` refuses one that doesn't.

Persistent `zelk acp` hosts may enable `-skill-cache` with bubblewrap or
Seatbelt. It uses the host workspace; ACP client filesystem and terminal
overrides cannot preserve its storage namespace and are refused. Sessions keep
checkpoints as in every persistent host; their records are durable Go events
and standard ACP session loading and streaming are unchanged.

## zelk extensions

Namespaced ACP extensions (ACP's extensibility rules: `_meta` and methods
starting with `_`) for clients that cooperate. Standard clients are
unaffected: nothing below is sent to a client that doesn't ask for it.

**Negotiation.** `initialize` advertises the extensions the agent serves
under `agentCapabilities._meta.zelk`, with `"version": 1`. A client names the
ones it uses under `clientCapabilities._meta.zelk`, each as an object
(`{"results": {}}`); only extensions both sides name are in effect. A method
of an extension the agent doesn't serve answers method-not-found, like any
unknown method; one of an extension the client didn't name is refused with
invalid-request, saying so. Every method takes a `sessionId` the connection
made or loaded.

| Extension | Advertised as | What it serves |
|---|---|---|
| `control` | `{}`, by agents that take commands outside a prompt (`acp.Controller`) | `_zelk/session/steer`, `_zelk/session/withdraw_steer`, `_zelk/session/background_calls`, `_zelk/session/inject_context`, `_zelk/session/set_goal`, `_zelk/session/clear_goal` |
| `results` | `{"output": true}` when the agent takes output contracts (`acp.OutputStarter`) | `_zelk/session/status`; each prompt's typed result; a prompt's output contract |
| `tools` | `{}`, by agents that run client tools (`zelk.WithACPClientTools`) | tools declared in `session/new` and `session/load`, called as `_zelk/tool/call` |
| `events` | `{"pageLimit": 1000}`, by agents that read and follow logs (`acp.Follower`) | `_zelk/session/events`, `_zelk/session/follow`, `_zelk/session/unfollow` |

**Control.** Each method sends the zelk command of its name (`zelk.Steer`,
`InjectContext`, `SetGoal`, `ClearGoal`) to the session: to its running
execution, or to one it starts. Params: `text` (`set_goal`'s is the goal),
`abandon` for `clear_goal`, `run` for `steer` (the run's ID; omitted, the run
under way, and with none the steer is refused), and an optional `commandId`.
The response, `{"seq": n}` (and `"run"` for a steer), comes once the
command's acceptance is recorded at sequence `n`: it means accepted, not
carried out. A request resent with the same `commandId` is accepted once and
answered with that acceptance; the same ID with other content is refused. A
steer whose run ends first is rejected in the log (`SteerOutcome`).
`_zelk/session/withdraw_steer` (`zelk.WithdrawSteer`) takes back a steer no
model call has taken yet; its `steer` param is the steer's command ID, so a
client that may withdraw a steer gives it a `commandId`. Whether it was taken
back is in the log, recorded with the withdrawal's acceptance
(`SteerWithdrawn`: `withdrawn`, or a `reason`); a model call that takes
steers records `SteersTaken` naming them, after which none can be withdrawn.
`_zelk/session/background_calls` (`zelk.BackgroundCalls`) asks the
run's Bash commands and subagents under way to move to the background, as
Claude Code's ctrl+b does; `run` defaults to the run under way. With
`sendNow` and `steers`, the command IDs of steers sent, it sends them now
(`zelk.SendNow`): what can move does, the reply's calls not started yet
aren't run, and the next model call takes the steers, or the run is
interrupted when what it waits on can't move, and the next run takes them.
What it did is in the log, recorded with its acceptance
(`BackgroundRequested`: `moving`, `interrupted`, `nothing_movable`,
`satisfied` once a model call took the steers, or `no_run`); each moved call
ends with a result naming its background job.

**Results.**
- `_zelk/session/status` returns `seq`, `running`, `run`, `suspended`,
  `mode`, `model`, `goal` (`text`, `explicit` when `set_goal` set it,
  `abandoned`), `budget` and `last`. `budget.limits` is the session's
  `event.Budget` (`null` without one); `budget.run` and `budget.session` are
  ledgers (`event.LedgerReport`) that keep measured usage apart from unknown,
  reserved and allocated amounts, so unknown usage never reads as a measured
  zero. `last` is the last finished run's typed result.
- A typed result is `outcome`, `run`, `error`, `errorKind`, `usage`
  (`event.Usage`), `ledger`, `report` (`event.Report`) and `output`, the
  validated structured output. A prompt's response carries it as
  `_meta.zelk.result`; a prompt that fails carries it in the JSON-RPC error's
  `data.zelk.result`. A prompt that ends waiting for an answer has none.
- A prompt may give its run an output contract:
  `"_meta": {"zelk": {"output": {"schema": {...}}}}`, a JSON Schema in the
  canonical subset (`zelk.WithRunOutput`). Only that run has it.
- A prompt can't set a budget (`_meta.zelk.budget` is refused): a run's
  budget is its session's.
- `usage`, `ledger`, `limits` and `report` use zelk's own event JSON
  (snake_case), not ACP's spelling.

**Events.** A session's log, in zelk's event JSON (`event.Event`: `seq`,
`kind`, `payload`, ...), read from a cursor: `after` is the sequence number
of the last event the client has, 0 for none.
- `_zelk/session/events {sessionId, after, limit}` returns a page:
  `events`, `last` (the last one's sequence number, or `after` if there are
  none) and `more`. A page holds at most `limit` events (100 by default,
  1000 at most) and stops adding once 4 MiB are encoded, but always holds
  one if any is left.
- `_zelk/session/follow {sessionId, after}` answers `{}`, then sends every
  event after the cursor as a `_zelk/session/event {sessionId, event}`
  notification, in order, never skipping or repeating one, and goes on as
  the session runs on this agent: live deltas of model text and reasoning
  as `_zelk/session/delta {sessionId, effectId, reasoning, text}`, and
  `_zelk/session/lagged {sessionId}` when deltas were dropped (deltas are
  lossy; events never are). Following lasts until
  `_zelk/session/unfollow {sessionId}`, the client disconnects, or the
  follower fails, which `_zelk/session/unfollowed {sessionId, error}` says.
  A session is followed once per connection.
- The follower reads the log at its own pace, so a slow client slows only
  its own notifications, never a run (`zelk.Session.Follow`).
- **Reattach:** after reconnecting, `session/load` the session and follow
  it from the last sequence number received.
- Events another process appends reach a follower once this agent runs
  the session again; `_zelk/session/events` reads them at any time.

**Client tools.** A client of the `tools` extension may host tools of its
own, declared in `session/new` or `session/load` as
`"_meta": {"zelk": {"tools": [{"name", "description", "inputSchema",
"readOnly", "idempotent"}]}}`: at most 64, each name 1 to 56 letters, digits,
`_` or `-`, a description of at most 4 KiB, and an input schema of at most
64 KiB in the canonical subset. A bad declaration fails the request.
- The model calls a tool as `client__<name>`. Permissions, hooks, budgets
  and recovery see it as the tool it is: an untrusted tool of origin
  `client`, whose `readOnly` and `idempotent` claims are never relied on.
- A call goes to the client of the execution as the request
  `_zelk/tool/call {sessionId, name, input, idempotencyKey, attempt}`,
  answered with `{content: [{type: "text", text}], isError}`. The key is the
  same for every attempt of a call. Results are bounded to 256 KiB of text;
  other content types are noted, not shown.
- A call that never reached the client did nothing; an error response fails
  it; a connection lost after the call was sent leaves its outcome unknown,
  and it is never retried as if it hadn't run. With the client gone, later
  calls fail, saying the client isn't connected.
- A session keeps the tools it started with, like its MCP servers: the agent
  that runs it is built for its setup (`acp.Setup`), and one built without a
  declared tool is refused, never served without it.

MCP resource mentions in authored text blocks (`@server:uri`) are resolved by the session's zelk
agent and attached as bounded untrusted context before `session/prompt` runs.
An unreadable resource refuses the prompt. Embedded text resources still work;
bare `resource_link` blocks stay descriptive because they carry no server name.
Use a text mention to read a resource from a specific connected MCP server.
Mentions inside embedded resource contents never trigger resource reads.
