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
add opencode session sync
Justin D'Souzabc4a9059aa21
diff --git a/cli/beacon/cmd/endpoint_opencode.go b/cli/beacon/cmd/endpoint_opencode.gonew file mode 100644index 00000000..53fd93cc--- /dev/null+++ b/cli/beacon/cmd/endpoint_opencode.go@@ -0,0 +1,225 @@+package cmd++import (+ "context"+ "encoding/json"+ "fmt"+ "path/filepath"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/opencodesession"+ "github.com/spf13/cobra"+)++var endpointOpenCodeCmd = &cobra.Command{+ Use: "opencode",+ Short: "Collect telemetry from OpenCode local sessions",+ Long: `Collect endpoint telemetry from OpenCode's local session store.++Beacon's normal OpenCode integration uses a managed plugin for live capture.+This command reads OpenCode's committed local opencode.db or legacy storage tree+so historical sessions and sessions that ran without Beacon's plugin can still be+represented in the local endpoint log. Every emitted event is marked+harness.collection_method=poll: Beacon sees what OpenCode already wrote, so+nothing here can hold or deny a tool call.`,+}++var endpointOpenCodeSyncCmd = &cobra.Command{+ Use: "sync",+ Short: "Read new OpenCode session records into the runtime log",+ SilenceUsage: true,+ RunE: runEndpointOpenCodeSync,+}++var endpointOpenCodeStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show OpenCode local sessions and collection progress",+ SilenceUsage: true,+ RunE: runEndpointOpenCodeStatus,+}++var endpointOpenCodeOpts struct {+ dataDir string+ statePath string+ logPath string+ print bool+ watch bool+ interval time.Duration+}++func init() {+ endpointCmd.AddCommand(endpointOpenCodeCmd)+ endpointOpenCodeCmd.AddCommand(endpointOpenCodeSyncCmd)+ endpointOpenCodeCmd.AddCommand(endpointOpenCodeStatusCmd)++ for _, c := range []*cobra.Command{endpointOpenCodeSyncCmd, endpointOpenCodeStatusCmd} {+ f := c.Flags()+ f.StringVar(&endpointOpenCodeOpts.dataDir, "data-dir", "", "OpenCode data directory or opencode.db path (default ~/.config/opencode)")+ f.StringVar(&endpointOpenCodeOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/opencode-sessions.json)")+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")+ }++ sync := endpointOpenCodeSyncCmd.Flags()+ sync.StringVar(&endpointOpenCodeOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ sync.BoolVar(&endpointOpenCodeOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")+ sync.BoolVar(&endpointOpenCodeOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")+ sync.DurationVar(&endpointOpenCodeOpts.interval, "interval", time.Minute, "Sweep interval for --watch")+}++func runEndpointOpenCodeSync(cmd *cobra.Command, args []string) error {+ userMode := endpointUserMode()+ opts := opencodesession.CollectOptions{+ DataDir: endpointOpenCodeOpts.dataDir,+ Print: endpointOpenCodeOpts.print,+ Out: cmd.OutOrStdout(),+ Write: !endpointOpenCodeOpts.print,+ UserMode: userMode,+ }+ if !endpointOpenCodeOpts.print {+ opts.StatePath = resolveOpenCodeStatePath(endpointOpenCodeOpts.statePath, userMode)+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointOpenCodeOpts.logPath).EffectiveLogPath+ }+ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ if endpointOpenCodeOpts.watch && !endpointOpenCodeOpts.print {+ return watchOpenCode(ctx, cmd, opts)+ }+ summary, err := opencodesession.CollectOnce(opts)+ reportOpenCodeSweep(cmd, summary)+ return err+}++func watchOpenCode(ctx context.Context, cmd *cobra.Command, opts opencodesession.CollectOptions) error {+ interval := endpointOpenCodeOpts.interval+ if interval < 5*time.Second {+ interval = 5 * time.Second+ }+ for {+ summary, err := opencodesession.CollectOnce(opts)+ if err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "opencode sync error: %v\n", err)+ }+ reportOpenCodeSweep(cmd, summary)+ select {+ case <-ctx.Done():+ return nil+ case <-time.After(interval):+ }+ }+}++func reportOpenCodeSweep(cmd *cobra.Command, summary opencodesession.Summary) {+ if endpointOpenCodeOpts.print {+ return+ }+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)+ return+ }+ fmt.Fprintf(cmd.OutOrStdout(), "opencode sync: %d traces, %d changed, %d events, %d errors\n",+ summary.Traces, summary.TracesChanged, summary.EventsEmitted, summary.Errors)+}++type openCodeStatusRef struct {+ ID string `json:"id"`+ Source string `json:"source"`+ Workspace string `json:"workspace,omitempty"`+ UpdatedAt string `json:"updated_at,omitempty"`+ Collected bool `json:"collected"`+ EventsRead int `json:"events_read"`+ SizeBytes int64 `json:"size_bytes"`+ SourcePath string `json:"source_path,omitempty"`+}++type openCodeStatusReport struct {+ DataDir string `json:"data_dir"`+ SQLitePath string `json:"sqlite_path"`+ LegacyDir string `json:"legacy_storage_dir"`+ Present bool `json:"present"`+ StatePath string `json:"state_path,omitempty"`+ Traces []openCodeStatusRef `json:"traces"`+}++func runEndpointOpenCodeStatus(cmd *cobra.Command, args []string) error {+ store, err := opencodesession.NewStore(endpointOpenCodeOpts.dataDir)+ if err != nil {+ return err+ }+ statePath := resolveOpenCodeStatePath(endpointOpenCodeOpts.statePath, endpointUserMode())+ state, err := opencodesession.LoadState(statePath)+ if err != nil {+ return err+ }+ refs, listErr := store.List()+ if listErr != nil && len(refs) == 0 {+ return listErr+ }+ report := openCodeStatusReport{+ DataDir: store.DataDir,+ SQLitePath: store.SQLitePath,+ LegacyDir: store.LegacyStorageDir,+ Present: store.Exists(),+ StatePath: statePath,+ Traces: make([]openCodeStatusRef, 0, len(refs)),+ }+ for _, ref := range refs {+ cursor := state.Traces[string(ref.Kind)+":"+ref.ID]+ status := openCodeStatusRef{+ ID: ref.ID,+ Source: string(ref.Kind),+ Workspace: ref.Directory,+ Collected: cursor != nil && cursor.UpdatedAtMS >= ref.UpdatedAtUnixMS,+ SizeBytes: ref.SizeBytes,+ SourcePath: ref.SourcePath,+ }+ if ref.UpdatedAtUnixMS > 0 {+ status.UpdatedAt = time.UnixMilli(ref.UpdatedAtUnixMS).UTC().Format(time.RFC3339)+ }+ if cursor != nil {+ status.EventsRead = cursor.LastOrder+ }+ report.Traces = append(report.Traces, status)+ }+ if endpointOpts.jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(report)+ }+ if !report.Present {+ fmt.Fprintf(cmd.OutOrStdout(), "OpenCode session store not found at %s\n", report.DataDir)+ return listErr+ }+ fmt.Fprintf(cmd.OutOrStdout(), "OpenCode session store: %s\n", report.DataDir)+ fmt.Fprintf(cmd.OutOrStdout(), "State: %s\n", report.StatePath)+ for _, trace := range report.Traces {+ collected := "pending"+ if trace.Collected {+ collected = "collected"+ }+ updated := trace.UpdatedAt+ if updated == "" {+ updated = "unknown"+ }+ fmt.Fprintf(cmd.OutOrStdout(), " %s [%s] %s events=%d updated=%s", trace.ID, trace.Source, collected, trace.EventsRead, updated)+ if trace.Workspace != "" {+ fmt.Fprintf(cmd.OutOrStdout(), " workspace=%s", trace.Workspace)+ }+ fmt.Fprintln(cmd.OutOrStdout())+ }+ return listErr+}++func resolveOpenCodeStatePath(path string, userMode bool) string {+ if strings.TrimSpace(path) != "" {+ return path+ }+ base := filepath.Join("/var", "lib", "beacon", "endpoint", "state")+ if userMode {+ base = filepath.Dir(opencodesession.DefaultStatePath())+ }+ return filepath.Join(base, "opencode-sessions.json")+}diff --git a/cli/beacon/internal/opencodesession/collect.go b/cli/beacon/internal/opencodesession/collect.gonew file mode 100644index 00000000..8ee78c21--- /dev/null+++ b/cli/beacon/internal/opencodesession/collect.go@@ -0,0 +1,200 @@+package opencodesession++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+)++const StateVersion = 1++type Cursor struct {+ LastOrder int `json:"last_order"`+ UpdatedAtMS int64 `json:"updated_at_ms,omitempty"`+}++type State struct {+ Version int `json:"version"`+ Traces map[string]*Cursor `json:"traces"`+}++func LoadState(path string) (*State, error) {+ state := &State{Version: StateVersion, Traces: map[string]*Cursor{}}+ if strings.TrimSpace(path) == "" {+ return state, nil+ }+ data, err := os.ReadFile(path)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return state, nil+ }+ return nil, err+ }+ var stored State+ if err := json.Unmarshal(data, &stored); err != nil {+ return nil, fmt.Errorf("read OpenCode collector state %s: %w", path, err)+ }+ if stored.Version != StateVersion || stored.Traces == nil {+ return state, nil+ }+ return &stored, nil+}++func (s *State) Save(path string) error {+ if strings.TrimSpace(path) == "" {+ return nil+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ return err+ }+ s.Version = StateVersion+ data, err := json.MarshalIndent(s, "", " ")+ if err != nil {+ return err+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return err+ }+ return os.Rename(tmp, path)+}++func (s *State) cursor(ref TraceRef) *Cursor {+ if s.Traces == nil {+ s.Traces = map[string]*Cursor{}+ }+ key := stateKey(ref)+ cursor := s.Traces[key]+ if cursor == nil {+ cursor = &Cursor{}+ s.Traces[key] = cursor+ }+ return cursor+}++func stateKey(ref TraceRef) string {+ return string(ref.Kind) + ":" + ref.ID+}++func DefaultStatePath() string {+ base := filepath.Join(os.TempDir(), "beacon")+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {+ base = filepath.Join(home, ".beacon")+ }+ return filepath.Join(base, "endpoint", "state", "opencode-sessions.json")+}++type CollectOptions struct {+ DataDir string+ StatePath string+ Write bool+ LogPath string+ UserMode bool+ Print bool+ Out io.Writer+}++type Summary struct {+ Traces int `json:"traces"`+ TracesChanged int `json:"traces_changed"`+ EventsEmitted int `json:"events_emitted"`+ Errors int `json:"errors"`+}++func CollectOnce(opts CollectOptions) (summary Summary, err error) {+ store, err := NewStore(opts.DataDir)+ if err != nil {+ return summary, err+ }+ refs, listErr := store.List()+ if listErr != nil && len(refs) == 0 {+ return summary, listErr+ }+ summary.Traces = len(refs)+ state, err := LoadState(opts.StatePath)+ if err != nil {+ return summary, err+ }+ defer func() {+ if saveErr := state.Save(opts.StatePath); saveErr != nil && err == nil {+ err = fmt.Errorf("save OpenCode collector state: %w", saveErr)+ }+ }()++ var errs []error+ if listErr != nil {+ summary.Errors+++ errs = append(errs, listErr)+ }+ for _, ref := range refs {+ changed, collectErr := collectTrace(store, ref, state, opts, &summary)+ if collectErr != nil {+ summary.Errors+++ errs = append(errs, fmt.Errorf("OpenCode trace %s: %w", ref.ID, collectErr))+ continue+ }+ if changed {+ summary.TracesChanged+++ }+ }+ if len(errs) > 0 {+ return summary, errors.Join(errs...)+ }+ return summary, nil+}++func collectTrace(store *Store, ref TraceRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {+ cursor := state.cursor(ref)+ if ref.UpdatedAtUnixMS > 0 && ref.UpdatedAtUnixMS <= cursor.UpdatedAtMS {+ return false, nil+ }+ records, err := store.Read(ref)+ if err != nil {+ return false, err+ }+ mapped := MapTrace(ref, records, MapOptions{MinOrder: cursor.LastOrder})+ if len(mapped) == 0 {+ if len(records) > 0 && records[len(records)-1].Order > cursor.LastOrder {+ cursor.LastOrder = records[len(records)-1].Order+ }+ cursor.UpdatedAtMS = ref.UpdatedAtUnixMS+ return false, nil+ }+ for i, item := range mapped {+ if err := emit(item.Event, opts); err != nil {+ if i > 0 {+ cursor.LastOrder = mapped[i-1].SourceOrder+ }+ return true, err+ }+ cursor.LastOrder = item.SourceOrder+ summary.EventsEmitted+++ }+ cursor.UpdatedAtMS = ref.UpdatedAtUnixMS+ return true, nil+}++func emit(event schema.Event, opts CollectOptions) error {+ if opts.Print && opts.Out != nil {+ data, err := json.Marshal(event)+ if err != nil {+ return err+ }+ if _, err := opts.Out.Write(append(data, '\n')); err != nil {+ return err+ }+ }+ if opts.Write {+ if _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {+ return err+ }+ }+ return nil+}diff --git a/cli/beacon/internal/opencodesession/helpers.go b/cli/beacon/internal/opencodesession/helpers.gonew file mode 100644index 00000000..743a150e--- /dev/null+++ b/cli/beacon/internal/opencodesession/helpers.go@@ -0,0 +1,150 @@+package opencodesession++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "strconv"+ "strings"+)++func mapFromAny(value interface{}) map[string]interface{} {+ if value == nil {+ return nil+ }+ if m, ok := value.(map[string]interface{}); ok {+ return m+ }+ return nil+}++func stringFromMap(m map[string]interface{}, keys ...string) string {+ for _, key := range keys {+ if value := stringFromAny(m[key]); value != "" {+ return value+ }+ }+ return ""+}++func stringFromAny(value interface{}) string {+ switch v := value.(type) {+ case string:+ return strings.TrimSpace(v)+ case fmt.Stringer:+ return strings.TrimSpace(v.String())+ default:+ return ""+ }+}++func intFromAny(value interface{}) int64 {+ switch v := value.(type) {+ case int:+ return int64(v)+ case int64:+ return v+ case float64:+ return int64(v)+ case json.Number:+ n, _ := strconv.ParseInt(v.String(), 10, 64)+ return n+ case string:+ n, _ := strconv.ParseInt(strings.TrimSpace(v), 10, 64)+ return n+ default:+ return 0+ }+}++func floatFromAny(value interface{}) float64 {+ switch v := value.(type) {+ case float64:+ return v+ case int:+ return float64(v)+ case int64:+ return float64(v)+ case json.Number:+ f, _ := strconv.ParseFloat(v.String(), 64)+ return f+ case string:+ f, _ := strconv.ParseFloat(strings.TrimSpace(v), 64)+ return f+ default:+ return 0+ }+}++func boolFromAny(value interface{}) bool {+ switch v := value.(type) {+ case bool:+ return v+ case string:+ return strings.EqualFold(v, "true")+ default:+ return false+ }+}++func firstMapValue(m map[string]interface{}, keys ...string) interface{} {+ for _, key := range keys {+ if value, ok := m[key]; ok {+ return value+ }+ }+ return nil+}++func hasAnyKey(m map[string]interface{}, keys ...string) bool {+ for _, key := range keys {+ if _, ok := m[key]; ok {+ return true+ }+ }+ return false+}++func tokenUsageFromAny(value interface{}) TokenUsage {+ m := mapFromAny(value)+ cache := mapFromAny(m["cache"])+ return TokenUsage{+ Input: intFromAny(m["input"]),+ Output: intFromAny(m["output"]),+ Reasoning: intFromAny(m["reasoning"]),+ CacheRead: intFromAny(cache["read"]),+ CacheWrite: intFromAny(cache["write"]),+ }+}++func hasUsage(usage TokenUsage) bool {+ return usage.Input > 0 || usage.Output > 0 || usage.Reasoning > 0 || usage.CacheRead > 0 || usage.CacheWrite > 0 || usage.CostUSD > 0+}++func opencodeModel(raw map[string]interface{}) string {+ if model := stringFromMap(raw, "model"); model != "" {+ return model+ }+ if provider, model := stringFromMap(raw, "providerID", "provider_id"), stringFromMap(raw, "modelID", "model_id"); provider != "" && model != "" {+ return provider + "/" + model+ }+ modelInfo := mapFromAny(raw["model"])+ if len(modelInfo) == 0 {+ modelInfo = mapFromAny(raw["modelInfo"])+ }+ if len(modelInfo) == 0 {+ modelInfo = mapFromAny(raw["model_info"])+ }+ provider := stringFromMap(modelInfo, "providerID", "provider_id", "provider")+ name := stringFromMap(modelInfo, "modelID", "model_id", "id", "name")+ if provider != "" && name != "" {+ return provider + "/" + name+ }+ return name+}++func sha256Hex(value string) string {+ sum := sha256.Sum256([]byte(value))+ return hex.EncodeToString(sum[:])+}diff --git a/cli/beacon/internal/opencodesession/mapper.go b/cli/beacon/internal/opencodesession/mapper.gonew file mode 100644index 00000000..86b1d41c--- /dev/null+++ b/cli/beacon/internal/opencodesession/mapper.go@@ -0,0 +1,405 @@+package opencodesession++import (+ "crypto/sha1"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "io"+ "path/filepath"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++const Harness = "opencode"++type MappedEvent struct {+ DedupID string+ SourceOrder int+ Event schema.Event+}++type MapOptions struct {+ MinOrder int+}++func MapTrace(ref TraceRef, records []Record, opts MapOptions) []MappedEvent {+ m := &mapper{ref: ref, opts: opts}+ for i := range records {+ m.consume(records[i])+ }+ return m.out+}++type mapper struct {+ ref TraceRef+ opts MapOptions+ out []MappedEvent+}++func (m *mapper) consume(record Record) {+ if record.Order <= m.opts.MinOrder {+ return+ }+ switch record.Type {+ case "user_message":+ m.emitPrompt(record)+ case "assistant_text":+ m.emitAgentMessage(record)+ case "agent_reasoning":+ m.emitReasoning(record)+ case "tool_call":+ m.emitToolCall(record)+ case "tool_result":+ m.emitToolResult(record)+ case "compaction":+ m.emitCompaction(record)+ case "error":+ m.emitError(record)+ case "token_usage":+ m.emitUsage(record)+ }+}++func (m *mapper) base(record Record, action, category string, severity schema.Severity, message string) schema.Event {+ ev := schema.NewEvent(schema.NewEventOptions{+ Action: action,+ Category: category,+ Severity: severity,+ Fidelity: schema.FidelityObserved,+ Message: message,+ Origin: schema.OriginLocal,+ Harness: schema.HarnessInfo{+ Name: Harness,+ CollectionMethod: schema.CollectionMethodPoll,+ },+ })+ if record.TimestampMS > 0 {+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(record.TimestampMS))+ } else if m.ref.UpdatedAtUnixMS > 0 {+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(m.ref.UpdatedAtUnixMS))+ }+ ev.Session = &schema.SessionInfo{ID: m.ref.ID, WorkingDirectory: m.ref.Directory}+ if record.ModelID != "" {+ ev.Model = asymptoteobserve.NormalizeModelName(record.ModelID)+ }+ return ev+}++func (m *mapper) emitPrompt(record Record) {+ text := strings.TrimSpace(record.Content)+ if text == "" {+ return+ }+ ev := m.base(record, "prompt.submitted", "prompt", schema.SeverityInfo, "opencode prompt submitted")+ ev.Prompt = &schema.PromptInfo{Text: text}+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)+ ev.GenAI = &schema.GenAIInfo{Input: &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}}+ m.append(record, "prompt", ev)+}++func (m *mapper) emitAgentMessage(record Record) {+ text := strings.TrimSpace(record.Content)+ if text == "" {+ return+ }+ ev := m.base(record, "agent.message", "session", schema.SeverityInfo, "opencode agent message")+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(text)}}+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultRawStringLimit)+ m.append(record, "assistant", ev)+}++func (m *mapper) emitReasoning(record Record) {+ text := strings.TrimSpace(record.Content)+ if text == "" {+ return+ }+ ev := m.base(record, "agent.reasoning", "session", schema.SeverityInfo, "opencode agent reasoning")+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: []interface{}{map[string]interface{}{+ "role": "assistant",+ "parts": []interface{}{map[string]interface{}{+ "type": "reasoning",+ "content": text,+ }},+ }}}}+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultRawStringLimit)+ m.append(record, "reasoning", ev)+}++func (m *mapper) emitToolCall(record Record) {+ name := firstNonEmpty(record.ToolName, "unknown")+ ev := m.base(record, "tool.invoked", "tool", schema.SeverityInfo, "opencode tool invoked")+ ev.Tool = &schema.ToolInfo{Name: name}+ applyToolCall(&ev, name, record)+ ev.Raw = mergeRaw(ev.Raw, record.Raw)+ m.append(record, "tool.call", ev)+}++func (m *mapper) emitToolResult(record Record) {+ name := firstNonEmpty(record.ToolName, "unknown")+ action, category, severity, message := classifyTool(name, record)+ ev := m.base(record, action, category, severity, message)+ ev.Tool = &schema.ToolInfo{Name: name}+ applyToolCall(&ev, name, record)+ switch category {+ case "command":+ applyCommand(&ev, record)+ case "file":+ applyFile(&ev, name, record)+ case "mcp":+ ev.MCP = &schema.MCPInfo{Tool: name}+ }+ if record.Status == "error" {+ ev.Error = &schema.ErrorInfo{Type: "tool_error"}+ }+ ev.Raw = mergeRaw(ev.Raw, record.Raw)+ m.append(record, "tool.result", ev)+}++func (m *mapper) emitCompaction(record Record) {+ ev := m.base(record, "session.compacting", "session", schema.SeverityInfo, "opencode compacted session history")+ ev.Raw = mergeRaw(ev.Raw, record.Raw)+ m.append(record, "compaction", ev)+}++func (m *mapper) emitError(record Record) {+ ev := m.base(record, "session.error", "session", schema.SeverityHigh, "opencode session error")+ ev.Error = &schema.ErrorInfo{Type: firstNonEmpty(record.Content, "session_error")}+ ev.Raw = mergeRaw(ev.Raw, record.Raw)+ m.append(record, "error", ev)+}++func (m *mapper) emitUsage(record Record) {+ if record.Tokens == nil {+ return+ }+ usage := &schema.GenAIUsageInfo{}+ if record.Tokens.Input > 0 {+ value := record.Tokens.Input+ usage.InputTokens = &value+ }+ if record.Tokens.Output > 0 {+ value := record.Tokens.Output+ usage.OutputTokens = &value+ }+ if record.Tokens.Reasoning > 0 {+ value := record.Tokens.Reasoning+ usage.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: &value}+ }+ if record.Tokens.CacheRead > 0 {+ value := record.Tokens.CacheRead+ usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: &value}+ }+ if record.Tokens.CacheWrite > 0 {+ value := record.Tokens.CacheWrite+ usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: &value}+ }+ if record.Tokens.CostUSD > 0 {+ value := record.Tokens.CostUSD+ usage.CostUSD = &value+ }+ if usage.InputTokens == nil && usage.OutputTokens == nil && usage.Reasoning == nil && usage.CacheRead == nil && usage.CacheCreation == nil && usage.CostUSD == nil {+ return+ }+ ev := m.base(record, "token.usage", "metric", schema.SeverityInfo, "opencode token usage")+ ev.GenAI = &schema.GenAIInfo{Usage: usage}+ m.append(record, "usage", ev)+}++func classifyTool(name string, record Record) (action, category string, severity schema.Severity, message string) {+ lower := strings.ToLower(strings.TrimSpace(name))+ switch {+ case toolNameHasToken(lower, "mcp"):+ return "mcp.tool_invoked", "mcp", schema.SeverityInfo, "opencode MCP tool invoked"+ case toolNameHasToken(lower, "bash") || toolNameHasToken(lower, "shell") || toolNameHasToken(lower, "terminal") || lower == "powershell":+ return "command.executed", "command", schema.SeverityInfo, "opencode command executed"+ case toolNameHasToken(lower, "read") || toolNameHasToken(lower, "view") || toolNameHasToken(lower, "list") || toolNameHasToken(lower, "grep") || toolNameHasToken(lower, "glob"):+ return "file.read", "file", schema.SeverityInfo, "opencode file read"+ case toolNameHasToken(lower, "write") || toolNameHasToken(lower, "create"):+ return "file.created", "file", schema.SeverityInfo, "opencode file created"+ case toolNameHasToken(lower, "edit") || toolNameHasToken(lower, "patch") || lower == "applypatch" || lower == "multiedit":+ return "file.modified", "file", schema.SeverityInfo, "opencode file modified"+ case record.Status == "error":+ return "tool.failed", "tool", schema.SeverityHigh, "opencode tool failed"+ default:+ return "tool.completed", "tool", schema.SeverityInfo, "opencode tool completed"+ }+}++func applyToolCall(ev *schema.Event, name string, record Record) {+ call := &schema.GenAIToolCallInfo{ID: record.CallID}+ if len(record.Args) > 0 {+ call.Arguments = record.Args+ }+ if record.Output != nil && record.Type == "tool_result" {+ call.Result = record.Output+ }+ ev.GenAI = &schema.GenAIInfo{+ Operation: &schema.GenAIOperationInfo{Name: "execute_tool"},+ Tool: &schema.GenAIToolInfo{Name: name, Call: call},+ }+ if path := argString(record.Args, "file_path", "filePath", "path", "target", "destination"); path != "" {+ ev.Tool.Path = path+ }+ if command := argString(record.Args, "command", "cmd"); command != "" {+ ev.Tool.Command = command+ }+}++func applyCommand(ev *schema.Event, record Record) {+ command := ""+ if ev.Tool != nil {+ command = ev.Tool.Command+ }+ info := &schema.CommandInfo{Command: command}+ if out := outputString(record.Output); out != "" {+ info.Output = out+ ev.Content = asymptoteobserve.RetainedContent(out, asymptoteobserve.DefaultStringLimit)+ }+ if metadata := mapFromAny(record.Output); len(metadata) > 0 {+ if inner := mapFromAny(metadata["metadata"]); len(inner) > 0 {+ if code := intFromAny(firstMapValue(inner, "exit", "exit_code", "exitCode", "status")); code != 0 || hasAnyKey(inner, "exit", "exit_code", "exitCode", "status") {+ v := int(code)+ info.ExitCode = &v+ }+ }+ }+ ev.Command = info+}++func applyFile(ev *schema.Event, name string, record Record) {+ path := ""+ if ev.Tool != nil {+ path = ev.Tool.Path+ }+ if path == "" {+ path = argString(record.Args, "file_path", "filePath", "path", "target", "destination")+ }+ operation := "modify"+ action := ev.Event.Action+ switch action {+ case "file.read":+ operation = "read"+ case "file.created":+ operation = "create"+ }+ file := &schema.FileInfo{Path: path, Operation: operation}+ if path != "" {+ file.Language = strings.TrimPrefix(filepath.Ext(path), ".")+ }+ if diff := diffText(name, record); diff != "" {+ file.Diff = diff+ file.DiffBytes = len(diff)+ file.DiffHash = sha256Hex(diff)+ ev.Content = asymptoteobserve.RetainedContent(diff, asymptoteobserve.DefaultStringLimit)+ }+ ev.File = file+}++func diffText(name string, record Record) string {+ if value := argString(record.Args, "diff", "patch"); value != "" {+ return value+ }+ if value := argString(record.Args, "content", "new_string", "newString"); value != "" && classifyFileOperation(name) != "read" {+ return value+ }+ if out := mapFromAny(record.Output); len(out) > 0 {+ if value := stringFromAny(out["diff"]); value != "" {+ return value+ }+ }+ return ""+}++func classifyFileOperation(name string) string {+ lower := strings.ToLower(name)+ switch {+ case toolNameHasToken(lower, "read"), toolNameHasToken(lower, "view"), toolNameHasToken(lower, "list"):+ return "read"+ case toolNameHasToken(lower, "write"), toolNameHasToken(lower, "create"):+ return "create"+ default:+ return "modify"+ }+}++func (m *mapper) append(record Record, suffix string, ev schema.Event) {+ dedupID := fmt.Sprintf("%s:%s:%d:%s:%s", m.ref.Kind, m.ref.ID, record.Order, record.NativeID, suffix)+ ev.Event.ID = opencodeEventID(dedupID)+ m.out = append(m.out, MappedEvent{DedupID: dedupID, SourceOrder: record.Order, Event: ev})+}++var opencodeIDNamespace = [16]byte{+ 0x7d, 0xa2, 0x3e, 0x0c, 0x5b, 0x7a, 0x4f, 0x22,+ 0xa6, 0x5a, 0x31, 0xc2, 0x85, 0xf9, 0x11, 0x6e,+}++func opencodeEventID(dedupID string) string {+ digest := sha1.New()+ digest.Write(opencodeIDNamespace[:])+ io.WriteString(digest, dedupID)+ var id [16]byte+ copy(id[:], digest.Sum(nil))+ id[6] = (id[6] & 0x0f) | 0x50+ id[8] = (id[8] & 0x3f) | 0x80+ out := make([]byte, 32)+ hex.Encode(out, id[:])+ return fmt.Sprintf("%s-%s-%s-%s-%s", out[0:8], out[8:12], out[12:16], out[16:20], out[20:32])+}++func toolNameHasToken(name, token string) bool {+ for _, part := range strings.FieldsFunc(name, func(r rune) bool {+ return !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9')+ }) {+ if part == token {+ return true+ }+ }+ return false+}++func mergeRaw(existing map[string]interface{}, fields map[string]interface{}) map[string]interface{} {+ if len(fields) == 0 {+ return existing+ }+ if existing == nil {+ existing = map[string]interface{}{}+ }+ nested, ok := existing["opencode"].(map[string]interface{})+ if !ok {+ nested = map[string]interface{}{}+ }+ for key, value := range fields {+ nested[key] = value+ }+ existing["opencode"] = nested+ return existing+}++func argString(args map[string]interface{}, keys ...string) string {+ for _, key := range keys {+ if value := stringFromAny(args[key]); value != "" {+ return value+ }+ }+ return ""+}++func outputString(value interface{}) string {+ if s := stringFromAny(value); s != "" {+ return s+ }+ if m := mapFromAny(value); len(m) > 0 {+ if s := stringFromAny(m["output"]); s != "" {+ return s+ }+ data, err := json.Marshal(m)+ if err == nil {+ return string(data)+ }+ }+ return ""+}diff --git a/cli/beacon/internal/opencodesession/mapper_test.go b/cli/beacon/internal/opencodesession/mapper_test.gonew file mode 100644index 00000000..8cc8f1d5--- /dev/null+++ b/cli/beacon/internal/opencodesession/mapper_test.go@@ -0,0 +1,54 @@+package opencodesession++import "testing"++func TestMapTraceMarksPollProvenanceAndClassifiesCommand(t *testing.T) {+ ref := TraceRef{ID: "ses_1", Kind: SourceSQLite, Directory: "/repo", UpdatedAtUnixMS: 1770000000000}+ records := []Record{+ {Order: 1, NativeID: "user", TimestampMS: 1770000000100, Type: "user_message", Content: "run tests"},+ {Order: 2, NativeID: "tool", TimestampMS: 1770000000200, Type: "tool_result", ToolName: "bash", CallID: "call_1", Args: map[string]interface{}{"command": "go test ./..."}, Output: map[string]interface{}{"output": "ok", "metadata": map[string]interface{}{"exit": 0}}, Status: "completed"},+ }+ mapped := MapTrace(ref, records, MapOptions{})+ if len(mapped) != 2 {+ t.Fatalf("mapped = %d, want 2", len(mapped))+ }+ for _, item := range mapped {+ if item.Event.Harness.Name != Harness {+ t.Fatalf("harness = %q", item.Event.Harness.Name)+ }+ if item.Event.Harness.CollectionMethod != "poll" {+ t.Fatalf("collection_method = %q, want poll", item.Event.Harness.CollectionMethod)+ }+ if item.Event.Event.Fidelity != "observed" {+ t.Fatalf("fidelity = %q, want observed", item.Event.Event.Fidelity)+ }+ }+ command := mapped[1].Event+ if command.Event.Action != "command.executed" {+ t.Fatalf("action = %q, want command.executed", command.Event.Action)+ }+ if command.Command == nil || command.Command.Command != "go test ./..." {+ t.Fatalf("command fields = %+v", command.Command)+ }+ if command.GenAI == nil || command.GenAI.Tool == nil || command.GenAI.Tool.Call == nil || command.GenAI.Tool.Call.ID != "call_1" {+ t.Fatalf("gen_ai tool call = %+v", command.GenAI)+ }+ if command.Event.ID == "" || command.Event.ID != MapTrace(ref, records, MapOptions{})[1].Event.Event.ID {+ t.Fatalf("event id was not deterministic: %q", command.Event.ID)+ }+}++func TestMapTraceHonorsMinOrder(t *testing.T) {+ ref := TraceRef{ID: "ses_1", Kind: SourceSQLite}+ records := []Record{+ {Order: 1, NativeID: "one", Type: "user_message", Content: "first"},+ {Order: 2, NativeID: "two", Type: "user_message", Content: "second"},+ }+ mapped := MapTrace(ref, records, MapOptions{MinOrder: 1})+ if len(mapped) != 1 {+ t.Fatalf("mapped = %d, want 1", len(mapped))+ }+ if mapped[0].SourceOrder != 2 {+ t.Fatalf("source order = %d, want 2", mapped[0].SourceOrder)+ }+}diff --git a/cli/beacon/internal/opencodesession/store.go b/cli/beacon/internal/opencodesession/store.gonew file mode 100644index 00000000..4feb2547--- /dev/null+++ b/cli/beacon/internal/opencodesession/store.go@@ -0,0 +1,765 @@+package opencodesession++import (+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "io/fs"+ "net/url"+ "os"+ "path/filepath"+ "runtime"+ "sort"+ "strconv"+ "strings"++ _ "modernc.org/sqlite"+)++const (+ defaultListLimit = 10000+ maxSessionBytes = 1 << 20+)++type Store struct {+ DataDir string+ SQLitePath string+ LegacyStorageDir string+}++func NewStore(dataDir string) (*Store, error) {+ if strings.TrimSpace(dataDir) == "" {+ dataDir = DefaultDataDir()+ }+ if strings.TrimSpace(dataDir) == "" {+ return nil, errors.New("opencode data directory is empty")+ }+ dataDir = filepath.Clean(dataDir)+ if strings.HasSuffix(dataDir, ".db") {+ return &Store{+ DataDir: filepath.Dir(dataDir),+ SQLitePath: dataDir,+ LegacyStorageDir: filepath.Join(filepath.Dir(dataDir), "storage"),+ }, nil+ }+ return &Store{+ DataDir: dataDir,+ SQLitePath: filepath.Join(dataDir, "opencode.db"),+ LegacyStorageDir: filepath.Join(dataDir, "storage"),+ }, nil+}++func DefaultDataDir() string {+ home, err := os.UserHomeDir()+ if err != nil || strings.TrimSpace(home) == "" {+ return ""+ }+ switch runtime.GOOS {+ case "windows":+ if appData := strings.TrimSpace(os.Getenv("APPDATA")); appData != "" {+ return filepath.Join(appData, "opencode")+ }+ return filepath.Join(home, "AppData", "Roaming", "opencode")+ default:+ if xdg := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME")); xdg != "" {+ return filepath.Join(xdg, "opencode")+ }+ return filepath.Join(home, ".config", "opencode")+ }+}++func (s *Store) Exists() bool {+ return fileExists(s.SQLitePath) || dirExists(s.LegacyStorageDir)+}++func (s *Store) List() ([]TraceRef, error) {+ var refs []TraceRef+ var errs []error+ sqliteRefs, err := s.listSQLite()+ if err != nil {+ errs = append(errs, err)+ }+ refs = append(refs, sqliteRefs...)+ seen := make(map[string]bool, len(sqliteRefs))+ for _, ref := range sqliteRefs {+ seen[ref.ID] = true+ }+ legacyRefs, err := s.listLegacy()+ if err != nil {+ errs = append(errs, err)+ }+ for _, ref := range legacyRefs {+ if seen[ref.ID] {+ continue+ }+ refs = append(refs, ref)+ }+ sort.SliceStable(refs, func(i, j int) bool {+ if refs[i].UpdatedAtUnixMS != refs[j].UpdatedAtUnixMS {+ return refs[i].UpdatedAtUnixMS < refs[j].UpdatedAtUnixMS+ }+ return refs[i].ID < refs[j].ID+ })+ return refs, errors.Join(errs...)+}++func (s *Store) Read(ref TraceRef) ([]Record, error) {+ switch ref.Kind {+ case SourceSQLite:+ return s.readSQLite(ref)+ case SourceLegacy:+ return s.readLegacy(ref)+ default:+ return nil, fmt.Errorf("unknown opencode source kind %q", ref.Kind)+ }+}++func (s *Store) listSQLite() ([]TraceRef, error) {+ if !fileExists(s.SQLitePath) {+ return nil, nil+ }+ db, err := openSQLiteReadOnly(s.SQLitePath)+ if err != nil {+ return nil, fmt.Errorf("open OpenCode sqlite: %w", err)+ }+ defer db.Close()+ if !sqliteTableExists(db, "session") {+ return nil, nil+ }+ cols := sqliteColumns(db, "session")+ selects := []string{+ sqliteSelectColumn(cols, "id"),+ sqliteSelectColumn(cols, "title"),+ sqliteSelectColumn(cols, "directory"),+ sqliteSelectColumn(cols, "project_worktree"),+ sqliteSelectColumn(cols, "time_created"),+ 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)+ if err != nil {+ return nil, fmt.Errorf("read OpenCode sessions: %w", err)+ }+ defer rows.Close()+ var refs []TraceRef+ for rows.Next() {+ var id, title, directory, worktree, parent sql.NullString+ var created, updated sql.NullInt64+ if err := rows.Scan(&id, &title, &directory, &worktree, &created, &updated, &parent); err != nil {+ continue+ }+ if !id.Valid || strings.TrimSpace(id.String) == "" {+ continue+ }+ dir := firstNonEmpty(nullString(directory), nullString(worktree))+ ref := TraceRef{+ ID: id.String,+ Kind: SourceSQLite,+ SourcePath: s.SQLitePath,+ Title: firstNonEmpty(nullString(title), "Untitled Session"),+ Preview: firstNonEmpty(nullString(title), "(No preview)"),+ Directory: dir,+ CreatedAtUnixMS: normalizeMillis(nullInt(created)),+ UpdatedAtUnixMS: normalizeMillis(firstNonZero(nullInt(updated), nullInt(created))),+ }+ if parent.Valid && parent.String != "" {+ ref.RelatedTo = parent.String+ ref.RelationshipType = "subagent"+ }+ if info, err := os.Stat(s.SQLitePath); err == nil {+ ref.SizeBytes = info.Size()+ }+ refs = append(refs, ref)+ }+ return refs, rows.Err()+}++func (s *Store) readSQLite(ref TraceRef) ([]Record, error) {+ db, err := openSQLiteReadOnly(s.SQLitePath)+ if err != nil {+ 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+ }+ parts, err := readSQLiteParts(db, ref.ID)+ if err != nil {+ return nil, err+ }+ return recordsFromMessages(messages, parts), nil+}++func readSQLiteMessages(db *sql.DB, sessionID string) ([]opencodeMessage, error) {+ cols := sqliteColumns(db, "message")+ rows, err := db.Query("SELECT "+strings.Join([]string{+ sqliteSelectColumn(cols, "id"),+ sqliteSelectColumn(cols, "session_id"),+ sqliteSelectColumn(cols, "time_created"),+ sqliteSelectColumn(cols, "data"),+ }, ", ")+" FROM message WHERE session_id = ? ORDER BY COALESCE(time_created, 0), id", sessionID)+ if err != nil {+ return nil, fmt.Errorf("read OpenCode messages: %w", err)+ }+ defer rows.Close()+ var out []opencodeMessage+ for rows.Next() {+ var id, sid, data sql.NullString+ var created sql.NullInt64+ if err := rows.Scan(&id, &sid, &created, &data); err != nil {+ continue+ }+ msg := parseMessageJSON(nullString(data))+ msg.ID = firstNonEmpty(msg.ID, nullString(id))+ msg.SessionID = firstNonEmpty(msg.SessionID, nullString(sid), sessionID)+ if msg.Time.Created == 0 {+ msg.Time.Created = normalizeMillis(nullInt(created))+ }+ out = append(out, msg)+ }+ return out, rows.Err()+}++func readSQLiteParts(db *sql.DB, sessionID string) (map[string][]opencodePart, error) {+ cols := sqliteColumns(db, "part")+ rows, err := db.Query("SELECT "+strings.Join([]string{+ sqliteSelectColumn(cols, "id"),+ sqliteSelectColumn(cols, "message_id"),+ sqliteSelectColumn(cols, "session_id"),+ sqliteSelectColumn(cols, "time_created"),+ sqliteSelectColumn(cols, "data"),+ }, ", ")+" FROM part WHERE session_id = ? ORDER BY COALESCE(time_created, 0), id", sessionID)+ if err != nil {+ return nil, fmt.Errorf("read OpenCode parts: %w", err)+ }+ defer rows.Close()+ out := map[string][]opencodePart{}+ for rows.Next() {+ var id, messageID, sid, data sql.NullString+ var created sql.NullInt64+ if err := rows.Scan(&id, &messageID, &sid, &created, &data); err != nil {+ continue+ }+ part := parsePartJSON(nullString(data))+ part.ID = firstNonEmpty(part.ID, nullString(id))+ part.MessageID = firstNonEmpty(part.MessageID, nullString(messageID))+ part.SessionID = firstNonEmpty(part.SessionID, nullString(sid), sessionID)+ part.TimeCreated = normalizeMillis(nullInt(created))+ out[part.MessageID] = append(out[part.MessageID], part)+ }+ return out, rows.Err()+}++func (s *Store) listLegacy() ([]TraceRef, error) {+ sessionRoot := filepath.Join(s.LegacyStorageDir, "session")+ if !dirExists(sessionRoot) {+ return nil, nil+ }+ projects, err := os.ReadDir(sessionRoot)+ if err != nil {+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ return nil, fmt.Errorf("read OpenCode legacy sessions: %w", err)+ }+ var refs []TraceRef+ for _, project := range projects {+ if !project.IsDir() {+ continue+ }+ projectID := project.Name()+ projectDir := legacyProjectDirectory(filepath.Join(s.LegacyStorageDir, "project", projectID+".json"))+ sessionDir := filepath.Join(sessionRoot, projectID)+ files, err := os.ReadDir(sessionDir)+ if err != nil {+ continue+ }+ for _, file := range files {+ if file.IsDir() || !strings.HasSuffix(file.Name(), ".json") {+ continue+ }+ path := filepath.Join(sessionDir, file.Name())+ ref, ok := readLegacySessionRef(path, projectDir)+ if ok {+ refs = append(refs, ref)+ }+ }+ }+ return refs, nil+}++func (s *Store) readLegacy(ref TraceRef) ([]Record, error) {+ session := readLegacySession(ref.SourcePath)+ if session.ID == "" {+ return nil, fmt.Errorf("read OpenCode legacy session %s", ref.SourcePath)+ }+ messageDir := filepath.Join(s.LegacyStorageDir, "message", session.ID)+ files, err := os.ReadDir(messageDir)+ if err != nil {+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ return nil, err+ }+ var messages []opencodeMessage+ for _, file := range files {+ if file.IsDir() || !strings.HasSuffix(file.Name(), ".json") {+ continue+ }+ msg := readLegacyMessage(filepath.Join(messageDir, file.Name()))+ if msg.ID != "" {+ messages = append(messages, msg)+ }+ }+ sort.SliceStable(messages, func(i, j int) bool {+ if messages[i].Time.Created != messages[j].Time.Created {+ return messages[i].Time.Created < messages[j].Time.Created+ }+ return messages[i].ID < messages[j].ID+ })+ parts := map[string][]opencodePart{}+ for _, msg := range messages {+ partDir := filepath.Join(s.LegacyStorageDir, "part", msg.ID)+ partFiles, err := os.ReadDir(partDir)+ if err != nil {+ continue+ }+ sort.SliceStable(partFiles, func(i, j int) bool { return naturalLess(partFiles[i].Name(), partFiles[j].Name()) })+ for _, file := range partFiles {+ if file.IsDir() || !strings.HasSuffix(file.Name(), ".json") {+ continue+ }+ part := readLegacyPart(filepath.Join(partDir, file.Name()))+ if part.ID != "" {+ part.MessageID = firstNonEmpty(part.MessageID, msg.ID)+ parts[msg.ID] = append(parts[msg.ID], part)+ }+ }+ }+ return recordsFromMessages(messages, parts), nil+}++type opencodeMessage struct {+ ID string+ SessionID string+ Role string+ ModelID string+ Summary bool+ ParentID string+ Error map[string]interface{}+ Time struct {+ Created int64+ Completed int64+ }+ Tokens TokenUsage+ Cost float64+ Raw map[string]interface{}+}++type opencodePart struct {+ ID string+ SessionID string+ MessageID string+ Type string+ Text string+ Tool string+ CallID string+ State map[string]interface{}+ TimeCreated int64+ Raw map[string]interface{}+}++func recordsFromMessages(messages []opencodeMessage, parts map[string][]opencodePart) []Record {+ var records []Record+ order := 1+ for _, msg := range messages {+ if msg.Role == "assistant" && msg.Summary {+ continue+ }+ msgParts := parts[msg.ID]+ for _, part := range msgParts {+ rec, ok := recordFromPart(msg, part, order)+ if !ok {+ continue+ }+ records = append(records, rec)+ order+++ }+ if msg.Role == "assistant" && hasUsage(msg.Tokens) {+ records = append(records, Record{+ Order: order,+ NativeID: msg.ID + ":usage",+ TimestampMS: firstNonZero(msg.Time.Completed, msg.Time.Created),+ Type: "token_usage",+ ModelID: msg.ModelID,+ Tokens: &msg.Tokens,+ })+ order+++ }+ if len(msgParts) == 0 && len(msg.Error) > 0 {+ records = append(records, Record{+ Order: order,+ NativeID: msg.ID + ":error",+ TimestampMS: firstNonZero(msg.Time.Completed, msg.Time.Created),+ Type: "error",+ Content: stringFromMap(msg.Error, "message", "name", "type"),+ ModelID: msg.ModelID,+ Raw: map[string]interface{}{"message": msg.Raw},+ })+ order+++ }+ }+ return records+}++func recordFromPart(msg opencodeMessage, part opencodePart, order int) (Record, bool) {+ timestamp := firstNonZero(partTimestamp(part), msg.Time.Created)+ nativeID := firstNonEmpty(msg.ID+":"+part.ID, strconv.Itoa(order))+ switch part.Type {+ case "text", "file":+ if strings.TrimSpace(part.Text) == "" {+ return Record{}, false+ }+ recType := "assistant_text"+ if msg.Role == "user" {+ recType = "user_message"+ }+ return Record{Order: order, NativeID: nativeID, TimestampMS: timestamp, Type: recType, Role: msg.Role, Content: part.Text, ModelID: msg.ModelID, Raw: map[string]interface{}{"part": part.Raw}}, true+ case "reasoning":+ if strings.TrimSpace(part.Text) == "" {+ return Record{}, false+ }+ return Record{Order: order, NativeID: nativeID, TimestampMS: timestamp, Type: "agent_reasoning", Role: msg.Role, Content: part.Text, ModelID: msg.ModelID, Raw: map[string]interface{}{"part": part.Raw}}, true+ case "tool":+ return toolRecord(msg, part, order, nativeID, timestamp)+ case "compaction":+ return Record{Order: order, NativeID: nativeID, TimestampMS: timestamp, Type: "compaction", ModelID: msg.ModelID, Raw: map[string]interface{}{"part": part.Raw}}, true+ default:+ return Record{}, false+ }+}++func toolRecord(msg opencodeMessage, part opencodePart, order int, nativeID string, timestamp int64) (Record, bool) {+ state := part.State+ if len(state) == 0 {+ return Record{}, false+ }+ args := mapFromAny(state["input"])+ status := stringFromAny(state["status"])+ if status == "" {+ status = "invoked"+ }+ recType := "tool_result"+ if status != "completed" && status != "error" {+ recType = "tool_call"+ }+ out := state["output"]+ if out == nil {+ out = state["result"]+ }+ if metadata := mapFromAny(state["metadata"]); len(metadata) > 0 {+ out = map[string]interface{}{"output": out, "metadata": metadata}+ }+ ts := timestamp+ if timeMap := mapFromAny(state["time"]); status == "completed" || status == "error" {+ if end := intFromAny(timeMap["end"]); end > 0 {+ ts = normalizeMillis(end)+ }+ } else if timeMap := mapFromAny(state["time"]); len(timeMap) > 0 {+ if start := intFromAny(timeMap["start"]); start > 0 {+ ts = normalizeMillis(start)+ }+ }+ raw := map[string]interface{}{"part": part.Raw}+ if errText := stringFromAny(state["error"]); errText != "" {+ raw["error"] = errText+ }+ return Record{+ Order: order,+ NativeID: nativeID,+ TimestampMS: ts,+ Type: recType,+ ModelID: msg.ModelID,+ ToolName: part.Tool,+ CallID: firstNonEmpty(part.CallID, part.ID),+ Args: args,+ Output: out,+ Status: status,+ Raw: raw,+ }, true+}++func parseMessageJSON(data string) opencodeMessage {+ var raw map[string]interface{}+ _ = json.Unmarshal([]byte(data), &raw)+ return messageFromMap(raw)+}++func messageFromMap(raw map[string]interface{}) opencodeMessage {+ msg := opencodeMessage{Raw: raw}+ if raw == nil {+ return msg+ }+ msg.ID = stringFromMap(raw, "id")+ msg.SessionID = stringFromMap(raw, "sessionID", "session_id")+ msg.Role = stringFromMap(raw, "role")+ msg.ModelID = opencodeModel(raw)+ msg.Summary = boolFromAny(raw["summary"])+ msg.ParentID = stringFromMap(raw, "parentID", "parent_id")+ msg.Error = mapFromAny(raw["error"])+ timeMap := mapFromAny(raw["time"])+ msg.Time.Created = normalizeMillis(intFromAny(timeMap["created"]))+ msg.Time.Completed = normalizeMillis(intFromAny(timeMap["completed"]))+ msg.Tokens = tokenUsageFromAny(raw["tokens"])+ if cost := floatFromAny(raw["cost"]); cost > 0 {+ msg.Tokens.CostUSD = cost+ msg.Cost = cost+ }+ return msg+}++func parsePartJSON(data string) opencodePart {+ var raw map[string]interface{}+ _ = json.Unmarshal([]byte(data), &raw)+ return partFromMap(raw)+}++func partFromMap(raw map[string]interface{}) opencodePart {+ part := opencodePart{Raw: raw}+ if raw == nil {+ return part+ }+ part.ID = stringFromMap(raw, "id")+ part.SessionID = stringFromMap(raw, "sessionID", "session_id")+ part.MessageID = stringFromMap(raw, "messageID", "message_id")+ part.Type = stringFromMap(raw, "type")+ part.Text = stringFromMap(raw, "text")+ part.Tool = stringFromMap(raw, "tool")+ part.CallID = stringFromMap(raw, "callID", "call_id")+ part.State = mapFromAny(raw["state"])+ timeMap := mapFromAny(raw["time"])+ part.TimeCreated = normalizeMillis(firstNonZero(intFromAny(timeMap["start"]), intFromAny(timeMap["created"])))+ return part+}++func readLegacySessionRef(path, projectDir string) (TraceRef, bool) {+ info, err := os.Stat(path)+ if err != nil || info.IsDir() || info.Size() > maxSessionBytes {+ return TraceRef{}, false+ }+ session := readLegacySession(path)+ if session.ID == "" {+ return TraceRef{}, false+ }+ if timeMap := mapFromAny(session.Raw["time"]); boolFromAny(timeMap["archived"]) {+ return TraceRef{}, false+ }+ created := firstNonZero(session.Time.Created, info.ModTime().UnixMilli())+ updated := firstNonZero(session.Time.Completed, intFromAny(mapFromAny(session.Raw["time"])["updated"]), created)+ ref := TraceRef{+ ID: session.ID,+ Kind: SourceLegacy,+ SourcePath: path,+ Title: firstNonEmpty(stringFromMap(session.Raw, "title"), "Untitled Session"),+ Preview: firstNonEmpty(stringFromMap(session.Raw, "title"), "(No preview)"),+ Directory: firstNonEmpty(projectDir, stringFromMap(session.Raw, "directory")),+ CreatedAtUnixMS: normalizeMillis(created),+ UpdatedAtUnixMS: normalizeMillis(updated),+ SizeBytes: info.Size(),+ }+ if parent := stringFromMap(session.Raw, "parentID", "parent_id"); parent != "" {+ ref.RelatedTo = parent+ ref.RelationshipType = "subagent"+ }+ return ref, true+}++func readLegacySession(path string) opencodeMessage {+ data, err := os.ReadFile(path)+ if err != nil {+ return opencodeMessage{}+ }+ var raw map[string]interface{}+ if err := json.Unmarshal(data, &raw); err != nil {+ return opencodeMessage{}+ }+ msg := messageFromMap(raw)+ msg.ID = firstNonEmpty(msg.ID, strings.TrimSuffix(filepath.Base(path), ".json"))+ return msg+}++func readLegacyMessage(path string) opencodeMessage {+ data, err := os.ReadFile(path)+ if err != nil {+ return opencodeMessage{}+ }+ var raw map[string]interface{}+ if err := json.Unmarshal(data, &raw); err != nil {+ return opencodeMessage{}+ }+ msg := messageFromMap(raw)+ msg.ID = firstNonEmpty(msg.ID, strings.TrimSuffix(filepath.Base(path), ".json"))+ return msg+}++func readLegacyPart(path string) opencodePart {+ data, err := os.ReadFile(path)+ if err != nil {+ return opencodePart{}+ }+ var raw map[string]interface{}+ if err := json.Unmarshal(data, &raw); err != nil {+ return opencodePart{}+ }+ part := partFromMap(raw)+ part.ID = firstNonEmpty(part.ID, strings.TrimSuffix(filepath.Base(path), ".json"))+ return part+}++func legacyProjectDirectory(path string) string {+ data, err := os.ReadFile(path)+ if err != nil {+ return ""+ }+ var raw map[string]interface{}+ if err := json.Unmarshal(data, &raw); err != nil {+ return ""+ }+ return firstNonEmpty(stringFromMap(raw, "worktree"), stringFromMap(raw, "directory"), stringFromMap(raw, "name"))+}++func openSQLiteReadOnly(path string) (*sql.DB, error) {+ u := url.URL{Scheme: "file", Path: path}+ q := u.Query()+ q.Set("mode", "ro")+ q.Set("_pragma", "query_only(1)")+ u.RawQuery = q.Encode()+ return sql.Open("sqlite", u.String())+}++func sqliteTableExists(db *sql.DB, table string) bool {+ var name string+ err := db.QueryRow(`SELECT name FROM sqlite_master WHERE type='table' AND name = ?`, table).Scan(&name)+ return err == nil+}++func sqliteColumns(db *sql.DB, table string) map[string]bool {+ rows, err := db.Query("PRAGMA table_info(" + table + ")")+ if err != nil {+ return nil+ }+ defer rows.Close()+ cols := map[string]bool{}+ for rows.Next() {+ var cid int+ var name, typ string+ var notnull int+ var dflt interface{}+ var pk int+ if err := rows.Scan(&cid, &name, &typ, ¬null, &dflt, &pk); err == nil {+ cols[name] = true+ }+ }+ return cols+}++func sqliteSelectColumn(cols map[string]bool, name string) string {+ if cols[name] {+ return name+ }+ return "NULL AS " + name+}++func fileExists(path string) bool {+ info, err := os.Stat(path)+ return err == nil && info.Mode().IsRegular()+}++func dirExists(path string) bool {+ info, err := os.Stat(path)+ return err == nil && info.IsDir()+}++func nullString(value sql.NullString) string {+ if value.Valid {+ return value.String+ }+ return ""+}++func nullInt(value sql.NullInt64) int64 {+ if value.Valid {+ return value.Int64+ }+ return 0+}++func normalizeMillis(value int64) int64 {+ if value > 0 && value < 1000000000000 {+ return value * 1000+ }+ return value+}++func firstNonZero(values ...int64) int64 {+ for _, value := range values {+ if value != 0 {+ return value+ }+ }+ return 0+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if strings.TrimSpace(value) != "" {+ return value+ }+ }+ return ""+}++func naturalLess(a, b string) bool {+ ai := firstNumber(a)+ bi := firstNumber(b)+ if ai != bi {+ return ai < bi+ }+ return a < b+}++func firstNumber(value string) int {+ start := -1+ for i, r := range value {+ if r >= '0' && r <= '9' {+ if start < 0 {+ start = i+ }+ continue+ }+ if start >= 0 {+ n, _ := strconv.Atoi(value[start:i])+ return n+ }+ }+ if start >= 0 {+ n, _ := strconv.Atoi(value[start:])+ return n+ }+ return 0+}++func partTimestamp(part opencodePart) int64 {+ if part.TimeCreated > 0 {+ return part.TimeCreated+ }+ if timeMap := mapFromAny(part.Raw["time"]); len(timeMap) > 0 {+ return normalizeMillis(firstNonZero(intFromAny(timeMap["start"]), intFromAny(timeMap["created"])))+ }+ return 0+}diff --git a/cli/beacon/internal/opencodesession/store_test.go b/cli/beacon/internal/opencodesession/store_test.gonew file mode 100644index 00000000..f7ad52a1--- /dev/null+++ b/cli/beacon/internal/opencodesession/store_test.go@@ -0,0 +1,106 @@+package opencodesession++import (+ "database/sql"+ "encoding/json"+ "path/filepath"+ "testing"++ _ "modernc.org/sqlite"+)++func TestSQLiteStoreReadsMessagesPartsAndTokenUsage(t *testing.T) {+ dbPath := filepath.Join(t.TempDir(), "opencode.db")+ db, err := sql.Open("sqlite", dbPath)+ if err != nil {+ t.Fatal(err)+ }+ defer db.Close()+ mustExec(t, db, `CREATE TABLE session (+ id TEXT PRIMARY KEY,+ title TEXT,+ directory TEXT,+ time_created INTEGER,+ time_updated INTEGER+ )`)+ mustExec(t, db, `CREATE TABLE message (+ id TEXT PRIMARY KEY,+ session_id TEXT,+ time_created INTEGER,+ data TEXT+ )`)+ mustExec(t, db, `CREATE TABLE part (+ id TEXT PRIMARY KEY,+ message_id TEXT,+ session_id TEXT,+ time_created INTEGER,+ data TEXT+ )`)+ mustExec(t, db, `INSERT INTO session (id, title, directory, time_created, time_updated) VALUES ('ses_1', 'Fix tests', '/repo', 1770000000000, 1770000002000)`)+ insertJSON(t, db, `INSERT INTO message (id, session_id, time_created, data) VALUES (?, ?, ?, ?)`, "msg_user", "ses_1", 1770000000100, map[string]interface{}{+ "id": "msg_user", "role": "user", "time": map[string]interface{}{"created": 1770000000100},+ })+ insertJSON(t, db, `INSERT INTO part (id, message_id, session_id, time_created, data) VALUES (?, ?, ?, ?, ?)`, "part_user", "msg_user", "ses_1", 1770000000100, map[string]interface{}{+ "id": "part_user", "type": "text", "text": "please run tests",+ })+ insertJSON(t, db, `INSERT INTO message (id, session_id, time_created, data) VALUES (?, ?, ?, ?)`, "msg_assistant", "ses_1", 1770000000200, map[string]interface{}{+ "id": "msg_assistant", "role": "assistant", "modelID": "claude-sonnet-4-5", "time": map[string]interface{}{"created": 1770000000200},+ "tokens": map[string]interface{}{"input": 100, "output": 20, "reasoning": 3, "cache": map[string]interface{}{"read": 7, "write": 5}},+ "cost": 0.01,+ })+ insertJSON(t, db, `INSERT INTO part (id, message_id, session_id, time_created, data) VALUES (?, ?, ?, ?, ?)`, "part_tool", "msg_assistant", "ses_1", 1770000000300, map[string]interface{}{+ "id": "part_tool", "type": "tool", "tool": "bash", "callID": "call_1",+ "state": map[string]interface{}{+ "status": "completed",+ "input": map[string]interface{}{"command": "go test ./..."},+ "output": map[string]interface{}{"output": "ok"},+ "time": map[string]interface{}{"start": 1770000000300, "end": 1770000000400},+ "metadata": map[string]interface{}{+ "exit": 0,+ },+ },+ })++ store, err := NewStore(filepath.Dir(dbPath))+ if err != nil {+ t.Fatal(err)+ }+ refs, err := store.List()+ if err != nil {+ t.Fatal(err)+ }+ if len(refs) != 1 {+ t.Fatalf("refs = %d, want 1", len(refs))+ }+ if refs[0].ID != "ses_1" || refs[0].Directory != "/repo" || refs[0].Kind != SourceSQLite {+ t.Fatalf("ref = %+v", refs[0])+ }+ records, err := store.Read(refs[0])+ if err != nil {+ t.Fatal(err)+ }+ if len(records) != 3 {+ t.Fatalf("records = %d, want prompt, tool, usage", len(records))+ }+ if records[0].Type != "user_message" || records[1].Type != "tool_result" || records[2].Type != "token_usage" {+ t.Fatalf("record types = %s, %s, %s", records[0].Type, records[1].Type, records[2].Type)+ }+}++func mustExec(t *testing.T, db *sql.DB, query string, args ...interface{}) {+ t.Helper()+ if _, err := db.Exec(query, args...); err != nil {+ t.Fatal(err)+ }+}++func insertJSON(t *testing.T, db *sql.DB, query string, args ...interface{}) {+ t.Helper()+ last := len(args) - 1+ data, err := json.Marshal(args[last])+ if err != nil {+ t.Fatal(err)+ }+ args[last] = string(data)+ mustExec(t, db, query, args...)+}diff --git a/cli/beacon/internal/opencodesession/types.go b/cli/beacon/internal/opencodesession/types.gonew file mode 100644index 00000000..9e6733f2--- /dev/null+++ b/cli/beacon/internal/opencodesession/types.go@@ -0,0 +1,51 @@+package opencodesession++type SourceKind string++const (+ SourceSQLite SourceKind = "sqlite"+ SourceLegacy SourceKind = "legacy"+)++type TraceRef struct {+ ID string+ Kind SourceKind+ SourcePath string+ Title string+ Preview string+ Directory string+ UpdatedAtUnixMS int64+ CreatedAtUnixMS int64+ SizeBytes int64+ RelatedTo string+ RelationshipType string+}++type Record struct {+ Order int+ NativeID string+ TimestampMS int64+ Type string++ Role string+ Content string+ ModelID string++ ToolName string+ CallID string+ Args map[string]interface{}+ Output interface{}+ Status string++ Tokens *TokenUsage+ Raw map[string]interface{}+}++type TokenUsage struct {+ Input int64+ Output int64+ Reasoning int64+ CacheRead int64+ CacheWrite int64+ CostUSD float64+}diff --git a/docs/cli/endpoint-opencode.mdx b/docs/cli/endpoint-opencode.mdxnew file mode 100644index 00000000..af9e00f3--- /dev/null+++ b/docs/cli/endpoint-opencode.mdx@@ -0,0 +1,83 @@+---+title: "beacon endpoint opencode"+description: "Collect endpoint telemetry from OpenCode session records"+---++## Command overview++`beacon endpoint opencode` supplements the live [OpenCode](/runtimes/opencode) plugin by reading OpenCode's committed local session store and converting those records into Beacon [endpoint events](/concepts/core-concepts#endpoint-event).++```bash title="Command syntax"+beacon endpoint opencode [command]+```++Beacon reads `opencode.db` when present and falls back to OpenCode's legacy `storage/session`, `storage/message`, `storage/part`, and `storage/project` tree. This path is useful for historical sessions and sessions that ran before Beacon's OpenCode plugin was installed or loaded.++Every event is marked `harness.collection_method=poll`. Beacon sees what OpenCode already wrote, so nothing here can hold or deny a tool call. Keep the managed plugin installed when you need live approval telemetry and richer hook timing.++Reading is local and offline. Nothing this command does reaches the network.++## Commands++| Command | Description |+|---------|-------------|+| `beacon endpoint opencode sync` | Read new OpenCode session records into the runtime log |+| `beacon endpoint opencode status` | Show OpenCode local sessions and how much has been collected |++## Flags++Both subcommands accept:++| Flag | Description |+|------|-------------|+| `--data-dir <path>` | OpenCode data directory or `opencode.db` path. Defaults to `~/.config/opencode` |+| `--state <path>` | Collector cursor file. Defaults to `~/.beacon/endpoint/state/opencode-sessions.json` |+| `--json` | Print the result as JSON |+| `--user` | Use per-user endpoint paths. Enabled by default |+| `--system` | Use system endpoint paths |++`sync` also accepts:++| Flag | Description |+|------|-------------|+| `--log-path <path>` | Runtime JSONL log path. Defaults to the resolved endpoint log |+| `--print` | Print mapped events as JSON without writing them or advancing the cursor |+| `--watch` | Sweep continuously on `--interval` instead of sweeping once and exiting |+| `--interval <duration>` | Sweep interval for `--watch`. Defaults to `1m`, with a 5-second floor |++## Sweeping++```bash title="Sweep once"+beacon endpoint opencode sync+```++```bash title="Preview without writing anything"+beacon endpoint opencode sync --print+```++`--print` is a dry run in both directions: it neither writes the runtime log nor advances the cursor.++```bash title="Sweep continuously"+beacon endpoint opencode sync --watch --interval 5m+```++Nothing sweeps on its own. Run `sync` under whatever scheduler the platform already uses, or leave `--watch` running in the user context that owns OpenCode's data directory.++## Status++```bash title="Show OpenCode sessions and collection progress"+beacon endpoint opencode status+```++`collected` means the cursor is level with the records Beacon read from that OpenCode session source. SQLite-backed sessions and legacy JSON sessions are tracked separately so upgrading OpenCode's storage format does not confuse the cursor.++## Related++<Columns cols={2}>+ <Card title="OpenCode" icon="code" href="/runtimes/opencode">+ Telemetry coverage, plugin setup, and known gaps for the runtime.+ </Card>+ <Card title="Hooks" icon="plug" href="/cli/hooks">+ Install the live OpenCode plugin for hook-time telemetry.+ </Card>+</Columns>diff --git a/docs/runtimes/opencode.mdx b/docs/runtimes/opencode.mdxindex 9e10da26..6dc2910a 100644--- a/docs/runtimes/opencode.mdx+++ b/docs/runtimes/opencode.mdx@@ -7,6 +7,10 @@ description: "Asymptote support details for OpenCode endpoint telemetry"Asymptote supports OpenCode through a managed local plugin that invokes `beacon-hooks`.+Beacon can also read OpenCode's committed local session store with `beacon endpoint opencode sync`.+That poll path backfills historical or uninstrumented sessions, while the managed plugin remains the+live path for hook-time events and approval telemetry.+## PrerequisitesBefore enabling OpenCode telemetry, make sure:@@ -22,11 +26,14 @@ Asymptote installs an owned OpenCode plugin at `~/.config/opencode/plugins/beacoThe 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.+## Discovery and statusAsymptote detects OpenCode through the `opencode` executable or `~/.config/opencode`, then checks for Asymptote plugin configuration.Use `beacon endpoint hooks status --harness opencode` to inspect OpenCode plugin status.+Use `beacon endpoint opencode status` to inspect persisted session-store collection progress.## Install or configuration support@@ -36,19 +43,23 @@ Use `beacon endpoint hooks status --harness opencode` to inspect OpenCode pluginbeacon endpoint hooks install --harness opencode```+```bash title="Backfill committed local sessions"+beacon endpoint opencode sync+```+## Telemetry coverage| Area | Support ||------|---------|| Prompt telemetry | Supported through `chat.message` hooks |-| Assistant output and reasoning | Completed text and reasoning parts, correlated by session/message/part IDs |+| Assistant output and reasoning | Completed text and reasoning parts, correlated by session/message/part IDs; committed text and reasoning can also be recovered from the session store || Tool lifecycle | Invocation, completion, result, duration, and failure using `tool.execute.before`, `tool.execute.after`, and terminal tool parts || Command telemetry | Model-invoked Bash/shell tools plus successful OpenCode custom commands || File telemetry | Read/search/glob and write/edit/patch activity with agent-derived paths; empty session diffs are ignored || Web and MCP telemetry | Web tool arguments/results and normalized MCP server/tool/resource context |-| Approval telemetry | Requests plus `once`, `always`, and `reject` replies, normalized as requested, allowed, and denied |-| Model and usage | Provider/model, finish reason, token usage, cache usage, reasoning tokens, and runtime-reported cost |-| Session telemetry | Create, busy/idle/end, retry, and error boundaries |+| Approval telemetry | Requests plus `once`, `always`, and `reject` replies from the live plugin, normalized as requested, allowed, and denied. Approval telemetry is not recovered from the session-store poll path |+| Model and usage | Provider/model, finish reason, token usage, cache usage, reasoning tokens, and runtime-reported cost where OpenCode reports them |+| Session telemetry | Live create, busy/idle/end, retry, and error boundaries through the plugin; persisted sessions can be backfilled through `beacon endpoint opencode sync` || Local JSONL and dashboard | Supported || MDM deployment | Supported for the endpoint agent. OpenCode plugins are installed separately in the logged-in user's context |@@ -56,7 +67,7 @@ beacon endpoint hooks install --harness opencodeOpenCode prompts, completed assistant text and reasoning, tool arguments and results, commands, command output, paths, and diffs are retained in local or customer-controlled logs. Beacon applies local secret redaction and per-string limits before writing. Each content-bearing event includes a hash and byte count for the original value. Events over the 64 KiB limit drop raw and retained content, preserve stable metadata, and set `field_truncated`.-The plugin uses OpenCode session, message, part, permission request, and tool call identifiers for correlation. It does not create file events without an agent-derived path, so object-storage ingestion paths are not treated as files the agent touched.+The plugin uses OpenCode session, message, part, permission request, and tool call identifiers for correlation. The poll path uses OpenCode's persisted session, message, part, and tool call identifiers. It does not create file events without an agent-derived path, so object-storage ingestion paths are not treated as files the agent touched.## Deployment notes@@ -64,6 +75,8 @@ Restart OpenCode after installing or removing hooks so new sessions pick up theFor local troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment that launches OpenCode to emit best-effort plugin debug logs. The adapter has a bounded local subprocess timeout and remains fail-open, so telemetry failures do not interrupt OpenCode execution.+For historical collection or deployments where OpenCode did not load the plugin, run `beacon endpoint opencode sync --print` to preview mapped events, then `beacon endpoint opencode sync` to append them to the runtime log. Use `--watch` or a scheduler if you want the poll path to stay current.+Validate a system-mode installation after restarting OpenCode:```bash@@ -74,11 +87,14 @@ Validate a system-mode installation after restarting OpenCode:## Related-<Columns cols={2}>+<Columns cols={3}><Card title="Supported agent harnesses" icon="list-check" href="/runtimes">Return to the runtime support overview.</Card><Card title="Hooks" icon="plug" href="/cli/hooks">Install, inspect, and uninstall runtime hook integrations.</Card>+ <Card title="beacon endpoint opencode" icon="rotate" href="/cli/endpoint-opencode">+ Backfill OpenCode sessions from the local session store.+ </Card></Columns>