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 plugin support
Justin D'Souza06e5c4a751e8
diff --git a/README.md b/README.mdindex 481cfc04..450be083 100644--- a/README.md+++ b/README.md@@ -34,7 +34,7 @@ Beacon is Asymptote's open-source endpoint agent for security and IT teams thatneed visibility into local AI agent activity.It runs locally, captures supported activity from local agent harnesses like-Claude Code, Codex CLI, Factory Droid, Claude Cowork, and Cursor, then+Claude Code, Codex CLI, opencode, Factory Droid, Claude Cowork, and Cursor, thennormalizes that activity into endpoint events your team can inspect and retainlocally.diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.goindex 590450b5..b41320ee 100644--- a/cli/beacon-hooks/cmd/helpers.go+++ b/cli/beacon-hooks/cmd/helpers.go@@ -51,6 +51,8 @@ func resolveSessionID(input map[string]interface{}, platform string) string {return getFirstStr(input, "sessionId", "session_id")case "cursor":return getFirstStr(input, "conversation_id")+ case "opencode":+ return getFirstStr(input, "session_id", "sessionID")default:id, _ := input["session_id"].(string)return id@@ -72,6 +74,9 @@ func resolveSessionIDWithTranscript(input map[string]interface{}, platform strinsessionID = getFirstStr(input, "conversation_id")transcriptPath = getFirstStr(input, "transcript_path")return+ case "opencode":+ sessionID = getFirstStr(input, "session_id", "sessionID")+ returndefault:sessionID, _ = input["session_id"].(string)transcriptPath, _ = input["transcript_path"].(string)@@ -107,6 +112,11 @@ func resolveCwd(input map[string]interface{}, platform string) string {}return ""}+ if platform == "opencode" {+ if cwd := getFirstStr(input, "cwd", "directory", "worktree"); cwd != "" {+ return cwd+ }+ }cwd, _ := input["cwd"].(string)return cwd}diff --git a/cli/beacon-hooks/cmd/opencode_event.go b/cli/beacon-hooks/cmd/opencode_event.gonew file mode 100644index 00000000..82ca93c8--- /dev/null+++ b/cli/beacon-hooks/cmd/opencode_event.go@@ -0,0 +1,207 @@+package cmd++import (+ "strings"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"+)++var opencodeEventCmd = &cobra.Command{+ Use: "opencode-event",+ Short: "Record opencode plugin telemetry",+ Long: `opencode-event receives raw Beacon opencode plugin payloads and writes local endpoint telemetry.`,+ Run: runOpenCodeEvent,+}++func init() {+ rootCmd.AddCommand(opencodeEventCmd)+}++func runOpenCodeEvent(cmd *cobra.Command, args []string) {+ input, err := readStdinJSON()+ if err != nil {+ outputJSON(emptyResponse)+ return+ }+ sessionID := resolveSessionID(input, "opencode")+ var logger *logging.Logger+ if sessionID != "" {+ logger = logging.NewSessionLogger("opencode-event", "opencode", sessionID)+ } else {+ logger = logging.NewLoggerForPlatform("opencode-event", "opencode")+ }+ action, category, severity, message, fields := opencodeEndpointEvent(input, sessionID)+ if action == "" {+ outputJSON(emptyResponse)+ return+ }+ logger.EndpointEvent(action, category, severity, message, fields)+ outputJSON(emptyResponse)+}++func opencodeEndpointEvent(input map[string]interface{}, sessionID string) (string, string, string, string, map[string]interface{}) {+ eventType := getFirstStr(input, "type", "event_type", "hook")+ fields := sessionFields(sessionID, input)+ fields["raw"] = map[string]interface{}{+ "opencode": input,+ }+ if model := opencodeModel(input); model != "" {+ fields["model"] = model+ }++ switch eventType {+ case "chat.message":+ if config.ContentRetentionMode() != config.ContentRetentionMetadata {+ if prompt := opencodePromptText(input); prompt != "" {+ fields["prompt"] = map[string]interface{}{"text": prompt}+ }+ }+ return "prompt.submitted", "prompt", "info", "Prompt submitted to opencode", fields+ case "session.created":+ return "session.started", "session", "info", "opencode session started", fields+ case "session.idle":+ return "session.ended", "session", "info", "opencode session ended", fields+ case "session.error":+ return "tool.failed", "tool", "high", "opencode session error", fields+ case "session.diff":+ mergeMap(fields, opencodeDiffFields(input))+ return "file.modified", "file", "info", "opencode session diff observed", fields+ case "command.executed":+ if command := opencodeCommand(input); command != "" {+ fields["command"] = map[string]interface{}{"command": command}+ fields["tool"] = map[string]interface{}{"name": "command", "command": command}+ }+ return "command.executed", "command", "info", "opencode command executed", fields+ case "permission.asked":+ fields["approval"] = map[string]interface{}{"required": true, "decision": "requested"}+ if tool := opencodeToolName(input); tool != "" {+ fields["tool"] = map[string]interface{}{"name": tool}+ }+ return "approval.requested", "approval", "info", "opencode permission requested", fields+ case "permission.replied", "permission.updated":+ decision := opencodeDecision(input)+ if decision == "" {+ decision = "unknown"+ }+ fields["approval"] = map[string]interface{}{"required": true, "decision": decision}+ if tool := opencodeToolName(input); tool != "" {+ fields["tool"] = map[string]interface{}{"name": tool}+ }+ return "approval.allowed", "approval", "info", "opencode permission " + decision, fields+ default:+ return "", "", "", "", nil+ }+}++func supportedOpenCodeEventTypes() []string {+ return []string{+ "chat.message",+ "command.executed",+ "permission.asked",+ "permission.replied",+ "permission.updated",+ "session.created",+ "session.diff",+ "session.error",+ "session.idle",+ }+}++func opencodePromptText(input map[string]interface{}) string {+ if prompt := getFirstStr(input, "prompt", "text", "user_prompt"); prompt != "" {+ return prompt+ }+ output, _ := input["output"].(map[string]interface{})+ parts, _ := output["parts"].([]interface{})+ var values []string+ for _, part := range parts {+ partMap, ok := part.(map[string]interface{})+ if !ok {+ continue+ }+ switch getFirstStr(partMap, "type") {+ case "text":+ if text := getFirstStr(partMap, "text"); text != "" {+ values = append(values, text)+ }+ case "file":+ if file := getFirstStr(partMap, "filename", "url"); file != "" {+ values = append(values, file)+ }+ case "agent", "subtask":+ if name := getFirstStr(partMap, "name", "description"); name != "" {+ values = append(values, name)+ }+ }+ }+ return strings.Join(values, "\n")+}++func opencodeModel(input map[string]interface{}) string {+ if model := getFirstStr(input, "model"); model != "" {+ return model+ }+ model, _ := input["model_info"].(map[string]interface{})+ if model == nil {+ model, _ = input["modelInfo"].(map[string]interface{})+ }+ provider := getFirstStr(model, "providerID", "provider_id", "provider")+ name := getFirstStr(model, "modelID", "model_id", "id", "name")+ if provider != "" && name != "" {+ return provider + "/" + name+ }+ return name+}++func opencodeDiffFields(input map[string]interface{}) map[string]interface{} {+ path := getFirstStr(input, "file_path", "filePath", "path")+ diff := getFirstStr(input, "diff")+ if path == "" {+ properties, _ := input["properties"].(map[string]interface{})+ path = getFirstStr(properties, "file_path", "filePath", "path")+ diff = firstNonEmpty(diff, getFirstStr(properties, "diff"))+ }+ return diffFields(path, diff)+}++func opencodeCommand(input map[string]interface{}) string {+ if command := getFirstStr(input, "command", "cmd"); command != "" {+ return command+ }+ properties, _ := input["properties"].(map[string]interface{})+ return getFirstStr(properties, "command", "cmd")+}++func opencodeToolName(input map[string]interface{}) string {+ if tool := getFirstStr(input, "tool", "tool_name", "toolName"); tool != "" {+ return tool+ }+ properties, _ := input["properties"].(map[string]interface{})+ return getFirstStr(properties, "tool", "tool_name", "toolName")+}++func opencodeDecision(input map[string]interface{}) string {+ if decision := getFirstStr(input, "decision", "status"); decision != "" {+ return decision+ }+ properties, _ := input["properties"].(map[string]interface{})+ return getFirstStr(properties, "decision", "status")+}++func mergeMap(dst, src map[string]interface{}) {+ for key, value := range src {+ dst[key] = value+ }+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if strings.TrimSpace(value) != "" {+ return value+ }+ }+ return ""+}diff --git a/cli/beacon-hooks/cmd/opencode_event_test.go b/cli/beacon-hooks/cmd/opencode_event_test.gonew file mode 100644index 00000000..aa338375--- /dev/null+++ b/cli/beacon-hooks/cmd/opencode_event_test.go@@ -0,0 +1,189 @@+package cmd++import (+ "encoding/json"+ "os"+ "path/filepath"+ "regexp"+ "sort"+ "strings"+ "testing"+)++func TestOpenCodeEventRecordsPrompt(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "opencode"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ t.Setenv("BEACON_CONTENT_RETENTION", "full")++ out := runHookWithInput(t, runOpenCodeEvent, map[string]interface{}{+ "type": "chat.message",+ "session_id": "session-1",+ "directory": "/tmp/project",+ "model": "anthropic/claude-sonnet-4",+ "output": map[string]interface{}{+ "parts": []interface{}{+ map[string]interface{}{"type": "text", "text": "summarize token=opencode-secret"},+ },+ },+ })+ if len(out) != 0 {+ t.Fatalf("response = %#v, want empty object", out)+ }+ event := lastEndpointEvent(t, logPath)+ if action := event["event"].(map[string]interface{})["action"]; action != "prompt.submitted" {+ t.Fatalf("event.action = %q, want prompt.submitted", action)+ }+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "opencode" {+ t.Fatalf("harness.name = %q, want opencode", harness)+ }+ if got := event["prompt"].(map[string]interface{})["text"]; got != "summarize token=[REDACTED]" {+ t.Fatalf("prompt.text = %q, want redacted prompt", got)+ }+ if got := event["model"]; got != "anthropic/claude-sonnet-4" {+ t.Fatalf("model = %q, want opencode model", got)+ }+}++func TestOpenCodeEventFixtureRecordsPrompt(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "opencode"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ t.Setenv("BEACON_CONTENT_RETENTION", "full")++ input := readOpenCodeFixture(t, "chat_message.json")+ runHookWithInput(t, runOpenCodeEvent, input)+ event := lastEndpointEvent(t, logPath)+ if action := event["event"].(map[string]interface{})["action"]; action != "prompt.submitted" {+ t.Fatalf("fixture event.action = %q, want prompt.submitted", action)+ }+}++func TestOpenCodeEventMetadataOmitsPromptAndRawPayload(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "opencode"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)+ t.Setenv("BEACON_CONTENT_RETENTION", "metadata")++ runHookWithInput(t, runOpenCodeEvent, map[string]interface{}{+ "type": "chat.message",+ "session_id": "session-1",+ "output": map[string]interface{}{+ "parts": []interface{}{+ map[string]interface{}{"type": "text", "text": "secret prompt"},+ },+ },+ })+ event := lastEndpointEvent(t, logPath)+ if _, ok := event["prompt"]; ok {+ t.Fatalf("metadata retention should omit prompt: %#v", event["prompt"])+ }+ raw := event["raw"].(map[string]interface{})+ if _, ok := raw["opencode"]; ok {+ t.Fatalf("metadata retention should omit raw opencode payload: %#v", raw)+ }+}++func TestOpenCodeEventMapsPermissionDecision(t *testing.T) {+ fields := map[string]interface{}{+ "type": "permission.replied",+ "session_id": "session-1",+ "tool": "bash",+ "decision": "accepted",+ }+ _, category, _, _, eventFields := opencodeEndpointEvent(fields, "session-1")+ if category != "approval" {+ t.Fatalf("category = %q, want approval", category)+ }+ approval := eventFields["approval"].(map[string]interface{})+ if approval["decision"] != "accepted" {+ t.Fatalf("approval.decision = %q, want accepted", approval["decision"])+ }+}++func TestOpenCodeEventIgnoresUnsupportedEvents(t *testing.T) {+ setupHookConfigDirs(t)+ platformFlag = "opencode"+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ out := runHookWithInput(t, runOpenCodeEvent, map[string]interface{}{+ "type": "message.updated",+ "session_id": "session-1",+ })+ if len(out) != 0 {+ t.Fatalf("response = %#v, want empty object", out)+ }+ assertNoEndpointLog(t, logPath)++ runHookWithInput(t, runOpenCodeEvent, map[string]interface{}{+ "type": "tool.completed",+ "session_id": "session-1",+ })+ assertNoEndpointLog(t, logPath)++ runHookWithInput(t, runOpenCodeEvent, map[string]interface{}{+ "type": "session.deleted",+ "session_id": "session-1",+ })+ assertNoEndpointLog(t, logPath)+}++func TestOpenCodeForwardedEventsMatchGoIngestion(t *testing.T) {+ source, err := os.ReadFile(filepath.Join("..", "..", "beacon", "internal", "endpoint", "hooks", "assets", "opencode", "beacon.ts"))+ if err != nil {+ t.Fatalf("read embedded plugin source: %v", err)+ }+ got := forwardedEventsFromPluginSource(t, string(source))+ want := supportedOpenCodeEventTypes()+ sort.Strings(got)+ sort.Strings(want)+ if strings.Join(got, "\n") != strings.Join(want, "\n") {+ t.Fatalf("forwarded events do not match Go ingestion\nplugin=%#v\ngo=%#v", got, want)+ }+}++func assertNoEndpointLog(t *testing.T, path string) {+ t.Helper()+ if _, err := os.Stat(path); err == nil {+ t.Fatalf("endpoint log should not exist for unsupported event: %s", path)+ } else if !os.IsNotExist(err) {+ t.Fatalf("unexpected endpoint log stat error: %v", err)+ }+}++func forwardedEventsFromPluginSource(t *testing.T, source string) []string {+ t.Helper()+ re := regexp.MustCompile(`(?s)forwardedEvents = new Set\(\[(.*?)\]\)`)+ match := re.FindStringSubmatch(source)+ if len(match) != 2 {+ t.Fatalf("forwardedEvents list not found in plugin source")+ }+ itemRE := regexp.MustCompile(`"([^"]+)"`)+ matches := itemRE.FindAllStringSubmatch(match[1], -1)+ events := []string{"chat.message"}+ for _, match := range matches {+ events = append(events, match[1])+ }+ return events+}++func readOpenCodeFixture(t *testing.T, name string) map[string]interface{} {+ t.Helper()+ data, err := os.ReadFile(filepath.Join("..", "testdata", "opencode", name))+ if err != nil {+ t.Fatalf("read opencode fixture %s: %v", name, err)+ }+ var payload map[string]interface{}+ if err := json.Unmarshal(data, &payload); err != nil {+ t.Fatalf("decode opencode fixture %s: %v", name, err)+ }+ return payload+}diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex 0013d6f0..1fc2c149 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -187,18 +187,21 @@ func setupHookConfigDirs(t *testing.T) {origCopilotDir := hookconfig.CopilotDirorigCursorDir := hookconfig.CursorDirorigFactoryDir := hookconfig.FactoryDir+ origOpenCodeDir := hookconfig.OpenCodeDirorigPlatform := platformFlaghookconfig.BeaconDir = tmphookconfig.ClaudeDir = filepath.Join(tmp, "claude")hookconfig.CopilotDir = filepath.Join(tmp, "copilot")hookconfig.CursorDir = filepath.Join(tmp, "cursor")hookconfig.FactoryDir = filepath.Join(tmp, "factory")+ hookconfig.OpenCodeDir = filepath.Join(tmp, "opencode")t.Cleanup(func() {hookconfig.BeaconDir = origBeaconDirhookconfig.ClaudeDir = origClaudeDirhookconfig.CopilotDir = origCopilotDirhookconfig.CursorDir = origCursorDirhookconfig.FactoryDir = origFactoryDir+ hookconfig.OpenCodeDir = origOpenCodeDirplatformFlag = origPlatform})}diff --git a/cli/beacon-hooks/cmd/root.go b/cli/beacon-hooks/cmd/root.goindex ef962ab1..687fc955 100644--- a/cli/beacon-hooks/cmd/root.go+++ b/cli/beacon-hooks/cmd/root.go@@ -11,8 +11,8 @@ var platformFlag stringvar rootCmd = &cobra.Command{Use: "beacon-hooks",- Short: "Beacon hooks for Claude Code, GitHub Copilot, Cursor, and Factory",- Long: `Beacon hooks binary for Claude Code, GitHub Copilot, Cursor, and Factory integration.+ Short: "Beacon hooks for Claude Code, GitHub Copilot, Cursor, Factory, and opencode",+ Long: `Beacon hooks binary for Claude Code, GitHub Copilot, Cursor, Factory, and opencode integration.This binary provides hook commands that are called by IDE plugin systemsto evaluate code changes for security violations.@@ -21,7 +21,7 @@ Use --platform to specify the calling platform (default: claude).`,}func init() {- rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, copilot, cursor, or factory")+ rootCmd.PersistentFlags().StringVar(&platformFlag, "platform", "claude", "Platform context: claude, copilot, cursor, factory, or opencode")}// Execute runs the root commanddiff --git a/cli/beacon-hooks/internal/config/config.go b/cli/beacon-hooks/internal/config/config.goindex 8c2c7d0b..a16c0128 100644--- a/cli/beacon-hooks/internal/config/config.go+++ b/cli/beacon-hooks/internal/config/config.go@@ -9,11 +9,12 @@ import (// Directoriesvar (- BeaconDir = getBeaconDir()- ClaudeDir = filepath.Join(BeaconDir, "claude")- CopilotDir = filepath.Join(BeaconDir, "copilot")- CursorDir = filepath.Join(BeaconDir, "cursor")- FactoryDir = filepath.Join(BeaconDir, "factory")+ BeaconDir = getBeaconDir()+ ClaudeDir = filepath.Join(BeaconDir, "claude")+ CopilotDir = filepath.Join(BeaconDir, "copilot")+ CursorDir = filepath.Join(BeaconDir, "cursor")+ FactoryDir = filepath.Join(BeaconDir, "factory")+ OpenCodeDir = filepath.Join(BeaconDir, "opencode"))// Log rotation@@ -89,6 +90,8 @@ func GetStateDir(platform string) string {return CursorDircase "factory":return FactoryDir+ case "opencode":+ return OpenCodeDirdefault:return ClaudeDir}diff --git a/cli/beacon-hooks/testdata/opencode/README.md b/cli/beacon-hooks/testdata/opencode/README.mdnew file mode 100644index 00000000..b274f0c0--- /dev/null+++ b/cli/beacon-hooks/testdata/opencode/README.md@@ -0,0 +1,19 @@+# opencode payload fixtures++This directory is reserved for captured opencode plugin payload fixtures.++Capture representative payloads for:++- `chat.message`+- `session.created`+- `session.idle`+- `session.error`+- `session.diff`+- `command.executed`+- `permission.asked`+- `permission.replied`+- `permission.updated`++Keep secrets and real prompt content out of fixtures. Use sanitized payloads that+preserve the field shape needed by `beacon-hooks --platform opencode+opencode-event`.diff --git a/cli/beacon-hooks/testdata/opencode/chat_message.json b/cli/beacon-hooks/testdata/opencode/chat_message.jsonnew file mode 100644index 00000000..9a150b5a--- /dev/null+++ b/cli/beacon-hooks/testdata/opencode/chat_message.json@@ -0,0 +1,14 @@+{+ "type": "chat.message",+ "session_id": "fixture-session",+ "directory": "/tmp/project",+ "model": "provider/model",+ "output": {+ "parts": [+ {+ "type": "text",+ "text": "sanitized prompt text"+ }+ ]+ }+}diff --git a/cli/beacon/README.md b/cli/beacon/README.mdindex 5b78d669..a9f771c5 100644--- a/cli/beacon/README.md+++ b/cli/beacon/README.md@@ -66,11 +66,21 @@ that may need review../beacon endpoint hooks install --harness cursor./beacon endpoint hooks status --harness cursor+./beacon endpoint hooks install --harness opencode+./beacon endpoint hooks status --harness opencode+./beacon endpoint integrations claude-cowork setup --endpoint https://collector.example.com --open./beacon endpoint integrations claude-cowork setup --ngrok --open./beacon endpoint integrations claude-cowork validate --since 10m```+The opencode integration installs Beacon's owned local plugin at+`~/.config/opencode/plugins/beacon.ts`. The plugin is a thin adapter that sends+raw opencode hook payloads to Beacon's Go hook binary; Beacon handles+normalization, retention, redaction, and JSONL output locally. For local+troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment that launches+opencode to emit best-effort plugin debug logs.+Claude Cowork monitoring is configured in the Claude admin console at`https://claude.ai/admin-settings/cowork`. The OTLP endpoint must be reachableby Claude Cowork, so use a durable public HTTPS Collector endpoint for ongoingdiff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex dbbbe468..1f4a6df1 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -348,6 +348,16 @@ func runEndpointHooksInstall(cmd *cobra.Command, args []string) error {return err}fmt.Printf("Factory hooks installed: %s\n", status.SettingsPath)+ case "opencode":+ status, err := endpointhooks.InstallOpenCode(endpointhooks.OpenCodeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })+ if err != nil {+ return err+ }+ fmt.Printf("opencode plugin installed: %s\n", status.PluginPath)case "":default:return fmt.Errorf("unsupported hook harness %q", name)@@ -380,6 +390,16 @@ func runEndpointHooksUninstall(cmd *cobra.Command, args []string) error {return err}fmt.Println(status.Message)+ case "opencode":+ status, err := endpointhooks.UninstallOpenCode(endpointhooks.OpenCodeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })+ if err != nil {+ return err+ }+ fmt.Println(status.Message)case "":default:return fmt.Errorf("unsupported hook harness %q", name)@@ -405,6 +425,12 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {LogPath: cfg.LogPath,UserMode: cfg.UserMode,})+ case "opencode":+ statuses["opencode"] = endpointhooks.OpenCodeHookStatus(endpointhooks.OpenCodeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })case "":default:return fmt.Errorf("unsupported hook harness %q", name)@@ -423,6 +449,10 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {status := statuses["factory"].(endpointhooks.FactoryStatus)fmt.Printf("Factory hooks: installed=%t path=%s\n", status.Installed, status.SettingsPath)fmt.Println(status.Message)+ case "opencode":+ status := statuses["opencode"].(endpointhooks.OpenCodeStatus)+ fmt.Printf("opencode plugin: installed=%t path=%s\n", status.Installed, status.PluginPath)+ fmt.Println(status.Message)}}return nildiff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.goindex 59bd29f7..0cf27085 100644--- a/cli/beacon/internal/endpoint/harness/harness.go+++ b/cli/beacon/internal/endpoint/harness/harness.go@@ -47,6 +47,7 @@ func DiscoverAll() []Harness {return []Harness{DiscoverClaude(),DiscoverCodex(),+ DiscoverOpenCode(),DiscoverFactory(),DiscoverCursor(),DiscoverClaudeCowork(),@@ -127,6 +128,36 @@ func DiscoverFactory() Harness {return h}+func DiscoverOpenCode() Harness {+ h := Harness{Name: "opencode", DisplayName: "opencode", Capability: "plugin"}+ path, err := exec.LookPath("opencode")+ if err == nil {+ h.Detected = true+ h.ExecutablePath = path+ h.Version = commandVersion(path)+ }+ home, _ := os.UserHomeDir()+ pluginPath := filepath.Join(home, ".config", "opencode", "plugins", "beacon.ts")+ h.ConfigPath = pluginPath+ if !h.Detected && dirExists(filepath.Join(home, ".config", "opencode")) {+ h.Detected = true+ }+ if fileExists(pluginPath) {+ data, _ := os.ReadFile(pluginPath)+ if strings.Contains(string(data), "beacon-managed-opencode-plugin:v1") {+ h.TelemetryStatus = TelemetryEnabled+ h.Message = "Beacon opencode plugin is configured"+ } else {+ h.TelemetryStatus = TelemetryDisabled+ h.Message = "opencode plugin file exists but Beacon endpoint plugin was not found"+ }+ } else {+ h.TelemetryStatus = TelemetryMissing+ h.Message = "Beacon opencode plugin was not found"+ }+ return h+}+func DiscoverCursor() Harness {h := Harness{Name: "cursor", DisplayName: "Cursor", Capability: "hooks"}path, err := exec.LookPath("cursor")diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.tsnew file mode 100644index 00000000..c14c217b--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts@@ -0,0 +1,95 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry plugin for opencode.+// Managed by beacon endpoint hooks install --harness opencode.++const beaconCommand = "__BEACON_COMMAND__"+const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"+const forwardedEvents = new Set([+ "session.created",+ "session.idle",+ "session.error",+ "session.diff",+ "command.executed",+ "permission.asked",+ "permission.replied",+ "permission.updated",+])++async function debugLog(client, message, extra) {+ if (!debugEnabled) return+ try {+ await client?.app?.log?.({+ body: {+ service: "beacon-opencode-plugin",+ level: "debug",+ message,+ extra,+ },+ })+ } catch {+ // Debug logging must stay best-effort.+ }+}++async function sendToBeacon(client, payload) {+ try {+ const proc = Bun.spawn(["/bin/sh", "-lc", beaconCommand], {+ stdin: "pipe",+ stdout: "ignore",+ stderr: "ignore",+ })+ proc.stdin.write(JSON.stringify(payload))+ proc.stdin.end()+ const code = await proc.exited+ if (code !== 0) {+ await debugLog(client, "Beacon hook command exited non-zero", { code, type: payload?.type })+ }+ } catch (err) {+ await debugLog(client, "Beacon hook command failed", {+ error: err instanceof Error ? err.message : String(err),+ type: payload?.type,+ })+ // Beacon telemetry must never interrupt opencode execution.+ }+}++function sessionID(value) {+ return value?.sessionID || value?.session_id || value?.id || value?.session?.id || value?.info?.sessionID || ""+}++function modelName(value) {+ const model = value?.model || value?.modelInfo+ if (!model || typeof model === "string") return model || ""+ if (model.providerID && model.modelID) return model.providerID + "/" + model.modelID+ return model.modelID || model.id || model.name || ""+}++export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {+ const context = { project, directory, worktree }+ return {+ "chat.message": async (input, output) => {+ await sendToBeacon(client, {+ type: "chat.message",+ session_id: sessionID(input),+ model: modelName(input),+ input,+ output,+ ...context,+ })+ },+ event: async ({ event }) => {+ const type = event?.type || "event"+ if (!forwardedEvents.has(type)) return++ const properties = event?.properties || {}+ await sendToBeacon(client, {+ type,+ session_id: sessionID(properties),+ model: modelName(properties?.info || properties),+ properties,+ event,+ ...context,+ })+ },+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/embed.go b/cli/beacon/internal/endpoint/hooks/assets/opencode/embed.gonew file mode 100644index 00000000..ce896988--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/embed.go@@ -0,0 +1,10 @@+package opencodeplugin++import _ "embed"++// Template embeds the checked copy used by Beacon's Go installer.+// The root source of truth lives at plugins/opencode-beacon/src/beacon.ts.+// Tests fail if this copy drifts.+//+//go:embed beacon.ts+var Template stringdiff --git a/cli/beacon/internal/endpoint/hooks/opencode.go b/cli/beacon/internal/endpoint/hooks/opencode.gonew file mode 100644index 00000000..f2cbe586--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/opencode.go@@ -0,0 +1,158 @@+package hooks++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"++ opencodeplugin "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks/assets/opencode"+)++const (+ opencodePluginFileName = "beacon.ts"+ opencodeManagedPluginMarker = "beacon-managed-opencode-plugin:v1"+)++var opencodePluginTemplate = opencodeplugin.Template++type OpenCodeOptions struct {+ Level Level+ LogPath string+ UserMode bool+}++type OpenCodeStatus struct {+ Installed bool `json:"installed"`+ BinaryPath string `json:"binary_path,omitempty"`+ PluginPath string `json:"plugin_path,omitempty"`+ Message string `json:"message,omitempty"`+}++var opencodeRuntime = hookRuntime{+ displayName: "opencode",+ configPath: opencodePluginPath,+ install: installOpenCodePlugin,+ uninstall: removeOpenCodePlugin,+ isInstalled: isOpenCodeInstalledAt,+}++func InstallOpenCode(opts OpenCodeOptions) (OpenCodeStatus, error) {+ status, err := installRuntimeHooks(opencodeRuntime, RuntimeOptions(opts))+ if err != nil {+ return OpenCodeStatus{}, err+ }+ return opencodeStatusFromRuntime(status), nil+}++func UninstallOpenCode(opts OpenCodeOptions) (OpenCodeStatus, error) {+ status, err := uninstallRuntimeHooks(opencodeRuntime, RuntimeOptions(opts))+ if err != nil {+ return OpenCodeStatus{}, err+ }+ return opencodeStatusFromRuntime(status), nil+}++func OpenCodeHookStatus(opts OpenCodeOptions) OpenCodeStatus {+ return opencodeStatusFromRuntime(runtimeHookStatus(opencodeRuntime, RuntimeOptions(opts)))+}++func IsOpenCodeInstalled(opts OpenCodeOptions) bool {+ return isRuntimeInstalled(opencodeRuntime, RuntimeOptions(opts))+}++func opencodeStatusFromRuntime(status runtimeStatus) OpenCodeStatus {+ out := OpenCodeStatus{+ Installed: status.Installed,+ BinaryPath: status.BinaryPath,+ PluginPath: status.ConfigPath,+ Message: status.Message,+ }+ if out.Installed && out.BinaryPath != "" {+ if _, err := os.Stat(out.BinaryPath); err != nil {+ out.Installed = false+ out.Message = fmt.Sprintf("opencode plugin is installed, but Beacon hook binary is missing at %s", out.BinaryPath)+ }+ }+ return out+}++func opencodeEmbeddedPluginSourcePath() string {+ return filepath.Clean(filepath.Join("assets", "opencode", "beacon.ts"))+}++func opencodeRootPluginSourcePath() string {+ return filepath.Clean(filepath.Join("..", "..", "..", "..", "..", "plugins", "opencode-beacon", "src", "beacon.ts"))+}++func installOpenCodePlugin(path, binaryPath, logPath, configPath string) error {+ plugin, err := renderOpenCodePlugin(binaryPath, logPath, configPath)+ if err != nil {+ return err+ }+ return os.WriteFile(path, []byte(plugin), 0644)+}++func removeOpenCodePlugin(path string) (bool, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return false, nil+ }+ return false, err+ }+ if !strings.Contains(string(data), opencodeManagedPluginMarker) {+ return false, nil+ }+ return true, os.Remove(path)+}++func isOpenCodeInstalledAt(path string) bool {+ data, err := os.ReadFile(path)+ if err != nil {+ return false+ }+ text := string(data)+ return strings.Contains(text, opencodeManagedPluginMarker)+}++func opencodePluginPath(level Level) (string, error) {+ dir, err := opencodePluginDir(level)+ if err != nil {+ return "", err+ }+ return filepath.Join(dir, opencodePluginFileName), nil+}++func opencodePluginDir(level Level) (string, error) {+ switch level {+ case "", LevelUser:+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, ".config", "opencode", "plugins"), nil+ case LevelProject:+ cwd, err := os.Getwd()+ if err != nil {+ return "", err+ }+ return filepath.Join(cwd, ".opencode", "plugins"), nil+ default:+ return "", fmt.Errorf("unknown hook level %q", level)+ }+}++func renderOpenCodePlugin(binaryPath, logPath, configPath string) (string, error) {+ return renderOpenCodePluginTemplate(opencodePluginTemplate, binaryPath, logPath, configPath)+}++func renderOpenCodePluginTemplate(template, binaryPath, logPath, configPath string) (string, error) {+ commandPrefix := endpointCommandPrefix("opencode", binaryPath, logPath, configPath)+ source := strings.ReplaceAll(template, "__BEACON_MANAGED_MARKER__", opencodeManagedPluginMarker)+ source = strings.ReplaceAll(source, `"__BEACON_COMMAND__"`, fmt.Sprintf("%q", commandPrefix+" opencode-event"))+ if strings.Contains(source, "__BEACON_") {+ return "", fmt.Errorf("opencode plugin template contains unresolved Beacon placeholders")+ }+ return source, nil+}diff --git a/cli/beacon/internal/endpoint/hooks/opencode_test.go b/cli/beacon/internal/endpoint/hooks/opencode_test.gonew file mode 100644index 00000000..949f5098--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/opencode_test.go@@ -0,0 +1,147 @@+package hooks++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestInstallOpenCodePluginWritesManagedPlugin(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ if err := installOpenCodePlugin(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installOpenCodePlugin returned error: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read plugin: %v", err)+ }+ text := string(data)+ for _, want := range []string{+ opencodeManagedPluginMarker,+ "BeaconEndpointPlugin",+ "BEACON_OPENCODE_DEBUG",+ "BEACON_ENDPOINT_MODE=1",+ "--platform opencode",+ "opencode-event",+ "BEACON_ENDPOINT_LOG='/tmp/runtime.jsonl'",+ "BEACON_ENDPOINT_CONFIG='/tmp/config.json'",+ "forwardedEvents",+ "session.created",+ } {+ if !strings.Contains(text, want) {+ t.Fatalf("plugin missing %q:\n%s", want, text)+ }+ }+ if strings.Contains(text, "message.updated") || strings.Contains(text, "message.part.updated") {+ t.Fatalf("high-volume message update events should not be forwarded:\n%s", text)+ }+}++func TestRenderOpenCodePluginRejectsUnresolvedPlaceholders(t *testing.T) {+ _, err := renderOpenCodePluginTemplate("__BEACON_UNKNOWN__", "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json")+ if err == nil {+ t.Fatal("expected unresolved placeholder error")+ }+}++func TestOpenCodeEmbeddedPluginMatchesRootSource(t *testing.T) {+ embedded, err := os.ReadFile(opencodeEmbeddedPluginSourcePath())+ if err != nil {+ t.Fatalf("read embedded plugin source: %v", err)+ }+ root, err := os.ReadFile(opencodeRootPluginSourcePath())+ if err != nil {+ t.Fatalf("read root plugin source: %v", err)+ }+ if string(embedded) != string(root) {+ t.Fatalf("embedded opencode plugin source drifted from root package source")+ }+}++func TestRemoveOpenCodePluginOnlyRemovesManagedPlugin(t *testing.T) {+ dir := t.TempDir()+ userPlugin := filepath.Join(dir, "user.ts")+ if err := os.WriteFile(userPlugin, []byte("export const UserPlugin = async () => ({})"), 0644); err != nil {+ t.Fatalf("write user plugin: %v", err)+ }+ changed, err := removeOpenCodePlugin(userPlugin)+ if err != nil {+ t.Fatalf("removeOpenCodePlugin returned error: %v", err)+ }+ if changed {+ t.Fatal("user plugin should not be removed")+ }+ if _, err := os.Stat(userPlugin); err != nil {+ t.Fatalf("user plugin was removed: %v", err)+ }++ managed := filepath.Join(dir, "beacon.ts")+ if err := installOpenCodePlugin(managed, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installOpenCodePlugin returned error: %v", err)+ }+ changed, err = removeOpenCodePlugin(managed)+ if err != nil {+ t.Fatalf("removeOpenCodePlugin returned error: %v", err)+ }+ if !changed {+ t.Fatal("expected managed plugin removal")+ }+ if _, err := os.Stat(managed); !os.IsNotExist(err) {+ t.Fatalf("managed plugin still exists or unexpected error: %v", err)+ }+}++func TestOpenCodeStatusWarnsWhenHookBinaryMissing(t *testing.T) {+ status := opencodeStatusFromRuntime(runtimeStatus{+ Installed: true,+ BinaryPath: filepath.Join(t.TempDir(), "missing-beacon-hooks"),+ ConfigPath: "/tmp/beacon.ts",+ Message: "opencode endpoint hooks are installed",+ })+ if status.Installed {+ t.Fatal("status should not be fully installed when hook binary is missing")+ }+ if !strings.Contains(status.Message, "hook binary is missing") {+ t.Fatalf("status message = %q, want missing binary warning", status.Message)+ }+}++func TestOpenCodeInstalledUsesManagedMarker(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ if err := os.WriteFile(path, []byte("BEACON_ENDPOINT_MODE=1 opencode-event"), 0644); err != nil {+ t.Fatalf("write unmarked plugin: %v", err)+ }+ if isOpenCodeInstalledAt(path) {+ t.Fatal("unmarked plugin should not be detected as installed")+ }+ if err := installOpenCodePlugin(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {+ t.Fatalf("installOpenCodePlugin returned error: %v", err)+ }+ if !isOpenCodeInstalledAt(path) {+ t.Fatal("managed plugin should be detected by marker")+ }+}++func TestOpenCodePluginPathLevels(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ if got, want := mustOpenCodePluginPath(t, LevelUser), filepath.Join(home, ".config", "opencode", "plugins", "beacon.ts"); got != want {+ t.Fatalf("user plugin path = %q, want %q", got, want)+ }++ project := t.TempDir()+ t.Chdir(project)+ if got, want := mustOpenCodePluginPath(t, LevelProject), filepath.Join(project, ".opencode", "plugins", "beacon.ts"); got != want {+ t.Fatalf("project plugin path = %q, want %q", got, want)+ }+}++func mustOpenCodePluginPath(t *testing.T, level Level) string {+ t.Helper()+ path, err := opencodePluginPath(level)+ if err != nil {+ t.Fatalf("opencodePluginPath returned error: %v", err)+ }+ return path+}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 5be6a462..e4865910 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -371,6 +371,8 @@ func configureHarnesses(cfg endpointconfig.Config) ([]string, error) {return paths, err}paths = append(paths, path)+ case "opencode":+ return paths, fmt.Errorf("opencode telemetry is installed with `beacon endpoint hooks install --harness opencode`, not endpoint install")case "factory", "droid":return paths, fmt.Errorf("Factory Droid telemetry is MDM-managed; set OTEL_TELEMETRY_ENDPOINT=http://127.0.0.1:%d in the Droid launch environment instead of using --harness %s", cfg.Collector.HTTPPort, name)case "":diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.goindex 429d0b79..89c0c63d 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go@@ -148,6 +148,14 @@ func TestConfigureHarnessesRejectsFactoryAsMDMManaged(t *testing.T) {}}+func TestConfigureHarnessesRejectsOpenCodeAsHookManaged(t *testing.T) {+ cfg := endpointconfig.Config{Harnesses: []string{"opencode"}}+ _, err := configureHarnesses(cfg)+ if err == nil || !strings.Contains(err.Error(), "endpoint hooks install --harness opencode") {+ t.Fatalf("configureHarnesses error = %v, want opencode hook-managed error", err)+ }+}+func TestWriteReadManifestRoundTrip(t *testing.T) {home := t.TempDir()t.Setenv("HOME", home)diff --git a/packaging/macos/README.md b/packaging/macos/README.mdindex 232b80b7..465de45e 100644--- a/packaging/macos/README.md+++ b/packaging/macos/README.md@@ -112,13 +112,14 @@ Recommended rollout:4. Scope repair/remediation to unhealthy devices.5. Broaden deployment in stages after inventory and validation stay healthy.-Cursor and Factory hook installation is separate from the base system package-because both integrations write per-user or per-project runtime settings. Run-hook helpers only when an interactive console user is present. Cursor hooks use-`.cursor/hooks.json`; Factory hooks use `.factory/settings.json`; restart the-runtime after installation so new sessions pick up the settings. Install hooks-with the same endpoint log path as the collector when you want hook telemetry and-OTLP telemetry to appear in one dashboard.+Cursor, Factory, and opencode hook installation is separate from the base system+package because these integrations write per-user or per-project runtime+settings. Run hook helpers only when an interactive console user is present.+Cursor hooks use `.cursor/hooks.json`; Factory hooks use `.factory/settings.json`;+opencode uses Beacon's owned plugin at `~/.config/opencode/plugins/beacon.ts`.+Restart the runtime after installation so new sessions pick up the settings.+Install hooks with the same endpoint log path as the collector when you want hook+telemetry and OTLP telemetry to appear in one dashboard.Factory Droid OTLP metrics are also managed outside the base system package.Droid reads OTLP settings from its launch environment, so deploy the environment@@ -140,6 +141,19 @@ hooks in the logged-in user's context:beacon endpoint hooks install --harness factory --level user --log-path /var/log/beacon-agent/runtime.jsonl```+For opencode prompt/session/tool telemetry, install Beacon's opencode plugin in+the logged-in user's context:++```bash+beacon endpoint hooks install --harness opencode --level user --log-path /var/log/beacon-agent/runtime.jsonl+```++The opencode plugin is a small Beacon-owned TypeScript adapter that calls the+Beacon Go hook binary with raw opencode payloads. It does not depend on the+third-party `@devtheops/opencode-plugin-otel` package or configure a separate+OTLP exporter. For troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the+environment that launches opencode to enable best-effort plugin debug logs.+## Jamf ProUpload the generated `.pkg` to Jamf Pro and create a Policy scoped to a pilotdiff --git a/packaging/macos/pkgbuild.md b/packaging/macos/pkgbuild.mdindex 798a423d..cffe58b6 100644--- a/packaging/macos/pkgbuild.md+++ b/packaging/macos/pkgbuild.md@@ -76,6 +76,20 @@ The package installs files under `/opt/beacon` and runscollector and retention settings. The default packaged content retention is`full`, matching the shared MDM install wrapper.+opencode support is intentionally not part of the default package install. To+enable opencode prompt/session/tool telemetry, run Beacon's hook installer in the+target user's context:++```bash+beacon endpoint hooks install --harness opencode --level user --log-path /var/log/beacon-agent/runtime.jsonl+```++This writes Beacon's owned plugin to `~/.config/opencode/plugins/beacon.ts`. The+plugin is only an opencode adapter; Beacon's Go hook binary handles event+normalization, retention, redaction, and JSONL output. Set+`BEACON_OPENCODE_DEBUG=1` in the opencode launch environment only when+troubleshooting plugin delivery.+## Jamf DeploymentUpload the generated `.pkg` to Jamf Pro and create a Policy scoped to a pilotdiff --git a/plugins/opencode-beacon/package.json b/plugins/opencode-beacon/package.jsonnew file mode 100644index 00000000..d6629b58--- /dev/null+++ b/plugins/opencode-beacon/package.json@@ -0,0 +1,19 @@+{+ "name": "@asymptote-labs/opencode-beacon",+ "version": "0.0.0",+ "private": true,+ "description": "Beacon endpoint telemetry adapter for opencode",+ "type": "module",+ "scripts": {+ "check": "bun --check src/beacon.ts"+ },+ "exports": {+ ".": "./src/beacon.ts"+ },+ "files": [+ "src/"+ ],+ "peerDependencies": {+ "@opencode-ai/plugin": "*"+ }+}diff --git a/plugins/opencode-beacon/src/beacon.ts b/plugins/opencode-beacon/src/beacon.tsnew file mode 100644index 00000000..c14c217b--- /dev/null+++ b/plugins/opencode-beacon/src/beacon.ts@@ -0,0 +1,95 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry plugin for opencode.+// Managed by beacon endpoint hooks install --harness opencode.++const beaconCommand = "__BEACON_COMMAND__"+const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"+const forwardedEvents = new Set([+ "session.created",+ "session.idle",+ "session.error",+ "session.diff",+ "command.executed",+ "permission.asked",+ "permission.replied",+ "permission.updated",+])++async function debugLog(client, message, extra) {+ if (!debugEnabled) return+ try {+ await client?.app?.log?.({+ body: {+ service: "beacon-opencode-plugin",+ level: "debug",+ message,+ extra,+ },+ })+ } catch {+ // Debug logging must stay best-effort.+ }+}++async function sendToBeacon(client, payload) {+ try {+ const proc = Bun.spawn(["/bin/sh", "-lc", beaconCommand], {+ stdin: "pipe",+ stdout: "ignore",+ stderr: "ignore",+ })+ proc.stdin.write(JSON.stringify(payload))+ proc.stdin.end()+ const code = await proc.exited+ if (code !== 0) {+ await debugLog(client, "Beacon hook command exited non-zero", { code, type: payload?.type })+ }+ } catch (err) {+ await debugLog(client, "Beacon hook command failed", {+ error: err instanceof Error ? err.message : String(err),+ type: payload?.type,+ })+ // Beacon telemetry must never interrupt opencode execution.+ }+}++function sessionID(value) {+ return value?.sessionID || value?.session_id || value?.id || value?.session?.id || value?.info?.sessionID || ""+}++function modelName(value) {+ const model = value?.model || value?.modelInfo+ if (!model || typeof model === "string") return model || ""+ if (model.providerID && model.modelID) return model.providerID + "/" + model.modelID+ return model.modelID || model.id || model.name || ""+}++export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {+ const context = { project, directory, worktree }+ return {+ "chat.message": async (input, output) => {+ await sendToBeacon(client, {+ type: "chat.message",+ session_id: sessionID(input),+ model: modelName(input),+ input,+ output,+ ...context,+ })+ },+ event: async ({ event }) => {+ const type = event?.type || "event"+ if (!forwardedEvents.has(type)) return++ const properties = event?.properties || {}+ await sendToBeacon(client, {+ type,+ session_id: sessionID(properties),+ model: modelName(properties?.info || properties),+ properties,+ event,+ ...context,+ })+ },+ }+}