acp

package
v0.6.76 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: AGPL-3.0, Apache-2.0, MIT Imports: 17 Imported by: 0

Documentation

Overview

Package acp is the daemon's ACP client layer: a raw JSON-RPC connection to a harness over stdio, converters between ACP JSON and the devbox.v1 protos, the v1 -> v2 entity normalizer, subagent lineage extraction and the live entity store.

It deliberately works on raw JSON (json.RawMessage / map[string]any decoded with UseNumber) instead of the typed acp-go-sdk structs, so nothing the agent sends is flattened or dropped (section 4.6a item 5). The SDK's Connection is used only as the JSON-RPC transport.

Index

Constants

View Source
const (
	MethodInitialize        = "initialize"
	MethodAuthenticate      = "authenticate"
	MethodSessionNew        = "session/new"
	MethodSessionLoad       = "session/load"
	MethodSessionResume     = "session/resume"
	MethodSessionList       = "session/list"
	MethodSessionClose      = "session/close"
	MethodSessionDelete     = "session/delete"
	MethodSessionFork       = "session/fork"
	MethodSessionPrompt     = "session/prompt"
	MethodSessionCancel     = "session/cancel"
	MethodSetConfigOption   = "session/set_config_option"
	MethodSetModel          = "session/set_model"
	MethodSetMode           = "session/set_mode"
	MethodSessionUpdate     = "session/update"
	MethodRequestPermission = "session/request_permission"
	MethodElicitationCreate = "elicitation/create"
	MethodElicitationDone   = "elicitation/complete"
	MethodReadTextFile      = "fs/read_text_file"
	MethodWriteTextFile     = "fs/write_text_file"
	MethodTerminalCreate    = "terminal/create"
	MethodTerminalOutput    = "terminal/output"
	MethodTerminalWait      = "terminal/wait_for_exit"
	MethodTerminalKill      = "terminal/kill"
	MethodTerminalRelease   = "terminal/release"
)

ACP method names used by the daemon. The v1 methods match acp-go-sdk's constants; session/set_model and session/fork are the pre-config-option and unstable variants some v1 adapters still serve.

View Source
const (
	StateUpdate             = "state_update"
	StateConfigOptionUpdate = "config_option_update"
	StateCommandsUpdate     = "available_commands_update"
	StateSessionInfoUpdate  = "session_info_update"
	StateUsageUpdate        = "usage_update"
	// StateCurrentModeUpdate is v1-only; the session layer folds it into the mode config option.
	StateCurrentModeUpdate = "current_mode_update"
)

State kinds carried by ChangeState (DeltaOp STATE `state_kind`).

View Source
const (
	StatusCompleted = "completed"
	StatusFailed    = "failed"
)

Terminal statuses shared by tool calls and native subagents.

View Source
const (
	SubagentSpawned     = "subagent_spawned"
	SubagentStateUpdate = "subagent_state_update"
)

Native subagent updates (claude-agent-acp and codex-acp, see AdvertiseNativeSubagents). Both arrive on the parent session; the child's own updates then arrive on the child's session ID.

View Source
const NewToolCall = "tool_call"

NewToolCall is the v1 update that introduces a tool call.

View Source
const SettleQuiet = 5 * time.Second

SettleQuiet is how long an entity may go without updates before it settles on its own (section 4.6a item 4).

View Source
const SubagentSeparator = "/subagent/"

SubagentSeparator joins a parent session ID and the parent's spawning tool call ID into the ID of a v1 child session inferred from adapter `_meta`. v1 has no subagent sessions of its own, so the child ID is daemon-made.

View Source
const SubagentSpawnPrefix = "spawn-"

SubagentSpawnPrefix prefixes the ID of the parent's session message that marks where a native subagent started.

View Source
const TextType = "text"

TextType is the type of ACP text content blocks and of text command inputs.

Variables

This section is empty.

Functions

func AdvertiseNativeSubagents

func AdvertiseNativeSubagents(caps map[string]any)

AdvertiseNativeSubagents adds the client capabilities that switch native subagent sessions on: the draft `subagents` capability, and the JetBrains AIR `_meta` extension. claude-agent-acp and codex-acp check either, but their ACP SDK drops capability fields it doesn't know (`subagents` among them) before they look.

func Arr

func Arr(o Object, k string) []any

Arr returns o[k] as an array, or nil.

func Bool

func Bool(o Object, k string) bool

Bool returns o[k] as a bool.

func CloneJSON

func CloneJSON(v any) any

CloneJSON deep-copies a decoded JSON value.

func CommandOf

func CommandOf(o Object) *devboxv1.AvailableCommand

CommandOf converts an ACP available command, normalizing v1 `input: {hint}` into v2 `{type: "text", hint}`.

func ConfigOptionOf

func ConfigOptionOf(o Object) *devboxv1.ConfigOption

ConfigOptionOf converts an ACP session config option. Select options are modelled; other types keep raw JSON.

func ContentBlockJSON

func ContentBlockJSON(b *devboxv1.ContentBlock) (any, error)

ContentBlockJSON converts a proto ContentBlock back into ACP JSON. Unknown blocks are sent verbatim.

func ContentBlockOf

func ContentBlockOf(v any) *devboxv1.ContentBlock

ContentBlockOf converts an ACP ContentBlock. Unknown `type`s become UnknownVariant with the raw object.

func ContentBlocksJSON

func ContentBlocksJSON(blocks []*devboxv1.ContentBlock) ([]any, error)

ContentBlocksJSON converts a prompt into ACP JSON.

func ContentBlocksOf

func ContentBlocksOf(arr []any) []*devboxv1.ContentBlock

ContentBlocksOf converts a JSON array of ContentBlocks.

func Decode

func Decode(raw []byte) (any, error)

Decode decodes raw JSON into any value with numbers kept as json.Number.

func EntityIDField

func EntityIDField(t devboxv1.EntityType) string

EntityIDField is the ACP ID field name for an entity type.

func EntityUpdateName

func EntityUpdateName(t devboxv1.EntityType) string

EntityUpdateName is the v2 sessionUpdate discriminator for an entity type.

func Float

func Float(o Object, k string) (float64, bool)

Float returns o[k] as a float64.

func Has

func Has(o Object, k string) bool

Has reports whether k is present (even when null).

func Int

func Int(o Object, k string) (int64, bool)

Int returns o[k] as an int64.

func IsMethodNotFound

func IsMethodNotFound(err error) bool

IsMethodNotFound reports a JSON-RPC -32601.

func MetaStruct

func MetaStruct(o Object) *structpb.Struct

MetaStruct converts an `_meta` value into a Struct, or nil.

func MustJSON

func MustJSON(v any) []byte

MustJSON encodes v, which must be JSON-encodable.

func PlanOf

func PlanOf(o Object) *devboxv1.PlanEntity

PlanOf converts a plan entity.

func Str

func Str(o Object, k string) string

Str returns o[k] as a string, or "".

func StructOf

func StructOf(m Object) *structpb.Struct

StructOf converts an arbitrary object into a Struct, or nil.

func SyntheticID

func SyntheticID(prefix string) string

SyntheticID returns a daemon-synthesized entity ID. IDs are random so they never collide with entities already in the session's transcript, even across daemon restarts.

func ToolCallContentOf

func ToolCallContentOf(v any) *devboxv1.ToolCallContent

ToolCallContentOf converts ACP tool call content.

func ToolCallOf

func ToolCallOf(o Object) *devboxv1.ToolCall

ToolCallOf converts an ACP tool call (or merged tool_call_update state).

func ValueOf

func ValueOf(v any, present bool) *structpb.Value

ValueOf converts an arbitrary JSON value into a Value, or nil when absent.

Types

type Change

type Change struct {
	Kind ChangeKind
	// SessionID is the session the change belongs to after lineage routing (a subagent's for child updates).
	SessionID  string
	EntityType devboxv1.EntityType
	EntityID   string
	// Patch holds the fields to upsert (ChangePatch) or, for ChangeAppend, the chunk with "content" set to the
	// appended block.
	Patch Object
	// StateKind and Payload describe a ChangeState or ChangeNotice. Payload is the v2-shaped update.
	StateKind string
	// Payload is the v2-shaped update sent as the live delta's payload_json.
	Payload Object
	// Complete marks the end of the entity's own lifecycle (a tool call reaching completed/failed), which settles
	// it immediately.
	Complete bool
	// Subagent is set when lineage routed the change to a child session.
	Subagent *Lineage
	// SubagentAnnouncement is a v2 subagent_update: a child session appeared.
	SubagentAnnouncement *Lineage
}

Change is one normalized, v2-shaped change to a session.

func TaskMessage

func TaskMessage(child, task string) Change

TaskMessage opens a subagent's transcript with the task it was given, for agents that never stream the prompt into the child session itself.

type ChangeKind

type ChangeKind int

ChangeKind says how a normalized change applies.

const (
	// ChangeAppend appends a chunk's content block to a message-like entity.
	ChangeAppend ChangeKind = iota + 1
	// ChangePatch upserts fields on an entity: omitted unchanged, null clears, values replace.
	ChangePatch
	// ChangeState is session state (state_update, config options, commands, session info, usage).
	ChangeState
	// ChangeNotice is a live-only notice; never stored.
	ChangeNotice
)

type Conn

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

Conn is one JSON-RPC connection to a harness process.

func NewConn

func NewConn(w io.Writer, r io.Reader, h Handler, log *slog.Logger) *Conn

NewConn starts serving JSON-RPC over the harness's stdin (w) and stdout (r).

func (*Conn) Call

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

Call sends a request and returns the raw result.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done is closed when the peer disconnects.

func (*Conn) Notify

func (c *Conn) Notify(ctx context.Context, method string, params any) error

Notify sends a notification.

type Entity

type Entity struct {
	SessionID string
	Type      devboxv1.EntityType
	ID        string
	Position  uint64
	Revision  uint64
	CreatedAt time.Time
	UpdatedAt time.Time
	Settled   bool
	Body      Object

	// Extra is daemon-side data merged into the typed view (prompt ID and sender for user messages).
	PromptID string
	SentBy   *devboxv1.Principal
	// contains filtered or unexported fields
}

Entity is the live state of one ACP entity.

func (*Entity) Proto

func (e *Entity) Proto() *devboxv1.AcpEntity

Proto renders the entity's current state as an AcpEntity, with the verbatim v2 JSON and a typed view.

type Handler

type Handler interface {
	HandleNotification(ctx context.Context, method string, params json.RawMessage)
	HandleRequest(ctx context.Context, method string, params json.RawMessage) (any, *RequestError)
}

Handler serves agent -> client calls. Notifications are delivered one at a time in arrival order; requests run concurrently and may block (permission prompts wait for a human).

type HiddenCalls

type HiddenCalls interface {
	// Hidden is whether a tool call update belongs to a call the adapter never shows as a tool call.
	Hidden(update Object) bool
}

HiddenCalls is implemented by extractors whose adapter hides some tool calls behind native subagent sessions.

type Lineage

type Lineage struct {
	ParentSessionID string
	ChildSessionID  string
	// ParentToolCallID is the parent's tool call that spawned the child, when known.
	ParentToolCallID string
	Title            string
	Meta             Object
}

Lineage links a child (subagent) session to its parent.

type LineageExtractor

type LineageExtractor interface {
	// Extract returns the child session an update belongs to, or nil when the update belongs to sessionID itself.
	Extract(sessionID string, update Object) *Lineage
}

LineageExtractor infers subagent lineage for v1 adapters from their `_meta`. Implementations must only report lineage that the adapter states explicitly, never guess from content or timing (section 4.6a item 7).

var (
	ClaudeLineage LineageExtractor = claudeLineage{MetaPathExtractor{Path: []string{"claudeCode", "parentToolUseId"}}}
)

Known v1 lineage hints, keyed by adapter. claude-agent-acp tags the updates of Task subagents with the parent tool use ID; other v1 adapters expose nothing yet. DBX-02 confirms these against the pinned adapter versions.

type MetaPathExtractor

type MetaPathExtractor struct {
	// Path inside `_meta`, e.g. ["claudeCode", "parentToolUseId"].
	Path []string
}

MetaPathExtractor reads a parent tool call ID from a fixed `_meta` path. Updates carrying it are routed to the child session `<session>/subagent/<parent tool call id>`.

func (MetaPathExtractor) Extract

func (e MetaPathExtractor) Extract(sessionID string, update Object) *Lineage

Extract implements LineageExtractor.

type NoLineage

type NoLineage struct{}

NoLineage never reports lineage, for adapters whose `_meta` carries none.

func (NoLineage) Extract

func (NoLineage) Extract(string, Object) *Lineage

Extract implements LineageExtractor.

type Normalizer

type Normalizer interface {
	Normalize(sessionID string, update Object) []Change
	// TurnStarted resets per-turn state (chunk runs, the v1 synthetic plan ID) for a session.
	TurnStarted(sessionID string)
	// ProtocolVersion is the negotiated ACP version this normalizer serves.
	ProtocolVersion() int
}

Normalizer turns raw session/update notifications into v2 changes. One Normalizer serves one ACP connection; it tracks contiguous chunk runs and per-turn plan IDs per session.

func NewNormalizer

func NewNormalizer(version int, lineage LineageExtractor, opts ...Option) Normalizer

NewNormalizer returns the normalizer for a negotiated protocol version.

type Object

type Object = map[string]any

Object is a decoded JSON object with numbers kept as json.Number, so re-encoding is lossless.

func DecodeObject

func DecodeObject(raw []byte) (Object, error)

DecodeObject decodes raw JSON into an Object.

func NormalizeCommandJSON

func NormalizeCommandJSON(o Object) Object

NormalizeCommandJSON rewrites a v1 command object into its v2 shape (input.type defaults to "text").

func Obj

func Obj(o Object, k string) Object

Obj returns o[k] as an object, or nil.

func RawObject

func RawObject(raw json.RawMessage) Object

RawObject is a convenience for tests and callers holding raw JSON.

type Option

type Option func(*v1Normalizer)

Option configures a Normalizer.

func TranscriptTool

func TranscriptTool(name string) Option

TranscriptTool names a tool whose streamed output is its subagents' transcripts: pi's subagent extension runs each subagent as its own `pi --mode json` process and reports, on every message, `rawOutput.details.results` with each subagent's task and every message so far. Each result becomes a child session under the tool call.

type RequestError

type RequestError = acpsdk.RequestError

RequestError is a JSON-RPC error.

func AsRequestError

func AsRequestError(err error) (*RequestError, bool)

AsRequestError extracts a JSON-RPC error.

type Store

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

Store holds the live entities of one session and assigns timeline positions.

func NewStore

func NewStore(sessionID string, nextPosition uint64) *Store

NewStore returns a store whose next position is nextPosition (persisted across daemon restarts).

func (*Store) Apply

func (s *Store) Apply(c Change, now time.Time) (*Entity, bool)

Apply applies a ChangeAppend or ChangePatch and returns the entity and whether it is new.

func (*Store) Count

func (s *Store) Count() uint64

Count is the number of distinct entities seen by this store.

func (*Store) Get

func (s *Store) Get(t devboxv1.EntityType, id string) *Entity

Get returns a live entity.

func (*Store) NextPosition

func (s *Store) NextPosition() uint64

NextPosition is the position the next new entity will get.

func (*Store) Quiet

func (s *Store) Quiet(now time.Time) []*Entity

Quiet returns unsettled entities that haven't changed for SettleQuiet.

func (*Store) Settle

func (s *Store) Settle(e *Entity, now time.Time) *devboxv1.AcpEntity

Settle marks e settled, bumps its revision and returns the stored form.

func (*Store) Unsettled

func (s *Store) Unsettled() []*Entity

Unsettled returns in-flight entities in position order.

Jump to

Keyboard shortcuts

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