The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(hooks): retain finalized assistant answers from Pi sessions (#984)
Divyam Talwar72b3d7196e61
diff --git a/cli/beacon-hooks/cmd/assistant_response.go b/cli/beacon-hooks/cmd/assistant_response.goindex 4f38be49..e5bb7b6a 100644--- a/cli/beacon-hooks/cmd/assistant_response.go+++ b/cli/beacon-hooks/cmd/assistant_response.go@@ -51,8 +51,16 @@ func emitStopAssistantResponse(logger *logging.Logger, input map[string]interfac// nothing: an empty agent.message would assert the agent answered with nothing, which is different// from the runtime not reporting an answer.func emitAssistantMessage(logger *logging.Logger, input, fields map[string]interface{}, text string) {+ event := assistantMessageEvent(fields, text)+ if event.action != "" {+ emitHookEvent(logger, event.action, event.category, event.severity, event.message, input, event.fields)+ }+}++// assistantMessageEvent shares the reply shape with stream mappers that return events for writing.+func assistantMessageEvent(fields map[string]interface{}, text string) normalizedEvent {if strings.TrimSpace(text) == "" {- return+ return normalizedEvent{}}if fields == nil {fields = map[string]interface{}{}@@ -61,5 +69,8 @@ func emitAssistantMessage(logger *logging.Logger, input, fields map[string]inter"output": map[string]interface{}{"messages": asymptoteobserve.TextOutputMessages(text)},})fields["content"] = retainedContentFields(text)- emitHookEvent(logger, "agent.message", "session", "info", "Agent response captured", input, fields)+ return normalizedEvent{+ action: "agent.message", category: "session", severity: "info",+ message: "Agent response captured", fields: fields,+ }}diff --git a/cli/beacon-hooks/cmd/pi_assistant_response_test.go b/cli/beacon-hooks/cmd/pi_assistant_response_test.gonew file mode 100644index 00000000..3b641ee8--- /dev/null+++ b/cli/beacon-hooks/cmd/pi_assistant_response_test.go@@ -0,0 +1,156 @@+package cmd++import (+ "encoding/json"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++// All four managed extensions already forward this native message_end shape; their existing+// usage/reasoning tests contain the same thinking and text parts.+func TestPiFamilyFinalizedAssistantReplyReachesChat(t *testing.T) {+ for _, runtime := range []struct {+ platform string+ harness string+ }{+ {"pi", "pi_cli"}, {"omp", "omp"}, {"prime", "prime_agent"}, {"omo", "omo_senpi"},+ } {+ t.Run(runtime.platform, func(t *testing.T) {+ input := map[string]interface{}{+ "type": "message_end", "sessionId": "final-reply-session",+ "message": map[string]interface{}{+ "role": "assistant", "model": "test-model",+ "content": []interface{}{+ map[string]interface{}{"type": "thinking", "thinking": "compare the approaches"},+ map[string]interface{}{"type": "text", "text": "First paragraph."},+ map[string]interface{}{"type": "text", "text": "Second paragraph."},+ },+ "usage": map[string]interface{}{+ "input": 10, "output": 5, "cost": map[string]interface{}{"total": 0.0042},+ },+ },+ }+ started := time.Now()+ logPath, stdout := runHookProcess(t, input, "--platform", runtime.platform, runtime.platform+"-event")+ finished := time.Now()+ var recorded struct {+ Recorded int `json:"recorded"`+ }+ if err := json.Unmarshal(stdout, &recorded); err != nil {+ t.Fatal(err)+ }+ events := endpointEvents(t, logPath)+ messages := assistantMessages(t, logPath)+ if len(messages) != 1 {+ t.Fatalf("finalized assistant replies = %d, want 1; actions=%v recorded=%d", len(messages), piEventActions(t, logPath), recorded.Recorded)+ }+ wantText := "First paragraph.\nSecond paragraph."+ if got := outputText(t, messages[0]); got != wantText {+ t.Fatalf("assistant text = %q, want %q", got, wantText)+ }+ if recorded.Recorded != 3 || len(events) != 3 {+ t.Fatalf("recorded=%d events=%d, want reply, reasoning and usage once each", recorded.Recorded, len(events))+ }+ ids := map[string]bool{}+ usageEvents := 0+ for _, event := range events {+ for _, check := range []struct {+ path []string+ want string+ }{+ {[]string{"harness", "name"}, runtime.harness},+ {[]string{"harness", "collection_method"}, asymptoteobserve.CollectionMethodPlugin},+ {[]string{"session", "id"}, "final-reply-session"},+ {[]string{"model"}, "test-model"},+ {[]string{"event", "fidelity"}, asymptoteobserve.FidelityObserved},+ } {+ if got := leaf(event, check.path...); got != check.want {+ t.Errorf("%s = %q, want %q", strings.Join(check.path, "."), got, check.want)+ }+ }+ id := leaf(event, "event", "id")+ if id == "" || ids[id] {+ t.Errorf("missing or duplicate event ID %q", id)+ }+ ids[id] = true+ if got := leaf(event, "trace", "id"); got != asymptoteobserve.DerivedTraceIDForSession(runtime.harness, "final-reply-session") {+ t.Errorf("trace.id = %q", got)+ }+ timestamp, err := time.Parse(time.RFC3339Nano, leaf(event, "timestamp"))+ if err != nil || timestamp.Before(started) || timestamp.After(finished) {+ t.Errorf("timestamp=%v err=%v, want actual hook emission time within [%v, %v]", timestamp, err, started, finished)+ }+ genAI := nested(t, event, "gen_ai")+ if leaf(event, "event", "action") == "token.usage" {+ usageEvents+++ usage := nested(t, event, "gen_ai", "usage")+ if usage["input_tokens"] != float64(10) || usage["output_tokens"] != float64(5) || usage["cost_usd"] != 0.0042 {+ t.Errorf("usage = %#v, want the single runtime-reported token/cost record", usage)+ }+ if _, present := genAI["output"]; present {+ t.Error("reply/reasoning output leaked into usage event")+ }+ } else if _, present := genAI["usage"]; present {+ t.Error("usage duplicated onto a content event")+ }+ }+ if usageEvents != 1 {+ t.Fatalf("usage events = %d, want 1", usageEvents)+ }+ reasoning := piEventWithAction(t, logPath, "agent.reasoning")+ output := nested(t, reasoning, "gen_ai", "output")+ if got := asymptoteobserve.GenAIText(output["messages"], asymptoteobserve.RoleAssistant, asymptoteobserve.GenAIPartTypeReasoning); !reflect.DeepEqual(got, []string{"compare the approaches"}) {+ t.Fatalf("reasoning = %q, want only thinking", got)+ }+ if outputText(t, reasoning) != "" {+ t.Error("visible answer was recorded as reasoning")+ }+ var replies []string+ for _, message := range chatView(t, logPath) {+ if message.Kind == asymptoteobserve.TraceMessageKindAssistant {+ replies = append(replies, message.Text)+ }+ }+ if !reflect.DeepEqual(replies, []string{wantText}) {+ t.Fatalf("chat replies = %q, want the finalized visible answer once", replies)+ }+ })+ }+}++func TestPiFinalizedAssistantReplyOnlyRecordsVisibleText(t *testing.T) {+ for _, tc := range []struct {+ name string+ role string+ content []interface{}+ want string+ }{+ {"text-only", "assistant", []interface{}{map[string]interface{}{"type": "text", "text": "The final answer."}}, "The final answer."},+ {"blank-text", "assistant", []interface{}{map[string]interface{}{"type": "text", "text": " \n\t"}}, ""},+ {"no-text", "assistant", nil, ""},+ {"non-text-parts", "assistant", []interface{}{map[string]interface{}{"type": "toolCall", "name": "read"}}, ""},+ {"user", "user", []interface{}{map[string]interface{}{"type": "text", "text": "User text"}}, ""},+ {"tool-result", "toolResult", []interface{}{map[string]interface{}{"type": "text", "text": "Tool text"}}, ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ logPath, stdout := runHookProcess(t, map[string]interface{}{+ "type": "message_end", "sessionId": "reply-only-session",+ "message": map[string]interface{}{"role": tc.role, "content": tc.content},+ }, "--platform", "pi", "pi-event")+ events := endpointEventsIfAny(t, logPath)+ if tc.want == "" {+ if len(events) != 0 || strings.TrimSpace(string(stdout)) != `{"recorded":0}` {+ t.Fatalf("events=%v stdout=%s, want no telemetry for absent assistant text", events, stdout)+ }+ return+ }+ if len(events) != 1 || leaf(events[0], "event", "action") != "agent.message" || outputText(t, events[0]) != tc.want {+ t.Fatalf("events=%#v, want just the visible reply %q", events, tc.want)+ }+ })+ }+}diff --git a/cli/beacon-hooks/cmd/pi_family.go b/cli/beacon-hooks/cmd/pi_family.goindex 79116d86..e8dea8b5 100644--- a/cli/beacon-hooks/cmd/pi_family.go+++ b/cli/beacon-hooks/cmd/pi_family.go@@ -1306,12 +1306,12 @@ func (f piFamily) userMessagePromptEvents(input, fields map[string]interface{})return events}-// messageEndEvents records what a finished assistant message tells us: its token usage, and the+// messageEndEvents records a finished assistant message's visible text, token usage, and the// model's reasoning when the provider returned any. A user message is a prompt; see// userMessagePromptEvents.//// A finalized message is the only place these runtimes report usage, and message_end fires for-// toolResult messages too, so a message with neither usage nor reasoning produces nothing rather+// toolResult messages too, so a message with no text, usage or reasoning produces nothing rather// than an empty row per turn.func (f piFamily) messageEndEvents(input map[string]interface{}, fields map[string]interface{}) []normalizedEvent {message := firstMap(input, "message")@@ -1331,7 +1331,7 @@ func (f piFamily) messageEndEvents(input map[string]interface{}, fields map[strivar events []normalizedEvent- if reasoning := piReasoningText(message); reasoning != "" {+ if reasoning := piPartsText(message, "thinking", "thinking", "text", "content"); reasoning != "" {reasoningFields := cloneFields(fields)reasoningFields["gen_ai"] = mergeNested(reasoningFields["gen_ai"], map[string]interface{}{"output": map[string]interface{}{@@ -1345,6 +1345,10 @@ func (f piFamily) messageEndEvents(input map[string]interface{}, fields map[strievents = append(events, f.one("agent.reasoning", "reasoning", "info", "agent reasoning", reasoningFields)...)}+ if reply := assistantMessageEvent(cloneFields(fields), piPartsText(message, "text", "text")); reply.action != "" {+ events = append(events, reply)+ }+if usage := piUsage(firstMap(message, "usage")); len(usage) > 0 {usageFields := cloneFields(fields)usageFields["gen_ai"] = mergeNested(usageFields["gen_ai"], map[string]interface{}{"usage": usage})@@ -1354,27 +1358,21 @@ func (f piFamily) messageEndEvents(input map[string]interface{}, fields map[strireturn events}-// piReasoningText concatenates the thinking parts of an assistant message.+// piPartsText concatenates the parts of an assistant message that have the given type.//// Assistant content is a list of parts, and a reasoning model emits thinking alongside text in the-// same message. Only the thinking parts are collected here: the assistant's visible answer is not-// reasoning, and recording it as such would put the model's output where a reader looking for its-// private deliberation expects to find it.-func piReasoningText(message map[string]interface{}) string {- content, ok := message["content"].([]interface{})- if !ok {- return ""- }+// same message. Thinking parts are reasoning and text parts are the visible answer; keeping them+// apart keeps the model's output out of where a reader looking for its private deliberation expects+// to find it.+func piPartsText(message map[string]interface{}, partType string, keys ...string) string {+ content, _ := message["content"].([]interface{})var parts []stringfor _, item := range content {part, ok := item.(map[string]interface{})- if !ok {- continue- }- if getFirstStr(part, "type") != "thinking" {+ if !ok || getFirstStr(part, "type") != partType {continue}- if text := getFirstStr(part, "thinking", "text", "content"); text != "" {+ if text := getFirstStr(part, keys...); text != "" {parts = append(parts, text)}}diff --git a/docs/runtimes/index.mdx b/docs/runtimes/index.mdxindex 1c335919..c6329da7 100644--- a/docs/runtimes/index.mdx+++ b/docs/runtimes/index.mdx@@ -37,13 +37,13 @@ These integrations are grouped by where the agent runs and how telemetry is coll| [Kimi Code](/runtimes/kimi-code) | Native hooks appended to the `[[hooks]]` array of Kimi Code's own `$KIMI_CODE_HOME/config.toml` | Session start and end, prompts, pre-tool and post-tool activity, failed tools, real operator approval decisions, commands with output and exit code, file reads and edits with diffs, MCP tool calls, subagents, and context compaction. No token usage or agent message text, because Kimi Code exposes neither on a hook || [Kiro](/runtimes/kiro) | Native hooks through a Beacon-owned file in `.kiro/hooks/` | Session start, prompts, pre-tool and post-tool activity, commands with output, file reads and edits, MCP tool calls, failed tools, and the agent's final response. No approval decisions or token usage, because Kiro exposes neither on a hook || [Muse Code](/runtimes/muse-code) | Native hooks through a managed hooks file | Session start, prompt, pre-tool, post-tool, permission request, subagent, context compaction, stop, command, and file telemetry |-| [Oh My Pi](/runtimes/oh-my-pi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, operator approval decisions, commands including operator `!` and `$` commands, file reads and edits with the unified patch, MCP tool activity, agent reasoning, and token usage |+| [Oh My Pi](/runtimes/oh-my-pi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, operator approval decisions, commands including operator `!` and `$` commands, file reads and edits with the unified patch, MCP tool activity, assistant replies, agent reasoning, and token usage || [OpenCode](/runtimes/opencode) | Managed plugin hooks plus optional poll of OpenCode's local session store through `beacon endpoint opencode sync` | Plugin: chat messages, session events, command execution, permission activity, diffs, and errors. Poll: historical prompts, assistant text/reasoning, tool outcomes, commands, file activity with paths, compaction, and token usage where persisted. Approval telemetry comes from the live plugin only || [OpenHands](/runtimes/openhands) | Native hooks merged into the repository's own `.openhands/hooks.json` | Session start and end, prompts, pre-tool and post-tool activity, commands with exit codes and output, file reads and edits with exact before/after diffs, MCP tool calls, and failed tools. No approval decisions or token usage, because OpenHands exposes neither on a hook |-| [Pi](/runtimes/pi) | Managed extension hooks plus optional poll of Pi's local session store through `beacon endpoint pi sync` | Extension: session lifecycle, prompts, tool lifecycle, commands including operator `!` commands, file reads and edits with the unified patch, agent reasoning, and token usage. Poll: historical prompts, assistant text/reasoning, tool calls/results, commands, file activity with paths and diffs where persisted, compaction, skill-load records, and token usage. No approval decisions, because Pi exposes none |-| [Prime Agent](/runtimes/prime-agent) | Managed extension hooks plus optional poll of Prime Agent's session files through `beacon endpoint prime sync` | Extension: session lifecycle, prompts, tool lifecycle, commands including each `ipython` kernel cell and operator `!` commands, file edits with the unified patch, agent reasoning, and token usage. Poll: historical prompts, assistant messages and reasoning, tool results, context attachments, errors, compactions, refinement state, and subagent artifacts. No approval decisions, because Prime Agent exposes none |+| [Pi](/runtimes/pi) | Managed extension hooks plus optional poll of Pi's local session store through `beacon endpoint pi sync` | Extension: session lifecycle, prompts, tool lifecycle, commands including operator `!` commands, file reads and edits with the unified patch, assistant replies, agent reasoning, and token usage. Poll: historical prompts, assistant text/reasoning, tool calls/results, commands, file activity with paths and diffs where persisted, compaction, skill-load records, and token usage. No approval decisions, because Pi exposes none |+| [Prime Agent](/runtimes/prime-agent) | Managed extension hooks plus optional poll of Prime Agent's session files through `beacon endpoint prime sync` | Extension: session lifecycle, prompts, tool lifecycle, commands including each `ipython` kernel cell and operator `!` commands, file edits with the unified patch, assistant replies, agent reasoning, and token usage. Poll: historical prompts, assistant messages and reasoning, tool results, context attachments, errors, compactions, refinement state, and subagent artifacts. No approval decisions, because Prime Agent exposes none || [Qwen Code](/runtimes/qwen-code) | Native hooks | Session, prompt, pre-tool, post-tool, failed tool, permission request, subagent, stop, session-end, command, and file telemetry |-| [Senpi](/runtimes/senpi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, commands including operator `!` commands, file reads and edits with the unified patch, agent reasoning, and token usage. The standalone `omo` edition of oh-my-openagent; its OpenCode and Codex CLI editions ride the existing OpenCode and Codex CLI integrations instead. No approval decisions, because Senpi exposes none through its extension API |+| [Senpi](/runtimes/senpi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle, commands including operator `!` commands, file reads and edits with the unified patch, assistant replies, agent reasoning, and token usage. The standalone `omo` edition of oh-my-openagent; its OpenCode and Codex CLI editions ride the existing OpenCode and Codex CLI integrations instead. No approval decisions, because Senpi exposes none through its extension API || [VS Code](/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 |Poll collection reads records a runtime has already committed to disk, so every event from those paths is marked `harness.collection_method=poll`. It is useful for backfill and scheduled catch-up, but it cannot hold, approve, deny, or delay a tool call. [fx](/runtimes/vercel-fx) is the pure poll case because it exposes no hook, plugin, or OpenTelemetry surface at all; the other poll paths complement live hooks, plugins, or OTLP export.diff --git a/docs/runtimes/oh-my-pi.mdx b/docs/runtimes/oh-my-pi.mdxindex 49d1cc54..129b286b 100644--- a/docs/runtimes/oh-my-pi.mdx+++ b/docs/runtimes/oh-my-pi.mdx@@ -105,6 +105,7 @@ Unlike Pi, a project-level install needs no trust prompt: Oh My Pi loads `.omp`| Commands | Supported. `command.executed` for the agent's `bash` tool, with its output in `command.output`, for commands you run with the `!` prefix, and for code you run with the `$` Python prefix — the last two marked as operator-initiated || File activity | Supported. `file.read`, `file.created`, and `file.modified` under the absolute path Oh My Pi resolved, with the edit's diff. An edit that changes several files records one `file.modified` per file. Only filesystem targets count: see [file paths](#file-paths) and [tool devices and URIs](#tool-devices-and-uris) || MCP activity | Supported. `tool.invoked` then `mcp.tool_invoked`, whether the model called the tool directly or through its `xd://` device. `mcp.server` and `mcp.tool` are the server's configured name and the tool's own name, read from the result Oh My Pi reports. A `read mcp://<uri>` is recorded as an MCP `resources/read` with `mcp.resource.uri` |+| Agent responses | Supported. `agent.message` from a finished assistant message's text parts || Agent reasoning | Supported. `agent.reasoning` from an assistant message's thinking parts, in the OTel GenAI reasoning-part shape || Model-visible skill listings | Supported through the `context` event's `ctx.getSystemPrompt()`; Beacon retains only the `<skills>` index under the system prompt's `# Skills & Rules` heading, one part per skill in `gen_ai.system_instructions` with the skills named in `system_context`, not the full system prompt or skill bodies || Model-visible MCP tool descriptions | Supported through the same `context` event. Beacon reads only the rows under the system prompt's `## MCP Tool Routes` heading and records one `mcp.tool_listed` per described tool, with the device name in `gen_ai.tool.name` and the description in `gen_ai.tool.description`, once per session and again when it changes |diff --git a/docs/runtimes/pi.mdx b/docs/runtimes/pi.mdxindex e41160da..be87820b 100644--- a/docs/runtimes/pi.mdx+++ b/docs/runtimes/pi.mdx@@ -96,6 +96,7 @@ Install writes one file and refuses to touch a `beacon.ts` it did not write, so| Tool use | Supported. `tool.invoked` before execution, then `tool.completed` or `tool.failed` || Commands | Supported. `command.executed` for the agent's `bash` tool, with its output in `command.output`, and for commands you run with Pi's `!` prefix, which are marked as operator-initiated || File activity | Supported. `file.read`, `file.created`, and `file.modified`, with the unified patch on an edit. A read's result is kept in `gen_ai.tool.call.result`, which rules match as `e.gen_ai.tool.call.result_text` |+| Agent responses | Supported. `agent.message` from a finished assistant message's text parts || Agent reasoning | Supported. `agent.reasoning` from an assistant message's thinking parts, in the OTel GenAI reasoning-part shape || Token usage and cost | Supported. `token.usage` normalized into `gen_ai.usage`, including cache and reasoning tokens and runtime-reported cost || Approval decisions | Not available. Pi exposes no operator approval decision to observe. See [Known gaps](#known-gaps) |diff --git a/docs/runtimes/prime-agent.mdx b/docs/runtimes/prime-agent.mdxindex 88e0bdc0..87898736 100644--- a/docs/runtimes/prime-agent.mdx+++ b/docs/runtimes/prime-agent.mdx@@ -112,6 +112,7 @@ Install writes one file and refuses to touch a `beacon.ts` it did not write, so| Tool use | Supported. `tool.invoked` before execution, then `tool.completed` or `tool.failed` || Commands | Supported. `command.executed` for each `ipython` cell, for the optional `bash` tool, and for commands you run with the `!` prefix, which are marked as operator-initiated. A cell's result carries its captured output, the runtime's own duration, and its status, and a `bash` call's output is in `command.output` || File activity | Supported. `file.modified` per file a kernel cell rewrote, with the unified patch; plus `file.modified` for the optional `edit` tool, carrying the unified diff it reports |+| Agent responses | Supported. `agent.message` from a finished assistant message's text parts || Agent reasoning | Supported. `agent.reasoning` from an assistant message's thinking parts, in the OTel GenAI reasoning-part shape || Token usage and cost | Supported. `token.usage` normalized into `gen_ai.usage`, including cache and reasoning tokens and runtime-reported cost || Approval decisions | Not available. Prime Agent exposes no operator approval decision to observe. See [Known gaps](#known-gaps) |diff --git a/docs/runtimes/senpi.mdx b/docs/runtimes/senpi.mdxindex d17237e7..a5000774 100644--- a/docs/runtimes/senpi.mdx+++ b/docs/runtimes/senpi.mdx@@ -103,6 +103,7 @@ Install writes one file and refuses to touch a `beacon.ts` it did not write, so| Tool use | Supported. `tool.invoked` before execution, then `tool.completed` or `tool.failed` || Commands | Supported. `command.executed` for the `bash` tool, with its output in `command.output`, and for commands you run with the `!` prefix, which are marked as operator-initiated || File activity | Supported. `file.read`, `file.created`, and `file.modified` for the `read`, `write`, and `edit` tools, the last carrying the unified patch. A read's result is kept in `gen_ai.tool.call.result`, which rules match as `e.gen_ai.tool.call.result_text` |+| Agent responses | Supported. `agent.message` from a finished assistant message's text parts || Agent reasoning | Supported. `agent.reasoning` from an assistant message's thinking parts, in the OTel GenAI reasoning-part shape || Token usage and cost | Supported. `token.usage` normalized into `gen_ai.usage`, including cache and reasoning tokens and runtime-reported cost || Approval decisions | Not available. Senpi exposes no operator approval decision through its extension API. See [Known gaps](#known-gaps) |