Skip to content

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

feat(pi): ship the managed Pi extension so a listed runtime collects telemetry

Claudec2f59c4068d0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 040fddce..c4104906 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -58,6 +58,9 @@ jobs:
- name: Check Cline plugin
working-directory: plugins/cline-beacon
run: bun run check && bun test
+ - name: Check Pi extension
+ working-directory: plugins/pi-beacon
+ run: bun run check && bun test
- name: Build embedded hooks binary
working-directory: cli/beacon
# hooks.bin is gitignored (build-time artifact). The CLI embeds it via
diff --git a/CLAUDE.md b/CLAUDE.md
index 1b95d32c..165771cb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -32,6 +32,7 @@ Supported runtime surfaces today:
- Claude Code and Codex CLI telemetry configuration through local OpenTelemetry settings.
- Cursor hook telemetry for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, file edits, and agent reasoning (`afterAgentThought` thinking text recorded as `agent.reasoning` events in the OTel GenAI `gen_ai.output.messages` reasoning-part shape) where hook payloads expose those fields.
- Cline hook telemetry through a Beacon-managed local plugin (`~/.cline/plugins/beacon.ts`) covering prompts, task lifecycle, tool lifecycle, commands, file reads/edits with diffs, MCP activity, and task token usage. One plugin serves Cline's VS Code, JetBrains, and CLI hosts; Cline's own OTel export and hosted prompt storage are not used. Approval decisions are not exposed by Cline's hook payloads and are not synthesized.
+- Pi hook telemetry through a Beacon-managed local extension (`~/.pi/agent/extensions/beacon.ts`, or `.pi/extensions/beacon.ts` at project level) covering session lifecycle, prompts, tool lifecycle and results, commands including operator `!` commands, file reads/creates/edits with the unified patch, agent reasoning from assistant thinking parts, and token usage/cost. The extension subscribes to seven Pi event types and ignores the streaming and provider internals. Approval decisions are not exposed by Pi's extension API -- its `tool_call` handler can block, but that is an extension deciding rather than an operator being asked -- and are not synthesized, matching the Cline decision.
- Claude Cowork admin-configured OpenTelemetry setup guidance and local validation.
- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.
- Asymptote Observe TypeScript SDK instrumentation for cloud applications, starting from OpenTelemetry/OpenLLMetry patterns and `observe()` wrappers.
@@ -97,6 +98,17 @@ cd pkg/asymptoteobserve
go test ./...
```
+Run the managed runtime plugin/extension checks (each verifies the checked-in copy matches its embedded twin, then runs its tests):
+
+```bash
+cd plugins/opencode-beacon && bun run check && bun test
+cd ../cline-beacon && bun run check && bun test
+cd ../pi-beacon && bun run check && bun test
+```
+
+After editing a plugin or extension source, run `bun run sync` in its directory to update the
+embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`; a Go test fails if the two drift.
+
Run TypeScript SDK checks:
```bash
@@ -367,6 +379,7 @@ CI runs:
- `go test ./...` in `cli/beacon-hooks`.
- `go test ./...` in `collector-builder/exporter/beaconjsonexporter`.
- `go test ./...` in `pkg/asymptoteobserve` (includes threat-rules pack conformance).
+- `bun run check && bun test` in `plugins/opencode-beacon`, `plugins/cline-beacon`, and `plugins/pi-beacon`.
- CLI help smoke checks for the public command tree.
- macOS packaging script validation via `packaging/macos/test-endpoint-scripts.sh`.
- macOS endpoint smoke validation via `packaging/macos/smoke-endpoint.sh`.
diff --git a/README.md b/README.md
index 5afc368b..cad6eb60 100644
--- a/README.md
+++ b/README.md
@@ -90,7 +90,7 @@ CI, and cloud surfaces.
| [GitHub Copilot CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-github-copilot-cli) | MDM-managed OTLP HTTP | Prompt, session, tool, and approval-like activity emitted through Copilot CLI spans |
| [Grok Build](https://docs.asymptotelabs.ai/cli/supported-runtimes-grok-build) | Native hooks | Session, prompt, pre-tool, post-tool, failed tool, stop, session-end, command, and file telemetry |
| [OpenCode](https://docs.asymptotelabs.ai/cli/supported-runtimes-opencode) | Managed plugin hooks | Prompts, assistant output/reasoning, model usage/cost, tool lifecycle/results, commands, file/web/MCP activity, approvals, and session errors |
-| [Pi](https://docs.asymptotelabs.ai/runtimes/pi) | Managed extension hooks | Discovery and harness attribution today; the managed extension that collects session, prompt, tool, command, and approval telemetry is not shipped yet |
+| [Pi](https://docs.asymptotelabs.ai/runtimes/pi) | Managed extension hooks | Session lifecycle, prompts, tool lifecycle/results, commands including operator `!` commands, file reads/writes/edits with diffs, agent reasoning, and token usage/cost |
| [VS Code](https://docs.asymptotelabs.ai/cli/supported-runtimes-vscode) | Copilot Chat OTel plus optional preview hooks | Copilot session, prompt, model, and tool activity through OTel; optional hooks for extra lifecycle and cross-agent detail |
##### Knowledge Worker Agent Harnesses
diff --git a/cli/beacon-hooks/cmd/helpers.go b/cli/beacon-hooks/cmd/helpers.go
index c89dc5b6..932b55c8 100644
--- a/cli/beacon-hooks/cmd/helpers.go
+++ b/cli/beacon-hooks/cmd/helpers.go
@@ -125,6 +125,11 @@ 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 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":
+ return getFirstStr(input, "sessionId", "session_id", "sessionID")
default:
id, _ := input["session_id"].(string)
return id
@@ -248,6 +253,14 @@ 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 cwd := getFirstStr(input, "cwd", "workingDirectory", "working_directory"); cwd != "" {
+ return cwd
+ }
+ }
if platform == "cline" {
if cwd := getFirstStr(input, "cwd", "workingDirectory", "working_directory"); cwd != "" {
return cwd
diff --git a/cli/beacon-hooks/cmd/pi_event.go b/cli/beacon-hooks/cmd/pi_event.go
new file mode 100644
index 00000000..faea749a
--- /dev/null
+++ b/cli/beacon-hooks/cmd/pi_event.go
@@ -0,0 +1,446 @@
+package cmd
+
+import (
+ "path/filepath"
+ "strings"
+
+ "github.com/spf13/cobra"
+)
+
+// pi-event is the single entry point for every Pi lifecycle payload.
+//
+// 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.
+var piEventCmd = &cobra.Command{
+ Use: "pi-event",
+ Short: "Record Pi hook telemetry",
+ Long: `pi-event receives raw Beacon Pi extension payloads and writes local endpoint telemetry.`,
+ Run: runPiEvent,
+}
+
+func init() {
+ rootCmd.AddCommand(piEventCmd)
+}
+
+func runPiEvent(cmd *cobra.Command, args []string) {
+ 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) {
+ if event.action == "" {
+ continue
+ }
+ _ = logger.EndpointEvent(event.action, event.category, event.severity, event.message, event.fields)
+ }
+ outputJSON(emptyResponse)
+}
+
+// supportedPiEventTypes lists every Pi event type this mapper handles.
+//
+// These strings are the contract between the managed extension's subscription list and this 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 {
+ return []string{
+ "session_start",
+ "session_shutdown",
+ "input",
+ "tool_call",
+ "tool_result",
+ "user_bash",
+ "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"] = map[string]interface{}{
+ "input": map[string]interface{}{
+ "messages": []interface{}{map[string]interface{}{
+ "role": "user",
+ "parts": []interface{}{map[string]interface{}{"type": "text", "content": 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
new file mode 100644
index 00000000..2289fd03
--- /dev/null
+++ b/cli/beacon-hooks/cmd/pi_event_test.go
@@ -0,0 +1,430 @@
+package cmd
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+// piTestLog puts a Pi extension run in a temp endpoint log and returns its path.
+func piTestLog(t *testing.T) string {
+ t.Helper()
+ setupHookConfigDirs(t)
+ platformFlag = "pi"
+ 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 piEventActions(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 piEventWithAction(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, piEventActions(t, logPath))
+ return nil
+}
+
+// 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 TestPiEventEverySupportedTypeProducesTelemetry(t *testing.T) {
+ // One payload per type, each carrying the minimum its branch needs to emit.
+ payloads := 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)},
+ }},
+ }
+
+ for _, name := range supportedPiEventTypes() {
+ payload, ok := payloads[name]
+ if !ok {
+ t.Fatalf("no fixture for supported Pi event type %q; the mapper claims to handle it", name)
+ }
+ events := piEndpointEvents(payload, "sess-1")
+ if len(events) == 0 {
+ t.Fatalf("supported Pi event type %q produced no telemetry", name)
+ }
+ }
+}
+
+// An unrecognized type is silent rather than generic. Pi publishes far more events than the
+// extension subscribes to, and a future one becoming an undifferentiated row would fill the log
+// 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")
+ if len(events) != 0 {
+ t.Fatalf("Pi event type %q produced %d events, want none", name, len(events))
+ }
+ }
+}
+
+func TestPiEventSessionStartAndShutdown(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "session_start", "reason": "resume", "sessionId": "sess-1", "cwd": "/repo",
+ })
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "session_shutdown", "reason": "quit", "sessionId": "sess-1",
+ })
+
+ if got := piEventActions(t, logPath); len(got) != 2 || got[0] != "session.started" || got[1] != "session.ended" {
+ t.Fatalf("actions = %v, want [session.started session.ended]", got)
+ }
+ started := piEventWithAction(t, logPath, "session.started")
+ session, _ := started["session"].(map[string]interface{})
+ if session["id"] != "sess-1" {
+ t.Fatalf("session.id = %v, want sess-1", session["id"])
+ }
+ // The reason distinguishes a fresh session from one that already has history behind it, which a
+ // reader counting sessions needs.
+ raw := nested(t, started, "raw")
+ if raw["pi_session_reason"] != "resume" {
+ t.Fatalf("raw.pi_session_reason = %v, want resume", raw["pi_session_reason"])
+ }
+}
+
+func TestPiEventInputRecordsPrompt(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "input", "text": "refactor the parser", "source": "interactive",
+ "sessionId": "sess-1", "cwd": "/repo",
+ })
+
+ event := piEventWithAction(t, logPath, "prompt.submitted")
+ prompt := nested(t, event, "prompt")
+ if prompt["text"] != "refactor the parser" {
+ t.Fatalf("prompt.text = %v, want the submitted text", prompt["text"])
+ }
+ content := nested(t, event, "content")
+ if 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["pi_input_source"] != "interactive" {
+ t.Fatalf("raw.pi_input_source = %v, want interactive", raw["pi_input_source"])
+ }
+}
+
+// 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")
+ if len(events) != 0 {
+ t.Fatalf("empty input produced %d events, want none", len(events))
+ }
+}
+
+func TestPiEventToolCallRecordsInvocation(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "tool_call", "toolName": "bash", "toolCallId": "call-1",
+ "input": map[string]interface{}{"command": "go test ./..."}, "sessionId": "sess-1",
+ })
+
+ event := piEventWithAction(t, logPath, "tool.invoked")
+ tool := nested(t, event, "tool")
+ if tool["name"] != "bash" || tool["command"] != "go test ./..." {
+ t.Fatalf("tool = %v, want the bash tool and its command", tool)
+ }
+}
+
+// The decision this mapper must not make. Pi's tool_call handler can block a call, but that is an
+// extension deciding rather than an operator being asked -- Pi exposes no approval decision through
+// the extension API. An approval event here would put a decision nobody made into the log, and
+// would be indistinguishable from Claude Code's PermissionRequest, which is a real one.
+func TestPiEventNeverSynthesizesApprovals(t *testing.T) {
+ logPath := piTestLog(t)
+
+ for _, payload := range []map[string]interface{}{
+ {"type": "tool_call", "toolName": "bash", "input": map[string]interface{}{"command": "rm -rf /tmp/x"}, "sessionId": "sess-1"},
+ {"type": "tool_result", "toolName": "bash", "input": map[string]interface{}{"command": "rm -rf /tmp/x"}, "sessionId": "sess-1"},
+ {"type": "user_bash", "command": "sudo -s", "sessionId": "sess-1"},
+ } {
+ runHookWithInput(t, runPiEvent, payload)
+ }
+
+ for _, event := range endpointEvents(t, logPath) {
+ meta, _ := event["event"].(map[string]interface{})
+ action, _ := meta["action"].(string)
+ if len(action) >= 9 && action[:9] == "approval." {
+ t.Fatalf("Pi produced an approval event (%s); Pi exposes no approval decision to observe", action)
+ }
+ if _, ok := event["approval"]; ok {
+ t.Fatalf("Pi event carries an approval block: %v", event)
+ }
+ }
+}
+
+func TestPiEventToolResultActionsPerTool(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, find takes a glob, ls takes a directory. None is a file operation,
+ // and a custom tool's arguments mean whatever its author decided.
+ {"grep", map[string]interface{}{"pattern": "TODO"}, "tool.completed"},
+ {"my_custom_tool", map[string]interface{}{"anything": true}, "tool.completed"},
+ } {
+ t.Run(tc.tool, func(t *testing.T) {
+ events := piEndpointEvents(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)
+ }
+ })
+ }
+}
+
+// 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 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{}{
+ "type": "tool_result", "toolName": "read", "input": map[string]interface{}{},
+ }, "sess-1")
+ if len(events) != 1 || events[0].action != "tool.completed" {
+ t.Fatalf("events = %v, want a single tool.completed", events)
+ }
+}
+
+// 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{}{
+ "type": "tool_result", "toolName": "bash", "input": map[string]interface{}{},
+ }, "sess-1")
+ if len(events) != 1 || events[0].action != "tool.completed" {
+ t.Fatalf("events = %v, want a single tool.completed", events)
+ }
+}
+
+func TestPiEventEditResultRecordsTheUnifiedPatch(t *testing.T) {
+ logPath := piTestLog(t)
+ patch := "--- a/main.go\n+++ b/main.go\n@@ -1 +1 @@\n-old\n+new\n"
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "tool_result", "toolName": "edit", "sessionId": "sess-1",
+ "input": map[string]interface{}{"path": "/repo/main.go"},
+ "details": map[string]interface{}{"patch": patch, "diff": "display form"},
+ })
+
+ event := piEventWithAction(t, logPath, "file.modified")
+ file := nested(t, event, "file")
+ if file["path"] != "/repo/main.go" || file["operation"] != "modify" {
+ t.Fatalf("file = %v, want the edited path with a modify operation", file)
+ }
+ // The unified patch is the machine-readable one; the display diff is only a fallback.
+ content := nested(t, event, "content")
+ if content["bytes"] != float64(len(patch)) {
+ t.Fatalf("content.bytes = %v, want the patch length %d", content["bytes"], len(patch))
+ }
+}
+
+func TestPiEventFailedToolIsRecordedAsAFailure(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "tool_result", "toolName": "bash", "sessionId": "sess-1",
+ "input": map[string]interface{}{"command": "false"}, "isError": true,
+ })
+
+ event := piEventWithAction(t, logPath, "tool.failed")
+ meta := nested(t, event, "event")
+ if event["severity"] != "high" {
+ t.Fatalf("severity = %v, want high for a failed tool", event["severity"])
+ }
+ if meta["category"] != "tool" {
+ t.Fatalf("category = %v, want tool", meta["category"])
+ }
+}
+
+func TestPiEventUserBashRecordsAnOperatorCommand(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "user_bash", "command": "git status", "cwd": "/repo",
+ "excludeFromContext": true, "sessionId": "sess-1",
+ })
+
+ event := piEventWithAction(t, logPath, "command.executed")
+ command := nested(t, event, "command")
+ if command["command"] != "git status" {
+ t.Fatalf("command.command = %v, want git status", command["command"])
+ }
+ // Marked as the operator's rather than silently merged in with agent-run commands: this is the
+ // one command shape in Pi the agent did not originate.
+ raw := nested(t, event, "raw")
+ if raw["pi_user_initiated"] != true {
+ t.Fatalf("raw.pi_user_initiated = %v, want true", raw["pi_user_initiated"])
+ }
+}
+
+func TestPiEventMessageEndRecordsUsageAndReasoning(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "message_end", "sessionId": "sess-1",
+ "message": map[string]interface{}{
+ "role": "assistant",
+ "model": "claude-opus-5",
+ "content": []interface{}{
+ map[string]interface{}{"type": "thinking", "thinking": "weighing two approaches"},
+ map[string]interface{}{"type": "text", "text": "here is the answer"},
+ },
+ "usage": map[string]interface{}{
+ "input": float64(120), "output": float64(40),
+ "cacheRead": float64(90), "cacheWrite": float64(10), "reasoning": float64(25),
+ "totalTokens": float64(160),
+ "cost": map[string]interface{}{"total": 0.0042},
+ },
+ },
+ })
+
+ reasoning := piEventWithAction(t, logPath, "agent.reasoning")
+ // Only the thinking parts. 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 deliberation expects it.
+ parts := nested(t, reasoning, "gen_ai", "output")
+ messages, ok := parts["messages"].([]interface{})
+ if !ok || len(messages) != 1 {
+ t.Fatalf("gen_ai.output.messages = %v, want one reasoning message", parts["messages"])
+ }
+ first, _ := messages[0].(map[string]interface{})
+ firstParts, _ := first["parts"].([]interface{})
+ part, _ := firstParts[0].(map[string]interface{})
+ if part["type"] != "reasoning" || part["content"] != "weighing two approaches" {
+ t.Fatalf("reasoning part = %v, want only the thinking text", part)
+ }
+
+ usageEvent := piEventWithAction(t, logPath, "token.usage")
+ usage := nested(t, usageEvent, "gen_ai", "usage")
+ if usage["input_tokens"] != float64(120) || usage["output_tokens"] != float64(40) {
+ t.Fatalf("usage = %v, want the semconv token names", usage)
+ }
+ // Cache and reasoning are nested objects in the canonical shape, not scalars.
+ if got := nested(t, usageEvent, "gen_ai", "usage", "cache_read"); got["input_tokens"] != float64(90) {
+ t.Fatalf("cache_read = %v, want input_tokens 90", got)
+ }
+ if got := nested(t, usageEvent, "gen_ai", "usage", "cache_creation"); got["input_tokens"] != float64(10) {
+ t.Fatalf("cache_creation = %v, want input_tokens 10", got)
+ }
+ if got := nested(t, usageEvent, "gen_ai", "usage", "reasoning"); got["output_tokens"] != float64(25) {
+ t.Fatalf("reasoning = %v, want output_tokens 25", got)
+ }
+ if usage["cost_usd"] != 0.0042 {
+ t.Fatalf("cost_usd = %v, want the runtime-reported 0.0042", usage["cost_usd"])
+ }
+ // Pi reports a totalTokens that can disagree with its own parts, and Beacon's usage shape has no
+ // total. Carrying it would add a field nothing reads and something could contradict.
+ if _, ok := usage["total_tokens"]; ok {
+ t.Fatalf("usage carries total_tokens, which is not part of the canonical shape: %v", usage)
+ }
+ if _, ok := usage["totalTokens"]; ok {
+ t.Fatalf("usage carries Pi's own totalTokens spelling: %v", usage)
+ }
+}
+
+// message_end fires for user and toolResult messages too. Emitting a row for each would put an
+// 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{}{
+ "type": "message_end",
+ "message": map[string]interface{}{"role": role, "usage": map[string]interface{}{"input": float64(5)}},
+ }, "sess-1")
+ if len(events) != 0 {
+ t.Fatalf("%s message produced %d events, want none", role, len(events))
+ }
+ }
+}
+
+// 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{}{
+ "type": "message_end",
+ "message": map[string]interface{}{"role": "assistant", "content": []interface{}{}},
+ }, "sess-1")
+ if len(events) != 0 {
+ t.Fatalf("bare assistant message produced %d events, want none", len(events))
+ }
+}
+
+// The extension lifts Pi's cwd onto the envelope, and an event that carried its own wins. Without
+// this the working directory, repository, and branch are missing from every event of a run.
+func TestPiEventResolvesWorkspaceFromTheEnvelope(t *testing.T) {
+ logPath := piTestLog(t)
+ repo := t.TempDir()
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "input", "text": "hello", "sessionId": "sess-1", "cwd": repo,
+ })
+
+ event := piEventWithAction(t, logPath, "prompt.submitted")
+ session := nested(t, event, "session")
+ if session["working_directory"] != repo {
+ t.Fatalf("session.working_directory = %v, want %q", session["working_directory"], repo)
+ }
+}
+
+// The harness name is normalized at write time, so a Pi session is not split across two spellings
+// in any query that groups by harness.name.
+func TestPiEventNormalizesTheHarnessName(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{
+ "type": "session_start", "reason": "startup", "sessionId": "sess-1",
+ })
+
+ event := piEventWithAction(t, logPath, "session.started")
+ harness := nested(t, event, "harness")
+ if harness["name"] != "pi_cli" {
+ t.Fatalf("harness.name = %v, want pi_cli", harness["name"])
+ }
+}
+
+// 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 TestPiEventSurvivesAMissingSessionID(t *testing.T) {
+ logPath := piTestLog(t)
+
+ runHookWithInput(t, runPiEvent, map[string]interface{}{"type": "input", "text": "hello"})
+
+ if got := piEventActions(t, logPath); len(got) != 1 || got[0] != "prompt.submitted" {
+ t.Fatalf("actions = %v, want [prompt.submitted]", got)
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.go
index 08c5fbcc..2b45ffad 100644
--- a/cli/beacon/cmd/endpoint_diagnostics.go
+++ b/cli/beacon/cmd/endpoint_diagnostics.go
@@ -920,6 +920,9 @@ func hookStatusesWithConfig(targets []string, cfg endpointconfig.Config) map[str
case "cline":
status := endpointhooks.ClineHookStatus(endpointhooks.ClineOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.PluginPath, Raw: status}
+ case "pi":
+ status := endpointhooks.PiHookStatus(endpointhooks.PiOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
+ statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ExtensionPath, Raw: status}
case "grok":
status := endpointhooks.GrokHookStatus(endpointhooks.GrokOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
diff --git a/cli/beacon/cmd/endpoint_hooks.go b/cli/beacon/cmd/endpoint_hooks.go
index 61b7f08c..f5bccab5 100644
--- a/cli/beacon/cmd/endpoint_hooks.go
+++ b/cli/beacon/cmd/endpoint_hooks.go
@@ -140,6 +140,19 @@ func installEndpointHookTarget(name string, cfg endpointconfig.Config) error {
return err
}
fmt.Printf("Cline plugin installed: %s\n", status.PluginPath)
+ case "pi":
+ status, err := endpointhooks.InstallPi(endpointhooks.PiOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Printf("Pi extension installed: %s\n", status.ExtensionPath)
+ if endpointhooks.Level(endpointOpts.hookLevel) == endpointhooks.LevelProject {
+ fmt.Println("Project-level Pi extensions are subject to Pi's project-trust prompt; a user-level install needs no further interaction.")
+ }
case "grok":
status, err := endpointhooks.InstallGrok(endpointhooks.GrokOptions{
Level: endpointhooks.Level(endpointOpts.hookLevel),
@@ -295,6 +308,16 @@ func uninstallEndpointHookTarget(name string, cfg endpointconfig.Config) error {
return err
}
fmt.Println(status.Message)
+ case "pi":
+ status, err := endpointhooks.UninstallPi(endpointhooks.PiOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Println(status.Message)
case "grok":
status, err := endpointhooks.UninstallGrok(endpointhooks.GrokOptions{
Level: endpointhooks.Level(endpointOpts.hookLevel),
@@ -399,6 +422,12 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {
LogPath: cfg.LogPath,
UserMode: cfg.UserMode,
})
+ case "pi":
+ statuses["pi"] = endpointhooks.PiHookStatus(endpointhooks.PiOptions{
+ Level: endpointhooks.Level(endpointOpts.hookLevel),
+ LogPath: cfg.LogPath,
+ UserMode: cfg.UserMode,
+ })
case "grok":
statuses["grok"] = endpointhooks.GrokHookStatus(endpointhooks.GrokOptions{
Level: endpointhooks.Level(endpointOpts.hookLevel),
@@ -461,6 +490,10 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {
status := statuses["cline"].(endpointhooks.ClineStatus)
fmt.Printf("Cline plugin: installed=%t path=%s\n", status.Installed, status.PluginPath)
fmt.Println(status.Message)
+ case "pi":
+ status := statuses["pi"].(endpointhooks.PiStatus)
+ fmt.Printf("Pi extension: installed=%t path=%s\n", status.Installed, status.ExtensionPath)
+ fmt.Println(status.Message)
case "grok":
status := statuses["grok"].(endpointhooks.GrokStatus)
fmt.Printf("Grok hooks: installed=%t path=%s\n", status.Installed, status.HooksPath)
diff --git a/cli/beacon/cmd/endpoint_hooks_repair.go b/cli/beacon/cmd/endpoint_hooks_repair.go
index 66c4b241..1f195e99 100644
--- a/cli/beacon/cmd/endpoint_hooks_repair.go
+++ b/cli/beacon/cmd/endpoint_hooks_repair.go
@@ -148,7 +148,7 @@ func installedHookTargetsForUser(homeDir, logPath string) ([]string, error) {
}
func repairTargetOrder() []string {
- return []string{"claude", "codex", "cursor", "vscode", "factory", "opencode", "cline", "grok", "hermes", "devin-cli", "devin-desktop", "antigravity"}
+ return []string{"claude", "codex", "cursor", "vscode", "factory", "opencode", "cline", "pi", "grok", "hermes", "devin-cli", "devin-desktop", "antigravity"}
}
// withUserHome runs fn as if it were executing inside another user's profile.
diff --git a/cli/beacon/cmd/endpoint_targets.go b/cli/beacon/cmd/endpoint_targets.go
index 6c39e434..b32bdfd2 100644
--- a/cli/beacon/cmd/endpoint_targets.go
+++ b/cli/beacon/cmd/endpoint_targets.go
@@ -46,6 +46,10 @@ var harnessTargets = []harnessTarget{
{name: "factory", endpointKind: endpointTargetHook, endpointAliases: []string{"factory", "droid"}, hookAliases: []string{"factory", "droid"}},
{name: "opencode", endpointKind: endpointTargetHook, endpointAliases: []string{"opencode"}, hookAliases: []string{"opencode"}},
{name: "cline", endpointKind: endpointTargetHook, endpointAliases: []string{"cline"}, hookAliases: []string{"cline"}},
+ // pi_cli is accepted alongside pi because it is the canonical harness name events are written
+ // under, so anyone reading a Pi row out of the runtime log and passing it back to a --harness
+ // flag gets the runtime they are looking at rather than an "unsupported harness" error.
+ {name: "pi", endpointKind: endpointTargetHook, endpointAliases: []string{"pi", "pi-cli", "pi_cli"}, hookAliases: []string{"pi", "pi-cli", "pi_cli"}},
{name: "grok", endpointKind: endpointTargetHook, endpointAliases: []string{"grok"}, hookAliases: []string{"grok"}},
{name: "hermes", endpointKind: endpointTargetHook, endpointAliases: []string{"hermes", "hermes-agent"}, hookAliases: []string{"hermes", "hermes-agent"}},
{name: "antigravity", endpointKind: endpointTargetHook, endpointAliases: []string{"antigravity", "antigravity-cli"}, hookAliases: []string{"antigravity", "antigravity-cli"}},
diff --git a/cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts
new file mode 100644
index 00000000..2a1d7cfc
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts
@@ -0,0 +1,270 @@
+// __BEACON_MANAGED_MARKER__
+// Beacon endpoint telemetry extension for Pi.
+// Managed by beacon endpoint hooks install --harness pi.
+
+// The argv Beacon's installer writes, as an array rather than a command line.
+//
+// An argv array is passed straight to the OS with no shell in between, which sidesteps quoting
+// entirely -- the same reason the Cline plugin uses one. Pi runs as a Bun-compiled binary or under
+// Node depending on how it was installed, and on Windows as readily as on macOS, so there is no one
+// shell whose quoting rules would hold.
+const beaconArgv: string[] = ["__BEACON_ARGV__"]
+
+const debugEnabled = process.env.BEACON_PI_DEBUG === "1"
+
+// A send that has not finished in this long is abandoned. Pi awaits event handlers before
+// continuing the agent loop, so this is the worst case Beacon can add to a tool call.
+const sendTimeoutMs = 2000
+
+// How deep into an event the serializer will walk before giving up.
+const maxDepth = 8
+
+// Pi's own event objects, narrowed to the fields Beacon reads.
+//
+// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose. The installed
+// file sits in ~/.pi/agent/extensions with no node_modules beside it, and Pi loads it through jiti,
+// which strips types without resolving them. A value import would fail at load; a type import would
+// resolve for nobody. Local structural types cost the compile-time link to Pi's definitions and buy
+// a file that loads wherever Pi does.
+type PiEvent = Record<string, unknown> & { type: string }
+
+interface PiSessionManager {
+ getSessionId?: () => string
+ getCwd?: () => string
+}
+
+interface PiContext {
+ cwd?: string
+ sessionManager?: PiSessionManager
+ model?: { id?: string; name?: string; provider?: string } | undefined
+ mode?: string
+}
+
+// The events Beacon subscribes to, and nothing else.
+//
+// Pi publishes roughly thirty event types, most of them provider-request and TUI-rendering
+// internals that describe no agent action. Subscribing to all of them would fill the runtime log
+// with rows no query asks for -- the same reason the Cline mapper drops unrecognized stages -- and
+// would put Beacon in the path of every streaming token update.
+//
+// `tool_call` and `tool_result` are the pair that carries tool activity: the first names the tool
+// and its arguments before it runs, the second carries the outcome. `user_bash` is a command the
+// human ran with Pi's `!` prefix, which no tool event covers.
+//
+// Deliberately absent: any approval event. Pi's `tool_call` handler can block a call, but that is
+// an extension deciding, not an operator being asked -- Pi exposes no operator approval decision
+// through this API. Synthesizing an approval from a pre-tool notification would put a decision
+// nobody made into the log, so Beacon records these as tool activity and leaves approval telemetry
+// empty for Pi, exactly as it does for Cline.
+const subscribedEvents = [
+ "session_start",
+ "session_shutdown",
+ "input",
+ "tool_call",
+ "tool_result",
+ "user_bash",
+ "message_end",
+] as const
+
+function debugLog(message: string, extra?: unknown) {
+ if (!debugEnabled) return
+ try {
+ // eslint-disable-next-line no-console
+ console.error("[beacon-pi]", message, extra ?? "")
+ } catch {
+ // Debug logging must stay best-effort.
+ }
+}
+
+// safeClone turns a Pi event into something JSON.stringify accepts.
+//
+// Pi's events carry live objects: an AbortSignal on the session events, AgentMessage arrays holding
+// class instances, and tool inputs that are mutable by design. JSON.stringify throws on a circular
+// reference and on a bigint, and silently flattens an Error to {}, so each is handled here rather
+// than losing the whole payload to one bad field.
+//
+// Cycles are tracked along the current path and released on the way out, so an object that legibly
+// appears twice -- the same file path referenced from two places in one edit -- is kept both times.
+// A WeakSet that never released would drop the second occurrence as if it were a cycle.
+function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {
+ if (value === null) return null
+ const kind = typeof value
+ if (kind === "function" || kind === "symbol" || kind === "undefined") return undefined
+ if (kind === "bigint") return String(value)
+ if (kind !== "object") return value
+ if (depth >= maxDepth) return undefined
+
+ const object = value as object
+ if (seen.has(object)) return undefined
+ if (value instanceof Error) return { name: value.name, message: value.message }
+ if (value instanceof Date) return value.toISOString()
+
+ seen.add(object)
+ try {
+ if (Array.isArray(value)) {
+ return value.map((item) => safeClone(item, depth + 1, seen))
+ }
+ const out: Record<string, unknown> = {}
+ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
+ const cloned = safeClone(nested, depth + 1, seen)
+ if (cloned !== undefined) out[key] = cloned
+ }
+ return out
+ } finally {
+ seen.delete(object)
+ }
+}
+
+async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
+ // Flattened before anything else sees it, so every consumer of this function is handed plain
+ // data rather than a live Pi event with cycles and functions still attached.
+ const safe = safeClone(payload)
+
+ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.pi.testSender")]
+ if (typeof testSender === "function") {
+ await (testSender as (value: unknown) => unknown)(safe)
+ return
+ }
+
+ let body: string
+ try {
+ body = JSON.stringify(safe)
+ } catch (err) {
+ debugLog("payload could not be serialized", err)
+ return
+ }
+ if (!body) return
+
+ try {
+ // Imported lazily so a host without node:child_process fails to send rather than failing to
+ // load: a throwing import at module scope would surface to the user as a broken extension, and
+ // Pi reports an extension that throws at load time rather than continuing without it.
+ const { spawn } = await import("node:child_process")
+ await new Promise<void>((resolve) => {
+ let settled = false
+ const finish = () => {
+ if (settled) return
+ settled = true
+ resolve()
+ }
+ let child
+ try {
+ child = spawn(beaconArgv[0], beaconArgv.slice(1), {
+ stdio: ["pipe", "ignore", "ignore"],
+ windowsHide: true,
+ })
+ } catch (err) {
+ debugLog("hook binary could not be spawned", err)
+ finish()
+ return
+ }
+ const timer = setTimeout(() => {
+ try {
+ child.kill()
+ } catch {
+ // Already gone.
+ }
+ debugLog("hook binary timed out", { type: payload?.type })
+ finish()
+ }, sendTimeoutMs)
+ // An unreferenced timer cannot keep Pi alive at exit waiting on Beacon telemetry.
+ if (typeof timer.unref === "function") timer.unref()
+ const done = () => {
+ clearTimeout(timer)
+ finish()
+ }
+ child.on("error", (err) => {
+ debugLog("hook binary failed", err)
+ done()
+ })
+ child.on("close", done)
+ // Without this, a hook binary that exits before reading stdin turns an EPIPE into an
+ // unhandled error event in the host process. Beacon telemetry must never do that.
+ child.stdin?.on("error", () => {})
+ try {
+ child.stdin?.end(body)
+ } catch (err) {
+ debugLog("payload could not be written", err)
+ }
+ })
+ } catch (err) {
+ debugLog("send failed", err)
+ // Beacon telemetry must never interrupt Pi execution.
+ }
+}
+
+// identity lifts the session and workspace fields Beacon needs to the top level of the envelope.
+//
+// Pi keeps them on the handler context rather than on the event, and behind accessor functions
+// rather than as properties, so they have to be read per event: a session id captured once at
+// extension load would be wrong after `/new`, a resume, or a fork, all of which replace the session
+// without reloading the extension.
+//
+// Each accessor is called defensively. `getSessionId` and `getCwd` are documented members of the
+// read-only session manager, but an extension that loses its session id loses the field that groups
+// every event of a run, so a throwing accessor costs that field rather than the event.
+function identity(ctx: PiContext | undefined): Record<string, unknown> {
+ const fields: Record<string, unknown> = {}
+ if (!ctx) return fields
+ const manager = ctx.sessionManager
+ try {
+ const sessionId = manager?.getSessionId?.()
+ if (sessionId) fields.sessionId = sessionId
+ } catch (err) {
+ debugLog("session id could not be read", err)
+ }
+ let cwd = ctx.cwd
+ if (!cwd) {
+ try {
+ cwd = manager?.getCwd?.()
+ } catch (err) {
+ debugLog("cwd could not be read", err)
+ }
+ }
+ if (cwd) fields.cwd = cwd
+ const model = ctx.model
+ if (model) {
+ // Pi's Model carries an id and a provider separately. Joined here so the envelope's `model` is
+ // one string, matching how every other Beacon collection path reports it.
+ const name = model.id || model.name
+ if (name) fields.model = model.provider ? `${model.provider}/${name}` : name
+ }
+ if (ctx.mode) fields.piMode = ctx.mode
+ return fields
+}
+
+type PiExtensionAPI = {
+ on: (event: string, handler: (event: PiEvent, ctx: PiContext) => Promise<void> | void) => void
+}
+
+// createBeaconExtension is exported for tests; Pi loads the default export below.
+export function createBeaconExtension() {
+ const forward = async (event: PiEvent, ctx: PiContext) => {
+ try {
+ await sendToBeacon({ ...identity(ctx), ...event })
+ } catch (err) {
+ // Unreachable in practice: sendToBeacon swallows its own failures. Kept because a handler
+ // that rejects is a handler that can break the run it was observing.
+ debugLog("handler failed", err)
+ }
+ }
+
+ return {
+ register(pi: PiExtensionAPI) {
+ for (const name of subscribedEvents) {
+ // Every handler returns undefined. Beacon observes; it never blocks a tool call, rewrites a
+ // prompt, transforms input, or replaces a message. Pi reads a returned object as a request
+ // to change behavior -- `{ block: true }` on tool_call, `{ action: "transform" }` on input
+ // -- so returning nothing is what keeps this extension an observer. Enforcement lives
+ // behind the policy provider seam in the hook adapter, not here.
+ pi.on(name, forward)
+ }
+ },
+ // Exposed so a test can assert the subscription list without a live Pi instance.
+ subscribedEvents: [...subscribedEvents],
+ }
+}
+
+export default function beaconExtension(pi: PiExtensionAPI) {
+ createBeaconExtension().register(pi)
+}
diff --git a/cli/beacon/internal/endpoint/hooks/assets/pi/embed.go b/cli/beacon/internal/endpoint/hooks/assets/pi/embed.go
new file mode 100644
index 00000000..80991f98
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/assets/pi/embed.go
@@ -0,0 +1,10 @@
+package piextension
+
+import _ "embed"
+
+// Template embeds the checked copy used by Beacon's Go installer.
+// The root source of truth lives at plugins/pi-beacon/src/beacon.ts.
+// Tests fail if this copy drifts.
+//
+//go:embed beacon.ts
+var Template string
diff --git a/cli/beacon/internal/endpoint/hooks/pi.go b/cli/beacon/internal/endpoint/hooks/pi.go
index 72d5dffc..6a83346c 100644
--- a/cli/beacon/internal/endpoint/hooks/pi.go
+++ b/cli/beacon/internal/endpoint/hooks/pi.go
@@ -1,9 +1,13 @@
package hooks
import (
+ "encoding/json"
"fmt"
"os"
"path/filepath"
+ "strings"
+
+ piextension "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks/assets/pi"
)
// Pi (pi.dev) has no hooks configuration file and no OpenTelemetry support, so neither of Beacon's
@@ -27,8 +31,181 @@ const (
// when the extension's behavior changes in a way that makes an older installed copy wrong,
// which is what lets a repair recognize a stale file rather than leave it in place.
PiManagedExtensionMarker = "beacon-managed-pi-extension:v1"
+
+ // piArgvPlaceholder is the literal the extension source carries where the hook invocation goes.
+ // Spelled out as a constant so the renderer can verify it was present before substituting: a
+ // template edit that renamed it would otherwise install a file that spawns nothing and reports
+ // success.
+ piArgvPlaceholder = `["__BEACON_ARGV__"]`
)
+var piExtensionTemplate = piextension.Template
+
+type PiOptions struct {
+ Level Level
+ LogPath string
+ UserMode bool
+}
+
+type PiStatus struct {
+ Installed bool `json:"installed"`
+ BinaryPath string `json:"binary_path,omitempty"`
+ ExtensionPath string `json:"extension_path,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+var piRuntime = hookRuntime{
+ displayName: "Pi",
+ configPath: PiExtensionPath,
+ install: installPiExtension,
+ uninstall: removePiExtension,
+ isInstalled: isPiInstalledAt,
+}
+
+func InstallPi(opts PiOptions) (PiStatus, error) {
+ status, err := installRuntimeHooks(piRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return PiStatus{}, err
+ }
+ return piStatusFromRuntime(status), nil
+}
+
+func UninstallPi(opts PiOptions) (PiStatus, error) {
+ status, err := uninstallRuntimeHooks(piRuntime, RuntimeOptions(opts))
+ if err != nil {
+ return PiStatus{}, err
+ }
+ return piStatusFromRuntime(status), nil
+}
+
+func PiHookStatus(opts PiOptions) PiStatus {
+ return piStatusFromRuntime(runtimeHookStatus(piRuntime, RuntimeOptions(opts)))
+}
+
+func IsPiInstalled(opts PiOptions) bool {
+ return isRuntimeInstalled(piRuntime, RuntimeOptions(opts))
+}
+
+// piStatusFromRuntime reports installed only when the extension can actually reach the hook binary.
+//
+// The marker alone is not enough, for the same reasons it is not enough for Cline: an extension file
+// survives a Beacon uninstall, a partially applied update, or a home directory restored onto a
+// machine where the binary lives elsewhere. In each case Pi loads an extension that spawns nothing,
+// and reporting that as installed tells an operator telemetry is being collected when none is.
+func piStatusFromRuntime(status runtimeStatus) PiStatus {
+ out := PiStatus{
+ Installed: status.Installed,
+ BinaryPath: status.BinaryPath,
+ ExtensionPath: status.ConfigPath,
+ Message: status.Message,
+ }
+ if !out.Installed || out.BinaryPath == "" {
+ return out
+ }
+ if _, err := os.Stat(out.BinaryPath); err != nil {
+ out.Installed = false
+ out.Message = fmt.Sprintf("Pi extension is installed, but Beacon hook binary is missing at %s", out.BinaryPath)
+ return out
+ }
+ data, err := os.ReadFile(out.ExtensionPath)
+ if err != nil || !piExtensionReferencesBinary(string(data), out.BinaryPath) || strings.Contains(string(data), "__BEACON_") {
+ out.Installed = false
+ out.Message = fmt.Sprintf("Pi extension at %s does not reference the active Beacon hook binary", out.ExtensionPath)
+ }
+ return out
+}
+
+// piExtensionReferencesBinary reports whether a rendered extension spawns the given hook binary.
+//
+// The path is compared in the form the file actually holds it. The installer writes argv through
+// json.Marshal, which escapes a backslash as two, so searching for the raw path finds nothing on
+// Windows. Marshalling the path and stripping the surrounding quotes produces exactly the substring
+// the file contains, on every platform, rather than a second escaping rule maintained by hand --
+// the same fix clinePluginReferencesBinary documents from having gotten it wrong first.
+func piExtensionReferencesBinary(source, binaryPath string) bool {
+ if binaryPath == "" {
+ return false
+ }
+ encoded, err := json.Marshal(binaryPath)
+ if err != nil || len(encoded) < 2 {
+ return false
+ }
+ return strings.Contains(source, string(encoded[1:len(encoded)-1]))
+}
+
+func installPiExtension(path, binaryPath, logPath, configPath string) error {
+ if existing, err := os.ReadFile(path); err == nil {
+ if !strings.Contains(string(existing), PiManagedExtensionMarker) {
+ return fmt.Errorf("refusing to overwrite unmanaged Pi extension at %s", path)
+ }
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+ extension, err := renderPiExtension(binaryPath, logPath, configPath)
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, []byte(extension), 0644)
+}
+
+func removePiExtension(path string) (bool, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ if !strings.Contains(string(data), PiManagedExtensionMarker) {
+ return false, nil
+ }
+ return true, os.Remove(path)
+}
+
+func isPiInstalledAt(path string) bool {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return false
+ }
+ return strings.Contains(string(data), PiManagedExtensionMarker)
+}
+
+func renderPiExtension(binaryPath, logPath, configPath string) (string, error) {
+ return renderPiExtensionTemplate(piExtensionTemplate, binaryPath, logPath, configPath)
+}
+
+// renderPiExtensionTemplate substitutes the hook invocation into the extension source.
+//
+// The invocation goes in as a JSON array of argv, not as a command line, because the extension
+// spawns the binary directly. That removes the shell -- and with it the per-shell quoting problem
+// endpointCommandPrefix documents -- from a runtime that ships as a Bun binary on Windows as
+// readily as on macOS. JSON encoding also means a path containing a quote or a backslash needs no
+// special handling, which is exactly what a Windows path is.
+func renderPiExtensionTemplate(template, binaryPath, logPath, configPath string) (string, error) {
+ args := append(endpointCommandArgs("pi", binaryPath, logPath, configPath), "pi-event")
+ argv, err := json.Marshal(args)
+ if err != nil {
+ return "", err
+ }
+ source := strings.ReplaceAll(template, "__BEACON_MANAGED_MARKER__", PiManagedExtensionMarker)
+ if !strings.Contains(source, piArgvPlaceholder) {
+ return "", fmt.Errorf("pi extension template is missing the %s placeholder", piArgvPlaceholder)
+ }
+ source = strings.ReplaceAll(source, piArgvPlaceholder, string(argv))
+ if strings.Contains(source, "__BEACON_") {
+ return "", fmt.Errorf("pi extension template contains unresolved Beacon placeholders")
+ }
+ return source, nil
+}
+
+func piEmbeddedExtensionSourcePath() string {
+ return filepath.Clean(filepath.Join("assets", "pi", "beacon.ts"))
+}
+
+func piRootExtensionSourcePath() string {
+ return filepath.Clean(filepath.Join("..", "..", "..", "..", "..", "plugins", "pi-beacon", "src", "beacon.ts"))
+}
+
// PiExtensionPath returns the extension file Beacon manages for a given install level.
//
// Pi loads extensions from two documented locations, and the distinction matters beyond the path:
diff --git a/cli/beacon/internal/endpoint/hooks/pi_test.go b/cli/beacon/internal/endpoint/hooks/pi_test.go
index 73f9729f..51157c8d 100644
--- a/cli/beacon/internal/endpoint/hooks/pi_test.go
+++ b/cli/beacon/internal/endpoint/hooks/pi_test.go
@@ -1,7 +1,11 @@
package hooks
import (
+ "encoding/json"
+ "os"
"path/filepath"
+ "regexp"
+ "strings"
"testing"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
@@ -60,3 +64,247 @@ func TestPiManagedExtensionMarkerIsStable(t *testing.T) {
"earlier builds, which uninstall then refuses to remove", PiManagedExtensionMarker)
}
}
+
+// piRenderedArgv extracts the argv the installer substituted into the extension.
+//
+// Parsed back out of the source rather than compared as a string: argv is the whole point of this
+// install shape, so the test asserts on the decoded array a host would spawn. The optional carriage
+// return is load-bearing for the same reason it is in the Cline test -- the extension source is a
+// checked-in file, and a Windows checkout converts its line endings.
+func piRenderedArgv(t *testing.T, source string) []string {
+ t.Helper()
+ match := regexp.MustCompile(`(?m)^const beaconArgv: string\[\] = (\[.*?\])\r?$`).FindStringSubmatch(source)
+ if len(match) != 2 {
+ t.Fatalf("no beaconArgv assignment in rendered extension:\n%s", source)
+ }
+ var argv []string
+ if err := json.Unmarshal([]byte(match[1]), &argv); err != nil {
+ t.Fatalf("decode beaconArgv %q: %v", match[1], err)
+ }
+ return argv
+}
+
+func TestInstallPiExtensionWritesManagedExtension(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "beacon.ts")
+ if err := installPiExtension(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatalf("installPiExtension returned error: %v", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read installed extension: %v", err)
+ }
+ source := string(data)
+ if !strings.Contains(source, PiManagedExtensionMarker) {
+ t.Fatal("installed extension is missing the managed marker, so uninstall would refuse to remove it")
+ }
+ if strings.Contains(source, "__BEACON_") {
+ t.Fatalf("installed extension still contains an unresolved placeholder:\n%s", source)
+ }
+
+ argv := piRenderedArgv(t, source)
+ want := []string{"/tmp/beacon-hooks", "--platform", "pi", "--log", "/tmp/runtime.jsonl", "--config", "/tmp/config.json"}
+ for i, value := range want {
+ if i >= len(argv) || argv[i] != value {
+ t.Fatalf("rendered argv = %v, want it to begin with %v", argv, want)
+ }
+ }
+ // The subcommand must be last: the hook adapter dispatches on it, and an argv that ends with a
+ // flag value instead would spawn the root command and write nothing.
+ if argv[len(argv)-1] != "pi-event" {
+ t.Fatalf("rendered argv ends with %q, want pi-event", argv[len(argv)-1])
+ }
+}
+
+// A Windows path is the case that a hand-rolled quoting rule gets wrong, and the case a JSON-encoded
+// argv gets right for free.
+func TestRenderPiExtensionEncodesWindowsPaths(t *testing.T) {
+ source, err := renderPiExtension(`C:\Program Files\beacon\beacon-hooks.exe`, `C:\ProgramData\beacon\runtime.jsonl`, "")
+ if err != nil {
+ t.Fatalf("renderPiExtension returned error: %v", err)
+ }
+ argv := piRenderedArgv(t, source)
+ if argv[0] != `C:\Program Files\beacon\beacon-hooks.exe` {
+ t.Fatalf("argv[0] = %q, want the unescaped Windows path back", argv[0])
+ }
+}
+
+func TestInstallPiExtensionRefusesToOverwriteUnmanagedExtension(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "beacon.ts")
+ // Somebody else's extension that happens to share the filename. Overwriting it would delete
+ // their work, and Pi loads exactly one file per path.
+ if err := os.WriteFile(path, []byte("export default function () {}\n"), 0644); err != nil {
+ t.Fatalf("seed unmanaged extension: %v", err)
+ }
+ if err := installPiExtension(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", ""); err == nil {
+ t.Fatal("installPiExtension overwrote an unmanaged extension")
+ }
+ data, _ := os.ReadFile(path)
+ if string(data) != "export default function () {}\n" {
+ t.Fatalf("unmanaged extension was modified: %q", string(data))
+ }
+}
+
+func TestRemovePiExtensionOnlyRemovesManagedExtension(t *testing.T) {
+ dir := t.TempDir()
+ managed := filepath.Join(dir, "managed.ts")
+ unmanaged := filepath.Join(dir, "unmanaged.ts")
+ if err := installPiExtension(managed, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", ""); err != nil {
+ t.Fatalf("installPiExtension returned error: %v", err)
+ }
+ if err := os.WriteFile(unmanaged, []byte("export default function () {}\n"), 0644); err != nil {
+ t.Fatalf("seed unmanaged extension: %v", err)
+ }
+
+ removed, err := removePiExtension(managed)
+ if err != nil || !removed {
+ t.Fatalf("removePiExtension(managed) = %v, %v; want true, nil", removed, err)
+ }
+ if _, err := os.Stat(managed); !os.IsNotExist(err) {
+ t.Fatal("managed extension survived removal")
+ }
+
+ removed, err = removePiExtension(unmanaged)
+ if err != nil {
+ t.Fatalf("removePiExtension(unmanaged) returned error: %v", err)
+ }
+ if removed {
+ t.Fatal("removePiExtension removed an extension Beacon does not manage")
+ }
+ if _, err := os.Stat(unmanaged); err != nil {
+ t.Fatalf("unmanaged extension was deleted: %v", err)
+ }
+}
+
+func TestRemovePiExtensionIsQuietWhenNothingIsInstalled(t *testing.T) {
+ removed, err := removePiExtension(filepath.Join(t.TempDir(), "absent.ts"))
+ if err != nil {
+ t.Fatalf("removePiExtension on a missing file returned error: %v", err)
+ }
+ if removed {
+ t.Fatal("removePiExtension reported removing a file that does not exist")
+ }
+}
+
+// The placeholder check is what turns a template rename into a loud failure instead of an install
+// that reports success and spawns nothing.
+func TestRenderPiExtensionRejectsATemplateMissingItsPlaceholder(t *testing.T) {
+ if _, err := renderPiExtensionTemplate("// __BEACON_MANAGED_MARKER__\nconst x = 1\n", "/tmp/beacon-hooks", "", ""); err == nil {
+ t.Fatal("renderPiExtensionTemplate accepted a template with no argv placeholder")
+ }
+}
+
+func TestRenderPiExtensionRejectsUnresolvedPlaceholders(t *testing.T) {
+ template := "// __BEACON_MANAGED_MARKER__\nconst beaconArgv: string[] = [\"__BEACON_ARGV__\"]\nconst leftover = \"__BEACON_SOMETHING_ELSE__\"\n"
+ if _, err := renderPiExtensionTemplate(template, "/tmp/beacon-hooks", "", ""); err == nil {
+ t.Fatal("renderPiExtensionTemplate accepted a template with an unresolved placeholder")
+ }
+}
+
+func TestPiEmbeddedExtensionMatchesRootSource(t *testing.T) {
+ embedded, err := os.ReadFile(piEmbeddedExtensionSourcePath())
+ if err != nil {
+ t.Fatalf("read embedded extension source: %v", err)
+ }
+ root, err := os.ReadFile(piRootExtensionSourcePath())
+ if err != nil {
+ t.Fatalf("read root extension source: %v", err)
+ }
+ if string(embedded) != string(root) {
+ t.Fatal("embedded Pi extension source drifted from root package source; run `bun run sync` in plugins/pi-beacon")
+ }
+}
+
+// The marker alone is not enough to call an install healthy. An extension file outlives the binary
+// it was rendered against -- a Beacon uninstall, a partial update, a restored home directory -- and
+// in each case Pi loads an extension that spawns nothing.
+func TestPiStatusRejectsAnExtensionWithNoBinary(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "beacon.ts")
+ missing := filepath.Join(dir, "beacon-hooks")
+ if err := installPiExtension(path, missing, "/tmp/runtime.jsonl", ""); err != nil {
+ t.Fatalf("installPiExtension returned error: %v", err)
+ }
+ status := piStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: missing, ConfigPath: path})
+ if status.Installed {
+ t.Fatal("status reported installed while the hook binary is absent")
+ }
+ if !strings.Contains(status.Message, "missing") {
+ t.Fatalf("status message = %q, want it to name the missing binary", status.Message)
+ }
+}
+
+func TestPiStatusRejectsAnExtensionPointingElsewhere(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "beacon.ts")
+ stale := filepath.Join(dir, "old-beacon-hooks")
+ current := filepath.Join(dir, "beacon-hooks")
+ for _, binary := range []string{stale, current} {
+ if err := os.WriteFile(binary, []byte("#!/bin/sh\n"), 0755); err != nil {
+ t.Fatalf("seed binary: %v", err)
+ }
+ }
+ if err := installPiExtension(path, stale, "/tmp/runtime.jsonl", ""); err != nil {
+ t.Fatalf("installPiExtension returned error: %v", err)
+ }
+ status := piStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: current, ConfigPath: path})
+ if status.Installed {
+ t.Fatal("status reported installed while the extension spawns a different binary")
+ }
+}
+
+func TestPiStatusAcceptsAHealthyInstall(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "beacon.ts")
+ binary := filepath.Join(dir, "beacon-hooks")
+ if err := os.WriteFile(binary, []byte("#!/bin/sh\n"), 0755); err != nil {
+ t.Fatalf("seed binary: %v", err)
+ }
+ if err := installPiExtension(path, binary, "/tmp/runtime.jsonl", ""); err != nil {
+ t.Fatalf("installPiExtension returned error: %v", err)
+ }
+ status := piStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: binary, ConfigPath: path})
+ if !status.Installed {
+ t.Fatalf("status reported not installed for a healthy install: %q", status.Message)
+ }
+ if status.ExtensionPath != path {
+ t.Fatalf("status.ExtensionPath = %q, want %q", status.ExtensionPath, path)
+ }
+}
+
+func TestIsPiInstalledAtRequiresTheManagedMarker(t *testing.T) {
+ dir := t.TempDir()
+ managed := filepath.Join(dir, "managed.ts")
+ unmanaged := filepath.Join(dir, "unmanaged.ts")
+ if err := installPiExtension(managed, "/tmp/beacon-hooks", "", ""); err != nil {
+ t.Fatalf("installPiExtension returned error: %v", err)
+ }
+ if err := os.WriteFile(unmanaged, []byte("export default function () {}\n"), 0644); err != nil {
+ t.Fatalf("seed unmanaged extension: %v", err)
+ }
+ if !isPiInstalledAt(managed) {
+ t.Fatal("isPiInstalledAt did not recognize Beacon's own extension")
+ }
+ if isPiInstalledAt(unmanaged) {
+ t.Fatal("isPiInstalledAt claimed an unmanaged extension as Beacon's")
+ }
+ if isPiInstalledAt(filepath.Join(dir, "absent.ts")) {
+ t.Fatal("isPiInstalledAt claimed a file that does not exist")
+ }
+}
+
+func TestPiExtensionReferencesBinaryHandlesWindowsPaths(t *testing.T) {
+ binary := `C:\Program Files\beacon\beacon-hooks.exe`
+ source, err := renderPiExtension(binary, `C:\ProgramData\beacon\runtime.jsonl`, "")
+ if err != nil {
+ t.Fatalf("renderPiExtension returned error: %v", err)
+ }
+ if !piExtensionReferencesBinary(source, binary) {
+ t.Fatal("a correctly installed Windows extension was reported as not referencing its own binary")
+ }
+ if piExtensionReferencesBinary(source, `C:\Other\beacon-hooks.exe`) {
+ t.Fatal("piExtensionReferencesBinary matched a binary the extension does not spawn")
+ }
+ if piExtensionReferencesBinary(source, "") {
+ t.Fatal("piExtensionReferencesBinary matched an empty binary path")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/inventory/inventory.go b/cli/beacon/internal/endpoint/inventory/inventory.go
index de6da3b2..34885ca0 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory.go
@@ -14,6 +14,8 @@ import (
"github.com/pelletier/go-toml/v2"
"gopkg.in/yaml.v3"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
)
const (
@@ -202,6 +204,7 @@ func candidates(home, wd string) []candidate {
items = append(items, copilotCandidates(home)...)
items = append(items, opencodeCandidates(home, wd)...)
items = append(items, clineCandidates(home, wd)...)
+ items = append(items, piCandidates(home, wd)...)
items = append(items, hermesCandidates(home)...)
items = append(items, devinCandidates(home, wd)...)
items = append(items, grokCandidates(home, wd)...)
@@ -291,6 +294,32 @@ func clineCandidates(home, wd string) []candidate {
}
}
+// piCandidates covers both documented Pi extension locations.
+//
+// The paths come from the installer rather than being rebuilt here: hooks.PiExtensionPath is the
+// one definition of where Beacon writes, and a second copy of that path is how inventory comes to
+// report on a file the installer does not touch. A resolution error yields no candidate rather than
+// a relative path, which would otherwise make inventory report on whatever sits under the current
+// working directory.
+func piCandidates(home, wd string) []candidate {
+ items := []candidate{}
+ if home != "" {
+ items = append(items, candidate{
+ runtime: "pi_cli",
+ path: filepath.Join(home, ".pi", "agent", "extensions", "beacon.ts"),
+ scope: ScopeUser, format: formatMetadataOnly, kind: KindPlugin,
+ })
+ }
+ if wd != "" {
+ items = append(items, candidate{
+ runtime: "pi_cli",
+ path: filepath.Join(wd, ".pi", "extensions", "beacon.ts"),
+ scope: ScopeProject, format: formatMetadataOnly, kind: KindPlugin,
+ })
+ }
+ return items
+}
+
func hermesCandidates(home string) []candidate {
return []candidate{{runtime: "hermes", path: filepath.Join(home, ".hermes", "config.yaml"), scope: ScopeUser, format: formatYAML, kind: KindNativeConfig}}
}
@@ -622,6 +651,11 @@ func beaconManaged(item candidate, data []byte) bool {
return strings.Contains(text, "beacon-managed-opencode-plugin:v1")
case "cline":
return strings.Contains(text, "beacon-managed-cline-plugin:v1")
+ // Read from the installer's own constant rather than repeated as a literal here, unlike the
+ // markers above. Two spellings of a marker is how discovery comes to report on a file the
+ // installer does not write -- the reason hooks.PiManagedExtensionMarker is exported at all.
+ case "pi_cli":
+ return strings.Contains(text, hooks.PiManagedExtensionMarker)
case "grok":
return strings.Contains(text, "beacon-managed-grok-hooks:v1")
}
diff --git a/cli/beacon/internal/endpoint/inventory/inventory_test.go b/cli/beacon/internal/endpoint/inventory/inventory_test.go
index fd4060a3..54e1933d 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory_test.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory_test.go
@@ -340,6 +340,10 @@ func TestScanIncludesAllSupportedCurrentUserAndProjectConfigs(t *testing.T) {
{runtime: "opencode", path: filepath.Join(work, ".opencode", "plugins", "beacon.ts"), scope: ScopeProject, format: formatMetadataOnly, kind: KindPlugin},
{runtime: "cline", path: filepath.Join(home, ".cline", "plugins", "beacon.ts"), scope: ScopeUser, format: formatMetadataOnly, kind: KindPlugin},
{runtime: "cline", path: filepath.Join(work, ".cline", "plugins", "beacon.ts"), scope: ScopeProject, format: formatMetadataOnly, kind: KindPlugin},
+ // Pi's user extension directory carries an `agent` segment that its project directory does
+ // not, so the two paths are spelled out rather than derived from each other.
+ {runtime: "pi_cli", path: filepath.Join(home, ".pi", "agent", "extensions", "beacon.ts"), scope: ScopeUser, format: formatMetadataOnly, kind: KindPlugin},
+ {runtime: "pi_cli", path: filepath.Join(work, ".pi", "extensions", "beacon.ts"), scope: ScopeProject, format: formatMetadataOnly, kind: KindPlugin},
{runtime: "hermes", path: filepath.Join(home, ".hermes", "config.yaml"), scope: ScopeUser, format: formatYAML, kind: KindNativeConfig},
{runtime: "devin-cli", path: filepath.Join(home, ".config", "devin", "config.json"), scope: ScopeUser, format: formatJSON, kind: KindNativeConfig},
{runtime: "devin-cli", path: filepath.Join(work, ".devin", "hooks.v1.json"), scope: ScopeProject, format: formatJSON, kind: KindHookConfig},
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 31066d9c..bbe54917 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -810,6 +810,8 @@ func configureHarnesses(cfg endpointconfig.Config) ([]string, error) {
return paths, fmt.Errorf("opencode telemetry is installed with `beacon endpoint hooks install --harness opencode`, not endpoint install")
case "cline":
return paths, fmt.Errorf("Cline telemetry is installed with `beacon endpoint hooks install --harness cline`, not endpoint install")
+ case "pi", "pi_cli":
+ return paths, fmt.Errorf("Pi telemetry is installed with `beacon endpoint hooks install --harness pi`, not endpoint install")
case "copilot", "copilot_cli", "github_copilot":
return paths, fmt.Errorf("Copilot CLI telemetry is MDM-managed; set COPILOT_OTEL_ENABLED=true and OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:%d in the Copilot CLI launch environment instead of using --harness %s", cfg.Collector.HTTPPort, name)
case "factory", "droid":
diff --git a/docs/runtimes/pi.mdx b/docs/runtimes/pi.mdx
index 8515108c..f1ecfd6b 100644
--- a/docs/runtimes/pi.mdx
+++ b/docs/runtimes/pi.mdx
@@ -5,13 +5,15 @@ description: "Asymptote support details for Pi endpoint telemetry"
## Runtime Overview
-Asymptote supports [Pi](https://pi.dev/) as a discovered runtime surface, with a managed local extension as the collection path.
+Asymptote supports [Pi](https://pi.dev/) through a managed local extension.
Pi is neither of Asymptote's two established integration shapes. It has no hooks configuration file to merge a managed hook block into, and no OpenTelemetry support to point at the local collector. Its documented observation surface is the TypeScript extension API, which makes the integration extension-shaped — one Asymptote-owned extension file that forwards runtime events to `beacon-hooks`, the same shape as the OpenCode and Cline plugins.
-<Note>
-Pi support is currently **discovery only**. `beacon endpoint discover` identifies Pi, resolves the managed extension path, and reports whether Asymptote's extension is in place, and any Pi-attributed event that reaches the runtime log normalizes to the canonical `pi_cli` harness name. The managed extension itself is not shipped yet, so `beacon endpoint hooks install --harness pi` returns `unsupported hook harness "pi"` and no Pi hook events are collected. See [Known gaps](#known-gaps).
-</Note>
+Install it with:
+
+```bash
+beacon endpoint hooks install --harness pi
+```
## Prerequisites
@@ -53,45 +55,86 @@ An unmarked extension file reports `disabled` rather than `enabled` on purpose.
## Install or configuration support
-`beacon endpoint install` prepares shared endpoint config and runtime log paths, and includes Pi in discovery. There is no Pi hook install target yet:
+`beacon endpoint install` prepares shared endpoint config and runtime log paths. The extension is
+installed separately, because Pi loads it from the user's own profile rather than from a machine-wide
+location:
-```bash title="Not yet available"
-beacon endpoint hooks install --harness pi
-# Error: unsupported hook harness "pi"
+```bash
+beacon endpoint hooks install --harness pi # user level (default)
+beacon endpoint hooks install --harness pi --level project
+beacon endpoint hooks status --harness pi
+beacon endpoint hooks uninstall --harness pi
```
+Install writes one file and refuses to touch a `beacon.ts` it did not write, so an extension of your
+own that happens to share the filename is left alone and the install fails loudly rather than
+silently replacing it.
+
+`status` reports `installed=false` when the extension exists but points at a hook binary that is no
+longer there — after a Beacon uninstall, a partly applied update, or a home directory restored onto a
+different machine. In each of those cases Pi loads an extension that spawns nothing, and reporting
+that as installed would claim telemetry nobody is collecting.
+
## Telemetry coverage
| Area | Support |
|------|---------|
| Runtime discovery | Supported — executable and `~/.pi/agent` detection, managed extension path, and telemetry status |
| Harness attribution | Supported — `pi`, `pi.dev`, `pi_cli`, `pi-cli`, `pi_agent`, `pi-agent`, and `pi agent` all normalize to `pi_cli` |
-| Extension install and repair | Not yet available — see [Known gaps](#known-gaps) |
-| Prompt, session, tool, command, file, and approval telemetry | Not yet available — no extension is shipped, so no Pi hook events are collected |
-| Local JSONL and dashboard | Supported for any Pi-attributed event already in the runtime log |
-| MDM deployment | Supported for the endpoint agent; Pi extensions will install separately in the logged-in user's context |
+| Extension install, status, uninstall, and repair | Supported |
+| Session lifecycle | Supported — `session.started` and `session.ended`, carrying why the session started or stopped |
+| Prompts | Supported — `prompt.submitted`, with whether the input was typed, delivered over RPC, or injected by another extension |
+| Tool use | Supported — `tool.invoked` before execution, then `tool.completed` or `tool.failed` |
+| Commands | Supported — `command.executed` for the agent's `bash` tool and for commands you run with Pi's `!` prefix, which are marked as operator-initiated |
+| File activity | Supported — `file.read`, `file.created`, and `file.modified`, with the unified patch on an edit |
+| Agent reasoning | Supported — `agent.reasoning` from an assistant message's thinking parts, in the OTel GenAI reasoning-part shape |
+| Token usage and cost | Supported — `token.usage` normalized into `gen_ai.usage`, including cache and reasoning tokens and runtime-reported cost |
+| Approval decisions | Not available — Pi exposes no operator approval decision to observe. See [Known gaps](#known-gaps) |
+| Local JSONL and dashboard | Supported |
+| MDM deployment | Supported for the endpoint agent; the Pi extension installs separately in the logged-in user's context |
Pi's harness name is matched by equality against a closed set of spellings rather than by substring, because `pi` is two characters and appears inside names that belong to other runtimes — `copilot` contains it. A substring rule would attribute every GitHub Copilot and VS Code Copilot session to Pi.
## Data handling
-Discovery reads the managed extension path and reports its state. It records no prompt text, command output, tool input, or file content, because no Pi collection path is active yet.
+Pi content is handled the same way as every other runtime: prompts, tool arguments, commands, paths,
+diffs, and reasoning text retained in local or customer-controlled logs, with local secret redaction
+and per-string limits applied before writing, a hash and byte count on each content-bearing event,
+and events over the 64 KiB limit dropping raw and retained content while preserving stable metadata
+and setting `field_truncated`.
-When the managed extension lands, Pi content will be handled the same way as every other runtime: prompts, tool arguments and results, commands, command output, paths, and diffs retained in local or customer-controlled logs, with local secret redaction and per-string limits applied before writing, a hash and byte count on each content-bearing event, and events over the 64 KiB limit dropping raw and retained content while preserving stable metadata and setting `field_truncated`.
+The extension itself sends nothing over the network. It spawns the local `beacon-hooks` binary with a
+fixed argv and writes the event to its stdin; a send that has not completed in two seconds is
+abandoned so Beacon cannot stall Pi's agent loop, and a failure to spawn costs the event rather than
+the run.
## Known gaps
-- **No managed extension yet.** What ships today is Pi's runtime identity and discovery: the canonical harness name, the managed extension paths, the file marker, and status reporting. The extension source and its hook-event mapping are not in the build, so `beacon endpoint hooks install --harness pi` and `beacon endpoint hooks status --harness pi` both reject `pi` as an unsupported harness.
-- **No Pi hook telemetry.** Until the extension ships, Pi activity produces no endpoint events. Discovery reporting `missing` for a detected Pi install is the expected state, not a misconfiguration.
-- **No enforcement.** Consistent with every other runtime, enforcement stays behind the optional, off-by-default policy-provider seam (`BEACON_POLICY_PROVIDER`), which is not wired to Pi.
+- **No approval telemetry.** Pi's `tool_call` event lets an extension block a call, but that is an
+ extension deciding rather than an operator being asked — Pi exposes no operator approval decision
+ through the extension API. Beacon records these as tool activity and writes no approval events for
+ Pi, rather than synthesizing an approval nobody granted. The same choice applies to Cline for the
+ same reason. Detections in `rules/approval-abuse/` therefore do not fire on Pi activity.
+- **No enforcement.** Consistent with every other runtime, enforcement stays behind the optional,
+ off-by-default policy-provider seam (`BEACON_POLICY_PROVIDER`), which is not wired to Pi. Pi's
+ blocking `tool_call` handler would make it a viable target for that seam later.
+- **Streaming events are not collected.** The extension subscribes to seven of Pi's event types and
+ ignores the rest, which are provider-request and TUI-rendering internals. Assistant output is
+ recorded once when a message finalizes rather than token by token, so Beacon stays out of the
+ streaming path.
+- **Project-level installs need Pi's trust prompt.** A `.pi/extensions/beacon.ts` is subject to Pi's
+ project-trust prompt, so a user-level install is the one that works without further interaction.
## Deployment notes
-Because Pi collection is not active, there is nothing to restart and no hook state to validate. Confirm that discovery sees the runtime:
+The extension is loaded when Pi starts, so an install taken while Pi is running takes effect on its
+next launch. Confirm discovery sees the runtime, then generate one Pi event and check the log:
```bash
/opt/beacon/bin/beacon endpoint discover --all --json
+/opt/beacon/bin/beacon endpoint hooks status --harness pi
/opt/beacon/bin/beacon endpoint doctor --system
+grep '"name":"pi_cli"' ~/.beacon/endpoint/logs/runtime.jsonl | tail -3
```
## Related
diff --git a/plugins/pi-beacon/package.json b/plugins/pi-beacon/package.json
new file mode 100644
index 00000000..cae8a50c
--- /dev/null
+++ b/plugins/pi-beacon/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@asymptote-labs/pi-beacon",
+ "version": "0.0.0",
+ "private": true,
+ "description": "Beacon endpoint telemetry extension for Pi",
+ "type": "module",
+ "scripts": {
+ "check": "bun --check src/beacon.ts && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts",
+ "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts",
+ "test": "bun test src/beacon.test.ts"
+ },
+ "exports": {
+ ".": "./src/beacon.ts"
+ },
+ "files": [
+ "src/"
+ ],
+ "peerDependencies": {
+ "@earendil-works/pi-coding-agent": "*"
+ }
+}
diff --git a/plugins/pi-beacon/src/beacon.test.ts b/plugins/pi-beacon/src/beacon.test.ts
new file mode 100644
index 00000000..ab96ad35
--- /dev/null
+++ b/plugins/pi-beacon/src/beacon.test.ts
@@ -0,0 +1,234 @@
+import { afterEach, describe, expect, test } from "bun:test"
+
+import { createBeaconExtension } from "./beacon"
+
+const senderKey = Symbol.for("beacon.pi.testSender")
+
+type Sent = Record<string, unknown>
+
+function captureSends(): Sent[] {
+ const sent: Sent[] = []
+ ;(globalThis as Record<symbol, unknown>)[senderKey] = (payload: Sent) => {
+ sent.push(payload)
+ }
+ return sent
+}
+
+// A stand-in for Pi's ExtensionAPI that records subscriptions and lets a test fire one.
+function fakePi() {
+ const handlers = new Map<string, (event: Record<string, unknown>, ctx: unknown) => Promise<void> | void>()
+ return {
+ api: {
+ on(event: string, handler: (event: Record<string, unknown>, ctx: unknown) => Promise<void> | void) {
+ handlers.set(event, handler)
+ },
+ },
+ handlers,
+ async fire(event: Record<string, unknown> & { type: string }, ctx?: unknown) {
+ const handler = handlers.get(event.type)
+ if (!handler) throw new Error(`no handler registered for ${event.type}`)
+ await handler(event, ctx)
+ },
+ }
+}
+
+function context(overrides: Record<string, unknown> = {}) {
+ return {
+ cwd: "/repo",
+ sessionManager: { getSessionId: () => "sess-1", getCwd: () => "/repo" },
+ ...overrides,
+ }
+}
+
+afterEach(() => {
+ delete (globalThis as Record<symbol, unknown>)[senderKey]
+})
+
+describe("beacon pi extension", () => {
+ // These strings are the contract between this extension and the pi-event mapper in the hook
+ // adapter. A typo on either side produces no telemetry rather than an error, so the list is
+ // pinned here and asserted against the mapper's own list on the Go side.
+ test("subscribes to exactly the events the mapper handles", () => {
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ expect([...pi.handlers.keys()].sort()).toEqual([
+ "input",
+ "message_end",
+ "session_shutdown",
+ "session_start",
+ "tool_call",
+ "tool_result",
+ "user_bash",
+ ])
+ })
+
+ // Pi publishes many more events than these, most of them provider-request and TUI internals.
+ // Subscribing to one would put Beacon in the path of every streaming token update.
+ test("does not subscribe to streaming or provider internals", () => {
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ for (const noisy of [
+ "message_update",
+ "before_provider_request",
+ "before_provider_headers",
+ "after_provider_response",
+ "context",
+ "tool_execution_update",
+ ]) {
+ expect(pi.handlers.has(noisy)).toBe(false)
+ }
+ })
+
+ test("forwards the event with its type intact", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ await pi.fire({ type: "input", text: "do the thing", source: "interactive" }, context())
+
+ expect(sent).toHaveLength(1)
+ expect(sent[0].type).toBe("input")
+ expect(sent[0].text).toBe("do the thing")
+ })
+
+ // Pi keeps identity on the handler context behind accessor functions, not on the event, so the
+ // envelope has to carry it or every event loses the field that groups a run.
+ test("lifts session identity off the context onto the envelope", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ await pi.fire({ type: "session_start", reason: "startup" }, context())
+
+ expect(sent[0].sessionId).toBe("sess-1")
+ expect(sent[0].cwd).toBe("/repo")
+ })
+
+ // Re-read per event rather than captured at load: `/new`, a resume, and a fork all replace the
+ // session without reloading the extension, so a cached id would be silently wrong afterwards.
+ test("re-reads the session id for every event", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ let current = "sess-first"
+ const ctx = context({ sessionManager: { getSessionId: () => current, getCwd: () => "/repo" } })
+
+ await pi.fire({ type: "session_start", reason: "startup" }, ctx)
+ current = "sess-second"
+ await pi.fire({ type: "session_start", reason: "new" }, ctx)
+
+ expect(sent.map((event) => event.sessionId)).toEqual(["sess-first", "sess-second"])
+ })
+
+ test("joins provider and model id into one model string", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ await pi.fire(
+ { type: "input", text: "hello" },
+ context({ model: { id: "claude-opus-5", provider: "anthropic" } }),
+ )
+
+ expect(sent[0].model).toBe("anthropic/claude-opus-5")
+ })
+
+ // A throwing accessor must cost the field, not the event. An extension that drops telemetry
+ // because one getter failed is worse than one that reports an event without its cwd.
+ test("survives a context whose accessors throw", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ await pi.fire({ type: "tool_call", toolName: "bash", toolCallId: "call-1" }, {
+ sessionManager: {
+ getSessionId: () => {
+ throw new Error("session gone")
+ },
+ getCwd: () => {
+ throw new Error("cwd gone")
+ },
+ },
+ })
+
+ expect(sent).toHaveLength(1)
+ expect(sent[0].type).toBe("tool_call")
+ expect(sent[0].sessionId).toBeUndefined()
+ })
+
+ test("survives a missing context entirely", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ await pi.fire({ type: "session_shutdown", reason: "quit" })
+
+ expect(sent).toHaveLength(1)
+ expect(sent[0].type).toBe("session_shutdown")
+ })
+
+ // Pi's session events carry an AbortSignal and its message events carry live AgentMessage
+ // objects, so a payload that JSON.stringify would reject is the normal case, not the edge case.
+ test("serializes an event containing a cycle", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ const selfReferential: Record<string, unknown> = { name: "loop" }
+ selfReferential.self = selfReferential
+
+ await pi.fire({ type: "tool_result", toolName: "read", details: selfReferential }, context())
+
+ expect(sent).toHaveLength(1)
+ expect(JSON.stringify(sent[0])).toContain("tool_result")
+ })
+
+ test("drops functions and stringifies bigints rather than failing the send", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ await pi.fire(
+ {
+ type: "tool_result",
+ toolName: "bash",
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
+ onDone: () => {},
+ bytes: BigInt(42),
+ },
+ context(),
+ )
+
+ expect(sent[0].onDone).toBeUndefined()
+ expect(sent[0].bytes).toBe("42")
+ })
+
+ // Every handler must resolve to undefined. Pi reads a returned object as a request to change
+ // behavior -- `{ block: true }` on tool_call, `{ action: "transform" }` on input -- so a handler
+ // that returned anything would turn this observer into an enforcer.
+ test("handlers return nothing so Pi never reads a directive", async () => {
+ captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ for (const [, handler] of pi.handlers) {
+ const result = await handler({ type: "tool_call", toolName: "bash" }, context())
+ expect(result).toBeUndefined()
+ }
+ })
+
+ // Event fields win over the lifted identity fields on a key collision, so a value Pi reported
+ // is never overwritten by one Beacon derived.
+ test("event fields take precedence over lifted identity", async () => {
+ const sent = captureSends()
+ const pi = fakePi()
+ createBeaconExtension().register(pi.api)
+
+ await pi.fire({ type: "user_bash", command: "ls", cwd: "/other" }, context())
+
+ expect(sent[0].cwd).toBe("/other")
+ })
+})
diff --git a/plugins/pi-beacon/src/beacon.ts b/plugins/pi-beacon/src/beacon.ts
new file mode 100644
index 00000000..2a1d7cfc
--- /dev/null
+++ b/plugins/pi-beacon/src/beacon.ts
@@ -0,0 +1,270 @@
+// __BEACON_MANAGED_MARKER__
+// Beacon endpoint telemetry extension for Pi.
+// Managed by beacon endpoint hooks install --harness pi.
+
+// The argv Beacon's installer writes, as an array rather than a command line.
+//
+// An argv array is passed straight to the OS with no shell in between, which sidesteps quoting
+// entirely -- the same reason the Cline plugin uses one. Pi runs as a Bun-compiled binary or under
+// Node depending on how it was installed, and on Windows as readily as on macOS, so there is no one
+// shell whose quoting rules would hold.
+const beaconArgv: string[] = ["__BEACON_ARGV__"]
+
+const debugEnabled = process.env.BEACON_PI_DEBUG === "1"
+
+// A send that has not finished in this long is abandoned. Pi awaits event handlers before
+// continuing the agent loop, so this is the worst case Beacon can add to a tool call.
+const sendTimeoutMs = 2000
+
+// How deep into an event the serializer will walk before giving up.
+const maxDepth = 8
+
+// Pi's own event objects, narrowed to the fields Beacon reads.
+//
+// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose. The installed
+// file sits in ~/.pi/agent/extensions with no node_modules beside it, and Pi loads it through jiti,
+// which strips types without resolving them. A value import would fail at load; a type import would
+// resolve for nobody. Local structural types cost the compile-time link to Pi's definitions and buy
+// a file that loads wherever Pi does.
+type PiEvent = Record<string, unknown> & { type: string }
+
+interface PiSessionManager {
+ getSessionId?: () => string
+ getCwd?: () => string
+}
+
+interface PiContext {
+ cwd?: string
+ sessionManager?: PiSessionManager
+ model?: { id?: string; name?: string; provider?: string } | undefined
+ mode?: string
+}
+
+// The events Beacon subscribes to, and nothing else.
+//
+// Pi publishes roughly thirty event types, most of them provider-request and TUI-rendering
+// internals that describe no agent action. Subscribing to all of them would fill the runtime log
+// with rows no query asks for -- the same reason the Cline mapper drops unrecognized stages -- and
+// would put Beacon in the path of every streaming token update.
+//
+// `tool_call` and `tool_result` are the pair that carries tool activity: the first names the tool
+// and its arguments before it runs, the second carries the outcome. `user_bash` is a command the
+// human ran with Pi's `!` prefix, which no tool event covers.
+//
+// Deliberately absent: any approval event. Pi's `tool_call` handler can block a call, but that is
+// an extension deciding, not an operator being asked -- Pi exposes no operator approval decision
+// through this API. Synthesizing an approval from a pre-tool notification would put a decision
+// nobody made into the log, so Beacon records these as tool activity and leaves approval telemetry
+// empty for Pi, exactly as it does for Cline.
+const subscribedEvents = [
+ "session_start",
+ "session_shutdown",
+ "input",
+ "tool_call",
+ "tool_result",
+ "user_bash",
+ "message_end",
+] as const
+
+function debugLog(message: string, extra?: unknown) {
+ if (!debugEnabled) return
+ try {
+ // eslint-disable-next-line no-console
+ console.error("[beacon-pi]", message, extra ?? "")
+ } catch {
+ // Debug logging must stay best-effort.
+ }
+}
+
+// safeClone turns a Pi event into something JSON.stringify accepts.
+//
+// Pi's events carry live objects: an AbortSignal on the session events, AgentMessage arrays holding
+// class instances, and tool inputs that are mutable by design. JSON.stringify throws on a circular
+// reference and on a bigint, and silently flattens an Error to {}, so each is handled here rather
+// than losing the whole payload to one bad field.
+//
+// Cycles are tracked along the current path and released on the way out, so an object that legibly
+// appears twice -- the same file path referenced from two places in one edit -- is kept both times.
+// A WeakSet that never released would drop the second occurrence as if it were a cycle.
+function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {
+ if (value === null) return null
+ const kind = typeof value
+ if (kind === "function" || kind === "symbol" || kind === "undefined") return undefined
+ if (kind === "bigint") return String(value)
+ if (kind !== "object") return value
+ if (depth >= maxDepth) return undefined
+
+ const object = value as object
+ if (seen.has(object)) return undefined
+ if (value instanceof Error) return { name: value.name, message: value.message }
+ if (value instanceof Date) return value.toISOString()
+
+ seen.add(object)
+ try {
+ if (Array.isArray(value)) {
+ return value.map((item) => safeClone(item, depth + 1, seen))
+ }
+ const out: Record<string, unknown> = {}
+ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
+ const cloned = safeClone(nested, depth + 1, seen)
+ if (cloned !== undefined) out[key] = cloned
+ }
+ return out
+ } finally {
+ seen.delete(object)
+ }
+}
+
+async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
+ // Flattened before anything else sees it, so every consumer of this function is handed plain
+ // data rather than a live Pi event with cycles and functions still attached.
+ const safe = safeClone(payload)
+
+ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.pi.testSender")]
+ if (typeof testSender === "function") {
+ await (testSender as (value: unknown) => unknown)(safe)
+ return
+ }
+
+ let body: string
+ try {
+ body = JSON.stringify(safe)
+ } catch (err) {
+ debugLog("payload could not be serialized", err)
+ return
+ }
+ if (!body) return
+
+ try {
+ // Imported lazily so a host without node:child_process fails to send rather than failing to
+ // load: a throwing import at module scope would surface to the user as a broken extension, and
+ // Pi reports an extension that throws at load time rather than continuing without it.
+ const { spawn } = await import("node:child_process")
+ await new Promise<void>((resolve) => {
+ let settled = false
+ const finish = () => {
+ if (settled) return
+ settled = true
+ resolve()
+ }
+ let child
+ try {
+ child = spawn(beaconArgv[0], beaconArgv.slice(1), {
+ stdio: ["pipe", "ignore", "ignore"],
+ windowsHide: true,
+ })
+ } catch (err) {
+ debugLog("hook binary could not be spawned", err)
+ finish()
+ return
+ }
+ const timer = setTimeout(() => {
+ try {
+ child.kill()
+ } catch {
+ // Already gone.
+ }
+ debugLog("hook binary timed out", { type: payload?.type })
+ finish()
+ }, sendTimeoutMs)
+ // An unreferenced timer cannot keep Pi alive at exit waiting on Beacon telemetry.
+ if (typeof timer.unref === "function") timer.unref()
+ const done = () => {
+ clearTimeout(timer)
+ finish()
+ }
+ child.on("error", (err) => {
+ debugLog("hook binary failed", err)
+ done()
+ })
+ child.on("close", done)
+ // Without this, a hook binary that exits before reading stdin turns an EPIPE into an
+ // unhandled error event in the host process. Beacon telemetry must never do that.
+ child.stdin?.on("error", () => {})
+ try {
+ child.stdin?.end(body)
+ } catch (err) {
+ debugLog("payload could not be written", err)
+ }
+ })
+ } catch (err) {
+ debugLog("send failed", err)
+ // Beacon telemetry must never interrupt Pi execution.
+ }
+}
+
+// identity lifts the session and workspace fields Beacon needs to the top level of the envelope.
+//
+// Pi keeps them on the handler context rather than on the event, and behind accessor functions
+// rather than as properties, so they have to be read per event: a session id captured once at
+// extension load would be wrong after `/new`, a resume, or a fork, all of which replace the session
+// without reloading the extension.
+//
+// Each accessor is called defensively. `getSessionId` and `getCwd` are documented members of the
+// read-only session manager, but an extension that loses its session id loses the field that groups
+// every event of a run, so a throwing accessor costs that field rather than the event.
+function identity(ctx: PiContext | undefined): Record<string, unknown> {
+ const fields: Record<string, unknown> = {}
+ if (!ctx) return fields
+ const manager = ctx.sessionManager
+ try {
+ const sessionId = manager?.getSessionId?.()
+ if (sessionId) fields.sessionId = sessionId
+ } catch (err) {
+ debugLog("session id could not be read", err)
+ }
+ let cwd = ctx.cwd
+ if (!cwd) {
+ try {
+ cwd = manager?.getCwd?.()
+ } catch (err) {
+ debugLog("cwd could not be read", err)
+ }
+ }
+ if (cwd) fields.cwd = cwd
+ const model = ctx.model
+ if (model) {
+ // Pi's Model carries an id and a provider separately. Joined here so the envelope's `model` is
+ // one string, matching how every other Beacon collection path reports it.
+ const name = model.id || model.name
+ if (name) fields.model = model.provider ? `${model.provider}/${name}` : name
+ }
+ if (ctx.mode) fields.piMode = ctx.mode
+ return fields
+}
+
+type PiExtensionAPI = {
+ on: (event: string, handler: (event: PiEvent, ctx: PiContext) => Promise<void> | void) => void
+}
+
+// createBeaconExtension is exported for tests; Pi loads the default export below.
+export function createBeaconExtension() {
+ const forward = async (event: PiEvent, ctx: PiContext) => {
+ try {
+ await sendToBeacon({ ...identity(ctx), ...event })
+ } catch (err) {
+ // Unreachable in practice: sendToBeacon swallows its own failures. Kept because a handler
+ // that rejects is a handler that can break the run it was observing.
+ debugLog("handler failed", err)
+ }
+ }
+
+ return {
+ register(pi: PiExtensionAPI) {
+ for (const name of subscribedEvents) {
+ // Every handler returns undefined. Beacon observes; it never blocks a tool call, rewrites a
+ // prompt, transforms input, or replaces a message. Pi reads a returned object as a request
+ // to change behavior -- `{ block: true }` on tool_call, `{ action: "transform" }` on input
+ // -- so returning nothing is what keeps this extension an observer. Enforcement lives
+ // behind the policy provider seam in the hook adapter, not here.
+ pi.on(name, forward)
+ }
+ },
+ // Exposed so a test can assert the subscription list without a live Pi instance.
+ subscribedEvents: [...subscribedEvents],
+ }
+}
+
+export default function beaconExtension(pi: PiExtensionAPI) {
+ createBeaconExtension().register(pi)
+}