Documentation
¶
Overview ¶
Package acp implements the Agent Client Protocol (ACP) surface for ZERO: a JSON-RPC 2.0 peer spoken over stdio (newline-delimited JSON) so editors such as Zed, JetBrains, and Neovim can drive ZERO's agent core as a backend.
The protocol shapes (method names, message fields) are derived solely from the public, Apache-licensed ACP specification at agentclientprotocol.com and the agentclientprotocol/agent-client-protocol repository (schema/v1). All logic here is written originally against ZERO's own interfaces.
Index ¶
- Constants
- func RPCError(code int, message string) error
- type Agent
- type AgentCapabilities
- type AuthMethod
- type AvailableCommand
- type AvailableCommandsUpdate
- type BrowserToolDetails
- type CancelParams
- type ClientCapabilities
- type Conn
- type ContentBlock
- type ContentChunk
- type CurrentModeUpdate
- type Deps
- type FileSystemCapabilities
- type HandlerFunc
- type Implementation
- type InitializeParams
- type InitializeResult
- type ListSessionsParams
- type ListSessionsResult
- type LoadSessionParams
- type LoadSessionResult
- type McpServer
- type NewSessionParams
- type NewSessionResult
- type NotifyFunc
- type PermissionOption
- type PlanEntry
- type PlanUpdate
- type PromptCapabilities
- type PromptParams
- type PromptResult
- type RequestPermissionOutcome
- type RequestPermissionParams
- type RequestPermissionResult
- type ResumeSessionParams
- type ResumeSessionResult
- type SessionCapabilities
- type SessionConfigOption
- type SessionConfigOptionValue
- type SessionInfo
- type SessionInfoMeta
- type SessionMode
- type SessionModeState
- type SessionNotification
- type SetSessionConfigOptionParams
- type SetSessionConfigOptionResult
- type SetSessionModeParams
- type SetSessionModeResult
- type ToolCallContent
- type ToolCallLocation
- type ToolCallUpdate
- type Workspace
- type ZeroSetModelParams
- type ZeroSetModelResult
Constants ¶
const ( MethodInitialize = "initialize" MethodAuthenticate = "authenticate" MethodSessionNew = "session/new" MethodSessionLoad = "session/load" MethodSessionList = "session/list" MethodSessionResume = "session/resume" MethodSessionPrompt = "session/prompt" MethodSessionCancel = "session/cancel" // notification MethodSessionUpdate = "session/update" // notification (agent -> client) MethodSessionSetMode = "session/set_mode" MethodSessionSetConfigOption = "session/set_config_option" MethodSessionRequestPerm = "session/request_permission" // agent -> client MethodFSReadTextFile = "fs/read_text_file" // agent -> client MethodFSWriteTextFile = "fs/write_text_file" // agent -> client // Vendor-prefixed ZERO extensions (clients that don't support them ignore the // method and degrade cleanly, per the spec's _-prefixed convention). MethodZeroSetModel = "_zero/set_model" )
Method names exactly as they appear on the wire (public ACP spec).
const ( UpdateAgentMessageChunk = "agent_message_chunk" UpdateAgentThoughtChunk = "agent_thought_chunk" UpdateUserMessageChunk = "user_message_chunk" UpdateToolCall = "tool_call" UpdateToolCallUpdate = "tool_call_update" UpdatePlan = "plan" UpdateAvailableCommands = "available_commands_update" UpdateCurrentMode = "current_mode_update" )
SessionUpdate discriminator values (the "sessionUpdate" field).
const ( StopEndTurn = "end_turn" StopMaxTokens = "max_tokens" StopRefusal = "refusal" StopCancelled = "cancelled" )
StopReason values (why a prompt turn ended).
const ( ToolKindRead = "read" ToolKindEdit = "edit" ToolKindDelete = "delete" ToolKindMove = "move" ToolKindSearch = "search" ToolKindExecute = "execute" ToolKindThink = "think" ToolKindFetch = "fetch" ToolKindOther = "other" )
ToolKind classifies a tool call for client rendering.
const ( ToolStatusPending = "pending" ToolStatusInProgress = "in_progress" ToolStatusCompleted = "completed" ToolStatusFailed = "failed" )
ToolCallStatus values.
const ( PlanStatusPending = "pending" PlanStatusInProgress = "in_progress" PlanStatusCompleted = "completed" PlanPriorityHigh = "high" PlanPriorityMedium = "medium" PlanPriorityLow = "low" )
const ( PermAllowOnce = "allow_once" PermAllowAlways = "allow_always" PermRejectOnce = "reject_once" PermRejectAlways = "reject_always" )
const ( OutcomeSelected = "selected" OutcomeCancelled = "cancelled" )
const ProtocolVersion = 1
ProtocolVersion is the ACP protocol version ZERO speaks. Wire compatibility is negotiated during initialize; v1 is the current stable version.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is the ACP agent server bound to one JSON-RPC connection (one editor).
type AgentCapabilities ¶
type AgentCapabilities struct {
LoadSession bool `json:"loadSession"`
PromptCapabilities PromptCapabilities `json:"promptCapabilities"`
SessionCapabilities *SessionCapabilities `json:"sessionCapabilities,omitempty"`
}
type AuthMethod ¶
type AvailableCommand ¶
type AvailableCommandsUpdate ¶
type AvailableCommandsUpdate struct {
SessionUpdate string `json:"sessionUpdate"`
AvailableCommands []AvailableCommand `json:"availableCommands"`
}
type BrowserToolDetails ¶
BrowserToolDetails identifies the browser helper operation behind a tool call. Version is the schema version for this optional ZERO extension; Command is one of install, launch, connect, open, snapshot, click, type, press, or action. Future fields must remain display-safe and must not include browser profile data, cookies, typed text, URL paths/queries, or DevTools endpoints.
type CancelParams ¶
type CancelParams struct {
SessionID string `json:"sessionId"`
}
type ClientCapabilities ¶
type ClientCapabilities struct {
FS FileSystemCapabilities `json:"fs"`
Terminal bool `json:"terminal"`
}
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a JSON-RPC 2.0 peer over a single ndjson stream pair. It both serves inbound requests/notifications (via registered handlers) and issues outbound requests/notifications — needed because ACP is bidirectional (the agent calls the client for session/request_permission, fs/*, terminal/*).
func NewConn ¶
NewConn builds a peer reading ndjson from r and writing ndjson to w. This Conn does not own r: cancelling Serve's context cannot forcibly close it, so a Read on r that's genuinely idle (never returns on its own) leaves Serve blocked until r itself produces something — e.g. a test that closes r's own write side to unblock it. Use NewOwnedConn when this Conn should own r's lifetime.
func NewOwnedConn ¶
NewOwnedConn is like NewConn but declares that this Conn exclusively owns r: if r implements io.Closer, Serve closes it on context cancellation to interrupt an otherwise-idle blocking Read. Only pass a reader whose lifetime this Conn should control — e.g. the process's own stdin — never a reader a caller retains or shares elsewhere, since cancellation tears it down permanently for every consumer, not just this Conn.
func (*Conn) Call ¶
Call issues an outbound request and blocks until the response arrives, ctx is cancelled, or the connection closes.
func (*Conn) Handle ¶
func (c *Conn) Handle(method string, fn HandlerFunc)
Handle registers a request handler for method.
func (*Conn) HandleNotify ¶
func (c *Conn) HandleNotify(method string, fn NotifyFunc)
HandleNotify registers a notification handler for method.
func (*Conn) Serve ¶
Serve runs the read loop until the stream ends, ctx is cancelled, or a fatal decode error occurs. Inbound requests and notifications are dispatched on their own goroutines so a long-running handler (e.g. session/prompt) never blocks the loop from delivering session/cancel or a permission response.
type ContentBlock ¶
type ContentBlock struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"` // image/audio: base64
MimeType string `json:"mimeType,omitempty"` // image/audio
URI string `json:"uri,omitempty"` // resource_link
Name string `json:"name,omitempty"` // resource_link
Resource json.RawMessage `json:"resource,omitempty"` // embedded resource
}
ContentBlock is the polymorphic content type. ZERO emits "text" (and "image" on tool content); it parses "text", "image", and "resource"/"resource_link" from inbound prompts. A single struct with omitempty fields covers both directions since the field names do not collide across the variants ZERO uses.
func TextBlock ¶
func TextBlock(text string) ContentBlock
type ContentChunk ¶
type ContentChunk struct {
SessionUpdate string `json:"sessionUpdate"`
MessageID string `json:"messageId,omitempty"`
Content ContentBlock `json:"content"`
}
AgentMessageChunk / AgentThoughtChunk / UserMessageChunk all carry a single ContentBlock under "content"; the variant is set via SessionUpdate.
type CurrentModeUpdate ¶
type Deps ¶
type Deps struct {
ResolveConfig func(workspaceRoot string, overrides config.Overrides) (config.ResolvedConfig, error)
DiscoverModels func(context.Context, config.ProviderProfile) ([]providermodeldiscovery.Model, error)
NewProvider func(profile config.ProviderProfile) (zeroruntime.Provider, error)
RunAgent func(ctx context.Context, prompt string, provider zeroruntime.Provider, opts agent.Options) (agent.Result, error)
// BuildWorkspace creates the per-turn scoped tool workspace for a validated
// workspace root. Its Close method releases any resources the registry owns
// (notably MCP server connections) after the turn completes or is cancelled.
// Shell tools remain confined exactly like the exec surface — never unconfined
// on the host.
BuildWorkspace func(ctx context.Context, workspaceRoot string, resolved config.ResolvedConfig, mode agent.PermissionMode) (*Workspace, error)
// ResolveWorkspaceRoot validates + normalizes a client-supplied cwd (must be an
// existing directory; never the bare root). It is the file-tool confinement root.
ResolveWorkspaceRoot func(cwd string) (string, error)
// PersistEvents is an optional test seam for injecting event-store failures.
// It receives a COMPLETED TURN as one batch, never one event at a time: the
// batch is the unit the shared store keeps contiguous (see persistTurn).
PersistEvents func(sessionID string, inputs []sessions.AppendEventInput) error
Store *sessions.Store
AgentInfo Implementation
}
Deps are the ZERO capabilities the ACP Agent drives. The CLI fills these with real implementations; tests inject fakes (e.g. a canned provider) to drive the full ACP flow without a live model. Keeping auth/model/keys behind these deps means the editor only hosts the thread — ZERO owns BYOK and telemetry-free operation.
type FileSystemCapabilities ¶
type HandlerFunc ¶
HandlerFunc handles an inbound request and returns the result to encode, or an error. Returning an *rpcError controls the wire code; any other error becomes a generic internal error.
type Implementation ¶
type InitializeParams ¶
type InitializeParams struct {
ProtocolVersion int `json:"protocolVersion"`
ClientCapabilities ClientCapabilities `json:"clientCapabilities"`
ClientInfo *Implementation `json:"clientInfo,omitempty"`
}
type InitializeResult ¶
type InitializeResult struct {
ProtocolVersion int `json:"protocolVersion"`
AgentCapabilities AgentCapabilities `json:"agentCapabilities"`
AgentInfo *Implementation `json:"agentInfo,omitempty"`
AuthMethods []AuthMethod `json:"authMethods"`
}
type ListSessionsParams ¶
type ListSessionsParams struct {
Cwd string `json:"cwd,omitempty"`
Cursor string `json:"cursor,omitempty"`
}
ListSessionsParams and the following types implement ACP v1 session/list. Transcript contents stay behind session/load; this method returns metadata only and leaves the optional pagination cursor opaque.
type ListSessionsResult ¶
type ListSessionsResult struct {
Sessions []SessionInfo `json:"sessions"`
NextCursor string `json:"nextCursor,omitempty"`
}
type LoadSessionParams ¶
type LoadSessionResult ¶
type LoadSessionResult struct {
ConfigOptions []SessionConfigOption `json:"configOptions,omitempty"`
Modes *SessionModeState `json:"modes,omitempty"`
}
type McpServer ¶
type McpServer struct {
Name string `json:"name"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Env json.RawMessage `json:"env,omitempty"`
URL string `json:"url,omitempty"`
}
McpServer mirrors the editor-provided MCP server entry. ZERO owns its own MCP configuration (BYOK), so these are accepted for spec compliance; ZERO's configured servers remain authoritative.
type NewSessionParams ¶
type NewSessionParams struct {
Cwd string `json:"cwd"`
McpServers []McpServer `json:"mcpServers"`
// AdditionalDirectories is declared by the protocol and consumed nowhere in
// this repo yet. When it is wired up it must go through requestedWorkspace
// like Cwd does: these are client-supplied paths with no absoluteness rule of
// their own, which is the same shape as the resume-cwd hole that made
// {"sessionId":"known"} activate a session against this process's directory.
AdditionalDirectories []string `json:"additionalDirectories,omitempty"`
}
type NewSessionResult ¶
type NewSessionResult struct {
SessionID string `json:"sessionId"`
ConfigOptions []SessionConfigOption `json:"configOptions,omitempty"`
Modes *SessionModeState `json:"modes,omitempty"`
}
type NotifyFunc ¶
type NotifyFunc func(ctx context.Context, params json.RawMessage)
NotifyFunc handles an inbound notification (no response is sent).
type PermissionOption ¶
type PlanUpdate ¶
type PromptCapabilities ¶
type PromptParams ¶
type PromptParams struct {
SessionID string `json:"sessionId"`
Prompt []ContentBlock `json:"prompt"`
}
type PromptResult ¶
type PromptResult struct {
StopReason string `json:"stopReason"`
}
type RequestPermissionOutcome ¶
type RequestPermissionOutcome struct {
Outcome string `json:"outcome"`
OptionID string `json:"optionId,omitempty"`
}
RequestPermissionOutcome is a tagged union: {"outcome":"cancelled"} or {"outcome":"selected","optionId":"..."}.
type RequestPermissionParams ¶
type RequestPermissionParams struct {
SessionID string `json:"sessionId"`
ToolCall ToolCallUpdate `json:"toolCall"`
Options []PermissionOption `json:"options"`
}
type RequestPermissionResult ¶
type RequestPermissionResult struct {
Outcome RequestPermissionOutcome `json:"outcome"`
}
type ResumeSessionParams ¶
type ResumeSessionParams = LoadSessionParams
session/resume takes session/load's wire shape, so its cwd is a plain string too and an omitted one decodes exactly like an empty one. Sharing the type is safe only because activatePersistedSession requires an absolute cwd from the request itself — nothing downstream may supply a default for either method.
type ResumeSessionResult ¶
type ResumeSessionResult = LoadSessionResult
type SessionCapabilities ¶
type SessionCapabilities struct {
List *struct{} `json:"list,omitempty"`
Resume *struct{} `json:"resume,omitempty"`
}
Empty capability objects are presence flags in ACP v1. Pointers preserve the wire distinction between an advertised `{}` and an omitted capability.
type SessionConfigOption ¶
type SessionInfo ¶
type SessionInfo struct {
SessionID string `json:"sessionId"`
Cwd string `json:"cwd"`
Title string `json:"title,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"`
Meta *SessionInfoMeta `json:"_meta,omitempty"`
}
type SessionInfoMeta ¶
type SessionMode ¶
type SessionModeState ¶
type SessionModeState struct {
CurrentModeID string `json:"currentModeId"`
AvailableModes []SessionMode `json:"availableModes"`
}
type SessionNotification ¶
type SetSessionConfigOptionResult ¶
type SetSessionConfigOptionResult struct {
ConfigOptions []SessionConfigOption `json:"configOptions"`
}
type SetSessionModeParams ¶
type SetSessionModeResult ¶
type SetSessionModeResult struct{}
type ToolCallContent ¶
type ToolCallContent struct {
Type string `json:"type"`
// type == "content"
Content *ContentBlock `json:"content,omitempty"`
// type == "diff"
Path string `json:"path,omitempty"`
OldText *string `json:"oldText,omitempty"`
NewText *string `json:"newText,omitempty"`
}
ToolCallContent is a tool call's rendered output. ZERO emits "content" (a text/image block) and "diff" (a file change); "terminal" is part of the spec but unused because ZERO executes locally.
func ToolContent ¶
func ToolContent(block ContentBlock) ToolCallContent
func (ToolCallContent) MarshalJSON ¶
func (content ToolCallContent) MarshalJSON() ([]byte, error)
MarshalJSON preserves ACP's discriminated content union. A diff always has path, while nullable oldText/newText distinguish creation, deletion, and an existing file replaced with empty content. Other content variants omit all diff fields rather than serializing irrelevant nulls.
type ToolCallLocation ¶
type ToolCallUpdate ¶
type ToolCallUpdate struct {
SessionUpdate string `json:"sessionUpdate,omitempty"`
ToolCallID string `json:"toolCallId"`
Title string `json:"title,omitempty"`
Kind string `json:"kind,omitempty"`
Status string `json:"status,omitempty"`
RawInput json.RawMessage `json:"rawInput,omitempty"`
Content []ToolCallContent `json:"content,omitempty"`
Locations []ToolCallLocation `json:"locations,omitempty"`
// Meta is ACP's extension channel. ZERO-owned values must remain beneath a
// namespaced key so protocol-shaped clients can preserve them while decoding
// and re-encoding a tool call.
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
ToolCallUpdate is used for both the initial "tool_call" and subsequent "tool_call_update" notifications (distinguished by SessionUpdate). It also appears inside session/request_permission.
type Workspace ¶
type Workspace struct {
Registry *tools.Registry
Sandbox *sandbox.Engine
DeferThreshold int
Notices []string
Cleanup func() error
}
Workspace is the per-turn execution environment passed to the agent. ACP does not retain it across turns because MCP connections belong to the registry that advertised their tools; keeping a stale registry after a cancelled turn would leak its server process and its permission state into the next turn.
type ZeroSetModelParams ¶
type ZeroSetModelResult ¶
type ZeroSetModelResult struct {
Model string `json:"model"`
}