The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
opencode, hermes: read OpenCode 2.x sessions and older Hermes state.db files (#952)
claude[bot]6926f03afc11
diff --git a/cli/beacon-hooks/cmd/opencode_event.go b/cli/beacon-hooks/cmd/opencode_event.goindex 7c23e411..050bfdca 100644--- a/cli/beacon-hooks/cmd/opencode_event.go+++ b/cli/beacon-hooks/cmd/opencode_event.go@@ -504,8 +504,8 @@ func opencodeUsage(input map[string]interface{}) map[string]interface{} {// 2026) did not either, but a live event is far more likely to come from the// current runtime, so a missing total is taken as the current shape. The poll// backfill (cli/beacon/internal/opencodesession) makes the same call, except-// that a stored message without a total is from those early releases, because-// 2.x keeps its messages in a table the backfill does not read.+// that a stored 1.x message without a total is from those early releases; it+// reads 2.x's session_message rows as the current shape.func opencodeOutputTokens(tokens, cache map[string]interface{}, output, reasoning int) int {if reasoning <= 0 {return outputdiff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.goindex 20f89943..6260d4fe 100644--- a/cli/beacon/internal/hermessession/collect.go+++ b/cli/beacon/internal/hermessession/collect.go@@ -367,6 +367,9 @@ func emit(event schema.Event, opts CollectOptions) error {type Store struct {path stringdb *sql.DB+ // Hermes adds columns to an existing state.db as it upgrades, so an older database lacks some+ // the collector reads, such as cwd and archived. Those read as NULL or their default instead.+ sessionCols, messageCols map[string]bool}func OpenStore(path string) (*Store, error) {@@ -378,7 +381,52 @@ func OpenStore(path string) (*Store, error) {_ = db.Close()return nil, err}- return &Store{path: path, db: db}, nil+ store := &Store{path: path, db: db}+ if store.sessionCols, err = tableColumns(db, "sessions"); err == nil {+ store.messageCols, err = tableColumns(db, "messages")+ }+ if err != nil {+ _ = db.Close()+ return nil, err+ }+ return store, nil+}++func tableColumns(db *sql.DB, table string) (map[string]bool, error) {+ rows, err := db.Query(`SELECT name FROM pragma_table_info(?)`, table)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ cols := map[string]bool{}+ for rows.Next() {+ var name string+ if err := rows.Scan(&name); err != nil {+ return nil, err+ }+ cols[name] = true+ }+ return cols, rows.Err()+}++// column is alias.name when the table has the column, and fallback when it does not.+func column(cols map[string]bool, alias, name, fallback string) string {+ if !cols[name] {+ return fallback+ }+ if alias != "" {+ return alias + "." + name+ }+ return name+}++// columns selects each name, or NULL for one the table does not have.+func columns(cols map[string]bool, names ...string) string {+ out := make([]string, len(names))+ for i, name := range names {+ out[i] = column(cols, "", name, "NULL")+ }+ return strings.Join(out, ", ")}func (s *Store) Close() error { return s.db.Close() }@@ -387,13 +435,13 @@ func (s *Store) Path() string { return s.path }func (s *Store) ListSessions() ([]Session, error) {rows, err := s.db.Query(`-SELECT id, source, model, cwd, title, parent_session_id, started_at, ended_at, end_reason,- message_count, tool_call_count, input_tokens, output_tokens, cache_read_tokens,- cache_write_tokens, reasoning_tokens, estimated_cost_usd, actual_cost_usd,- cost_status, cost_source,- (SELECT max(m.timestamp) FROM messages m WHERE m.session_id = sessions.id AND m.active = 1) AS last_message_at+SELECT id, source, ` + columns(s.sessionCols, "model", "cwd", "title", "parent_session_id") + `, started_at,+ ` + columns(s.sessionCols, "ended_at", "end_reason", "message_count", "tool_call_count", "input_tokens",+ "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "estimated_cost_usd",+ "actual_cost_usd", "cost_status", "cost_source") + `,+ (SELECT max(m.timestamp) FROM messages m WHERE m.session_id = sessions.id AND ` + column(s.messageCols, "m", "active", "1") + ` = 1) AS last_message_atFROM sessions-WHERE archived = 0+WHERE ` + column(s.sessionCols, "", "archived", "0") + ` = 0ORDER BY started_at, id`)if err != nil {return nil, err@@ -437,11 +485,11 @@ ORDER BY started_at, id`)func (s *Store) ReadMessages(sessionID string, afterID int64) ([]Message, error) {rows, err := s.db.Query(`-SELECT id, session_id, role, content, tool_call_id, tool_calls, tool_name, timestamp,- token_count, finish_reason, reasoning, reasoning_content, reasoning_details,- platform_message_id, observed, active+SELECT id, session_id, role, `+columns(s.messageCols, "content", "tool_call_id", "tool_calls", "tool_name")+`, timestamp,+ `+columns(s.messageCols, "token_count", "finish_reason", "reasoning", "reasoning_content", "reasoning_details",+ "platform_message_id", "observed")+`, `+column(s.messageCols, "", "active", "1")+`FROM messages-WHERE session_id = ? AND active = 1 AND id > ?+WHERE session_id = ? AND `+column(s.messageCols, "", "active", "1")+` = 1 AND id > ?ORDER BY id`, sessionID, afterID)if err != nil {return nil, err@@ -495,28 +543,8 @@ type SessionDetail struct {// SessionDetails returns a SessionDetail for every session ListSessions lists, keyed by id.func (s *Store) SessionDetails() (map[string]SessionDetail, error) {- columns := map[string]bool{}- rows, err := s.db.Query(`SELECT name FROM pragma_table_info('sessions')`)- if err != nil {- return nil, err- }- for rows.Next() {- var name string- if err := rows.Scan(&name); err != nil {- rows.Close()- return nil, err- }- columns[name] = true- }- if err := rows.Close(); err != nil {- return nil, err- }- branch := "NULL"- if columns["git_branch"] {- branch = "git_branch"- }out := map[string]SessionDetail{}- rows, err = s.db.Query(`SELECT id, model_config, ` + branch + ` FROM sessions WHERE archived = 0`)+ rows, err := s.db.Query(`SELECT id, ` + columns(s.sessionCols, "model_config", "git_branch") + ` FROM sessions WHERE ` + column(s.sessionCols, "", "archived", "0") + ` = 0`)if err != nil {return nil, err}@@ -539,10 +567,10 @@ func (s *Store) SessionDetails() (map[string]SessionDetail, error) {rows, err = s.db.Query(`SELECT session_id, max(timestamp),(SELECT f.content FROM messages f- WHERE f.session_id = m.session_id AND f.active = 1 AND f.role = 'user' AND trim(COALESCE(f.content, '')) != ''+ WHERE f.session_id = m.session_id AND ` + column(s.messageCols, "f", "active", "1") + ` = 1 AND f.role = 'user' AND trim(COALESCE(f.content, '')) != ''ORDER BY f.id LIMIT 1)FROM messages m-WHERE active = 1+WHERE ` + column(s.messageCols, "m", "active", "1") + ` = 1GROUP BY session_id`)if err != nil {return nil, err@@ -568,7 +596,7 @@ GROUP BY session_id`)func (s *Store) LastMessageID(sessionID string) (int64, error) {var last sql.NullInt64- if err := s.db.QueryRow(`SELECT max(id) FROM messages WHERE session_id = ? AND active = 1`, sessionID).Scan(&last); err != nil {+ if err := s.db.QueryRow(`SELECT max(id) FROM messages WHERE session_id = ? AND `+column(s.messageCols, "", "active", "1")+` = 1`, sessionID).Scan(&last); err != nil {return 0, err}return last.Int64, nildiff --git a/cli/beacon/internal/hermessession/collect_test.go b/cli/beacon/internal/hermessession/collect_test.goindex 945b9568..3fab5014 100644--- a/cli/beacon/internal/hermessession/collect_test.go+++ b/cli/beacon/internal/hermessession/collect_test.go@@ -91,6 +91,32 @@ func TestCollectOnceMapsHermesStateDBAndAdvancesCursor(t *testing.T) {}}+// A state.db from an older Hermes lacks columns later releases added, such as cwd and archived.+// The sweep reads them as empty rather than failing with "no such column".+func TestCollectOnceReadsAStateDBWithoutLaterColumns(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "state.db")+ createHermesFixtureDB(t, dbPath)+ db, err := sql.Open("sqlite", dbPath)+ if err != nil {+ t.Fatal(err)+ }+ for _, stmt := range []string{"ALTER TABLE sessions DROP COLUMN cwd", "ALTER TABLE sessions DROP COLUMN archived", "ALTER TABLE messages DROP COLUMN active"} {+ if _, err := db.Exec(stmt); err != nil {+ t.Fatalf("%s: %v", stmt, err)+ }+ }+ db.Close()++ summary, err := CollectOnce(CollectOptions{DBPath: dbPath, StatePath: filepath.Join(dir, "state.json"), LogPath: filepath.Join(dir, "runtime.jsonl"), Write: true, UserMode: true})+ if err != nil {+ t.Fatalf("CollectOnce returned error: %v", err)+ }+ if summary.Sessions != 1 || summary.EventsEmitted == 0 {+ t.Fatalf("summary = %#v, want the session's events", summary)+ }+}+func TestMapSessionClassifiesFileTool(t *testing.T) {session := Session{ID: "s1", Model: "anthropic/claude-opus-4.6", CWD: "/repo", StartedAtMS: 1000}messages := []Message{diff --git a/cli/beacon/internal/opencodesession/collect.go b/cli/beacon/internal/opencodesession/collect.goindex 66302619..5424d8e2 100644--- a/cli/beacon/internal/opencodesession/collect.go+++ b/cli/beacon/internal/opencodesession/collect.go@@ -17,6 +17,10 @@ import (const StateVersion = 1+// stateCheckpointInterval is how often a sweep saves its cursors while it runs. A first sync over a+// long history can take minutes, and a sweep stopped before it returns otherwise keeps nothing.+const stateCheckpointInterval = 5 * time.Second+type Cursor struct {LastOrder int `json:"last_order"`UpdatedAtMS int64 `json:"updated_at_ms,omitempty"`@@ -144,7 +148,13 @@ func CollectOnce(opts CollectOptions) (summary Summary, err error) {summary.Errors++errs = append(errs, listErr)}+ saved := time.Now()for _, ref := range refs {+ if time.Since(saved) >= stateCheckpointInterval {+ if err := state.Save(opts.StatePath); err == nil {+ saved = time.Now()+ }+ }changed, collectErr := collectTrace(store, ref, state, opts, &summary)if errors.Is(collectErr, writer.ErrBudgetSpent) {// Not a failed session: this one and the rest are left for a later sync, with cursorsdiff --git a/cli/beacon/internal/opencodesession/collect_test.go b/cli/beacon/internal/opencodesession/collect_test.goindex f2c8ee4e..9dbe9968 100644--- a/cli/beacon/internal/opencodesession/collect_test.go+++ b/cli/beacon/internal/opencodesession/collect_test.go@@ -149,3 +149,53 @@ func loggedActions(t *testing.T, path string) []string {}return actions}++// OpenCode 2.x lists sessions in session_v2 and keeps their history in session_message, migrating+// 1.x sessions into both under the same ids and timestamps. The migrated copy must not be written+// twice, and what 2.x added afterwards must be.+func TestCollectOnceReadsOpenCode2Sessions(t *testing.T) {+ dir := t.TempDir()+ db := newOpenCodeDB(t, filepath.Join(dir, "opencode.db"))+ insertJSON(t, db, `INSERT INTO message (id, session_id, time_created, data) VALUES (?, ?, ?, ?)`, "msg_1", "ses_1", int64(1770000000100), map[string]interface{}{"id": "msg_1", "role": "user"})+ insertJSON(t, db, `INSERT INTO part (id, message_id, session_id, time_created, data) VALUES (?, ?, ?, ?, ?)`, "prt_1", "msg_1", "ses_1", int64(1770000000100), map[string]interface{}{"id": "prt_1", "type": "text", "text": "old prompt"})+ mustExec(t, db, `CREATE TABLE session_v2 (id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, time_archived INTEGER)`)+ mustExec(t, db, `CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, type TEXT NOT NULL, seq INTEGER NOT NULL, time_created INTEGER NOT NULL, data TEXT NOT NULL)`)+ mustExec(t, db, `INSERT INTO session_v2 (id, directory, time_created, time_updated) VALUES ('ses_1', '/repo', 1770000000000, 1770000000900), ('ses_2', '/repo2', 1770000001000, 1770000001500)`)+ insert := `INSERT INTO session_message (id, session_id, type, seq, time_created, data) VALUES (?, ?, ?, ?, ?, ?)`+ insertJSON(t, db, insert, "msg_1", "ses_1", "user", 1, int64(1770000000100), map[string]interface{}{"text": "old prompt"})+ insertJSON(t, db, insert, "msg_2", "ses_1", "user", 2, int64(1770000000800), map[string]interface{}{"text": "resumed in 2.x"})+ insertJSON(t, db, insert, "msg_3", "ses_2", "user", 1, int64(1770000001100), map[string]interface{}{"text": "run tests"})+ insertJSON(t, db, insert, "msg_4", "ses_2", "assistant", 2, int64(1770000001200), map[string]interface{}{+ "model": map[string]interface{}{"id": "claude-sonnet-4-5", "providerID": "anthropic"},+ "content": []interface{}{+ map[string]interface{}{"type": "text", "text": "Running them."},+ map[string]interface{}{"type": "tool", "id": "call_1", "name": "bash",+ "state": map[string]interface{}{"status": "completed", "input": map[string]interface{}{"command": "go test ./..."},+ "content": []interface{}{map[string]interface{}{"type": "text", "text": "ok"}}, "metadata": map[string]interface{}{"exit": 0}},+ "time": map[string]interface{}{"created": 1770000001300, "completed": 1770000001400}},+ },+ "tokens": map[string]interface{}{"input": 100, "output": 20, "reasoning": 5, "cache": map[string]interface{}{"read": 0, "write": 0}},+ "cost": 0.01,+ })+ // A completed compaction carries the usage of the summarizing model call.+ insertJSON(t, db, insert, "msg_5", "ses_2", "compaction", 3, int64(1770000001450), map[string]interface{}{+ "status": "completed", "model": map[string]interface{}{"id": "claude-sonnet-4-5", "providerID": "anthropic"},+ "tokens": map[string]interface{}{"input": 400, "output": 50, "reasoning": 0, "cache": map[string]interface{}{"read": 0, "write": 0}},+ "cost": 0.02,+ })++ logPath := filepath.Join(dir, "runtime.jsonl")+ if _, err := CollectOnce(CollectOptions{DataDir: dir, StatePath: filepath.Join(dir, "state.json"), LogPath: logPath, Write: true}); err != nil {+ t.Fatal(err)+ }+ got := map[string]int{}+ for _, action := range loggedActions(t, logPath) {+ got[action]+++ }+ want := map[string]int{"prompt.submitted": 3, "agent.message": 1, "command.executed": 1, "token.usage": 2}+ for action, n := range want {+ if got[action] != n {+ t.Fatalf("logged %v, want %v", got, want)+ }+ }+}diff --git a/cli/beacon/internal/opencodesession/mapper.go b/cli/beacon/internal/opencodesession/mapper.goindex 8c8f68e7..6ad83870 100644--- a/cli/beacon/internal/opencodesession/mapper.go+++ b/cli/beacon/internal/opencodesession/mapper.go@@ -224,9 +224,10 @@ func (m *mapper) emitUsage(record Record) {// Total settles which shape a message has: OpenCode copies the provider's// total, which is the full input side plus every output token, so it reaches// input + cache + output + reasoning only when output left reasoning out. A-// reasoning count above output can only mean the same. A message with no-// total predates v1.1.57 (the 2.x runtime keeps its messages in-// session_message, which this store does not read), so it keeps its output.+// reasoning count above output can only mean the same. A 1.x message with no+// total predates v1.1.57, so it keeps its output. 2.x session_message rows+// carry no total either; sessionMessageRecords gives them one that covers+// reasoning.// The live hook mapper (cli/beacon-hooks/cmd/opencode_event.go) makes the// same call, except that it takes a missing total as a 2.x step event.func (u TokenUsage) outputTokens() int64 {diff --git a/cli/beacon/internal/opencodesession/store.go b/cli/beacon/internal/opencodesession/store.goindex b0f427c6..dd24a916 100644--- a/cli/beacon/internal/opencodesession/store.go+++ b/cli/beacon/internal/opencodesession/store.go@@ -142,10 +142,30 @@ func (s *Store) listSQLite() ([]TraceRef, error) {return nil, fmt.Errorf("open OpenCode sqlite: %w", err)}defer db.Close()- if !sqliteTableExists(db, "session") {- return nil, nil+ // OpenCode 2.x keeps sessions in session_v2 and migrates 1.x sessions into it under the same+ // ids. session is the 1.x table, still read for a session that has not been migrated.+ var refs []TraceRef+ seen := map[string]bool{}+ for _, table := range []string{"session_v2", "session"} {+ if !sqliteTableExists(db, table) {+ continue+ }+ tableRefs, err := s.listSQLiteTable(db, table)+ for _, ref := range tableRefs {+ if !seen[ref.ID] {+ seen[ref.ID] = true+ refs = append(refs, ref)+ }+ }+ if err != nil {+ return refs, err+ }}- cols := sqliteColumns(db, "session")+ return refs, nil+}++func (s *Store) listSQLiteTable(db *sql.DB, table string) ([]TraceRef, error) {+ cols := sqliteColumns(db, table)selects := []string{sqliteSelectColumn(cols, "id"),sqliteSelectColumn(cols, "title"),@@ -155,7 +175,7 @@ func (s *Store) listSQLite() ([]TraceRef, error) {sqliteSelectColumn(cols, "time_updated"),sqliteSelectColumn(cols, "parent_id"),}- rows, err := db.Query("SELECT "+strings.Join(selects, ", ")+" FROM session ORDER BY COALESCE(time_updated, time_created, 0) DESC LIMIT ?", defaultListLimit)+ rows, err := db.Query("SELECT "+strings.Join(selects, ", ")+" FROM "+table+" ORDER BY COALESCE(time_updated, time_created, 0) DESC LIMIT ?", defaultListLimit)if err != nil {return nil, fmt.Errorf("read OpenCode sessions: %w", err)}@@ -199,18 +219,35 @@ func (s *Store) readSQLite(ref TraceRef) ([]Record, error) {return nil, fmt.Errorf("open OpenCode sqlite: %w", err)}defer db.Close()- if !sqliteTableExists(db, "message") || !sqliteTableExists(db, "part") {- return nil, nil- }- messages, err := readSQLiteMessages(db, ref.ID)- if err != nil {- return nil, err+ var records []Record+ // through is the latest 1.x message or part. OpenCode's migration copies a 1.x session into+ // session_message with the same timestamps, so only what 2.x wrote after it is read from there.+ var through int64+ if sqliteTableExists(db, "message") && sqliteTableExists(db, "part") {+ messages, err := readSQLiteMessages(db, ref.ID)+ if err != nil {+ return nil, err+ }+ parts, err := readSQLiteParts(db, ref.ID)+ if err != nil {+ return nil, err+ }+ records = recordsFromMessages(messages, parts)+ for _, msg := range messages {+ through = max(through, msg.Time.Created, msg.Time.Completed)+ for _, part := range parts[msg.ID] {+ through = max(through, part.TimeCreated)+ }+ }}- parts, err := readSQLiteParts(db, ref.ID)- if err != nil {- return nil, err+ if sqliteTableExists(db, "session_message") {+ v2, err := readSessionMessages(db, ref.ID, through, len(records)+1)+ if err != nil {+ return nil, err+ }+ records = append(records, v2...)}- return recordsFromMessages(messages, parts), nil+ return records, nil}func readSQLiteMessages(db *sql.DB, sessionID string) ([]opencodeMessage, error) {@@ -273,6 +310,150 @@ func readSQLiteParts(db *sql.DB, sessionID string) (map[string][]opencodePart, ereturn out, rows.Err()}+// readSessionMessages reads the session_message rows OpenCode 2.x wrote after through. Each row is+// one typed entry, and an assistant step carries its text, reasoning and tool calls in content.+func readSessionMessages(db *sql.DB, sessionID string, through int64, order int) ([]Record, error) {+ rows, err := db.Query("SELECT id, type, time_created, data FROM session_message WHERE session_id = ? AND time_created > ? ORDER BY seq", sessionID, through)+ if err != nil {+ return nil, fmt.Errorf("read OpenCode session messages: %w", err)+ }+ defer rows.Close()+ var out []Record+ for rows.Next() {+ var id, typ, data sql.NullString+ var created sql.NullInt64+ if err := rows.Scan(&id, &typ, &created, &data); err != nil {+ continue+ }+ var raw map[string]interface{}+ _ = json.Unmarshal([]byte(nullString(data)), &raw)+ for _, rec := range sessionMessageRecords(nullString(id), nullString(typ), normalizeMillis(nullInt(created)), raw) {+ rec.Order = order+ order+++ out = append(out, rec)+ }+ }+ return out, rows.Err()+}++func sessionMessageRecords(id, typ string, created int64, raw map[string]interface{}) []Record {+ model := opencodeModel(raw)+ switch typ {+ case "user":+ text := stringFromMap(raw, "text")+ if strings.TrimSpace(text) == "" {+ return nil+ }+ return []Record{{NativeID: id, TimestampMS: created, Type: "user_message", Role: "user", Content: text, ModelID: model}}+ case "shell":+ // A command the user ran with !, recorded as the bash tool call 1.x stored it as.+ status := "completed"+ if stringFromMap(raw, "status") == "running" {+ status = "running"+ }+ output := map[string]interface{}{"output": stringFromMap(mapFromAny(raw["output"]), "output")}+ if exit, ok := raw["exit"]; ok {+ output["metadata"] = map[string]interface{}{"exit": exit}+ }+ recType := "tool_result"+ if status == "running" {+ recType = "tool_call"+ }+ return []Record{{NativeID: id, TimestampMS: firstNonZero(normalizeMillis(intFromAny(mapFromAny(raw["time"])["completed"])), created), Type: recType,+ ToolName: "bash", CallID: firstNonEmpty(stringFromMap(raw, "shellID"), id), Args: map[string]interface{}{"command": stringFromMap(raw, "command")},+ Output: output, Status: status, Raw: map[string]interface{}{"message": raw}}}+ case "compaction":+ // A completed compaction carries the usage of the model call that summarized the history.+ out := []Record{{NativeID: id, TimestampMS: created, Type: "compaction", ModelID: model, Raw: map[string]interface{}{"message": raw}}}+ if usage, ok := sessionMessageUsage(id, raw, created, model); ok {+ out = append(out, usage)+ }+ return out+ case "assistant":+ default:+ return nil+ }+ var out []Record+ content, _ := raw["content"].([]interface{})+ for i, value := range content {+ item := mapFromAny(value)+ nativeID := id + ":" + strconv.Itoa(i)+ switch stringFromMap(item, "type") {+ case "text", "reasoning":+ text := stringFromMap(item, "text")+ if strings.TrimSpace(text) == "" {+ continue+ }+ recType := "assistant_text"+ if stringFromMap(item, "type") == "reasoning" {+ recType = "agent_reasoning"+ }+ out = append(out, Record{NativeID: nativeID, TimestampMS: created, Type: recType, Role: "assistant", Content: text, ModelID: model, Raw: map[string]interface{}{"part": item}})+ case "tool":+ out = append(out, sessionToolRecord(id, item, created, model))+ }+ }+ if usage, ok := sessionMessageUsage(id, raw, created, model); ok {+ out = append(out, usage)+ }+ completed := firstNonZero(normalizeMillis(intFromAny(mapFromAny(raw["time"])["completed"])), created)+ if errMap := mapFromAny(raw["error"]); len(content) == 0 && len(errMap) > 0 {+ out = append(out, Record{NativeID: id + ":error", TimestampMS: completed, Type: "error", Content: stringFromMap(errMap, "message", "type"), ModelID: model, Raw: map[string]interface{}{"message": raw}})+ }+ return out+}++// sessionMessageUsage is the token_usage record for a session_message row's tokens and cost.+func sessionMessageUsage(id string, raw map[string]interface{}, created int64, model string) (Record, bool) {+ completed := firstNonZero(normalizeMillis(intFromAny(mapFromAny(raw["time"])["completed"])), created)+ tokens := tokenUsageFromAny(raw["tokens"])+ // 2.x stores output without reasoning; a total that covers both tells outputTokens to add it back.+ tokens.Total = tokens.Input + tokens.CacheRead + tokens.CacheWrite + tokens.Output + tokens.Reasoning+ tokens.CostUSD = floatFromAny(raw["cost"])+ if !hasUsage(tokens) {+ return Record{}, false+ }+ return Record{NativeID: id + ":usage", TimestampMS: completed, Type: "token_usage", ModelID: model, Tokens: &tokens}, true+}++func sessionToolRecord(messageID string, item map[string]interface{}, created int64, model string) Record {+ state := mapFromAny(item["state"])+ timeMap := mapFromAny(item["time"])+ status := stringFromMap(state, "status")+ rec := Record{+ NativeID: messageID + ":" + stringFromMap(item, "id"),+ TimestampMS: firstNonZero(normalizeMillis(intFromAny(timeMap["created"])), created),+ Type: "tool_call",+ ModelID: model,+ ToolName: stringFromMap(item, "name"),+ CallID: stringFromMap(item, "id"),+ Args: mapFromAny(state["input"]),+ Status: firstNonEmpty(status, "invoked"),+ Raw: map[string]interface{}{"part": item},+ }+ if status != "completed" && status != "error" {+ return rec+ }+ rec.Type = "tool_result"+ rec.TimestampMS = firstNonZero(normalizeMillis(intFromAny(timeMap["completed"])), rec.TimestampMS)+ var texts []string+ contentItems, _ := state["content"].([]interface{})+ for _, value := range contentItems {+ if text := stringFromMap(mapFromAny(value), "text"); text != "" {+ texts = append(texts, text)+ }+ }+ var output interface{} = strings.Join(texts, "\n")+ if metadata := mapFromAny(state["metadata"]); len(metadata) > 0 {+ output = map[string]interface{}{"output": output, "metadata": metadata}+ }+ rec.Output = output+ if errText := stringFromMap(mapFromAny(state["error"]), "message"); errText != "" {+ rec.Raw["error"] = errText+ }+ return rec+}+func (s *Store) listLegacy() ([]TraceRef, error) {sessionRoot := filepath.Join(s.LegacyStorageDir, "session")if !dirExists(sessionRoot) {diff --git a/docs/runtimes/opencode.mdx b/docs/runtimes/opencode.mdxindex 11707372..47a6bffd 100644--- a/docs/runtimes/opencode.mdx+++ b/docs/runtimes/opencode.mdx@@ -28,7 +28,7 @@ The one plugin file loads in both OpenCode 1.x and OpenCode 2.x. Its default expThe integration is plugin-based. OpenCode's native OTLP export is neither configured nor required by Beacon.-For backfill, `beacon endpoint opencode sync` reads OpenCode's local `opencode.db` when present and falls back to the legacy `storage/session`, `storage/message`, `storage/part`, and `storage/project` tree. Those events are marked `harness.collection_method=poll` because Beacon reads committed records after the fact; nothing on that path can hold or deny a tool call.+For backfill, `beacon endpoint opencode sync` reads OpenCode's local `opencode.db` when present (the 2.x `session_v2` and `session_message` tables as well as the 1.x `session`, `message`, and `part` tables) and falls back to the legacy `storage/session`, `storage/message`, `storage/part`, and `storage/project` tree. Those events are marked `harness.collection_method=poll` because Beacon reads committed records after the fact; nothing on that path can hold or deny a tool call.## Discovery and status