Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat: capture full OpenCode agent traces

Cursor Agentb69b873b0594
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 477e8ecc..a7e8110f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,9 +46,15 @@ jobs:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: latest
- uses: actions/setup-go@v5
with:
go-version-file: cli/beacon/go.mod
+ - name: Check OpenCode plugin
+ working-directory: plugins/opencode-beacon
+ run: bun run check && bun test
- name: Build embedded hooks binary
working-directory: cli/beacon
# hooks.bin is gitignored (build-time artifact). The CLI embeds it via
diff --git a/README.md b/README.md
index 8249d5fe..8c921f86 100644
--- a/README.md
+++ b/README.md
@@ -88,7 +88,7 @@ CI, and cloud surfaces.
| [Gemini CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-gemini-cli) | Opt-in local OTLP | Prompts, tool calls, MCP activity, file operations, and approval-related events emitted through OTLP |
| [GitHub Copilot CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-github-copilot-cli) | MDM-managed OTLP HTTP | Prompt, session, tool, and approval-like activity emitted through Copilot CLI spans |
| [Grok Build](https://docs.asymptotelabs.ai/cli/supported-runtimes-grok-build) | Native hooks | Session, prompt, pre-tool, post-tool, failed tool, stop, session-end, command, and file telemetry |
-| [OpenCode](https://docs.asymptotelabs.ai/cli/supported-runtimes-opencode) | Managed plugin hooks | Chat messages, session events, command execution, permission activity, diffs, and errors |
+| [OpenCode](https://docs.asymptotelabs.ai/cli/supported-runtimes-opencode) | Managed plugin hooks | Prompts, assistant output/reasoning, model usage/cost, tool lifecycle/results, commands, file/web/MCP activity, approvals, and session errors |
| [VS Code](https://docs.asymptotelabs.ai/cli/supported-runtimes-vscode) | Copilot Chat OTel plus optional preview hooks | Copilot session, prompt, model, and tool activity through OTel; optional hooks for extra lifecycle and cross-agent detail |
##### Knowledge Worker Agent Harnesses
diff --git a/cli/beacon-hooks/cmd/opencode_event.go b/cli/beacon-hooks/cmd/opencode_event.go
index 631c6c0f..f59f8c00 100644
--- a/cli/beacon-hooks/cmd/opencode_event.go
+++ b/cli/beacon-hooks/cmd/opencode_event.go
@@ -1,8 +1,13 @@
package cmd
import (
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+ "strconv"
"strings"
+ hookdiff "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/diff"
"github.com/spf13/cobra"
)
@@ -25,54 +30,150 @@ func runOpenCodeEvent(cmd *cobra.Command, args []string) {
}
sessionID := resolveSessionID(input, "opencode")
logger := newHookLogger("opencode-event", "opencode", sessionID)
- action, category, severity, message, fields := opencodeEndpointEvent(input, sessionID)
- if action == "" {
- outputJSON(emptyResponse)
- return
+ for _, event := range opencodeEndpointEvents(input, sessionID) {
+ if event.action == "" {
+ continue
+ }
+ _ = logger.EndpointEvent(event.action, event.category, event.severity, event.message, event.fields)
}
- logger.EndpointEvent(action, category, severity, message, fields)
outputJSON(emptyResponse)
}
+type opencodeNormalizedEvent struct {
+ action string
+ category string
+ severity string
+ message string
+ fields map[string]interface{}
+}
+
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)
- applyWorkspaceFields(fields, input, "")
- fields["raw"] = map[string]interface{}{
- "opencode": input,
+ events := opencodeEndpointEvents(input, sessionID)
+ if len(events) == 0 {
+ return "", "", "", "", nil
}
- if model := opencodeModel(input); model != "" {
- fields["model"] = model
+ event := events[0]
+ return event.action, event.category, event.severity, event.message, event.fields
+}
+
+func opencodeEndpointEvents(input map[string]interface{}, sessionID string) []opencodeNormalizedEvent {
+ eventType := getFirstStr(input, "type", "event_type", "hook")
+ fields := opencodeBaseFields(input, sessionID)
+ one := func(action, category, severity, message string, values map[string]interface{}) []opencodeNormalizedEvent {
+ return []opencodeNormalizedEvent{{action: action, category: category, severity: severity, message: message, fields: values}}
}
switch eventType {
case "chat.message":
if prompt := opencodePromptText(input); prompt != "" {
fields["prompt"] = map[string]interface{}{"text": prompt}
+ fields["gen_ai"] = map[string]interface{}{
+ "input": map[string]interface{}{
+ "messages": []interface{}{map[string]interface{}{
+ "role": "user",
+ "parts": []interface{}{map[string]interface{}{"type": "text", "content": prompt}},
+ }},
+ },
+ }
+ fields["content"] = retainedContentFields(prompt)
+ }
+ return one("prompt.submitted", "prompt", "info", "Prompt submitted to opencode", fields)
+ case "tool.execute.before":
+ mergeMap(fields, opencodeToolFields(input, false))
+ return one("tool.invoked", "tool", "info", "opencode tool invoked", fields)
+ case "tool.execute.after":
+ mergeMap(fields, opencodeToolFields(input, true))
+ action, category := opencodeToolAction(input)
+ if action == "file.modified" {
+ if _, ok := fields["file"]; !ok {
+ action, category = "tool.completed", "tool"
+ }
+ }
+ return one(action, category, "info", opencodeToolMessage(action), fields)
+ case "message.updated":
+ info := opencodeMap(input, "message_info", "info")
+ if len(info) == 0 {
+ info = opencodeProperties(input)
+ info = opencodeMap(info, "info")
}
- return "prompt.submitted", "prompt", "info", "Prompt submitted to opencode", fields
+ if getFirstStr(info, "role") != "assistant" {
+ return nil
+ }
+ mergeMap(fields, opencodeAssistantFields(info))
+ severity := "info"
+ if opencodeMap(info, "error") != nil {
+ severity = "high"
+ }
+ return one("agent.response.completed", "session", severity, "opencode assistant response completed", fields)
+ case "message.part.updated":
+ part := opencodeMap(input, "part")
+ if len(part) == 0 {
+ part = opencodeMap(opencodeProperties(input), "part")
+ }
+ return opencodePartEvents(fields, part)
case "session.created":
- return "session.started", "session", "info", "opencode session started", fields
+ return one("session.started", "session", "info", "opencode session started", fields)
+ case "session.status":
+ status := opencodeMap(opencodeProperties(input), "status")
+ statusType := getFirstStr(status, "type")
+ switch statusType {
+ case "idle":
+ return one("session.ended", "session", "info", "opencode session idle", fields)
+ case "retry":
+ fields["error"] = map[string]interface{}{"type": "retry"}
+ return one("model.retry", "session", "medium", "opencode model retry", fields)
+ default:
+ return one("session.status", "session", "info", "opencode session "+firstNonEmpty(statusType, "status updated"), fields)
+ }
case "session.idle":
- return "session.ended", "session", "info", "opencode session ended", fields
+ return one("session.ended", "session", "info", "opencode session ended", fields)
case "session.error":
- return "tool.failed", "tool", "high", "opencode session error", fields
+ errorInfo := opencodeMap(opencodeProperties(input), "error")
+ if len(errorInfo) > 0 {
+ fields["error"] = map[string]interface{}{"type": firstNonEmpty(getFirstStr(errorInfo, "name", "type"), "session_error")}
+ }
+ return one("session.error", "session", "high", "opencode session error", fields)
case "session.diff":
- mergeMap(fields, opencodeDiffFields(input))
- return "file.modified", "file", "info", "opencode session diff observed", fields
+ return opencodeDiffEvents(input, fields)
+ case "file.edited", "file.watcher.updated":
+ properties := opencodeProperties(input)
+ path := getFirstStr(properties, "file", "path", "file_path", "filePath")
+ if path == "" || sessionID == "" {
+ return nil
+ }
+ operation := "modify"
+ if getFirstStr(properties, "event") == "unlink" {
+ operation = "delete"
+ }
+ fields["file"] = map[string]interface{}{
+ "path": path,
+ "operation": operation,
+ "language": strings.TrimPrefix(filepath.Ext(path), "."),
+ }
+ return one("file.modified", "file", "info", "opencode file change observed", fields)
+ case "command.execute.before":
+ if command := opencodeCommand(input); command != "" {
+ fields["command"] = map[string]interface{}{"command": command}
+ fields["tool"] = map[string]interface{}{"name": "command", "command": command}
+ }
+ return one("command.invoked", "command", "info", "opencode command invoked", 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":
+ return one("command.executed", "command", "info", "opencode command executed", fields)
+ case "permission.asked", "permission.v2.asked":
+ properties := opencodeProperties(input)
fields["approval"] = map[string]interface{}{"required": true, "decision": "requested"}
+ if permission := getFirstStr(properties, "permission"); permission != "" {
+ fields["approval"].(map[string]interface{})["reason"] = permission
+ }
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":
+ return one("approval.requested", "approval", "info", "opencode permission requested", fields)
+ case "permission.replied", "permission.updated", "permission.v2.replied":
decision := opencodeDecision(input)
if decision == "" {
decision = "unknown"
@@ -81,24 +182,45 @@ func opencodeEndpointEvent(input map[string]interface{}, sessionID string) (stri
if tool := opencodeToolName(input); tool != "" {
fields["tool"] = map[string]interface{}{"name": tool}
}
- return "approval.allowed", "approval", "info", "opencode permission " + decision, fields
+ action := opencodeApprovalAction(decision)
+ return one(action, "approval", "info", "opencode permission "+decision, fields)
default:
- return "", "", "", "", nil
+ return nil
}
}
func supportedOpenCodeEventTypes() []string {
return []string{
"chat.message",
+ "command.execute.before",
"command.executed",
+ "file.edited",
+ "file.watcher.updated",
+ "message.part.updated",
+ "message.updated",
"permission.asked",
"permission.replied",
"permission.updated",
+ "permission.v2.asked",
+ "permission.v2.replied",
"session.created",
"session.diff",
"session.error",
"session.idle",
+ "session.status",
+ "tool.execute.after",
+ "tool.execute.before",
+ }
+}
+
+func opencodeBaseFields(input map[string]interface{}, sessionID string) map[string]interface{} {
+ fields := sessionFields(sessionID, input)
+ applyWorkspaceFields(fields, input, "")
+ fields["raw"] = map[string]interface{}{"opencode": input}
+ if model := opencodeModel(input); model != "" {
+ fields["model"] = model
}
+ return fields
}
func opencodePromptText(input map[string]interface{}) string {
@@ -135,51 +257,424 @@ func opencodeModel(input map[string]interface{}) string {
if model := getFirstStr(input, "model"); model != "" {
return model
}
+ if provider, model := getFirstStr(input, "providerID", "provider_id"), getFirstStr(input, "modelID", "model_id"); provider != "" && model != "" {
+ return provider + "/" + model
+ }
model, _ := input["model_info"].(map[string]interface{})
if model == nil {
model, _ = input["modelInfo"].(map[string]interface{})
}
+ if model == nil {
+ model = opencodeMap(opencodeProperties(input), "info")
+ }
provider := getFirstStr(model, "providerID", "provider_id", "provider")
- name := getFirstStr(model, "modelID", "model_id", "id", "name")
+ name := getFirstStr(model, "modelID", "model_id")
+ if name == "" {
+ nested := opencodeMap(model, "model")
+ provider = firstNonEmpty(provider, getFirstStr(nested, "providerID", "provider_id", "provider"))
+ name = getFirstStr(nested, "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"))
+func opencodeToolFields(input map[string]interface{}, completed bool) map[string]interface{} {
+ toolName := opencodeToolName(input)
+ toolInput := opencodeMap(input, "tool_input", "toolInput")
+ toolResponse := opencodeMap(input, "tool_response", "toolResponse")
+ fields := toolFieldsWithResponse(toolName, toolInput, toolResponse)
+ callID := getFirstStr(input, "call_id", "callID")
+ call := map[string]interface{}{}
+ if len(toolInput) > 0 {
+ call["arguments"] = toolInput
+ }
+ if completed && len(toolResponse) > 0 {
+ if output, ok := toolResponse["output"]; ok {
+ call["result"] = output
+ } else {
+ call["result"] = toolResponse
+ }
+ }
+ if callID != "" {
+ call["id"] = callID
+ }
+ genAI := map[string]interface{}{
+ "operation": map[string]interface{}{"name": "execute_tool"},
+ "tool": map[string]interface{}{
+ "name": toolName,
+ "call": call,
+ },
+ }
+ fields["gen_ai"] = genAI
+ if duration, ok := firstToolIntAcross([]map[string]interface{}{input}, "duration_ms", "durationMs"); ok {
+ fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"duration_ms": duration})
+ }
+
+ if path := opencodeToolPath(toolInput); path != "" {
+ fields["file"] = map[string]interface{}{
+ "path": path,
+ "operation": fileOperation(toolName),
+ "language": strings.TrimPrefix(filepath.Ext(path), "."),
+ }
+ fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"name": toolName, "path": path})
+ }
+
+ if completed {
+ if action, _ := opencodeToolAction(input); action == "file.modified" {
+ path := opencodeToolPath(toolInput)
+ diffText := hookdiff.FromToolResponse(toolName, toolInput, toolResponse)
+ if diffText == "" {
+ diffText = firstToolString(toolInput, "content", "new_string", "newString")
+ }
+ if path != "" {
+ mergeMap(fields, diffFields(path, diffText))
+ file := fields["file"].(map[string]interface{})
+ file["operation"] = fileOperation(toolName)
+ }
+ }
+ if action, _ := opencodeToolAction(input); action == "command.executed" {
+ command := firstToolString(toolInput, "command", "cmd")
+ commandFields := map[string]interface{}{"command": command}
+ if output, ok := toolResponse["output"]; ok {
+ commandFields["output"] = output
+ }
+ if duration, ok := firstToolIntAcross([]map[string]interface{}{input}, "duration_ms", "durationMs"); ok {
+ commandFields["duration_ms"] = duration
+ }
+ if metadata := opencodeMap(toolResponse, "metadata"); len(metadata) > 0 {
+ if exitCode, ok := firstToolIntAcross([]map[string]interface{}{metadata}, "exit_code", "exitCode", "status"); ok {
+ commandFields["exit_code"] = exitCode
+ }
+ }
+ fields["command"] = commandFields
+ }
}
- return diffFields(path, diff)
+ if encoded, err := json.Marshal(map[string]interface{}{"input": toolInput, "response": toolResponse}); err == nil && len(encoded) > 0 {
+ fields["content"] = retainedContentFields(string(encoded))
+ }
+ return fields
}
func opencodeCommand(input map[string]interface{}) string {
- if command := getFirstStr(input, "command", "cmd"); command != "" {
+ if command := getFirstStr(input, "command", "cmd", "command_name"); command != "" {
+ if args := getFirstStr(input, "arguments"); args != "" {
+ return strings.TrimSpace(command + " " + args)
+ }
return command
}
- properties, _ := input["properties"].(map[string]interface{})
- return getFirstStr(properties, "command", "cmd")
+ properties := opencodeProperties(input)
+ command := getFirstStr(properties, "command", "cmd", "name")
+ if args := getFirstStr(properties, "arguments"); args != "" {
+ command = strings.TrimSpace(command + " " + args)
+ }
+ return command
}
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")
+ properties := opencodeProperties(input)
+ if tool := getFirstStr(properties, "tool", "tool_name", "toolName", "permission"); tool != "" {
+ return tool
+ }
+ part := opencodeMap(input, "part")
+ return getFirstStr(part, "tool")
}
func opencodeDecision(input map[string]interface{}) string {
- if decision := getFirstStr(input, "decision", "status"); decision != "" {
+ if decision := getFirstStr(input, "decision", "status", "reply"); decision != "" {
return decision
}
- properties, _ := input["properties"].(map[string]interface{})
- return getFirstStr(properties, "decision", "status")
+ properties := opencodeProperties(input)
+ return getFirstStr(properties, "decision", "status", "reply")
+}
+
+func opencodeToolAction(input map[string]interface{}) (string, string) {
+ name := strings.ToLower(opencodeToolName(input))
+ switch {
+ case strings.Contains(name, "mcp") || strings.HasPrefix(name, "list_mcp_") || strings.HasPrefix(name, "read_mcp_"):
+ return "mcp.tool_invoked", "mcp"
+ case name == "bash" || strings.Contains(name, "shell") || strings.Contains(name, "terminal"):
+ return "command.executed", "command"
+ case strings.Contains(name, "read"):
+ return "file.read", "file"
+ case strings.Contains(name, "edit") || strings.Contains(name, "write") || strings.Contains(name, "patch"):
+ return "file.modified", "file"
+ default:
+ return "tool.completed", "tool"
+ }
+}
+
+func opencodeToolMessage(action string) string {
+ switch action {
+ case "command.executed":
+ return "opencode shell command executed"
+ case "file.read":
+ return "opencode file read"
+ case "file.modified":
+ return "opencode file modified"
+ case "mcp.tool_invoked":
+ return "opencode MCP tool executed"
+ default:
+ return "opencode tool completed"
+ }
+}
+
+func opencodeToolPath(input map[string]interface{}) string {
+ path := firstToolString(input, "file_path", "filePath", "path", "target", "destination")
+ if path == "" {
+ path = firstToolString(input, "pattern")
+ }
+ return hookdiff.NormalizePath(path)
+}
+
+func opencodeAssistantFields(info map[string]interface{}) map[string]interface{} {
+ fields := map[string]interface{}{}
+ if model := opencodeModel(info); model != "" {
+ fields["model"] = model
+ }
+ genAI := map[string]interface{}{}
+ response := map[string]interface{}{}
+ if finish := getFirstStr(info, "finish"); finish != "" {
+ response["finish_reasons"] = []interface{}{finish}
+ }
+ if id := getFirstStr(info, "id"); id != "" {
+ response["id"] = id
+ }
+ if len(response) > 0 {
+ genAI["response"] = response
+ }
+ if usage := opencodeUsage(info); len(usage) > 0 {
+ genAI["usage"] = usage
+ }
+ if len(genAI) > 0 {
+ fields["gen_ai"] = genAI
+ }
+ if errInfo := opencodeMap(info, "error"); len(errInfo) > 0 {
+ fields["error"] = map[string]interface{}{"type": firstNonEmpty(getFirstStr(errInfo, "name", "type"), "assistant_error")}
+ }
+ return fields
+}
+
+func opencodeUsage(input map[string]interface{}) map[string]interface{} {
+ tokens := opencodeMap(input, "tokens")
+ if len(tokens) == 0 {
+ return nil
+ }
+ usage := map[string]interface{}{}
+ if value, ok := opencodeInt(tokens["input"]); ok {
+ usage["input_tokens"] = value
+ }
+ if value, ok := opencodeInt(tokens["output"]); ok {
+ usage["output_tokens"] = value
+ }
+ if value, ok := opencodeInt(tokens["reasoning"]); ok {
+ usage["reasoning"] = map[string]interface{}{"output_tokens": value}
+ }
+ cache := opencodeMap(tokens, "cache")
+ if value, ok := opencodeInt(cache["read"]); ok {
+ usage["cache_read"] = map[string]interface{}{"input_tokens": value}
+ }
+ if value, ok := opencodeInt(cache["write"]); ok {
+ usage["cache_creation"] = map[string]interface{}{"input_tokens": value}
+ }
+ if value, ok := opencodeFloat(input["cost"]); ok {
+ usage["cost_usd"] = value
+ }
+ return usage
+}
+
+func opencodePartEvents(base map[string]interface{}, part map[string]interface{}) []opencodeNormalizedEvent {
+ if len(part) == 0 {
+ return nil
+ }
+ fields := cloneOpenCodeFields(base)
+ partType := getFirstStr(part, "type")
+ switch partType {
+ case "text", "reasoning":
+ text := getFirstStr(part, "text")
+ if text == "" {
+ return nil
+ }
+ fields["gen_ai"] = map[string]interface{}{
+ "output": map[string]interface{}{
+ "messages": []interface{}{map[string]interface{}{
+ "role": "assistant",
+ "parts": []interface{}{map[string]interface{}{"type": partType, "content": text}},
+ }},
+ },
+ }
+ fields["content"] = retainedContentFields(text)
+ action, message := "agent.response", "opencode assistant response captured"
+ if partType == "reasoning" {
+ action, message = "agent.reasoning", "opencode agent reasoning captured"
+ }
+ return []opencodeNormalizedEvent{{action: action, category: "session", severity: "info", message: message, fields: fields}}
+ case "tool":
+ state := opencodeMap(part, "state")
+ status := getFirstStr(state, "status")
+ if status != "completed" && status != "error" {
+ return nil
+ }
+ toolInput := opencodeMap(state, "input")
+ response := map[string]interface{}{}
+ if output, ok := state["output"]; ok {
+ response["output"] = output
+ }
+ if metadata := opencodeMap(state, "metadata"); len(metadata) > 0 {
+ response["metadata"] = metadata
+ }
+ toolPayload := map[string]interface{}{
+ "type": "tool.execute.after",
+ "session_id": getFirstStr(part, "sessionID", "session_id"),
+ "tool_name": getFirstStr(part, "tool"),
+ "call_id": getFirstStr(part, "callID", "call_id"),
+ "tool_input": toolInput,
+ "tool_response": response,
+ }
+ if start, ok := opencodeInt(opencodeMap(state, "time")["start"]); ok {
+ if end, ok := opencodeInt(opencodeMap(state, "time")["end"]); ok && end >= start {
+ toolPayload["duration_ms"] = end - start
+ }
+ }
+ mergeMap(fields, opencodeToolFields(toolPayload, true))
+ if status == "error" {
+ errText := getFirstStr(state, "error")
+ fields["error"] = map[string]interface{}{"type": "tool_error"}
+ if errText != "" {
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"opencode_tool_error": errText})
+ fields["content"] = retainedContentFields(errText)
+ }
+ return []opencodeNormalizedEvent{{action: "tool.failed", category: "tool", severity: "high", message: "opencode tool failed", fields: fields}}
+ }
+ action, category := opencodeToolAction(toolPayload)
+ if action == "file.modified" {
+ if _, ok := fields["file"]; !ok {
+ action, category = "tool.completed", "tool"
+ }
+ }
+ return []opencodeNormalizedEvent{{action: action, category: category, severity: "info", message: opencodeToolMessage(action), fields: fields}}
+ case "retry":
+ fields["error"] = map[string]interface{}{"type": "model_retry"}
+ return []opencodeNormalizedEvent{{action: "model.retry", category: "session", severity: "medium", message: "opencode model retry", fields: fields}}
+ default:
+ return nil
+ }
+}
+
+func opencodeDiffEvents(input map[string]interface{}, base map[string]interface{}) []opencodeNormalizedEvent {
+ properties := opencodeProperties(input)
+ rawDiff, ok := properties["diff"]
+ if !ok {
+ rawDiff = input["diff"]
+ }
+ items, ok := rawDiff.([]interface{})
+ if !ok || len(items) == 0 {
+ return nil
+ }
+ var events []opencodeNormalizedEvent
+ for _, item := range items {
+ diffItem, ok := item.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ path := getFirstStr(diffItem, "file", "path", "file_path", "filePath")
+ before, after := getFirstStr(diffItem, "before"), getFirstStr(diffItem, "after")
+ additions, _ := opencodeInt(diffItem["additions"])
+ deletions, _ := opencodeInt(diffItem["deletions"])
+ if path == "" || (before == after && additions == 0 && deletions == 0) {
+ continue
+ }
+ diffText := ""
+ if before != "" || after != "" {
+ diffText = fmt.Sprintf("--- before\n%s\n+++ after\n%s", before, after)
+ }
+ fields := cloneOpenCodeFields(base)
+ mergeMap(fields, diffFields(path, diffText))
+ events = append(events, opencodeNormalizedEvent{
+ action: "file.modified", category: "file", severity: "info",
+ message: "opencode session diff observed", fields: fields,
+ })
+ }
+ return events
+}
+
+func opencodeApprovalAction(decision string) string {
+ switch strings.ToLower(strings.TrimSpace(decision)) {
+ case "once", "always", "accepted", "accept", "allow", "allowed", "approve", "approved":
+ return "approval.allowed"
+ case "reject", "rejected", "deny", "denied", "timeout":
+ return "approval.denied"
+ default:
+ return "approval.requested"
+ }
+}
+
+func opencodeProperties(input map[string]interface{}) map[string]interface{} {
+ if properties := opencodeMap(input, "properties", "data"); len(properties) > 0 {
+ return properties
+ }
+ event := opencodeMap(input, "event")
+ return opencodeMap(event, "properties", "data")
+}
+
+func opencodeMap(input map[string]interface{}, keys ...string) map[string]interface{} {
+ if input == nil {
+ return nil
+ }
+ for _, key := range keys {
+ if value, ok := input[key].(map[string]interface{}); ok {
+ return value
+ }
+ }
+ return nil
+}
+
+func opencodeInt(value interface{}) (int, bool) {
+ switch typed := value.(type) {
+ case int:
+ return typed, true
+ case int64:
+ return int(typed), true
+ case float64:
+ return int(typed), true
+ case json.Number:
+ result, err := typed.Int64()
+ return int(result), err == nil
+ case string:
+ result, err := strconv.Atoi(strings.TrimSpace(typed))
+ return result, err == nil
+ default:
+ return 0, false
+ }
+}
+
+func opencodeFloat(value interface{}) (float64, bool) {
+ switch typed := value.(type) {
+ case float64:
+ return typed, true
+ case int:
+ return float64(typed), true
+ case json.Number:
+ result, err := typed.Float64()
+ return result, err == nil
+ case string:
+ result, err := strconv.ParseFloat(strings.TrimSpace(typed), 64)
+ return result, err == nil
+ default:
+ return 0, false
+ }
+}
+
+func cloneOpenCodeFields(input map[string]interface{}) map[string]interface{} {
+ out := make(map[string]interface{}, len(input))
+ for key, value := range input {
+ out[key] = value
+ }
+ return out
}
func mergeMap(dst, src map[string]interface{}) {
diff --git a/cli/beacon-hooks/cmd/opencode_event_test.go b/cli/beacon-hooks/cmd/opencode_event_test.go
index c91a8315..6fe02f54 100644
--- a/cli/beacon-hooks/cmd/opencode_event_test.go
+++ b/cli/beacon-hooks/cmd/opencode_event_test.go
@@ -63,7 +63,34 @@ func TestOpenCodeEventFixtureRecordsPrompt(t *testing.T) {
}
}
-func TestOpenCodeEventIgnoresLegacyRetentionEnv(t *testing.T) {
+func TestOpenCodeFixtureContracts(t *testing.T) {
+ tests := []struct {
+ file string
+ action string
+ category string
+ }{
+ {file: "tool_execute_after_bash.json", action: "command.executed", category: "command"},
+ {file: "tool_part_error.json", action: "tool.failed", category: "tool"},
+ {file: "assistant_completed.json", action: "agent.response.completed", category: "session"},
+ {file: "session_diff.json", action: "file.modified", category: "file"},
+ {file: "permission_replied.json", action: "approval.denied", category: "approval"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.file, func(t *testing.T) {
+ input := readOpenCodeFixture(t, tt.file)
+ sessionID := resolveSessionID(input, "opencode")
+ action, category, _, _, fields := opencodeEndpointEvent(input, sessionID)
+ if action != tt.action || category != tt.category {
+ t.Fatalf("event = %s/%s, want %s/%s", action, category, tt.action, tt.category)
+ }
+ if fields["raw"] == nil {
+ t.Fatal("raw opencode payload missing")
+ }
+ })
+ }
+}
+
+func TestOpenCodeEventAppliesContentMetadataDespiteLegacyRetentionEnv(t *testing.T) {
setupHookConfigDirs(t)
platformFlag = "opencode"
logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
@@ -88,8 +115,9 @@ func TestOpenCodeEventIgnoresLegacyRetentionEnv(t *testing.T) {
if _, ok := raw["opencode"]; !ok {
t.Fatalf("legacy retention env should not omit raw opencode payload: %#v", raw)
}
- if _, ok := event["content"]; ok {
- t.Fatalf("legacy retention env should not emit content marker: %#v", event["content"])
+ content := event["content"].(map[string]interface{})
+ if content["retention"] != "full" || content["included"] != true {
+ t.Fatalf("content metadata = %#v, want full/included", content)
}
}
@@ -100,10 +128,13 @@ func TestOpenCodeEventMapsPermissionDecision(t *testing.T) {
"tool": "bash",
"decision": "accepted",
}
- _, category, _, _, eventFields := opencodeEndpointEvent(fields, "session-1")
+ action, category, _, _, eventFields := opencodeEndpointEvent(fields, "session-1")
if category != "approval" {
t.Fatalf("category = %q, want approval", category)
}
+ if action != "approval.allowed" {
+ t.Fatalf("action = %q, want approval.allowed", action)
+ }
approval := eventFields["approval"].(map[string]interface{})
if approval["decision"] != "accepted" {
t.Fatalf("approval.decision = %q, want accepted", approval["decision"])
@@ -118,7 +149,7 @@ func TestOpenCodeEventIgnoresUnsupportedEvents(t *testing.T) {
t.Setenv("BEACON_ENDPOINT_LOG", logPath)
out := runHookWithInput(t, runOpenCodeEvent, map[string]interface{}{
- "type": "message.updated",
+ "type": "installation.updated",
"session_id": "session-1",
})
if len(out) != 0 {
@@ -139,6 +170,225 @@ func TestOpenCodeEventIgnoresUnsupportedEvents(t *testing.T) {
assertNoEndpointLog(t, logPath)
}
+func TestOpenCodeToolLifecycleNormalization(t *testing.T) {
+ tests := []struct {
+ name string
+ tool string
+ input map[string]interface{}
+ response map[string]interface{}
+ action string
+ category string
+ }{
+ {
+ name: "bash", tool: "bash",
+ input: map[string]interface{}{"command": "git status --short"},
+ response: map[string]interface{}{"output": " M README.md", "metadata": map[string]interface{}{"exitCode": 0}},
+ action: "command.executed", category: "command",
+ },
+ {
+ name: "read", tool: "read",
+ input: map[string]interface{}{"filePath": "/repo/README.md"},
+ response: map[string]interface{}{"output": "Beacon"},
+ action: "file.read", category: "file",
+ },
+ {
+ name: "write", tool: "write",
+ input: map[string]interface{}{"filePath": "/repo/test.txt", "content": "token=fixture-secret"},
+ response: map[string]interface{}{"output": "ok"},
+ action: "file.modified", category: "file",
+ },
+ {
+ name: "webfetch", tool: "webfetch",
+ input: map[string]interface{}{"url": "https://example.com"},
+ response: map[string]interface{}{"output": "Example Domain"},
+ action: "tool.completed", category: "tool",
+ },
+ {
+ name: "mcp", tool: "mcp__github__get_issue",
+ input: map[string]interface{}{"owner": "asymptote-labs", "repo": "agent-beacon"},
+ response: map[string]interface{}{"output": "issue"},
+ action: "mcp.tool_invoked", category: "mcp",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ input := map[string]interface{}{
+ "type": "tool.execute.after",
+ "session_id": "ses_test",
+ "directory": "/repo",
+ "tool_name": tt.tool,
+ "call_id": "call_" + tt.name,
+ "duration_ms": 12,
+ "tool_input": tt.input,
+ "tool_response": tt.response,
+ }
+ action, category, _, _, fields := opencodeEndpointEvent(input, "ses_test")
+ if action != tt.action || category != tt.category {
+ t.Fatalf("event = %s/%s, want %s/%s", action, category, tt.action, tt.category)
+ }
+ genAI := fields["gen_ai"].(map[string]interface{})
+ tool := genAI["tool"].(map[string]interface{})
+ call := tool["call"].(map[string]interface{})
+ if call["id"] != "call_"+tt.name {
+ t.Fatalf("call id = %#v", call["id"])
+ }
+ if tt.category == "file" {
+ file := fields["file"].(map[string]interface{})
+ if file["path"] == "" {
+ t.Fatalf("file path missing: %#v", file)
+ }
+ }
+ })
+ }
+}
+
+func TestOpenCodeCompletedAssistantNormalizesUsageOnce(t *testing.T) {
+ input := map[string]interface{}{
+ "type": "message.updated",
+ "session_id": "ses_test",
+ "model": "moonshotai/kimi-k3",
+ "properties": map[string]interface{}{
+ "info": map[string]interface{}{
+ "id": "msg_1", "role": "assistant", "providerID": "moonshotai", "modelID": "kimi-k3",
+ "finish": "stop", "cost": 0.42,
+ "tokens": map[string]interface{}{
+ "input": 10, "output": 5, "reasoning": 2,
+ "cache": map[string]interface{}{"read": 7, "write": 1},
+ },
+ },
+ },
+ }
+ action, _, _, _, fields := opencodeEndpointEvent(input, "ses_test")
+ if action != "agent.response.completed" {
+ t.Fatalf("action = %q", action)
+ }
+ usage := fields["gen_ai"].(map[string]interface{})["usage"].(map[string]interface{})
+ if usage["input_tokens"] != 10 || usage["output_tokens"] != 5 || usage["cost_usd"] != 0.42 {
+ t.Fatalf("usage = %#v", usage)
+ }
+}
+
+func TestOpenCodePartNormalization(t *testing.T) {
+ for _, tt := range []struct {
+ partType string
+ action string
+ }{
+ {partType: "text", action: "agent.response"},
+ {partType: "reasoning", action: "agent.reasoning"},
+ } {
+ t.Run(tt.partType, func(t *testing.T) {
+ action, _, _, _, fields := opencodeEndpointEvent(map[string]interface{}{
+ "type": "message.part.updated",
+ "session_id": "ses_test",
+ "part": map[string]interface{}{
+ "type": tt.partType, "text": "token=part-secret",
+ },
+ }, "ses_test")
+ if action != tt.action {
+ t.Fatalf("action = %q, want %q", action, tt.action)
+ }
+ if fields["content"] == nil || fields["gen_ai"] == nil {
+ t.Fatalf("missing content/gen_ai: %#v", fields)
+ }
+ })
+ }
+}
+
+func TestOpenCodeStructuredDiffSuppressesEmptyAndEmitsChangedFiles(t *testing.T) {
+ base := map[string]interface{}{
+ "type": "session.diff",
+ "session_id": "ses_test",
+ "properties": map[string]interface{}{"diff": []interface{}{}},
+ }
+ if events := opencodeEndpointEvents(base, "ses_test"); len(events) != 0 {
+ t.Fatalf("empty diff emitted events: %#v", events)
+ }
+
+ base["properties"] = map[string]interface{}{"diff": []interface{}{
+ map[string]interface{}{"file": "/repo/a.go", "before": "old", "after": "new", "additions": 1, "deletions": 1},
+ map[string]interface{}{"file": "/repo/unchanged.go", "before": "same", "after": "same", "additions": 0, "deletions": 0},
+ }}
+ events := opencodeEndpointEvents(base, "ses_test")
+ if len(events) != 1 {
+ t.Fatalf("events = %d, want 1", len(events))
+ }
+ file := events[0].fields["file"].(map[string]interface{})
+ if file["path"] != "/repo/a.go" || file["diff_hash"] == "" {
+ t.Fatalf("file = %#v", file)
+ }
+}
+
+func TestOpenCodePermissionRepliesMapAllowAndDeny(t *testing.T) {
+ for _, tt := range []struct {
+ reply string
+ action string
+ }{
+ {reply: "once", action: "approval.allowed"},
+ {reply: "always", action: "approval.allowed"},
+ {reply: "reject", action: "approval.denied"},
+ {reply: "timeout", action: "approval.denied"},
+ {reply: "unknown", action: "approval.requested"},
+ } {
+ action, _, _, _, _ := opencodeEndpointEvent(map[string]interface{}{
+ "type": "permission.replied",
+ "session_id": "ses_test",
+ "properties": map[string]interface{}{"reply": tt.reply},
+ }, "ses_test")
+ if action != tt.action {
+ t.Fatalf("reply %q action = %q, want %q", tt.reply, action, tt.action)
+ }
+ }
+}
+
+func TestOpenCodeTidyPlanetTraceReplay(t *testing.T) {
+ payloads := []map[string]interface{}{
+ {"type": "chat.message", "session_id": "ses_tidy", "output": map[string]interface{}{"parts": []interface{}{map[string]interface{}{"type": "text", "text": "hi kimi"}}}},
+ {"type": "chat.message", "session_id": "ses_tidy", "output": map[string]interface{}{"parts": []interface{}{map[string]interface{}{"type": "text", "text": "summarize this repo"}}}},
+ {"type": "tool.execute.before", "session_id": "ses_tidy", "tool_name": "read", "call_id": "call_read", "tool_input": map[string]interface{}{"filePath": "/repo/README.md"}},
+ {"type": "tool.execute.after", "session_id": "ses_tidy", "tool_name": "read", "call_id": "call_read", "tool_input": map[string]interface{}{"filePath": "/repo/README.md"}, "tool_response": map[string]interface{}{"output": "Beacon"}},
+ {"type": "tool.execute.before", "session_id": "ses_tidy", "tool_name": "glob", "call_id": "call_glob", "tool_input": map[string]interface{}{"pattern": "**/README.md"}},
+ {"type": "tool.execute.after", "session_id": "ses_tidy", "tool_name": "glob", "call_id": "call_glob", "tool_input": map[string]interface{}{"pattern": "**/README.md"}, "tool_response": map[string]interface{}{"output": "/repo/README.md"}},
+ {"type": "chat.message", "session_id": "ses_tidy", "output": map[string]interface{}{"parts": []interface{}{map[string]interface{}{"type": "text", "text": "look up NYC weather"}}}},
+ {"type": "tool.execute.before", "session_id": "ses_tidy", "tool_name": "webfetch", "call_id": "call_web", "tool_input": map[string]interface{}{"url": "https://example.com/weather"}},
+ {"type": "tool.execute.after", "session_id": "ses_tidy", "tool_name": "webfetch", "call_id": "call_web", "tool_input": map[string]interface{}{"url": "https://example.com/weather"}, "tool_response": map[string]interface{}{"output": "sunny"}},
+ {"type": "chat.message", "session_id": "ses_tidy", "output": map[string]interface{}{"parts": []interface{}{map[string]interface{}{"type": "text", "text": "persist this to a local file"}}}},
+ {"type": "tool.execute.before", "session_id": "ses_tidy", "tool_name": "write", "call_id": "call_write", "tool_input": map[string]interface{}{"filePath": "/repo/weather.md", "content": "sunny"}},
+ {"type": "tool.execute.after", "session_id": "ses_tidy", "tool_name": "write", "call_id": "call_write", "tool_input": map[string]interface{}{"filePath": "/repo/weather.md", "content": "sunny"}, "tool_response": map[string]interface{}{"output": "ok"}},
+ {"type": "chat.message", "session_id": "ses_tidy", "output": map[string]interface{}{"parts": []interface{}{map[string]interface{}{"type": "text", "text": "now delete it"}}}},
+ {"type": "tool.execute.before", "session_id": "ses_tidy", "tool_name": "bash", "call_id": "call_delete", "tool_input": map[string]interface{}{"command": "rm /repo/weather.md"}},
+ {"type": "tool.execute.after", "session_id": "ses_tidy", "tool_name": "bash", "call_id": "call_delete", "tool_input": map[string]interface{}{"command": "rm /repo/weather.md"}, "tool_response": map[string]interface{}{"output": "", "metadata": map[string]interface{}{"exitCode": 0}}},
+ }
+ var actions []string
+ var calls = map[string]int{}
+ for _, payload := range payloads {
+ for _, event := range opencodeEndpointEvents(payload, "ses_tidy") {
+ actions = append(actions, event.action)
+ genAI, _ := event.fields["gen_ai"].(map[string]interface{})
+ tool, _ := genAI["tool"].(map[string]interface{})
+ call, _ := tool["call"].(map[string]interface{})
+ if id, _ := call["id"].(string); id != "" {
+ calls[id]++
+ }
+ }
+ }
+ want := []string{
+ "prompt.submitted", "prompt.submitted",
+ "tool.invoked", "file.read",
+ "tool.invoked", "tool.completed",
+ "prompt.submitted", "tool.invoked", "tool.completed",
+ "prompt.submitted", "tool.invoked", "file.modified",
+ "prompt.submitted", "tool.invoked", "command.executed",
+ }
+ if strings.Join(actions, ",") != strings.Join(want, ",") {
+ t.Fatalf("actions:\n got %v\nwant %v", actions, want)
+ }
+ for _, id := range []string{"call_read", "call_glob", "call_web", "call_write", "call_delete"} {
+ if calls[id] != 2 {
+ t.Fatalf("%s appears %d times, want invocation and terminal event", id, calls[id])
+ }
+ }
+}
+
func TestOpenCodeForwardedEventsMatchGoIngestion(t *testing.T) {
source, err := os.ReadFile(filepath.Join("..", "..", "beacon", "internal", "endpoint", "hooks", "assets", "opencode", "beacon.ts"))
if err != nil {
@@ -164,16 +414,18 @@ func assertNoEndpointLog(t *testing.T, path string) {
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])
+ var events []string
+ for _, setName := range []string{"directHookTypes", "forwardedEvents"} {
+ re := regexp.MustCompile(`(?s)` + setName + ` = new Set\(\[(.*?)\]\)`)
+ match := re.FindStringSubmatch(source)
+ if len(match) != 2 {
+ t.Fatalf("%s list not found in plugin source", setName)
+ }
+ itemRE := regexp.MustCompile(`"([^"]+)"`)
+ matches := itemRE.FindAllStringSubmatch(match[1], -1)
+ for _, match := range matches {
+ events = append(events, match[1])
+ }
}
return events
}
diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
index d44f128f..daa726ab 100644
--- a/cli/beacon-hooks/internal/logging/endpoint_event_test.go
+++ b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
@@ -42,6 +42,48 @@ func TestEndpointEventStillWritesStructuredTelemetry(t *testing.T) {
}
}
+func TestEndpointEventCompactsOversizedRetainedContent(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ large := make([]interface{}, 40)
+ for i := range large {
+ large[i] = strings.Repeat("x", 4096)
+ }
+ fields := map[string]interface{}{
+ "session": map[string]interface{}{"id": "ses_large"},
+ "gen_ai": map[string]interface{}{
+ "tool": map[string]interface{}{
+ "name": "read",
+ "call": map[string]interface{}{"id": "call_large", "result": large},
+ },
+ },
+ "content": map[string]interface{}{"retention": "full", "included": true, "bytes": 163840},
+ }
+
+ logger := NewLoggerForPlatform("opencode-event", "opencode")
+ if err := logger.EndpointEvent("tool.completed", "tool", "info", "opencode tool completed", fields); err != nil {
+ t.Fatalf("EndpointEvent returned error: %v", err)
+ }
+ data, err := os.ReadFile(logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(data) > 64*1024 {
+ t.Fatalf("event size = %d", len(data))
+ }
+ var event map[string]interface{}
+ if err := json.Unmarshal(data, &event); err != nil {
+ t.Fatal(err)
+ }
+ if event["field_truncated"] != true {
+ t.Fatalf("field_truncated = %#v", event["field_truncated"])
+ }
+ content := event["content"].(map[string]interface{})
+ if content["included"] != false || content["truncated"] != true {
+ t.Fatalf("content = %#v", content)
+ }
+}
+
func TestEndpointEventCreatesSharedRuntimeFilesDespiteUmask(t *testing.T) {
oldUmask := syscall.Umask(0022)
t.Cleanup(func() {
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index 6bc5cbac..1a9eab06 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -230,9 +230,42 @@ func writeEndpointJSON(path string, event map[string]interface{}) error {
return err
}
}
+ if len(data) > 64*1024 {
+ compactEndpointContent(event)
+ data, err = json.Marshal(sanitizeEndpointMap(event))
+ if err != nil {
+ return err
+ }
+ }
+ if len(data) > 64*1024 {
+ return fmt.Errorf("endpoint event exceeds 64 KiB after content compaction")
+ }
return appendEndpointJSONL(path, append(data, '\n'), defaultEndpointRotateBytes, defaultEndpointRotateArchives)
}
+func compactEndpointContent(event map[string]interface{}) {
+ if file, ok := event["file"].(map[string]interface{}); ok {
+ delete(file, "diff")
+ }
+ if command, ok := event["command"].(map[string]interface{}); ok {
+ delete(command, "output")
+ }
+ if genAI, ok := event["gen_ai"].(map[string]interface{}); ok {
+ delete(genAI, "input")
+ delete(genAI, "output")
+ if tool, ok := genAI["tool"].(map[string]interface{}); ok {
+ if call, ok := tool["call"].(map[string]interface{}); ok {
+ delete(call, "arguments")
+ delete(call, "result")
+ }
+ }
+ }
+ if content, ok := event["content"].(map[string]interface{}); ok {
+ content["included"] = false
+ content["truncated"] = true
+ }
+}
+
func endpointLogPath() string {
if path := firstEnv("BEACON_ENDPOINT_LOG", "BEACON_CLOUD_LOG_PATH", "BEACON_LOG_PATH", "BEACON_RUNTIME_LOG"); path != "" {
return path
diff --git a/cli/beacon-hooks/testdata/opencode/README.md b/cli/beacon-hooks/testdata/opencode/README.md
index b274f0c0..127b66b3 100644
--- a/cli/beacon-hooks/testdata/opencode/README.md
+++ b/cli/beacon-hooks/testdata/opencode/README.md
@@ -1,18 +1,17 @@
# opencode payload fixtures
-This directory is reserved for captured opencode plugin payload fixtures.
+These sanitized payloads follow the OpenCode 1.18.3 runtime schemas captured on
+2026-07-18. They intentionally preserve runtime field names even where the
+generated `@opencode-ai/plugin` SDK types differ.
-Capture representative payloads for:
+Covered payloads include:
- `chat.message`
-- `session.created`
-- `session.idle`
-- `session.error`
-- `session.diff`
-- `command.executed`
-- `permission.asked`
-- `permission.replied`
-- `permission.updated`
+- `tool.execute.after` for a Bash command
+- terminal error `message.part.updated`
+- completed assistant `message.updated` with usage and runtime cost
+- structured multi-file-capable `session.diff`
+- rejected `permission.replied`
Keep secrets and real prompt content out of fixtures. Use sanitized payloads that
preserve the field shape needed by `beacon-hooks --platform opencode
diff --git a/cli/beacon-hooks/testdata/opencode/assistant_completed.json b/cli/beacon-hooks/testdata/opencode/assistant_completed.json
new file mode 100644
index 00000000..6ed246fb
--- /dev/null
+++ b/cli/beacon-hooks/testdata/opencode/assistant_completed.json
@@ -0,0 +1,29 @@
+{
+ "type": "message.updated",
+ "session_id": "ses_fixture",
+ "properties": {
+ "sessionID": "ses_fixture",
+ "info": {
+ "id": "msg_assistant",
+ "parentID": "msg_user",
+ "role": "assistant",
+ "providerID": "moonshotai",
+ "modelID": "kimi-k3",
+ "finish": "stop",
+ "cost": 0.0123,
+ "tokens": {
+ "input": 100,
+ "output": 20,
+ "reasoning": 5,
+ "cache": {
+ "read": 40,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 100,
+ "completed": 200
+ }
+ }
+ }
+}
diff --git a/cli/beacon-hooks/testdata/opencode/permission_replied.json b/cli/beacon-hooks/testdata/opencode/permission_replied.json
new file mode 100644
index 00000000..5d943f6c
--- /dev/null
+++ b/cli/beacon-hooks/testdata/opencode/permission_replied.json
@@ -0,0 +1,9 @@
+{
+ "type": "permission.replied",
+ "session_id": "ses_fixture",
+ "properties": {
+ "sessionID": "ses_fixture",
+ "requestID": "per_fixture",
+ "reply": "reject"
+ }
+}
diff --git a/cli/beacon-hooks/testdata/opencode/session_diff.json b/cli/beacon-hooks/testdata/opencode/session_diff.json
new file mode 100644
index 00000000..bf1d726d
--- /dev/null
+++ b/cli/beacon-hooks/testdata/opencode/session_diff.json
@@ -0,0 +1,16 @@
+{
+ "type": "session.diff",
+ "session_id": "ses_fixture",
+ "properties": {
+ "sessionID": "ses_fixture",
+ "diff": [
+ {
+ "file": "/repo/README.md",
+ "before": "old",
+ "after": "new",
+ "additions": 1,
+ "deletions": 1
+ }
+ ]
+ }
+}
diff --git a/cli/beacon-hooks/testdata/opencode/tool_execute_after_bash.json b/cli/beacon-hooks/testdata/opencode/tool_execute_after_bash.json
new file mode 100644
index 00000000..490b5de3
--- /dev/null
+++ b/cli/beacon-hooks/testdata/opencode/tool_execute_after_bash.json
@@ -0,0 +1,18 @@
+{
+ "type": "tool.execute.after",
+ "session_id": "ses_fixture",
+ "directory": "/repo",
+ "tool_name": "bash",
+ "call_id": "call_bash",
+ "duration_ms": 15,
+ "tool_input": {
+ "command": "git status --short"
+ },
+ "tool_response": {
+ "title": "git status",
+ "output": " M README.md",
+ "metadata": {
+ "exitCode": 0
+ }
+ }
+}
diff --git a/cli/beacon-hooks/testdata/opencode/tool_part_error.json b/cli/beacon-hooks/testdata/opencode/tool_part_error.json
new file mode 100644
index 00000000..7f8201a1
--- /dev/null
+++ b/cli/beacon-hooks/testdata/opencode/tool_part_error.json
@@ -0,0 +1,23 @@
+{
+ "type": "message.part.updated",
+ "session_id": "ses_fixture",
+ "part": {
+ "id": "prt_tool_error",
+ "messageID": "msg_fixture",
+ "sessionID": "ses_fixture",
+ "callID": "call_read",
+ "type": "tool",
+ "tool": "read",
+ "state": {
+ "status": "error",
+ "input": {
+ "filePath": "/repo/missing.txt"
+ },
+ "error": "file not found",
+ "time": {
+ "start": 100,
+ "end": 125
+ }
+ }
+ }
+}
diff --git a/cli/beacon/README.md b/cli/beacon/README.md
index 7a476149..4f7b475b 100644
--- a/cli/beacon/README.md
+++ b/cli/beacon/README.md
@@ -522,11 +522,12 @@ tooling, not in Beacon endpoint configuration.
```
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.
+`~/.config/opencode/plugins/beacon.ts`. It captures prompts, completed assistant
+text/reasoning, model usage, correlated tool input/results, commands, file,
+web/MCP, approval, and lifecycle events through OpenCode's plugin hooks. Beacon
+handles normalization, retention, redaction, event-size controls, 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 Code supports two Beacon setup paths. `beacon endpoint install --harness claude`
configures Claude Code's local OpenTelemetry export to Beacon's collector.
diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
index c14c217b..4ae46406 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
@@ -4,9 +4,24 @@
const beaconCommand = "__BEACON_COMMAND__"
const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"
+const sendTimeoutMs = 2000
+const directHookTypes = new Set([
+ "chat.message",
+ "command.execute.before",
+ "tool.execute.before",
+ "tool.execute.after",
+])
const forwardedEvents = new Set([
+ "file.edited",
+ "file.watcher.updated",
+ "message.part.updated",
+ "message.part.delta",
+ "message.updated",
+ "permission.v2.asked",
+ "permission.v2.replied",
"session.created",
"session.idle",
+ "session.status",
"session.error",
"session.diff",
"command.executed",
@@ -32,15 +47,25 @@ async function debugLog(client, message, extra) {
}
async function sendToBeacon(client, payload) {
+ let proc
try {
- const proc = Bun.spawn(["/bin/sh", "-lc", beaconCommand], {
+ 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
+ const outcome = await Promise.race([
+ proc.exited.then((code) => ({ code })),
+ Bun.sleep(sendTimeoutMs).then(() => ({ timeout: true })),
+ ])
+ if ("timeout" in outcome) {
+ proc.kill()
+ await debugLog(client, "Beacon hook command timed out", { type: payload?.type })
+ return
+ }
+ const code = outcome.code
if (code !== 0) {
await debugLog(client, "Beacon hook command exited non-zero", { code, type: payload?.type })
}
@@ -54,7 +79,11 @@ async function sendToBeacon(client, payload) {
}
function sessionID(value) {
- return value?.sessionID || value?.session_id || value?.id || value?.session?.id || value?.info?.sessionID || ""
+ const direct = value?.sessionID || value?.session_id || value?.session?.id || value?.info?.sessionID
+ if (direct) return direct
+ if (typeof value?.id === "string" && value.id.startsWith("ses_")) return value.id
+ if (typeof value?.info?.id === "string" && value.info.id.startsWith("ses_")) return value.info.id
+ return ""
}
function modelName(value) {
@@ -64,8 +93,80 @@ function modelName(value) {
return model.modelID || model.id || model.name || ""
}
+function filePath(value) {
+ return (
+ value?.filePath ||
+ value?.file_path ||
+ value?.path ||
+ value?.file ||
+ value?.target ||
+ value?.destination ||
+ ""
+ )
+}
+
+function isFileMutationTool(tool) {
+ const name = String(tool || "").toLowerCase()
+ return ["edit", "write", "patch", "apply_patch", "create"].some((part) => name.includes(part))
+}
+
export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {
const context = { project, directory, worktree }
+ const activeCalls = new Map()
+ const completedCalls = new Set()
+ const emittedParts = new Set()
+ const pendingParts = new Map()
+ const partDeltas = new Map()
+ const messageModels = new Map()
+ const recentFilePaths = new Map()
+ let eventQueue = Promise.resolve()
+
+ const payload = (type, values = {}) => ({ type, ...values, ...context })
+ const enqueue = (value) => {
+ eventQueue = eventQueue
+ .then(() => sendToBeacon(client, value))
+ .catch((err) => debugLog(client, "Beacon event queue failed", { error: String(err), type: value?.type }))
+ return eventQueue
+ }
+ const rememberFilePath = (tool, args) => {
+ if (!isFileMutationTool(tool)) return
+ const path = filePath(args)
+ if (path) recentFilePaths.set(path, Date.now())
+ }
+ const partKey = (part) => `${part?.sessionID || ""}:${part?.messageID || ""}:${part?.id || ""}`
+ const emitPart = (part, sid, model) => {
+ if (!part) return
+ const key = partKey(part)
+ if (emittedParts.has(key)) return
+ const next = structuredClone(part)
+ const delta = partDeltas.get(key)
+ if ((next.type === "text" || next.type === "reasoning") && !next.text && delta) next.text = delta
+ if (next.type === "tool") {
+ const status = next.state?.status
+ if (status !== "completed" && status !== "error") return
+ if (status === "completed" && completedCalls.has(next.callID)) return
+ } else if (next.type === "text" || next.type === "reasoning") {
+ if (!next.time?.end) {
+ pendingParts.set(key, { part: next, session_id: sid, model })
+ return
+ }
+ } else if (next.type !== "retry") {
+ return
+ }
+ emittedParts.add(key)
+ pendingParts.delete(key)
+ partDeltas.delete(key)
+ void enqueue(payload("message.part.updated", { session_id: sid, model, part: next }))
+ }
+ const flushParts = (sid) => {
+ for (const [key, item] of pendingParts) {
+ if (item.session_id !== sid) continue
+ const part = { ...item.part, time: { ...(item.part.time || {}), end: Date.now() } }
+ pendingParts.delete(key)
+ emitPart(part, sid, item.model)
+ }
+ }
+
return {
"chat.message": async (input, output) => {
await sendToBeacon(client, {
@@ -77,19 +178,100 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
...context,
})
},
+ "command.execute.before": async (input, output) => {
+ await sendToBeacon(
+ client,
+ payload("command.execute.before", {
+ session_id: sessionID(input),
+ command_name: input?.command,
+ arguments: input?.arguments,
+ parts: output?.parts,
+ }),
+ )
+ },
+ "tool.execute.before": async (input, output) => {
+ activeCalls.set(input?.callID, {
+ tool: input?.tool,
+ args: structuredClone(output?.args || {}),
+ started_at: Date.now(),
+ })
+ await sendToBeacon(
+ client,
+ payload("tool.execute.before", {
+ session_id: sessionID(input),
+ tool_name: input?.tool,
+ call_id: input?.callID,
+ tool_input: output?.args || {},
+ }),
+ )
+ },
+ "tool.execute.after": async (input, output) => {
+ const active = activeCalls.get(input?.callID)
+ const args = input?.args || active?.args || {}
+ rememberFilePath(input?.tool, args)
+ await sendToBeacon(
+ client,
+ payload("tool.execute.after", {
+ session_id: sessionID(input),
+ tool_name: input?.tool,
+ call_id: input?.callID,
+ duration_ms: active?.started_at ? Date.now() - active.started_at : undefined,
+ tool_input: args,
+ tool_response: output,
+ }),
+ )
+ activeCalls.delete(input?.callID)
+ completedCalls.add(input?.callID)
+ },
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,
- })
+ const properties = event?.properties || event?.data || {}
+ const sid = sessionID(properties)
+ const info = properties?.info || {}
+ if (type === "message.updated") {
+ if (info?.role !== "assistant") return
+ const model = modelName(info)
+ if (info?.id && model) messageModels.set(info.id, model)
+ if (!info?.time?.completed && !info?.error) return
+ }
+ if (type === "message.part.delta") {
+ const key = `${sid}:${properties?.messageID || ""}:${properties?.partID || ""}`
+ partDeltas.set(key, (partDeltas.get(key) || "") + (properties?.delta || ""))
+ return
+ }
+ if (type === "message.part.updated") {
+ const part = properties?.part
+ emitPart(part, sid, messageModels.get(part?.messageID) || "")
+ return
+ }
+ if (type === "session.status" && properties?.status?.type === "idle") flushParts(sid)
+ if (type === "session.idle") flushParts(sid)
+ if (type === "session.diff") {
+ const diffs = Array.isArray(properties?.diff) ? properties.diff : []
+ const now = Date.now()
+ const filtered = diffs.filter((item) => {
+ const path = filePath(item)
+ if (!path) return false
+ const seen = recentFilePaths.get(path)
+ if (seen && now - seen < 5000) return false
+ return item?.before !== item?.after || item?.additions || item?.deletions
+ })
+ if (filtered.length === 0) return
+ properties.diff = filtered
+ }
+ if (type === "file.edited" || type === "file.watcher.updated") {
+ if (!sid) return
+ }
+ void enqueue(
+ payload(type, {
+ session_id: sid,
+ model: modelName(info || properties),
+ properties,
+ event,
+ }),
+ )
},
}
}
diff --git a/cli/beacon/internal/endpoint/hooks/opencode.go b/cli/beacon/internal/endpoint/hooks/opencode.go
index f2cbe586..d8fb9a13 100644
--- a/cli/beacon/internal/endpoint/hooks/opencode.go
+++ b/cli/beacon/internal/endpoint/hooks/opencode.go
@@ -72,6 +72,12 @@ func opencodeStatusFromRuntime(status runtimeStatus) OpenCodeStatus {
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
+ }
+ data, err := os.ReadFile(out.PluginPath)
+ if err != nil || !strings.Contains(string(data), out.BinaryPath) || strings.Contains(string(data), "__BEACON_") {
+ out.Installed = false
+ out.Message = fmt.Sprintf("opencode plugin at %s does not reference the active Beacon hook binary", out.PluginPath)
}
}
return out
@@ -86,6 +92,13 @@ func opencodeRootPluginSourcePath() string {
}
func installOpenCodePlugin(path, binaryPath, logPath, configPath string) error {
+ if existing, err := os.ReadFile(path); err == nil {
+ if !strings.Contains(string(existing), opencodeManagedPluginMarker) {
+ return fmt.Errorf("refusing to overwrite unmanaged opencode plugin at %s", path)
+ }
+ } else if !os.IsNotExist(err) {
+ return err
+ }
plugin, err := renderOpenCodePlugin(binaryPath, logPath, configPath)
if err != nil {
return err
diff --git a/cli/beacon/internal/endpoint/hooks/opencode_test.go b/cli/beacon/internal/endpoint/hooks/opencode_test.go
index 949f5098..d6389766 100644
--- a/cli/beacon/internal/endpoint/hooks/opencode_test.go
+++ b/cli/beacon/internal/endpoint/hooks/opencode_test.go
@@ -27,14 +27,31 @@ func TestInstallOpenCodePluginWritesManagedPlugin(t *testing.T) {
"BEACON_ENDPOINT_LOG='/tmp/runtime.jsonl'",
"BEACON_ENDPOINT_CONFIG='/tmp/config.json'",
"forwardedEvents",
+ "tool.execute.before",
+ "tool.execute.after",
+ "message.updated",
+ "message.part.updated",
"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 TestInstallOpenCodePluginRefusesToOverwriteUnmanagedPlugin(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "beacon.ts")
+ original := "export const UserPlugin = async () => ({})"
+ if err := os.WriteFile(path, []byte(original), 0644); err != nil {
+ t.Fatal(err)
+ }
+ err := installOpenCodePlugin(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json")
+ if err == nil || !strings.Contains(err.Error(), "refusing to overwrite unmanaged") {
+ t.Fatalf("install error = %v", err)
+ }
+ data, readErr := os.ReadFile(path)
+ if readErr != nil || string(data) != original {
+ t.Fatalf("unmanaged plugin changed: err=%v body=%q", readErr, data)
}
}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index e633a194..9923448e 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -13,6 +13,17 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
### Unreleased
+- **Full OpenCode agent traces** · Expanded the managed OpenCode plugin to
+ capture correlated prompt, assistant text/reasoning, model usage/cost, tool
+ invocation/result/failure, command, file, web/MCP, approval, and session
+ lifecycle telemetry.
+- **Accurate OpenCode file and approval events** · Empty or pathless
+ `session.diff` payloads no longer become file modifications, structured diffs
+ retain real agent paths, and rejected permission replies normalize to
+ `approval.denied`.
+- **Bounded fail-open plugin delivery** · OpenCode event delivery is ordered,
+ time-bounded, locally redacted/truncated, collision-safe during install, and
+ covered by Bun, Go, fixture, and macOS smoke tests.
- **Cursor Cloud prompt telemetry** · Committed `beforeSubmitPrompt` project
hooks now retain observed follow-up prompts and immediately refresh the
per-run object-storage snapshot, including prompt-only turns after hooks
diff --git a/docs/runtimes/opencode.mdx b/docs/runtimes/opencode.mdx
index 030e4684..ebc94f00 100644
--- a/docs/runtimes/opencode.mdx
+++ b/docs/runtimes/opencode.mdx
@@ -20,6 +20,9 @@ Before enabling OpenCode telemetry, make sure:
Asymptote installs an owned OpenCode plugin at `~/.config/opencode/plugins/beacon.ts` for user-level hooks or `./.opencode/plugins/beacon.ts` for project-level hooks. The plugin forwards supported OpenCode hook payloads to Asymptote's hook adapter.
+The integration is plugin-based. OpenCode native OTLP is not configured or
+required by Beacon.
+
## Discovery and status
Asymptote detects OpenCode through the `opencode` executable or `~/.config/opencode`, then checks for Asymptote plugin configuration.
@@ -39,15 +42,44 @@ beacon endpoint hooks install --harness opencode
| Area | Support |
|------|---------|
| Prompt telemetry | Supported through `chat.message` hooks |
-| Command, tool, and file telemetry | Supported for chat messages, session events, command execution, permission activity, diffs, and errors where OpenCode exposes payloads |
+| Assistant output and reasoning | Completed text and reasoning parts, correlated by session/message/part IDs |
+| 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/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 |
| Local JSONL and dashboard | Supported |
| MDM deployment | Supported for the endpoint agent; OpenCode plugins are installed separately in the logged-in user's context |
+## Data handling
+
+OpenCode prompts, completed assistant text and reasoning, tool arguments/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 that exceed the 64 KiB limit drop raw and
+retained content while preserving 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.
+
## Deployment notes
Restart OpenCode after installing or removing hooks so new sessions pick up the updated plugin configuration.
-For local troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment that launches OpenCode to emit best-effort plugin debug logs. Asymptote telemetry should not interrupt OpenCode execution if the hook command fails.
+For 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.
+
+Validate a system-mode installation after restarting OpenCode:
+
+```bash
+/opt/beacon/bin/beacon endpoint hooks status --harness opencode --level user
+/opt/beacon/bin/beacon endpoint doctor --system
+/opt/beacon/bin/beacon endpoint dashboard --system --open
+```
## Related
diff --git a/docs/security/data-inventory.mdx b/docs/security/data-inventory.mdx
index 4c83a32b..44c9ff75 100644
--- a/docs/security/data-inventory.mdx
+++ b/docs/security/data-inventory.mdx
@@ -15,7 +15,7 @@ Beacon writes normalized endpoint events only when supported runtimes provide te
| Codex CLI | Local OTLP logs plus optional inventory hooks | Session, prompt, approval, and tool-result activity from Codex semantic logs; inventory heartbeat triggers from hooks |
| Gemini CLI | Opt-in local OTLP | Prompts, tool calls, MCP activity, file operations, and approval-related events emitted through OTLP |
| Grok Build | Native hooks | Session, prompt, pre-tool, post-tool, failed tool, stop, session-end, command, and file telemetry |
-| OpenCode | Managed plugin hooks | Chat messages, session events, command execution, permission activity, diffs, and errors |
+| OpenCode | Managed plugin hooks | Prompts, assistant text/reasoning, model and usage metadata, tool inputs/results/failures, commands and output, file activity/diffs, web/MCP calls, approvals, and session lifecycle/errors |
| Devin CLI | Native hooks | Session, prompt, pre-tool, post-tool, permission request, stop, session-end, approval, and file telemetry |
| Devin Desktop | Cascade/Windsurf hooks | Prompt, command, MCP tool, file read, and file write telemetry where Desktop exposes Cascade hook payloads |
| Factory Droid | OTLP HTTP plus optional hooks | Session, prompt, write/edit/create tool use, stop, session-end, and available OTLP telemetry |
@@ -82,6 +82,13 @@ Top-level `model`, `repository`, `branch`, `message`, `raw`, and `field_truncate
For hook-based runtimes, `branch` is derived locally from the workspace's `.git/HEAD` file when the runtime payload does not provide one. This is a local file read only — no git command runs and nothing leaves the machine — and it can be disabled with `BEACON_DISABLE_GIT_METADATA=1`.
+OpenCode's managed plugin retains full prompt, completed assistant/reasoning,
+tool argument/result, command output, and diff content in local or
+customer-controlled logs. All values pass through secret redaction and
+per-string truncation. Content events carry original hashes and byte counts;
+oversized events discard raw/content payloads, set `field_truncated`, and remain
+within the endpoint event-size limit.
+
## Related
<Columns cols={2}>
diff --git a/docs/telemetry-schema/normalization.mdx b/docs/telemetry-schema/normalization.mdx
index 41540eeb..a426590d 100644
--- a/docs/telemetry-schema/normalization.mdx
+++ b/docs/telemetry-schema/normalization.mdx
@@ -34,6 +34,25 @@ Beacon normalizes [OTLP](/concepts/core-concepts#otlp) attributes and [hook](/co
| Approval events | `approval.requested` |
| Other tool activity | `tool.invoked` |
+### OpenCode plugin mapping
+
+OpenCode's managed plugin maps `chat.message` to `prompt.submitted`;
+`tool.execute.before` to `tool.invoked`; and successful terminal tool events to
+`command.executed`, `file.read`, `file.modified`, `mcp.tool_invoked`, or
+`tool.completed` according to tool semantics. Terminal tool errors become
+`tool.failed`.
+
+Completed assistant message metadata supplies model, finish reason,
+runtime-reported cost, and canonical `gen_ai.usage`. Completed text and reasoning
+parts use `gen_ai.output.messages`; reasoning additionally uses
+`agent.reasoning`. Permission replies map `once` and `always` to
+`approval.allowed`, `reject` to `approval.denied`, and unknown states to
+`approval.requested`.
+
+Structured `session.diff` arrays emit file events only for entries containing a
+real path and change. Empty/cumulative duplicate diffs do not create pathless
+`file.modified` records.
+
## OpenTelemetry GenAI fields
Beacon preserves OpenTelemetry GenAI semantic convention fields under the nested `gen_ai` object and also projects selected fields into Beacon's common investigation fields. This keeps the raw GenAI context available without forcing downstream rules to parse runtime-specific attribute names.
diff --git a/packaging/macos/smoke-endpoint.sh b/packaging/macos/smoke-endpoint.sh
index c3accb88..45905be0 100755
--- a/packaging/macos/smoke-endpoint.sh
+++ b/packaging/macos/smoke-endpoint.sh
@@ -96,6 +96,46 @@ if ! grep -q 'BEACON_ENDPOINT_MODE=1' "$HOME_DIR/.cursor/hooks.json"; then
exit 1
fi
+echo "Installing and exercising OpenCode plugin in temporary HOME..."
+run_beacon endpoint hooks install --harness opencode --user --log-path "$LOG_PATH" >/dev/null
+run_beacon endpoint hooks status --harness opencode --user --log-path "$LOG_PATH" >/dev/null
+OPENCODE_PLUGIN="$HOME_DIR/.config/opencode/plugins/beacon.ts"
+OPENCODE_HOOK="$HOME_DIR/.beacon/endpoint/hooks/beacon-hooks"
+test -f "$OPENCODE_PLUGIN"
+test -x "$OPENCODE_HOOK"
+
+if grep -q '__BEACON_' "$OPENCODE_PLUGIN"; then
+ echo "OpenCode plugin contains unresolved Beacon placeholders" >&2
+ exit 1
+fi
+
+emit_opencode() {
+ printf '%s\n' "$1" | \
+ HOME="$HOME_DIR" BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG="$LOG_PATH" \
+ "$OPENCODE_HOOK" --platform opencode opencode-event >/dev/null
+}
+
+emit_opencode '{"type":"chat.message","session_id":"ses_smoke","directory":"/tmp/project","model":"test/model","output":{"parts":[{"type":"text","text":"summarize"}]}}'
+emit_opencode '{"type":"tool.execute.after","session_id":"ses_smoke","directory":"/tmp/project","tool_name":"bash","call_id":"call_bash","duration_ms":5,"tool_input":{"command":"git status --short"},"tool_response":{"output":"","metadata":{"exitCode":0}}}'
+emit_opencode '{"type":"tool.execute.after","session_id":"ses_smoke","directory":"/tmp/project","tool_name":"write","call_id":"call_write","tool_input":{"filePath":"/tmp/project/smoke.txt","content":"value"},"tool_response":{"output":"ok","metadata":{}}}'
+emit_opencode '{"type":"permission.replied","session_id":"ses_smoke","properties":{"sessionID":"ses_smoke","requestID":"per_smoke","reply":"reject"}}'
+emit_opencode '{"type":"session.diff","session_id":"ses_smoke","properties":{"sessionID":"ses_smoke","diff":[]}}'
+
+for action in prompt.submitted command.executed file.modified approval.denied; do
+ if ! grep -q "\"action\":\"$action\"" "$LOG_PATH"; then
+ echo "expected OpenCode $action event in runtime log" >&2
+ exit 1
+ fi
+done
+
+if grep '"session":{"id":"ses_smoke"' "$LOG_PATH" | grep -q 'opencode session diff observed'; then
+ echo "empty OpenCode session diff produced a file event" >&2
+ exit 1
+fi
+
+run_beacon endpoint hooks uninstall --harness opencode --user --log-path "$LOG_PATH" >/dev/null
+test ! -f "$OPENCODE_PLUGIN"
+
echo "Uninstalling endpoint config..."
run_beacon endpoint uninstall --user --log-path "$LOG_PATH" --keep-logs >/dev/null
diff --git a/pkg/asymptoteobserve/dedupe.go b/pkg/asymptoteobserve/dedupe.go
index e067691d..6a6844fb 100644
--- a/pkg/asymptoteobserve/dedupe.go
+++ b/pkg/asymptoteobserve/dedupe.go
@@ -20,6 +20,7 @@ type endpointDedupeEvent struct {
action string
harness string
key string
+ callID string
ts time.Time
}
@@ -41,7 +42,10 @@ func IsDuplicateEndpointEvent(path string, candidateLine []byte, window time.Dur
if !ok || existing.key != candidate.key {
continue
}
- if existing.harness == candidate.harness {
+ // Same-harness events are normally preserved because two adjacent calls
+ // can legitimately target the same file or command. A stable tool call
+ // ID makes an exact duplicate safe to collapse.
+ if existing.harness == candidate.harness && (existing.callID == "" || candidate.callID == "") {
continue
}
diff := candidate.ts.Sub(existing.ts)
@@ -100,6 +104,7 @@ func endpointDedupeCandidate(line []byte) (endpointDedupeEvent, bool) {
return endpointDedupeEvent{}, false
}
harness := strings.ToLower(nestedString(event, "harness", "name"))
+ callID := nestedString(event, "gen_ai", "tool", "call", "id")
target := dedupeTarget(action, event)
if target == "" {
return endpointDedupeEvent{}, false
@@ -113,8 +118,9 @@ func endpointDedupeCandidate(line []byte) (endpointDedupeEvent, bool) {
sessionID,
strings.ToLower(workspace),
target,
+ callID,
}, "\x00")
- return endpointDedupeEvent{action: strings.ToLower(action), harness: harness, key: key, ts: ts.UTC()}, true
+ return endpointDedupeEvent{action: strings.ToLower(action), harness: harness, key: key, callID: callID, ts: ts.UTC()}, true
}
func endpointDedupeWindow(action string, fallback time.Duration) time.Duration {
diff --git a/pkg/asymptoteobserve/dedupe_test.go b/pkg/asymptoteobserve/dedupe_test.go
index f6f76acd..25b09797 100644
--- a/pkg/asymptoteobserve/dedupe_test.go
+++ b/pkg/asymptoteobserve/dedupe_test.go
@@ -45,6 +45,19 @@ func TestIsDuplicateEndpointEventKeepsSameHarnessCalls(t *testing.T) {
}
}
+func TestIsDuplicateEndpointEventCollapsesSameHarnessCallID(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ existing := `{"timestamp":"2026-06-18T21:11:24Z","event":{"action":"tool.completed"},"harness":{"name":"opencode"},"session":{"id":"s1"},"tool":{"name":"webfetch"},"gen_ai":{"tool":{"name":"webfetch","call":{"id":"call_1"}}},"message":"opencode tool completed"}`
+ candidate := []byte(`{"timestamp":"2026-06-18T21:11:25Z","event":{"action":"tool.completed"},"harness":{"name":"opencode"},"session":{"id":"s1"},"tool":{"name":"webfetch"},"gen_ai":{"tool":{"name":"webfetch","call":{"id":"call_1"}}},"message":"opencode tool completed"}`)
+ if err := os.WriteFile(path, []byte(existing+"\n"), 0644); err != nil {
+ t.Fatalf("write existing event: %v", err)
+ }
+
+ if !IsDuplicateEndpointEvent(path, candidate, EndpointDuplicateWindow) {
+ t.Fatal("same OpenCode call ID should dedupe")
+ }
+}
+
func TestIsDuplicateEndpointEventRequiresSession(t *testing.T) {
path := filepath.Join(t.TempDir(), "runtime.jsonl")
existing := `{"timestamp":"2026-06-18T21:11:24Z","event":{"action":"mcp.tool_invoked"},"harness":{"name":"cursor"},"mcp":{"tool":"list_tables"}}`
diff --git a/plugins/opencode-beacon/package.json b/plugins/opencode-beacon/package.json
index d6629b58..52a05538 100644
--- a/plugins/opencode-beacon/package.json
+++ b/plugins/opencode-beacon/package.json
@@ -5,7 +5,9 @@
"description": "Beacon endpoint telemetry adapter for opencode",
"type": "module",
"scripts": {
- "check": "bun --check src/beacon.ts"
+ "check": "bun --check src/beacon.ts && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts",
+ "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts",
+ "test": "bun test src/beacon.test.ts"
},
"exports": {
".": "./src/beacon.ts"
diff --git a/plugins/opencode-beacon/src/beacon.test.ts b/plugins/opencode-beacon/src/beacon.test.ts
new file mode 100644
index 00000000..abfd6bdd
--- /dev/null
+++ b/plugins/opencode-beacon/src/beacon.test.ts
@@ -0,0 +1,176 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test"
+import { BeaconEndpointPlugin } from "./beacon"
+
+const originalSpawn = Bun.spawn
+const payloads: any[] = []
+
+beforeEach(() => {
+ payloads.length = 0
+ Object.defineProperty(Bun, "spawn", {
+ configurable: true,
+ value: () => ({
+ stdin: {
+ write(value: string) {
+ payloads.push(JSON.parse(value))
+ },
+ end() {},
+ },
+ exited: Promise.resolve(0),
+ kill() {},
+ }),
+ })
+})
+
+afterEach(() => {
+ Object.defineProperty(Bun, "spawn", { configurable: true, value: originalSpawn })
+})
+
+async function plugin() {
+ return BeaconEndpointPlugin({
+ project: { id: "project-1" },
+ directory: "/repo",
+ worktree: "/repo",
+ client: { app: { log: async () => true } },
+ } as any)
+}
+
+describe("BeaconEndpointPlugin", () => {
+ test("forwards prompts and correlated tool lifecycle payloads", async () => {
+ const hooks = await plugin()
+
+ await hooks["chat.message"]!(
+ { sessionID: "ses_1", model: { providerID: "moonshotai", modelID: "kimi-k3" } } as any,
+ { parts: [{ type: "text", text: "summarize" }] } as any,
+ )
+ await hooks["tool.execute.before"]!(
+ { tool: "bash", sessionID: "ses_1", callID: "call_1" },
+ { args: { command: "git status --short" } },
+ )
+ await hooks["tool.execute.after"]!(
+ { tool: "bash", sessionID: "ses_1", callID: "call_1", args: { command: "git status --short" } },
+ { title: "status", output: "", metadata: { exitCode: 0 } },
+ )
+
+ expect(payloads.map((item) => item.type)).toEqual([
+ "chat.message",
+ "tool.execute.before",
+ "tool.execute.after",
+ ])
+ expect(payloads[2]).toMatchObject({
+ session_id: "ses_1",
+ call_id: "call_1",
+ tool_name: "bash",
+ directory: "/repo",
+ })
+ })
+
+ test("forwards terminal text, errors, usage, and permission replies once", async () => {
+ const hooks = await plugin()
+
+ await hooks.event!({
+ event: {
+ type: "message.updated",
+ properties: {
+ sessionID: "ses_1",
+ info: {
+ id: "msg_1",
+ role: "assistant",
+ modelID: "kimi-k3",
+ providerID: "moonshotai",
+ time: { completed: 2 },
+ tokens: { input: 3, output: 4, reasoning: 1, cache: { read: 2, write: 0 } },
+ },
+ },
+ },
+ } as any)
+ await hooks.event!({
+ event: {
+ type: "message.part.updated",
+ properties: {
+ sessionID: "ses_1",
+ part: {
+ id: "prt_1",
+ messageID: "msg_1",
+ sessionID: "ses_1",
+ type: "text",
+ text: "Done",
+ time: { start: 1, end: 2 },
+ },
+ },
+ },
+ } as any)
+ await hooks.event!({
+ event: {
+ type: "permission.replied",
+ properties: { sessionID: "ses_1", requestID: "per_1", reply: "reject" },
+ },
+ } as any)
+ await hooks.event!({
+ event: {
+ type: "message.part.updated",
+ properties: {
+ sessionID: "ses_1",
+ part: {
+ id: "prt_tool",
+ messageID: "msg_1",
+ sessionID: "ses_1",
+ callID: "call_failed",
+ type: "tool",
+ tool: "read",
+ state: {
+ status: "error",
+ input: { filePath: "/repo/missing" },
+ error: "not found",
+ time: { start: 1, end: 2 },
+ },
+ },
+ },
+ },
+ } as any)
+ await Bun.sleep(20)
+
+ expect(payloads.map((item) => item.type)).toEqual([
+ "message.updated",
+ "message.part.updated",
+ "permission.replied",
+ "message.part.updated",
+ ])
+ expect(payloads[1].model).toBe("moonshotai/kimi-k3")
+ expect(payloads[3].part.state.status).toBe("error")
+ })
+
+ test("suppresses empty diffs and duplicate successful tool parts", async () => {
+ const hooks = await plugin()
+ await hooks["tool.execute.before"]!(
+ { tool: "write", sessionID: "ses_1", callID: "call_1" },
+ { args: { filePath: "/repo/test.txt", content: "value" } },
+ )
+ await hooks["tool.execute.after"]!(
+ { tool: "write", sessionID: "ses_1", callID: "call_1", args: { filePath: "/repo/test.txt" } },
+ { title: "write", output: "ok", metadata: {} },
+ )
+ await hooks.event!({
+ event: { type: "session.diff", properties: { sessionID: "ses_1", diff: [] } },
+ } as any)
+ await hooks.event!({
+ event: {
+ type: "message.part.updated",
+ properties: {
+ sessionID: "ses_1",
+ part: {
+ id: "prt_1",
+ messageID: "msg_1",
+ sessionID: "ses_1",
+ callID: "call_1",
+ type: "tool",
+ tool: "write",
+ state: { status: "completed", input: {}, output: "ok", metadata: {}, time: { start: 1, end: 2 } },
+ },
+ },
+ },
+ } as any)
+ await Bun.sleep(20)
+
+ expect(payloads.map((item) => item.type)).toEqual(["tool.execute.before", "tool.execute.after"])
+ })
+})
diff --git a/plugins/opencode-beacon/src/beacon.ts b/plugins/opencode-beacon/src/beacon.ts
index c14c217b..4ae46406 100644
--- a/plugins/opencode-beacon/src/beacon.ts
+++ b/plugins/opencode-beacon/src/beacon.ts
@@ -4,9 +4,24 @@
const beaconCommand = "__BEACON_COMMAND__"
const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"
+const sendTimeoutMs = 2000
+const directHookTypes = new Set([
+ "chat.message",
+ "command.execute.before",
+ "tool.execute.before",
+ "tool.execute.after",
+])
const forwardedEvents = new Set([
+ "file.edited",
+ "file.watcher.updated",
+ "message.part.updated",
+ "message.part.delta",
+ "message.updated",
+ "permission.v2.asked",
+ "permission.v2.replied",
"session.created",
"session.idle",
+ "session.status",
"session.error",
"session.diff",
"command.executed",
@@ -32,15 +47,25 @@ async function debugLog(client, message, extra) {
}
async function sendToBeacon(client, payload) {
+ let proc
try {
- const proc = Bun.spawn(["/bin/sh", "-lc", beaconCommand], {
+ 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
+ const outcome = await Promise.race([
+ proc.exited.then((code) => ({ code })),
+ Bun.sleep(sendTimeoutMs).then(() => ({ timeout: true })),
+ ])
+ if ("timeout" in outcome) {
+ proc.kill()
+ await debugLog(client, "Beacon hook command timed out", { type: payload?.type })
+ return
+ }
+ const code = outcome.code
if (code !== 0) {
await debugLog(client, "Beacon hook command exited non-zero", { code, type: payload?.type })
}
@@ -54,7 +79,11 @@ async function sendToBeacon(client, payload) {
}
function sessionID(value) {
- return value?.sessionID || value?.session_id || value?.id || value?.session?.id || value?.info?.sessionID || ""
+ const direct = value?.sessionID || value?.session_id || value?.session?.id || value?.info?.sessionID
+ if (direct) return direct
+ if (typeof value?.id === "string" && value.id.startsWith("ses_")) return value.id
+ if (typeof value?.info?.id === "string" && value.info.id.startsWith("ses_")) return value.info.id
+ return ""
}
function modelName(value) {
@@ -64,8 +93,80 @@ function modelName(value) {
return model.modelID || model.id || model.name || ""
}
+function filePath(value) {
+ return (
+ value?.filePath ||
+ value?.file_path ||
+ value?.path ||
+ value?.file ||
+ value?.target ||
+ value?.destination ||
+ ""
+ )
+}
+
+function isFileMutationTool(tool) {
+ const name = String(tool || "").toLowerCase()
+ return ["edit", "write", "patch", "apply_patch", "create"].some((part) => name.includes(part))
+}
+
export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {
const context = { project, directory, worktree }
+ const activeCalls = new Map()
+ const completedCalls = new Set()
+ const emittedParts = new Set()
+ const pendingParts = new Map()
+ const partDeltas = new Map()
+ const messageModels = new Map()
+ const recentFilePaths = new Map()
+ let eventQueue = Promise.resolve()
+
+ const payload = (type, values = {}) => ({ type, ...values, ...context })
+ const enqueue = (value) => {
+ eventQueue = eventQueue
+ .then(() => sendToBeacon(client, value))
+ .catch((err) => debugLog(client, "Beacon event queue failed", { error: String(err), type: value?.type }))
+ return eventQueue
+ }
+ const rememberFilePath = (tool, args) => {
+ if (!isFileMutationTool(tool)) return
+ const path = filePath(args)
+ if (path) recentFilePaths.set(path, Date.now())
+ }
+ const partKey = (part) => `${part?.sessionID || ""}:${part?.messageID || ""}:${part?.id || ""}`
+ const emitPart = (part, sid, model) => {
+ if (!part) return
+ const key = partKey(part)
+ if (emittedParts.has(key)) return
+ const next = structuredClone(part)
+ const delta = partDeltas.get(key)
+ if ((next.type === "text" || next.type === "reasoning") && !next.text && delta) next.text = delta
+ if (next.type === "tool") {
+ const status = next.state?.status
+ if (status !== "completed" && status !== "error") return
+ if (status === "completed" && completedCalls.has(next.callID)) return
+ } else if (next.type === "text" || next.type === "reasoning") {
+ if (!next.time?.end) {
+ pendingParts.set(key, { part: next, session_id: sid, model })
+ return
+ }
+ } else if (next.type !== "retry") {
+ return
+ }
+ emittedParts.add(key)
+ pendingParts.delete(key)
+ partDeltas.delete(key)
+ void enqueue(payload("message.part.updated", { session_id: sid, model, part: next }))
+ }
+ const flushParts = (sid) => {
+ for (const [key, item] of pendingParts) {
+ if (item.session_id !== sid) continue
+ const part = { ...item.part, time: { ...(item.part.time || {}), end: Date.now() } }
+ pendingParts.delete(key)
+ emitPart(part, sid, item.model)
+ }
+ }
+
return {
"chat.message": async (input, output) => {
await sendToBeacon(client, {
@@ -77,19 +178,100 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
...context,
})
},
+ "command.execute.before": async (input, output) => {
+ await sendToBeacon(
+ client,
+ payload("command.execute.before", {
+ session_id: sessionID(input),
+ command_name: input?.command,
+ arguments: input?.arguments,
+ parts: output?.parts,
+ }),
+ )
+ },
+ "tool.execute.before": async (input, output) => {
+ activeCalls.set(input?.callID, {
+ tool: input?.tool,
+ args: structuredClone(output?.args || {}),
+ started_at: Date.now(),
+ })
+ await sendToBeacon(
+ client,
+ payload("tool.execute.before", {
+ session_id: sessionID(input),
+ tool_name: input?.tool,
+ call_id: input?.callID,
+ tool_input: output?.args || {},
+ }),
+ )
+ },
+ "tool.execute.after": async (input, output) => {
+ const active = activeCalls.get(input?.callID)
+ const args = input?.args || active?.args || {}
+ rememberFilePath(input?.tool, args)
+ await sendToBeacon(
+ client,
+ payload("tool.execute.after", {
+ session_id: sessionID(input),
+ tool_name: input?.tool,
+ call_id: input?.callID,
+ duration_ms: active?.started_at ? Date.now() - active.started_at : undefined,
+ tool_input: args,
+ tool_response: output,
+ }),
+ )
+ activeCalls.delete(input?.callID)
+ completedCalls.add(input?.callID)
+ },
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,
- })
+ const properties = event?.properties || event?.data || {}
+ const sid = sessionID(properties)
+ const info = properties?.info || {}
+ if (type === "message.updated") {
+ if (info?.role !== "assistant") return
+ const model = modelName(info)
+ if (info?.id && model) messageModels.set(info.id, model)
+ if (!info?.time?.completed && !info?.error) return
+ }
+ if (type === "message.part.delta") {
+ const key = `${sid}:${properties?.messageID || ""}:${properties?.partID || ""}`
+ partDeltas.set(key, (partDeltas.get(key) || "") + (properties?.delta || ""))
+ return
+ }
+ if (type === "message.part.updated") {
+ const part = properties?.part
+ emitPart(part, sid, messageModels.get(part?.messageID) || "")
+ return
+ }
+ if (type === "session.status" && properties?.status?.type === "idle") flushParts(sid)
+ if (type === "session.idle") flushParts(sid)
+ if (type === "session.diff") {
+ const diffs = Array.isArray(properties?.diff) ? properties.diff : []
+ const now = Date.now()
+ const filtered = diffs.filter((item) => {
+ const path = filePath(item)
+ if (!path) return false
+ const seen = recentFilePaths.get(path)
+ if (seen && now - seen < 5000) return false
+ return item?.before !== item?.after || item?.additions || item?.deletions
+ })
+ if (filtered.length === 0) return
+ properties.diff = filtered
+ }
+ if (type === "file.edited" || type === "file.watcher.updated") {
+ if (!sid) return
+ }
+ void enqueue(
+ payload(type, {
+ session_id: sid,
+ model: modelName(info || properties),
+ properties,
+ event,
+ }),
+ )
},
}
}