Skip to content

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

fix: address OpenCode live trace regressions

Cursor Agent5d9bb9a1d08a
diff --git a/cli/beacon-hooks/cmd/opencode_event.go b/cli/beacon-hooks/cmd/opencode_event.go
index 8f8a33ee..ef892235 100644
--- a/cli/beacon-hooks/cmd/opencode_event.go
+++ b/cli/beacon-hooks/cmd/opencode_event.go
@@ -113,12 +113,14 @@ func opencodeEndpointEvents(input map[string]interface{}, sessionID string) []op
return opencodePartEvents(fields, part)
case "session.created":
return one("session.started", "session", "info", "opencode session started", fields)
+ case "session.deleted":
+ return one("session.ended", "session", "info", "opencode session deleted", 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)
+ return one("session.status", "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)
@@ -126,7 +128,7 @@ func opencodeEndpointEvents(input map[string]interface{}, sessionID string) []op
return one("session.status", "session", "info", "opencode session "+firstNonEmpty(statusType, "status updated"), fields)
}
case "session.idle":
- return one("session.ended", "session", "info", "opencode session ended", fields)
+ return one("session.status", "session", "info", "opencode session idle", fields)
case "session.error":
errorInfo := opencodeMap(opencodeProperties(input), "error")
if len(errorInfo) > 0 {
@@ -150,6 +152,15 @@ func opencodeEndpointEvents(input map[string]interface{}, sessionID string) []op
"operation": operation,
"language": strings.TrimPrefix(filepath.Ext(path), "."),
}
+ if callID := getFirstStr(properties, "callID", "call_id"); callID != "" {
+ fields["gen_ai"] = map[string]interface{}{
+ "operation": map[string]interface{}{"name": "execute_tool"},
+ "tool": map[string]interface{}{
+ "name": "file_watcher",
+ "call": map[string]interface{}{"id": callID},
+ },
+ }
+ }
return one("file.modified", "file", "info", "opencode file change observed", fields)
case "command.execute.before":
if command := opencodeCommand(input); command != "" {
@@ -208,6 +219,7 @@ func supportedOpenCodeEventTypes() []string {
"permission.v2.asked",
"permission.v2.replied",
"session.created",
+ "session.deleted",
"session.diff",
"session.error",
"session.idle",
@@ -319,17 +331,18 @@ func opencodeToolFields(input map[string]interface{}, completed bool) map[string
if path := opencodeToolPath(toolInput); path != "" {
operation := fileOperation(toolName)
if operation == "" {
- lower := strings.ToLower(toolName)
- if strings.Contains(lower, "glob") || strings.Contains(lower, "grep") || strings.Contains(lower, "search") {
- operation = "read"
+ delete(fields, "file")
+ if tool, ok := fields["tool"].(map[string]interface{}); ok {
+ delete(tool, "path")
}
+ } else {
+ fields["file"] = map[string]interface{}{
+ "path": path,
+ "operation": operation,
+ "language": strings.TrimPrefix(filepath.Ext(path), "."),
+ }
+ fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"name": toolName, "path": path})
}
- fields["file"] = map[string]interface{}{
- "path": path,
- "operation": operation,
- "language": strings.TrimPrefix(filepath.Ext(path), "."),
- }
- fields["tool"] = mergeNested(fields["tool"], map[string]interface{}{"name": toolName, "path": path})
}
if completed {
@@ -355,7 +368,7 @@ func opencodeToolFields(input map[string]interface{}, completed bool) map[string
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 {
+ if exitCode, ok := firstToolIntAcross([]map[string]interface{}{metadata}, "exit", "exit_code", "exitCode", "status"); ok {
commandFields["exit_code"] = exitCode
}
}
@@ -405,14 +418,12 @@ func opencodeDecision(input map[string]interface{}) string {
func opencodeToolAction(input map[string]interface{}) (string, string) {
name := strings.ToLower(opencodeToolName(input))
- toolInput := opencodeMap(input, "tool_input", "toolInput")
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") ||
- ((strings.Contains(name, "glob") || strings.Contains(name, "grep") || strings.Contains(name, "search")) && opencodeToolPath(toolInput) != ""):
+ 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"
@@ -437,11 +448,7 @@ func opencodeToolMessage(action string) string {
}
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)
+ return hookdiff.NormalizePath(firstToolString(input, "file_path", "filePath", "path", "target", "destination"))
}
func opencodeAssistantFields(info map[string]interface{}) map[string]interface{} {
diff --git a/cli/beacon-hooks/cmd/opencode_event_test.go b/cli/beacon-hooks/cmd/opencode_event_test.go
index f962f86e..11391dfc 100644
--- a/cli/beacon-hooks/cmd/opencode_event_test.go
+++ b/cli/beacon-hooks/cmd/opencode_event_test.go
@@ -164,7 +164,7 @@ func TestOpenCodeEventIgnoresUnsupportedEvents(t *testing.T) {
assertNoEndpointLog(t, logPath)
runHookWithInput(t, runOpenCodeEvent, map[string]interface{}{
- "type": "session.deleted",
+ "type": "session.compacted",
"session_id": "session-1",
})
assertNoEndpointLog(t, logPath)
@@ -318,6 +318,68 @@ func TestOpenCodeStructuredDiffSuppressesEmptyAndEmitsChangedFiles(t *testing.T)
}
}
+func TestOpenCodeIdleIsStatusUntilSessionDeletion(t *testing.T) {
+ action, _, _, _, _ := opencodeEndpointEvent(map[string]interface{}{
+ "type": "session.status",
+ "session_id": "ses_test",
+ "properties": map[string]interface{}{"status": map[string]interface{}{"type": "idle"}},
+ }, "ses_test")
+ if action != "session.status" {
+ t.Fatalf("idle action = %q, want session.status", action)
+ }
+ action, _, _, _, _ = opencodeEndpointEvent(map[string]interface{}{
+ "type": "session.deleted",
+ "session_id": "ses_test",
+ }, "ses_test")
+ if action != "session.ended" {
+ t.Fatalf("deleted action = %q, want session.ended", action)
+ }
+}
+
+func TestOpenCodeBashCapturesExitMetadata(t *testing.T) {
+ _, _, _, _, fields := opencodeEndpointEvent(map[string]interface{}{
+ "type": "tool.execute.after",
+ "session_id": "ses_test",
+ "tool_name": "bash",
+ "call_id": "bash_1",
+ "tool_input": map[string]interface{}{"command": "test -f missing"},
+ "tool_response": map[string]interface{}{
+ "output": "missing",
+ "metadata": map[string]interface{}{
+ "exit": 1,
+ },
+ },
+ }, "ses_test")
+ command := fields["command"].(map[string]interface{})
+ if command["exit_code"] != 1 {
+ t.Fatalf("exit_code = %#v, want 1", command["exit_code"])
+ }
+}
+
+func TestOpenCodeWatcherUnlinkNormalizesFileDeletion(t *testing.T) {
+ action, category, _, _, fields := opencodeEndpointEvent(map[string]interface{}{
+ "type": "file.watcher.updated",
+ "session_id": "ses_test",
+ "properties": map[string]interface{}{
+ "sessionID": "ses_test",
+ "file": "/repo/.tmp/e2e.txt",
+ "event": "unlink",
+ "callID": "call_rm",
+ },
+ }, "ses_test")
+ if action != "file.modified" || category != "file" {
+ t.Fatalf("event = %s/%s", action, category)
+ }
+ file := fields["file"].(map[string]interface{})
+ if file["operation"] != "delete" || file["path"] != "/repo/.tmp/e2e.txt" {
+ t.Fatalf("file = %#v", file)
+ }
+ call := fields["gen_ai"].(map[string]interface{})["tool"].(map[string]interface{})["call"].(map[string]interface{})
+ if call["id"] != "call_rm" {
+ t.Fatalf("call = %#v", call)
+ }
+}
+
func TestOpenCodePermissionRepliesMapAllowAndDeny(t *testing.T) {
for _, tt := range []struct {
reply string
@@ -377,7 +439,7 @@ func TestOpenCodeTidyPlanetTraceReplay(t *testing.T) {
want := []string{
"prompt.submitted", "prompt.submitted",
"tool.invoked", "file.read",
- "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",
diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
index be8c4d1e..9d9991df 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
@@ -20,6 +20,7 @@ const forwardedEvents = new Set([
"permission.v2.asked",
"permission.v2.replied",
"session.created",
+ "session.deleted",
"session.idle",
"session.status",
"session.error",
@@ -116,6 +117,19 @@ function isFileMutationTool(tool) {
return ["edit", "write", "patch", "apply_patch", "create"].some((part) => name.includes(part))
}
+function shellMutationPaths(tool, args) {
+ const name = String(tool || "").toLowerCase()
+ if (name !== "bash" && !name.includes("shell")) return []
+ const command = String(args?.command || args?.cmd || "")
+ const paths = []
+ const pattern = /\b(?:rm|unlink)\s+(?:-[^\s]+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))/g
+ for (const match of command.matchAll(pattern)) {
+ const path = match[1] || match[2] || match[3]
+ if (path) paths.push(path)
+ }
+ return paths
+}
+
export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {
const context = { project, directory, worktree }
const activeCalls = new Map()
@@ -124,6 +138,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const pendingParts = new Map()
const partDeltas = new Map()
const messageModels = new Map()
+ const messageRoles = new Map()
const completedMessages = new Set()
const permissionRequests = new Map()
const sessionStates = new Map()
@@ -138,9 +153,10 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
return eventQueue
}
const rememberFilePath = (tool, args, sid, callID) => {
- if (!isFileMutationTool(tool)) return
- const path = filePath(args)
- if (path) recentFilePaths.set(path, { time: Date.now(), sessionID: sid, callID })
+ const paths = []
+ if (isFileMutationTool(tool) && filePath(args)) paths.push(filePath(args))
+ paths.push(...shellMutationPaths(tool, args))
+ for (const path of paths) recentFilePaths.set(path, { time: Date.now(), sessionID: sid, callID })
}
const partKey = (part) => `${part?.sessionID || ""}:${part?.messageID || ""}:${part?.id || ""}`
const emitPart = (part, sid, model) => {
@@ -155,6 +171,19 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
if (status !== "completed" && status !== "error") return
if (status === "completed" && completedCalls.has(next.callID)) return
} else if (next.type === "text" || next.type === "reasoning") {
+ if (next.type === "text") {
+ const role = messageRoles.get(next.messageID)
+ if (role === "user") {
+ emittedParts.add(key)
+ pendingParts.delete(key)
+ partDeltas.delete(key)
+ return
+ }
+ if (role !== "assistant") {
+ pendingParts.set(key, { part: next, session_id: sid, model })
+ return
+ }
+ }
if (!next.time?.end) {
pendingParts.set(key, { part: next, session_id: sid, model })
return
@@ -178,6 +207,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
return {
"chat.message": async (input, output) => {
+ if (output?.message?.id) messageRoles.set(output.message.id, "user")
await sendToBeacon(client, {
type: "chat.message",
session_id: sessionID(input),
@@ -199,11 +229,14 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
)
},
"tool.execute.before": async (input, output) => {
+ const sid = sessionID(input)
activeCalls.set(input?.callID, {
tool: input?.tool,
args: structuredClone(output?.args || {}),
+ session_id: sid,
started_at: Date.now(),
})
+ rememberFilePath(input?.tool, output?.args || {}, sid, input?.callID)
await sendToBeacon(
client,
payload("tool.execute.before", {
@@ -240,6 +273,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const sid = sessionID(properties)
const info = properties?.info || {}
if (type === "message.updated") {
+ if (info?.id && info?.role) messageRoles.set(info.id, info.role)
if (info?.role !== "assistant") return
const model = modelName(info)
if (info?.id && model) messageModels.set(info.id, model)
@@ -261,6 +295,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
}
if (type === "session.status") {
const status = properties?.status?.type || ""
+ if (sessionStates.get(sid) === status) return
sessionStates.set(sid, status)
if (status === "idle") flushParts(sid)
}
diff --git a/pkg/asymptoteobserve/privacy.go b/pkg/asymptoteobserve/privacy.go
index 0d8b33b6..806ff619 100644
--- a/pkg/asymptoteobserve/privacy.go
+++ b/pkg/asymptoteobserve/privacy.go
@@ -18,12 +18,24 @@ var secretPatterns = []*regexp.Regexp{
regexp.MustCompile(`sk-[a-zA-Z0-9]{20,}`),
}
+var assignedSecretPattern = regexp.MustCompile("(?i)(?:api[_-]?key|token|secret|password|authorization)\\s*[:=]\\s*[\"'`]?([^\"'`,\\s]+)")
+
type PrivacyOptions struct {
RedactSecrets bool
StringLimit int
}
func RedactString(value string) string {
+ // Remember assignment values before replacing their labeled occurrence so
+ // repeated bare copies in the same retained prompt/output are also removed.
+ // This is common in model reasoning that quotes `token=value` and later
+ // refers to `value` by itself.
+ var assigned []string
+ for _, match := range assignedSecretPattern.FindAllStringSubmatch(value, -1) {
+ if len(match) > 1 && len(match[1]) >= 8 {
+ assigned = append(assigned, match[1])
+ }
+ }
for _, pattern := range secretPatterns {
value = pattern.ReplaceAllStringFunc(value, func(match string) string {
if strings.Contains(match, "=") {
@@ -35,6 +47,9 @@ func RedactString(value string) string {
return "[REDACTED]"
})
}
+ for _, secret := range assigned {
+ value = strings.ReplaceAll(value, secret, "[REDACTED]")
+ }
return value
}
diff --git a/pkg/asymptoteobserve/privacy_test.go b/pkg/asymptoteobserve/privacy_test.go
index b54cd335..abd5c23e 100644
--- a/pkg/asymptoteobserve/privacy_test.go
+++ b/pkg/asymptoteobserve/privacy_test.go
@@ -22,6 +22,17 @@ func TestRedactStringRedactsKnownSecretForms(t *testing.T) {
}
}
+func TestRedactStringRedactsRepeatedBareAssignedValue(t *testing.T) {
+ value := "Use token=beacon-opencode-e2e-secret, then replace beacon-opencode-e2e-secret in the file."
+ got := RedactString(value)
+ if strings.Contains(got, "beacon-opencode-e2e-secret") {
+ t.Fatalf("repeated assigned value leaked: %q", got)
+ }
+ if strings.Count(got, "[REDACTED]") != 2 {
+ t.Fatalf("redactions = %q, want both occurrences redacted", got)
+ }
+}
+
func TestSanitizeMapDoesNotMutateInput(t *testing.T) {
input := map[string]interface{}{
"token": "token=super-secret",
diff --git a/plugins/opencode-beacon/src/beacon.test.ts b/plugins/opencode-beacon/src/beacon.test.ts
index 6735ef9d..90df5b9f 100644
--- a/plugins/opencode-beacon/src/beacon.test.ts
+++ b/plugins/opencode-beacon/src/beacon.test.ts
@@ -161,4 +161,53 @@ describe("BeaconEndpointPlugin", () => {
expect(payloads.map((item) => item.type)).toEqual(["tool.execute.before", "tool.execute.after"])
})
+
+ test("does not flush user text as assistant output and deduplicates session status", async () => {
+ const hooks = await plugin()
+ await hooks["chat.message"]!(
+ { sessionID: "ses_1", model: { providerID: "moonshotai", modelID: "kimi-k3" } } as any,
+ {
+ message: { id: "msg_user", role: "user" },
+ parts: [{ id: "prt_user", messageID: "msg_user", sessionID: "ses_1", type: "text", text: "hello" }],
+ } as any,
+ )
+ await hooks.event!({
+ event: {
+ type: "message.part.updated",
+ properties: {
+ sessionID: "ses_1",
+ part: { id: "prt_user", messageID: "msg_user", sessionID: "ses_1", type: "text", text: "hello" },
+ },
+ },
+ } as any)
+ for (const status of ["busy", "busy", "idle"]) {
+ await hooks.event!({
+ event: { type: "session.status", properties: { sessionID: "ses_1", status: { type: status } } },
+ } as any)
+ }
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } } as any)
+ await Bun.sleep(20)
+
+ expect(payloads.map((item) => item.type)).toEqual(["chat.message", "session.status", "session.status"])
+ expect(payloads.some((item) => item.type === "message.part.updated")).toBe(false)
+ })
+
+ test("correlates file deletion watcher events with an active bash call", async () => {
+ const hooks = await plugin()
+ const path = "/repo/.tmp/beacon-opencode-e2e.txt"
+ await hooks["tool.execute.before"]!(
+ { tool: "bash", sessionID: "ses_1", callID: "call_rm" },
+ { args: { command: `rm "${path}"` } },
+ )
+ await hooks.event!({
+ event: { type: "file.watcher.updated", properties: { file: path, event: "unlink" } },
+ } as any)
+ await Bun.sleep(20)
+
+ expect(payloads[1]).toMatchObject({
+ type: "file.watcher.updated",
+ session_id: "ses_1",
+ properties: { sessionID: "ses_1", callID: "call_rm", file: path, event: "unlink" },
+ })
+ })
})
diff --git a/plugins/opencode-beacon/src/beacon.ts b/plugins/opencode-beacon/src/beacon.ts
index be8c4d1e..9d9991df 100644
--- a/plugins/opencode-beacon/src/beacon.ts
+++ b/plugins/opencode-beacon/src/beacon.ts
@@ -20,6 +20,7 @@ const forwardedEvents = new Set([
"permission.v2.asked",
"permission.v2.replied",
"session.created",
+ "session.deleted",
"session.idle",
"session.status",
"session.error",
@@ -116,6 +117,19 @@ function isFileMutationTool(tool) {
return ["edit", "write", "patch", "apply_patch", "create"].some((part) => name.includes(part))
}
+function shellMutationPaths(tool, args) {
+ const name = String(tool || "").toLowerCase()
+ if (name !== "bash" && !name.includes("shell")) return []
+ const command = String(args?.command || args?.cmd || "")
+ const paths = []
+ const pattern = /\b(?:rm|unlink)\s+(?:-[^\s]+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))/g
+ for (const match of command.matchAll(pattern)) {
+ const path = match[1] || match[2] || match[3]
+ if (path) paths.push(path)
+ }
+ return paths
+}
+
export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {
const context = { project, directory, worktree }
const activeCalls = new Map()
@@ -124,6 +138,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const pendingParts = new Map()
const partDeltas = new Map()
const messageModels = new Map()
+ const messageRoles = new Map()
const completedMessages = new Set()
const permissionRequests = new Map()
const sessionStates = new Map()
@@ -138,9 +153,10 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
return eventQueue
}
const rememberFilePath = (tool, args, sid, callID) => {
- if (!isFileMutationTool(tool)) return
- const path = filePath(args)
- if (path) recentFilePaths.set(path, { time: Date.now(), sessionID: sid, callID })
+ const paths = []
+ if (isFileMutationTool(tool) && filePath(args)) paths.push(filePath(args))
+ paths.push(...shellMutationPaths(tool, args))
+ for (const path of paths) recentFilePaths.set(path, { time: Date.now(), sessionID: sid, callID })
}
const partKey = (part) => `${part?.sessionID || ""}:${part?.messageID || ""}:${part?.id || ""}`
const emitPart = (part, sid, model) => {
@@ -155,6 +171,19 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
if (status !== "completed" && status !== "error") return
if (status === "completed" && completedCalls.has(next.callID)) return
} else if (next.type === "text" || next.type === "reasoning") {
+ if (next.type === "text") {
+ const role = messageRoles.get(next.messageID)
+ if (role === "user") {
+ emittedParts.add(key)
+ pendingParts.delete(key)
+ partDeltas.delete(key)
+ return
+ }
+ if (role !== "assistant") {
+ pendingParts.set(key, { part: next, session_id: sid, model })
+ return
+ }
+ }
if (!next.time?.end) {
pendingParts.set(key, { part: next, session_id: sid, model })
return
@@ -178,6 +207,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
return {
"chat.message": async (input, output) => {
+ if (output?.message?.id) messageRoles.set(output.message.id, "user")
await sendToBeacon(client, {
type: "chat.message",
session_id: sessionID(input),
@@ -199,11 +229,14 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
)
},
"tool.execute.before": async (input, output) => {
+ const sid = sessionID(input)
activeCalls.set(input?.callID, {
tool: input?.tool,
args: structuredClone(output?.args || {}),
+ session_id: sid,
started_at: Date.now(),
})
+ rememberFilePath(input?.tool, output?.args || {}, sid, input?.callID)
await sendToBeacon(
client,
payload("tool.execute.before", {
@@ -240,6 +273,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const sid = sessionID(properties)
const info = properties?.info || {}
if (type === "message.updated") {
+ if (info?.id && info?.role) messageRoles.set(info.id, info.role)
if (info?.role !== "assistant") return
const model = modelName(info)
if (info?.id && model) messageModels.set(info.id, model)
@@ -261,6 +295,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
}
if (type === "session.status") {
const status = properties?.status?.type || ""
+ if (sessionStates.get(sid) === status) return
sessionStates.set(sid, status)
if (status === "idle") flushParts(sid)
}