acp

package
v0.40.3 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 9 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 is the inbound transport floor for the Agent Client Protocol (ACP, Zed-stewarded): line-delimited JSON-RPC 2.0 over an io.Reader (inbound) and io.Writer (outbound), plus a method dispatch table. The host writes one JSON object per line; the agent replies and streams notifications one JSON object per line; diagnostics go only to a structured logger (stderr in production), never onto the writer.

This package owns framing, ids, and error codes — it knows nothing about any concrete ACP method (session/*). Later tickets register handlers against the dispatch table as pure registrations. It defines its own JSON-RPC wire types and imports only the standard library; it is deliberately NOT coupled to the mobile-wire envelope types in internal/protocol.

Hard cost invariant (stated here, enforced by later tickets): when a subsequent ticket wires claude behind an ACP method, pyry acp MUST drive a real INTERACTIVE claude session billed under the interactive subscription — never the non-interactive `claude -p` path and never the metered Agent SDK. This ticket ships no claude driving and cannot violate the invariant; the constraint is recorded here so it stays visible at the transport layer.

Batch decision: a top-level JSON array (a JSON-RPC batch) is rejected with a single Invalid Request (-32600, id null). Batching is not supported — ACP does not use it, so this deviation from the spec's per-element batch handling is inert in practice and keeps the transport a strict one-frame-per-line reader.

Diagnostics MUST NOT log line bytes or params content: an ACP request's params may carry user prompt material. The transport logs only method names, error kinds, and structural facts — never the frame body.

Index

Constants

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

JSON-RPC 2.0 error codes. Handlers may reference these when returning an *Error; the transport itself produces CodeParseError, CodeInvalidRequest, CodeMethodNotFound, and CodeInternalError. CodeInvalidParams is provided for handlers that validate their params.

Variables

View Source
var ErrAlreadyResolved = errors.New("acp: response already resolved")

ErrAlreadyResolved is returned by Responder.Reply / Responder.ReplyError when the response has already been written (a double-resolve, or a resolve losing a race with another goroutine). The losing call writes no frame — it only reports that it did not answer.

View Source
var ErrDeferred = errors.New("acp: response deferred")

ErrDeferred is the sentinel a request Handler returns to tell dispatchRequest not to write a response now: the handler has taken ownership of its Responder (obtained via ResponderFrom) and will resolve it later, from any goroutine — e.g. a session/prompt handler holding its call open for the duration of a turn. A handler that returns ErrDeferred without stashing its Responder leaves the request unanswered forever; that ownership contract is the consumer's, not the transport's.

Functions

This section is empty.

Types

type Error

type Error struct {
	Code    int
	Message string
	// Data is optional structured detail; omitted from the wire when nil.
	Data any
}

Error is a JSON-RPC error a handler may return to control the wire error code. A handler returning a plain error instead maps to CodeInternalError with a generic message (the real error is logged to stderr, never leaked to the client).

func NewError

func NewError(code int, message string) *Error

NewError constructs an *Error carrying code and message (no data).

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type Handler

type Handler func(ctx context.Context, params json.RawMessage) (result any, err error)

Handler is the contract every later ACP-method ticket registers against. It receives the raw JSON-RPC params (may be nil) and returns either a result to marshal into the JSON-RPC "result", or an error. A notification handler returns (nil, nil) — "nothing". A returned *Error controls the wire error code and message; any other error maps to CodeInternalError with a generic message, the detail logged to stderr and never leaked to the client.

type Responder

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

Responder answers exactly one inbound request id, once, from any goroutine. dispatchRequest builds one per request and injects it into the handler's context; a handler that defers (returns ErrDeferred) keeps its Responder and resolves it later — e.g. from the outbound event goroutine when a turn ends.

Every answer for a given id — the synchronous success/error path taken by dispatchRequest and any deferred resolve — funnels through this one guarded handle, so "exactly one frame per id" is a structural invariant rather than a matter of handler discipline. Resolution goes through the transport's existing writeMu-guarded write path (writeSuccess / writeErrorWithData); no second write path is introduced.

func ResponderFrom

func ResponderFrom(ctx context.Context) *Responder

ResponderFrom returns the *Responder dispatchRequest injected into ctx, or nil when ctx carries none (a notification handler, or a context not derived from dispatchRequest). A handler that intends to defer must nil-check before stashing.

func (*Responder) ID added in v0.27.0

func (r *Responder) ID() json.RawMessage

ID returns a copy of the request id this Responder answers, as the peer sent it.

func (*Responder) Reply

func (r *Responder) Reply(result any) error

Reply resolves the request with a success result. The first call writes one success frame through the serialized write path and returns nil; any later call writes nothing and returns ErrAlreadyResolved. A result that fails to marshal still yields exactly one frame (an internal-error frame), matching writeSuccess's existing fallback.

func (*Responder) ReplyError

func (r *Responder) ReplyError(e *Error) error

ReplyError resolves the request with an error frame. The first call writes one error frame and returns nil; any later call writes nothing and returns ErrAlreadyResolved. A nil e is a consumer bug: it resolves as a generic internal error rather than panicking, preserving both never-panic and exactly-one-frame.

type Transport

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

Transport owns the line-delimited JSON-RPC 2.0 framing over one io.Reader (inbound) plus one io.Writer (outbound) and the method dispatch table.

func New

func New(r io.Reader, w io.Writer, log *slog.Logger) *Transport

New constructs a Transport reading JSON-RPC frames from r and writing them to w. r and w are required (panics if nil — programmer error). log is optional (nil → slog.Default()); diagnostics go only to log, never to w.

func (*Transport) Call

func (t *Transport) Call(ctx context.Context, method string, params any) (json.RawMessage, error)

Call issues a JSON-RPC 2.0 request to the client with a freshly-generated id and blocks until the response with the matching id is read, returning the result as raw JSON or the mapped *Error. A ctx cancellation returns ctx.Err() and reclaims the pending slot; a later matching response for a reclaimed id is dropped, not delivered.

Call MUST be issued from a goroutine other than the one running Serve. Inbound handlers dispatch inline on the read loop, so a Call that blocked that loop would deadlock — only the read loop reads the response Call awaits.

Ordering is load-bearing: params is marshalled first so a marshal failure burns no id and leaves no dangling slot, and the waiter is registered before the request is written so a fast response can never arrive before the slot exists.

func (*Transport) Notify

func (t *Transport) Notify(method string, params any) error

Notify writes one JSON-RPC 2.0 notification (method + params, no id) to the client. It mirrors Call minus the id / pending-channel machinery: params is marshalled first — nil omits the key, and a marshal failure writes nothing (no partial frame) — then the frame goes out through writeMessage under writeMu, the same leaf lock serialising reply and Call. Notify never awaits a response and never blocks on one; it is safe from any goroutine.

The streaming consumer (#750) calls this to emit session/update notifications; it is Call's write-only sibling and has no other caller yet.

func (*Transport) Register

func (t *Transport) Register(method string, h Handler)

Register binds h to a method name. Must be called before Serve. Panics on a duplicate method or if called after Serve has started (both programmer errors — mirrors internal/dispatch.Register).

func (*Transport) Serve

func (t *Transport) Serve(ctx context.Context) error

Serve reads frames until the reader reaches EOF (returns nil) or ctx is cancelled between frames (returns ctx.Err()). A structurally broken stream (over-long line or read error) returns a wrapped error. Serve never panics on malformed input — each malformed line produces a JSON-RPC error frame (or a silent drop for a response frame) and the loop continues.

A Read already blocked on a quiet reader cannot be unblocked by ctx alone (Go limitation); the ctx check happens between frames. In-memory callers terminate naturally at EOF; the subcommand (#756) unblocks a real blocked stdin by closing the reader on shutdown.

Jump to

Keyboard shortcuts

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