acp

package
v0.209.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	CodeParseError     = -32700
	CodeInvalidParams  = -32602
	CodeInternalError  = -32603
	CodeMethodNotFound = -32601
)

JSON-RPC 2.0 error codes we emit or care about.

View Source
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.

View Source
const (
	StopEndTurn         = "end_turn"
	StopMaxTokens       = "max_tokens"
	StopMaxTurnRequests = "max_turn_requests"
	StopRefusal         = "refusal"
	StopCancelled       = "cancelled"
)

session/prompt stopReason values.

View Source
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).

View Source
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.

View Source
const (
	OptionAllowOnce    = "allow_once"
	OptionAllowAlways  = "allow_always"
	OptionRejectOnce   = "reject_once"
	OptionRejectAlways = "reject_always"
)

session/request_permission option kinds.

View Source
const (
	OutcomeSelected  = "selected"
	OutcomeCancelled = "cancelled"
)

PermissionOutcome.Outcome values.

View Source
const (
	BlockTypeText  = "text"
	BlockTypeImage = "image"
)

BlockTypeText / BlockTypeImage are the ContentBlock.Type values a prompt uses.

View Source
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.

View Source
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

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).

func (AgentCapabilities) MCP added in v0.144.0

MCP decodes the agent's mcpCapabilities (zero value when absent or malformed).

func (AgentCapabilities) PromptImage added in v0.177.0

func (c AgentCapabilities) PromptImage() bool

PromptImage reports whether the agent advertised promptCapabilities.image (false when the block is absent or malformed: an agent that does not say so gets text only).

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

func Start(_ context.Context, opts Options) (*Client, error)

Start launches the agent process and begins reading its stdout. The returned client owns the process until Close.

func (*Client) Cancel

func (c *Client) Cancel(sessionID string) error

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

func (c *Client) Close() error

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) DeadErr

func (c *Client) DeadErr() error

DeadErr explains why Done closed.

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) PromptBlocks added in v0.177.0

func (c *Client) PromptBlocks(ctx context.Context, sessionID string, blocks []ContentBlock, h Handler) (PromptResult, error)

PromptBlocks is Prompt with explicit content blocks (text first, then images in order). The caller is responsible for only sending image blocks to an agent that advertised promptCapabilities.image (AgentCapabilities.PromptImage).

func (*Client) SetConfigOption

func (c *Client) SetConfigOption(ctx context.Context, sessionID, configID, value string) error

SetConfigOption sets a session config option (session/set_config_option); the model pick uses it with the option whose category is "model".

func (*Client) SetMode

func (c *Client) SetMode(ctx context.Context, sessionID, modeID string) error

SetMode switches a session's agent mode (e.g. a read-only mode). S2 drives it from job --read-only.

func (*Client) SetModel

func (c *Client) SetModel(ctx context.Context, sessionID, modelID string) error

SetModel switches the session's model through the older session/set_model method.

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

type ConfigOptionValue struct {
	Value string `json:"value"`
	Name  string `json:"name,omitempty"`
}

ConfigOptionValue is one selectable value of a ConfigOption.

type ContentBlock

type ContentBlock struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
	URI      string `json:"uri,omitempty"`
}

ContentBlock is one prompt/update content block. It sends and consumes text blocks and, for prompts, ACP image blocks (Type "image": Data is base64, MimeType the media type, URI optional). A text block marshals exactly as before — the image fields are omitempty.

func ImageBlock added in v0.177.0

func ImageBlock(mime string, data []byte) ContentBlock

ImageBlock builds an image content block from raw bytes (base64-encoded here).

func TextBlock added in v0.177.0

func TextBlock(text string) ContentBlock

TextBlock builds a text content block.

type EnvVariable

type EnvVariable struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

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 HTTPHeader added in v0.144.0

type HTTPHeader struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

HTTPHeader is one header of an HTTP MCP server.

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

type Implementation struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
}

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 MCPCapabilities added in v0.144.0

type MCPCapabilities struct {
	HTTP bool `json:"http,omitempty"`
	SSE  bool `json:"sse,omitempty"`
}

MCPCapabilities is the agent's mcpCapabilities block.

type MCPServer

type MCPServer struct {
	Name    string        `json:"name"`
	Command string        `json:"command"`
	Args    []string      `json:"args,omitempty"`
	Env     []EnvVariable `json:"env,omitempty"`
	Type    string        `json:"-"`
	URL     string        `json:"-"`
	Headers []HTTPHeader  `json:"-"`
}

MCPServer is one entry of session/new's mcpServers: the stdio transport (Command/Args/Env, no type field) or, with Type "http", the HTTP transport (URL/Headers), which an agent accepts only when it advertises mcpCapabilities.http.

func (MCPServer) MarshalJSON added in v0.144.0

func (m MCPServer) MarshalJSON() ([]byte, error)

MarshalJSON writes the shape of the server's 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 PromptCapabilities added in v0.177.0

type PromptCapabilities struct {
	Image bool `json:"image,omitempty"`
}

PromptCapabilities is the agent's promptCapabilities block.

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.

func (*RPCError) DataKind added in v0.168.0

func (e *RPCError) DataKind() (kind, resetAt string)

DataKind reads the agent's provider-error classification from the error's `data` object (suga: {"error_kind": "...", "reset_at": "..."}). Both are "" when the agent sent no data or none of these fields.

func (*RPCError) Error

func (e *RPCError) Error() string

Error implements error.

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

type SessionModel struct {
	ModelID string `json:"modelId"`
	Name    string `json:"name,omitempty"`
}

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

type SessionNewParams struct {
	Cwd        string      `json:"cwd"`
	MCPServers []MCPServer `json:"mcpServers"`
}

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

type ToolCallLocation struct {
	Path string `json:"path"`
	Line *int   `json:"line,omitempty"`
}

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

func (u *Update) UnmarshalJSON(b []byte) error

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL