Skip to content

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

fix: preserve OpenCode delta and cost telemetry

Cursor Agent475a22bdae17
diff --git a/cli/beacon-hooks/cmd/opencode_event.go b/cli/beacon-hooks/cmd/opencode_event.go
index 4b95bce7..a2f2e034 100644
--- a/cli/beacon-hooks/cmd/opencode_event.go
+++ b/cli/beacon-hooks/cmd/opencode_event.go
@@ -506,9 +506,6 @@ func opencodeAssistantFields(info map[string]interface{}) map[string]interface{}
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
diff --git a/cli/beacon-hooks/cmd/opencode_event_test.go b/cli/beacon-hooks/cmd/opencode_event_test.go
index 6bf7de11..2dd20058 100644
--- a/cli/beacon-hooks/cmd/opencode_event_test.go
+++ b/cli/beacon-hooks/cmd/opencode_event_test.go
@@ -287,6 +287,27 @@ func TestOpenCodeCompletedAssistantNormalizesUsageOnce(t *testing.T) {
}
}
+func TestOpenCodeAssistantPreservesCostWithoutTokens(t *testing.T) {
+ action, _, _, _, fields := opencodeEndpointEvent(map[string]interface{}{
+ "type": "message.updated",
+ "session_id": "ses_test",
+ "properties": map[string]interface{}{
+ "info": map[string]interface{}{
+ "id": "msg_cost", "role": "assistant",
+ "providerID": "moonshotai", "modelID": "kimi-k3",
+ "finish": "stop", "cost": 0.25,
+ },
+ },
+ }, "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["cost_usd"] != 0.25 {
+ t.Fatalf("usage = %#v", usage)
+ }
+}
+
func TestOpenCodePartNormalization(t *testing.T) {
for _, tt := range []struct {
partType string
diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
index bcfeb41a..ad37c21c 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
@@ -159,16 +159,17 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
.catch((err) => debugLog(client, "Beacon event queue failed", { error: String(err), type: value?.type }))
return eventQueue
}
- const rememberFilePath = (tool, args, sid, callID) => {
+ const rememberFilePath = (tool, args, sid, callID, includeShell = false) => {
const paths = []
if (isFileMutationTool(tool) && filePath(args)) paths.push(filePath(args))
- paths.push(...shellMutationPaths(tool, args))
+ if (includeShell) 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 partKey = (part, fallbackSessionID) =>
+ `${part?.sessionID || fallbackSessionID || ""}:${part?.messageID || ""}:${part?.id || ""}`
const emitPart = (part, sid, model) => {
if (!part) return
- const key = partKey(part)
+ const key = partKey(part, sid)
if (emittedParts.has(key)) return
const next = structuredClone(part)
const delta = partDeltas.get(key)
@@ -286,7 +287,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const active = activeCalls.get(input?.callID)
const args = input?.args || active?.args || {}
const exitCode = output?.metadata?.exit ?? output?.metadata?.exitCode ?? output?.metadata?.exit_code
- rememberFilePath(input?.tool, args, sessionID(input), input?.callID)
+ rememberFilePath(input?.tool, args, sessionID(input), input?.callID, exitCode === 0)
await enqueue(
payload("tool.execute.after", {
session_id: sessionID(input),
diff --git a/plugins/opencode-beacon/src/beacon.test.ts b/plugins/opencode-beacon/src/beacon.test.ts
index 3c43d823..8975a8e0 100644
--- a/plugins/opencode-beacon/src/beacon.test.ts
+++ b/plugins/opencode-beacon/src/beacon.test.ts
@@ -261,6 +261,50 @@ describe("BeaconEndpointPlugin", () => {
expect(payloads[0].part.text).toBe("late role")
})
+ test("joins deltas when the completed part omits its session ID", async () => {
+ const hooks = await plugin()
+ await hooks.event!({
+ event: {
+ type: "message.updated",
+ properties: {
+ sessionID: "ses_1",
+ info: { id: "msg_delta", role: "assistant", providerID: "moonshotai", modelID: "kimi-k3", time: {} },
+ },
+ },
+ } as any)
+ await hooks.event!({
+ event: {
+ type: "message.part.delta",
+ properties: {
+ sessionID: "ses_1",
+ messageID: "msg_delta",
+ partID: "prt_delta",
+ field: "text",
+ delta: "streamed text",
+ },
+ },
+ } as any)
+ await hooks.event!({
+ event: {
+ type: "message.part.updated",
+ properties: {
+ sessionID: "ses_1",
+ part: {
+ id: "prt_delta",
+ messageID: "msg_delta",
+ type: "text",
+ text: "",
+ time: { start: 1, end: 2 },
+ },
+ },
+ },
+ } as any)
+ await Bun.sleep(20)
+
+ expect(payloads).toHaveLength(1)
+ expect(payloads[0].part.text).toBe("streamed text")
+ })
+
test("idle flush does not loop when a pending part still has no role", async () => {
const hooks = await plugin()
await hooks.event!({
@@ -350,8 +394,19 @@ describe("BeaconEndpointPlugin", () => {
{ tool: "bash", sessionID: "ses_1", callID: "call_rm_unknown", args: { command: `rm "${path}"` } },
{ title: "rm", output: "", metadata: {} },
)
+ await hooks.event!({
+ event: {
+ type: "session.diff",
+ properties: {
+ sessionID: "ses_1",
+ diff: [{ file: path, before: "present", after: "", additions: 0, deletions: 1 }],
+ },
+ },
+ } as any)
+ await Bun.sleep(20)
expect(payloads[1].file_mutations).toEqual([])
+ expect(payloads[2].type).toBe("session.diff")
})
test("does not treat substrings inside custom tool names as file mutations", async () => {
diff --git a/plugins/opencode-beacon/src/beacon.ts b/plugins/opencode-beacon/src/beacon.ts
index bcfeb41a..ad37c21c 100644
--- a/plugins/opencode-beacon/src/beacon.ts
+++ b/plugins/opencode-beacon/src/beacon.ts
@@ -159,16 +159,17 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
.catch((err) => debugLog(client, "Beacon event queue failed", { error: String(err), type: value?.type }))
return eventQueue
}
- const rememberFilePath = (tool, args, sid, callID) => {
+ const rememberFilePath = (tool, args, sid, callID, includeShell = false) => {
const paths = []
if (isFileMutationTool(tool) && filePath(args)) paths.push(filePath(args))
- paths.push(...shellMutationPaths(tool, args))
+ if (includeShell) 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 partKey = (part, fallbackSessionID) =>
+ `${part?.sessionID || fallbackSessionID || ""}:${part?.messageID || ""}:${part?.id || ""}`
const emitPart = (part, sid, model) => {
if (!part) return
- const key = partKey(part)
+ const key = partKey(part, sid)
if (emittedParts.has(key)) return
const next = structuredClone(part)
const delta = partDeltas.get(key)
@@ -286,7 +287,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const active = activeCalls.get(input?.callID)
const args = input?.args || active?.args || {}
const exitCode = output?.metadata?.exit ?? output?.metadata?.exitCode ?? output?.metadata?.exit_code
- rememberFilePath(input?.tool, args, sessionID(input), input?.callID)
+ rememberFilePath(input?.tool, args, sessionID(input), input?.callID, exitCode === 0)
await enqueue(
payload("tool.execute.after", {
session_id: sessionID(input),