client

package
v0.51.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 17 Imported by: 3

Documentation

Overview

Package client wraps acp-go-sdk's low-level Connection for ACP relays. It manages a single stdio child agent process (e.g. fir --mode acp) and dispatches inbound server-initiated ACP calls — session updates, permission requests, fs reads/writes — back to the relay.

One AgentProc runs one ACP child process. It can serve many sessions concurrently — each NewSession/ResumeSession registers a per-session sink that receives the stream of session/update notifications.

The client talks to acp.Connection directly (rather than acp.ClientSideConnection) so it can issue the unstable session/list and session/resume methods that the SDK doesn't model. Standard methods are sent via acp.SendRequest with the SDK's typed request/response structs.

Security: the fs methods (ReadTextFile / WriteTextFile) currently require absolute paths but do not sandbox to the session cwd. That is adequate for trusted-agent relay deployments; do not expose this client to untrusted agents.

Notices: out-of-band operational messages from the agent.

Index

Constants

View Source
const (
	NoticeLevelInfo    = "info"
	NoticeLevelWarning = "warning"
	NoticeLevelError   = "error"
)

Notice levels.

View Source
const DefaultNoProgressTimeout = 2 * time.Minute

DefaultNoProgressTimeout bounds a wedged turn when TurnLivenessConfig.NoProgressTimeout is unset. Two minutes of total silence from an agent — not one token, not one tool call — is already far outside normal behaviour, while being generous enough never to cut a turn that is merely slow.

View Source
const NoticeMethod = "_dev.acp-kit/notice"

NoticeMethod is the ACP extension method carrying agent notices.

It exists because the alternative does not work. An agent that reports operational events — a provider rate-limit retry, a failed compaction — as agent message text puts them on the SAME ordered stream as the model's answer tokens, byte-identical and indistinguishable. A notice emitted by a background goroutine then lands wherever the stream happens to be, which in practice means mid-sentence, inside the user's reply. No separator or formatting can fix that: two independent writers share one stream.

A distinct JSON-RPC method breaks the tie. The relay can route notices to a status line or placeholder, and the answer stream stays the answer.

The name is namespaced under acp-kit rather than any one agent so sibling relays (zulip-acp, poe-acp, slack-acp) share a single handler.

Version skew is safe by construction: the ACP spec says implementations SHOULD ignore unrecognized notifications, so an old relay drops notices from a new agent, and a new relay simply never sees them from an old agent.

See: https://agentclientprotocol.com/protocol/extensibility

View Source
const SessionNotFoundCode = -32001

SessionNotFoundCode is the stable JSON-RPC error code an ACP agent returns when a request references a session it no longer holds in memory (released or idle-reaped). It is the shared contract between the agent (fir) and relays: on this code a relay can drop its cached session and re-create it.

Variables

View Source
var (
	// ErrNoProgress is the cause when a turn produced no evidence of agent
	// progress within TurnLivenessConfig.NoProgressTimeout.
	ErrNoProgress = errors.New("acp: agent made no progress within the liveness window")
	// ErrTurnCeiling is the cause when a turn ran past the opt-in absolute
	// ceiling TurnLivenessConfig.MaxTurnDuration, regardless of progress.
	ErrTurnCeiling = errors.New("acp: turn exceeded its absolute ceiling")
)

Sentinel causes reported through context.Cause on a context returned by StartTurnLiveness. They exist so a relay can tell WHY a turn ended and say something useful to the user: a plain context.Canceled means a human (or a superseding message) stopped the turn, ErrNoProgress means the agent went quiet, ErrTurnCeiling means an operator-configured hard cap fired.

View Source
var ErrAgentClosed = errors.New("acp agent closed")

ErrAgentClosed is the exit result reported by Err when the agent process went away because Close asked it to. It is the marker for "this death was expected"; anything else Err reports is an unexpected exit that the relay should treat as an outage.

View Source
var ErrAgentDied = errors.New("acp agent died")

ErrAgentDied is returned (wrapped, together with the child's exit result) by calls that were in flight when the agent child died, and by calls made while a replacement child is being spawned. With supervision on, retrying after a moment will reach the respawned agent.

View Source
var ErrAgentExited = errors.New("acp agent exited")

ErrAgentExited is the exit result reported when the agent process exited on its own with status 0. It exists so every terminated child has a non-nil exit result — a clean exit is still an outage for a relay that expected a long-lived child.

View Source
var ErrForkUnsupported = errors.New("acp agent: session/fork not supported")

ErrForkUnsupported is returned by ForkSession when the agent does not advertise sessionCapabilities.fork (or, with a fork point, fork._meta.at). Callers should fall back to a fresh session.

Functions

func AllowAllPermissions

AllowAllPermissions approves a request by selecting an allow-shaped option, falling back to the first option when no option advertises allow/approve.

func DenyAllPermissions

DenyAllPermissions rejects a request by selecting a reject-shaped option, falling back to the first option when no option advertises reject/deny.

func IsProgress added in v0.16.0

func IsProgress(u acp.SessionUpdate) bool

IsProgress reports whether a session/update is evidence that the agent is doing work, as opposed to merely being alive.

Progress is agent output — message and thought chunks — plus tool_call and tool_call_update: a running tool is the whole reason a turn may be long, so it must count. Everything else is explicitly not progress. Plans, available commands, mode and config changes, session info and echoed user message chunks are bookkeeping an agent (or its harness) can emit while wedged; if they reset the clock, a hung turn whose spinner keeps ticking is never detected, which is the exact failure this construct exists to catch.

The rule is exported so consumers can classify updates the same way — and so it is testable in one place rather than reimplemented per relay.

func IsSessionNotFound added in v0.2.3

func IsSessionNotFound(err error) bool

IsSessionNotFound reports whether err is the typed ACP session-not-found error (JSON-RPC code SessionNotFoundCode). Relays use it to distinguish a recoverable "agent forgot this session" condition from other failures.

func IsUnknownAuthMethod added in v0.40.0

func IsUnknownAuthMethod(err error) bool

IsUnknownAuthMethod reports whether err is an agent's refusal of an authenticate methodId it does not know — as opposed to a known method that failed. A relay uses it to detect an agent too old for a dynamic method such as "mcp:<server>" and fall back to whatever it did before.

Two shapes count: a JSON-RPC "method not found" (-32601), and the "unknown auth method" text fir returns (as an internal error) for an id it does not advertise. Anything else — an unknown MCP server, a server that is not OAuth, a failed exchange — is a real answer from an agent that does support the method, and must not be papered over.

func ReadOnlyPermissions

ReadOnlyPermissions allows read-like tool calls and rejects everything else. Heuristic: if the tool call title contains a write/exec-shaped verb (write, edit, bash, exec, run, delete, rm), the request is rejected; otherwise it is allowed.

Types

type AbstainResult added in v0.2.6

type AbstainResult struct {
	// Stop is the stop reason of the turn.
	Stop acp.StopReason
	// Abstained is true when the agent declined to respond and nothing was
	// delivered downstream.
	Abstained bool
	// LeafID is the turn's leaf id when the agent reports it (see
	// TurnResult). It is set when the agent abstained, too: the prompt
	// still reached the session.
	LeafID string
}

AbstainResult reports the outcome of PromptAbstainable.

func PromptAbstainable added in v0.2.6

func PromptAbstainable(ctx context.Context, agent Prompter, sid acp.SessionId, prompt []acp.ContentBlock, vs *ValidatingSink, sentinel string) (AbstainResult, error)

PromptAbstainable runs an ACP prompt through vs (which MUST be the session's sink) and lets the agent decline to respond. If the complete assistant message, trimmed, equals sentinel or is empty, the buffered output is discarded and nothing is delivered downstream (Abstained=true). Otherwise the buffered message is flushed downstream. Non-message updates (thoughts, plans, tool calls) stream live throughout — callers that must suppress those before the abstain verdict should gate them in the downstream sink.

The prompt always reaches the session regardless of the verdict, so the agent stays caught up on the conversation even when it stays silent. This is the generic decline construct for ambient participation: a transport-agnostic way for any ACP agent to opt out of replying via a sentinel string, with no tool plumbing. A blank sentinel disables sentinel-matching (only an empty message abstains).

type AgentInfo added in v0.21.0

type AgentInfo struct {
	Name    string
	Title   string
	Version string
}

AgentInfo is the agent's self-description from the initialize response (agentInfo). Every field is empty when the agent did not send one; the ACP spec makes it optional.

type AgentProc

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

AgentProc wraps a single stdio-connected ACP agent process and the ACP connection driving it.

func Start

func Start(ctx context.Context, cfg Config) (*AgentProc, error)

Start launches the agent process, performs Initialize (capturing caps), and returns a ready-to-use AgentProc. Unless cfg.NoRespawn is set, the child is supervised: see the package-level notes in supervise.go.

func (*AgentProc) AgentInfo added in v0.21.0

func (a *AgentProc) AgentInfo() AgentInfo

AgentInfo returns what the agent reported about itself at Initialize.

func (*AgentProc) AgentSupportsNotices added in v0.19.0

func (a *AgentProc) AgentSupportsNotices() bool

AgentSupportsNotices reports whether the agent advertised the acp-kit notice extension in its initialize response's agentCapabilities._meta.

A relay does not need this to receive notices — dispatch handles them unconditionally — but it is useful for deciding whether the agent will report retries at all, versus silently stalling.

func (*AgentProc) AuthMethods

func (a *AgentProc) AuthMethods() []AuthMethod

AuthMethods returns the auth methods the agent advertised at Initialize. Empty if the agent didn't advertise any (or initialize hasn't run yet).

func (*AgentProc) Authenticate

func (a *AgentProc) Authenticate(ctx context.Context, methodID, id, redirect string, cancel bool) (AuthResult, error)

Authenticate invokes the ACP authenticate RPC. Modes:

  • id == "" && redirect == "" && !cancel : start an interactive login. The agent returns a fresh id (and URL) in AuthResult.
  • id != "" && redirect != "" : submit the pasted redirect.
  • id != "" && cancel == true : cancel that pending login.

methodID must match the id advertised in the initialize response (e.g. "oauth-anthropic"). Requires an agent that supports the _meta.auth.interactive extension; older agents will run the legacy blocking flow and may return an empty AuthResult.

func (*AgentProc) AuthenticateSession added in v0.40.0

func (a *AgentProc) AuthenticateSession(ctx context.Context, sessionID, methodID, id, redirect string, cancel bool) (AuthResult, error)

AuthenticateSession is Authenticate scoped to one ACP session: a non-empty sessionID is sent as _meta.auth.sessionId. Session-scoped methods need it — "mcp:<server>" logs in an MCP server, and MCP servers live per session. Those ids are dynamic and never advertised at initialize, so methodID is sent as given and is NOT checked against AuthMethods.

func (*AgentProc) AvailableCommands added in v0.2.2

func (a *AgentProc) AvailableCommands() []CommandInfo

AvailableCommands returns a snapshot of the agent's last-advertised command catalog. Empty until the agent sends an availableCommandsUpdate. Safe for concurrent use.

func (*AgentProc) Cancel

func (a *AgentProc) Cancel(ctx context.Context, sid acp.SessionId) error

Cancel requests cancellation of an in-flight prompt for a session.

func (*AgentProc) Caps

func (a *AgentProc) Caps() Caps

Caps returns the agent's advertised capabilities (parsed at Initialize). It is refreshed each time the agent is re-spawned.

func (*AgentProc) Close

func (a *AgentProc) Close() error

Close terminates the agent process and stops supervision. Returns after the process has exited (or been force-killed).

func (*AgentProc) CloseSession added in v0.47.0

func (a *AgentProc) CloseSession(ctx context.Context, sid acp.SessionId) error

CloseSession asks the agent to free an in-memory session's resources (extension/MCP subprocesses). It uses the standard session/close RPC when the agent advertises sessionCapabilities.close, otherwise fir's unstable session/release. The on-disk session is left intact.

func (*AgentProc) CurrentModel added in v0.26.0

func (a *AgentProc) CurrentModel(sid acp.SessionId) (string, bool)

CurrentModel returns the model id session sid is running, as last reported by the agent for that session (session/new, session/resume, respawn re-establishment, a config option update) or set by a successful SetModel. sid is the id the relay holds, not a respawn wire alias. ok is false when the session's model is unknown; callers may then fall back to the process-wide current from Models().

func (*AgentProc) Done added in v0.7.0

func (a *AgentProc) Done() <-chan struct{}

Done returns a channel that is closed once the AgentProc is permanently finished: after Close, after the context given to Start ends, or — only with Config.NoRespawn — when the child exits. With supervision on (the default) an unexpected exit does NOT close Done: the child is re-spawned. Call Err for the result. Modelled on context.Context.Done/Err.

func (*AgentProc) DropSession

func (a *AgentProc) DropSession(sid acp.SessionId)

DropSession removes the sink for a session and forgets it for respawn recovery.

func (*AgentProc) Err added in v0.7.0

func (a *AgentProc) Err() error

Err reports why the AgentProc is finished: nil while it is running (or re-spawning), ErrAgentClosed after a Close, and otherwise the terminal cause — with NoRespawn, ErrAgentExited for a clean self-exit or the *exec.ExitError from the child. Safe to call concurrently; never blocks.

func (*AgentProc) ExtMethod added in v0.37.0

func (a *AgentProc) ExtMethod(ctx context.Context, sid acp.SessionId, method string, params map[string]any) (json.RawMessage, error)

ExtMethod sends an agent extension request (a method outside the ACP schema, e.g. "_fir/mcp/tools/call") for session sid and returns the raw result. params must not hold "sessionId": ExtMethod sets it to the wire id of sid, so a call still reaches the right session after a respawn.

func (*AgentProc) ForkSession added in v0.32.0

func (a *AgentProc) ForkSession(ctx context.Context, cwd string, parent acp.SessionId, at string, sink SessionUpdateSink) (acp.SessionId, error)

ForkSession calls the unstable session/fork on parent and registers sink for the returned child session exactly as NewSession/ResumeSession do: same update routing, and after an agent respawn the child is recovered by resuming it. at, when non-empty, is sent as `_meta.at` and names the entry to fork at; empty lets the agent choose (fir: the parent's latest entry with no tool call left unfinished). The parent's system prompt, if the kit knows one, is re-sent with the stable capability and inherited by the child. Returns ErrForkUnsupported (wrapped) when the agent does not advertise the needed capability.

func (*AgentProc) ListSessions

func (a *AgentProc) ListSessions(ctx context.Context, cwd string) ([]SessionInfo, error)

ListSessions calls the unstable session/list. Caller must check Caps().ListSessions first.

func (*AgentProc) Models

func (a *AgentProc) Models() (models []ModelInfo, currentID string)

Models returns a snapshot of the agent's last-seen available models. Empty until a session has been created (or ProbeModels has run).

func (*AgentProc) NewSession

func (a *AgentProc) NewSession(ctx context.Context, cwd string, sink SessionUpdateSink, systemPromptBlocks []acp.ContentBlock) (acp.SessionId, error)

NewSession creates a new ACP session and wires the given sink to receive its updates. Returns the ACP session id.

systemPromptBlocks, when non-nil, is the session's system prompt. With the stable ACP capability (Caps().SystemPromptVia == SystemPromptStable) it is sent as params.systemPrompt {mode: "append", content: blocks} and re-sent whenever the kit re-establishes the session (resume, load, fork, respawn recovery). Otherwise it goes in the deprecated _meta["session.systemPrompt"].blocks, as before the stable capability. Callers should only pass it when Caps().SystemPrompt is true, and only text blocks: the stable spec forbids other block types for now.

func (*AgentProc) NewSessionWithMeta added in v0.6.0

func (a *AgentProc) NewSessionWithMeta(ctx context.Context, cwd string, sink SessionUpdateSink, systemPromptBlocks []acp.ContentBlock, extraMeta map[string]any) (acp.SessionId, error)

NewSessionWithMeta is NewSession plus caller-supplied `_meta` entries on the session/new request. Relays use it to pass create-time placement or routing hints an agent understands (e.g. a `host` entry telling a tmux-multiplexing agent which SSH host to run the session's pane on).

extraMeta is merged into the request's `_meta`. On the deprecated legacy path the reserved "session.systemPrompt" key is owned by systemPromptBlocks and overwrites any same-named entry. An empty/nil extraMeta with no legacy system prompt leaves `_meta` absent from the wire entirely, exactly as NewSession does.

func (*AgentProc) ProbeModels

func (a *AgentProc) ProbeModels(ctx context.Context) error

ProbeModels creates a throwaway session in the agent's cwd to read its available-models list, then cancels it. The cached snapshot is returned from Models() afterwards. Idempotent: a no-op if Models() already has a list.

func (*AgentProc) Prompt

func (a *AgentProc) Prompt(ctx context.Context, sid acp.SessionId, prompt []acp.ContentBlock) (acp.StopReason, error)

Prompt sends a user message to the session. Returns the stop reason. The prompt is a sequence of ACP content blocks; callers build these from the latest user text plus any attachments.

If ctx is cancelled, Prompt tells the agent so with a session/cancel notification before returning. Abandoning the JSON-RPC request only stops the CLIENT waiting: the agent never hears about it and its in-flight tool keeps running. That was observed in the wild — a relay gave up on a turn and the agent went on writing files for another minute — so the notification is sent here, once, rather than left to every caller to remember.

Prompt then waits for the agent to answer the cancelled prompt, so the caller's next prompt reaches an agent whose run has unwound.

It is best-effort and bounded by cancelNotifyTimeout: a child wedged badly enough not to answer is past helping. ctx's error is returned regardless.

func (*AgentProc) PromptTurn added in v0.33.0

func (a *AgentProc) PromptTurn(ctx context.Context, sid acp.SessionId, prompt []acp.ContentBlock) (TurnResult, error)

PromptTurn is Prompt, and it also returns the turn's leaf id (see TurnResult). The cancellation behaviour is the same as Prompt.

func (*AgentProc) RebindSink

func (a *AgentProc) RebindSink(sid acp.SessionId, sink SessionUpdateSink)

RebindSink replaces the sink for an existing session id.

func (*AgentProc) ReleaseSession added in v0.2.3

func (a *AgentProc) ReleaseSession(ctx context.Context, sid acp.SessionId) error

ReleaseSession asks the agent to tear down and forget an in-memory session, freeing its extension/MCP subprocesses. The on-disk session is left intact. Returns a *acp.RequestError with code SessionNotFoundCode if the agent does not hold the session (see IsSessionNotFound).

func (*AgentProc) Restarts added in v0.25.0

func (a *AgentProc) Restarts() int

Restarts reports how many times the agent has been re-spawned.

func (*AgentProc) ResumeSession

func (a *AgentProc) ResumeSession(ctx context.Context, cwd string, sid acp.SessionId, sink SessionUpdateSink) error

ResumeSession calls the unstable session/resume and registers the sink for the resumed session. Caller must check Caps().ResumeSession first. The given sid is the agent-returned identifier (as listed by ListSessions). It sends no system prompt; see ResumeSessionWithSystemPrompt.

func (*AgentProc) ResumeSessionWithSystemPrompt added in v0.42.0

func (a *AgentProc) ResumeSessionWithSystemPrompt(ctx context.Context, cwd string, sid acp.SessionId, sink SessionUpdateSink, systemPromptBlocks []acp.ContentBlock) error

ResumeSessionWithSystemPrompt is ResumeSession that also carries the session's system prompt. With the stable ACP capability the blocks are re-sent as params.systemPrompt, as the spec asks clients to do on every lifecycle request. On the deprecated legacy path nothing extra goes on the wire (that extension only covered session/new). Either way the blocks are remembered for respawn recovery.

func (*AgentProc) SessionStats added in v0.21.0

func (a *AgentProc) SessionStats(sid acp.SessionId) (SessionStats, bool)

SessionStats returns what the agent has reported about sid. The second result is false when it has reported nothing.

func (*AgentProc) SetConfigOption

func (a *AgentProc) SetConfigOption(ctx context.Context, sid acp.SessionId, configID, value string) error

SetConfigOption calls the session/set_config_option RPC. Used for the model selector on new-style agents, and for thinking_level and similar dropdown-style knobs.

func (*AgentProc) SetModel

func (a *AgentProc) SetModel(ctx context.Context, sid acp.SessionId, modelID string) error

SetModel selects the session's model. New-style agents (ACP >= 0.13) are driven through session/set_config_option using the id of the "model" config option; older agents through the session/set_model RPC.

type AuthMethod

type AuthMethod struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Type        string `json:"type,omitempty"` // "agent" | "env_var" | "terminal" | ""
}

AuthMethod describes one authentication method advertised by the agent in the initialize response. Extra _meta fields the client doesn't use are ignored.

type AuthResult

type AuthResult struct {
	// State is one of "needs_redirect", "ok", "cancelled", or "" if the
	// agent's response carried no _meta.auth state field.
	State string
	// ID is the opaque pending-login id the agent returns on call 1.
	ID string
	// URL is the auth URL the user should visit (state="needs_redirect").
	URL string
	// Instructions is optional human-readable text alongside URL.
	Instructions string
}

AuthResult is the outcome of an Authenticate call.

type Caps

type Caps struct {
	// LoadSession is the standard agentCapabilities.loadSession bool.
	LoadSession bool
	// ListSessions reflects agentCapabilities.sessionCapabilities.list
	// (unstable RFD).
	ListSessions bool
	// ResumeSession reflects agentCapabilities.sessionCapabilities.resume
	// (unstable RFD).
	ResumeSession bool
	// ForkSession reflects agentCapabilities.sessionCapabilities.fork
	// (unstable RFD): the agent implements session/fork.
	ForkSession bool
	// ForkAt reflects agentCapabilities.sessionCapabilities.fork._meta.at:
	// session/fork honours a `_meta.at` entry id choosing the fork point.
	ForkAt bool
	// CloseSession reflects agentCapabilities.sessionCapabilities.close:
	// the agent implements the standard session/close RPC.
	CloseSession bool
	// EmbeddedContext reflects
	// agentCapabilities.promptCapabilities.embeddedContext: when true,
	// the relay may emit ContentBlock::Resource (with TextResourceContents)
	// in prompt requests instead of a bare ResourceLink, avoiding an
	// agent-side fetch.
	EmbeddedContext bool
	// Image reflects agentCapabilities.promptCapabilities.image: when
	// true, the relay may include ContentBlock::Image (base64 data plus
	// a mime type) in prompt requests, so an image a human attached
	// reaches the model as an image rather than as a path it has to go
	// and read. False is the ACP default, and the consumer must then
	// fall back to naming the file.
	Image bool
	// Audio reflects agentCapabilities.promptCapabilities.audio, the
	// same deal as Image for ContentBlock::Audio.
	Audio bool
	// SystemPrompt is true when the agent accepts a client system prompt
	// by either path: the stable ACP capability
	// agentCapabilities.sessionCapabilities.systemPrompt, or the
	// deprecated acp-kit extension agentCapabilities._meta
	// ["session.systemPrompt"]. When true the consumer passes the prompt
	// as blocks to NewSession (and ResumeSessionWithSystemPrompt) and the
	// kit picks the wire form; SystemPromptVia says which. When false the
	// consumer must fall back to inlining the same content on first
	// prompt (and re-arm on resume).
	SystemPrompt bool
	// SystemPromptVia names the path SystemPrompt was detected by. The
	// stable capability wins when an agent advertises both.
	SystemPromptVia SystemPromptVia
	// SystemPromptOverride reflects
	// sessionCapabilities.systemPrompt.mode.override: the agent would let
	// a client prompt replace its default instructions. acp-kit itself
	// always sends mode "append".
	SystemPromptOverride bool
	// Extensions captures arbitrary entries from agentCapabilities._meta
	// other than the kit-owned "session.systemPrompt". Consumers can
	// probe for custom extension ids (e.g. "dev.acp-kit.status-line/v1")
	// to discover advertised support. Values are the raw JSON bytes of
	// the entry — typically `{}` or `{"version": N}`. nil when the
	// agent advertised no _meta.
	Extensions map[string]json.RawMessage
	// Notices reflects whether the agent advertised the acp-kit notice
	// extension (see NoticeMethod). Receiving notices does not depend on
	// this — dispatch routes them regardless — but a relay can use it to
	// tell "this agent will tell me about provider retries" from "this
	// agent will simply go quiet".
	Notices bool
}

Caps captures the agent capabilities the relay cares about, parsed from the initialize response.

type CommandInfo added in v0.2.2

type CommandInfo struct {
	Name        string // command name, e.g. "reload" (invoked as "/reload")
	Description string
}

CommandInfo is one agent-advertised command (from an availableCommandsUpdate session notification).

type Config

type Config struct {
	// Command is the argv used to spawn the agent (e.g. []string{"fir", "--mode", "acp"}).
	Command []string
	// Cwd is the working directory for the child process.
	Cwd string
	// MCPServersForSession, when set, returns the MCP servers to include
	// in session/new and session/resume for a session at the given cwd.
	// This lets a client hand the agent client-hosted MCP servers (e.g. a
	// per-session stdio tool server) without changing the NewSession
	// signature. Nil (the default) means no MCP servers — identical to the
	// previous hardcoded empty list.
	MCPServersForSession func(cwd string) []acp.McpServer
	// Env is the environment for the child. If nil, os.Environ() is used.
	//
	// SECURITY: this env, or the inherited os.Environ() when Env is nil, is
	// handed verbatim to a process that a chat relay drives with text from
	// people who are not the operator. Any credential the child can read it
	// can use — to impersonate the relay, read its history, or re-scope its
	// reach — and no prompt-level guard can take that back. If the relay's
	// own inbound secret leaks into the child's environment, declare it in
	// SecretEnvNames (by variable name) or Secrets (by literal value) so it
	// is dropped before the child ever starts. The child still legitimately
	// needs provider credentials it is meant to use (e.g. ANTHROPIC_API_KEY,
	// POE_API_KEY); scrub only the relay's own secrets, not those.
	Env []string
	// SecretEnvNames are environment variable names dropped from the child's
	// environment before it is spawned — in BOTH the Env-provided and the
	// nil-Env (inherit os.Environ()) paths.
	SecretEnvNames []string
	// Secrets are literal secret VALUES; any variable whose value matches one
	// is dropped whatever it is named. Empty strings are ignored (a
	// config-file deployment legitimately has no token in the environment).
	Secrets []string
	// Policy decides permission responses. If nil, AllowAllPermissions is used.
	Policy PermissionPolicy
	// CloseGrace is how long Close waits after SIGINT before SIGKILL. Default 2s.
	CloseGrace time.Duration
	// Stderr is where the child's stderr is forwarded. If nil, os.Stderr.
	Stderr io.Writer
	// ClientMeta carries extra entries to merge into the outgoing
	// clientCapabilities._meta map at Initialize. Use this to advertise
	// support for custom ACP extensions (keyed by extension id, e.g.
	// "dev.acp-kit.status-line/v1"). Keys collide last-wins with
	// kit-owned entries (e.g. "session.systemPrompt"); pick distinct
	// extension ids to avoid clobber.
	ClientMeta map[string]any

	// NoRespawn disables supervision. By default an agent that exits
	// unexpectedly is logged (exit status plus the tail of its stderr)
	// and re-spawned with capped exponential backoff; sessions the relay
	// holds are re-established on their next use. With NoRespawn the
	// first exit is final: Done closes and every later call fails.
	NoRespawn bool
	// RespawnMin / RespawnMax bound the respawn backoff (defaults 1s and
	// 60s); the delay doubles per consecutive failure. RespawnHealthy is
	// how long a child must have run for the backoff to reset (default
	// 60s).
	RespawnMin, RespawnMax, RespawnHealthy time.Duration
	// Logger receives supervision events (exit, respawn, session
	// recovery). Nil means slog.Default().
	Logger *slog.Logger
}

Config configures an AgentProc.

type Cost added in v0.21.0

type Cost struct {
	Amount   float64
	Currency string // ISO 4217, e.g. "USD"
}

Cost is a cumulative session cost, as the agent reported it.

type ModelInfo

type ModelInfo struct {
	ID   string // "provider/modelID"
	Name string // human-readable label
}

ModelInfo is one entry in the agent's available-models list.

type Notice added in v0.19.0

type Notice struct {
	// SessionId identifies the session the notice concerns.
	SessionId acp.SessionId `json:"sessionId"`
	// Level is one of "info", "warning", "error".
	Level string `json:"level"`
	// Kind is a stable machine-readable discriminator, e.g.
	// "provider_retry" or "compaction_failed". Relays may switch on it;
	// unknown kinds must be treated as generic.
	Kind string `json:"kind"`
	// Text is a human-readable one-liner, safe to show in a status area.
	Text string `json:"text"`
}

Notice is the payload of a NoticeMethod notification.

type NoticeSink added in v0.19.0

type NoticeSink interface {
	OnNotice(ctx context.Context, n Notice) error
}

NoticeSink is an OPTIONAL interface a SessionUpdateSink may also implement to receive notices for its session. Sinks that do not implement it never see notices, which are then dropped — the correct outcome, since a notice is never part of the answer.

type PermissionFunc

PermissionFunc adapts a function into a PermissionPolicy.

func (PermissionFunc) Decide

Decide implements PermissionPolicy.

type PermissionPolicy

type PermissionPolicy interface {
	Decide(ctx context.Context, req acp.RequestPermissionRequest) acp.RequestPermissionResponse
}

PermissionPolicy decides how to respond to session/request_permission.

type Prompter added in v0.2.4

type Prompter interface {
	Prompt(ctx context.Context, sid acp.SessionId, prompt []acp.ContentBlock) (acp.StopReason, error)
}

Prompter is the subset of an ACP agent client that PromptValidated drives. *AgentProc satisfies it.

type RefuseConfig added in v0.2.4

type RefuseConfig struct {
	// Validator decides whether the assistant message is acceptable.
	// If nil, output is always accepted (PromptValidated becomes a plain
	// buffered prompt).
	Validator Validator
	// MaxRefusals caps how many times the agent is re-prompted to
	// regenerate. 0 validates once and never re-prompts.
	MaxRefusals int
	// BuildReprompt builds the corrective prompt fed back to the agent
	// after a refusal. If nil, a single text block holding the reason is
	// used.
	BuildReprompt func(reason string) []acp.ContentBlock
	// Fallback transforms the rejected text into a deliverable form when
	// regeneration is exhausted (e.g. mechanically escape offending
	// tokens). If nil, the last (still-rejected) output is delivered as-is.
	Fallback func(text string) string
}

RefuseConfig configures PromptValidated.

type RefuseResult added in v0.2.4

type RefuseResult struct {
	Stop     acp.StopReason // stop reason of the delivered turn
	Refusals int            // number of regenerations triggered
	Accepted bool           // a generation passed validation
	FellBack bool           // Fallback was applied after exhaustion
	LeafID   string         // leaf id of the delivered (last) attempt, if reported (see TurnResult)
}

RefuseResult reports the outcome of PromptValidated.

func PromptValidated added in v0.2.4

func PromptValidated(ctx context.Context, agent Prompter, sid acp.SessionId, prompt []acp.ContentBlock, vs *ValidatingSink, cfg RefuseConfig) (RefuseResult, error)

PromptValidated runs an ACP prompt, validates the assistant's complete message via vs (which MUST be the session's sink), and on refusal re-prompts the agent with a short reason up to cfg.MaxRefusals times. The visible message is delivered downstream only once accepted — or, on exhaustion, after cfg.Fallback. Non-message updates stream live throughout.

This is the generic "refuse LLM output" construct: a transport-agnostic way for an ACP client to reject and regenerate an agent's visible message before the user sees it, with a deterministic fallback so a turn can never wedge against a stubborn model.

type SessionInfo

type SessionInfo struct {
	SessionId string  `json:"sessionId"`
	Cwd       string  `json:"cwd,omitempty"`
	Title     *string `json:"title,omitempty"`
	UpdatedAt string  `json:"updatedAt,omitempty"`
}

SessionInfo is one entry from a session/list response.

type SessionStats added in v0.21.0

type SessionStats struct {
	// Thinking is the current value of the thought_level config
	// option, e.g. "medium".
	Thinking string
	// ContextUsed and ContextSize are tokens in the context window
	// and the window size, from the latest usage_update.
	ContextUsed int
	ContextSize int
	// Cost is the cumulative session cost; nil when not reported.
	Cost *Cost
}

SessionStats is what the agent has told the client about one session over ACP: its thinking level (a thought_level config option) and its latest usage_update. A zero field means the agent did not report it. The relay shows these facts; it never invents them.

type SessionUpdateSink

type SessionUpdateSink interface {
	OnUpdate(ctx context.Context, n acp.SessionNotification) error
}

SessionUpdateSink receives streaming updates for a single ACP session. Each consumer (e.g. a relay) implements this to forward the stream to its own transport (SSE, WebSocket, IM channel, ...).

type SystemPromptVia added in v0.42.0

type SystemPromptVia string

SystemPromptVia names how the agent accepts a client system prompt.

const (
	// SystemPromptNone: the agent advertised neither path. A consumer
	// that wants the prompt to reach the model must inline it into user
	// content (see state.Manager.TakePendingSystemPrompt).
	SystemPromptNone SystemPromptVia = ""
	// SystemPromptStable: the agent advertised the stable ACP capability
	// agentCapabilities.sessionCapabilities.systemPrompt. The prompt is
	// sent as params.systemPrompt on session/new and re-sent on
	// session/load, session/resume and session/fork.
	SystemPromptStable SystemPromptVia = "stable"
	// SystemPromptLegacyMeta: the agent advertised only the acp-kit
	// extension agentCapabilities._meta["session.systemPrompt"]. The
	// prompt is sent once, in session/new _meta.
	//
	// Deprecated: kept for one release for agents that predate the
	// stable capability.
	SystemPromptLegacyMeta SystemPromptVia = "legacy-meta"
)

type TurnLiveness added in v0.16.0

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

TurnLiveness bounds one prompt turn by PROGRESS rather than wall-clock.

Create one per turn with StartTurnLiveness, run the turn on the context it returns, and install Wrap(sink) as the session's SessionUpdateSink. Updates pass through untouched; the ones that count as progress (IsProgress) reset the no-progress clock.

It is a watcher, not just a decorator — it owns timers and cancels a context — which is why it is not named like the package's other sink decorator, ValidatingSink: a sink that silently cancels contexts would be a surprise, so the cancelling half is the named type and the sink is something you ask it for.

func StartTurnLiveness added in v0.16.0

func StartTurnLiveness(parent context.Context, cfg TurnLivenessConfig) (*TurnLiveness, context.Context, context.CancelFunc)

StartTurnLiveness begins watching a turn. It returns the watcher, a context derived from parent that is cancelled with cause ErrNoProgress or ErrTurnCeiling when the turn stops making progress, and a stop function.

The stop function releases the timers and cancels the returned context with a plain context.Canceled cause — so it doubles as the caller's own cancel handle for a user-initiated stop, and context.Cause tells the two apart. Call it exactly as you would a context.CancelFunc: always, on every path.

Construction is split from Wrap because relays create the turn context (and stash its cancel func in an in-flight map) before they build the sink.

func (*TurnLiveness) Progress added in v0.17.0

func (l *TurnLiveness) Progress()

Progress restarts the no-progress window: evidence that the agent is doing work. Call it for — and ONLY for — updates that satisfy IsProgress; a relay that resets this clock on bookkeeping frames (plans, spinners, mode changes) can never detect a wedged agent, which is the whole failure this construct exists to catch.

Most consumers should install Wrap(sink) instead and never call this: Wrap applies IsProgress for them. It is exported for relays whose ACP sink is session-lifetime rather than per-turn — poe-acp enqueues every session/update onto one drain goroutine and attaches the per-turn sink in-band, so a per-turn decorator has nowhere to live; it classifies with IsProgress in the drain and feeds the watcher directly.

It deliberately does not touch the ceiling — that is an absolute cap, by definition unaffected by progress — and does nothing once the turn has settled: a stray update arriving after the cut must not re-arm a timer nobody will ever stop.

func (*TurnLiveness) Wrap added in v0.16.0

Wrap returns a SessionUpdateSink that forwards every update to down and resets the no-progress clock (Progress) on those that count as progress. Install the result as the session's sink for the duration of the turn.

type TurnLivenessConfig added in v0.16.0

type TurnLivenessConfig struct {
	// NoProgressTimeout is how long a turn may go with NO evidence of agent
	// progress before it is cancelled with cause ErrNoProgress. The clock is
	// reset by every progress update (see IsProgress) and by nothing else,
	// so a legitimately long-running tool is never cut while a genuinely
	// wedged agent is still detected — even one whose harness keeps emitting
	// cosmetic frames (plans, spinners, mode changes).
	//
	// This is deliberately NOT called an "idle timeout": acp-kit already has
	// state.Config.IdleTimeout, which reaps whole IDLE SESSIONS long after
	// their turns finished. This bound is about one in-flight turn and about
	// the absence of PROGRESS, not the absence of a user. Naming it after
	// the condition it detects keeps the two from ever being confused.
	//
	// <=0 falls back to DefaultNoProgressTimeout (2m).
	NoProgressTimeout time.Duration

	// MaxTurnDuration is an OPTIONAL absolute wall-clock ceiling on the turn,
	// enforced regardless of progress, with cause ErrTurnCeiling.
	//
	// <=0 (the default) means NO ceiling: while the agent keeps making
	// progress the turn runs for as long as it needs. A wall-clock cap
	// punishes exactly the turns that are working hardest, and gets worse as
	// tool use deepens, so it is opt-in for operators who deliberately want a
	// hard upper bound. It is NOT the wedge guard — that is
	// NoProgressTimeout's job.
	MaxTurnDuration time.Duration

	// NoProgressCause optionally replaces ErrNoProgress as the cause
	// reported when the no-progress window expires, and TurnCeilingCause
	// replaces ErrTurnCeiling for the ceiling. They exist because the
	// layer that owns the timeouts is the only one that knows the
	// NUMBERS, and a relay that wants to tell its user "no output for
	// 2m0s" must be able to put that sentence on the cause rather than
	// re-deriving it wherever the cause is rendered.
	//
	// A replacement is honoured only if it still satisfies
	// errors.Is(cause, <the sentinel it replaces>) — otherwise it is
	// IGNORED and the sentinel is used. The cross-relay promise is that
	// `errors.Is(context.Cause(ctx), client.ErrNoProgress)` identifies a
	// wedge cut everywhere; a custom sentence may ride along on top of
	// that promise but may never break it. Wrap, do not replace:
	//
	//	func (c myCause) Unwrap() error { return client.ErrNoProgress }
	//
	// nil (the default) means the bare sentinel.
	NoProgressCause  error
	TurnCeilingCause error
}

TurnLivenessConfig configures StartTurnLiveness.

type TurnPrompter added in v0.33.0

type TurnPrompter interface {
	PromptTurn(ctx context.Context, sid acp.SessionId, prompt []acp.ContentBlock) (TurnResult, error)
}

TurnPrompter is a Prompter that also reports the turn's leaf id. *AgentProc satisfies it.

type TurnResult added in v0.33.0

type TurnResult struct {
	// Stop is the stop reason of the turn.
	Stop acp.StopReason
	// LeafID is the agent's id for the last entry of the turn, read from
	// the prompt response's _meta.leafId. It is empty when the agent does
	// not report it. An agent that reports it accepts it as the
	// session/fork _meta.at value (see ForkSession).
	LeafID string
}

TurnResult is what one session/prompt round trip reports.

type ValidatingSink added in v0.2.4

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

ValidatingSink wraps a downstream SessionUpdateSink. While a turn is in progress it buffers AgentMessageChunk updates (the assistant's visible message) instead of forwarding them, so an orchestrator can validate the complete message and either Commit it (flush downstream) or Drop it (discard) before the user ever sees it. Every other update — thoughts, tool calls, plans, command catalogs — passes through live, so progress keeps streaming.

Holding the message until validation is deliberate: a generic ACP transport cannot assume it can retract bytes already sent, so buffering the visible message is the only transport-agnostic way to guarantee that rejected output never reaches the user.

func NewValidatingSink added in v0.2.4

func NewValidatingSink(down SessionUpdateSink) *ValidatingSink

NewValidatingSink wraps down. Install the returned sink as the session's SessionUpdateSink (e.g. via AgentProc.NewSession) and drive turns through PromptValidated.

func (*ValidatingSink) Commit added in v0.2.4

func (v *ValidatingSink) Commit(ctx context.Context) error

Commit flushes the buffered message chunks downstream in order, then clears.

func (*ValidatingSink) CommitText added in v0.2.4

func (v *ValidatingSink) CommitText(ctx context.Context, sid acp.SessionId, text string) error

CommitText discards whatever was buffered and flushes a single synthetic message chunk carrying text. Used to deliver a transformed (e.g. escaped) fallback when regeneration is exhausted.

func (*ValidatingSink) Drop added in v0.2.4

func (v *ValidatingSink) Drop()

Drop discards buffered message chunks (used before a regeneration).

func (*ValidatingSink) OnUpdate added in v0.2.4

OnUpdate implements SessionUpdateSink. Agent message chunks are buffered; all other updates are forwarded downstream immediately.

func (*ValidatingSink) Text added in v0.2.4

func (v *ValidatingSink) Text() string

Text returns the assistant message text accumulated for the current attempt.

type Validator added in v0.2.4

type Validator interface {
	// Validate returns ok=true to accept the output. To refuse it, return
	// ok=false with a short, agent-facing reason describing what is wrong.
	// The reason is fed back to the agent as the next prompt so it can
	// regenerate a compliant message.
	Validate(text string) (reason string, ok bool)
}

Validator inspects the complete assistant message text produced during a single prompt turn and decides whether it may be delivered to the user.

type ValidatorFunc added in v0.2.4

type ValidatorFunc func(text string) (reason string, ok bool)

ValidatorFunc adapts a plain function to a Validator.

func (ValidatorFunc) Validate added in v0.2.4

func (f ValidatorFunc) Validate(text string) (string, bool)

Validate implements Validator.

Jump to

Keyboard shortcuts

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