opencodeacp

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: GPL-3.0 Imports: 42 Imported by: 0

README

acp-go-opencode

Go ACP agent that exposes the local OpenCode CLI as an Agent Client Protocol agent.

Go Reference CI

It runs one authenticated opencode serve runtime for all sessions owned by an agent instance, speaks ACP over JSON-RPC streams, and builds on github.com/coder/acp-go-sdk.

Use it as either:

  • a standalone ACP subprocess: acp-go-opencode
  • an embedded Go adapter through opencodeacp.Serve

Install

Library:

go get github.com/savid/acp-go-opencode

CLI:

go install github.com/savid/acp-go-opencode/cmd/acp-go-opencode@latest

The acp-go-opencode binary speaks ACP over stdin/stdout and reserves stdout for ACP JSON-RPC while diagnostics go to stderr; an editor or ACP host launches it as a subprocess rather than a human-facing chat UI.

Quickstart

The example programs run from a checkout of this repo, so clone it first:

git clone https://github.com/savid/acp-go-opencode && cd acp-go-opencode

Run a tiny local client against the agent:

go run ./examples/minimal-client "Reply with a short hello from ACP."

Start an interactive session against the agent:

go run ./examples/interactive-chat

Load and resume a stored session transcript:

go run ./examples/resume-from-file -file ./examples/resume-from-file/session.jsonl

Embedded Go

package main

import (
	"context"
	"log"
	"os"

	opencodeacp "github.com/savid/acp-go-opencode"
)

func main() {
	err := opencodeacp.Serve(context.Background(), os.Stdin, os.Stdout,
		opencodeacp.WithDefaultModel("openai/gpt-default"),
	)
	if err != nil {
		log.Fatal(err)
	}
}

See the Go API reference for options such as the OpenCode executable path, the exclusive runtime home, scratch parent, default model, process environment, session storage, and OpenTelemetry providers.

What It Provides

  • ACP session lifecycle: create, prompt, cancel, close, list, load, resume, and fork.
  • One Agent-owned opencode serve process and shared XDG root. -home / WithHome selects that exclusive root; -scratch-dir / WithScratchDir selects the parent used when the adapter materializes one. The root must be on an approved local filesystem; network, overlay, and unknown filesystem semantics fail closed before the native process starts.
  • Native sessions remain independently routed inside the shared runtime. Directory-scoped MCP is bound to one live session principal per canonical working directory. Native prompt turns are serialized across the Agent so cancel or timeout can retire the shared generation without killing unrelated concurrent work.
  • Cancel and timeout send native abort only as an advisory hint, then await one memoized containment result for the exact runtime generation. Fenced stream/control failures use the same path. Linux helper-owned subreapers catch setsid escapees. Windows native launch fails closed because its process API cannot apply the mandatory Unix UID/GID identity boundary with empty supplementary groups; cross-compilation proves only that this refusal path builds, not runtime support. The standalone command is Linux-only; embedded Darwin hosts may explicitly select best-effort process-group containment with WithDarwinBestEffortContainment.
  • A native-server crash fails the active turn, retains loaded logical sessions, and reconstructs a session from its last committed sync-event generation before a following prompt can reach the replacement runtime.
  • Native OpenCode REST calls and an SSE event stream mapped to ACP prompt streaming for messages, reasoning, plans, tool calls, usage, and session metadata.
  • Prompt image and resource-blob input gated before a turn starts, with the effective per-image and per-prompt byte bounds advertised at initialize under acp-go.dev/mediaEnvelope so a host can pre-check against the exact numbers the gates enforce. WithInputHandoffRoot additionally accepts a digest-verified local handoff form: an image block whose bytes are read from beneath that read root instead of being carried inline. Unset, no inbound path is ever read.
  • Brokered provider logins through the seven _opencode/auth/* extension methods, advertised only while both -provider-auth-root / WithProviderAuthRoot and -home / WithHome are configured. The adapter installs a completed credential into OpenCode's own durable store and hands none back: there is no credential leg and no injection key. Each device or paste-back flow runs in a short-lived broker home destroyed on every terminal transition, and the durable ledger under the auth root records slot identity and provenance only, never credential material.
  • Permission and question requests bridged to ACP permission and elicitation flows.
  • MCP stdio and streamable HTTP server configuration through ACP session requests.
  • Model and mode selection through ACP session config options and _meta.opencode.options.
  • Durable, credential-free native event snapshots through a host-provided SessionStore; stored rows use opencode-sync-events-v1, keyed by {SessionID, Subpath} and requiring OpenCode 1.18.3 or newer.
  • Versioned acp-go.dev/route envelopes bind each prompt, cancellation, session update, raw event, and elicitation to one turn nonce. Permission requests are fenced structurally by session id plus a tool-call id already pending in that turn.
  • Optional raw native event notifications through _opencode/rawEvent.
  • OpenTelemetry adapter telemetry without recording prompt or tool secrets by default.

Slash Commands

Native OpenCode commands are refreshed from the running opencode serve process and projected into ACP AvailableCommand entries as the session's command set changes. A slash-prefixed prompt that matches a command runs it natively.

Docs

Full Go API reference: pkg.go.dev/github.com/savid/acp-go-opencode.

Development

make audit
make test-integration-smoke
make test-integration-live
make test-integration-cover

make audit runs the full local gate: format, lint, build, unit tests, coverage, cross-compile, vuln, and docs checks. Live integration tests require a local authenticated OpenCode 1.18.3-or-newer CLI. make test-integration-smoke sets ACP_GO_OPENCODE_RUN_INTEGRATION=1 and avoids model spend; make test-integration-live additionally sets ACP_GO_OPENCODE_RUN_LIVE_TOKENS=1 and may spend model tokens; make test-integration-cover runs the smoke suite against a coverage-instrumented binary. Live tests always launch OpenCode under an isolated runtime scratch directory.

License

Distributed under the GNU General Public License v3.0. See LICENSE.

Documentation

Overview

Package opencodeacp exposes the local OpenCode CLI as an Agent Client Protocol agent.

Most hosts run the agent over a pair of JSON-RPC streams using Serve. Serve launches one authenticated loopback `opencode serve` process owned by the Agent, maps ACP requests into directory-scoped OpenCode REST/SSE calls, and keeps that runtime alive across session close. Hosts must complete ACP initialization before issuing session or other agent methods.

Hosts should use Serve for the JSON-RPC transport; hosts that embed the agent directly construct one with NewAgent and the same Option values. OpenCode authentication and provider credentials remain owned by the local OpenCode installation. WithHome selects the Agent's exclusive shared XDG root. When it is empty, the adapter materializes the root beneath the parent selected by WithScratchDir.

Darwin native startup fails closed unless WithDarwinBestEffortContainment is selected. That option accepts a bounded original-process-group cleanup and direct-child reap; descendants that escape the group can survive, so it is not an authoritative absence proof.

Hosts that need durable remote resume can provide WithSessionStore. A session store receives `opencode-sync-events-v1` native event bundles keyed by the ACP-visible session ID and subpath, can back session/list, and can replay an adopted parent/child graph through OpenCode's online sync API.

Hosts that need structured output can attach OpenCodeOptions with WithSessionOpenCodeOptions or use WithSessionOutputSchema. Parsed response objects are returned under _meta.opencode.structuredOutput.

Hosts can call CallForkSession for the OpenCode fork extension method _opencode/session/fork. Raw OpenCode events are emitted as RawEventMethod notifications only when a session request opts in with WithSessionRawEvents.

Hosts that need adapter telemetry can provide OpenTelemetry providers with WithTracerProvider and WithMeterProvider. The package never configures global OpenTelemetry providers; the acp-go-opencode binary handles env-based exporter setup for command-line use. Caller-supplied providers remain owned by the caller, including ForceFlush and Shutdown.

Index

Examples

Constants

View Source
const (
	AuthMethodsMethod    = "_opencode/auth/methods"
	AuthAuthorizeMethod  = "_opencode/auth/authorize"
	AuthCallbackMethod   = "_opencode/auth/callback"
	AuthStatusMethod     = "_opencode/auth/status"
	AuthCancelMethod     = "_opencode/auth/cancel"
	AuthInventoryMethod  = "_opencode/auth/inventory"
	AuthDisconnectMethod = "_opencode/auth/disconnect"
)

Session-scoped provider-auth extension methods. OpenCode installs a completed credential into its own durable runtime store, so it brokers no credential out and accepts no injection: there is no credential leg and no injection key.

View Source
const (
	ForkSessionMethod = "_opencode/session/fork"
	RawEventMethod    = "_opencode/rawEvent"
)
View Source
const (
	SessionStoreMainSubpath = ""
	SessionStoreFormat      = "opencode-sync-events-v1"
)

Variables

View Source
var ErrProcessContainmentIncomplete = opencode.ErrProcessContainmentIncomplete

ErrProcessContainmentIncomplete means the selected native containment boundary did not complete. Callers must keep the runtime quarantined.

Functions

func CancelRequest

func CancelRequest(sessionID acp.SessionId, turnNonce string) acp.CancelNotification

func DeleteSessionRequest

func DeleteSessionRequest(sessionID acp.SessionId) acp.UnstableDeleteSessionRequest

func ForkSessionRequest

func ForkSessionRequest(sessionID acp.SessionId, cwd string, opts ...SessionRequestOption) acp.UnstableForkSessionRequest

func HTTPMCPServer

func HTTPMCPServer(name string, url string, headers map[string]string) acp.McpServer

func LoadSessionRequest

func LoadSessionRequest(sessionID acp.SessionId, cwd string, opts ...SessionRequestOption) acp.LoadSessionRequest

func NewSessionRequest

func NewSessionRequest(cwd string, opts ...SessionRequestOption) acp.NewSessionRequest

func NewTurnNonce

func NewTurnNonce() (string, error)

func PromptRequest

func PromptRequest(sessionID acp.SessionId, turnNonce string, blocks ...acp.ContentBlock) acp.PromptRequest

func ResumeSessionRequest

func ResumeSessionRequest(sessionID acp.SessionId, cwd string, opts ...SessionRequestOption) acp.ResumeSessionRequest

func Serve

func Serve(ctx context.Context, input io.Reader, output io.Writer, opts ...Option) (serveErr error)
Example (Initialize)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

clientToAgentReader, clientToAgentWriter := io.Pipe()
agentToClientReader, agentToClientWriter := io.Pipe()
defer clientToAgentReader.Close()
defer clientToAgentWriter.Close()
defer agentToClientReader.Close()
defer agentToClientWriter.Close()

done := make(chan error, 1)
go func() {
	done <- Serve(ctx, clientToAgentReader, agentToClientWriter)
}()

_, _ = fmt.Fprintln(clientToAgentWriter, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}`)
line, _ := bufio.NewReader(agentToClientReader).ReadString('\n')
cancel()
_ = clientToAgentWriter.Close()
<-done

var response struct {
	Result struct {
		AuthMethods       []any `json:"authMethods"`
		AgentCapabilities struct {
			LoadSession     bool `json:"loadSession"`
			McpCapabilities struct {
				Http bool `json:"http"`
			} `json:"mcpCapabilities"`
		} `json:"agentCapabilities"`
	} `json:"result"`
}
_ = json.Unmarshal([]byte(line), &response)

fmt.Println(len(response.Result.AuthMethods) == 0)
fmt.Println(response.Result.AgentCapabilities.LoadSession)
fmt.Println(response.Result.AgentCapabilities.McpCapabilities.Http)
Output:
true
true
true

func SetModelRequest

func SetModelRequest(sessionID acp.SessionId, model string) acp.SetSessionConfigOptionRequest

func StdioMCPServer

func StdioMCPServer(name string, command string, args []string, env map[string]string) acp.McpServer

func TextPromptRequest

func TextPromptRequest(sessionID acp.SessionId, turnNonce, text string) acp.PromptRequest

Types

type Agent

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

Agent exposes OpenCode through ACP.

func NewAgent

func NewAgent(opts ...Option) *Agent

func (*Agent) Authenticate

func (a *Agent) Authenticate(_ context.Context, params acp.AuthenticateRequest) (acp.AuthenticateResponse, error)

func (*Agent) Cancel

func (a *Agent) Cancel(ctx context.Context, params acp.CancelNotification) error

func (*Agent) Close

func (a *Agent) Close() error

func (*Agent) CloseSession

func (a *Agent) CloseSession(ctx context.Context, params acp.CloseSessionRequest) (acp.CloseSessionResponse, error)

func (*Agent) ContainmentMode

func (a *Agent) ContainmentMode() RuntimeContainmentMode

ContainmentMode reports the effective native process boundary.

func (*Agent) HandleExtensionMethod

func (a *Agent) HandleExtensionMethod(ctx context.Context, method string, params json.RawMessage) (any, error)

func (*Agent) Initialize

func (a *Agent) Initialize(_ context.Context, params acp.InitializeRequest) (acp.InitializeResponse, error)

func (*Agent) ListSessions

func (a *Agent) ListSessions(ctx context.Context, params acp.ListSessionsRequest) (acp.ListSessionsResponse, error)

func (*Agent) LoadSession

func (a *Agent) LoadSession(ctx context.Context, params acp.LoadSessionRequest) (acp.LoadSessionResponse, error)

func (*Agent) Logout

func (*Agent) NewSession

func (a *Agent) NewSession(ctx context.Context, params acp.NewSessionRequest) (acp.NewSessionResponse, error)

func (*Agent) Prompt

func (a *Agent) Prompt(ctx context.Context, params acp.PromptRequest) (resp acp.PromptResponse, err error)

func (*Agent) ResumeSession

func (a *Agent) ResumeSession(ctx context.Context, params acp.ResumeSessionRequest) (acp.ResumeSessionResponse, error)

type ConcurrencyLimits

type ConcurrencyLimits struct {
	MaxActiveSessions        int
	MaxConcurrentClientCalls int
}

ConcurrencyLimits bounds work accepted by one Agent.

type ImageLimits

type ImageLimits struct {
	MaxInputBytesPerImage     int64
	MaxInputBytesPerPrompt    int64
	MaxOutputBytesPerImage    int64
	MaxOutputBytesPerToolCall int64
}

ImageLimits bounds decoded image bytes crossing the ACP boundary. Input fields bound prompt images before a native turn starts; output fields bound emitted image content. A zero field disables that adapter policy limit; it never bypasses hard native framing, provider, or host request limits. Negative fields are rejected when the agent is constructed.

type InMemorySessionStore

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

func NewInMemorySessionStore

func NewInMemorySessionStore() *InMemorySessionStore

func (*InMemorySessionStore) Append

func (s *InMemorySessionStore) Append(ctx context.Context, key SessionKey, entries []SessionStoreEntry) error

func (*InMemorySessionStore) Delete

func (s *InMemorySessionStore) Delete(ctx context.Context, key SessionKey) error

func (*InMemorySessionStore) ListSessions

func (s *InMemorySessionStore) ListSessions(ctx context.Context) ([]SessionSummary, error)

func (*InMemorySessionStore) ListSubkeys

func (s *InMemorySessionStore) ListSubkeys(ctx context.Context, key SessionKey) ([]string, error)

func (*InMemorySessionStore) Load

func (*InMemorySessionStore) Replace

func (s *InMemorySessionStore) Replace(ctx context.Context, main SessionKey, replacements []SessionStoreReplacement) error

type ListSessionsRequestOption

type ListSessionsRequestOption func(*acp.ListSessionsRequest)

func WithListSessionsCursor

func WithListSessionsCursor(cursor string) ListSessionsRequestOption

func WithListSessionsCwd

func WithListSessionsCwd(cwd string) ListSessionsRequestOption

func WithListSessionsMeta

func WithListSessionsMeta(meta map[string]any) ListSessionsRequestOption

type OpenCodeOption

type OpenCodeOption func(*OpenCodeOptions)

func WithOpenCodeEnv

func WithOpenCodeEnv(env map[string]string) OpenCodeOption

WithOpenCodeEnv sets the environment this session's native process runs under, overlaying WithEnv. One native process serves every session of an Agent, so a session asking for an environment the running process was not started under is served by a fresh process, and is refused outright while another session still holds the running one.

func WithOpenCodeExtraPathDirs

func WithOpenCodeExtraPathDirs(dirs ...string) OpenCodeOption

WithOpenCodeExtraPathDirs places absolute directories ahead of the inherited PATH of that process, in the order given. It is the only way to extend the search path: WithOpenCodeEnv rejects PATH because its entries replace whole values.

func WithOpenCodeMode

func WithOpenCodeMode(mode string) OpenCodeOption

func WithOpenCodeModel

func WithOpenCodeModel(model string) OpenCodeOption

func WithOpenCodeOutputSchema

func WithOpenCodeOutputSchema(schema map[string]any) OpenCodeOption

func WithOpenCodePermission

func WithOpenCodePermission(permission string) OpenCodeOption

type OpenCodeOptions

type OpenCodeOptions struct {
	Model        string         `json:"model,omitempty"`
	OutputSchema map[string]any `json:"outputSchema,omitempty"`
	Mode         string         `json:"mode,omitempty"`
	Permission   string         `json:"permission,omitempty"`
	// Env overlays the agent-wide environment for the native process this
	// session runs under. PATH belongs in ExtraPathDirs.
	Env map[string]string `json:"env,omitempty"`
	// ExtraPathDirs are absolute directories placed ahead of the inherited PATH
	// of that process, in order.
	ExtraPathDirs []string `json:"extraPathDirs,omitempty"`
}

OpenCodeOptions is the stable OpenCode-specific subset accepted at _meta.opencode.options.

func NewOpenCodeOptions

func NewOpenCodeOptions(opts ...OpenCodeOption) OpenCodeOptions

func (OpenCodeOptions) Meta

func (options OpenCodeOptions) Meta() map[string]any

Meta returns an ACP _meta object for the supported OpenCode-specific options.

type Option

type Option func(*Options)

Option configures the OpenCode ACP agent.

func WithAgentName

func WithAgentName(name string) Option

func WithAgentTitle

func WithAgentTitle(title string) Option

func WithAgentVersion

func WithAgentVersion(version string) Option

func WithConcurrencyLimits

func WithConcurrencyLimits(limits ConcurrencyLimits) Option

func WithDarwinBestEffortContainment

func WithDarwinBestEffortContainment() Option

WithDarwinBestEffortContainment explicitly accepts Darwin process-group containment.

func WithDefaultModel

func WithDefaultModel(model string) Option

func WithEnv

func WithEnv(env map[string]string) Option

WithEnv adds ordinary variables to the shared native runtime environment. Managed home, XDG, database, and config roots are rejected during agent initialization.

func WithExecutablePath

func WithExecutablePath(path string) Option

func WithHome

func WithHome(path string) Option

WithHome selects the exclusive shared OpenCode XDG root owned by the Agent.

func WithImageLimits

func WithImageLimits(limits ImageLimits) Option

WithImageLimits replaces every image byte limit. The supplied struct owns all four fields: an unset field is zero and disables that policy limit.

func WithInputHandoffRoot

func WithInputHandoffRoot(dir string) Option

WithInputHandoffRoot sets the absolute directory a prompt image may be read from when it arrives in the handoff form: an image block with empty data, a file URI, and a digest envelope. It is a read root only — the wrapper never writes, moves, or deletes anything beneath it, and it materializes nothing, so it carries no scratch semantics. Unset rejects every handoff-form block.

func WithLogger

func WithLogger(logger *slog.Logger) Option

func WithMeterProvider

func WithMeterProvider(provider metric.MeterProvider) Option

func WithOpenCodeHealthCheckTimeout

func WithOpenCodeHealthCheckTimeout(timeout time.Duration) Option

func WithOpenCodeLogLevel

func WithOpenCodeLogLevel(level string) Option

func WithOpenCodePure

func WithOpenCodePure(enabled bool) Option

func WithOpenCodeQuestionTool

func WithOpenCodeQuestionTool(enabled bool) Option

func WithProcessIsolation

func WithProcessIsolation(isolation ProcessIsolation) Option

WithProcessIsolation requires every native process to run as the supplied uid/gid with no supplementary groups. BaseEnvironment is the complete native environment base; the adapter never overlays os.Environ.

func WithProviderAuthDirectHome

func WithProviderAuthDirectHome(path string) Option

WithProviderAuthDirectHome names the canonical native home an operator consents to an account-level provider-auth leg reading or clearing. OpenCode removes a credential through a scoped per-provider call, so it has no leg to gate and rejects any configured value at session start.

func WithProviderAuthRoot

func WithProviderAuthRoot(path string) Option

WithProviderAuthRoot sets the absolute durable directory holding the values-free provider-auth ledger. It sits outside session scratch, outlives every session and native generation, and carries no config or auth-resolution semantics. Unset — or set alongside no Home — leaves every provider-auth method unadvertised.

func WithRuntimeResourceHooks

func WithRuntimeResourceHooks(hooks RuntimeResourceHooks) Option

func WithScratchDir

func WithScratchDir(dir string) Option

WithScratchDir sets the parent directory for all ephemeral on-disk materialization, including a generated shared runtime root. An empty value uses the system temporary directory.

func WithSeedFiles

func WithSeedFiles(files map[string]string) Option

WithSeedFiles writes immutable bootstrap files into the shared OpenCode runtime config root before launching opencode serve. Keys are paths relative to <XDG_CONFIG_HOME>/opencode/ directory mapped to file contents; absolute paths, parent-directory escapes, and empty keys are rejected. A native-owned durable runtime home accepts only opencode.json, which is delivered through the managed process environment without a privileged write beneath the home. A seeded opencode.json must not contain permission or MCP policy because those values are bound to native sessions and directory scopes respectively. The map is cloned like WithEnv.

func WithSessionStore

func WithSessionStore(store SessionStore) Option

func WithSessionStoreLoadTimeout

func WithSessionStoreLoadTimeout(timeout time.Duration) Option

WithSessionStoreLoadTimeout bounds session store reads (load, list, and subkey enumeration). Store writes use a separate fixed bound.

func WithTextMapPropagator

func WithTextMapPropagator(propagator propagation.TextMapPropagator) Option

func WithTracerProvider

func WithTracerProvider(provider trace.TracerProvider) Option

func WithTurnTimeout

func WithTurnTimeout(timeout time.Duration) Option

WithTurnTimeout bounds how long a single prompt turn may run before the wrapper aborts the native turn and fails the prompt with a turn-failure error carrying cause "timeout". The default of 0 disables the deadline.

type Options

type Options struct {
	AgentName    string
	AgentTitle   string
	AgentVersion string

	ExecutablePath string
	// Home is the exclusive shared XDG root owned by this Agent runtime. Empty
	// creates one beneath ScratchDir.
	Home string
	// ScratchDir is the parent for a generated shared runtime root and transient
	// adapter scratch material. It is never a per-session OpenCode home.
	ScratchDir string
	// InputHandoffRoot is the only directory a prompt image may be read from.
	// Empty rejects the handoff input form outright.
	InputHandoffRoot string
	// ProviderAuthRoot is the durable host-owned directory holding the
	// values-free provider-auth ledger. Empty leaves every provider-auth method
	// unadvertised.
	ProviderAuthRoot string
	// ProviderAuthDirectHome names a canonical native home an account-level
	// provider-auth leg may read or clear. OpenCode removes a credential with a
	// scoped per-provider call and has no such leg, so a configured value is
	// rejected at session start.
	ProviderAuthDirectHome string
	DefaultModel           string
	Env                    map[string]string
	ProcessIsolation       *ProcessIsolation

	Logger            *slog.Logger
	TracerProvider    trace.TracerProvider
	MeterProvider     metric.MeterProvider
	TextMapPropagator propagation.TextMapPropagator

	SessionStore            SessionStore
	SessionStoreLoadTimeout time.Duration
	ConcurrencyLimits       ConcurrencyLimits
	SeedFiles               map[string]string
	ImageLimits             ImageLimits

	Pure                        bool
	QuestionTool                bool
	LogLevel                    string
	HealthCheckTimeout          time.Duration
	TurnTimeout                 time.Duration
	RuntimeResourceHooks        RuntimeResourceHooks
	DarwinBestEffortContainment bool
	// contains filtered or unexported fields
}

Options configures the ACP agent process and OpenCode sessions it starts.

type ProcessIdentityLockCapability

type ProcessIdentityLockCapability interface {
	Duplicate() (*os.File, error)
}

ProcessIsolation defines the complete operating-system identity and base environment inherited by every native OpenCode process.

type ProcessIsolation

type ProcessIsolation struct {
	UID                 uint32
	GID                 uint32
	BaseEnvironment     map[string]string
	StandaloneOwnerID   string
	StandaloneStateRoot string
	// IdentityLock is an optional trusted-supervisor descriptor for the
	// host-global UID lock. Linux supervisors validate it and never expose it to
	// the native OpenCode process. Standalone embeddings should leave it nil.
	IdentityLock    ProcessIdentityLockCapability
	AuthorityDomain ProcessIdentityLockCapability
}

type RuntimeContainmentMode

type RuntimeContainmentMode string

RuntimeContainmentMode reports the selected native process boundary.

const (
	// RuntimeContainmentAuthoritative identifies a platform proof boundary.
	RuntimeContainmentAuthoritative RuntimeContainmentMode = "authoritative"
	// RuntimeContainmentBestEffort identifies explicitly accepted Darwin process-group containment.
	RuntimeContainmentBestEffort RuntimeContainmentMode = "best_effort"
	// RuntimeContainmentUnavailable identifies a platform with no selected boundary.
	RuntimeContainmentUnavailable RuntimeContainmentMode = "unavailable"
)

type RuntimeProcessKind

type RuntimeProcessKind string
const (
	RuntimeProcessHomeLockSupervisor RuntimeProcessKind = "home_lock_supervisor"
	RuntimeProcessProviderDescendant RuntimeProcessKind = "provider_descendant"
)

type RuntimeResourceHooks

type RuntimeResourceHooks struct {
	AcquireNativeRoot      func(context.Context, RuntimeResourceKind) (func(), error)
	ReserveScratchRoot     func(context.Context, RuntimeResourceKind) (func(), error)
	ObserveProcess         func(context.Context, RuntimeProcessKind, int64)
	ObserveProcessSnapshot func(context.Context, RuntimeProcessKind, int)
	ObserveStartupStage    func(context.Context, RuntimeResourceKind, RuntimeStartupStage, time.Duration, error)
	ObserveContainment     func(context.Context, RuntimeContainmentMode)
}

RuntimeResourceHooks lets an embedding worker account for native roots and adapter-created scratch roots in its worker-global permit pools. A nil hook selects the standalone, unbounded controller.

type RuntimeResourceKind

type RuntimeResourceKind string
const (
	RuntimeResourceRuntime   RuntimeResourceKind = "runtime"
	RuntimeResourceSession   RuntimeResourceKind = "session"
	RuntimeResourcePrompt    RuntimeResourceKind = "prompt"
	RuntimeResourceDiscovery RuntimeResourceKind = "discovery"
)

type RuntimeStartupStage

type RuntimeStartupStage string
const (
	RuntimeStartupSpawn         RuntimeStartupStage = "spawn"
	RuntimeStartupReadiness     RuntimeStartupStage = "readiness"
	RuntimeStartupConfiguration RuntimeStartupStage = "configuration"
	RuntimeStartupSession       RuntimeStartupStage = "session"
)

type SessionKey

type SessionKey struct {
	SessionID string
	Subpath   string
}

type SessionRequestOption

type SessionRequestOption func(*sessionRequestConfig)

func WithSessionAdditionalDirectories

func WithSessionAdditionalDirectories(paths ...string) SessionRequestOption

func WithSessionMCPServers

func WithSessionMCPServers(servers ...acp.McpServer) SessionRequestOption

func WithSessionMeta

func WithSessionMeta(meta map[string]any) SessionRequestOption

func WithSessionOpenCodeOptions

func WithSessionOpenCodeOptions(options OpenCodeOptions) SessionRequestOption

func WithSessionOutputSchema

func WithSessionOutputSchema(schema map[string]any) SessionRequestOption

func WithSessionRawEvents

func WithSessionRawEvents(enabled bool) SessionRequestOption

type SessionStore

type SessionStore interface {
	Append(ctx context.Context, key SessionKey, entries []SessionStoreEntry) error
	Load(ctx context.Context, key SessionKey) ([]SessionStoreEntry, error)
	Replace(ctx context.Context, main SessionKey, replacements []SessionStoreReplacement) error
	Delete(ctx context.Context, key SessionKey) error
	ListSessions(ctx context.Context) ([]SessionSummary, error)
	ListSubkeys(ctx context.Context, key SessionKey) ([]string, error)
}

type SessionStoreEntry

type SessionStoreEntry = json.RawMessage

type SessionStoreReplacement

type SessionStoreReplacement struct {
	Key     SessionKey
	Entries []SessionStoreEntry
}

type SessionStoreTerminalState

type SessionStoreTerminalState struct {
	MessageID string
}

SessionStoreTerminalState is the provider-native terminal identity recovered from one committed opencode-sync-events-v1 snapshot entry.

func InspectSessionStoreTerminalState

func InspectSessionStoreTerminalState(
	logicalSessionID string,
	entries []SessionStoreEntry,
) (SessionStoreTerminalState, error)

InspectSessionStoreTerminalState validates the current-format snapshot for logicalSessionID and returns its latest finished assistant message. The snapshot owns the private native aggregate identity; callers do not need to know it. OpenCode may append repeated user-message events after the terminal assistant; those events are intentionally not terminal state.

A valid snapshot with no terminal assistant returns the zero state. Invalid cardinality, JSON, snapshot formats, message events, and aggregate ordering fail closed.

type SessionSummary

type SessionSummary struct {
	SessionID          string
	UpdatedAtUnixMilli int64
	Cwd                string
	Title              string
	Meta               map[string]any
}

Directories

Path Synopsis
cmd
acp-go-opencode command
examples
minimal-client command
internal

Jump to

Keyboard shortcuts

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