opencode

package
v0.42.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: Apache-2.0 Imports: 18 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 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.

Types

type Ingester

type Ingester struct {
	// 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 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
}

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.

func Sessions

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

Sessions returns every session, newest activity first.

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
	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