Versions in this module Expand all Collapse all v0 v0.0.3 Apr 24, 2026 Changes in this version + func ListModelCapabilities(ctx context.Context, opts ...Option) (map[string]ModelCapabilities, error) + type ModalityCapabilities struct + Audio bool + Image bool + PDF bool + Text bool + Video bool + type ModelCapabilities struct + Attachment bool + ContextLimit int + Input ModalityCapabilities + Interleaved bool + ModelID string + Name string + Output ModalityCapabilities + OutputLimit int + ProviderID string + Reasoning bool + Temperature bool + Toolcall bool v0.0.2 Apr 24, 2026 v0.0.1 Apr 23, 2026 Changes in this version + const AskUserQuestionToolName + const MinimumCLIVersion + const ModeBuild + const ModePlan + const ProtocolVersion + const StopReasonCancelled + const StopReasonEndTurn + const StopReasonMaxTokens + const StopReasonMaxTurnRequests + const StopReasonRefusal + const StructuredOutputToolName + const ToolCallStatusCompleted + const ToolCallStatusFailed + const ToolCallStatusInProgress + const ToolCallStatusPending + const ToolKindDelete + const ToolKindEdit + const ToolKindExecute + const ToolKindFetch + const ToolKindMove + const ToolKindOther + const ToolKindRead + const ToolKindSearch + const ToolKindSwitchMode + const ToolKindThink + const Version + var ErrAuthRequired = errors.New("opencode authentication required; run `opencode auth login` in a terminal") + var ErrBudgetExceeded = errors.New("opencodesdk: budget exceeded") + var ErrCLINotFound = errors.New("opencode CLI not found") + var ErrCancelled = errors.New("prompt cancelled") + var ErrCapabilityUnavailable = errors.New("agent does not advertise required prompt capability") + var ErrClientAlreadyConnected = errors.New("client has already been started") + var ErrClientClosed = errors.New("client is closed") + var ErrClientNotStarted = errors.New("client has not been started") + var ErrElicitationUnavailable = errors.New(...) + var ErrExtensionMethodRequired = errors.New("extension method names must begin with \"_\"") + var ErrHookRejected = errors.New("opencodesdk: hook rejected") + var ErrRequestTimeout = errors.New("request timed out") + var ErrSessionCostNotFound = errors.New("opencodesdk: session cost not found") + var ErrSessionNotFound = errors.New("opencodesdk: session not found") + var ErrStructuredOutputMissing = errors.New("opencodesdk: structured output missing") + var ErrTransport = errors.New("opencodesdk: transport closed unexpectedly") + var ErrUnsupportedCLIVersion = errors.New("opencode CLI version is older than MinimumCLIVersion") + var ErrUpdateQueueOverflow = errors.New("session updates buffer overflowed; notifications were dropped") + func AllowAlways(_ context.Context, req acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) + func AllowOnce(_ context.Context, req acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) + func BoolPtr(b bool) *bool + func DeclineElicitation(_ context.Context, _ acp.UnstableCreateElicitationRequest) (acp.UnstableCreateElicitationResponse, error) + func DecodePromptResult[T any](result *PromptResult) (T, error) + func DecodeStructuredOutput[T any](result *QueryResult) (T, error) + func DeleteSessionCost(sessionID string, opts SessionCostOptions) error + func Float64Ptr(v float64) *float64 + func IntPtr(v int) *int + func IsRetryable(err error) bool + func NopLogger() *slog.Logger + func ParseArguments(in map[string]any, dst any) error + func PromptsFromChannel(ch <-chan []acp.ContentBlock) iter.Seq[[]acp.ContentBlock] + func PromptsFromSlice(prompts [][]acp.ContentBlock) iter.Seq[[]acp.ContentBlock] + func PromptsFromStrings(prompts []string) iter.Seq[[]acp.ContentBlock] + func QueryStream(ctx context.Context, prompts []string, opts ...Option) iter.Seq2[*QueryResult, error] + func QueryStreamContent(ctx context.Context, prompts iter.Seq[[]acp.ContentBlock], opts ...Option) iter.Seq2[*QueryResult, error] + func RejectOnce(_ context.Context, req acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) + func SaveSessionCost(sessionID string, snap CostSnapshot, opts SessionCostOptions) error + func SimpleSchema(fields map[string]string) map[string]any + func SinglePrompt(blocks ...acp.ContentBlock) iter.Seq[[]acp.ContentBlock] + func WithClient(ctx context.Context, fn func(Client) error, opts ...Option) error + type BudgetStatus struct + BudgetExceeded bool + CompletionRatio float64 + Cost CostSnapshot + MaxCostUSD *float64 + MaxTotalTokens *int + NearCompletion bool + Reason string + type BudgetTracker struct + func NewBudgetTracker(o BudgetTrackerOptions) (*BudgetTracker, error) + func (t *BudgetTracker) CheckBudget() error + func (t *BudgetTracker) CostTracker() *CostTracker + func (t *BudgetTracker) ObserveNotification(sessionID string, n acp.SessionNotification) + func (t *BudgetTracker) ObservePromptResult(sessionID string, result *PromptResult) + func (t *BudgetTracker) ObserveUsage(sessionID string) func(ctx context.Context, upd *acp.SessionUsageUpdate) + func (t *BudgetTracker) Status() BudgetStatus + type BudgetTrackerOptions struct + CompletionThreshold float64 + MaxCostUSD *float64 + MaxTotalTokens *int + type CLINotFoundError struct + Err error + SearchedPaths []string + func (e *CLINotFoundError) Error() string + func (e *CLINotFoundError) Is(target error) bool + func (e *CLINotFoundError) Unwrap() error + type Client interface + AgentInfo func() acp.Implementation + AuthMethods func() []acp.AuthMethod + BudgetTracker func() *BudgetTracker + CallExtension func(ctx context.Context, method string, params any) (json.RawMessage, error) + CancelAll func(ctx context.Context) error + Capabilities func() acp.AgentCapabilities + Close func() error + ForkSession func(ctx context.Context, parentID string, opts ...Option) (Session, error) + GetTransportHealth func() TransportHealth + IterSessions func(ctx context.Context) iter.Seq2[SessionInfo, error] + ListSessions func(ctx context.Context, cursor string) (sessions []SessionInfo, nextCursor string, err error) + LoadSession func(ctx context.Context, id string, opts ...Option) (Session, error) + LoadSessionHistory func(ctx context.Context, id string, opts ...Option) (*SessionHistory, error) + NewSession func(ctx context.Context, opts ...Option) (Session, error) + ResumeSession func(ctx context.Context, sessionID string, opts ...Option) (Session, error) + Start func(ctx context.Context) error + UnstableSetModel func(ctx context.Context, sessionID, modelID string) error + func NewClient(opts ...Option) (Client, error) + type ContentBlock = acp.ContentBlock + func AudioBlock(data, mimeType string) ContentBlock + func AudioFileInput(path string) (ContentBlock, error) + func AudioFileInputMime(path, mimeType string) (ContentBlock, error) + func Blocks(blocks ...ContentBlock) []ContentBlock + func ImageBlock(data, mimeType string) ContentBlock + func ImageFileInput(path string) (ContentBlock, error) + func ImageFileInputMime(path, mimeType string) (ContentBlock, error) + func PDFFileInput(path string) (ContentBlock, error) + func PathInput(path string) (ContentBlock, error) + func ResourceBlock(res acp.EmbeddedResourceResource) ContentBlock + func ResourceLinkBlock(name, uri string) ContentBlock + func Text(text string) []ContentBlock + func TextBlock(text string) ContentBlock + type CostSnapshot struct + CachedReadTokens int + CachedWriteTokens int + ContextWindowSize int + ContextWindowUsed int + Currencies []string + InputTokens int + OutputTokens int + Sessions int + ThoughtTokens int + TotalCostUSD float64 + TotalTokens int + func LoadSessionCost(sessionID string, opts SessionCostOptions) (*CostSnapshot, error) + type CostTracker struct + func NewCostTracker() *CostTracker + func (t *CostTracker) LoadSessionCost(sessionID string, opts SessionCostOptions) error + func (t *CostTracker) ObserveNotification(sessionID string, n acp.SessionNotification) + func (t *CostTracker) ObservePromptResult(sessionID string, result *PromptResult) + func (t *CostTracker) ObserveUsage(sessionID string) func(ctx context.Context, upd *acp.SessionUsageUpdate) + func (t *CostTracker) SaveSessionCost(sessionID string, opts SessionCostOptions) error + func (t *CostTracker) SessionSnapshot(sessionID string) (CostSnapshot, bool) + func (t *CostTracker) Snapshot() CostSnapshot + type Effort string + const EffortHigh + const EffortLow + const EffortMax + const EffortMedium + const EffortNone + type ElicitMode string + const ElicitModeForm + const ElicitModeURL + type ElicitParams struct + ElicitationID string + Message string + Meta map[string]any + Mode ElicitMode + RequestedSchema map[string]any + URL string + type ElicitResult struct + Action string + Content map[string]any + Meta map[string]any + func Elicit(ctx context.Context, params ElicitParams) (*ElicitResult, error) + type ElicitationCallback func(ctx context.Context, req acp.UnstableCreateElicitationRequest) (acp.UnstableCreateElicitationResponse, error) + type ElicitationCompleteCallback func(ctx context.Context, params acp.UnstableCompleteElicitationNotification) + type ErrorClass string + const ErrorClassAuthentication + const ErrorClassCLI + const ErrorClassCancelled + const ErrorClassCapability + const ErrorClassExecution + const ErrorClassOverload + const ErrorClassRateLimit + const ErrorClassTransientConnection + const ErrorClassUnknown + type ErrorClassification struct + Class ErrorClass + HTTPStatus *int + Message string + RecoveryAction RecoveryAction + Retryable bool + SubClass ErrorSubClass + func ClassifyError(err error) ErrorClassification + type ErrorSubClass string + const ErrorSubClassInvalidModel + const ErrorSubClassInvalidSchema + const ErrorSubClassNone + const ErrorSubClassPromptTooLong + const ErrorSubClassProviderError + const ErrorSubClassRateLimitRequests + const ErrorSubClassRateLimitTokens + const ErrorSubClassSubprocessDied + type FsWriteCallback func(ctx context.Context, req acp.WriteTextFileRequest) error + type HistoryMessage struct + Role string + Text string + type HookCallback func(ctx context.Context, input HookInput) (HookOutput, error) + type HookEvent string + const HookEventFileChanged + const HookEventPermissionDenied + const HookEventPermissionRequest + const HookEventPostToolUse + const HookEventPostToolUseFailure + const HookEventPreToolUse + const HookEventSessionEnd + const HookEventSessionStart + const HookEventStop + const HookEventStopFailure + const HookEventUserPromptSubmit + type HookInput struct + Event HookEvent + FileWrite *acp.WriteTextFileRequest + PermissionRequest *acp.RequestPermissionRequest + PermissionResponse *acp.RequestPermissionResponse + PromptError error + PromptResult *PromptResult + PromptText string + SessionID string + ToolCall *acp.SessionUpdateToolCall + ToolCallUpdate *acp.SessionToolCallUpdate + type HookMatcher struct + Hooks []HookCallback + Matcher *regexp.Regexp + Once bool + Timeout time.Duration + type HookOutput struct + Continue bool + Reason string + SuppressOutput bool + func HookAllow() HookOutput + func HookBlock(reason string) HookOutput + type ListModelsResponse struct + CurrentModelID string + Models []ModelInfo + func ListModelsResponseFor(ctx context.Context, opts ...Option) (*ListModelsResponse, error) + type ListSessionsOptions struct + IncludeArchived bool + Limit int + type ModelInfo = acp.ModelInfo + func ListModels(ctx context.Context, opts ...Option) ([]ModelInfo, error) + type NewToolOption func(*toolConfig) + func WithToolAnnotations(ann ToolAnnotations) NewToolOption + type OpencodeSDKError interface + type Option func(*options) + func WithAddDirs(dirs ...string) Option + func WithAgent(agent string) Option + func WithAllowedTools(names ...string) Option + func WithAutoLaunchLogin(enabled bool) Option + func WithBudgetTracker(t *BudgetTracker) Option + func WithCLIFlags(flags ...string) Option + func WithCLIPath(path string) Option + func WithCanUseTool(cb PermissionCallback) Option + func WithCwd(path string) Option + func WithDisallowedTools(names ...string) Option + func WithEffort(level Effort) Option + func WithEnv(env map[string]string) Option + func WithExtraArgs(args map[string]*string) Option + func WithHooks(hooks map[HookEvent][]*HookMatcher) Option + func WithInitialMode(mode string) Option + func WithInitializeTimeout(d time.Duration) Option + func WithLogger(l *slog.Logger) Option + func WithMCPServers(servers ...acp.McpServer) Option + func WithMaxBudgetUSD(budgetUSD float64) Option + func WithMaxTurns(n int) Option + func WithMeterProvider(mp metric.MeterProvider) Option + func WithModel(id string) Option + func WithOnElicitation(cb ElicitationCallback) Option + func WithOnElicitationComplete(cb ElicitationCompleteCallback) Option + func WithOnFsWrite(cb FsWriteCallback) Option + func WithOnTurnComplete(cb TurnCompleteCallback) Option + func WithOnUpdateDropped(cb UpdateDroppedCallback) Option + func WithOnUserInput(cb UserInputCallback) Option + func WithOpencodeHome(path string) Option + func WithOutputSchema(schema map[string]any) Option + func WithPrometheusRegisterer(reg prometheus.Registerer) Option + func WithPure() Option + func WithSDKTools(tools ...Tool) Option + func WithSkipVersionCheck(skip bool) Option + func WithStderr(fn func(line string)) Option + func WithStrictCwdBoundary(enabled bool) Option + func WithTerminalAuthCapability(enabled bool) Option + func WithTracerProvider(tp trace.TracerProvider) Option + func WithTransport(factory TransportFactory) Option + func WithUpdatesBuffer(n int) Option + func WithUser(user string) Option + type PermissionCallback func(ctx context.Context, req acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) + type ProcessError struct + Err error + ExitCode int + Stderr string + func (e *ProcessError) Error() string + func (e *ProcessError) Unwrap() error + type PromptResult struct + Meta map[string]any + StopReason acp.StopReason + Usage *acp.Usage + type QueryResult struct + AssistantText string + Notifications []acp.SessionNotification + SessionID string + StopReason acp.StopReason + Usage *acp.Usage + func Query(ctx context.Context, prompt string, opts ...Option) (*QueryResult, error) + func QueryContent(ctx context.Context, blocks []acp.ContentBlock, opts ...Option) (*QueryResult, error) + func ResilientQuery(ctx context.Context, prompt string, rq ResilientQueryOptions, opts ...Option) (*QueryResult, error) + type Question struct + Header string + ID string + IsOther bool + IsSecret bool + MultiSelect bool + Options []QuestionOption + Question string + type QuestionOption struct + Description string + Label string + type RecoveryAction string + const RecoveryActionFallback + const RecoveryActionNone + const RecoveryActionRefreshAuth + const RecoveryActionRetryWithBackoff + const RecoveryActionStop + type RequestError struct + Code int + Data any + Message string + func UnwrapRequestError(err error) *RequestError + func (e *RequestError) Error() string + type ResilientQueryOptions struct + Logger *slog.Logger + OnRetry func(ctx context.Context, attempt int, decision RetryDecision, err error) + RetryPolicy RetryPolicy + type RetryDecision struct + Attempt int + Class ErrorClass + MaxRetries int + RecommendedDelay time.Duration + Retryable bool + func EvaluateRetry(err error, attempt int, policy RetryPolicy) RetryDecision + type RetryPolicy struct + BaseDelay time.Duration + JitterRatio float64 + MaxDelay time.Duration + MaxRetries int + func DefaultRetryPolicy() RetryPolicy + type Session interface + AvailableCommands func() []acp.AvailableCommand + AvailableModels func() []acp.ModelInfo + AvailableModes func() []acp.SessionMode + Cancel func(ctx context.Context) error + CurrentVariant func() *VariantInfo + DroppedUpdates func() int64 + ID func() string + InitialConfigOptions func() []acp.SessionConfigOption + InitialModels func() *acp.SessionModelState + InitialModes func() *acp.SessionModeState + Meta func() map[string]any + Prompt func(ctx context.Context, blocks ...acp.ContentBlock) (*PromptResult, error) + RunCommand func(ctx context.Context, name string, args ...string) (*PromptResult, error) + SetConfigOption func(ctx context.Context, configID, value string) error + SetConfigOptionBool func(ctx context.Context, configID string, value bool) error + SetMode func(ctx context.Context, modeID string) error + SetModel func(ctx context.Context, modelID string) error + Subscribe func(handlers UpdateHandlers) (unsubscribe func()) + Updates func() <-chan acp.SessionNotification + type SessionCostOptions struct + OpencodeHome string + type SessionHistory struct + Messages []HistoryMessage + Notifications []acp.SessionNotification + Session Session + Usage *acp.SessionUsageUpdate + type SessionInfo = acp.SessionInfo + type SessionStat struct + ArchivedAt *time.Time + CompactingAt *time.Time + CreatedAt time.Time + Directory string + MessageCount int64 + ParentID string + ProjectID string + SessionID string + ShareURL string + Slug string + SummaryAdditions *int64 + SummaryDeletions *int64 + SummaryFiles *int64 + Title string + UpdatedAt time.Time + Version string + WorkspaceID string + func ListSessions(ctx context.Context, listOpts ListSessionsOptions, opts ...Option) ([]SessionStat, error) + func StatSession(ctx context.Context, sessionID string, opts ...Option) (*SessionStat, error) + func (s *SessionStat) Archived() bool + type StopReason = acp.StopReason + type TerminalAuthLaunch struct + Args []string + Command string + Env map[string]string + Label string + func TerminalAuthInstructions(m acp.AuthMethod) (*TerminalAuthLaunch, bool) + type Tool interface + Description func() string + Execute func(ctx context.Context, input map[string]any) (ToolResult, error) + InputSchema func() map[string]any + Name func() string + func NewTool(name, description string, schema map[string]any, fn ToolFunc, ...) Tool + type ToolAnnotations struct + DestructiveHint *bool + IdempotentHint bool + OpenWorldHint *bool + ReadOnlyHint bool + Title string + type ToolCallStatus = acp.ToolCallStatus + type ToolFunc func(ctx context.Context, input map[string]any) (ToolResult, error) + type ToolKind = acp.ToolKind + type ToolResult struct + IsError bool + Structured any + Text string + func ErrorResult(message string) ToolResult + func ImageResult(data []byte, mimeType string) ToolResult + func TextResult(text string) ToolResult + type Transport interface + Close func() error + Conn func() *acp.ClientSideConnection + type TransportError struct + Err error + Reason string + func (e *TransportError) Error() string + func (e *TransportError) Is(target error) bool + func (e *TransportError) Unwrap() error + type TransportFactory func(ctx context.Context, handler acp.Client) (Transport, error) + type TransportHealth struct + ConsecutiveFailures int + Degraded bool + LastError *string + LastFailureAt *time.Time + ReadFailures int + SendFailures int + type TurnCompleteCallback func(ctx context.Context, sessionID string, result *PromptResult, err error) + type UpdateDroppedCallback func(ctx context.Context, sessionID string, count int64) + type UpdateHandlers struct + AgentMessage func(ctx context.Context, chunk *acp.SessionUpdateAgentMessageChunk) + AgentThought func(ctx context.Context, chunk *acp.SessionUpdateAgentThoughtChunk) + AvailableCommands func(ctx context.Context, upd *acp.SessionAvailableCommandsUpdate) + ConfigOption func(ctx context.Context, upd *acp.SessionConfigOptionUpdate) + CurrentMode func(ctx context.Context, upd *acp.SessionCurrentModeUpdate) + Plan func(ctx context.Context, plan *acp.SessionUpdatePlan) + SessionInfo func(ctx context.Context, upd *acp.SessionSessionInfoUpdate) + ToolCall func(ctx context.Context, tc *acp.SessionUpdateToolCall) + ToolCallUpdate func(ctx context.Context, tcu *acp.SessionToolCallUpdate) + Usage func(ctx context.Context, upd *acp.SessionUsageUpdate) + UserMessage func(ctx context.Context, chunk *acp.SessionUpdateUserMessageChunk) + type UserInputAnswer struct + Answers []string + type UserInputCallback func(ctx context.Context, req *UserInputRequest) (*UserInputResponse, error) + type UserInputRequest struct + Questions []Question + type UserInputResponse struct + Answers map[string]*UserInputAnswer + type VariantInfo struct + AvailableVariants []string + ModelId string + Variant string + func OpencodeVariant(meta map[string]any) (*VariantInfo, bool) + type WatchableTransport interface + ExitErr func() error + Exited func() <-chan struct{}