Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/acp"

Package acp serves a zelk agent over the Agent Client Protocol, standard ACP version 1 on any io.ReadWriteCloser, such as a process’s standard streams. It depends only on zelk’s public packages: Serve takes the small Agent interface, which zelk.ACP adapts a *zelk.Agent to.

The capability mapping, what each zelk feature maps to and the known limitations, is in docs/acp.md.

const ClientToolPrefix = "client__"

ClientToolPrefix starts the model’s name of every client tool, keeping it apart from the host’s tools and MCP servers’.

const ProtocolVersion = 1

ProtocolVersion is the ACP version served.

const WebSocketPath = "/acp"

WebSocketPath is the endpoint ServeWebSocket serves, as ACP’s remote transport draft (the Streamable HTTP and WebSocket RFD) names it.

func CanElicit(ctx context.Context) bool

CanElicit reports whether ctx belongs to a connected client offering forms. Ordinary suspended input does not imply a live elicitation channel.

func ClientEnv(base env.Environment, root string, opts ...ClientOption) (env.Environment, error)

ClientEnv returns base, the host’s environment, using the capabilities opts choose of the client of the session an execution serves: only when the host opts in, and only while that client is connected and offers them. Everything else, and everything once the client is gone, goes to base. root is the workspace’s absolute path, as the client names files.

A client’s capabilities are weaker than an environment’s, and the result says so in its Enforcement: the client checks no workspace jail, so file access through it is at most advisory, and a client terminal enforces nothing. The client’s file system has no revisions: a write checks the file’s revision just before it, not with it, and takes text only. A client terminal takes no input and keeps only the output the client retains.

base must not be a ProcessReconciler, Snapshotter, Materializer or BundleReleaser: client filesystem/terminal mapping cannot preserve their reconciliation or protected publication namespaces. When base is a Differ, the result preserves its workspace baselines and diffs. These describe base’s files, not unsaved client buffers. The result also preserves base’s ability to confirm the loss of processes it started.

func Elicit(ctx context.Context, server string, e mcp.Elicitation) (mcp.ElicitationResult, error)

Elicit forwards a live MCP form on the same elicitation/create channel as AskUserQuestion, identifying the server and marking its message untrusted. A client without forms declines; a disconnected or cancelled wait cancels. This request is never durably suspended or answered by a later prompt.

func Serve(ctx context.Context, conn io.ReadWriteCloser, a Agent, opts ...Option) error

Serve serves a over ACP on conn until the client disconnects or ctx is done, and closes conn. Executions outlive the connection: a client that disconnects detaches, its sessions’ runs go on, and a request for permission stays pending in the session until a client takes the session up again (session/load, then a prompt). The agent owns them: closing it stops them. Serve returns nil when the client disconnects.

func ServeListener(ctx context.Context, ln net.Listener, a Agent, opts ...ListenOption) error

ServeListener serves ACP to every client ln accepts, at once, each as Serve serves one: newline-delimited JSON-RPC, as on standard input and output. All share a, so a session one client started can be loaded by another, and a prompt keeps running when its client leaves. It returns when ctx ends, or ln fails, after closing ln and every connection and waiting for them; a cancelled ctx returns nil.

Who may connect is the caller’s to decide: a Unix socket’s file permissions, say. ServeWebSocket checks a token.

Example

A host serves many editors at once on a Unix socket only its user may use, until ctx ends. path should be in a directory only the user can enter, so no one connects before the mode is set (zelk acp -listen makes the socket in a private directory and moves it into place).

var h acp.Agent // from zelk.ACP(agent)
serve := func(ctx context.Context, path string) error {
var lc net.ListenConfig
ln, err := lc.Listen(ctx, "unix", path)
if err != nil {
return err
}
if err := os.Chmod(path, 0o600); err != nil {
return err
}
return acp.ServeListener(ctx, ln, h, acp.WithLogger(slog.Default()))
}
_ = serve
func ServeWebSocket(ctx context.Context, ln net.Listener, token string, a Agent, opts ...ListenOption) error

ServeWebSocket serves ACP over WebSocket to every client ln accepts, at once, as ServeListener serves them. It follows the WebSocket profile of ACP’s remote transport draft: the handshake is a GET of WebSocketPath, answered with an Acp-Connection-Id header; each text message is one JSON-RPC message, and binary messages are ignored. The client sends initialize first, as on stdio.

The draft leaves authentication to the server. ln must be on a loopback address, and a client is let in only when its handshake carries “Authorization: Bearer <token>”, names a loopback host, and has no Origin header: a web page can’t connect, whatever it knows. It returns as ServeListener does.

Example

A host serves ACP’s WebSocket profile on loopback: clients connect to ws://127.0.0.1:PORT/acp with “Authorization: Bearer <token>”.

var h acp.Agent // from zelk.ACP(agent)
serve := func(ctx context.Context, token string) error {
var lc net.ListenConfig
ln, err := lc.Listen(ctx, "tcp", "127.0.0.1:0")
if err != nil {
return err
}
return acp.ServeWebSocket(ctx, ln, token, h)
}
_ = serve
func ServerName(name string) string

ServerName makes a client’s server name a valid MCP server name: each character but letters, digits, ‘_’ and ‘-’ becomes ‘_’, and it is cut to 32 bytes.

type Agent interface {
// Config is what the agent offers clients. Serve reads it once.
Config() Config
// SetModel returns the command that switches a session to model.
SetModel(ctx context.Context, model string) (event.Command, error)
// Start takes the session's lease and runs cmds in it, creating the
// session if it is new, with the client's setup for it.
// The execution runs under ctx.
Start(ctx context.Context, session string, setup Setup, cmds ...event.Command) (Execution, error)
// Status says where a session stands; ok is false for a session that
// has never started.
Status(ctx context.Context, session string) (st Status, ok bool, err error)
// History returns a session's whole conversation, with the turns
// compaction removed.
History(ctx context.Context, session string) ([]history.Item, error)
}

Agent is what Serve needs from zelk; zelk.ACP adapts a *zelk.Agent.

type Attacher interface {
Attach(ctx context.Context, setup Setup, text string) ([]event.Attachment, error)
}

Attacher is an Agent that resolves @ mentions before a prompt runs. Serve passes only text blocks, so embedded resources cannot trigger reads.

type ClientOption func(*clientEnv)

ClientOption chooses which of a client’s capabilities ClientEnv uses.

func WithClientFS() ClientOption

WithClientFS reads and writes files through the client, when it offers fs/read_text_file and fs/write_text_file: an editor then shows the agent its unsaved buffers and its own edits as they happen.

func WithClientTerminal() ClientOption

WithClientTerminal runs commands in the client’s terminals, when it offers them, so the user watches them run. A client terminal runs outside the host’s launcher: nothing zelk enforces holds for those commands.

type ClientTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"inputSchema"`
ReadOnly bool `json:"readOnly,omitempty"`
Idempotent bool `json:"idempotent,omitempty"`
}

ClientTool is a tool a client hosts, declared under _meta.zelk.tools. The model calls it as ClientToolPrefix+Name; the call goes to the client as _zelk/tool/call, within the run, and only while the client that declared it is connected. ReadOnly and Idempotent are the client’s claims: like an MCP server’s, they are never trusted.

func (t ClientTool) Tool() (*tool.Tool, error)

Tool returns t as a tool the agent can run: each call asks the client of the execution, from the context Serve gives it. Portable schemas retain the canonical path; foreign JSON Schema uses local validation and non-strict rendering.

type Config struct {
// Root is the workspace's absolute path, "" for an agent without one.
Root string
// Mode is the permission mode new sessions start in, and Modes are
// the modes a session may switch to.
Mode event.PermissionMode
Modes []event.PermissionMode
// Model is the model new sessions use, and Models are the models a
// session may switch to.
Model string
Models []string
// StdioMCP and HTTPMCP say which of a client's MCP servers the agent
// connects. ACP requires stdio of any agent that takes them.
StdioMCP, HTTPMCP bool
// ClientTools says the agent runs tools clients host (the tools
// extension).
ClientTools bool
}

Config is what an agent offers ACP clients, fixed for the agent’s lifetime.

type Controller interface {
// Send delivers c to session, to its running execution or to one it
// starts, and returns the sequence number of the event that accepted
// it once that is recorded: acceptance, not execution.
Send(ctx context.Context, session string, setup Setup, c event.Command) (uint64, error)
}

Controller is an Agent that takes commands outside a prompt, for the control extension: Serve offers it only to one.

type Delta struct {
EffectID string
Reasoning bool
Text string
}

Delta is a piece of a model turn as it streams.

type Execution interface {
// Updates returns the session's events from fromSeq on and the live
// deltas, until the execution ends.
Updates(ctx context.Context, fromSeq uint64) iter.Seq2[Update, error]
// Send gives the running execution a command.
Send(c event.Command) error
// Wait waits for the execution to end.
Wait(ctx context.Context) (Result, error)
}

Execution is a running execution of a session.

type Follower interface {
// Events returns the session's recorded events from fromSeq on.
Events(ctx context.Context, session string, fromSeq uint64) iter.Seq2[event.Event, error]
// Follow returns the session's events from fromSeq on, then follows
// it as it runs, with live deltas and lag markers, until ctx is done.
// It never skips or repeats an event.
Follow(ctx context.Context, session string, setup Setup, fromSeq uint64) iter.Seq2[Update, error]
}

Follower is an Agent that reads and follows sessions’ event logs, for the events extension: Serve offers it only to one.

type Forker interface {
Fork(ctx context.Context, from, id string, setup Setup) error
}

Forker is an Agent that copies a session’s conversation into a new session, id, for session/fork: Serve offers the method only to one. It returns ErrNoSession-like errors as is; Serve has already checked that from exists.

type ListenOption func(*listener)

ListenOption configures ServeListener and ServeWebSocket.

func WithConnOptions(opts ...Option) ListenOption

WithConnOptions configures each connection as Serve’s options do.

func WithLogger(l *slog.Logger) ListenOption

WithLogger logs what ends a client’s connection other than the client leaving. By default nothing is logged.

type Lister interface {
Sessions(ctx context.Context) ([]SessionInfo, error)
}

Lister is an Agent that lists its sessions, for session/list: Serve offers the method only to one. Sessions are those a client may take up with session/load: conversations, not subagents, with logs this version reads, most recently updated first.

type MCPServer struct {
// Name is the client's name for it.
Name string
// Command is the executable's absolute path. A Windows host may supply
// a name to resolve through PATH. Args are its arguments and Env is its
// environment, as KEY=value pairs.
Command string
Args []string
Env []string
// URL and Header reach a streamable HTTP server.
URL string
Header http.Header
// AlwaysLoad names the server's tools whose schemas stay visible when
// MCP tools are deferred ("*" for all of them). A host sets it from its
// own configuration; ACP's session/new carries no such field.
AlwaysLoad []string
}

MCPServer is an MCP server a client asks a session to use, from session/new or session/load. A stdio server has Command; an HTTP one has URL.

func (s MCPServer) AlwaysLoaded() []string

AlwaysLoaded returns the full tool names AlwaysLoad gives, as zelk.WithAlwaysLoadedTools takes them.

func (s MCPServer) Server(e env.Environment, client *http.Client, base []string) mcp.Server

Server returns s as package mcp reaches it, named for the session’s tools: a stdio server started in e, with base, such as the host’s command environment, under the client’s variables; an HTTP one through client. The name is the client’s, made a valid server name.

func (s MCPServer) Stdio() bool

Stdio reports whether the server is started as a process.

func (s MCPServer) String() string

String names the server for errors.

type Option func(*server)

Option configures Serve.

func WithInfo(name, version string) Option

WithInfo sets the name and version the server introduces itself with.

func WithStateDir(dir string) Option

WithStateDir names where the host keeps its sessions, so that refusing to load one this zelk can’t read says where it is.

type OutputStarter interface {
// StartOutput is Start with schema as the contract of the run the
// commands begin.
StartOutput(ctx context.Context, session string, setup Setup, schema json.RawMessage, cmds ...event.Command) (Execution, error)
}

OutputStarter is an Agent that can give a run its own structured output contract, for prompts of the results extension that ask for one.

type Overviewer interface {
Overview(ctx context.Context, session string, setup Setup) (o present.Overview, ok bool, err error)
}

Overviewer is an Agent that says where a session stands, for the /status command: Serve offers the command only to one. ok is false for a session that has never started.

type Recoverer interface {
Recover(ctx context.Context, session string, setup Setup) error
}

Recoverer is an Agent that recovers a session’s background work when a client loads it: work a host that has since gone left behind, and the completion wakes it is owed. session/load calls it after replaying the conversation, and reports a failure to the client without failing the load, so a session stays readable.

type Request struct {
ID string
event.AwaitInput
}

Request is a request for human input a session waits for.

type Result struct {
Outcome event.RunOutcome
Error string
// ErrorKind is the class of the model call failure that ended the run,
// if one did; the client is told the recovery that fits.
ErrorKind event.ModelErrorKind
// Report is the run's report, if the session keeps them; the client is
// told what it leaves open.
Report *event.Report
// Text is the run's answer (zelk.Result.Text). The client is sent it
// when the run's last message had no text: the model answered only in
// its report.
Text string
// Run, Usage, Ledger and Output are the run's ID, its measured usage,
// its budget commitment and its validated structured output, for the
// results extension.
Run uint64
Usage event.Usage
Ledger event.LedgerReport
Output json.RawMessage
// Requests are what a suspended session waits for.
Requests []Request
}

Result is how an execution ended.

type SessionInfo struct {
ID, Cwd, Title string
Updated time.Time
}

SessionInfo is a session as session/list shows it. Cwd is the workspace it continues in, with forward slashes.

type Setup struct {
Servers []MCPServer
Tools []ClientTool
}

Setup is what a client gives a session in session/new or session/load: the MCP servers it asks the session to use, and, with the tools extension, the tools it hosts. The agent that runs the session is built for its setup; a session keeps the tools of the setup it started with.

func (s Setup) Empty() bool

Empty reports whether the setup adds nothing to the host’s agent.

func (s Setup) ToolSet() ([]*tool.Tool, error)

ToolSet returns the client’s tools as tools an agent runs (zelk.WithTools).

type SkillCommand struct {
Name, Description, ArgumentHint string
}

SkillCommand is a skill as a slash command: its name, what it does, and a hint of what to pass it, which may be empty.

type Skiller interface {
SkillCommands(ctx context.Context, setup Setup) []SkillCommand
InvokeSkill(ctx context.Context, session string, setup Setup, name, args string, approve func(ctx context.Context, command, reason string) (bool, error)) (c event.Command, ok bool, err error)
}

Skiller is an Agent with skills the user runs by name: Serve offers them as slash commands beside its own, and a prompt “/name args” naming one invokes it. SkillCommands lists them for a client with setup; it may return none. InvokeSkill returns the command that invokes the skill name with args in session, and ok false when there is no such skill; approve asks the client about a skill’s shell command the session’s permissions ask about (zelk.WithShellApproval).

type Status struct {
Seq uint64
Suspended bool
Requests []Request
Mode event.PermissionMode
Model string
// Running says a run is under way, and Run is its ID, as a steer
// names it.
Running bool
Run uint64
// Goal is the session's goal: the request that began the latest run,
// unless GoalExplicit says a SetGoal set it. GoalAbandoned says the
// user abandoned it.
Goal string
GoalExplicit, GoalAbandoned bool
// Budget is the session's limits, nil without any; Ledger is the run
// under way's commitment against them, and SessionLedger the whole
// session's.
Budget *event.Budget
Ledger event.LedgerReport
SessionLedger event.LedgerReport
// Last is how the last finished run ended, Report its report and
// Output its structured output, if it has them.
Last *event.RunFinished
Report *event.Report
Output json.RawMessage
}

Status is a session’s state as Serve needs it.

type Update struct {
Event *event.Event
Delta *Delta
// Lagged says deltas were dropped: the text of model turns in progress
// is sent whole when they end.
Lagged bool
}

Update is a persisted event, a live delta, or a mark that deltas were lost.