Documentation
¶
Overview ¶
Package acp implements a minimal Agent Client Protocol (ACP) client: gofer spawns an ACP agent as a child process and drives one prompt turn over its stdio (JSON-RPC 2.0, one message per line).
It is the transport half of the `acp-agent` type (see docs/design/2026-09-17-acp-agent-and-approval-gate-design.md §一): initialize → session/new → session/prompt, with session/update notifications delivered to a Handler and agent→client requests (session/request_permission) answered by it. The package knows nothing about jobs, config or logs — internal/runner/acp maps its events onto a job's stdout/acp.jsonl.
Scope (S0): one process per client, one session, one prompt turn. Results declare no fs/terminal capability, so an agent's fs/* and terminal/* requests are refused with JSON-RPC -32601 (method not found) like any unknown method.
Index ¶
- Constants
- Variables
- type AgentCapabilities
- type AvailableCommand
- type Client
- func (c *Client) Cancel(sessionID string) error
- func (c *Client) Close() error
- func (c *Client) DeadErr() error
- func (c *Client) Done() <-chan struct{}
- func (c *Client) Initialize(ctx context.Context) (InitializeResult, error)
- func (c *Client) LoadSession(ctx context.Context, params SessionLoadParams) (SessionNewResult, error)
- func (c *Client) NewSession(ctx context.Context, params SessionNewParams) (SessionNewResult, error)
- func (c *Client) Prompt(ctx context.Context, sessionID, text string, h Handler) (PromptResult, error)
- func (c *Client) SetConfigOption(ctx context.Context, sessionID, configID, value string) error
- func (c *Client) SetMode(ctx context.Context, sessionID, modeID string) error
- func (c *Client) SetModel(ctx context.Context, sessionID, modelID string) error
- type ClientCapabilities
- type ConfigOption
- type ConfigOptionValue
- type ContentBlock
- type EnvVariable
- type FSCapabilities
- type Handler
- type Implementation
- type InitializeParams
- type InitializeResult
- type MCPServer
- type Message
- type Options
- type PermissionOption
- type PermissionOutcome
- type Plan
- type PlanEntry
- type PromptParams
- type PromptResult
- type RPCError
- type RequestPermissionParams
- type SessionCancelParams
- type SessionLoadParams
- type SessionMode
- type SessionModel
- type SessionModels
- type SessionModes
- type SessionNewParams
- type SessionNewResult
- type SessionSetConfigParams
- type SessionSetModeParams
- type SessionSetModelParams
- type SessionUpdateParams
- type ToolCall
- type ToolCallLocation
- type Update
Constants ¶
const ( CodeParseError = -32700 CodeInvalidParams = -32602 CodeInternalError = -32603 CodeMethodNotFound = -32601 )
JSON-RPC 2.0 error codes we emit or care about.
const ( MethodInitialize = "initialize" MethodSessionNew = "session/new" MethodSessionLoad = "session/load" MethodSessionSetMode = "session/set_mode" MethodSessionSetConfig = "session/set_config_option" MethodSessionSetModel = "session/set_model" MethodSessionPrompt = "session/prompt" MethodSessionCancel = "session/cancel" MethodSessionUpdate = "session/update" MethodRequestPermission = "session/request_permission" )
JSON-RPC method names exchanged with the agent.
const ( StopEndTurn = "end_turn" StopMaxTokens = "max_tokens" StopMaxTurnRequests = "max_turn_requests" StopRefusal = "refusal" StopCancelled = "cancelled" )
session/prompt stopReason values.
const ( UpdateUserMessageChunk = "user_message_chunk" UpdateAgentMessageChunk = "agent_message_chunk" UpdateAgentThoughtChunk = "agent_thought_chunk" UpdateToolCall = "tool_call" UpdateToolCallUpdate = "tool_call_update" UpdatePlan = "plan" UpdateAvailableCommands = "available_commands_update" UpdateCurrentMode = "current_mode_update" // UpdateUsage is the token/cost accounting update an agent reports as it runs // (SUP-01 E). The spec leaves its payload to the agent (no typed fields here): // the raw object is what the runner reads its recognisable subset from. UpdateUsage = "usage_update" )
session/update discriminators (Update.Kind).
const ( ToolKindRead = "read" ToolKindEdit = "edit" ToolKindDelete = "delete" ToolKindMove = "move" ToolKindSearch = "search" ToolKindExecute = "execute" ToolKindThink = "think" ToolKindFetch = "fetch" ToolKindSwitchMode = "switch_mode" ToolKindOther = "other" )
toolCall.kind values — the ACP ToolKind vocabulary. A gofer policy that names tool kinds (the project approval gate) is validated against ToolKinds, so the vocabulary has exactly one home.
const ( OptionAllowOnce = "allow_once" OptionAllowAlways = "allow_always" OptionRejectOnce = "reject_once" OptionRejectAlways = "reject_always" )
session/request_permission option kinds.
const ( OutcomeSelected = "selected" OutcomeCancelled = "cancelled" )
PermissionOutcome.Outcome values.
const DefaultClientVersion = "0.0.0"
DefaultClientVersion is the clientInfo.version advertised when Options.ClientInfo carries none. A version is REQUIRED by the ACP schema in practice — the claude-code-acp adapter rejects an initialize whose clientInfo has no version (-32602 Invalid params) — so the client never omits it.
const ProtocolVersion = 1
ProtocolVersion is the ACP protocol version this client speaks (an integer in the wire protocol, per the design's protocol memo).
Variables ¶
var ToolKinds = []string{ ToolKindRead, ToolKindEdit, ToolKindDelete, ToolKindMove, ToolKindSearch, ToolKindExecute, ToolKindThink, ToolKindFetch, ToolKindSwitchMode, ToolKindOther, }
ToolKinds is the complete ToolKind vocabulary, in schema order.
Functions ¶
This section is empty.
Types ¶
type AgentCapabilities ¶
type AgentCapabilities struct {
LoadSession bool `json:"loadSession,omitempty"`
PromptCapabilities json.RawMessage `json:"promptCapabilities,omitempty"`
MCPCapabilities json.RawMessage `json:"mcpCapabilities,omitempty"`
}
AgentCapabilities is the agent's side of the capability negotiation. The prompt/mcp capability blocks are carried verbatim (S0 only reads LoadSession).
type AvailableCommand ¶
type AvailableCommand struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
}
AvailableCommand is one entry of available_commands_update.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client drives one ACP agent process: JSON-RPC 2.0 over its stdin/stdout, with concurrent-safe request/response correlation, notification dispatch and agent→client request handling.
One Client owns exactly one process. It is safe for concurrent use, but a turn (Prompt) must not be started twice at once: the agent serves one prompt per session at a time.
func Start ¶
Start launches the agent process and begins reading its stdout. The returned client owns the process until Close.
func (*Client) Cancel ¶
Cancel tells the agent to abort the session's current turn. It is a notification: the agent answers by ending the in-flight prompt with stopReason cancelled.
func (*Client) Close ¶
Close ends the client: stdin is closed (the agent's documented exit signal), then the process is given closeGrace to exit before its WHOLE PROCESS TREE is killed. It is idempotent.
Every wait here is bounded (F12): the tree kill removes descendants that could keep cmd.Wait blocked on inherited stdio; waitDelay and waitAfterKill bound the fallback if a process refuses to be reaped.
func (*Client) Done ¶
func (c *Client) Done() <-chan struct{}
Done closes when the agent protocol stream ends, including an unexpected process exit while no prompt call is in flight.
func (*Client) Initialize ¶
func (c *Client) Initialize(ctx context.Context) (InitializeResult, error)
Initialize performs the ACP handshake. This client declares no fs/terminal capability (the agent uses its own tools), so the agent must not delegate them.
func (*Client) LoadSession ¶
func (c *Client) LoadSession(ctx context.Context, params SessionLoadParams) (SessionNewResult, error)
LoadSession resumes an existing session (S2 uses it): the agent replays that session's history so the next prompt continues it. The agent must have declared agentCapabilities.loadSession.
The ACP schema's session/load response carries NO sessionId — what was loaded IS params.SessionID, and the result, when it carries anything, is the session's own state (modes/…) — so an empty result is a compliant answer and is attributed to the requested session. Requiring an id here failed every real resume with "session/load returned an empty sessionId" (ACP-02 真机, 2026-09-25: omp-acp and jcode-acp both answer this way). An agent that DOES answer with an id is a non-standard adapter: a differing id is warned about and then used, because the agent is the authority on what it actually loaded and the turn has to go there.
func (*Client) NewSession ¶
func (c *Client) NewSession(ctx context.Context, params SessionNewParams) (SessionNewResult, error)
NewSession opens a session in cwd, advertising the given MCP servers (nil/empty for none). The response MUST carry the session id every later call needs: that is what session/new answers with (unlike session/load), so an empty one is an agent bug, not a shape to interpret.
func (*Client) Prompt ¶
func (c *Client) Prompt(ctx context.Context, sessionID, text string, h Handler) (PromptResult, error)
Prompt runs one prompt turn: the text is sent as a single text content block and every session/update it triggers is delivered to h. The agent→client permission requests of the turn are answered by h too.
Cancellation: when ctx ends, session/cancel is sent first and the client waits up to cancelGrace for the agent's stopReason cancelled response — so a cancelled turn still reports its stopReason — then returns the context error. The caller closes (and, if needed, kills) the process.
func (*Client) SetConfigOption ¶
SetConfigOption sets a session config option (session/set_config_option); the model pick uses it with the option whose category is "model".
type ClientCapabilities ¶
type ClientCapabilities struct {
FS *FSCapabilities `json:"fs,omitempty"`
Terminal bool `json:"terminal"`
}
ClientCapabilities is what the client offers the agent. S0 declares NO fs and NO terminal delegation: the agent uses its own tools, so the fields stay nil/false and the agent's fs/*, terminal/* requests are refused with -32601.
type ConfigOption ¶
type ConfigOption struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Category string `json:"category,omitempty"`
Type string `json:"type,omitempty"`
CurrentValue json.RawMessage `json:"currentValue,omitempty"`
Options []ConfigOptionValue `json:"-"`
RawOptions json.RawMessage `json:"options,omitempty"`
}
ConfigOption is one session config option (select variant). Options is flattened: grouped options are merged into one list, which is all a model pick needs.
func (*ConfigOption) UnmarshalJSON ¶
func (o *ConfigOption) UnmarshalJSON(b []byte) error
UnmarshalJSON decodes the option and flattens its (flat or grouped) value list.
type ConfigOptionValue ¶
ConfigOptionValue is one selectable value of a ConfigOption.
type ContentBlock ¶
ContentBlock is one prompt/update content block. S0 only sends and consumes text blocks; other block types are carried by Raw where they matter.
type EnvVariable ¶
EnvVariable is one name/value pair of an MCP server's environment.
type FSCapabilities ¶
type FSCapabilities struct {
ReadTextFile bool `json:"readTextFile"`
WriteTextFile bool `json:"writeTextFile"`
}
FSCapabilities is the client-side file-system delegation block. Never set in S0.
type Handler ¶
type Handler interface {
// SessionUpdate receives one session/update payload for a session.
SessionUpdate(sessionID string, u Update)
// RequestPermission answers an agent's session/request_permission.
RequestPermission(req RequestPermissionParams) PermissionOutcome
}
Handler consumes what the agent sends: session/update notifications and agent→client requests. Both methods are called from the client's read loop goroutine (requests from their own goroutine, so a slow answer cannot block notifications), and must be safe for concurrent use.
type Implementation ¶
Implementation identifies a client or agent (clientInfo / agentInfo).
type InitializeParams ¶
type InitializeParams struct {
ProtocolVersion int `json:"protocolVersion"`
ClientCapabilities ClientCapabilities `json:"clientCapabilities"`
ClientInfo *Implementation `json:"clientInfo,omitempty"`
}
InitializeParams is the initialize request.
type InitializeResult ¶
type InitializeResult struct {
ProtocolVersion int `json:"protocolVersion"`
AgentCapabilities AgentCapabilities `json:"agentCapabilities"`
AgentInfo *Implementation `json:"agentInfo,omitempty"`
AuthMethods json.RawMessage `json:"authMethods,omitempty"`
}
InitializeResult is the initialize response.
type MCPServer ¶
type MCPServer struct {
Name string `json:"name"`
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Env []EnvVariable `json:"env,omitempty"`
}
MCPServer is one entry of session/new's mcpServers (stdio transport).
type Message ¶
type Message struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
Message is one JSON-RPC 2.0 message. ACP puts exactly one message per stdio line, so the codec below is line-oriented.
type Options ¶
type Options struct {
// Command is the ACP agent executable; Args its argv (the launch argv, never a
// prompt — the prompt travels over the protocol).
Command string
Args []string
// Dir is the working directory (the job's resolved cwd).
Dir string
// Env is layered over the process environment, like the local runner does.
Env map[string]string
// EnvDeny / EnvAllow filter the INHERITED process environment before Env is
// layered on (SEC-01, util.EnvironWithout): an ACP agent is a job process too, so
// it must not start holding the serve process's bearer token. See
// runner.Request.EnvDeny.
EnvDeny []string
EnvAllow []string
// Stderr receives the agent's own diagnostics verbatim (the protocol channel is
// stdin/stdout only). Nil discards them.
Stderr io.Writer
// ClientInfo identifies this client in initialize. Nil means {Name: "gofer"}.
ClientInfo *Implementation
}
Options configures Start.
type PermissionOption ¶
type PermissionOption struct {
OptionID string `json:"optionId"`
Name string `json:"name,omitempty"`
Kind string `json:"kind"`
}
PermissionOption is one choice offered by the agent's permission request.
type PermissionOutcome ¶
type PermissionOutcome struct {
Outcome string `json:"outcome"`
OptionID string `json:"optionId,omitempty"`
}
PermissionOutcome is the answer to a permission request: either a selected option or a cancellation. It marshals as the ACP `outcome` object.
func PermissionCancelled ¶
func PermissionCancelled() PermissionOutcome
PermissionCancelled answers a permission request without choosing an option (the agent then aborts the tool call / the turn).
func PermissionSelected ¶
func PermissionSelected(optionID string) PermissionOutcome
PermissionSelected answers a permission request with one of the offered options.
type Plan ¶
type Plan struct {
Entries []PlanEntry `json:"entries"`
}
Plan is the session/update plan payload.
type PlanEntry ¶
type PlanEntry struct {
Content string `json:"content"`
Priority string `json:"priority,omitempty"`
Status string `json:"status,omitempty"`
}
PlanEntry is one item of an agent plan.
type PromptParams ¶
type PromptParams struct {
SessionID string `json:"sessionId"`
Prompt []ContentBlock `json:"prompt"`
}
PromptParams is the session/prompt request.
type PromptResult ¶
type PromptResult struct {
StopReason string `json:"stopReason"`
}
PromptResult is the session/prompt response.
type RPCError ¶
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
RPCError is a JSON-RPC 2.0 error object.
type RequestPermissionParams ¶
type RequestPermissionParams struct {
SessionID string `json:"sessionId"`
ToolCall *ToolCall `json:"toolCall,omitempty"`
Options []PermissionOption `json:"options"`
}
RequestPermissionParams is the agent→client session/request_permission request.
type SessionCancelParams ¶
type SessionCancelParams struct {
SessionID string `json:"sessionId"`
}
SessionCancelParams is the session/cancel notification (a notification, not a request: the agent answers by ending the turn with stopReason cancelled).
type SessionLoadParams ¶
type SessionLoadParams struct {
SessionID string `json:"sessionId"`
Cwd string `json:"cwd"`
MCPServers []MCPServer `json:"mcpServers"`
}
SessionLoadParams is the session/load request (resume; S2).
type SessionMode ¶
type SessionMode struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
}
SessionMode is one selectable agent mode (e.g. read-only).
type SessionModel ¶
SessionModel is one selectable model.
type SessionModels ¶
type SessionModels struct {
CurrentModelID string `json:"currentModelId"`
AvailableModels []SessionModel `json:"availableModels"`
}
SessionModels is the model block of a session/new (or load) response.
type SessionModes ¶
type SessionModes struct {
CurrentModeID string `json:"currentModeId"`
AvailableModes []SessionMode `json:"availableModes"`
}
SessionModes is the mode block a session/new response may carry.
type SessionNewParams ¶
SessionNewParams is the session/new request.
type SessionNewResult ¶
type SessionNewResult struct {
SessionID string `json:"sessionId"`
Modes *SessionModes `json:"modes,omitempty"`
// ConfigOptions is the session's selectable settings (ACP "session config
// options"); the one with category "model" is how a client picks the model.
ConfigOptions []ConfigOption `json:"configOptions,omitempty"`
// Models is the older (unstable) model block some agents still answer with
// instead of a config option; session/set_model drives it.
Models *SessionModels `json:"models,omitempty"`
}
SessionNewResult is the session/new (and session/load) response.
type SessionSetConfigParams ¶
type SessionSetConfigParams struct {
SessionID string `json:"sessionId"`
ConfigID string `json:"configId"`
Value string `json:"value"`
}
SessionSetConfigParams is the session/set_config_option request.
type SessionSetModeParams ¶
type SessionSetModeParams struct {
SessionID string `json:"sessionId"`
ModeID string `json:"modeId"`
}
SessionSetModeParams is the session/set_mode request.
type SessionSetModelParams ¶
type SessionSetModelParams struct {
SessionID string `json:"sessionId"`
ModelID string `json:"modelId"`
}
SessionSetModelParams is the session/set_model request.
type SessionUpdateParams ¶
type SessionUpdateParams struct {
SessionID string `json:"sessionId"`
Update Update `json:"update"`
}
SessionUpdateParams is the session/update notification.
type ToolCall ¶
type ToolCall struct {
ToolCallID string `json:"toolCallId"`
Title string `json:"title,omitempty"`
Kind string `json:"kind,omitempty"`
Status string `json:"status,omitempty"`
Content json.RawMessage `json:"content,omitempty"`
Locations []ToolCallLocation `json:"locations,omitempty"`
RawInput json.RawMessage `json:"rawInput,omitempty"`
RawOutput json.RawMessage `json:"rawOutput,omitempty"`
}
ToolCall is ACP's tool_call payload. session/update carries it twice: kind tool_call (the initial call, with title/kind/rawInput) and kind tool_call_update (a status/content refresh, every field optional except toolCallId). One struct decodes both — Update.Kind tells which one arrived.
type ToolCallLocation ¶
ToolCallLocation is a file location a tool call touched.
type Update ¶
type Update struct {
Kind string
Raw json.RawMessage
MessageChunk *ContentBlock // agent_message_chunk / agent_thought_chunk / user_message_chunk
ToolCall *ToolCall // tool_call and tool_call_update
Plan *Plan // plan
CurrentModeID string // current_mode_update
AvailableCommands []AvailableCommand
}
Update is one decoded session/update payload. Kind is the `sessionUpdate` discriminator; Raw is the untouched update object, so a variant S0 does not model (or a future field) is still available to the caller. Exactly one typed payload is set for the kinds this client understands.
func (*Update) UnmarshalJSON ¶
UnmarshalJSON decodes the discriminated payload. The variant fields differ per kind (a message chunk's `content` is a block, a tool call's `content` is a list of tool-call content), which is why the split lives here rather than in a flat struct.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package acptest provides an in-repo fake ACP agent: a scripted JSON-RPC 2.0 stdio server used as a test double for internal/acp and internal/runner/acp.
|
Package acptest provides an in-repo fake ACP agent: a scripted JSON-RPC 2.0 stdio server used as a test double for internal/acp and internal/runner/acp. |