Skip to content

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

Add the Prime Agent hook adapter

Claude6ff6164d36c2
diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.go
index db0a6f0a..504d41a6 100644
--- a/cli/beacon-hooks/cmd/helpers.go
+++ b/cli/beacon-hooks/cmd/helpers.go
@@ -137,10 +137,10 @@ func resolveSessionID(input map[string]interface{}, platform string) string {
// 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.
//
- // 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":
+ // Oh My Pi and Prime Agent share this reader because they share the envelope: both extensions
+ // are built from the same contract. Some Oh My Pi 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", "prime":
return getFirstStr(input, "sessionId", "session_id", "sessionID")
default:
id, _ := input["session_id"].(string)
@@ -265,7 +265,7 @@ func resolveCwd(input map[string]interface{}, platform string) string {
return cwd
}
}
- if platform == "pi" || platform == "omp" {
+ if platform == "pi" || platform == "omp" || platform == "prime" {
// 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
diff --git a/cli/beacon-hooks/cmd/pi_family.go b/cli/beacon-hooks/cmd/pi_family.go
index 4f03aa6f..07aebd2b 100644
--- a/cli/beacon-hooks/cmd/pi_family.go
+++ b/cli/beacon-hooks/cmd/pi_family.go
@@ -4,29 +4,31 @@ import (
"path/filepath"
"strings"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/diff"
"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.
+// Oh My Pi and Prime Agent are both hard forks of pi-mono, and their 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 three times would mean three
+// 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.
+// shared is the identity: they 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 here too, and gated by the subscription
-// list rather than by a branch: Oh My Pi's extension subscribes to its approval and user_python
-// events, Pi's does not, so those cases are simply never reached for Pi. That is a stronger
+// Events one runtime has and the others do not are mapped here too, and gated by the subscription
+// list and the tool catalog rather than by a branch: Oh My Pi's extension subscribes to its
+// approval and user_python events and Pi's does not, and only Prime Agent ships an `ipython` tool,
+// so those cases are simply never reached for the runtimes that lack them. That is a stronger
// guarantee than a platform check would be -- Beacon cannot synthesize a Pi approval because Pi
-// never sends one, not because a condition remembered to say so. Inventing one to keep the two
+// never sends one, not because a condition remembered to say so. Inventing one to keep the
// runtimes 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
@@ -40,6 +42,12 @@ type piFamily struct {
var (
piRuntime = piFamily{platform: "pi", displayName: "Pi"}
ompRuntime = piFamily{platform: "omp", displayName: "Oh My Pi"}
+ // Prime Agent's `--platform` is `prime` rather than `prime-agent` because the platform value is
+ // also the prefix on this runtime's keys inside `raw`, and `prime_agent_session_reason` reads
+ // as a field of a harness named `prime_agent` -- which is exactly what it is. The harness name
+ // events are written under is still `prime_agent`; NormalizeHarnessName pins both spellings so
+ // one session cannot be recorded under two names.
+ primeRuntime = piFamily{platform: "prime", displayName: "Prime Agent"}
)
// rawKey namespaces a runtime-specific detail inside the `raw` block.
@@ -98,6 +106,7 @@ func (f piFamily) endpointEvents(input map[string]interface{}, sessionID string)
// 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))
+ f.applyPythonMarker(fields, piToolName(input))
applyToolCallID(fields, input)
return f.one("tool.invoked", "tool", "info", "tool invoked", fields)
@@ -286,6 +295,21 @@ func (f piFamily) toolFields(input map[string]interface{}, withResult bool) map[
fields["command"] = map[string]interface{}{"command": command}
fields["content"] = retainedContentFields(command)
}
+ // Prime Agent's only default tool. It executes Python in a persistent kernel, and that kernel
+ // is where essentially all of its agent activity happens: it reads and writes files, and it
+ // runs shell commands through a `bash()` helper rather than through a separate shell tool. So
+ // the code is recorded in the command category rather than as an anonymous tool call, for the
+ // reason Oh My Pi's operator `$` code is -- `os.system("rm -rf /")` is a shell command wearing
+ // a Python hat, and the risky-command rules all match on `command.command`. It is marked as
+ // Python in `raw` rather than passed off as a shell command.
+ //
+ // Pi and Oh My Pi never reach this case: neither ships a tool by this name.
+ case "ipython":
+ if code := getFirstStr(args, "code"); code != "" {
+ tool["command"] = code
+ fields["command"] = map[string]interface{}{"command": code}
+ fields["content"] = retainedContentFields(code)
+ }
case "read", "edit", "write":
if path := getFirstStr(args, "path"); path != "" {
tool["path"] = path
@@ -378,10 +402,18 @@ func (f piFamily) toolResultEvents(input map[string]interface{}, fields map[stri
mergeMap(fields, f.toolFields(input, true))
applyToolCallID(fields, input)
name := piToolName(input)
+ f.applyPythonMarker(fields, name)
+
+ // Both of these read Prime Agent's `ipython` result and are no-ops for every other tool, so Pi
+ // and Oh My Pi never reach them. They run before the failure branch below because a cell that
+ // raised still executed the statements before the one that raised: its output and the files it
+ // wrote are exactly what an investigation into a failed cell reads.
+ f.applyPythonResult(fields, name, input)
+ kernelWrites := f.pythonDiffEvents(name, input, fields)
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)
+ return append(f.one("tool.failed", "tool", "high", "tool failed", fields), kernelWrites...)
}
if diff := piEditDiff(input); diff != "" {
@@ -403,7 +435,162 @@ func (f piFamily) toolResultEvents(input map[string]interface{}, fields map[stri
action, category = "tool.completed", "tool"
}
}
- return f.one(action, category, "info", piToolMessageSuffix(action), fields)
+ return append(f.one(action, category, "info", piToolMessageSuffix(action), fields), kernelWrites...)
+}
+
+// applyPythonMarker notes that a command block holds Python rather than a shell command line.
+//
+// Applied to the caller's fields rather than inside toolFields, which returns a fresh map that
+// mergeMap copies over the caller's -- writing `raw` there would replace the verbatim payload block
+// with this one key. Prime Agent's `ipython` cell is executed as literally as a shell command
+// (`os.system("rm -rf /")` is a shell command wearing a Python hat), which is why it is recorded in
+// the command category at all; the marker is what keeps a reader from taking command.command for a
+// shell line.
+func (f piFamily) applyPythonMarker(fields map[string]interface{}, toolName string) {
+ if strings.ToLower(toolName) != "ipython" {
+ return
+ }
+ if _, ok := fields["command"]; !ok {
+ return
+ }
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{f.rawKey("python"): true})
+}
+
+// applyPythonResult records what a Prime Agent `ipython` cell did, from the details it reports.
+//
+// Without this an ipython result is a command with no outcome at all: no output, no duration, and
+// no sign of whether the cell raised. That is the whole of Prime Agent's tool surface, so the gap
+// would not be one tool missing its result -- it would be every agent action missing it.
+//
+// Nothing here is derived. `status` is the runtime's own word, the duration is its own measurement,
+// and the output is the streams it captured. There is no exit code to record, because a Python
+// cell does not have one; inventing a 0/1 from `status` would put a shell's vocabulary on something
+// that is not a shell.
+func (f piFamily) applyPythonResult(fields map[string]interface{}, toolName string, input map[string]interface{}) {
+ if strings.ToLower(toolName) != "ipython" {
+ return
+ }
+ details := firstMap(input, "details")
+ if details == nil {
+ return
+ }
+
+ // stdout first, then stderr, then the cell's value. The order is the order a reader of the
+ // terminal saw them in, and each is included only when the runtime captured something, so a
+ // cell that printed nothing yields no output field rather than a string of blank lines.
+ var streams []string
+ for _, key := range []string{"stdout", "stderr", "result"} {
+ if text := getFirstStr(details, key); text != "" {
+ streams = append(streams, text)
+ }
+ }
+ if len(streams) > 0 {
+ output := strings.Join(streams, "\n")
+ command := mutableChild(fields["command"])
+ command["output"] = output
+ fields["command"] = command
+ // The retention marker on the code is the more specific claim -- it is what the rules match
+ // on -- so output only fills the field when nothing has claimed it, the same precedence
+ // applyKiroToolResult uses.
+ if _, exists := fields["content"]; !exists {
+ fields["content"] = retainedContentFields(output)
+ }
+ }
+
+ if duration, ok := firstToolIntAcross([]map[string]interface{}{details}, "durationMs", "duration_ms"); ok {
+ command := mutableChild(fields["command"])
+ command["duration_ms"] = duration
+ fields["command"] = command
+ }
+
+ raw := map[string]interface{}{}
+ // ok, error or aborted. "aborted" is the one worth keeping separately from isError: a cell the
+ // operator interrupted is not a cell that failed, and a log that cannot tell them apart reports
+ // every Ctrl+C as an agent error.
+ if status := getFirstStr(details, "status"); status != "" {
+ raw["python_status"] = status
+ }
+ // The exception class, when the cell raised one. The message and traceback are deliberately not
+ // promoted: they are already in the verbatim payload under `raw`, and a traceback quotes source
+ // lines, which is content rather than a fact about the event.
+ if errName := getFirstStr(details, "errorEname"); errName != "" {
+ raw["python_error"] = errName
+ } else if errDetail := firstMap(details, "error"); errDetail != nil {
+ if errName := getFirstStr(errDetail, "ename"); errName != "" {
+ raw["python_error"] = errName
+ }
+ }
+ // A restarted kernel has lost every variable, import and open handle the session had built up,
+ // so a reader comparing two cells across that boundary is comparing two different processes.
+ if restarted, ok := details["kernelRestarted"].(bool); ok && restarted {
+ raw["kernel_restarted"] = true
+ }
+ if len(raw) == 0 {
+ return
+ }
+ prefixed := map[string]interface{}{}
+ for key, value := range raw {
+ prefixed[f.rawKey(key)] = value
+ }
+ fields["raw"] = mergeNested(fields["raw"], prefixed)
+}
+
+// pythonDiffEvents turns the file edits a Prime Agent kernel cell reported into file events.
+//
+// Prime Agent's kernel streams a diff display for every file its helpers rewrite, so a cell that
+// edits three files reports three of them. Each becomes its own file.modified, the same one-event-
+// per-changed-file shape the OpenHands mapper produces for one apply_patch call: a store that files
+// one row per path is the one a "who touched this file" query can answer.
+//
+// The pair is a replaced span rather than the file before and after -- the kernel names the text it
+// matched and the text it substituted -- so the patch is built with FromEditFragments rather than
+// FromContentChange. Choosing the wrong one there produces a diff that is wrong rather than absent.
+func (f piFamily) pythonDiffEvents(toolName string, input, fields map[string]interface{}) []normalizedEvent {
+ if strings.ToLower(toolName) != "ipython" {
+ return nil
+ }
+ details := firstMap(input, "details")
+ if details == nil {
+ return nil
+ }
+ diffs, ok := details["diffs"].([]interface{})
+ if !ok {
+ return nil
+ }
+
+ var events []normalizedEvent
+ for _, item := range diffs {
+ entry, ok := item.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ path := getFirstStr(entry, "path")
+ if path == "" {
+ continue
+ }
+ // FromEditFragments returns nothing when the replaced span is identical to its
+ // replacement, which is an edit that changed nothing on disk. diffFields would still build
+ // a file block from the path alone, so the emptiness is checked here rather than there --
+ // otherwise a no-op edit is recorded as a modification that never happened.
+ patch := diff.FromEditFragments(path, getFirstStr(entry, "oldStr"), getFirstStr(entry, "newStr"))
+ if patch == "" {
+ continue
+ }
+ fileFields := diffFields(path, patch)
+ if fileFields == nil {
+ continue
+ }
+
+ values := cloneFields(fields)
+ // The cell's code stays out of the file event. It is already on the command.executed this
+ // event accompanies, joined to it by the same tool call id, and carrying it here would put
+ // a whole Python cell in `command.command` on a row whose subject is one file -- where a
+ // command-scoped rule would then match the cell once per file it happened to touch.
+ delete(values, "command")
+ mergeMap(values, fileFields)
+ events = append(events, f.one("file.modified", "file", "info", "file modified", values)...)
+ }
+ return events
}
// piEditDiff returns the unified patch the edit tool reports, when it reported one.
@@ -422,7 +609,7 @@ func piEditDiff(input map[string]interface{}) string {
// 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":
+ case "bash", "ipython":
return "command.executed", "command"
case "read":
return "file.read", "file"
diff --git a/cli/beacon-hooks/cmd/prime_event.go b/cli/beacon-hooks/cmd/prime_event.go
new file mode 100644
index 00000000..9c03a18f
--- /dev/null
+++ b/cli/beacon-hooks/cmd/prime_event.go
@@ -0,0 +1,62 @@
+package cmd
+
+import (
+ "github.com/spf13/cobra"
+)
+
+// prime-event is the single entry point for every Prime Agent lifecycle payload.
+//
+// Prime Agent (Prime Intellect) 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, Oh My 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, for the reason omp-event is: the two
+// are separately installed products, 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 Prime Agent is a hard fork of pi-mono that kept its payload
+// shapes.
+var primeEventCmd = &cobra.Command{
+ Use: "prime-event",
+ Short: "Record Prime Agent hook telemetry",
+ Long: `prime-event receives raw Beacon Prime Agent extension payloads and writes local endpoint telemetry.`,
+ Run: runPrimeEvent,
+}
+
+func init() {
+ rootCmd.AddCommand(primeEventCmd)
+}
+
+func runPrimeEvent(cmd *cobra.Command, args []string) {
+ runPiFamilyEvent(primeRuntime)
+}
+
+// supportedPrimeEventTypes lists every Prime Agent 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.
+//
+// The list is Pi's exactly, and that is a finding rather than a copy. Prime Agent publishes more
+// than forty event types -- provider request and response internals, streaming message updates,
+// compaction, refinement and tree navigation signals, TUI plumbing -- and of the ones that describe
+// an agent action rather than how the runtime got its work done, these seven are what it exposes.
+//
+// Two absences are Prime Agent's own rather than a choice made here. It has no `user_python`: its
+// operator surface is `!` for bash, and Python is the agent's tool rather than a second operator
+// prefix, so there is nothing to subscribe to. And it has no approval event at all -- its
+// `tool_call` handler can block, but that is an extension deciding rather than an operator being
+// asked -- so Beacon records tool activity and leaves approval telemetry empty, exactly as it does
+// for Pi and Cline. Oh My Pi's three extra subscriptions are the ones Oh My Pi added; Prime Agent
+// forked pi-mono separately and did not.
+func supportedPrimeEventTypes() []string {
+ return []string{
+ "session_start",
+ "session_shutdown",
+ "input",
+ "tool_call",
+ "tool_result",
+ "user_bash",
+ "message_end",
+ }
+}
diff --git a/cli/beacon-hooks/cmd/prime_event_test.go b/cli/beacon-hooks/cmd/prime_event_test.go
new file mode 100644
index 00000000..770142c9
--- /dev/null
+++ b/cli/beacon-hooks/cmd/prime_event_test.go
@@ -0,0 +1,414 @@
+package cmd
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// primeTestLog puts a Prime Agent extension run in a temp endpoint log and returns its path.
+func primeTestLog(t *testing.T) string {
+ t.Helper()
+ setupHookConfigDirs(t)
+ platformFlag = "prime"
+ 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 primeEventActions(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 primeEventWithAction(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, primeEventActions(t, logPath))
+ return nil
+}
+
+// primePayloads returns one payload per supported event type, each carrying the minimum its branch
+// needs to emit. The tool fixtures use `ipython` because that is Prime Agent's only default tool;
+// `bash` and `edit` exist but are opt-in, and a fixture set built from them would pass while the
+// tool the runtime actually calls went unmapped.
+func primePayloads() 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": "ipython", "toolCallId": "c1",
+ "input": map[string]interface{}{"code": "print(1)"}},
+ "tool_result": {"type": "tool_result", "toolName": "ipython", "toolCallId": "c1",
+ "input": map[string]interface{}{"code": "print(1)"},
+ "details": map[string]interface{}{"status": "ok", "stdout": "1\n"}},
+ "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 TestPrimeEventEverySupportedTypeProducesTelemetry(t *testing.T) {
+ payloads := primePayloads()
+ for _, name := range supportedPrimeEventTypes() {
+ payload, ok := payloads[name]
+ if !ok {
+ t.Fatalf("no fixture for supported Prime Agent event type %q; the mapper claims to handle it", name)
+ }
+ if events := primeRuntime.endpointEvents(cloneFields(payload), "sess-1"); len(events) == 0 {
+ t.Fatalf("supported Prime Agent event type %q produced no telemetry", name)
+ }
+ }
+}
+
+// An unrecognized type is silent rather than generic. Prime Agent publishes upwards of forty event
+// types -- provider request and response internals, streaming message updates, compaction,
+// refinement and tree navigation signals, TUI plumbing -- and a future one becoming an
+// undifferentiated row would fill the log with records no investigation asks for.
+func TestPrimeEventUnknownTypeProducesNothing(t *testing.T) {
+ for _, name := range []string{
+ "message_update", "before_provider_request", "after_provider_response", "turn_start",
+ "session_before_refine", "refine_complete", "resources_discover", "thinking_level_select",
+ "", "totally_new",
+ } {
+ events := primeRuntime.endpointEvents(map[string]interface{}{"type": name}, "sess-1")
+ if len(events) != 0 {
+ t.Fatalf("Prime Agent event type %q produced %d events, want none", name, len(events))
+ }
+ }
+}
+
+// Prime Agent, Pi and Oh My Pi are separately installed products that one machine 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.
+func TestPrimeEventIsAttributedToPrimeAgentNotPi(t *testing.T) {
+ logPath := primeTestLog(t)
+
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "session_start", "reason": "startup", "sessionId": "sess-1",
+ })
+
+ event := primeEventWithAction(t, logPath, "session.started")
+
+ // The `--platform` is `prime`; the harness name events are written under is `prime_agent`.
+ // Normalizing at write time is what keeps one Prime Agent session from being split across two
+ // spellings in any query that groups by harness.name -- and from being merged into Pi's.
+ harness := nested(t, event, "harness")
+ if harness["name"] != "prime_agent" {
+ t.Fatalf("harness.name = %v, want prime_agent", harness["name"])
+ }
+
+ if event["message"] != "Prime Agent session started" {
+ t.Fatalf("message = %v, want it to name Prime Agent", event["message"])
+ }
+
+ raw := nested(t, event, "raw")
+ if _, ok := raw["prime"]; !ok {
+ t.Fatalf("raw = %v, want the verbatim payload under a prime key", raw)
+ }
+ for _, other := range []string{"pi", "omp"} {
+ if _, ok := raw[other]; ok {
+ t.Fatalf("raw = %v, want no %s key on a Prime Agent event", raw, other)
+ }
+ }
+ if raw["prime_session_reason"] != "startup" {
+ t.Fatalf("raw.prime_session_reason = %v, want startup", raw["prime_session_reason"])
+ }
+}
+
+// One shared shape, three identities. The shared core in pi_family.go must never start hardcoding
+// one runtime's name -- which is the way a refactor like that goes wrong silently.
+func TestPiAndPrimeProduceTheSameShapeUnderDifferentIdentities(t *testing.T) {
+ shared := map[string]bool{}
+ for _, name := range supportedPiEventTypes() {
+ shared[name] = true
+ }
+ for name, payload := range primePayloads() {
+ if !shared[name] {
+ continue
+ }
+ t.Run(name, func(t *testing.T) {
+ piEvents := piRuntime.endpointEvents(cloneFields(payload), "sess-1")
+ primeEvents := primeRuntime.endpointEvents(cloneFields(payload), "sess-1")
+
+ if len(piEvents) != len(primeEvents) {
+ t.Fatalf("pi produced %d events and prime %d for %q; the shared mapper should emit "+
+ "the same events for the same payload", len(piEvents), len(primeEvents), name)
+ }
+ for i := range piEvents {
+ if piEvents[i].action != primeEvents[i].action {
+ t.Fatalf("action[%d] = %q (pi) vs %q (prime)", i, piEvents[i].action, primeEvents[i].action)
+ }
+ if piEvents[i].message == primeEvents[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 := primeEvents[i].fields["raw"].(map[string]interface{})["prime"]; !ok {
+ t.Fatalf("prime event[%d] raw block is not keyed by prime: %v", i, primeEvents[i].fields["raw"])
+ }
+ }
+ })
+ }
+}
+
+// Beacon ships and versions the extension file Prime Agent 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 TestPrimeEventCarriesPluginProvenance(t *testing.T) {
+ logPath := primeTestLog(t)
+
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "input", "text": "hello", "sessionId": "sess-1",
+ })
+
+ event := primeEventWithAction(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)
+ }
+}
+
+// The ipython cell is the whole of Prime Agent's default tool surface: the agent reads files,
+// writes files and runs shell commands through it rather than through separate tools. Recording it
+// as an anonymous `tool.completed` would leave every one of those actions invisible to the
+// command-scoped rules, which all match on `command.command`.
+func TestPrimeEventIpythonIsRecordedAsACommand(t *testing.T) {
+ logPath := primeTestLog(t)
+
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "tool_result", "toolName": "ipython", "toolCallId": "call-1",
+ "input": map[string]interface{}{"code": "import os; os.system('rm -rf /tmp/x')"},
+ "details": map[string]interface{}{
+ "status": "ok", "durationMs": float64(42), "stdout": "done\n",
+ },
+ "sessionId": "sess-1",
+ })
+
+ event := primeEventWithAction(t, logPath, "command.executed")
+ command := nested(t, event, "command")
+ if command["command"] != "import os; os.system('rm -rf /tmp/x')" {
+ t.Fatalf("command.command = %v, want the cell's code", command["command"])
+ }
+ if command["output"] != "done\n" {
+ t.Fatalf("command.output = %v, want the captured stdout", command["output"])
+ }
+ if command["duration_ms"] != float64(42) {
+ t.Fatalf("command.duration_ms = %v, want 42", command["duration_ms"])
+ }
+ if tool := nested(t, event, "tool"); tool["name"] != "ipython" {
+ t.Fatalf("tool.name = %v, want ipython", tool["name"])
+ }
+ raw := nested(t, event, "raw")
+ // Marked as Python rather than passed off as a shell command, so a reader can tell which
+ // interpreter ran the string in command.command.
+ if raw["prime_python"] != true {
+ t.Fatalf("raw.prime_python = %v, want true", raw["prime_python"])
+ }
+ if raw["prime_python_status"] != "ok" {
+ t.Fatalf("raw.prime_python_status = %v, want ok", raw["prime_python_status"])
+ }
+ // A Python cell has no exit code. Deriving a 0/1 from `status` would put a shell's vocabulary
+ // on something that is not a shell.
+ if _, ok := command["exit_code"]; ok {
+ t.Fatalf("command = %v, want no invented exit code", command)
+ }
+}
+
+// An interrupted cell is not a failed cell, and the log has to be able to tell them apart --
+// otherwise every Ctrl+C reads as an agent error.
+func TestPrimeEventIpythonRecordsStatusAndErrorClass(t *testing.T) {
+ logPath := primeTestLog(t)
+
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "tool_result", "toolName": "ipython", "toolCallId": "call-1",
+ "input": map[string]interface{}{"code": "1/0"},
+ "isError": true,
+ "details": map[string]interface{}{
+ "status": "error",
+ "error": map[string]interface{}{
+ "ename": "ZeroDivisionError", "evalue": "division by zero",
+ },
+ },
+ "sessionId": "sess-1",
+ })
+
+ event := primeEventWithAction(t, logPath, "tool.failed")
+ raw := nested(t, event, "raw")
+ if raw["prime_python_status"] != "error" {
+ t.Fatalf("raw.prime_python_status = %v, want error", raw["prime_python_status"])
+ }
+ if raw["prime_python_error"] != "ZeroDivisionError" {
+ t.Fatalf("raw.prime_python_error = %v, want ZeroDivisionError", raw["prime_python_error"])
+ }
+ // The code still has to reach the failed event: a cell that raised is exactly the cell an
+ // investigation wants to read.
+ if command := nested(t, event, "command"); command["command"] != "1/0" {
+ t.Fatalf("command.command = %v, want the cell's code on the failure event", command["command"])
+ }
+}
+
+// Prime Agent's kernel streams a diff for every file its helpers rewrite, so one cell that edits
+// three files reports three of them. Each becomes its own file.modified, because a store that files
+// one row per path is the one a "who touched this file" query can answer.
+func TestPrimeEventIpythonKernelDiffsBecomeFileEvents(t *testing.T) {
+ logPath := primeTestLog(t)
+
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "tool_result", "toolName": "ipython", "toolCallId": "call-1",
+ "input": map[string]interface{}{"code": "edit('a.py'); edit('b.py')"},
+ "details": map[string]interface{}{
+ "status": "ok",
+ "diffs": []interface{}{
+ map[string]interface{}{"path": "/repo/a.py", "oldStr": "x = 1", "newStr": "x = 2"},
+ map[string]interface{}{"path": "/repo/b.py", "oldStr": "y = 1", "newStr": "y = 2"},
+ // No path is not a file edit. Recording it would produce a row every file-scoped
+ // query matches and none can explain.
+ map[string]interface{}{"oldStr": "z = 1", "newStr": "z = 2"},
+ // An edit that substituted identical text changed nothing on disk.
+ map[string]interface{}{"path": "/repo/c.py", "oldStr": "same", "newStr": "same"},
+ },
+ },
+ "sessionId": "sess-1",
+ })
+
+ var paths []string
+ for _, event := range endpointEvents(t, logPath) {
+ meta, _ := event["event"].(map[string]interface{})
+ if meta["action"] != "file.modified" {
+ continue
+ }
+ file := nested(t, event, "file")
+ paths = append(paths, file["path"].(string))
+ if file["diff"] == nil || !strings.Contains(file["diff"].(string), "+") {
+ t.Fatalf("file.diff = %v, want a patch for %v", file["diff"], file["path"])
+ }
+ if file["diff_hash"] == nil || file["diff_bytes"] == nil {
+ t.Fatalf("file = %v, want the diff described by a hash and a byte count", file)
+ }
+ // The cell's code belongs on the command.executed this event accompanies, not here: a whole
+ // Python cell in command.command on a per-file row would make a command-scoped rule match
+ // the cell once per file it happened to touch.
+ if _, ok := event["command"]; ok {
+ t.Fatalf("file.modified carries a command block: %v", event)
+ }
+ // The tool call id is the only thing joining this write back to the cell that made it.
+ if genAI := nested(t, event, "gen_ai"); genAI["tool"] == nil {
+ t.Fatalf("gen_ai = %v, want the tool call id on the file event", genAI)
+ }
+ }
+
+ if len(paths) != 2 || paths[0] != "/repo/a.py" || paths[1] != "/repo/b.py" {
+ t.Fatalf("file.modified paths = %v, want one per changed file", paths)
+ }
+}
+
+// Prime Agent exposes no approval event at all. Its tool_call handler can block, but that is an
+// extension deciding rather than an operator being asked, and recording a block as an approval
+// would be indistinguishable from a decision a human actually made. This is the Pi and Cline
+// posture, and it is what separates Prime Agent from Oh My Pi, which does report real ones.
+func TestPrimeEventNeverSynthesizesAnApproval(t *testing.T) {
+ for _, name := range supportedPrimeEventTypes() {
+ if strings.Contains(name, "approval") {
+ t.Fatalf("supportedPrimeEventTypes includes %q; Prime Agent publishes no approval event", name)
+ }
+ }
+
+ logPath := primeTestLog(t)
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "tool_call", "toolName": "ipython", "toolCallId": "call-1",
+ "input": map[string]interface{}{"code": "import shutil; shutil.rmtree('/')"}, "sessionId": "sess-1",
+ })
+
+ event := primeEventWithAction(t, logPath, "tool.invoked")
+ if _, ok := event["approval"]; ok {
+ t.Fatalf("tool.invoked carries an approval block: %v", event)
+ }
+}
+
+// The `!` prefix is Prime Agent's operator shell surface, and no tool event covers it. It is the
+// one command shape here the agent did not originate, so it is marked rather than merged in with
+// agent-run commands.
+func TestPrimeEventUserBashIsMarkedOperatorInitiated(t *testing.T) {
+ logPath := primeTestLog(t)
+
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "user_bash", "command": "git push --force", "cwd": "/repo", "sessionId": "sess-1",
+ })
+
+ event := primeEventWithAction(t, logPath, "command.executed")
+ if command := nested(t, event, "command"); command["command"] != "git push --force" {
+ t.Fatalf("command.command = %v, want the operator's command", command["command"])
+ }
+ if raw := nested(t, event, "raw"); raw["prime_user_initiated"] != true {
+ t.Fatalf("raw.prime_user_initiated = %v, want true", raw["prime_user_initiated"])
+ }
+}
+
+// Usage and cost come off a finalized assistant message, the only place this family reports them,
+// and land in gen_ai.usage rather than in a parallel per-harness field.
+func TestPrimeEventMessageEndReportsUsageAndReasoning(t *testing.T) {
+ logPath := primeTestLog(t)
+
+ runHookWithInput(t, runPrimeEvent, map[string]interface{}{
+ "type": "message_end",
+ "sessionId": "sess-1",
+ "message": map[string]interface{}{
+ "role": "assistant",
+ "model": "prime-rl-1",
+ "content": []interface{}{
+ map[string]interface{}{"type": "thinking", "thinking": "consider the failing test"},
+ map[string]interface{}{"type": "text", "text": "Fixed it."},
+ },
+ "usage": map[string]interface{}{
+ "input": float64(120), "output": float64(30), "cacheRead": float64(8),
+ "cost": map[string]interface{}{"total": 0.0042},
+ },
+ },
+ })
+
+ usage := nested(t, nested(t, primeEventWithAction(t, logPath, "token.usage"), "gen_ai"), "usage")
+ if usage["input_tokens"] != float64(120) || usage["output_tokens"] != float64(30) {
+ t.Fatalf("gen_ai.usage = %v, want the reported input and output tokens", usage)
+ }
+ if cacheRead, ok := usage["cache_read"].(map[string]interface{}); !ok || cacheRead["input_tokens"] != float64(8) {
+ t.Fatalf("gen_ai.usage.cache_read = %v, want 8 input tokens", usage["cache_read"])
+ }
+ // Runtime-reported cost only; Beacon never derives it from a local pricing table.
+ if usage["cost_usd"] != 0.0042 {
+ t.Fatalf("gen_ai.usage.cost_usd = %v, want the runtime's reported cost", usage["cost_usd"])
+ }
+
+ reasoning := primeEventWithAction(t, logPath, "agent.reasoning")
+ output := nested(t, nested(t, reasoning, "gen_ai"), "output")
+ messages, _ := output["messages"].([]interface{})
+ if len(messages) != 1 {
+ t.Fatalf("gen_ai.output.messages = %v, want one reasoning message", output["messages"])
+ }
+ // The assistant's visible answer is not reasoning. Recording it as such would put the model's
+ // output where a reader looking for its private deliberation expects to find it.
+ first, _ := messages[0].(map[string]interface{})
+ parts, _ := first["parts"].([]interface{})
+ part, _ := parts[0].(map[string]interface{})
+ if part["content"] != "consider the failing test" {
+ t.Fatalf("reasoning part = %v, want only the thinking text", part)
+ }
+}