Documentation
¶
Index ¶
- Constants
- Variables
- func AssistantMessageError(message NativeMessage) error
- func BrokerIdentityHash(username string, password string) string
- func CleanupDarwinContainment(string, string, bool, io.Writer) error
- func ControlRootForXDG(root string) string
- func DiagnoseDarwinContainment(string, io.Writer) error
- func IntFromNumber(value any) (int, bool)
- func IsBadRequest(err error) bool
- func IsRateLimited(err error) bool
- func ReapAbandonedHomes(parent string, prefix string) error
- func StreamErrorEpoch(err error) uint64
- type AssistantError
- type BrokerLease
- type BrowserShim
- type Client
- type CommandRequest
- type DarwinGeneration
- type Event
- type HTTPError
- type MCPServerConfig
- type MessageRequest
- type ModelSelector
- type NativeAgent
- type NativeAttachment
- type NativeCommand
- type NativeError
- type NativeMessage
- type NativeMessageInfo
- type NativePart
- type NativeSession
- type NativeSessionStatus
- type NativeTodo
- type NativeTokens
- type OutputFormat
- type PermissionRequest
- type PermissionRoute
- type PermissionRule
- type PermissionTool
- type ProcessIdentityLockCapability
- type ProcessIsolation
- type ProviderAuthCredential
- type ProviderAuthMethod
- type ProviderAuthPrompt
- type ProviderAuthPromptOption
- type ProviderAuthPromptWhen
- type ProviderAuthorization
- type ProviderCatalogEntry
- type ProviderInfo
- type ProviderModel
- type ProviderModelCapabilities
- type ProviderModelInputCapabilities
- type ProvidersResponse
- type QuestionInfo
- type QuestionOption
- type QuestionRequest
- type QuestionRoute
- type QuestionTool
- type ScopeOptions
- type SessionError
- type StartOptions
- type StreamError
- type SyncEvent
- type SyncReplayEvent
- type XDGDirs
Constants ¶
const ( DarwinRuntimeIDEnv = "ACP_GO_OPENCODE_RUNTIME_ID" DarwinScratchRootEnv = "ACP_GO_OPENCODE_SCRATCH_ROOT" )
const ( ProviderAuthTypeOAuth = "oauth" ProviderAuthTypeAPI = "api" )
Native credential variants the store may hold. The adapter installs and reads the first two; `wellknown` is a native-only shape it never accepts.
const ( ProviderAuthNativeMethodAuto = "auto" ProviderAuthNativeMethodCode = "code" )
ProviderAuthNativeMethod reports which native interaction an authorize result selected.
const BrokerLeaseFileName = "acp-go-opencode-broker.lease.json"
BrokerLeaseFileName is the lease a broker server writes inside its own home. It is keyed by that home and never by the runtime key: concurrent pending flows each own a distinct home, and one shared file would have every reaper verify the wrong PID and kill the wrong server.
const HealthCheckTimeout = 60 * time.Second
HealthCheckTimeout is the default bound on OpenCode server readiness checks.
const OutputFormatJSONSchema = "json_schema"
Variables ¶
var ( ErrSSEDisconnect = errors.New("opencode SSE disconnected") ErrMCPDisconnectUnproven = errors.New("opencode MCP disconnect unproven") ErrScopeRuntimeShutdown = errors.New("directory-scoped OpenCode client cannot shut down the shared runtime") ErrRuntimeScratchCleanup = errors.New("OpenCode runtime scratch cleanup incomplete") )
var ErrProcessContainmentIncomplete = errors.New("OpenCode process containment incomplete")
ErrProcessContainmentIncomplete marks shutdown failures for which the native process tree has not been proved empty. Embedders must retain native-root ownership when this sentinel is present.
Functions ¶
func AssistantMessageError ¶
func AssistantMessageError(message NativeMessage) error
func BrokerIdentityHash ¶
BrokerIdentityHash binds the lease to the credentials the leased server authenticates with, so the lease names one server rather than a port number anything could be listening on. The secret itself never enters the file.
func ControlRootForXDG ¶
func IntFromNumber ¶
func IsBadRequest ¶
func IsRateLimited ¶
IsRateLimited reports a native refusal that asks the caller to slow down.
func ReapAbandonedHomes ¶
func StreamErrorEpoch ¶
Types ¶
type AssistantError ¶
type AssistantError struct {
// contains filtered or unexported fields
}
AssistantError is the typed error returned when an OpenCode assistant/provider turn fails. It carries the machine-readable native fields so the prompt site can surface a structured ACP error.
func AssistantErrorFromNativeError ¶
func AssistantErrorFromNativeError(nerr *NativeError) *AssistantError
func (*AssistantError) Detail ¶
func (e *AssistantError) Detail() string
func (*AssistantError) Error ¶
func (e *AssistantError) Error() string
func (*AssistantError) ProviderCode ¶
func (e *AssistantError) ProviderCode() string
func (*AssistantError) StatusCode ¶
func (e *AssistantError) StatusCode() int
type BrokerLease ¶
type BrokerLease struct {
PID int `json:"pid"`
Port int `json:"port"`
StartedAt int64 `json:"startedAtUnixMilli"`
IdentityHash string `json:"identityHash"`
// ProcessStart is the leased process's own start time, which is what
// separates the process this lease named from an unrelated one that reused
// its PID.
ProcessStart string `json:"processStartTime,omitempty"`
// OwnerPID and OwnerStart identify the adapter process that created the
// home. A home whose owner is still running belongs to a live flow, and a
// reaper that killed it would terminate a concurrent pending login rather
// than an orphan.
OwnerPID int `json:"ownerPid"`
OwnerStart string `json:"ownerProcessStartTime,omitempty"`
}
BrokerLease records what a later startup needs to tell an abandoned broker home from a live one. Without it a crashed adapter leaks an orphan server still holding a pending flow — and, after native completion, a live refresh token in a directory no ledger entry names.
type BrowserShim ¶
type BrowserShim struct {
// contains filtered or unexported fields
}
BrowserShim is a scratch directory of no-op launchers that shadows every browser a native login leg would otherwise open on the operator's desktop. The caller that starts the leg owns the directory, because the leg outlives no single call inside this package.
func NewBrowserShim ¶
func NewBrowserShim(string) (*BrowserShim, error)
NewBrowserShim fails closed. CreateProcess resolves cmd.exe, explorer.exe, and rundll32.exe out of the system directory ahead of every PATH entry, and the `start` that opens a URL is a cmd.exe builtin with no image to shadow, so a shim directory on PATH neutralises nothing here. A leg that cannot prove the launch is contained refuses to run rather than opening the operator's browser.
func (*BrowserShim) Dir ¶
func (s *BrowserShim) Dir() string
Dir names the directory the shim occupies.
func (*BrowserShim) Handoff ¶
func (s *BrowserShim) Handoff(isolation *ProcessIsolation) error
Handoff transfers the adapter-created shim to the isolated native identity.
func (*BrowserShim) Remove ¶
func (s *BrowserShim) Remove() error
Remove deletes the shim directory.
type Client ¶
type Client interface {
Close(context.Context) error
Shutdown(context.Context) error
Scope(context.Context, ScopeOptions) (Client, error)
RefreshMCP(context.Context, []MCPServerConfig) error
CreateSession(context.Context, string) (NativeSession, error)
CreateSessionWithPolicy(context.Context, string, []PermissionRule) (NativeSession, error)
GetSession(context.Context, string) (NativeSession, error)
ListSessions(context.Context, string) ([]NativeSession, error)
DeleteSession(context.Context, string) error
Commands(context.Context) ([]NativeCommand, error)
RunCommand(context.Context, string, CommandRequest) (NativeMessage, error)
SendMessage(context.Context, string, MessageRequest) (NativeMessage, error)
Messages(context.Context, string) ([]NativeMessage, error)
SessionStatus(context.Context) (map[string]NativeSessionStatus, error)
Abort(context.Context, string) error
Fork(context.Context, string, string) (NativeSession, error)
Todos(context.Context, string) ([]NativeTodo, error)
ConfigProviders(context.Context) (ProvidersResponse, error)
Agents(context.Context) ([]NativeAgent, error)
PendingPermissions(context.Context) ([]PermissionRequest, error)
ReplyPermission(context.Context, PermissionRequest, string, string) error
PendingQuestions(context.Context) ([]QuestionRequest, error)
ReplyQuestion(context.Context, QuestionRequest, [][]string) error
RejectQuestion(context.Context, QuestionRequest) error
Events() <-chan Event
EventErrors() <-chan error
RuntimeExited() <-chan struct{}
XDGDirs() XDGDirs
NativeVersion() string
SyncHistory(context.Context, map[string]int64) ([]SyncEvent, error)
SyncReplay(context.Context, string, []SyncReplayEvent) error
ProviderCatalog(context.Context) ([]ProviderCatalogEntry, error)
ProviderAuthMethods(context.Context) (map[string][]ProviderAuthMethod, error)
ProviderAuthorize(context.Context, string, int, map[string]string) (ProviderAuthorization, error)
ProviderAuthCallback(context.Context, string, int, string) error
SetProviderAuth(context.Context, string, ProviderAuthCredential) error
RemoveProviderAuth(context.Context, string) error
StoredProviderAuth(context.Context, string) (ProviderAuthCredential, bool, error)
DisposeInstance(context.Context) error
}
func StartServer ¶
func StartServer(ctx context.Context, options StartOptions) (_ Client, resultErr error)
type CommandRequest ¶
type DarwinGeneration ¶
type DarwinGeneration struct {
RuntimeID string
ScratchRoot string
RecordStarted func(pid, pgid int) error
RecordFinished func(complete bool) error
// contains filtered or unexported fields
}
DarwinGeneration binds one native launch to its wrapper-created writable generation root and persistent operator-diagnostic record.
func NewDarwinGenerationRecord ¶
func NewDarwinGenerationRecord(string, string, string) (*DarwinGeneration, error)
type Event ¶
type Event struct {
ID string `json:"id"`
Type string `json:"type"`
Properties json.RawMessage `json:"properties"`
Raw json.RawMessage `json:"-"`
StreamEpoch uint64 `json:"-"`
}
func (*Event) UnmarshalJSON ¶
type MCPServerConfig ¶
type MCPServerConfig struct {
Name string
URL string
Headers map[string]string
Command []string
Env map[string]string
}
MCPServerConfig describes one MCP server exposed to the native OpenCode process through the generated opencode.json. URL selects the remote transport; otherwise Command selects the local (stdio) transport.
type MessageRequest ¶
type MessageRequest struct {
MessageID string `json:"messageID,omitempty"`
Model *ModelSelector `json:"model,omitempty"`
Agent string `json:"agent,omitempty"`
NoReply bool `json:"noReply,omitempty"`
Parts []map[string]any `json:"parts"`
Format *OutputFormat `json:"format,omitempty"`
}
type ModelSelector ¶
type NativeAgent ¶
type NativeAttachment ¶
type NativeAttachment struct {
ID string `json:"id"`
Type string `json:"type"`
Mime string `json:"mime"`
Filename string `json:"filename"`
URL string `json:"url"`
}
NativeAttachment is a native file part carried inside a completed tool state's attachments array. The URL is a data URL, a file URL/path, or a remote location.
type NativeCommand ¶
type NativeCommand struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Agent string `json:"agent,omitempty"`
Model string `json:"model,omitempty"`
Source string `json:"source,omitempty"`
Template any `json:"template,omitempty"`
Subtask bool `json:"subtask,omitempty"`
Hints []string `json:"hints"`
}
type NativeError ¶
type NativeMessage ¶
type NativeMessage struct {
Info NativeMessageInfo `json:"info"`
Parts []NativePart `json:"parts"`
}
type NativeMessageInfo ¶
type NativeMessageInfo struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Role string `json:"role"`
ParentID string `json:"parentID"`
ModelID string `json:"modelID"`
ProviderID string `json:"providerID"`
Mode string `json:"mode"`
Agent string `json:"agent"`
Finish string `json:"finish"`
Cost float64 `json:"cost"`
Tokens NativeTokens `json:"tokens"`
Structured json.RawMessage `json:"structured,omitempty"`
Error *NativeError `json:"error,omitempty"`
Time struct {
Created int64 `json:"created"`
Completed int64 `json:"completed"`
} `json:"time"`
}
type NativePart ¶
type NativePart struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
MessageID string `json:"messageID"`
Type string `json:"type"`
Text string `json:"text"`
CallID string `json:"callID"`
Tool string `json:"tool"`
State json.RawMessage `json:"state"`
Reason string `json:"reason"`
Mime string `json:"mime"`
Filename string `json:"filename"`
URL string `json:"url"`
Cost float64 `json:"cost"`
Tokens NativeTokens `json:"tokens"`
Raw json.RawMessage `json:"-"`
}
func (*NativePart) UnmarshalJSON ¶
func (p *NativePart) UnmarshalJSON(data []byte) error
type NativeSession ¶
type NativeSession struct {
ID string `json:"id"`
Title string `json:"title"`
Directory string `json:"directory"`
Agent string `json:"agent"`
Model struct {
ID string `json:"id"`
ModelID string `json:"modelID"`
ProviderID string `json:"providerID"`
} `json:"model"`
Time struct {
Created int64 `json:"created"`
Updated int64 `json:"updated"`
} `json:"time"`
}
type NativeSessionStatus ¶
type NativeSessionStatus struct {
Type string `json:"type"`
}
type NativeTodo ¶
type NativeTokens ¶
type OutputFormat ¶
type PermissionRequest ¶
type PermissionRequest struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Action string `json:"action"`
Permission string `json:"permission"`
Resources []string `json:"resources"`
Patterns []string `json:"patterns"`
Save []string `json:"save"`
Always []string `json:"always"`
Metadata map[string]any `json:"metadata"`
Source map[string]any `json:"source"`
Tool PermissionTool `json:"tool"`
ReplyRoute PermissionRoute `json:"-"`
}
func (PermissionRequest) ActionName ¶
func (r PermissionRequest) ActionName() string
func (PermissionRequest) ResourceList ¶
func (r PermissionRequest) ResourceList() []string
func (PermissionRequest) Route ¶
func (r PermissionRequest) Route() PermissionRoute
type PermissionRoute ¶
type PermissionRoute string
const ( PermissionRouteSession PermissionRoute = "session" PermissionRouteAPI PermissionRoute = "api" )
type PermissionRule ¶
type PermissionTool ¶
type ProcessIdentityLockCapability ¶
ProcessIsolation is the mandatory credential and complete environment base applied to every provider process.
type ProcessIsolation ¶
type ProcessIsolation struct {
UID uint32
GID uint32
BaseEnvironment map[string]string
StandaloneOwnerID string
StandaloneStateRoot string
IdentityLock ProcessIdentityLockCapability
AuthorityDomain ProcessIdentityLockCapability
// contains filtered or unexported fields
}
type ProviderAuthCredential ¶
type ProviderAuthCredential struct {
Type string `json:"type"`
Refresh string `json:"refresh,omitempty"`
Access string `json:"access,omitempty"`
Expires int64 `json:"expires,omitempty"`
AccountID string `json:"accountId,omitempty"`
EnterpriseURL string `json:"enterpriseUrl,omitempty"`
Key string `json:"key,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
ProviderAuthCredential is one entry of the native credential store. It is the only native shape carrying credential material, so it decodes strictly.
type ProviderAuthMethod ¶
type ProviderAuthMethod struct {
Type string `json:"type"`
Label string `json:"label"`
Prompts []ProviderAuthPrompt `json:"prompts,omitempty"`
}
ProviderAuthMethod is one native login method of a provider. The native response carries no id: a method is addressed by its index in this array.
type ProviderAuthPrompt ¶
type ProviderAuthPrompt struct {
Type string `json:"type"`
Key string `json:"key"`
Message string `json:"message"`
Placeholder string `json:"placeholder,omitempty"`
Options []ProviderAuthPromptOption `json:"options,omitempty"`
When *ProviderAuthPromptWhen `json:"when,omitempty"`
}
ProviderAuthPrompt is one native input a login method collects.
type ProviderAuthPromptOption ¶
type ProviderAuthPromptOption struct {
Label string `json:"label"`
Value string `json:"value"`
Hint string `json:"hint,omitempty"`
}
ProviderAuthPromptOption is one choice of a select prompt.
type ProviderAuthPromptWhen ¶
type ProviderAuthPromptWhen struct {
Key string `json:"key"`
Op string `json:"op"`
Value string `json:"value"`
}
ProviderAuthPromptWhen gates a prompt on an earlier answer.
type ProviderAuthorization ¶
type ProviderAuthorization struct {
URL string `json:"url"`
Method string `json:"method"`
Instructions string `json:"instructions"`
}
ProviderAuthorization is the native authorize result.
type ProviderCatalogEntry ¶
type ProviderCatalogEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Source string `json:"source"`
Env []string `json:"env"`
Models map[string]json.RawMessage `json:"models"`
Options map[string]json.RawMessage `json:"options"`
}
ProviderCatalogEntry is one allowlisted entry of the native `all` provider catalog.
type ProviderInfo ¶
type ProviderInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Models map[string]ProviderModel `json:"models"`
}
type ProviderModel ¶
type ProviderModelCapabilities ¶
type ProviderModelCapabilities struct {
Input ProviderModelInputCapabilities `json:"input"`
}
ProviderModelCapabilities is the authenticated provider catalog's exhaustive per-model capability record.
type ProviderModelInputCapabilities ¶
type ProviderModelInputCapabilities struct {
Image *bool `json:"image"`
}
ProviderModelInputCapabilities reports which input kinds the model accepts. A nil field means the catalog did not state the fact either way.
type ProvidersResponse ¶
type ProvidersResponse struct {
Providers []ProviderInfo `json:"providers"`
Default map[string]string `json:"default"`
Raw json.RawMessage `json:"-"`
}
func (ProvidersResponse) HasModel ¶
func (p ProvidersResponse) HasModel(value string) bool
HasModel reports whether the provider catalog contains the "provider/model" value.
func (ProvidersResponse) Model ¶
func (p ProvidersResponse) Model(value string) (ProviderModel, bool)
Model returns the catalog record for the "provider/model" value.
func (ProvidersResponse) ModelContextWindow ¶
func (p ProvidersResponse) ModelContextWindow(value string) (int, bool)
ModelContextWindow returns the "provider/model" model's context-window size in tokens, or (0, false) when the catalog does not advertise one.
func (*ProvidersResponse) UnmarshalJSON ¶
func (p *ProvidersResponse) UnmarshalJSON(data []byte) error
type QuestionInfo ¶
type QuestionInfo struct {
Question string `json:"question"`
Header string `json:"header"`
Options []QuestionOption `json:"options"`
Multiple bool `json:"multiple"`
Custom bool `json:"custom"`
}
type QuestionOption ¶
type QuestionRequest ¶
type QuestionRequest struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Questions []QuestionInfo `json:"questions"`
Tool QuestionTool `json:"tool"`
ReplyRoute QuestionRoute `json:"-"`
}
func (QuestionRequest) Route ¶
func (r QuestionRequest) Route() QuestionRoute
type QuestionRoute ¶
type QuestionRoute string
const ( QuestionRouteSession QuestionRoute = "session" QuestionRouteAPI QuestionRoute = "api" )
type QuestionTool ¶
type ScopeOptions ¶
type ScopeOptions struct {
Directory string
MCPServers []MCPServerConfig
}
type SessionError ¶
type SessionError struct {
SessionID string `json:"sessionID"`
Error *NativeError `json:"error"`
}
type StartOptions ¶
type StartOptions struct {
Root string
ControlRoot string
// ScratchParent is the already-resolved parent directory for ephemeral
// on-disk materialization. The root package resolves it (system temp
// directory when unset); this package never consults the system temp
// directory itself. It is used only as the fallback root when Root is empty.
ScratchParent string
ExecutablePath string
// LeaseDir names the directory a server lease is written into before the
// server starts. It is set for a per-flow broker home, which is the one
// server whose home a later startup has to tell apart from an abandoned
// one; an empty value writes no lease.
LeaseDir string
// BrowserShim shadows every browser launcher on the child's PATH for the
// lifetime of a login leg. The caller owns the directory; leaving it nil
// leaves the child free to open the operator's desktop browser.
BrowserShim *BrowserShim
Env map[string]string
ProcessIsolation *ProcessIsolation
// ExtraPathDirs are absolute directories placed ahead of the inherited
// PATH, in order. Env cannot carry a search path: its entries replace whole
// values, so a PATH there would drop everything the child resolves against.
ExtraPathDirs []string
Pure bool
QuestionTool bool
LogLevel string
MinVersion string
HealthTimeout time.Duration
Logger *slog.Logger
ExistingXDG XDGDirs
// NativeOwnedXDG means the runtime identity owns Root. StartServer must not
// create, inspect, or write any path beneath it before launching OpenCode.
NativeOwnedXDG bool
HandoffXDG bool
SkipVersionGate bool
SeedFiles map[string]string
DarwinBestEffort bool
ContainmentScratchParent string
// ReserveContainmentScratch reserves one adapter-created Darwin generation
// root. DarwinBestEffort requires this callback; StartServer invokes it
// immediately before creating the generation root and owns the returned
// release until that exact root has been deleted.
ReserveContainmentScratch func(context.Context) (func(), error)
ObserveProcess func(context.Context, string, int64)
ObserveProcessSnapshot func(context.Context, string, int)
ObserveStartupStage func(context.Context, string, string, time.Duration, error)
// contains filtered or unexported fields
}
type StreamError ¶
func (StreamError) Error ¶
func (e StreamError) Error() string
func (StreamError) Unwrap ¶
func (e StreamError) Unwrap() error
type SyncReplayEvent ¶
type XDGDirs ¶
func CreateRuntimeXDGDirs ¶
CreateRuntimeXDGDirs materializes one shared runtime XDG root without a session-derived path component.
func RuntimeXDGDirs ¶
RuntimeXDGDirs returns the XDG layout without touching the filesystem.
Source Files
¶
- agent_identity_lock_other.go
- broker_lease.go
- broker_lease_other.go
- broker_lease_signal_other.go
- browser_shim.go
- browser_shim_windows.go
- containment_generation.go
- containment_registry_other.go
- helpers.go
- native_path_ownership_unsupported.go
- opencode_client.go
- opencode_generation_other.go
- opencode_process_other.go
- opencode_process_start_other.go
- path_dirs.go
- process_isolation.go
- process_isolation_other.go
- provider_auth.go
- runtime_control_root.go
- runtime_control_root_other.go
- supervisor.go
- supervisor_platform_other.go
- supervisor_unsupported.go
- supervisor_waiter.go