Skip to content

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

feat(hooks): add the omp-event mapper for Oh My Pi

Claude93342fe3818a
diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.go
index 932b55c8..d3e6d950 100644
--- a/cli/beacon-hooks/cmd/helpers.go
+++ b/cli/beacon-hooks/cmd/helpers.go
@@ -125,10 +125,14 @@ func resolveSessionID(input map[string]interface{}, platform string) string {
// documented as common to both.
case "cline":
return getFirstStr(input, "taskId", "task_id", "sessionId", "session_id")
- // The Beacon extension lifts Pi's session id onto the envelope as `sessionId`, reading it from
+ // The Beacon extension lifts the session id onto the envelope as `sessionId`, reading it from
// the handler context's session manager per event. The snake_case spellings are a fallback for
// a payload that reached this command by some other route.
- case "pi":
+ //
+ // Oh My Pi shares this reader because it shares the envelope: its extension is built from the
+ // same contract. Some of its events -- the approval pair -- also carry a `sessionId` of their
+ // own, which lands on the same key and needs no separate spelling.
+ case "pi", "omp":
return getFirstStr(input, "sessionId", "session_id", "sessionID")
default:
id, _ := input["session_id"].(string)
@@ -253,10 +257,11 @@ func resolveCwd(input map[string]interface{}, platform string) string {
return cwd
}
}
- if platform == "pi" {
- // The extension lifts Pi's cwd onto the envelope, preferring the handler context's own cwd
- // and falling back to the session manager's. An event that carried its own cwd -- user_bash
- // does -- wins over both, because the extension spreads event fields last.
+ if platform == "pi" || platform == "omp" {
+ // The extension lifts the runtime's cwd onto the envelope, preferring the handler context's
+ // own cwd and falling back to the session manager's. An event that carried its own cwd --
+ // user_bash does, and so does Oh My Pi's user_python -- wins over both, because the
+ // extension spreads event fields last.
if cwd := getFirstStr(input, "cwd", "workingDirectory", "working_directory"); cwd != "" {
return cwd
}
diff --git a/cli/beacon-hooks/cmd/omp_event.go b/cli/beacon-hooks/cmd/omp_event.go
new file mode 100644
index 00000000..fb3bc018
--- /dev/null
+++ b/cli/beacon-hooks/cmd/omp_event.go
@@ -0,0 +1,53 @@
+package cmd
+
+import (
+ "github.com/spf13/cobra"
+)
+
+// omp-event is the single entry point for every Oh My Pi lifecycle payload.
+//
+// Oh My Pi (`omp`) loads Beacon as a TypeScript extension whose handlers all fire in the same
+// process, so one command receiving a typed envelope fits the runtime the way it does for Pi,
+// opencode and Cline, rather than the command-per-hook shape used by runtimes that exec a separate
+// hook per event.
+//
+// It is a separate command from pi-event, not a flag on it, because the two runtimes are separate
+// products: they install independently, they are recorded under separate harness names, and a
+// running install must not change which runtime it attributes events to. The event *mapping* is
+// shared (see pi_family.go) precisely because Oh My Pi forked Pi and kept its payload shapes.
+var ompEventCmd = &cobra.Command{
+ Use: "omp-event",
+ Short: "Record Oh My Pi hook telemetry",
+ Long: `omp-event receives raw Beacon Oh My Pi extension payloads and writes local endpoint telemetry.`,
+ Run: runOmpEvent,
+}
+
+func init() {
+ rootCmd.AddCommand(ompEventCmd)
+}
+
+func runOmpEvent(cmd *cobra.Command, args []string) {
+ runPiFamilyEvent(ompRuntime)
+}
+
+// supportedOmpEventTypes lists every Oh My Pi event type this mapper handles.
+//
+// Like supportedPiEventTypes, this is the contract between the managed extension's subscription
+// list and the mapper: a typo on either side produces no telemetry rather than an error, so both
+// sides pin the list and a test asserts each entry still maps to an event.
+//
+// Oh My Pi publishes considerably more than this -- provider request/response internals, streaming
+// message updates, compaction and retry signals, TUI plumbing. Those describe how the runtime got
+// its work done rather than what the agent did, and subscribing to them would fill the runtime log
+// with rows no investigation asks for while putting Beacon in the path of every streaming token.
+func supportedOmpEventTypes() []string {
+ return []string{
+ "session_start",
+ "session_shutdown",
+ "input",
+ "tool_call",
+ "tool_result",
+ "user_bash",
+ "message_end",
+ }
+}
diff --git a/cli/beacon-hooks/cmd/omp_event_test.go b/cli/beacon-hooks/cmd/omp_event_test.go
new file mode 100644
index 00000000..0b36e87a
--- /dev/null
+++ b/cli/beacon-hooks/cmd/omp_event_test.go
@@ -0,0 +1,463 @@
+package cmd
+
+import (
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+// ompTestLog puts an Oh My Pi extension run in a temp endpoint log and returns its path.
+func ompTestLog(t *testing.T) string {
+ t.Helper()
+ setupHookConfigDirs(t)
+ platformFlag = "omp"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_MODE", "1")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ t.Setenv("BEACON_CONTENT_RETENTION", "full")
+ return logPath
+}
+
+func ompEventActions(t *testing.T, logPath string) []string {
+ t.Helper()
+ var actions []string
+ for _, event := range endpointEvents(t, logPath) {
+ meta, _ := event["event"].(map[string]interface{})
+ actions = append(actions, meta["action"].(string))
+ }
+ return actions
+}
+
+func ompEventWithAction(t *testing.T, logPath, action string) map[string]interface{} {
+ t.Helper()
+ for _, event := range endpointEvents(t, logPath) {
+ meta, _ := event["event"].(map[string]interface{})
+ if meta["action"] == action {
+ return event
+ }
+ }
+ t.Fatalf("no %s event in log; got %v", action, ompEventActions(t, logPath))
+ return nil
+}
+
+// ompPayloads returns one payload per supported event type, each carrying the minimum its branch
+// needs to emit. Shared by the contract test and the Pi/Oh My Pi separation test.
+func ompPayloads() map[string]map[string]interface{} {
+ return map[string]map[string]interface{}{
+ "session_start": {"type": "session_start", "reason": "startup"},
+ "session_shutdown": {"type": "session_shutdown", "reason": "quit"},
+ "input": {"type": "input", "text": "do the thing", "source": "interactive"},
+ "tool_call": {"type": "tool_call", "toolName": "bash", "toolCallId": "c1", "input": map[string]interface{}{"command": "ls"}},
+ "tool_result": {"type": "tool_result", "toolName": "bash", "toolCallId": "c1", "input": map[string]interface{}{"command": "ls"}},
+ "user_bash": {"type": "user_bash", "command": "git status", "cwd": "/repo"},
+ "message_end": {"type": "message_end", "message": map[string]interface{}{
+ "role": "assistant",
+ "usage": map[string]interface{}{"input": float64(10), "output": float64(5)},
+ }},
+ }
+}
+
+// Every type the managed extension subscribes to must map to at least one event. These strings are
+// the contract between the extension's subscription list and this mapper, and a typo on either side
+// produces no telemetry rather than an error -- so the list is walked rather than trusted.
+func TestOmpEventEverySupportedTypeProducesTelemetry(t *testing.T) {
+ payloads := ompPayloads()
+ for _, name := range supportedOmpEventTypes() {
+ payload, ok := payloads[name]
+ if !ok {
+ t.Fatalf("no fixture for supported Oh My Pi event type %q; the mapper claims to handle it", name)
+ }
+ events := ompRuntime.endpointEvents(payload, "sess-1")
+ if len(events) == 0 {
+ t.Fatalf("supported Oh My Pi event type %q produced no telemetry", name)
+ }
+ }
+}
+
+// An unrecognized type is silent rather than generic. Oh My Pi publishes far more than the
+// extension subscribes to -- provider request/response internals, streaming message updates,
+// compaction and retry signals -- and a future one becoming an undifferentiated row would fill the
+// log with records no investigation asks for.
+func TestOmpEventUnknownTypeProducesNothing(t *testing.T) {
+ for _, name := range []string{
+ "message_update", "before_provider_request", "after_provider_response", "turn_start",
+ "auto_compaction_start", "ttsr_triggered", "", "totally_new",
+ } {
+ events := ompRuntime.endpointEvents(map[string]interface{}{"type": name}, "sess-1")
+ if len(events) != 0 {
+ t.Fatalf("Oh My Pi event type %q produced %d events, want none", name, len(events))
+ }
+ }
+}
+
+// Oh My Pi and Pi are separately installed products that a fleet can run side by side. Sharing the
+// mapper must not mean sharing identity: every event has to name the runtime that produced it, in
+// the harness name, in the message, and in the `raw` block an operator reads to see the payload.
+//
+// This is the test that fails if the shared core in pi_family.go ever starts hardcoding one
+// runtime's name -- which is the way a refactor like that goes wrong silently.
+func TestOmpEventIsAttributedToOhMyPiNotPi(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "session_start", "reason": "startup", "sessionId": "sess-1",
+ })
+
+ event := ompEventWithAction(t, logPath, "session.started")
+
+ // The harness name is normalized at write time, so an Oh My Pi session is not split across two
+ // spellings in any query that groups by harness.name -- and is never merged into Pi's.
+ harness := nested(t, event, "harness")
+ if harness["name"] != "omp" {
+ t.Fatalf("harness.name = %v, want omp", harness["name"])
+ }
+
+ if event["message"] != "Oh My Pi session started" {
+ t.Fatalf("message = %v, want it to name Oh My Pi", event["message"])
+ }
+
+ raw := nested(t, event, "raw")
+ if _, ok := raw["omp"]; !ok {
+ t.Fatalf("raw = %v, want the verbatim payload under an omp key", raw)
+ }
+ if _, ok := raw["pi"]; ok {
+ t.Fatalf("raw = %v, want no pi key on an Oh My Pi event", raw)
+ }
+ if raw["omp_session_reason"] != "startup" {
+ t.Fatalf("raw.omp_session_reason = %v, want startup", raw["omp_session_reason"])
+ }
+}
+
+// The converse, on the same shared mapper: a Pi payload must keep naming Pi. Together with the test
+// above, this pins the property that matters -- one shared shape, two identities -- rather than
+// just asserting each side in isolation.
+func TestPiAndOmpProduceTheSameShapeUnderDifferentIdentities(t *testing.T) {
+ for name, payload := range ompPayloads() {
+ t.Run(name, func(t *testing.T) {
+ piEvents := piRuntime.endpointEvents(cloneFields(payload), "sess-1")
+ ompEvents := ompRuntime.endpointEvents(cloneFields(payload), "sess-1")
+
+ if len(piEvents) != len(ompEvents) {
+ t.Fatalf("pi produced %d events and omp %d for %q; the shared mapper should emit "+
+ "the same events for the same payload", len(piEvents), len(ompEvents), name)
+ }
+ for i := range piEvents {
+ if piEvents[i].action != ompEvents[i].action {
+ t.Fatalf("action[%d] = %q (pi) vs %q (omp)", i, piEvents[i].action, ompEvents[i].action)
+ }
+ if piEvents[i].category != ompEvents[i].category || piEvents[i].severity != ompEvents[i].severity {
+ t.Fatalf("event[%d] category/severity differ between runtimes: %+v vs %+v",
+ i, piEvents[i], ompEvents[i])
+ }
+ if piEvents[i].message == ompEvents[i].message {
+ t.Fatalf("event[%d] message %q is identical for both runtimes; a reader could "+
+ "not tell which one produced it", i, piEvents[i].message)
+ }
+ if _, ok := piEvents[i].fields["raw"].(map[string]interface{})["pi"]; !ok {
+ t.Fatalf("pi event[%d] raw block is not keyed by pi: %v", i, piEvents[i].fields["raw"])
+ }
+ if _, ok := ompEvents[i].fields["raw"].(map[string]interface{})["omp"]; !ok {
+ t.Fatalf("omp event[%d] raw block is not keyed by omp: %v", i, ompEvents[i].fields["raw"])
+ }
+ }
+ })
+ }
+}
+
+// Beacon ships and versions the extension file Oh My Pi loads, so its events are plugin-collected,
+// not hook-collected. `event.fidelity` stays observed because every action here was named by the
+// runtime rather than derived by Beacon.
+func TestOmpEventCarriesPluginProvenance(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "input", "text": "hello", "sessionId": "sess-1",
+ })
+
+ event := ompEventWithAction(t, logPath, "prompt.submitted")
+ if method := nested(t, event, "harness")["collection_method"]; method != "plugin" {
+ t.Fatalf("harness.collection_method = %v, want plugin", method)
+ }
+ if fidelity := nested(t, event, "event")["fidelity"]; fidelity != "observed" {
+ t.Fatalf("event.fidelity = %v, want observed", fidelity)
+ }
+}
+
+func TestOmpEventPromptRecordsTextAndSource(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "input", "text": "refactor the parser", "source": "interactive", "sessionId": "sess-1",
+ })
+
+ event := ompEventWithAction(t, logPath, "prompt.submitted")
+ if prompt := nested(t, event, "prompt"); prompt["text"] != "refactor the parser" {
+ t.Fatalf("prompt.text = %v, want the submitted text", prompt["text"])
+ }
+ if content := nested(t, event, "content"); content["included"] != true || content["hash"] == "" {
+ t.Fatalf("content = %v, want retained content with a hash", content)
+ }
+ // "A human typed this" and "a script sent this" are different facts about the same prompt.
+ if raw := nested(t, event, "raw"); raw["omp_input_source"] != "interactive" {
+ t.Fatalf("raw.omp_input_source = %v, want interactive", raw["omp_input_source"])
+ }
+}
+
+// A tool_call is not an approval. Oh My Pi's tool_call handler can block a call, but that is an
+// extension deciding rather than an operator being asked; the runtime's real operator decisions
+// arrive as their own approval events. Recording a block as an approval would be indistinguishable
+// from a decision a human actually made.
+func TestOmpEventToolCallIsNotAnApproval(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "tool_call", "toolName": "bash", "toolCallId": "call-1",
+ "input": map[string]interface{}{"command": "rm -rf /tmp/x"}, "sessionId": "sess-1",
+ })
+
+ event := ompEventWithAction(t, logPath, "tool.invoked")
+ if tool := nested(t, event, "tool"); tool["name"] != "bash" || tool["command"] != "rm -rf /tmp/x" {
+ t.Fatalf("tool = %v, want the bash tool and its command", tool)
+ }
+ if _, ok := event["approval"]; ok {
+ t.Fatalf("tool.invoked carries an approval block: %v", event)
+ }
+}
+
+func TestOmpEventToolResultActionsPerTool(t *testing.T) {
+ for _, tc := range []struct {
+ tool string
+ args map[string]interface{}
+ action string
+ }{
+ {"bash", map[string]interface{}{"command": "ls"}, "command.executed"},
+ {"read", map[string]interface{}{"path": "/repo/main.go"}, "file.read"},
+ {"edit", map[string]interface{}{"path": "/repo/main.go"}, "file.modified"},
+ {"write", map[string]interface{}{"path": "/repo/new.go"}, "file.created"},
+ // grep takes a pattern and glob takes a glob. Neither is a file operation, and a custom
+ // tool registered by another extension means whatever its author decided.
+ {"grep", map[string]interface{}{"pattern": "TODO"}, "tool.completed"},
+ {"glob", map[string]interface{}{"pattern": "**/*.go"}, "tool.completed"},
+ {"my_custom_tool", map[string]interface{}{"anything": true}, "tool.completed"},
+ } {
+ t.Run(tc.tool, func(t *testing.T) {
+ events := ompRuntime.endpointEvents(map[string]interface{}{
+ "type": "tool_result", "toolName": tc.tool, "input": tc.args,
+ }, "sess-1")
+ if len(events) != 1 {
+ t.Fatalf("%s produced %d events, want 1", tc.tool, len(events))
+ }
+ if events[0].action != tc.action {
+ t.Fatalf("%s action = %q, want %q", tc.tool, events[0].action, tc.action)
+ }
+ })
+ }
+}
+
+func TestOmpEventFailedToolIsRecordedAsAFailure(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "tool_result", "toolName": "bash", "toolCallId": "call-1",
+ "input": map[string]interface{}{"command": "false"}, "isError": true, "sessionId": "sess-1",
+ })
+
+ event := ompEventWithAction(t, logPath, "tool.failed")
+ if event["severity"] != "high" {
+ t.Fatalf("severity = %v, want high for a failed tool", event["severity"])
+ }
+ if meta := nested(t, event, "event"); meta["category"] != "tool" {
+ t.Fatalf("category = %v, want tool", meta["category"])
+ }
+ if errBlock := nested(t, event, "error"); errBlock["type"] != "tool_error" {
+ t.Fatalf("error = %v, want a tool_error", errBlock)
+ }
+}
+
+func TestOmpEventEditResultRecordsTheUnifiedPatch(t *testing.T) {
+ logPath := ompTestLog(t)
+ patch := "--- a/main.go\n+++ b/main.go\n@@ -1 +1 @@\n-old\n+new\n"
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "tool_result", "toolName": "edit", "toolCallId": "call-1",
+ "input": map[string]interface{}{"path": "/repo/main.go"},
+ "details": map[string]interface{}{"patch": patch, "diff": "display-only"},
+ "sessionId": "sess-1",
+ })
+
+ event := ompEventWithAction(t, logPath, "file.modified")
+ file := nested(t, event, "file")
+ if file["path"] != "/repo/main.go" || file["operation"] != "modify" || file["language"] != "go" {
+ t.Fatalf("file = %v, want the edited Go file", file)
+ }
+ // The unified patch is the machine-readable form; the display `diff` is only a fallback, and
+ // it is shorter -- so the retained byte count is what distinguishes which one was recorded.
+ if content := nested(t, event, "content"); content["bytes"] != float64(len(patch)) {
+ t.Fatalf("content.bytes = %v, want the unified patch length %d", content["bytes"], len(patch))
+ }
+}
+
+// A command the operator ran with the `!` prefix is the one command shape here the agent did not
+// originate, so it is marked rather than merged in with agent-run commands.
+func TestOmpEventUserBashIsMarkedOperatorInitiated(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "user_bash", "command": "git status", "excludeFromContext": true,
+ "cwd": "/repo", "sessionId": "sess-1",
+ })
+
+ event := ompEventWithAction(t, logPath, "command.executed")
+ if command := nested(t, event, "command"); command["command"] != "git status" {
+ t.Fatalf("command = %v, want git status", command)
+ }
+ raw := nested(t, event, "raw")
+ if raw["omp_user_initiated"] != true {
+ t.Fatalf("raw.omp_user_initiated = %v, want true", raw["omp_user_initiated"])
+ }
+ if raw["omp_exclude_from_context"] != true {
+ t.Fatalf("raw.omp_exclude_from_context = %v, want true", raw["omp_exclude_from_context"])
+ }
+}
+
+// Oh My Pi reports token usage the same way Pi does, and `gen_ai.usage` stays the only place
+// Beacon records it. `output` already includes `reasoning`, so reasoning gets its own key and is
+// added to nothing; `totalTokens` is dropped rather than written as a field that can disagree with
+// its own parts.
+func TestOmpEventNormalizesTokenUsage(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "message_end", "sessionId": "sess-1",
+ "message": map[string]interface{}{
+ "role": "assistant",
+ "model": "anthropic/claude-opus-4",
+ "usage": map[string]interface{}{
+ "input": float64(120), "output": float64(45),
+ "cacheRead": float64(900), "cacheWrite": float64(30),
+ "reasoning": float64(12), "totalTokens": float64(1095),
+ "cost": map[string]interface{}{"total": 0.0123},
+ },
+ },
+ })
+
+ event := ompEventWithAction(t, logPath, "token.usage")
+ usage := nested(t, nested(t, event, "gen_ai"), "usage")
+ for key, want := range map[string]float64{
+ "input_tokens": 120, "output_tokens": 45, "cost_usd": 0.0123,
+ } {
+ if got, _ := usage[key].(float64); got != want {
+ t.Fatalf("gen_ai.usage.%s = %v, want %v", key, usage[key], want)
+ }
+ }
+ if got := nested(t, usage, "cache_read")["input_tokens"]; got != float64(900) {
+ t.Fatalf("cache_read.input_tokens = %v, want 900", got)
+ }
+ if got := nested(t, usage, "cache_creation")["input_tokens"]; got != float64(30) {
+ t.Fatalf("cache_creation.input_tokens = %v, want 30", got)
+ }
+ if got := nested(t, usage, "reasoning")["output_tokens"]; got != float64(12) {
+ t.Fatalf("reasoning.output_tokens = %v, want 12", got)
+ }
+ if _, ok := usage["total_tokens"]; ok {
+ t.Fatalf("gen_ai.usage carries a total: %v", usage)
+ }
+ if model := event["model"]; model != "anthropic/claude-opus-4" {
+ t.Fatalf("model = %v, want the responding model", model)
+ }
+}
+
+// Only the thinking parts are reasoning. The assistant's visible answer is not, and recording it as
+// such would put the model's output where a reader looking for its private deliberation expects to
+// find it.
+func TestOmpEventRecordsOnlyThinkingPartsAsReasoning(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "message_end", "sessionId": "sess-1",
+ "message": map[string]interface{}{
+ "role": "assistant",
+ "content": []interface{}{
+ map[string]interface{}{"type": "thinking", "thinking": "weighing two approaches"},
+ map[string]interface{}{"type": "text", "text": "I'll use the second one."},
+ },
+ },
+ })
+
+ event := ompEventWithAction(t, logPath, "agent.reasoning")
+ messages, ok := nested(t, nested(t, event, "gen_ai"), "output")["messages"].([]interface{})
+ if !ok || len(messages) != 1 {
+ t.Fatalf("gen_ai.output.messages = %v, want one message", messages)
+ }
+ parts, _ := messages[0].(map[string]interface{})["parts"].([]interface{})
+ if len(parts) != 1 {
+ t.Fatalf("parts = %v, want one reasoning part", parts)
+ }
+ part, _ := parts[0].(map[string]interface{})
+ if part["type"] != "reasoning" || part["content"] != "weighing two approaches" {
+ t.Fatalf("part = %v, want only the thinking text as a reasoning part", part)
+ }
+ // The retained content is the thinking text alone, not the thinking plus the visible answer.
+ thinking := "weighing two approaches"
+ if content := nested(t, event, "content"); content["bytes"] != float64(len(thinking)) {
+ t.Fatalf("content.bytes = %v, want just the thinking text (%d bytes); the assistant's "+
+ "visible answer must not be recorded as reasoning", content["bytes"], len(thinking))
+ }
+}
+
+// message_end fires for user and toolResult messages too. A message with neither usage nor
+// reasoning must produce nothing rather than an empty row per turn.
+func TestOmpEventBareMessageEndProducesNothing(t *testing.T) {
+ for _, message := range []map[string]interface{}{
+ {"role": "user", "content": []interface{}{}},
+ {"role": "assistant", "content": []interface{}{}},
+ {"role": "toolResult"},
+ } {
+ events := ompRuntime.endpointEvents(map[string]interface{}{
+ "type": "message_end", "message": message,
+ }, "sess-1")
+ if len(events) != 0 {
+ t.Fatalf("message_end for %v produced %d events, want none", message, len(events))
+ }
+ }
+}
+
+// The extension lifts the runtime's cwd onto the envelope; an event carrying its own cwd wins.
+func TestOmpEventResolvesWorkspaceFromTheEnvelope(t *testing.T) {
+ logPath := ompTestLog(t)
+ repo := t.TempDir()
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "input", "text": "hello", "sessionId": "sess-1", "cwd": repo,
+ })
+
+ event := ompEventWithAction(t, logPath, "prompt.submitted")
+ if session := nested(t, event, "session"); session["working_directory"] != repo {
+ t.Fatalf("session.working_directory = %v, want %q", session["working_directory"], repo)
+ }
+}
+
+func TestOmpEventGroupsBySessionID(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{
+ "type": "input", "text": "hello", "sessionId": "sess-42",
+ })
+
+ event := ompEventWithAction(t, logPath, "prompt.submitted")
+ if session := nested(t, event, "session"); session["id"] != "sess-42" {
+ t.Fatalf("session.id = %v, want sess-42", session["id"])
+ }
+}
+
+// A payload with no session id still produces telemetry. Losing the grouping key is bad; losing the
+// event is worse, and a run whose accessor failed once should not go dark.
+func TestOmpEventSurvivesAMissingSessionID(t *testing.T) {
+ logPath := ompTestLog(t)
+
+ runHookWithInput(t, runOmpEvent, map[string]interface{}{"type": "input", "text": "hello"})
+
+ if got := ompEventActions(t, logPath); !reflect.DeepEqual(got, []string{"prompt.submitted"}) {
+ t.Fatalf("actions = %v, want [prompt.submitted]", got)
+ }
+}
diff --git a/cli/beacon-hooks/cmd/pi_event.go b/cli/beacon-hooks/cmd/pi_event.go
index 76ffbaa2..bffac5d5 100644
--- a/cli/beacon-hooks/cmd/pi_event.go
+++ b/cli/beacon-hooks/cmd/pi_event.go
@@ -1,12 +1,7 @@
package cmd
import (
- "path/filepath"
- "strings"
-
"github.com/spf13/cobra"
-
- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
// pi-event is the single entry point for every Pi lifecycle payload.
@@ -14,6 +9,10 @@ import (
// Pi delivers its events to an in-process extension whose handlers all fire in the same process, so
// one command receiving a typed envelope fits better than the command-per-hook shape used for
// runtimes that exec a separate hook per event. This mirrors how opencode and Cline are integrated.
+//
+// The mapping itself lives in pi_family.go, shared with Oh My Pi, which kept Pi's extension event
+// shapes when it forked. What is not shared is identity: the two runtimes are recorded under
+// separate harness names and each event carries its own runtime's block in `raw`.
var piEventCmd = &cobra.Command{
Use: "pi-event",
Short: "Record Pi hook telemetry",
@@ -26,14 +25,22 @@ func init() {
}
func runPiEvent(cmd *cobra.Command, args []string) {
+ runPiFamilyEvent(piRuntime)
+}
+
+// runPiFamilyEvent reads one envelope from stdin and writes the events it justifies.
+//
+// Shared by pi-event and omp-event because the transport is identical -- the extension spawns the
+// hook binary and writes one JSON object to its stdin -- and only the runtime it describes differs.
+func runPiFamilyEvent(runtime piFamily) {
input, err := readStdinJSON()
if err != nil {
outputJSON(emptyResponse)
return
}
- sessionID := resolveSessionID(input, "pi")
- logger := newHookLogger("pi-event", "pi", sessionID)
- for _, event := range piEndpointEvents(input, sessionID) {
+ sessionID := resolveSessionID(input, runtime.platform)
+ logger := newHookLogger(runtime.platform+"-event", runtime.platform, sessionID)
+ for _, event := range runtime.endpointEvents(input, sessionID) {
if event.action == "" {
continue
}
@@ -44,7 +51,7 @@ func runPiEvent(cmd *cobra.Command, args []string) {
// supportedPiEventTypes lists every Pi event type this mapper handles.
//
-// These strings are the contract between the managed extension's subscription list and this mapper.
+// These strings are the contract between the managed extension's subscription list and the mapper.
// A typo on either side produces no telemetry rather than an error, so both sides pin the list and
// a test asserts each entry still maps to an event.
func supportedPiEventTypes() []string {
@@ -58,386 +65,3 @@ func supportedPiEventTypes() []string {
"message_end",
}
}
-
-// piEndpointEvents maps one Pi payload onto the endpoint events it justifies.
-//
-// An unrecognized type returns nothing rather than a generic event, for the same reason the Cline
-// mapper drops unknown stages: Pi publishes far more events than the extension subscribes to, and a
-// future one arriving here should be silent rather than becoming an undifferentiated
-// "something happened" row that every query matches and none can explain.
-func piEndpointEvents(input map[string]interface{}, sessionID string) []normalizedEvent {
- fields := piBaseFields(input, sessionID)
- one := func(action, category, severity, message string, values map[string]interface{}) []normalizedEvent {
- return []normalizedEvent{{action: action, category: category, severity: severity, message: message, fields: values}}
- }
-
- switch getFirstStr(input, "type") {
- case "session_start":
- // Pi reports why the session started -- startup, reload, new, resume, fork -- and the
- // distinction matters for reading a log: a fork and a resume both produce a session id that
- // has history behind it, which a reader counting sessions needs to know.
- if reason := getFirstStr(input, "reason"); reason != "" {
- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"pi_session_reason": reason})
- }
- return one("session.started", "session", "info", "Pi session started", fields)
-
- case "session_shutdown":
- if reason := getFirstStr(input, "reason"); reason != "" {
- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"pi_shutdown_reason": reason})
- }
- return one("session.ended", "session", "info", "Pi session ended", fields)
-
- case "input":
- prompt := getFirstStr(input, "text")
- if prompt == "" {
- return nil
- }
- return []normalizedEvent{piPromptEvent(fields, prompt, getFirstStr(input, "source"))}
-
- case "tool_call":
- // The pre-execution half of a tool call: Pi has decided to run it and named its arguments,
- // but nothing has happened yet. Recorded as tool.invoked to match the Cline mapper's
- // tool_before stage, and deliberately not as an approval -- Pi's tool_call handler can
- // block, but that is an extension deciding rather than an operator being asked, so there is
- // no approval decision here to observe.
- mergeMap(fields, piToolFields(input, false))
- return one("tool.invoked", "tool", "info", "Pi tool invoked", fields)
-
- case "tool_result":
- return piToolResultEvents(input, fields)
-
- case "user_bash":
- // A command the human ran with Pi's `!` prefix rather than one the agent chose. No tool
- // event covers it, and it is the one command shape in Pi that the agent did not originate,
- // so it is recorded with the operator noted in raw rather than silently merged in with
- // agent-run commands.
- command := getFirstStr(input, "command")
- if command == "" {
- return nil
- }
- fields["command"] = map[string]interface{}{"command": command}
- fields["tool"] = map[string]interface{}{"name": "user_bash", "command": command}
- fields["content"] = retainedContentFields(command)
- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{
- "pi_user_initiated": true,
- "pi_exclude_from_context": input["excludeFromContext"],
- })
- return one("command.executed", "command", "info", "Pi user command executed", fields)
-
- case "message_end":
- return piMessageEndEvents(input, fields)
-
- default:
- return nil
- }
-}
-
-func piBaseFields(input map[string]interface{}, sessionID string) map[string]interface{} {
- fields := sessionFieldsForPlatform(sessionID, input, "pi")
- applyWorkspaceFieldsForPlatform(fields, input, "", "pi")
- fields["raw"] = map[string]interface{}{"pi": input}
- if model := getFirstStr(input, "model"); model != "" {
- fields["model"] = model
- }
- return fields
-}
-
-func piPromptEvent(fields map[string]interface{}, prompt, source string) normalizedEvent {
- fields["prompt"] = map[string]interface{}{"text": prompt}
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
- "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
- })
- fields["content"] = retainedContentFields(prompt)
- if source != "" {
- // Pi distinguishes interactive input from input delivered over its RPC surface or injected
- // by another extension. Retained because "a human typed this" and "a script sent this" are
- // different facts about the same prompt.
- fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"pi_input_source": source})
- }
- return normalizedEvent{
- action: "prompt.submitted", category: "prompt", severity: "info",
- message: "Prompt submitted to Pi", fields: fields,
- }
-}
-
-// piToolName reads the tool name off a tool_call or tool_result payload.
-func piToolName(input map[string]interface{}) string {
- return getFirstStr(input, "toolName", "tool_name")
-}
-
-// piToolInput returns a tool call's arguments.
-//
-// tool_call carries them under `input`; tool_result carries the same arguments under `input` too,
-// which is what lets one function serve both and a file path survive onto the result event.
-func piToolInput(input map[string]interface{}) map[string]interface{} {
- if args := firstMap(input, "input", "args"); args != nil {
- return args
- }
- return map[string]interface{}{}
-}
-
-// piToolFields builds the tool, command, and file blocks for one Pi tool event.
-//
-// Pi's built-in tools have fixed, documented argument shapes -- bash takes `command`, and read,
-// edit and write all take `path` -- so these are read by name rather than by guessing across
-// spellings. A custom tool registered by another extension carries an arbitrary shape, and gets
-// tool.name plus its raw arguments without a command or file block invented for it.
-func piToolFields(input map[string]interface{}, withResult bool) map[string]interface{} {
- name := piToolName(input)
- args := piToolInput(input)
- fields := map[string]interface{}{}
- tool := map[string]interface{}{}
- if name != "" {
- tool["name"] = name
- }
-
- switch strings.ToLower(name) {
- case "bash":
- if command := getFirstStr(args, "command"); command != "" {
- tool["command"] = command
- fields["command"] = map[string]interface{}{"command": command}
- fields["content"] = retainedContentFields(command)
- }
- case "read", "edit", "write":
- if path := getFirstStr(args, "path"); path != "" {
- tool["path"] = path
- file := map[string]interface{}{
- "path": path,
- "operation": piFileOperation(name),
- }
- file["language"] = strings.TrimPrefix(filepath.Ext(path), ".")
- fields["file"] = file
- }
- }
-
- if len(tool) > 0 {
- fields["tool"] = tool
- }
- if withResult {
- if usage := piUsage(firstMap(input, "usage")); len(usage) > 0 {
- fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{"usage": usage})
- }
- }
- return fields
-}
-
-// piFileOperation maps a Pi file tool onto the operation vocabulary the event schema uses.
-func piFileOperation(name string) string {
- switch strings.ToLower(name) {
- case "read":
- return "read"
- case "write":
- return "create"
- default:
- return "modify"
- }
-}
-
-// piToolResultEvents maps a completed tool call onto its outcome event.
-func piToolResultEvents(input map[string]interface{}, fields map[string]interface{}) []normalizedEvent {
- mergeMap(fields, piToolFields(input, true))
- name := piToolName(input)
-
- if isErr, ok := input["isError"].(bool); ok && isErr {
- fields["error"] = map[string]interface{}{"type": "tool_error"}
- return []normalizedEvent{{
- action: "tool.failed", category: "tool", severity: "high",
- message: "Pi tool failed", fields: fields,
- }}
- }
-
- if diff := piEditDiff(input); diff != "" {
- fields["content"] = retainedContentFields(diff)
- }
-
- action, category := piToolAction(name)
- // A file action with no file is not a file action. Pi's read tool accepts a path that failed to
- // resolve, and a custom tool can share a built-in's name, so reporting file.read with no file
- // field would produce a row every file-scoped query matches and none can explain -- the same
- // guard clineToolAfterEvents applies for the same reason.
- if strings.HasPrefix(action, "file.") {
- if _, ok := fields["file"]; !ok {
- action, category = "tool.completed", "tool"
- }
- }
- if action == "command.executed" {
- if _, ok := fields["command"]; !ok {
- action, category = "tool.completed", "tool"
- }
- }
- return []normalizedEvent{{
- action: action, category: category, severity: "info",
- message: piToolMessage(action), fields: fields,
- }}
-}
-
-// piEditDiff returns the unified patch Pi's edit tool reports, when it reported one.
-//
-// Pi's EditToolDetails carries both a display-oriented `diff` and a standard unified `patch`. The
-// patch is preferred because it is the machine-readable one; the diff is a fallback for a details
-// object that carried only the display form.
-func piEditDiff(input map[string]interface{}) string {
- details := firstMap(input, "details")
- if details == nil {
- return ""
- }
- return getFirstStr(details, "patch", "diff")
-}
-
-// piToolAction maps a Pi tool name onto the endpoint action its completion represents.
-func piToolAction(name string) (string, string) {
- switch strings.ToLower(name) {
- case "bash":
- return "command.executed", "command"
- case "read":
- return "file.read", "file"
- case "edit":
- return "file.modified", "file"
- case "write":
- return "file.created", "file"
- default:
- // grep, find, ls, and any tool another extension registered. These are real tool activity
- // with no file or command semantics worth asserting: grep takes a pattern, not a path, and
- // a custom tool's arguments mean whatever its author decided.
- return "tool.completed", "tool"
- }
-}
-
-func piToolMessage(action string) string {
- switch action {
- case "command.executed":
- return "Pi command executed"
- case "file.read":
- return "Pi file read"
- case "file.created":
- return "Pi file created"
- case "file.modified":
- return "Pi file modified"
- case "tool.failed":
- return "Pi tool failed"
- default:
- return "Pi tool completed"
- }
-}
-
-// piMessageEndEvents records what a finished assistant message tells us: its token usage, and the
-// model's reasoning when the provider returned any.
-//
-// A finalized message is the only place Pi reports usage, and message_end fires for user and
-// toolResult messages too, so a message with neither usage nor reasoning produces nothing rather
-// than an empty row per turn.
-func piMessageEndEvents(input map[string]interface{}, fields map[string]interface{}) []normalizedEvent {
- message := firstMap(input, "message")
- if message == nil {
- return nil
- }
- if role := getFirstStr(message, "role"); role != "assistant" {
- return nil
- }
- if model := getFirstStr(message, "model", "responseModel"); model != "" {
- fields["model"] = model
- }
-
- var events []normalizedEvent
-
- if reasoning := piReasoningText(message); reasoning != "" {
- reasoningFields := cloneFields(fields)
- reasoningFields["gen_ai"] = mergeNested(reasoningFields["gen_ai"], map[string]interface{}{
- "output": map[string]interface{}{
- "messages": []interface{}{map[string]interface{}{
- "role": "assistant",
- "parts": []interface{}{map[string]interface{}{"type": "reasoning", "content": reasoning}},
- }},
- },
- })
- reasoningFields["content"] = retainedContentFields(reasoning)
- events = append(events, normalizedEvent{
- action: "agent.reasoning", category: "reasoning", severity: "info",
- message: "Pi agent reasoning", fields: reasoningFields,
- })
- }
-
- if usage := piUsage(firstMap(message, "usage")); len(usage) > 0 {
- usageFields := cloneFields(fields)
- usageFields["gen_ai"] = mergeNested(usageFields["gen_ai"], map[string]interface{}{"usage": usage})
- events = append(events, normalizedEvent{
- action: "token.usage", category: "metric", severity: "info",
- message: "Pi token usage", fields: usageFields,
- })
- }
-
- return events
-}
-
-// piReasoningText concatenates the thinking parts of an assistant message.
-//
-// Pi's 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 ""
- }
- var parts []string
- for _, item := range content {
- part, ok := item.(map[string]interface{})
- if !ok {
- continue
- }
- if getFirstStr(part, "type") != "thinking" {
- continue
- }
- if text := getFirstStr(part, "thinking", "text", "content"); text != "" {
- parts = append(parts, text)
- }
- }
- return strings.Join(parts, "\n")
-}
-
-// piUsage normalizes Pi's Usage object into gen_ai.usage.
-//
-// Pi names its fields input/output/cacheRead/cacheWrite/reasoning and nests cost under `cost`, none
-// of which match the OTel GenAI semconv names Beacon writes, and two of which are nested objects on
-// Beacon's side rather than scalars. The mapping is spelled out against the canonical
-// GenAIUsageInfo shape rather than copied through, so gen_ai.usage stays the only token
-// representation in the log and no parallel per-harness field appears beside it.
-//
-// Pi's `output` already includes its `reasoning` tokens, so reasoning is recorded under its own key
-// but never added to anything: treating it as a separate bucket would double-count it in any total.
-// Pi also reports a `totalTokens`, which is deliberately dropped -- Beacon's usage shape has no
-// total, and a redundant field that can disagree with its own parts is worse than an absent one.
-func piUsage(usage map[string]interface{}) map[string]interface{} {
- if usage == nil {
- return nil
- }
- sources := []map[string]interface{}{usage}
- out := map[string]interface{}{}
- if value, ok := firstToolIntAcross(sources, "input"); ok {
- out["input_tokens"] = value
- }
- if value, ok := firstToolIntAcross(sources, "output"); ok {
- out["output_tokens"] = value
- }
- if value, ok := firstToolIntAcross(sources, "cacheRead"); ok {
- out["cache_read"] = map[string]interface{}{"input_tokens": value}
- }
- if value, ok := firstToolIntAcross(sources, "cacheWrite"); ok {
- out["cache_creation"] = map[string]interface{}{"input_tokens": value}
- }
- if value, ok := firstToolIntAcross(sources, "reasoning"); ok {
- out["reasoning"] = map[string]interface{}{"output_tokens": value}
- }
- // Runtime-reported cost only. Beacon never derives cost from a local pricing table, so a Pi
- // build or provider that reports no cost leaves the field absent rather than estimated.
- if cost := firstMap(usage, "cost"); cost != nil {
- if value, ok := jsonFloat(cost["total"]); ok {
- out["cost_usd"] = value
- }
- }
- if len(out) == 0 {
- return nil
- }
- return out
-}
diff --git a/cli/beacon-hooks/cmd/pi_event_test.go b/cli/beacon-hooks/cmd/pi_event_test.go
index 2289fd03..77939d74 100644
--- a/cli/beacon-hooks/cmd/pi_event_test.go
+++ b/cli/beacon-hooks/cmd/pi_event_test.go
@@ -62,7 +62,7 @@ func TestPiEventEverySupportedTypeProducesTelemetry(t *testing.T) {
if !ok {
t.Fatalf("no fixture for supported Pi event type %q; the mapper claims to handle it", name)
}
- events := piEndpointEvents(payload, "sess-1")
+ events := piRuntime.endpointEvents(payload, "sess-1")
if len(events) == 0 {
t.Fatalf("supported Pi event type %q produced no telemetry", name)
}
@@ -74,7 +74,7 @@ func TestPiEventEverySupportedTypeProducesTelemetry(t *testing.T) {
// with records no query asks for.
func TestPiEventUnknownTypeProducesNothing(t *testing.T) {
for _, name := range []string{"message_update", "before_provider_request", "turn_start", "", "totally_new"} {
- events := piEndpointEvents(map[string]interface{}{"type": name}, "sess-1")
+ events := piRuntime.endpointEvents(map[string]interface{}{"type": name}, "sess-1")
if len(events) != 0 {
t.Fatalf("Pi event type %q produced %d events, want none", name, len(events))
}
@@ -133,7 +133,7 @@ func TestPiEventInputRecordsPrompt(t *testing.T) {
// An input event with no text is Pi announcing an empty submission. Recording a prompt event with
// no prompt would put a row in the log that every prompt query matches and none can explain.
func TestPiEventEmptyInputProducesNothing(t *testing.T) {
- events := piEndpointEvents(map[string]interface{}{"type": "input", "source": "interactive"}, "sess-1")
+ events := piRuntime.endpointEvents(map[string]interface{}{"type": "input", "source": "interactive"}, "sess-1")
if len(events) != 0 {
t.Fatalf("empty input produced %d events, want none", len(events))
}
@@ -197,7 +197,7 @@ func TestPiEventToolResultActionsPerTool(t *testing.T) {
{"my_custom_tool", map[string]interface{}{"anything": true}, "tool.completed"},
} {
t.Run(tc.tool, func(t *testing.T) {
- events := piEndpointEvents(map[string]interface{}{
+ events := piRuntime.endpointEvents(map[string]interface{}{
"type": "tool_result", "toolName": tc.tool, "input": tc.args,
}, "sess-1")
if len(events) != 1 {
@@ -214,7 +214,7 @@ func TestPiEventToolResultActionsPerTool(t *testing.T) {
// resolve, and a custom tool can share a built-in's name, so a file.read with no file field would
// produce a row every file-scoped query matches and none can explain.
func TestPiEventFileActionWithoutAPathFallsBackToTool(t *testing.T) {
- events := piEndpointEvents(map[string]interface{}{
+ events := piRuntime.endpointEvents(map[string]interface{}{
"type": "tool_result", "toolName": "read", "input": map[string]interface{}{},
}, "sess-1")
if len(events) != 1 || events[0].action != "tool.completed" {
@@ -225,7 +225,7 @@ func TestPiEventFileActionWithoutAPathFallsBackToTool(t *testing.T) {
// The same guard on the command side: a bash result whose arguments carried no command is a tool
// call, not a command execution, and rules/risky-command/ all match on command.command.
func TestPiEventCommandActionWithoutACommandFallsBackToTool(t *testing.T) {
- events := piEndpointEvents(map[string]interface{}{
+ events := piRuntime.endpointEvents(map[string]interface{}{
"type": "tool_result", "toolName": "bash", "input": map[string]interface{}{},
}, "sess-1")
if len(events) != 1 || events[0].action != "tool.completed" {
@@ -362,7 +362,7 @@ func TestPiEventMessageEndRecordsUsageAndReasoning(t *testing.T) {
// empty usage record in the log on every turn.
func TestPiEventMessageEndIgnoresNonAssistantMessages(t *testing.T) {
for _, role := range []string{"user", "toolResult"} {
- events := piEndpointEvents(map[string]interface{}{
+ events := piRuntime.endpointEvents(map[string]interface{}{
"type": "message_end",
"message": map[string]interface{}{"role": role, "usage": map[string]interface{}{"input": float64(5)}},
}, "sess-1")
@@ -375,7 +375,7 @@ func TestPiEventMessageEndIgnoresNonAssistantMessages(t *testing.T) {
// An assistant message with neither usage nor reasoning is a message Beacon has nothing to say
// about, which is different from one it failed to read.
func TestPiEventMessageEndWithNothingToReportProducesNothing(t *testing.T) {
- events := piEndpointEvents(map[string]interface{}{
+ events := piRuntime.endpointEvents(map[string]interface{}{
"type": "message_end",
"message": map[string]interface{}{"role": "assistant", "content": []interface{}{}},
}, "sess-1")
diff --git a/cli/beacon-hooks/cmd/pi_family.go b/cli/beacon-hooks/cmd/pi_family.go
new file mode 100644
index 00000000..564fe41e
--- /dev/null
+++ b/cli/beacon-hooks/cmd/pi_family.go
@@ -0,0 +1,433 @@
+package cmd
+
+import (
+ "path/filepath"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// The Pi family is Pi (pi.dev) and the forks that kept its extension API.
+//
+// Oh My Pi is a fork of pi-mono, and its extension event payloads are structurally the same as
+// Pi's: the same `type` discriminator, the same `toolName`/`input`/`details` shape on tool events,
+// the same assistant message parts, and the same input/output/cacheRead/cacheWrite/cost usage
+// object. Mapping them twice would mean two copies of that knowledge drifting apart -- and the
+// drift would be silent, because a mapper that stops recognizing a field emits an event missing a
+// column rather than an error.
+//
+// So the shape lives here once, and each runtime supplies only what actually differs: which
+// `--platform` it was installed as, and what to call it in an event message. What must NOT be
+// shared is the identity: the two are separately installed products, they get separate harness
+// names (see asymptoteobserve.NormalizeHarnessName), and every event carries its own runtime's
+// name in `raw` so an operator reading a row can tell which binary produced it.
+//
+// Events one runtime has and the other does not are mapped by that runtime, not here. Oh My Pi
+// exposes operator approval decisions and Pi does not, and inventing a Pi approval to keep the two
+// symmetric would put a decision nobody made into the log.
+type piFamily struct {
+ // platform is the `--platform` value the runtime's hook is installed with. It selects the
+ // session-id and working-directory readers in helpers.go, keys this runtime's block inside
+ // `raw`, and prefixes the runtime-specific keys nested under it.
+ platform string
+ // displayName is how the runtime is named in an event's human-readable message.
+ displayName string
+}
+
+var (
+ piRuntime = piFamily{platform: "pi", displayName: "Pi"}
+ ompRuntime = piFamily{platform: "omp", displayName: "Oh My Pi"}
+)
+
+// rawKey namespaces a runtime-specific detail inside the `raw` block.
+//
+// These keys sit beside the verbatim payload rather than being promoted to schema fields, because
+// they describe how one runtime happened to phrase something rather than a fact the endpoint event
+// schema defines. Prefixing them with the platform keeps a Pi row and an Oh My Pi row from
+// colliding in a store that flattens `raw`.
+func (f piFamily) rawKey(suffix string) string {
+ return f.platform + "_" + suffix
+}
+
+// endpointEvents maps one Pi-family payload onto the endpoint events it justifies.
+//
+// An unrecognized type returns nothing rather than a generic event, for the same reason the Cline
+// mapper drops unknown stages: these runtimes publish far more events than the extension
+// subscribes to, and a future one arriving here should be silent rather than becoming an
+// undifferentiated "something happened" row that every query matches and none can explain.
+func (f piFamily) endpointEvents(input map[string]interface{}, sessionID string) []normalizedEvent {
+ fields := f.baseFields(input, sessionID)
+
+ switch getFirstStr(input, "type") {
+ case "session_start":
+ // The runtime reports why the session started -- startup, reload, new, resume, fork -- and
+ // the distinction matters for reading a log: a fork and a resume both produce a session id
+ // that has history behind it, which a reader counting sessions needs to know.
+ if reason := getFirstStr(input, "reason"); reason != "" {
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{f.rawKey("session_reason"): reason})
+ }
+ return f.one("session.started", "session", "info", "session started", fields)
+
+ case "session_shutdown":
+ if reason := getFirstStr(input, "reason"); reason != "" {
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{f.rawKey("shutdown_reason"): reason})
+ }
+ return f.one("session.ended", "session", "info", "session ended", fields)
+
+ case "input":
+ prompt := getFirstStr(input, "text")
+ if prompt == "" {
+ return nil
+ }
+ return []normalizedEvent{f.promptEvent(fields, prompt, getFirstStr(input, "source"))}
+
+ case "tool_call":
+ // The pre-execution half of a tool call: the runtime has decided to run it and named its
+ // arguments, but nothing has happened yet. Recorded as tool.invoked to match the Cline
+ // mapper's tool_before stage, and deliberately not as an approval -- a tool_call handler
+ // can block, but that is an extension deciding rather than an operator being asked. Oh My
+ // Pi's real approval decisions arrive as their own events and are mapped there.
+ mergeMap(fields, f.toolFields(input, false))
+ return f.one("tool.invoked", "tool", "info", "tool invoked", fields)
+
+ case "tool_result":
+ return f.toolResultEvents(input, fields)
+
+ case "user_bash":
+ // A command the human ran with the `!` prefix rather than one the agent chose. No tool
+ // event covers it, and it is the one command shape here that the agent did not originate,
+ // so it is recorded with the operator noted in raw rather than silently merged in with
+ // agent-run commands.
+ command := getFirstStr(input, "command")
+ if command == "" {
+ return nil
+ }
+ fields["command"] = map[string]interface{}{"command": command}
+ fields["tool"] = map[string]interface{}{"name": "user_bash", "command": command}
+ fields["content"] = retainedContentFields(command)
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{
+ f.rawKey("user_initiated"): true,
+ f.rawKey("exclude_from_context"): input["excludeFromContext"],
+ })
+ return f.one("command.executed", "command", "info", "user command executed", fields)
+
+ case "message_end":
+ return f.messageEndEvents(input, fields)
+
+ default:
+ return nil
+ }
+}
+
+// one wraps a single event, prefixing the runtime's display name onto the message.
+//
+// Messages are built from a suffix rather than spelled out per runtime so that "Pi tool failed"
+// and "Oh My Pi tool failed" cannot drift into describing the same thing two different ways.
+func (f piFamily) one(action, category, severity, messageSuffix string, values map[string]interface{}) []normalizedEvent {
+ return []normalizedEvent{{
+ action: action,
+ category: category,
+ severity: severity,
+ message: f.displayName + " " + messageSuffix,
+ fields: values,
+ }}
+}
+
+func (f piFamily) baseFields(input map[string]interface{}, sessionID string) map[string]interface{} {
+ fields := sessionFieldsForPlatform(sessionID, input, f.platform)
+ applyWorkspaceFieldsForPlatform(fields, input, "", f.platform)
+ fields["raw"] = map[string]interface{}{f.platform: input}
+ if model := getFirstStr(input, "model"); model != "" {
+ fields["model"] = model
+ }
+ return fields
+}
+
+func (f piFamily) promptEvent(fields map[string]interface{}, prompt, source string) normalizedEvent {
+ fields["prompt"] = map[string]interface{}{"text": prompt}
+ fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
+ "input": map[string]interface{}{"messages": asymptoteobserve.TextInputMessages(prompt)},
+ })
+ fields["content"] = retainedContentFields(prompt)
+ if source != "" {
+ // These runtimes distinguish interactive input from input delivered over their RPC surface
+ // or injected by another extension. Retained because "a human typed this" and "a script
+ // sent this" are different facts about the same prompt.
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{f.rawKey("input_source"): source})
+ }
+ return normalizedEvent{
+ action: "prompt.submitted", category: "prompt", severity: "info",
+ message: "Prompt submitted to " + f.displayName, fields: fields,
+ }
+}
+
+// piToolName reads the tool name off a tool_call or tool_result payload.
+func piToolName(input map[string]interface{}) string {
+ return getFirstStr(input, "toolName", "tool_name")
+}
+
+// piToolInput returns a tool call's arguments.
+//
+// tool_call carries them under `input`; tool_result carries the same arguments under `input` too,
+// which is what lets one function serve both and a file path survive onto the result event.
+func piToolInput(input map[string]interface{}) map[string]interface{} {
+ if args := firstMap(input, "input", "args"); args != nil {
+ return args
+ }
+ return map[string]interface{}{}
+}
+
+// toolFields builds the tool, command, and file blocks for one Pi-family tool event.
+//
+// The built-in tools have fixed, documented argument shapes -- bash takes `command`, and read,
+// edit and write all take `path` -- so these are read by name rather than by guessing across
+// spellings. A custom tool registered by another extension carries an arbitrary shape, and gets
+// tool.name plus its raw arguments without a command or file block invented for it.
+func (f piFamily) toolFields(input map[string]interface{}, withResult bool) map[string]interface{} {
+ name := piToolName(input)
+ args := piToolInput(input)
+ fields := map[string]interface{}{}
+ tool := map[string]interface{}{}
+ if name != "" {
+ tool["name"] = name
+ }
+
+ switch strings.ToLower(name) {
+ case "bash":
+ if command := getFirstStr(args, "command"); command != "" {
+ tool["command"] = command
+ fields["command"] = map[string]interface{}{"command": command}
+ fields["content"] = retainedContentFields(command)
+ }
+ case "read", "edit", "write":
+ if path := getFirstStr(args, "path"); path != "" {
+ tool["path"] = path
+ file := map[string]interface{}{
+ "path": path,
+ "operation": piFileOperation(name),
+ }
+ file["language"] = strings.TrimPrefix(filepath.Ext(path), ".")
+ fields["file"] = file
+ }
+ }
+
+ if len(tool) > 0 {
+ fields["tool"] = tool
+ }
+ if withResult {
+ if usage := piUsage(firstMap(input, "usage")); len(usage) > 0 {
+ fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{"usage": usage})
+ }
+ }
+ return fields
+}
+
+// piFileOperation maps a Pi-family file tool onto the operation vocabulary the event schema uses.
+func piFileOperation(name string) string {
+ switch strings.ToLower(name) {
+ case "read":
+ return "read"
+ case "write":
+ return "create"
+ default:
+ return "modify"
+ }
+}
+
+// toolResultEvents maps a completed tool call onto its outcome event.
+func (f piFamily) toolResultEvents(input map[string]interface{}, fields map[string]interface{}) []normalizedEvent {
+ mergeMap(fields, f.toolFields(input, true))
+ name := piToolName(input)
+
+ if isErr, ok := input["isError"].(bool); ok && isErr {
+ fields["error"] = map[string]interface{}{"type": "tool_error"}
+ return f.one("tool.failed", "tool", "high", "tool failed", fields)
+ }
+
+ if diff := piEditDiff(input); diff != "" {
+ fields["content"] = retainedContentFields(diff)
+ }
+
+ action, category := piToolAction(name)
+ // A file action with no file is not a file action. The read tool accepts a path that failed to
+ // resolve, and a custom tool can share a built-in's name, so reporting file.read with no file
+ // field would produce a row every file-scoped query matches and none can explain -- the same
+ // guard clineToolAfterEvents applies for the same reason.
+ if strings.HasPrefix(action, "file.") {
+ if _, ok := fields["file"]; !ok {
+ action, category = "tool.completed", "tool"
+ }
+ }
+ if action == "command.executed" {
+ if _, ok := fields["command"]; !ok {
+ action, category = "tool.completed", "tool"
+ }
+ }
+ return f.one(action, category, "info", piToolMessageSuffix(action), fields)
+}
+
+// piEditDiff returns the unified patch the edit tool reports, when it reported one.
+//
+// EditToolDetails carries both a display-oriented `diff` and a standard unified `patch`. The patch
+// is preferred because it is the machine-readable one; the diff is a fallback for a details object
+// that carried only the display form.
+func piEditDiff(input map[string]interface{}) string {
+ details := firstMap(input, "details")
+ if details == nil {
+ return ""
+ }
+ return getFirstStr(details, "patch", "diff")
+}
+
+// piToolAction maps a Pi-family tool name onto the endpoint action its completion represents.
+func piToolAction(name string) (string, string) {
+ switch strings.ToLower(name) {
+ case "bash":
+ return "command.executed", "command"
+ case "read":
+ return "file.read", "file"
+ case "edit":
+ return "file.modified", "file"
+ case "write":
+ return "file.created", "file"
+ default:
+ // grep, glob, and any tool another extension registered. These are real tool activity with
+ // no file or command semantics worth asserting: grep takes a pattern, not a path, and a
+ // custom tool's arguments mean whatever its author decided.
+ return "tool.completed", "tool"
+ }
+}
+
+// piToolMessageSuffix returns the runtime-independent half of a tool event's message.
+func piToolMessageSuffix(action string) string {
+ switch action {
+ case "command.executed":
+ return "command executed"
+ case "file.read":
+ return "file read"
+ case "file.created":
+ return "file created"
+ case "file.modified":
+ return "file modified"
+ case "tool.failed":
+ return "tool failed"
+ default:
+ return "tool completed"
+ }
+}
+
+// messageEndEvents records what a finished assistant message tells us: its token usage, and the
+// model's reasoning when the provider returned any.
+//
+// A finalized message is the only place these runtimes report usage, and message_end fires for
+// user and toolResult messages too, so a message with neither usage nor 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")
+ if message == nil {
+ return nil
+ }
+ if role := getFirstStr(message, "role"); role != "assistant" {
+ return nil
+ }
+ if model := getFirstStr(message, "model", "responseModel"); model != "" {
+ fields["model"] = model
+ }
+
+ var events []normalizedEvent
+
+ if reasoning := piReasoningText(message); reasoning != "" {
+ reasoningFields := cloneFields(fields)
+ reasoningFields["gen_ai"] = mergeNested(reasoningFields["gen_ai"], map[string]interface{}{
+ "output": map[string]interface{}{
+ "messages": []interface{}{map[string]interface{}{
+ "role": "assistant",
+ "parts": []interface{}{map[string]interface{}{"type": "reasoning", "content": reasoning}},
+ }},
+ },
+ })
+ reasoningFields["content"] = retainedContentFields(reasoning)
+ events = append(events, f.one("agent.reasoning", "reasoning", "info", "agent reasoning", reasoningFields)...)
+ }
+
+ if usage := piUsage(firstMap(message, "usage")); len(usage) > 0 {
+ usageFields := cloneFields(fields)
+ usageFields["gen_ai"] = mergeNested(usageFields["gen_ai"], map[string]interface{}{"usage": usage})
+ events = append(events, f.one("token.usage", "metric", "info", "token usage", usageFields)...)
+ }
+
+ return events
+}
+
+// piReasoningText concatenates the thinking parts of an assistant message.
+//
+// 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 ""
+ }
+ var parts []string
+ for _, item := range content {
+ part, ok := item.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ if getFirstStr(part, "type") != "thinking" {
+ continue
+ }
+ if text := getFirstStr(part, "thinking", "text", "content"); text != "" {
+ parts = append(parts, text)
+ }
+ }
+ return strings.Join(parts, "\n")
+}
+
+// piUsage normalizes a Pi-family Usage object into gen_ai.usage.
+//
+// These runtimes name their fields input/output/cacheRead/cacheWrite/reasoning and nest cost under
+// `cost`, none of which match the OTel GenAI semconv names Beacon writes, and two of which are
+// nested objects on Beacon's side rather than scalars. The mapping is spelled out against the
+// canonical GenAIUsageInfo shape rather than copied through, so gen_ai.usage stays the only token
+// representation in the log and no parallel per-harness field appears beside it.
+//
+// `output` already includes `reasoning` tokens, so reasoning is recorded under its own key but
+// never added to anything: treating it as a separate bucket would double-count it in any total.
+// A `totalTokens` is also reported and deliberately dropped -- Beacon's usage shape has no total,
+// and a redundant field that can disagree with its own parts is worse than an absent one.
+func piUsage(usage map[string]interface{}) map[string]interface{} {
+ if usage == nil {
+ return nil
+ }
+ sources := []map[string]interface{}{usage}
+ out := map[string]interface{}{}
+ if value, ok := firstToolIntAcross(sources, "input"); ok {
+ out["input_tokens"] = value
+ }
+ if value, ok := firstToolIntAcross(sources, "output"); ok {
+ out["output_tokens"] = value
+ }
+ if value, ok := firstToolIntAcross(sources, "cacheRead"); ok {
+ out["cache_read"] = map[string]interface{}{"input_tokens": value}
+ }
+ if value, ok := firstToolIntAcross(sources, "cacheWrite"); ok {
+ out["cache_creation"] = map[string]interface{}{"input_tokens": value}
+ }
+ if value, ok := firstToolIntAcross(sources, "reasoning"); ok {
+ out["reasoning"] = map[string]interface{}{"output_tokens": value}
+ }
+ // Runtime-reported cost only. Beacon never derives cost from a local pricing table, so a build
+ // or provider that reports no cost leaves the field absent rather than estimated.
+ if cost := firstMap(usage, "cost"); cost != nil {
+ if value, ok := jsonFloat(cost["total"]); ok {
+ out["cost_usd"] = value
+ }
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}