Help us shape the future of Go! Take the 2026 Go Developer Survey

sdk

package
v0.0.0-...-62a010e Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 20 Imported by: 0

README

OpenCode Go SDK (Embedded Mode)

This package exposes OpenCode as a Go library so external projects can call it directly instead of invoking the opencode binary.

Goals

  • Direct Go API invocation (no shell/system command call).
  • Reuse OpenCode native pipeline: session, message persistence, tools, model routing.
  • Stream all message events, including tool calls and tool results.

Directory Structure

  • sdk/doc.go: package-level documentation.
  • sdk/client.go: exported SDK client and stream event model.

Architecture

  1. Consumer initializes sdk.Client with workspace/config options.
  2. SDK bootstraps OpenCode internals:
    • config.Load to load .opencode.json
    • db.Connect to open sqlite and migrations
    • app.New to wire services (Sessions, Messages, CoderAgent, Permissions)
  3. Consumer calls SendMessageStream.
  4. SDK subscribes to Messages pubsub and starts CoderAgent.Run.
  5. SDK emits callbacks for:
    • message created/updated
    • assistant text/thinking deltas
    • full message snapshot including tool calls/results
    • completion/cancel/error

Call Flow

flowchart LR
    A[External Provider] --> B[sdk.NewClient]
    B --> C[config.Load + db.Connect + app.New]
    A --> D[sdk.SendMessageStream]
    D --> E[Sessions.Create/Get]
    D --> F[Messages.Subscribe]
    D --> G[CoderAgent.Run]
    G --> H[Provider.StreamResponse]
    H --> I[Agent processEvent -> Messages.Update]
    I --> F
    F --> J[SDK callback Event]
    J --> A

Consumer Contract

Use Event.Message as the authoritative snapshot. It always includes:

  • message role (user / assistant / tool)
  • assistant text and reasoning
  • tool call list (id, name, input, finished)
  • tool result list (tool_call_id, content, is_error, metadata)

This allows host applications to build a complete timeline without re-querying DB.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

func NewClient

func NewClient(ctx context.Context, opts Options) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, title string) (*Session, error)

func (*Client) SendMessageStream

func (c *Client) SendMessageStream(ctx context.Context, req RunRequest, handler StreamHandler) (*RunResult, error)

type Event

type Event struct {
	Type      EventType
	SessionID string
	Message   *MessageSnapshot
	Delta     string
	Error     error
	Progress  string
}

type EventType

type EventType string
const (
	EventSessionCreated       EventType = "session_created"
	EventMessageCreated       EventType = "message_created"
	EventMessageUpdated       EventType = "message_updated"
	EventAssistantTextDelta   EventType = "assistant_text_delta"
	EventAssistantThinkDelta  EventType = "assistant_thinking_delta"
	EventAgentCompleted       EventType = "agent_completed"
	EventAgentError           EventType = "agent_error"
	EventAgentCanceled        EventType = "agent_canceled"
	EventAgentSummaryProgress EventType = "agent_summary_progress"
)

type HostTool

type HostTool struct {
	Name        string
	Description string
	Parameters  map[string]any
	Required    []string
	Handler     func(ctx context.Context, call HostToolCall) (HostToolResult, error)

	// Permission 可选:声明该宿主工具的授权动作。为空则不触发权限门禁。
	Permission *HostToolPermission
}

HostTool 是宿主注入的自定义工具:暴露给模型,并在 opencode 的内置 tool-call 循环中执行。

Parameters / Required 与 opencode 内置工具(tools.ToolInfo)保持同一种组织方式: Parameters 是 JSON Schema 的 properties 映射,Required 是必填字段名列表。

type HostToolCall

type HostToolCall struct {
	ID    string // 工具调用 ID
	Name  string // 工具名
	Input string // 模型生成的参数(JSON)
}

HostToolCall 是传给宿主工具 Handler 的一次调用。

type HostToolPermission

type HostToolPermission struct {
	Action      string // execute / write / read / fetch / delete ...
	PathFrom    string // 可选:从入参 JSON 中取文件路径的字段名(如 "file_path")
	Description string // 可选:权限描述;为空时回退为 "Run tool: <name>"
}

HostToolPermission 声明宿主工具的授权动作;配置后该工具在执行前会走 permission.Service.Request(与 opencode 内置工具同一套权限门禁)。

未配置(nil)表示内部只读工具,不触发权限请求。

type HostToolResult

type HostToolResult struct {
	Content  string // 回传给模型的文本
	IsError  bool   // 是否为失败结果(模型据此纠正行为)
	Metadata any    // 可选的结构化元信息
}

HostToolResult 是宿主工具 Handler 返回的结果。

type InputMessage

type InputMessage struct {
	Role    Role
	Content string
}

InputMessage 是种子历史中的一条对话消息。 注意:opencode 的 provider 仅渲染 user / assistant / tool 三种历史角色, system 请通过 RunRequest.System 传递。

type MessageSnapshot

type MessageSnapshot struct {
	ID           string
	SessionID    string
	Role         Role
	Text         string
	Thinking     string
	ToolCalls    []ToolCall
	ToolResults  []ToolResult
	FinishReason string
	Finished     bool
	Model        string
	CreatedAt    int64
	UpdatedAt    int64
}

type Options

type Options struct {
	WorkingDir string
	Debug      bool

	// Provider 是厂商类型,决定走哪条 SDK 客户端(openai / anthropic / gemini / deepseek …)。
	Provider string
	// BaseURL 是厂商 API 基地址(OpenAI 兼容协议生效),为空则用内置默认地址。
	BaseURL string
	// APIKey 是本次请求使用的凭据。
	APIKey string
	// APIModel 是发给厂商的真实模型名;为空时回退为 ModelID。
	APIModel string
	// ModelID 是模型标识:类库内部用它作为模型 key 与日志/回显。
	ModelID string
	// Name 是模型展示名;为空时回退 ModelID。
	Name string

	// ContextWindow 模型上下文窗口(token 数);0 表示未知。
	ContextWindow int64
	// DefaultMaxTokens 模型默认最大输出 token;0 表示未知。
	DefaultMaxTokens int64
	// MaxTokens 本次请求的最大输出 token,覆盖 DefaultMaxTokens。
	MaxTokens int64
	// CanReason 表示模型支持推理 / 思考过程(决定是否下发 reasoning effort)。
	CanReason bool
	// SupportsAttachments 表示模型支持图片等附件。
	SupportsAttachments bool
	// ReasoningEffort 推理强度(openai 系 low / medium / high)。
	ReasoningEffort string

	// CostPer1MIn / CostPer1MOut 每百万输入 / 输出 token 价格(美元)。
	// 仅用于会话费用统计(Session.Cost 与 TUI 展示),不参与请求。
	CostPer1MIn  float64
	CostPer1MOut float64
	// CostPer1MInCached / CostPer1MOutCached 命中缓存的输入 / 输出价格。
	CostPer1MInCached  float64
	CostPer1MOutCached float64

	AutoApprove bool

	// PermissionHandler 可选:注入后,工具权限请求逐次委托给宿主决策。
	PermissionHandler PermissionHandler

	// Tools 可选:宿主注入的自定义工具,追加到 opencode 内置工具之后,与内置工具
	// 共用同一套 tool-call 循环(模型可调用,opencode 负责回填结果)。
	Tools []HostTool
}

Options 描述「一次请求」所需的全部模型参数。

作为类库使用时,调用方只需给出本次请求用到的模型与凭据, 不再需要传入整张 provider / agent 配置表(已移除 Providers / Agents 字段)。

type PermissionDecision

type PermissionDecision int

PermissionDecision 是权限委托返回的决策结果。

const (
	// PermissionDeny 拒绝(默认值,安全兜底)。
	PermissionDeny PermissionDecision = iota
	// PermissionAllow 允许执行。
	PermissionAllow
)

type PermissionHandler

type PermissionHandler func(ctx context.Context, req PermissionRequest) PermissionDecision

PermissionHandler 由宿主注入,用于把工具权限请求委托给外部策略 / UI。

clientOpts.PermissionHandler = func(ctx context.Context, req sdk.PermissionRequest) sdk.PermissionDecision {
    op := toOperation(req)                       // 转成上层的中立 Operation
    decision, err := rt.RequestPermission(ctx, userID, op)
    if err != nil || decision != agent.DecisionAllow {
        return sdk.PermissionDeny
    }
    return sdk.PermissionAllow
}

配置后,SDK 不再阻塞等待命令行交互,而是逐次调用该委托决策。

type PermissionRequest

type PermissionRequest struct {
	SessionID   string
	ToolName    string
	Action      string // execute / write / read / fetch ...
	Path        string
	Description string
	Params      any
}

PermissionRequest 是一次待决策的权限请求(面向宿主的公开视图)。

type Role

type Role string
const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

type RunRequest

type RunRequest struct {
	SessionID    string
	SessionTitle string
	Prompt       string
	AutoApprove  bool

	// System 可选:宿主系统提示词,作为真正的 system 消息注入到模型,
	// 不进入对话历史,因此不会被反复追加为 user 内容。
	System string
	// History 可选:结构化历史对话(按时间顺序),不含本轮 Prompt,也不含 System。
	// opencode 会把它作为已有会话消息加载,再追加本轮 Prompt。
	History []InputMessage
}

type RunResult

type RunResult struct {
	SessionID string
	Message   MessageSnapshot
}

type Session

type Session struct {
	ID               string
	ParentSessionID  string
	Title            string
	PromptTokens     int64
	CompletionTokens int64
	SummaryMessageID string
	Cost             float64
	CreatedAt        int64
	UpdatedAt        int64
}

type StreamHandler

type StreamHandler func(event Event)

type ToolCall

type ToolCall struct {
	ID       string
	Name     string
	Input    string
	Type     string
	Finished bool
}

type ToolResult

type ToolResult struct {
	ToolCallID string
	Name       string
	Content    string
	Metadata   string
	IsError    bool
}

Jump to

Keyboard shortcuts

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