sdk

package
v0.0.0-...-8ae2446 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 14 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 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
	AutoApprove bool
}

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
}

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