opencode

package
v0.186.3 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package opencode reads sessions from OpenCode's SQLite database.

OpenCode (github.com/sst/opencode) is a second coding agent people run alongside Claude Code, and often instead of it. Where Claude Code leaves a trail of JSONL transcripts that Caprock has to parse, join and price itself, OpenCode keeps one SQLite database in which cost and token counts are already computed per session and per message. Reading it is therefore a translation job, not an ingestion pipeline: the numbers arrive finished and only have to be mapped onto Caprock's event model.

The database is opened read-only. It belongs to another program that may be writing to it at the same time, and a monitoring tool that corrupts the thing it monitors is worse than no monitoring at all. WAL mode makes concurrent readers safe, but the immutable=0 read-only URI is what guarantees we never take a write lock and never block a running session.

Index

Constants

View Source
const Agent = "opencode"

Agent is the value written to sessions.agent for everything this package produces. It is the string the UI filters on, so it is defined once here.

View Source
const DefaultServerURL = "http://127.0.0.1:4096"

DefaultServerURL is where `opencode serve` listens unless told otherwise.

Variables

This section is empty.

Functions

func Available

func Available() bool

Available reports whether an OpenCode database exists on this machine.

func DBPath

func DBPath() string

DBPath returns the path to OpenCode's database, or "" if it is not present.

OpenCode follows the XDG data convention on Unix and uses the same layout under LOCALAPPDATA on Windows. Non-stable install channels write to opencode-{channel}.db beside the stable one; OPENCODE_DB overrides both.

func NormalizeTool

func NormalizeTool(t string) string

NormalizeTool maps an OpenCode tool name onto the Claude Code spelling.

The two agents converged on the same tool vocabulary in different cases: OpenCode writes "bash", "read", "edit", Claude Code writes "Bash", "Read", "Edit". Caprock's loop detection, narration and work-kind classification all match on the Claude Code spelling, so normalising here means none of that code needs to learn about a second agent. Names with no counterpart are title-cased rather than dropped: an unknown tool should appear in the feed as itself, not vanish.

func Open

func Open(path string) (*sql.DB, error)

Open opens OpenCode's database read-only.

func PromptText added in v0.65.0

func PromptText(parts []string) string

PromptText is what the person typed in one user message: its text parts (already without the ones OpenCode marks synthetic or ignored) joined and clipped like a reply, minus the parts that are context another program injected rather than words a person wrote.

OpenCode flags what it writes into a user message itself — the "Continue if you have next steps…" after a compaction, "Summarize the task tool output above…" — and TextParts has already dropped those. It does not flag text a program sends through it: on the owner's database four sessions open with a `<system-reminder>` block, a persona greeting an agent app drives OpenCode with, as the whole of the user message. Stored as a prompt it would become the session's description and match searches for words nobody typed. A part that opens with that tag is skipped; one that merely mentions it is kept.

func Read added in v0.93.0

func Read(ctx context.Context, db *sql.DB, s Session) ([]Message, []ToolCall, map[string][]string, error)

Read returns everything one session holds: its messages in order, its tool calls, and the text of each message, from whichever schema has them (see the note at the top of this file).

func ServerURL added in v0.23.0

func ServerURL() string

ServerURL is where OpenCode's headless server is expected.

OPENCODE_URL overrides it, which is what a user with a non-default port needs and what the tests point at a stub.

func TextParts added in v0.65.0

func TextParts(ctx context.Context, db *sql.DB, sessionID string) (map[string][]string, error)

TextParts returns the `text` parts of each message in one session, keyed by message id, in order and trimmed, without the parts OpenCode marks synthetic or ignored. Texts joins them into a reply and PromptText into a prompt; one read serves both, so importing a session's prompts costs no second scan of its parts.

func Texts added in v0.64.0

func Texts(ctx context.Context, db *sql.DB, sessionID string) (map[string]string, error)

Texts returns the visible prose of each message in one session, keyed by message id: the message's `text` parts in order, trimmed and joined with a newline, clipped on a rune boundary to the cap the Claude Code parser uses.

Only `text` parts are read. `reasoning` parts are the model's private thinking and are never stored, for the same reason Claude's extended thinking is not. The caller decides which roles it wants; this returns every message that has text.

func ToolInput added in v0.71.0

func ToolInput(raw json.RawMessage) map[string]any

ToolInput turns a call's arguments into the tool_input a Claude Code event carries, so every reader of tool_input — the tool drill-down's grouping by command, file, domain and query, loop signatures, narration, pull-request detection — reads an OpenCode call the way it reads a Claude Code one.

OpenCode and Claude Code name the same arguments in different cases: `filePath`, `oldString`, `replaceAll` against `file_path`, `old_string`, `replace_all`. Every key is moved to snake_case; `command`, `url`, `query`, `pattern` and `path` are the same word in both. Values are kept as they are, within the parser's size bounds.

A nil result means the call recorded no arguments at all.

func WaitCreated added in v0.70.0

func WaitCreated(ctx context.Context, url string) (string, error)

WaitCreated follows the event stream of one OpenCode server — a TUI Caprock started on a port it chose — and returns the id of the first top-level session that server creates. A subagent's session (parentID set) is skipped: it belongs to the session that spawned it.

The server is not up the moment the process starts, so a refused connection is retried until ctx ends, which the caller ties to the process's life. This is exact, unlike matching on folder and time: nothing but the TUI Caprock started is on that port, and the frame names the session it made.

Types

type Ingester

type Ingester struct {

	// Link files a session under the Caprock session that started it, when
	// Caprock did (see internal/sessionlink). Nil leaves every session under
	// OpenCode's own id.
	Link *sessionlink.Linker
	// contains filtered or unexported fields
}

Ingester copies OpenCode's sessions into Caprock's store.

It polls rather than tails. OpenCode exposes an SSE stream that would give live events, but the first pass deliberately reads the database instead: a few seconds of latency on a cost figure is not worth delaying every screen for, and the database is the only source that also carries history from before Caprock was installed. The stream is a later addition, not a replacement — see .ai/16-opencode.md.

Every write is idempotent. Events are keyed, and `(session_id, key)` is unique in the store, so a poll that re-reads rows it has already seen is a no-op rather than a duplicate.

func NewIngester

func NewIngester(db *sql.DB, rec *rollup.Recorder, log *slog.Logger, every time.Duration) *Ingester

NewIngester builds an ingester over an already-open OpenCode database.

func (*Ingester) Run

func (in *Ingester) Run(ctx context.Context) error

Run polls until the context is cancelled.

The first pass happens immediately so history is present on the first page load rather than one tick later.

func (*Ingester) Stats

func (in *Ingester) Stats() Stats

Stats returns a snapshot of what has been ingested.

func (*Ingester) Touch added in v0.23.0

func (in *Ingester) Touch(ctx context.Context, sessionID string)

Touch re-reads one session immediately, out of turn.

This is what the live stream calls: an event says a session changed, and the figures still come from the database rather than from the event, because the database is the only place OpenCode's own cost arithmetic lives. Reading the event's payload instead would mean maintaining a second understanding of their schema that drifts from the first.

type Message

type Message struct {
	ID         string
	SessionID  string
	Role       string
	Model      string
	Provider   string
	Cwd        string
	Cost       float64
	TokensIn   int64
	TokensOut  int64
	CacheRead  int64
	CacheWrite int64
	Created    int64 // unix ms
	Completed  int64 // unix ms
}

Message is one assistant turn with its own cost and token counts.

func Messages

func Messages(ctx context.Context, db *sql.DB, sessionID string) ([]Message, error)

Messages returns messages for one session in chronological order.

type ServiceStreamer added in v0.93.0

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

ServiceStreamer follows OpenCode 2's background service.

func NewServiceStreamer added in v0.93.0

func NewServiceStreamer(log *slog.Logger) *ServiceStreamer

NewServiceStreamer builds a streamer for the service this user's OpenCode 2 would connect to. It finds nothing to follow on a machine without OpenCode 2, which is the normal case, and keeps looking with backoff.

func (*ServiceStreamer) Run added in v0.93.0

func (s *ServiceStreamer) Run(ctx context.Context, onChange func(sessionID string))

Run follows the service until ctx ends. The file is read again before every connection, because the service can be restarted with a new password, and a missing file is the normal case on a machine that does not run OpenCode 2.

type Session

type Session struct {
	ID         string
	ParentID   string // non-empty for subagent sessions
	Directory  string
	Title      string
	Model      string
	Provider   string
	Cost       float64
	TokensIn   int64
	TokensOut  int64
	CacheRead  int64
	CacheWrite int64
	Created    int64 // unix ms
	Updated    int64 // unix ms
	// InV1 and InV2 say which table the session was read from: OpenCode 1's
	// `session`, OpenCode 2's `session_v2`, or both for a session OpenCode 2
	// migrated or continued (v2.go).
	InV1, InV2 bool
}

Session is one OpenCode session, with the totals it already carries.

Cost is OpenCode's own figure, computed from models.dev pricing at the time the turn ran. It is a modelled number rather than a billed one — the same caveat Caprock states for its own pricing — but it is the agent's own arithmetic, not ours, so it is used as given rather than recomputed.

func SessionByID added in v0.23.0

func SessionByID(ctx context.Context, db *sql.DB, id string) (Session, bool, error)

SessionByID returns one session, or false when it is not there.

The live path reads one row rather than the whole table: an event names a session, and listing every session to find it turned a per-event read into a full scan — enough, on a busy stream, to hold the store's write lock long enough for the daemon's own sweeps to fail with SQLITE_BUSY. A database OpenCode 2 has migrated can hold the session in both tables (v2.go); the two rows are merged.

func Sessions

func Sessions(ctx context.Context, db *sql.DB) ([]Session, error)

Sessions returns every session, newest activity first, from OpenCode 1's `session` table, OpenCode 2's `session_v2`, or both (v2.go).

func (Session) IsChild

func (s Session) IsChild() bool

IsChild reports whether this session is a subagent of another.

This matters for totals: OpenCode stores a subagent's cost on its own row, so summing every row double-counts against a parent-inclusive view. On the owner's machine that is 47 of 70 sessions and a 1.4% overstatement.

type Stats

type Stats struct {
	Sessions int   `json:"sessions"`
	Events   int   `json:"events"`
	LastPoll int64 `json:"last_poll_ms,omitempty"`
}

Stats is what the daemon reports about OpenCode ingest.

type Streamer added in v0.23.0

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

Streamer follows OpenCode's event stream and reports which sessions changed.

func NewStreamer added in v0.23.0

func NewStreamer(url string, log *slog.Logger) *Streamer

NewStreamer builds a streamer against an OpenCode server URL.

func (*Streamer) Run added in v0.23.0

func (s *Streamer) Run(ctx context.Context, onChange func(sessionID string))

Run follows the stream until the context is cancelled, calling onChange with the session id behind every event that matters.

It reconnects on its own. `opencode serve` is not always running — the stream is available while a TUI is open and gone when it closes — so a failed connection is the normal case rather than an error, and it is logged at debug level for that reason.

type ToolCall

type ToolCall struct {
	ID        string
	MessageID string
	SessionID string
	Tool      string // Caprock-cased name, see NormalizeTool
	RawTool   string // as OpenCode wrote it
	FilePath  string // the file it touched, when it names one
	// Input is the call's arguments as OpenCode wrote them (state.input), in
	// its own spelling; ToolInput turns them into Claude Code's.
	Input  json.RawMessage
	Status string
	Start  int64 // unix ms
	End    int64 // unix ms
}

ToolCall is one tool invocation inside a message.

func ToolCalls

func ToolCalls(ctx context.Context, db *sql.DB, sessionID string) ([]ToolCall, error)

ToolCalls returns the tool invocations of one session in order.

Jump to

Keyboard shortcuts

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