acpx

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

README

acpx

An Agent Client Protocol client layer for Go, on top of github.com/coder/acp-go-sdk v0.13.5. It adds ready-made calls for protocol features and agent extensions that the SDK does not type yet. The agents it was checked against are claude-agent-acp 0.100.0, codex-acp 2.5.0, OpenCode 1.19.5 and Hermes Agent 0.22.7.

It was written for a headless client that drives agents in sandboxes (k1dory/cluster-agent-k8s, cmd/agent-runner), but it does not depend on that project.

wire := acpx.NewWire(agentStdin, agentStdout, acpx.WireOptions{Notices: true, Compaction: true})
client.wire = wire // in its SessionUpdate: extra, sdk := wire.Classify(n.Update)
conn := wire.Connect(client)
init, _ := conn.Initialize(ctx, acp.InitializeRequest{ProtocolVersion: acp.ProtocolVersionNumber})

var meta map[string]any
if conn.Wire.SystemPrompt() { // sessionCapabilities.systemPrompt
	meta = acpx.SessionMeta(nil, "Follow the repository's conventions.")
}
s, _ := conn.NewSession(ctx, acp.NewSessionRequest{Cwd: dir, McpServers: []acp.McpServer{}, Meta: meta})
st := acpx.SessionState{Modes: s.Modes, Options: s.ConfigOptions}
_ = acpx.Configure(ctx, conn, s.SessionId, st, acpx.ModeSetting, "agent-full-access")
_ = acpx.Configure(ctx, conn, s.SessionId, st, acpx.ThoughtLevelSetting, "high")

// Later, while a prompt turn runs:
out, _ := conn.Steer(ctx, s.SessionId, "also update the tests") // injected | promptRequired

What it adds

Wire A JSON-RPC layer between the connection and the agent's stdio. The SDK drops some fields from initialize; Wire reads two of them, sessionCapabilities.systemPrompt and _meta.steering.supported. It advertises clientCapabilities.session.notices / .compaction, which ClientCapabilities cannot express. It carries a session's client system prompt (systemPrompt, mode append). It also decodes notice, compaction_update and compaction_summary_chunk. The SDK does not drop an update kind it does not know: it decodes it as whichever known kind its fields fit, so a notice with a title arrives as a session_info_update. Classify matches every update the SDK delivers with what was actually read. Called in the client's SessionUpdate, it says whether the SDK's update is genuine or is one of acpx's, keeping its place in the stream. Lines are handled up to the SDK's own 10 MiB limit, the same way however the agent's output is split into reads.
Conn The SDK's ClientSideConnection over a Wire. Adds Steer: the _session/steering extension (claude-agent-acp, codex-acp), which puts a message into the turn in progress. It uses idleBehavior: promptRequired, so the client still owns every turn.
Configure Selects a session's mode, model or reasoning level (thought_level) through the agent's configuration options. Mode falls back to session/set_mode. It matches the agent's own values: the exact value, a provider-qualified value (anthropic/claude-…), or a display name. It returns the session's state after the change: a new model may offer other reasoning levels. Anything it cannot apply comes back as an error to report.
SessionMeta Builds a session request's _meta from your metadata (for example claude-agent-acp's claudeCode.options) plus the system prompt.
Request, Pending Relays to a person what the agent asks them, for a headless client. A session/request_permission becomes PermissionRequest; an elicitation/create becomes ElicitationRequest, as a form with its JSON Schema or as a link such as an OAuth sign-in. Your client shows the request and sends back a Reply. PermissionResponse and ElicitationResponse turn that reply into the agent's answer and check it against the request. Pending keeps the agent's request open until the reply arrives, the time limit passes, or the context ends.
PromptBlocks Builds a prompt from text plus resource_link blocks for attached files. Every ACP agent takes these, so the agent sees the files as files.

When the SDK gains these fields, the wire-level parts can be removed.

Development

go vet ./... && go test -race ./...

Apache-2.0.

Documentation

Overview

Package acpx is an Agent Client Protocol (https://agentclientprotocol.com) client layer on top of github.com/coder/acp-go-sdk: ready calls for what the protocol and today's agents (claude-agent-acp, codex-acp, OpenCode, Hermes) offer beyond what the SDK (v0.13.5) types. It was written for a headless client that drives agents in sandboxes (k1dory/cluster-agent-k8s).

What it adds:

  • Wire, a JSON-RPC level layer between the connection and the agent's stdio. It reads the agent's capabilities the SDK drops from the initialize response (the client system prompt, steering), advertises the client's session capabilities the SDK cannot express (live notices, compaction updates), carries a session's system prompt, and hands over the session updates the SDK silently zeroes (notice, compaction_update, compaction_summary_chunk).
  • Conn: the SDK's client-side connection over a Wire, with Steer (_session/steering: a message joins the turn in progress) and the agent's capabilities.
  • Config options: select a session's mode, model or reasoning level by category (Configure), matching the agent's own values.
  • SessionMeta: a session request's _meta from the caller's free-form metadata and the system prompt.

Everything here is a client-side convenience over published ACP surfaces; when the SDK gains a field (systemPrompt, notices), the wire-level part of it can go.

Index

Constants

View Source
const (
	RequestPermission = "permission" // session/request_permission: pick one of the agent's options
	RequestForm       = "form"       // elicitation/create, form mode: fill a JSON-schema form
	RequestURL        = "url"        // elicitation/create, url mode: open a link (an OAuth sign-in) and come back
)

Request kinds.

View Source
const (
	ActionAccept  = "accept"
	ActionDecline = "decline"
	ActionCancel  = "cancel"
)

Reply actions.

View Source
const (
	UpdateNotice                 = "notice"
	UpdateCompaction             = "compaction_update"
	UpdateCompactionSummaryChunk = "compaction_summary_chunk"
)

Session update kinds acp-go-sdk v0.13.5 does not decode (it hands its client another kind's update for them, see Wire.Classify). The Wire decodes them for the client.

View Source
const MaxLine = 10 << 20

MaxLine is the longest line the Wire looks at: the connection's own limit (acp-go-sdk reads lines with a 10 MiB bufio.Scanner and cannot take a longer one). However the agent's output is cut into reads, a line up to it is looked at whole and a longer one not at all.

View Source
const SteerMethod = "_session/steering"

SteerMethod is the steering extension (claude-agent-acp, codex-acp): a message joins the turn in progress instead of waiting for it to end.

View Source
const SystemPromptMetaKey = "acpx/systemPrompt"

SystemPromptMetaKey marks a session request's system prompt: the text, in the request's _meta. The Wire moves it to the request's systemPrompt (append) and it never reaches the agent as metadata. acp-go-sdk v0.13.5 has no systemPrompt field.

Variables

View Source
var (
	ModeSetting = Setting{Name: "mode", Category: acp.SessionConfigOptionCategoryMode, Modes: true}
	// ModelSetting matches the model's name, a provider-qualified value (OpenCode's
	// anthropic/claude-…) or an option of that display name.
	ModelSetting = Setting{Name: "model", Category: acp.SessionConfigOptionCategoryModel, Match: MatchModel}
	// ThoughtLevelSetting is the reasoning level (codex-acp reasoning_effort, OpenCode effort,
	// Hermes reasoning_effort): its value or display name.
	ThoughtLevelSetting = Setting{Name: "thought_level", Category: acp.SessionConfigOptionCategoryThoughtLevel, Match: MatchValueOrName}
)

The settings a client can make; copy one and change Name to report it under the client's own name.

View Source
var ErrNoRequest = errors.New("no such request waiting")

ErrNoRequest: the reply names no request waiting (answered already, timed out, never was).

Functions

func CancelledElicitation added in v0.3.0

func CancelledElicitation() acp.UnstableCreateElicitationResponse

CancelledElicitation is the answer for a question nobody answered.

func ConfigOption

ConfigOption is the first select option of the category, nil when there is none.

func ElicitationResponse added in v0.3.0

func ElicitationResponse(r Request, reply Reply) (acp.UnstableCreateElicitationResponse, error)

ElicitationResponse is the answer to the agent for a person's reply. An accepted form must give every required field and only fields the schema has.

func KindOf added in v0.2.0

func KindOf(u acp.SessionUpdate) string

KindOf is the sessionUpdate kind of an update as the SDK decoded it ("" for none).

func MatchModel

func MatchModel(options []acp.SessionConfigSelectOption, model string) string

MatchModel picks the value that is the model's name, else one that ends in /<name>, else one whose display name is it.

func MatchValueOrName

func MatchValueOrName(options []acp.SessionConfigSelectOption, want string) string

MatchValueOrName picks the value that is want, else one whose display name is it.

func PermissionResponse added in v0.3.0

func PermissionResponse(r Request, reply Reply) (resp acp.RequestPermissionResponse, kind string, err error)

PermissionResponse is the answer to the agent for a person's reply: the option they picked (one the request offered), or a cancelled outcome for a declined or cancelled reply. kind is the picked option's kind, "cancelled" otherwise.

func PromptBlocks added in v0.3.0

func PromptBlocks(text string, files []string) []acp.ContentBlock

PromptBlocks is a prompt's content: the text, then a resource_link for each attached file (an absolute path in the agent's file system). Every ACP agent takes text and resource links (the baseline prompt capabilities): the agent sees the files as files, not as words in the text.

func SelectOptions

SelectOptions lists a select option's values, grouped or not.

func SelectValues

func SelectValues(opt *acp.SessionConfigOptionSelect) []string

SelectValues lists a select option's value ids.

func SessionMeta

func SessionMeta(meta map[string]any, systemPrompt string) map[string]any

SessionMeta is the _meta of a session request (new, load, resume): the caller's free-form metadata (claude-agent-acp reads claudeCode.options from it: maxTurns, maxBudgetUsd…) and, when the agent takes one, the system prompt (moved to the request's systemPrompt by the Wire). nil when there is neither.

Types

type Compaction

type Compaction struct {
	ID      string `json:"compactionId"`
	Status  string `json:"status"`
	Summary string `json:"-"`
	Error   string `json:"error,omitempty"`
}

Compaction is the state of one compaction of the session's context: in_progress, completed, failed or cancelled. Summary is the text of its summary, when the update carries one.

type CompactionSummaryChunk

type CompactionSummaryChunk struct {
	ID   string `json:"compactionId"`
	Text string `json:"-"`
}

CompactionSummaryChunk is a piece of a compaction's summary as it is written.

type Configurer

type Configurer interface {
	SetSessionMode(ctx context.Context, params acp.SetSessionModeRequest) (acp.SetSessionModeResponse, error)
	SetSessionConfigOption(ctx context.Context, params acp.SetSessionConfigOptionRequest) (acp.SetSessionConfigOptionResponse, error)
}

Configurer is what changing a session's configuration needs of a connection.

type Conn

type Conn struct {
	*acp.ClientSideConnection
	Wire *Wire
}

Conn is the client side of one ACP connection: the SDK's connection (every method it has is Conn's) over a Wire, plus the calls the SDK does not type.

func Dial

func Dial(client acp.Client, agentStdin io.Writer, agentStdout io.Reader, opts WireOptions) *Conn

Dial connects client to an agent over its stdin and stdout through a Wire. A client that calls Wire.Classify needs the Wire before the connection starts delivering updates: it makes the Wire with NewWire and connects with Wire.Connect instead.

func (*Conn) Steer

func (c *Conn) Steer(ctx context.Context, sessionID acp.SessionId, text string) (SteerOutcome, error)

Steer sends text into the turn in progress of a session. It asks the agent not to start a turn of its own when none is running (idleBehavior promptRequired), so the client keeps every turn a prompt it sent. An agent without steering (Wire.Steering false) is not asked: the result is SteerPromptRequired.

type ExtraUpdate

type ExtraUpdate struct {
	SessionID    string
	Notice       *Notice
	Compaction   *Compaction
	SummaryChunk *CompactionSummaryChunk
}

ExtraUpdate is one of those updates; exactly one of its pointers is set.

type Notice

type Notice struct {
	Severity    string `json:"severity"`
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
}

Notice is a user-facing notice from the agent: a limit reached, a degraded service, an error it recovered from. Severity is info, warning, error or the agent's own.

type Option added in v0.3.0

type Option struct {
	ID   string `json:"option_id"`
	Name string `json:"name"`
	Kind string `json:"kind"`
}

Option is one of a permission request's choices; Kind is allow_once, allow_always, reject_once or reject_always.

type Pending added in v0.3.0

type Pending struct {
	// contains filtered or unexported fields
}

Pending holds the requests waiting for a person, by id.

func NewPending added in v0.3.0

func NewPending() *Pending

NewPending is an empty set of requests.

func (*Pending) Open added in v0.3.0

func (p *Pending) Open(r Request) Request

Open gives r a fresh id and holds it until Wait returns.

func (*Pending) Resolve added in v0.3.0

func (p *Pending) Resolve(reply Reply) error

Resolve hands a reply to the request it names.

func (*Pending) Wait added in v0.3.0

func (p *Pending) Wait(ctx context.Context, id string, timeout time.Duration) (reply Reply, ok bool)

Wait waits for the reply to an open request; ok is false when the context ended or timeout passed first (timeout 0: no limit). The request is closed either way.

func (*Pending) Waiting added in v0.3.0

func (p *Pending) Waiting() []string

Waiting lists the ids of the requests waiting.

type Reply added in v0.3.0

type Reply struct {
	RequestID string         `json:"request_id"`
	OptionID  string         `json:"option_id,omitempty"`
	Action    string         `json:"action,omitempty"`
	Content   map[string]any `json:"content,omitempty"`
}

Reply is a person's answer: OptionID for a permission; Action (accept, decline, cancel) and, for an accepted form, Content.

type Request added in v0.3.0

type Request struct {
	ID         string   `json:"request_id"`
	Kind       string   `json:"kind"`
	ToolCallID string   `json:"tool_call_id,omitempty"` // permission: the tool call it is about
	Title      string   `json:"title,omitempty"`
	Message    string   `json:"message,omitempty"`
	Options    []Option `json:"options,omitempty"` // permission: the agent's choices
	// Schema is a form's requested schema (JSON Schema, object of primitive properties), as the
	// agent sent it.
	Schema json.RawMessage `json:"schema,omitempty"`
	URL    string          `json:"url,omitempty"`
}

Request is what the agent asks, in a form a person's client can show without knowing ACP.

func ElicitationRequest added in v0.3.0

func ElicitationRequest(p acp.UnstableCreateElicitationRequest) (Request, error)

ElicitationRequest describes an elicitation/create for a person.

func PermissionRequest added in v0.3.0

func PermissionRequest(p acp.RequestPermissionRequest) Request

PermissionRequest describes a session/request_permission for a person.

type SessionState

type SessionState struct {
	Modes   *acp.SessionModeState
	Options []acp.SessionConfigOption
}

SessionState is what the agent said about a session when it opened (new, load, resume): its modes and its configuration options. Either may be absent.

func Configure

func Configure(ctx context.Context, cf Configurer, sid acp.SessionId, st SessionState, s Setting, want string) (SessionState, error)

Configure selects want for the setting in a session and returns the session's state after it: selecting one option may change the others (codex-acp offers other reasoning levels for another model), so the next Configure is to be given that state. It changes nothing when the session already has the value; what cannot be applied (no such option, a value the agent does not offer, a refusal) is returned as an error to report, with the state unchanged, and the session keeps the agent's own value.

type Setting

type Setting struct {
	Name     string                          // for messages: "mode", "model"… (a caller may name its own setting)
	Category acp.SessionConfigOptionCategory // mode, model, thought_level
	// Modes: fall back to the session's modes (session/set_mode) when the agent has no config
	// option of the category. Only for the mode.
	Modes bool
	// Match picks the agent's value for want among its options; nil: the value itself.
	Match func(options []acp.SessionConfigSelectOption, want string) string
}

Setting names what to select and how a wanted value matches the agent's own.

type SteerOutcome

type SteerOutcome string

SteerOutcome is what became of a steered message.

const (
	// SteerInjected: the message joined the turn in progress.
	SteerInjected SteerOutcome = "injected"
	// SteerPromptRequired: no turn was running; the message was not taken and is to be sent as a
	// prompt of its own.
	SteerPromptRequired SteerOutcome = "promptRequired"
	// SteerStartedNewTurn: the agent started a turn with the message itself (an agent that ignores
	// idleBehavior). Its end is not the end of any prompt the client sent.
	SteerStartedNewTurn SteerOutcome = "startedNewTurn"
)

type Wire

type Wire struct {
	// contains filtered or unexported fields
}

Wire sits between the SDK's connection and the agent's stdio (Writer: to the agent, Reader: from it). Every byte passes through unchanged except the client's initialize request (the session capabilities) and a session request carrying SystemPromptMetaKey.

func NewWire

func NewWire(agentStdin io.Writer, agentStdout io.Reader, opts WireOptions) *Wire

NewWire layers a Wire over the agent's stdin (w) and stdout (r).

func (*Wire) Classify added in v0.2.0

func (x *Wire) Classify(u acp.SessionUpdate) (extra *ExtraUpdate, sdk bool)

Classify says what a session update the SDK hands its client really is. The client calls it once for every SessionUpdate, in order (the SDK delivers notifications in the order they came).

acp-go-sdk v0.13.5 does not know every kind of update: one it does not know is not dropped but decoded as whichever known kind its fields fit (a notice with a title arrives as a session_info_update). Classify matches the call with the notification the Wire read: sdk is true for an update the SDK decoded as what it is; otherwise the SDK's update is to be ignored, and extra is what acpx decoded of it (a notice, a compaction update or summary chunk; nil for a kind acpx does not decode either).

func (*Wire) Connect added in v0.2.0

func (x *Wire) Connect(client acp.Client) *Conn

Connect starts the SDK's client-side connection for client over the Wire.

func (*Wire) Read

func (x *Wire) Read(p []byte) (int, error)

Read passes the agent's output to the connection, looking at every line on the way. A line is looked at before the bytes that end it are returned, so what initialize declared is known by the time Initialize returns.

func (*Wire) Steering

func (x *Wire) Steering() bool

Steering reports whether the agent takes _session/steering (initialize _meta.steering.supported).

func (*Wire) SystemPrompt

func (x *Wire) SystemPrompt() bool

SystemPrompt reports whether the agent takes the client's system prompt (sessionCapabilities.systemPrompt in its initialize response).

func (*Wire) Write

func (x *Wire) Write(b []byte) (int, error)

Write passes the client's messages to the agent. The connection writes one whole message per call; initialize and a session request with the system prompt marker are rewritten.

type WireOptions

type WireOptions struct {
	// Notices and Compaction advertise clientCapabilities.session.notices / .compaction in
	// initialize: an agent sends notice, compaction_update and compaction_summary_chunk only to a
	// client that does. The client then gets them from Classify, in its SessionUpdate.
	Notices, Compaction bool
}

WireOptions says what the client advertises beyond the SDK's ClientCapabilities.

Jump to

Keyboard shortcuts

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