The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
feat(omp): add the managed Oh My Pi extension and its installer
Claudeb64073edf589
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e095e01f..2e1c004b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -168,6 +168,9 @@ jobs:- name: Check Pi extensionworking-directory: plugins/pi-beaconrun: bun run check && bun test+ - name: Check Oh My Pi extension+ working-directory: plugins/omp-beacon+ run: bun run check && bun test- name: Build embedded hooks binaryworking-directory: cli/beacon# hooks.bin is gitignored (build-time artifact). The CLI embeds it viadiff --git a/cli/beacon-hooks/cmd/pi_family_subscription_test.go b/cli/beacon-hooks/cmd/pi_family_subscription_test.gonew file mode 100644index 00000000..707bb578--- /dev/null+++ b/cli/beacon-hooks/cmd/pi_family_subscription_test.go@@ -0,0 +1,102 @@+package cmd++import (+ "os"+ "path/filepath"+ "regexp"+ "sort"+ "testing"+)++// The contract both sides have always claimed and neither has checked.+//+// A managed extension subscribes to a list of event types; the mapper here handles a list of event+// types. Both files carry a comment saying the two lists must agree, and until this test the+// agreement was maintained by hand. The failure mode is the quiet one: a name misspelled on either+// side produces no error anywhere -- the runtime dispatches nothing, the mapper is never called,+// and the only symptom is a category of agent activity silently missing from the log.+//+// Reading the extension source across the tree mirrors how the installer package already checks its+// embedded copy against plugins/. This is the one place both halves of the contract are visible at+// once, since the extension sources live outside this module.+func TestManagedExtensionSubscriptionsMatchTheirMappers(t *testing.T) {+ for _, tc := range []struct {+ runtime string+ source string+ supported []string+ }{+ {"pi", filepath.Join("..", "..", "..", "plugins", "pi-beacon", "src", "beacon.ts"), supportedPiEventTypes()},+ {"omp", filepath.Join("..", "..", "..", "plugins", "omp-beacon", "src", "beacon.ts"), supportedOmpEventTypes()},+ } {+ t.Run(tc.runtime, func(t *testing.T) {+ subscribed := subscribedEventTypes(t, tc.source)++ want := append([]string(nil), tc.supported...)+ sort.Strings(want)+ got := append([]string(nil), subscribed...)+ sort.Strings(got)++ if len(got) != len(want) {+ t.Fatalf("%s extension subscribes to %v but the mapper handles %v", tc.runtime, got, want)+ }+ for i := range got {+ if got[i] != want[i] {+ t.Fatalf("%s extension subscribes to %v but the mapper handles %v; a name on "++ "either side that the other does not have produces no telemetry and no error",+ tc.runtime, got, want)+ }+ }+ })+ }+}++// Every subscribed type must actually produce telemetry. A type both sides agree on but that the+// mapper's switch falls through on is the same silent gap wearing a matching pair of lists.+func TestEverySubscribedTypeIsMappedToAnEvent(t *testing.T) {+ fixtures := ompPayloads()+ for _, tc := range []struct {+ runtime piFamily+ source string+ }{+ {piRuntime, filepath.Join("..", "..", "..", "plugins", "pi-beacon", "src", "beacon.ts")},+ {ompRuntime, filepath.Join("..", "..", "..", "plugins", "omp-beacon", "src", "beacon.ts")},+ } {+ t.Run(tc.runtime.platform, func(t *testing.T) {+ for _, name := range subscribedEventTypes(t, tc.source) {+ payload, ok := fixtures[name]+ if !ok {+ t.Fatalf("no fixture for %q, which the %s extension subscribes to",+ name, tc.runtime.platform)+ }+ if events := tc.runtime.endpointEvents(cloneFields(payload), "sess-1"); len(events) == 0 {+ t.Fatalf("%s subscribes to %q but the mapper produces nothing for it",+ tc.runtime.platform, name)+ }+ }+ })+ }+}++// subscribedEventTypes reads the `subscribedEvents` array out of an extension source.+//+// Parsed from the shipped file rather than duplicated here, so this test cannot pass against a list+// that only exists in the test.+func subscribedEventTypes(t *testing.T, path string) []string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("extension source is unreadable: %v", err)+ }+ block := regexp.MustCompile(`(?s)const subscribedEvents = \[(.*?)\] as const`).FindSubmatch(data)+ if len(block) != 2 {+ t.Fatalf("%s has no subscribedEvents array; the mapper's contract is with that list", path)+ }+ var names []string+ for _, match := range regexp.MustCompile(`"([a-z_]+)"`).FindAllSubmatch(block[1], -1) {+ names = append(names, string(match[1]))+ }+ if len(names) == 0 {+ t.Fatalf("%s subscribes to no events", path)+ }+ return names+}diff --git a/cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/omp/beacon.tsnew file mode 100644index 00000000..4a2f3fad--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts@@ -0,0 +1,286 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry extension for Oh My Pi.+// Managed by beacon endpoint hooks install --harness omp.++// 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 and the Pi extension use one. Oh My Pi ships as a+// compiled binary on macOS, Linux and Windows alike, so there is no one shell whose quoting rules+// would hold.+const beaconArgv: string[] = ["__BEACON_ARGV__"]++const debugEnabled = process.env.BEACON_OMP_DEBUG === "1"++// A send that has not finished in this long is abandoned. Oh My Pi awaits extension handlers before+// continuing, 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++// Oh My Pi's own event objects, narrowed to the fields Beacon reads.+//+// Declared here rather than imported from @oh-my-pi/pi-coding-agent on purpose. The installed file+// sits in ~/.omp/agent/extensions with no node_modules beside it, and the loader imports it+// directly, stripping 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 Oh My Pi's+// definitions and buy a file that loads wherever Oh My Pi does.+type OmpEvent = Record<string, unknown> & { type: string }++interface OmpSessionManager {+ getSessionId?: () => string+ getCwd?: () => string+}++interface OmpContext {+ cwd?: string+ sessionManager?: OmpSessionManager+ model?: { id?: string; name?: string; provider?: string } | undefined+ mode?: string+}++// The events Beacon subscribes to, and nothing else.+//+// Oh My Pi publishes upwards of thirty event types. Most are provider-request internals, streaming+// message updates, compaction and retry signals, and TUI plumbing -- they describe how the runtime+// got its work done rather than what the agent did. Subscribing to all of them would fill the+// runtime log with rows no investigation asks for and would put Beacon in the path of every+// streaming token update.+//+// `tool_call` and `tool_result` are the pair carrying tool activity: the first names the tool and+// its arguments before it runs, the second carries the outcome. `user_bash` and `user_python` are+// code the operator ran with Oh My Pi's `!` and `$` prefixes, which no tool event covers.+//+// `tool_approval_requested` and `tool_approval_resolved` are the events upstream Pi does not have,+// and they are the reason this extension is not simply the Pi one pointed at a different directory.+// They report a decision an operator was actually asked to make. Beacon refuses to synthesize an+// approval from a tool call -- a `tool_call` handler that blocks is an extension deciding, not an+// operator being asked -- so a runtime that reports real ones is a genuine capability gain.+//+// Deliberately absent: `mcp_notification`, which fires for every JSON-RPC notification a connected+// server sends, most of them routine tools/resources list refreshes. It describes MCP transport+// plumbing rather than an action the agent took. The MCP activity worth recording is the agent+// calling an MCP tool, which already arrives as a tool_call/tool_result pair.+const subscribedEvents = [+ "session_start",+ "session_shutdown",+ "input",+ "tool_call",+ "tool_result",+ "tool_approval_requested",+ "tool_approval_resolved",+ "user_bash",+ "user_python",+ "message_end",+] as const++function debugLog(message: string, extra?: unknown) {+ if (!debugEnabled) return+ try {+ // eslint-disable-next-line no-console+ console.error("[beacon-omp]", message, extra ?? "")+ } catch {+ // Debug logging must stay best-effort.+ }+}++// safeClone turns an Oh My Pi event into something JSON.stringify accepts.+//+// The events carry live objects: AbortSignals 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 event with cycles and functions still attached.+ const safe = safeClone(payload)++ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.omp.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+ // Oh My 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 Oh My 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 Oh My Pi execution.+ }+}++// identity lifts the session and workspace fields Beacon needs to the top level of the envelope.+//+// Oh My 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, a fork, or a tree navigation, 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: OmpContext | 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) {+ // Oh My 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+ }+ // Which surface the session is running on: tui, rpc, json or print. A `print` or `rpc` run is+ // unattended, which changes how an approval row should be read -- there was no human at the+ // terminal to ask.+ if (ctx.mode) fields.ompMode = ctx.mode+ return fields+}++type OmpExtensionAPI = {+ on: (event: string, handler: (event: OmpEvent, ctx: OmpContext) => Promise<void> | void) => void+}++// createBeaconExtension is exported for tests; Oh My Pi loads the default export below.+export function createBeaconExtension() {+ const forward = async (event: OmpEvent, ctx: OmpContext) => {+ try {+ // The event is spread last so a field it carries itself wins over the context's. `user_bash`+ // and `user_python` both carry their own cwd, and the approval events carry their own+ // sessionId -- in each case the event's is the one that describes this action.+ 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: OmpExtensionAPI) {+ for (const name of subscribedEvents) {+ // Every handler returns undefined. Beacon observes; it never blocks a tool call, revises a+ // tool's arguments, rewrites a prompt, or replaces a message. Oh My Pi reads a returned+ // object as a request to change behavior -- `{ block: true }` or `{ input }` on tool_call,+ // `{ result }` on user_bash and user_python, `{ content }` on tool_result -- 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 Oh My Pi instance.+ subscribedEvents: [...subscribedEvents],+ }+}++export default function beaconExtension(pi: OmpExtensionAPI) {+ createBeaconExtension().register(pi)+}diff --git a/cli/beacon/internal/endpoint/hooks/assets/omp/embed.go b/cli/beacon/internal/endpoint/hooks/assets/omp/embed.gonew file mode 100644index 00000000..c1bce0e0--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/omp/embed.go@@ -0,0 +1,10 @@+package ompextension++import _ "embed"++// Template embeds the checked copy used by Beacon's Go installer.+// The root source of truth lives at plugins/omp-beacon/src/beacon.ts.+// Tests fail if this copy drifts.+//+//go:embed beacon.ts+var Template stringdiff --git a/cli/beacon/internal/endpoint/hooks/managed_extension.go b/cli/beacon/internal/endpoint/hooks/managed_extension.gonew file mode 100644index 00000000..f5c0c15a--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/managed_extension.go@@ -0,0 +1,166 @@+package hooks++import (+ "encoding/json"+ "fmt"+ "os"+ "strings"+)++// A managed extension is a single TypeScript file Beacon writes into a runtime's extension+// directory, which forwards that runtime's events to the `beacon-hooks` binary.+//+// Two runtimes are integrated this shape today, Pi and Oh My Pi, and both arrived at it for the+// same reason: neither has a hooks configuration file to merge into and neither exports+// OpenTelemetry, so the extension API is the only observation surface either offers. Everything+// about handling that file is identical between them -- render the argv into a template, refuse to+// overwrite a file Beacon did not write, remove only a file carrying Beacon's marker, and report+// installed only when the installed file can actually reach the binary. Only the four facts below+// differ.+//+// Sharing this matters more than it saves lines. The install/uninstall/status trio has to agree+// about the marker and the render, and the failure when it does not is silent: an install that+// reports success and collects nothing, or an uninstall that leaves a file behind and reports it+// gone. One implementation cannot disagree with itself.+type managedExtension struct {+ // platform is the `--platform` value written into the hook invocation. It decides which mapper+ // in beacon-hooks reads the payloads and which harness the events are attributed to.+ platform string+ // displayName is how the runtime is named in status and error messages.+ displayName string+ // marker identifies a file as one Beacon wrote. See the exported per-runtime constants for why+ // it is versioned.+ marker string+ // template is the extension source with its placeholders still in it.+ template string+ // configPath resolves the file Beacon manages for an install level.+ configPath func(Level) (string, error)+}++// argvPlaceholder is the literal each 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.+const argvPlaceholder = `["__BEACON_ARGV__"]`++// managedMarkerPlaceholder is where the runtime's marker is substituted in. Keeping the marker out+// of the checked-in source is what lets one test assert the shipped file and its embedded twin are+// byte-identical while each install still carries a versioned marker.+const managedMarkerPlaceholder = "__BEACON_MANAGED_MARKER__"++func (m managedExtension) runtime() hookRuntime {+ return hookRuntime{+ displayName: m.displayName,+ configPath: m.configPath,+ install: m.install,+ uninstall: m.remove,+ isInstalled: m.installedAt,+ }+}++// render 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 runtimes that ship as compiled binaries 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 (m managedExtension) render(binaryPath, logPath, configPath string) (string, error) {+ args := append(endpointCommandArgs(m.platform, binaryPath, logPath, configPath), m.platform+"-event")+ argv, err := json.Marshal(args)+ if err != nil {+ return "", err+ }+ source := strings.ReplaceAll(m.template, managedMarkerPlaceholder, m.marker)+ if !strings.Contains(source, argvPlaceholder) {+ return "", fmt.Errorf("%s extension template is missing the %s placeholder", m.platform, argvPlaceholder)+ }+ source = strings.ReplaceAll(source, argvPlaceholder, string(argv))+ if strings.Contains(source, "__BEACON_") {+ return "", fmt.Errorf("%s extension template contains unresolved Beacon placeholders", m.platform)+ }+ return source, nil+}++func (m managedExtension) install(path, binaryPath, logPath, configPath string) error {+ if existing, err := os.ReadFile(path); err == nil {+ if !strings.Contains(string(existing), m.marker) {+ return fmt.Errorf("refusing to overwrite unmanaged %s extension at %s", m.displayName, path)+ }+ } else if !os.IsNotExist(err) {+ return err+ }+ extension, err := m.render(binaryPath, logPath, configPath)+ if err != nil {+ return err+ }+ return os.WriteFile(path, []byte(extension), 0644)+}++func (m managedExtension) remove(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), m.marker) {+ return false, nil+ }+ return true, os.Remove(path)+}++func (m managedExtension) installedAt(path string) bool {+ data, err := os.ReadFile(path)+ if err != nil {+ return false+ }+ return strings.Contains(string(data), m.marker)+}++// reachableStatus downgrades an "installed" verdict that the file on disk does not support.+//+// 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 the runtime loads an extension that spawns+// nothing, and reporting that as installed tells an operator telemetry is being collected when none+// is.+func (m managedExtension) reachableStatus(status runtimeStatus) runtimeStatus {+ if !status.Installed || status.BinaryPath == "" {+ return status+ }+ if _, err := os.Stat(status.BinaryPath); err != nil {+ status.Installed = false+ status.Message = fmt.Sprintf("%s extension is installed, but Beacon hook binary is missing at %s",+ m.displayName, status.BinaryPath)+ return status+ }+ data, err := os.ReadFile(status.ConfigPath)+ if err != nil || !extensionReferencesBinary(string(data), status.BinaryPath) ||+ strings.Contains(string(data), "__BEACON_") {+ status.Installed = false+ status.Message = fmt.Sprintf("%s extension at %s does not reference the active Beacon hook binary",+ m.displayName, status.ConfigPath)+ }+ return status+}++// extensionReferencesBinary 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 extensionReferencesBinary(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]))+}diff --git a/cli/beacon/internal/endpoint/hooks/managed_extension_test.go b/cli/beacon/internal/endpoint/hooks/managed_extension_test.gonew file mode 100644index 00000000..a5353934--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/managed_extension_test.go@@ -0,0 +1,282 @@+package hooks++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// managedExtensions is every runtime integrated as a Beacon-managed extension file. Tests that+// assert a property of that shape rather than of one runtime walk this list, so a runtime added+// later inherits the same guarantees instead of quietly opting out of them.+func managedExtensions() []managedExtension {+ return []managedExtension{piExtension, ompExtension}+}++// testExtension builds a managedExtension over a caller-supplied template, so the render contract+// can be tested against a deliberately broken source without shipping one.+func testExtension(template string) managedExtension {+ return managedExtension{+ platform: "pi",+ displayName: "Pi",+ marker: "beacon-managed-test-extension:v1",+ template: template,+ configPath: PiExtensionPath,+ }+}++// The placeholder check is what turns a template rename into a loud failure instead of an install+// that reports success and spawns nothing.+func TestRenderRejectsATemplateMissingItsPlaceholder(t *testing.T) {+ ext := testExtension("// __BEACON_MANAGED_MARKER__\nconst x = 1\n")+ if _, err := ext.render("/tmp/beacon-hooks", "", ""); err == nil {+ t.Fatal("render accepted a template with no argv placeholder; an extension that spawns " ++ "nothing would have installed and reported success")+ }+}++func TestRenderRejectsUnresolvedPlaceholders(t *testing.T) {+ ext := testExtension("// __BEACON_MANAGED_MARKER__\nconst beaconArgv: string[] = [\"__BEACON_ARGV__\"]\n" ++ "const leftover = \"__BEACON_SOMETHING_ELSE__\"\n")+ if _, err := ext.render("/tmp/beacon-hooks", "", ""); err == nil {+ t.Fatal("render accepted a template with an unresolved placeholder")+ }+}++// Every shipped extension source must carry both placeholders. A source that lost one would fail+// only at install time, on a user's machine, with the runtime already configured to load it.+func TestShippedExtensionSourcesCarryTheirPlaceholders(t *testing.T) {+ for _, ext := range managedExtensions() {+ t.Run(ext.platform, func(t *testing.T) {+ if !strings.Contains(ext.template, argvPlaceholder) {+ t.Fatalf("%s extension source is missing %s", ext.platform, argvPlaceholder)+ }+ if !strings.Contains(ext.template, managedMarkerPlaceholder) {+ t.Fatalf("%s extension source is missing %s", ext.platform, managedMarkerPlaceholder)+ }+ })+ }+}++// A rendered extension must carry its own runtime's marker, its own `--platform`, and its own+// event subcommand. Getting any of the three wrong sends one runtime's payloads to the other's+// mapper, which would attribute Oh My Pi activity to Pi in every harness-grouped query.+func TestRenderedExtensionsCarryTheirOwnRuntimeIdentity(t *testing.T) {+ for _, ext := range managedExtensions() {+ t.Run(ext.platform, func(t *testing.T) {+ rendered, err := ext.render("/opt/beacon/bin/beacon-hooks", "/var/log/beacon/runtime.jsonl", "")+ if err != nil {+ t.Fatalf("render returned error: %v", err)+ }+ for _, want := range []string{+ ext.marker,+ `"--platform","` + ext.platform + `"`,+ `"` + ext.platform + `-event"`,+ } {+ if !strings.Contains(rendered, want) {+ t.Fatalf("%s rendered extension does not contain %q", ext.platform, want)+ }+ }+ for _, other := range managedExtensions() {+ if other.platform == ext.platform {+ continue+ }+ if strings.Contains(rendered, other.marker) {+ t.Fatalf("%s rendered extension carries %s's marker; an uninstall keyed on "++ "either marker would remove the wrong file", ext.platform, other.platform)+ }+ if strings.Contains(rendered, `"`+other.platform+`-event"`) {+ t.Fatalf("%s rendered extension invokes %s-event; one runtime's payloads would "++ "be attributed to the other", ext.platform, other.platform)+ }+ }+ })+ }+}++// Every runtime's marker must be unique. They are what install, uninstall, status, harness+// discovery and inventory all key on, and two runtimes sharing one means an uninstall of either+// removes the file of whichever it finds first.+func TestManagedExtensionMarkersAreDistinct(t *testing.T) {+ seen := map[string]string{}+ for _, ext := range managedExtensions() {+ if owner, ok := seen[ext.marker]; ok {+ t.Fatalf("%s and %s share the marker %q", owner, ext.platform, ext.marker)+ }+ seen[ext.marker] = ext.platform+ }+}++// Beacon must never overwrite a file it did not write. The extension filename is `beacon.ts` in a+// directory the user also owns, so somebody else's extension can legitimately sit at that path.+func TestInstallRefusesToOverwriteAnUnmanagedExtension(t *testing.T) {+ for _, ext := range managedExtensions() {+ t.Run(ext.platform, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ foreign := "// somebody else's extension\nexport default function () {}\n"+ if err := os.WriteFile(path, []byte(foreign), 0644); err != nil {+ t.Fatal(err)+ }++ if err := ext.install(path, "/opt/beacon/bin/beacon-hooks", "", ""); err == nil {+ t.Fatal("install overwrote an extension Beacon did not write")+ }++ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if string(data) != foreign {+ t.Fatalf("the unmanaged extension was modified: %q", string(data))+ }+ })+ }+}++// Uninstall removes only a file carrying this runtime's marker. A file at the same path without it+// belongs to someone else, and removing it would delete a user's own extension.+func TestRemoveLeavesAnUnmanagedExtensionAlone(t *testing.T) {+ for _, ext := range managedExtensions() {+ t.Run(ext.platform, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ if err := os.WriteFile(path, []byte("// not ours\n"), 0644); err != nil {+ t.Fatal(err)+ }++ removed, err := ext.remove(path)+ if err != nil {+ t.Fatalf("remove returned error: %v", err)+ }+ if removed {+ t.Fatal("remove reported it deleted an extension Beacon did not write")+ }+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("the unmanaged extension was deleted: %v", err)+ }+ })+ }+}++// One runtime's uninstall must not remove another's extension, even at the same path. This is what+// the distinct markers buy, asserted rather than assumed.+func TestRemoveIgnoresAnotherRuntimesExtension(t *testing.T) {+ for _, ext := range managedExtensions() {+ for _, other := range managedExtensions() {+ if other.platform == ext.platform {+ continue+ }+ t.Run(ext.platform+"/"+other.platform, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ rendered, err := other.render("/opt/beacon/bin/beacon-hooks", "", "")+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(rendered), 0644); err != nil {+ t.Fatal(err)+ }++ if removed, err := ext.remove(path); err != nil || removed {+ t.Fatalf("%s uninstall removed %s's extension (removed=%t, err=%v)",+ ext.platform, other.platform, removed, err)+ }+ if ext.installedAt(path) {+ t.Fatalf("%s reports itself installed over %s's extension",+ ext.platform, other.platform)+ }+ })+ }+ }+}++// Install then uninstall must leave nothing behind, for every runtime.+func TestInstallThenRemoveRoundTrips(t *testing.T) {+ for _, ext := range managedExtensions() {+ t.Run(ext.platform, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")++ if err := ext.install(path, "/opt/beacon/bin/beacon-hooks", "/var/log/beacon/runtime.jsonl", ""); err != nil {+ t.Fatalf("install returned error: %v", err)+ }+ if !ext.installedAt(path) {+ t.Fatal("installedAt does not recognize the file install just wrote")+ }++ removed, err := ext.remove(path)+ if err != nil || !removed {+ t.Fatalf("remove(removed=%t, err=%v)", removed, err)+ }+ if _, err := os.Stat(path); !os.IsNotExist(err) {+ t.Fatalf("the extension survived uninstall: %v", err)+ }+ })+ }+}++// Reinstalling over Beacon's own file is an upgrade, not a refusal.+func TestInstallOverwritesBeaconsOwnExtension(t *testing.T) {+ for _, ext := range managedExtensions() {+ t.Run(ext.platform, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")++ if err := ext.install(path, "/old/beacon-hooks", "", ""); err != nil {+ t.Fatalf("first install returned error: %v", err)+ }+ if err := ext.install(path, "/new/beacon-hooks", "", ""); err != nil {+ t.Fatalf("reinstall returned error: %v", err)+ }++ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if !extensionReferencesBinary(string(data), "/new/beacon-hooks") {+ t.Fatal("reinstall did not repoint the extension at the current hook binary")+ }+ if extensionReferencesBinary(string(data), "/old/beacon-hooks") {+ t.Fatal("the stale binary path survived reinstall")+ }+ })+ }+}++// A marker on disk is not enough to report telemetry as collected. An extension file survives a+// Beacon uninstall, a partial update, or a home directory restored onto a machine where the binary+// lives elsewhere; in each case the runtime loads an extension that spawns nothing.+func TestReachableStatusDowngradesAnUnreachableInstall(t *testing.T) {+ for _, ext := range managedExtensions() {+ t.Run(ext.platform, func(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "beacon.ts")+ binary := filepath.Join(dir, "beacon-hooks")++ if err := ext.install(path, binary, "", ""); err != nil {+ t.Fatal(err)+ }++ // The binary the extension names is not on disk.+ status := ext.reachableStatus(runtimeStatus{Installed: true, BinaryPath: binary, ConfigPath: path})+ if status.Installed {+ t.Fatal("reported installed while the hook binary it spawns is missing")+ }++ if err := os.WriteFile(binary, []byte("#!/bin/sh\n"), 0755); err != nil {+ t.Fatal(err)+ }+ status = ext.reachableStatus(runtimeStatus{Installed: true, BinaryPath: binary, ConfigPath: path})+ if !status.Installed {+ t.Fatalf("reported not installed for a reachable install: %s", status.Message)+ }++ // An extension pointing at some other binary is not this install.+ other := filepath.Join(dir, "other-hooks")+ if err := os.WriteFile(other, []byte("#!/bin/sh\n"), 0755); err != nil {+ t.Fatal(err)+ }+ status = ext.reachableStatus(runtimeStatus{Installed: true, BinaryPath: other, ConfigPath: path})+ if status.Installed {+ t.Fatal("reported installed for an extension that spawns a different binary")+ }+ })+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/omp.go b/cli/beacon/internal/endpoint/hooks/omp.gonew file mode 100644index 00000000..29de9dbe--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/omp.go@@ -0,0 +1,165 @@+package hooks++import (+ "fmt"+ "os"+ "path/filepath"++ ompextension "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks/assets/omp"+)++// Oh My Pi (`omp`) is integrated the same shape as Pi, which it forked: no hooks configuration file+// to merge into and no OpenTelemetry export, so the TypeScript extension API is the only+// observation surface. Beacon writes one extension file that forwards runtime events to the+// `beacon-hooks` binary, and managedExtension handles it exactly as it handles Pi's.+//+// The extension file itself is a separate source from Pi's rather than the same file installed+// twice. Oh My Pi exposes operator approval decisions and an operator Python surface that Pi does+// not, so the subscription lists genuinely differ, and each file carries its own marker so an+// install of one is never mistaken for an install of the other.+const (+ ompExtensionFileName = "beacon.ts"++ // OmpManagedExtensionMarker identifies an extension file as one Beacon wrote for Oh My Pi.+ //+ // Distinct from PiManagedExtensionMarker on purpose. The two runtimes install to different+ // directories today, but a shared marker would mean a status or repair pass could not tell+ // which runtime's extension it had found if either ever moved -- and an uninstall keyed on the+ // wrong marker removes the wrong file. Exported for the same three-package reason Pi's is.+ //+ // The version suffix is part of the contract with the extension source. Bump it 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.+ OmpManagedExtensionMarker = "beacon-managed-omp-extension:v1"++ // ompConfigDirName is the config directory Oh My Pi keeps under the home directory.+ ompConfigDirName = ".omp"++ // ompAgentDirEnv overrides the agent directory outright. Oh My Pi reads it itself, and sets it+ // on its own process when a named profile is active, so an install performed from inside a+ // profiled session lands in that profile's extension directory rather than the default one.+ ompAgentDirEnv = "PI_CODING_AGENT_DIR"++ // ompConfigDirEnv renames the config directory under the home directory. Oh My Pi applies it+ // only to that home-directory root, never to the project directory -- see ompExtensionDir.+ ompConfigDirEnv = "PI_CONFIG_DIR"+)++type OmpOptions struct {+ Level Level+ LogPath string+ UserMode bool+}++type OmpStatus struct {+ Installed bool `json:"installed"`+ BinaryPath string `json:"binary_path,omitempty"`+ ExtensionPath string `json:"extension_path,omitempty"`+ Message string `json:"message,omitempty"`+}++var ompExtension = managedExtension{+ platform: "omp",+ displayName: "Oh My Pi",+ marker: OmpManagedExtensionMarker,+ template: ompextension.Template,+ configPath: OmpExtensionPath,+}++var ompRuntime = ompExtension.runtime()++func InstallOmp(opts OmpOptions) (OmpStatus, error) {+ status, err := installRuntimeHooks(ompRuntime, RuntimeOptions(opts))+ if err != nil {+ return OmpStatus{}, err+ }+ return ompStatusFromRuntime(status), nil+}++func UninstallOmp(opts OmpOptions) (OmpStatus, error) {+ status, err := uninstallRuntimeHooks(ompRuntime, RuntimeOptions(opts))+ if err != nil {+ return OmpStatus{}, err+ }+ return ompStatusFromRuntime(status), nil+}++func OmpHookStatus(opts OmpOptions) OmpStatus {+ return ompStatusFromRuntime(runtimeHookStatus(ompRuntime, RuntimeOptions(opts)))+}++func IsOmpInstalled(opts OmpOptions) bool {+ return isRuntimeInstalled(ompRuntime, RuntimeOptions(opts))+}++// ompStatusFromRuntime reports installed only when the extension can actually reach the hook binary.+func ompStatusFromRuntime(status runtimeStatus) OmpStatus {+ status = ompExtension.reachableStatus(status)+ return OmpStatus{+ Installed: status.Installed,+ BinaryPath: status.BinaryPath,+ ExtensionPath: status.ConfigPath,+ Message: status.Message,+ }+}++func ompEmbeddedExtensionSourcePath() string {+ return filepath.Clean(filepath.Join("assets", "omp", "beacon.ts"))+}++func ompRootExtensionSourcePath() string {+ return filepath.Clean(filepath.Join("..", "..", "..", "..", "..", "plugins", "omp-beacon", "src", "beacon.ts"))+}++// OmpExtensionPath returns the extension file Beacon manages for a given install level.+//+// Oh My Pi auto-discovers extension modules from two directories, and unlike Pi neither is behind a+// trust prompt: `isProjectTrusted()` in its extension API always returns true, because `.omp`+// project-local inputs are already loaded unconditionally. A user-level install is still the+// default, because it follows the operator rather than one checkout.+func OmpExtensionPath(level Level) (string, error) {+ dir, err := ompExtensionDir(level)+ if err != nil {+ return "", err+ }+ return filepath.Join(dir, ompExtensionFileName), nil+}++// ompExtensionDir resolves the directory Oh My Pi actually scans for extension modules.+//+// The two levels resolve asymmetrically, and the asymmetry is Oh My Pi's rather than a+// simplification here. Its user root is the *agent* directory -- `~/.omp/agent` -- which+// `PI_CODING_AGENT_DIR` replaces outright and `PI_CONFIG_DIR` renames the `.omp` half of; a named+// profile moves it to `~/.omp/profiles/<name>/agent`, which the runtime signals by setting+// `PI_CODING_AGENT_DIR` on its own process, so a profiled install is reached through that variable+// rather than by Beacon guessing a profile name. Its project root is the plain `.omp` directory in+// the working directory, with no `agent` segment and no environment override at all: the runtime+// joins the literal there.+//+// Deriving either path from the other, or applying `PI_CONFIG_DIR` to both, would write the file+// where Oh My Pi does not look -- and the install would report success and collect nothing.+func ompExtensionDir(level Level) (string, error) {+ switch level {+ case "", LevelUser:+ if agentDir := os.Getenv(ompAgentDirEnv); agentDir != "" {+ return filepath.Join(agentDir, "extensions"), nil+ }+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ configDir := ompConfigDirName+ if named := os.Getenv(ompConfigDirEnv); named != "" {+ configDir = named+ }+ return filepath.Join(home, configDir, "agent", "extensions"), nil+ case LevelProject:+ cwd, err := os.Getwd()+ if err != nil {+ return "", err+ }+ return filepath.Join(cwd, ompConfigDirName, "extensions"), nil+ default:+ return "", fmt.Errorf("unknown hook level %q", level)+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/omp_test.go b/cli/beacon/internal/endpoint/hooks/omp_test.gonew file mode 100644index 00000000..b8e9ca70--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/omp_test.go@@ -0,0 +1,262 @@+package hooks++import (+ "encoding/json"+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++// An empty level means "the default", and the default has to be the user level. Every caller that+// does not care about scope passes the zero value, so treating "" as unknown would turn status,+// repair and uninstall into errors for the ordinary install.+func TestOmpExtensionPathDefaultsToUserLevel(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv(ompAgentDirEnv, "")+ t.Setenv(ompConfigDirEnv, "")++ want := filepath.Join(home, ".omp", "agent", "extensions", "beacon.ts")+ for _, level := range []Level{"", LevelUser} {+ got, err := OmpExtensionPath(level)+ if err != nil {+ t.Fatalf("OmpExtensionPath(%q) returned error: %v", level, err)+ }+ if got != want {+ t.Fatalf("OmpExtensionPath(%q) = %q, want %q", level, got, want)+ }+ }+}++// Oh My Pi's project extension directory is `.omp/extensions`, not `.omp/agent/extensions`: the+// `agent` segment exists only under the home directory. Deriving one path from the other would+// write the project extension where the runtime does not look for it, so the install would report+// success and collect nothing.+func TestOmpExtensionPathProjectLevelOmitsAgentSegment(t *testing.T) {+ cwd := t.TempDir()+ t.Chdir(cwd)++ got, err := OmpExtensionPath(LevelProject)+ if err != nil {+ t.Fatalf("OmpExtensionPath(project) returned error: %v", err)+ }+ want := filepath.Join(cwd, ".omp", "extensions", "beacon.ts")+ if got != want {+ t.Fatalf("OmpExtensionPath(project) = %q, want %q", got, want)+ }+}++// PI_CODING_AGENT_DIR replaces the agent directory outright. Oh My Pi reads it itself, and sets it+// on its own process when a named profile is active -- so honoring it is how a profiled install+// lands in `~/.omp/profiles/<name>/agent/extensions` without Beacon having to guess a profile name.+func TestOmpExtensionPathHonorsTheAgentDirOverride(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ agentDir := filepath.Join(home, ".omp", "profiles", "work", "agent")+ t.Setenv(ompAgentDirEnv, agentDir)+ t.Setenv(ompConfigDirEnv, "")++ got, err := OmpExtensionPath(LevelUser)+ if err != nil {+ t.Fatalf("OmpExtensionPath returned error: %v", err)+ }+ want := filepath.Join(agentDir, "extensions", "beacon.ts")+ if got != want {+ t.Fatalf("OmpExtensionPath = %q, want %q -- an install that ignores the override writes "++ "where the runtime does not look", got, want)+ }+}++// PI_CONFIG_DIR renames the `.omp` directory under the home directory only. Applying it to the+// project path too would be a plausible-looking mistake: the runtime joins the literal `.omp` there+// (getProjectAgentDir uses the constant, not the env-aware lookup), so an install that renamed both+// would miss the project directory entirely.+func TestOmpExtensionPathAppliesTheConfigDirOverrideToTheUserPathOnly(t *testing.T) {+ home := t.TempDir()+ cwd := t.TempDir()+ testenv.SetHome(t, home)+ t.Chdir(cwd)+ t.Setenv(ompAgentDirEnv, "")+ t.Setenv(ompConfigDirEnv, ".omp-alt")++ user, err := OmpExtensionPath(LevelUser)+ if err != nil {+ t.Fatalf("OmpExtensionPath(user) returned error: %v", err)+ }+ if want := filepath.Join(home, ".omp-alt", "agent", "extensions", "beacon.ts"); user != want {+ t.Fatalf("OmpExtensionPath(user) = %q, want %q", user, want)+ }++ project, err := OmpExtensionPath(LevelProject)+ if err != nil {+ t.Fatalf("OmpExtensionPath(project) returned error: %v", err)+ }+ if want := filepath.Join(cwd, ".omp", "extensions", "beacon.ts"); project != want {+ t.Fatalf("OmpExtensionPath(project) = %q, want %q -- PI_CONFIG_DIR does not rename the "++ "project directory", project, want)+ }+}++// The agent-dir override wins over the config-dir rename, because it replaces the whole path rather+// than one segment of it. Oh My Pi resolves them in that order too.+func TestOmpAgentDirOverrideBeatsTheConfigDirRename(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ agentDir := filepath.Join(home, "elsewhere", "agent")+ t.Setenv(ompAgentDirEnv, agentDir)+ t.Setenv(ompConfigDirEnv, ".omp-alt")++ got, err := OmpExtensionPath(LevelUser)+ if err != nil {+ t.Fatalf("OmpExtensionPath returned error: %v", err)+ }+ if want := filepath.Join(agentDir, "extensions", "beacon.ts"); got != want {+ t.Fatalf("OmpExtensionPath = %q, want %q", got, want)+ }+}++func TestOmpExtensionPathRejectsUnknownLevel(t *testing.T) {+ if _, err := OmpExtensionPath(Level("machine")); err == nil {+ t.Fatal("OmpExtensionPath accepted an unknown level; a typo in a scope flag must fail loudly " ++ "rather than silently installing at the default scope")+ }+}++// Oh My Pi must never install into Pi's directory or vice versa. They are separate products that a+// fleet can run side by side, and one writing into the other's extension directory would attribute+// a whole runtime's activity to the wrong harness.+func TestOmpAndPiInstallToDifferentDirectories(t *testing.T) {+ home := t.TempDir()+ cwd := t.TempDir()+ testenv.SetHome(t, home)+ t.Chdir(cwd)+ t.Setenv(ompAgentDirEnv, "")+ t.Setenv(ompConfigDirEnv, "")++ for _, level := range []Level{LevelUser, LevelProject} {+ omp, err := OmpExtensionPath(level)+ if err != nil {+ t.Fatal(err)+ }+ pi, err := PiExtensionPath(level)+ if err != nil {+ t.Fatal(err)+ }+ if omp == pi {+ t.Fatalf("Oh My Pi and Pi resolve to the same %s extension path %q", level, omp)+ }+ }+}++// The marker is the only thing that distinguishes a file Beacon may overwrite from one it must+// not, and it is read by three packages. Pinning the literal here means a change to it is a+// deliberate edit to a test rather than a silent break of install/uninstall/status agreement.+func TestOmpManagedExtensionMarkerIsStable(t *testing.T) {+ if OmpManagedExtensionMarker != "beacon-managed-omp-extension:v1" {+ t.Fatalf("OmpManagedExtensionMarker = %q; changing it strands extensions installed by "++ "earlier builds, which uninstall then refuses to remove", OmpManagedExtensionMarker)+ }+}++// ompRenderedArgv 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+// template, and a test that compared text would pass on a file the runtime cannot execute.+func ompRenderedArgv(t *testing.T, source string) []string {+ t.Helper()+ matches := regexp.MustCompile(`const beaconArgv: string\[\] = (\[.*\])`).FindStringSubmatch(source)+ if len(matches) != 2 {+ t.Fatalf("rendered extension has no beaconArgv array:\n%s", source)+ }+ var argv []string+ if err := json.Unmarshal([]byte(matches[1]), &argv); err != nil {+ t.Fatalf("beaconArgv is not a JSON array: %v", err)+ }+ return argv+}++func TestInstallOmpExtensionWritesAnExecutableInvocation(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ binary := "/opt/beacon/bin/beacon-hooks"+ logPath := "/var/log/beacon-agent/runtime.jsonl"++ if err := ompExtension.install(path, binary, logPath, "/etc/beacon/endpoint.yaml"); err != nil {+ t.Fatalf("install returned error: %v", err)+ }++ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ source := string(data)+ if !strings.Contains(source, OmpManagedExtensionMarker) {+ t.Fatal("the installed extension carries no Beacon marker; uninstall would refuse to remove it")+ }++ argv := ompRenderedArgv(t, source)+ if argv[0] != binary {+ t.Fatalf("argv[0] = %q, want the hook binary %q", argv[0], binary)+ }+ if argv[len(argv)-1] != "omp-event" {+ t.Fatalf("argv ends with %q, want omp-event -- any other subcommand sends Oh My Pi's "++ "payloads to a mapper that does not understand them", argv[len(argv)-1])+ }+ joined := strings.Join(argv, " ")+ for _, want := range []string{"--platform omp", "--log " + logPath, "--config /etc/beacon/endpoint.yaml"} {+ if !strings.Contains(joined, want) {+ t.Fatalf("argv %v is missing %q", argv, want)+ }+ }+}++// A Windows path is the case that makes argv worth encoding as JSON rather than as a command line.+func TestRenderOmpExtensionEncodesWindowsPaths(t *testing.T) {+ source, err := ompExtension.render(`C:\Program Files\beacon\beacon-hooks.exe`, `C:\ProgramData\beacon\runtime.jsonl`, "")+ if err != nil {+ t.Fatalf("render returned error: %v", err)+ }+ argv := ompRenderedArgv(t, source)+ if argv[0] != `C:\Program Files\beacon\beacon-hooks.exe` {+ t.Fatalf("argv[0] = %q; the Windows path did not survive rendering", argv[0])+ }+}++// The checked-in extension and the copy embedded in the binary must be byte-identical. They drift+// the moment somebody edits one and forgets `bun run sync`, and the drift is invisible until an+// install ships behavior nobody reviewed.+func TestOmpEmbeddedExtensionMatchesRootSource(t *testing.T) {+ embedded, err := os.ReadFile(ompEmbeddedExtensionSourcePath())+ if err != nil {+ t.Fatalf("embedded extension source is unreadable: %v", err)+ }+ root, err := os.ReadFile(ompRootExtensionSourcePath())+ if err != nil {+ t.Fatalf("root extension source is unreadable: %v", err)+ }+ if string(embedded) != string(root) {+ t.Fatal("plugins/omp-beacon/src/beacon.ts and its embedded copy have drifted; " ++ "run `bun run sync` in plugins/omp-beacon")+ }+}++// The subscription list is the contract between the extension and the omp-event mapper. It is+// asserted here against the shipped source rather than trusted, because a typo on either side+// produces no telemetry rather than an error.+func TestOmpExtensionSubscribesToTheApprovalEvents(t *testing.T) {+ for _, want := range []string{"tool_approval_requested", "tool_approval_resolved", "user_python"} {+ if !strings.Contains(ompExtension.template, `"`+want+`"`) {+ t.Fatalf("the Oh My Pi extension does not subscribe to %q; it is the capability that "++ "distinguishes this runtime from Pi", want)+ }+ }+ // mcp_notification is deliberately not subscribed to: it is MCP transport plumbing rather than+ // an action the agent took, and it fires for every routine list refresh.+ if strings.Contains(ompExtension.template, `"mcp_notification"`) {+ t.Fatal("the Oh My Pi extension subscribes to mcp_notification; it reports transport " ++ "plumbing rather than agent activity")+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/pi.go b/cli/beacon/internal/endpoint/hooks/pi.goindex 6a83346c..683c5392 100644--- a/cli/beacon/internal/endpoint/hooks/pi.go+++ b/cli/beacon/internal/endpoint/hooks/pi.go@@ -1,11 +1,9 @@package hooksimport (- "encoding/json""fmt""os""path/filepath"- "strings"piextension "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks/assets/pi")@@ -14,7 +12,7 @@ import (// two established integration shapes applies to it. Its only observation surface is the TypeScript// extension API, which makes the integration plugin-shaped: Beacon writes one extension file that// forwards runtime events to the `beacon-hooks` binary. That is the same shape as the opencode-// plugin, and the pieces below are the facts about that file which more than one package needs.+// plugin, and the handling of that file lives in managedExtension, shared with Oh My Pi.const (piExtensionFileName = "beacon.ts"@@ -31,16 +29,8 @@ 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 LevelLogPath string@@ -54,14 +44,16 @@ type PiStatus struct {Message string `json:"message,omitempty"`}-var piRuntime = hookRuntime{+var piExtension = managedExtension{+ platform: "pi",displayName: "Pi",+ marker: PiManagedExtensionMarker,+ template: piextension.Template,configPath: PiExtensionPath,- install: installPiExtension,- uninstall: removePiExtension,- isInstalled: isPiInstalledAt,}+var piRuntime = piExtension.runtime()+func InstallPi(opts PiOptions) (PiStatus, error) {status, err := installRuntimeHooks(piRuntime, RuntimeOptions(opts))if err != nil {@@ -87,115 +79,14 @@ func IsPiInstalled(opts PiOptions) bool {}// 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{+ status = piExtension.reachableStatus(status)+ return 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 {diff --git a/cli/beacon/internal/endpoint/hooks/pi_test.go b/cli/beacon/internal/endpoint/hooks/pi_test.goindex 51157c8d..dd998bdc 100644--- a/cli/beacon/internal/endpoint/hooks/pi_test.go+++ b/cli/beacon/internal/endpoint/hooks/pi_test.go@@ -86,7 +86,7 @@ func piRenderedArgv(t *testing.T, source string) []string {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 {+ if err := piExtension.install(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {t.Fatalf("installPiExtension returned error: %v", err)}data, err := os.ReadFile(path)@@ -118,9 +118,9 @@ func TestInstallPiExtensionWritesManagedExtension(t *testing.T) {// 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`, "")+ source, err := piExtension.render(`C:\Program Files\beacon\beacon-hooks.exe`, `C:\ProgramData\beacon\runtime.jsonl`, "")if err != nil {- t.Fatalf("renderPiExtension returned error: %v", err)+ t.Fatalf("piExtension.render returned error: %v", err)}argv := piRenderedArgv(t, source)if argv[0] != `C:\Program Files\beacon\beacon-hooks.exe` {@@ -135,7 +135,7 @@ func TestInstallPiExtensionRefusesToOverwriteUnmanagedExtension(t *testing.T) {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 {+ if err := piExtension.install(path, "/tmp/beacon-hooks", "/tmp/runtime.jsonl", ""); err == nil {t.Fatal("installPiExtension overwrote an unmanaged extension")}data, _ := os.ReadFile(path)@@ -148,24 +148,24 @@ 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 {+ if err := piExtension.install(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)+ removed, err := piExtension.remove(managed)if err != nil || !removed {- t.Fatalf("removePiExtension(managed) = %v, %v; want true, nil", removed, err)+ t.Fatalf("piExtension.remove(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)+ removed, err = piExtension.remove(unmanaged)if err != nil {- t.Fatalf("removePiExtension(unmanaged) returned error: %v", err)+ t.Fatalf("piExtension.remove(unmanaged) returned error: %v", err)}if removed {t.Fatal("removePiExtension removed an extension Beacon does not manage")@@ -176,7 +176,7 @@ func TestRemovePiExtensionOnlyRemovesManagedExtension(t *testing.T) {}func TestRemovePiExtensionIsQuietWhenNothingIsInstalled(t *testing.T) {- removed, err := removePiExtension(filepath.Join(t.TempDir(), "absent.ts"))+ removed, err := piExtension.remove(filepath.Join(t.TempDir(), "absent.ts"))if err != nil {t.Fatalf("removePiExtension on a missing file returned error: %v", err)}@@ -185,21 +185,6 @@ func TestRemovePiExtensionIsQuietWhenNothingIsInstalled(t *testing.T) {}}-// 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 {@@ -221,7 +206,7 @@ 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 {+ if err := piExtension.install(path, missing, "/tmp/runtime.jsonl", ""); err != nil {t.Fatalf("installPiExtension returned error: %v", err)}status := piStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: missing, ConfigPath: path})@@ -243,7 +228,7 @@ func TestPiStatusRejectsAnExtensionPointingElsewhere(t *testing.T) {t.Fatalf("seed binary: %v", err)}}- if err := installPiExtension(path, stale, "/tmp/runtime.jsonl", ""); err != nil {+ if err := piExtension.install(path, stale, "/tmp/runtime.jsonl", ""); err != nil {t.Fatalf("installPiExtension returned error: %v", err)}status := piStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: current, ConfigPath: path})@@ -259,7 +244,7 @@ func TestPiStatusAcceptsAHealthyInstall(t *testing.T) {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 {+ if err := piExtension.install(path, binary, "/tmp/runtime.jsonl", ""); err != nil {t.Fatalf("installPiExtension returned error: %v", err)}status := piStatusFromRuntime(runtimeStatus{Installed: true, BinaryPath: binary, ConfigPath: path})@@ -275,36 +260,36 @@ 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 {+ if err := piExtension.install(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) {+ if !piExtension.installedAt(managed) {t.Fatal("isPiInstalledAt did not recognize Beacon's own extension")}- if isPiInstalledAt(unmanaged) {+ if piExtension.installedAt(unmanaged) {t.Fatal("isPiInstalledAt claimed an unmanaged extension as Beacon's")}- if isPiInstalledAt(filepath.Join(dir, "absent.ts")) {+ if piExtension.installedAt(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`, "")+ source, err := piExtension.render(binary, `C:\ProgramData\beacon\runtime.jsonl`, "")if err != nil {- t.Fatalf("renderPiExtension returned error: %v", err)+ t.Fatalf("piExtension.render returned error: %v", err)}- if !piExtensionReferencesBinary(source, binary) {+ if !extensionReferencesBinary(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`) {+ if extensionReferencesBinary(source, `C:\Other\beacon-hooks.exe`) {t.Fatal("piExtensionReferencesBinary matched a binary the extension does not spawn")}- if piExtensionReferencesBinary(source, "") {+ if extensionReferencesBinary(source, "") {t.Fatal("piExtensionReferencesBinary matched an empty binary path")}}diff --git a/plugins/omp-beacon/package.json b/plugins/omp-beacon/package.jsonnew file mode 100644index 00000000..718a6994--- /dev/null+++ b/plugins/omp-beacon/package.json@@ -0,0 +1,21 @@+{+ "name": "@asymptote-labs/omp-beacon",+ "version": "0.0.0",+ "private": true,+ "description": "Beacon endpoint telemetry extension for Oh My Pi",+ "type": "module",+ "scripts": {+ "check": "bun --check src/beacon.ts && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts",+ "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts",+ "test": "bun test src/beacon.test.ts"+ },+ "exports": {+ ".": "./src/beacon.ts"+ },+ "files": [+ "src/"+ ],+ "peerDependencies": {+ "@oh-my-pi/pi-coding-agent": "*"+ }+}diff --git a/plugins/omp-beacon/src/beacon.test.ts b/plugins/omp-beacon/src/beacon.test.tsnew file mode 100644index 00000000..7dbd302a--- /dev/null+++ b/plugins/omp-beacon/src/beacon.test.ts@@ -0,0 +1,320 @@+import { afterEach, describe, expect, test } from "bun:test"++import { createBeaconExtension } from "./beacon"++const senderKey = Symbol.for("beacon.omp.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 Oh My Pi's ExtensionAPI that records subscriptions and lets a test fire one.+function fakeOmp() {+ 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",+ mode: "tui",+ sessionManager: { getSessionId: () => "sess-1", getCwd: () => "/repo" },+ ...overrides,+ }+}++afterEach(() => {+ delete (globalThis as Record<symbol, unknown>)[senderKey]+})++describe("beacon oh my pi extension", () => {+ // These strings are the contract between this extension and the omp-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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ expect([...omp.handlers.keys()].sort()).toEqual([+ "input",+ "message_end",+ "session_shutdown",+ "session_start",+ "tool_approval_requested",+ "tool_approval_resolved",+ "tool_call",+ "tool_result",+ "user_bash",+ "user_python",+ ])+ })++ // The reason this extension exists rather than pointing the Pi one at a different directory.+ // These are decisions an operator was actually asked to make, which Beacon refuses to synthesize+ // on runtimes that do not report them.+ test("subscribes to the approval events upstream Pi does not have", () => {+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ expect(omp.handlers.has("tool_approval_requested")).toBe(true)+ expect(omp.handlers.has("tool_approval_resolved")).toBe(true)+ })++ // Oh My Pi publishes upwards of thirty events, 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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ for (const noisy of [+ "message_update",+ "message_start",+ "before_provider_request",+ "after_provider_response",+ "context",+ "tool_execution_update",+ "tool_execution_start",+ "auto_compaction_start",+ "auto_retry_start",+ "ttsr_triggered",+ "todo_reminder",+ ]) {+ expect(omp.handlers.has(noisy)).toBe(false)+ }+ })++ // mcp_notification fires for every JSON-RPC notification a connected server sends, most of them+ // routine list refreshes. It is MCP transport plumbing, not an action the agent took.+ test("does not subscribe to mcp notifications", () => {+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ expect(omp.handlers.has("mcp_notification")).toBe(false)+ })++ test("forwards the event with its type intact", async () => {+ const sent = captureSends()+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.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")+ })++ test("forwards an approval decision with its outcome intact", async () => {+ const sent = captureSends()+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.fire(+ {+ type: "tool_approval_resolved",+ sessionId: "sess-1",+ toolCallId: "call-1",+ toolName: "bash",+ approved: false,+ reason: "operator declined",+ },+ context(),+ )++ expect(sent[0].approved).toBe(false)+ expect(sent[0].toolCallId).toBe("call-1")+ expect(sent[0].reason).toBe("operator declined")+ })++ test("forwards operator python with its source intact", async () => {+ const sent = captureSends()+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.fire(+ { type: "user_python", code: "import os", excludeFromContext: true, cwd: "/repo" },+ context(),+ )++ expect(sent[0].code).toBe("import os")+ expect(sent[0].excludeFromContext).toBe(true)+ })++ // Oh My 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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.fire({ type: "session_start" }, context())++ expect(sent[0].sessionId).toBe("sess-1")+ expect(sent[0].cwd).toBe("/repo")+ })++ // A print or rpc run is unattended, which changes how an approval row should be read: there was+ // no human at the terminal to ask.+ test("records which surface the session is running on", async () => {+ const sent = captureSends()+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.fire({ type: "session_start" }, context({ mode: "print" }))++ expect(sent[0].ompMode).toBe("print")+ })++ // Re-read per event rather than captured at load: `/new`, a resume, a fork and a tree navigation+ // 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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ let current = "sess-first"+ const ctx = context({ sessionManager: { getSessionId: () => current, getCwd: () => "/repo" } })++ await omp.fire({ type: "session_start" }, ctx)+ current = "sess-second"+ await omp.fire({ type: "session_start" }, 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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.fire({ type: "session_shutdown" })++ expect(sent).toHaveLength(1)+ expect(sent[0].type).toBe("session_shutdown")+ })++ // Oh My Pi's session events carry an AbortSignal and its message events carry live AgentMessage+ // objects, so a payload JSON.stringify would reject is the normal case, not the edge case.+ test("serializes an event containing a cycle", async () => {+ const sent = captureSends()+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ const selfReferential: Record<string, unknown> = { name: "loop" }+ selfReferential.self = selfReferential++ await omp.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 omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.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. Oh My Pi reads a returned object as a request to+ // change behavior -- `{ block: true }` or `{ input }` on tool_call, `{ result }` on user_bash and+ // user_python, `{ content }` on tool_result -- so a handler that returned anything would turn+ // this observer into an enforcer. On the approval events the stakes are highest: a returned value+ // there would let telemetry answer a question that was put to the operator.+ test("handlers return nothing so Oh My Pi never reads a directive", async () => {+ captureSends()+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ for (const [type, handler] of omp.handlers) {+ const result = await handler({ type, toolName: "bash" }, context())+ expect(result).toBeUndefined()+ }+ })++ // Event fields win over the lifted identity fields on a key collision, so a value Oh My Pi+ // reported is never overwritten by one Beacon derived. user_bash and user_python carry their own+ // cwd; the approval events carry their own sessionId.+ test("event fields take precedence over lifted identity", async () => {+ const sent = captureSends()+ const omp = fakeOmp()+ createBeaconExtension().register(omp.api)++ await omp.fire({ type: "user_bash", command: "ls", cwd: "/other" }, context())+ await omp.fire(+ { type: "tool_approval_requested", sessionId: "sess-own", toolName: "bash" },+ context(),+ )++ expect(sent[0].cwd).toBe("/other")+ expect(sent[1].sessionId).toBe("sess-own")+ })+})diff --git a/plugins/omp-beacon/src/beacon.ts b/plugins/omp-beacon/src/beacon.tsnew file mode 100644index 00000000..4a2f3fad--- /dev/null+++ b/plugins/omp-beacon/src/beacon.ts@@ -0,0 +1,286 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry extension for Oh My Pi.+// Managed by beacon endpoint hooks install --harness omp.++// 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 and the Pi extension use one. Oh My Pi ships as a+// compiled binary on macOS, Linux and Windows alike, so there is no one shell whose quoting rules+// would hold.+const beaconArgv: string[] = ["__BEACON_ARGV__"]++const debugEnabled = process.env.BEACON_OMP_DEBUG === "1"++// A send that has not finished in this long is abandoned. Oh My Pi awaits extension handlers before+// continuing, 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++// Oh My Pi's own event objects, narrowed to the fields Beacon reads.+//+// Declared here rather than imported from @oh-my-pi/pi-coding-agent on purpose. The installed file+// sits in ~/.omp/agent/extensions with no node_modules beside it, and the loader imports it+// directly, stripping 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 Oh My Pi's+// definitions and buy a file that loads wherever Oh My Pi does.+type OmpEvent = Record<string, unknown> & { type: string }++interface OmpSessionManager {+ getSessionId?: () => string+ getCwd?: () => string+}++interface OmpContext {+ cwd?: string+ sessionManager?: OmpSessionManager+ model?: { id?: string; name?: string; provider?: string } | undefined+ mode?: string+}++// The events Beacon subscribes to, and nothing else.+//+// Oh My Pi publishes upwards of thirty event types. Most are provider-request internals, streaming+// message updates, compaction and retry signals, and TUI plumbing -- they describe how the runtime+// got its work done rather than what the agent did. Subscribing to all of them would fill the+// runtime log with rows no investigation asks for and would put Beacon in the path of every+// streaming token update.+//+// `tool_call` and `tool_result` are the pair carrying tool activity: the first names the tool and+// its arguments before it runs, the second carries the outcome. `user_bash` and `user_python` are+// code the operator ran with Oh My Pi's `!` and `$` prefixes, which no tool event covers.+//+// `tool_approval_requested` and `tool_approval_resolved` are the events upstream Pi does not have,+// and they are the reason this extension is not simply the Pi one pointed at a different directory.+// They report a decision an operator was actually asked to make. Beacon refuses to synthesize an+// approval from a tool call -- a `tool_call` handler that blocks is an extension deciding, not an+// operator being asked -- so a runtime that reports real ones is a genuine capability gain.+//+// Deliberately absent: `mcp_notification`, which fires for every JSON-RPC notification a connected+// server sends, most of them routine tools/resources list refreshes. It describes MCP transport+// plumbing rather than an action the agent took. The MCP activity worth recording is the agent+// calling an MCP tool, which already arrives as a tool_call/tool_result pair.+const subscribedEvents = [+ "session_start",+ "session_shutdown",+ "input",+ "tool_call",+ "tool_result",+ "tool_approval_requested",+ "tool_approval_resolved",+ "user_bash",+ "user_python",+ "message_end",+] as const++function debugLog(message: string, extra?: unknown) {+ if (!debugEnabled) return+ try {+ // eslint-disable-next-line no-console+ console.error("[beacon-omp]", message, extra ?? "")+ } catch {+ // Debug logging must stay best-effort.+ }+}++// safeClone turns an Oh My Pi event into something JSON.stringify accepts.+//+// The events carry live objects: AbortSignals 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 event with cycles and functions still attached.+ const safe = safeClone(payload)++ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.omp.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+ // Oh My 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 Oh My 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 Oh My Pi execution.+ }+}++// identity lifts the session and workspace fields Beacon needs to the top level of the envelope.+//+// Oh My 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, a fork, or a tree navigation, 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: OmpContext | 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) {+ // Oh My 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+ }+ // Which surface the session is running on: tui, rpc, json or print. A `print` or `rpc` run is+ // unattended, which changes how an approval row should be read -- there was no human at the+ // terminal to ask.+ if (ctx.mode) fields.ompMode = ctx.mode+ return fields+}++type OmpExtensionAPI = {+ on: (event: string, handler: (event: OmpEvent, ctx: OmpContext) => Promise<void> | void) => void+}++// createBeaconExtension is exported for tests; Oh My Pi loads the default export below.+export function createBeaconExtension() {+ const forward = async (event: OmpEvent, ctx: OmpContext) => {+ try {+ // The event is spread last so a field it carries itself wins over the context's. `user_bash`+ // and `user_python` both carry their own cwd, and the approval events carry their own+ // sessionId -- in each case the event's is the one that describes this action.+ 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: OmpExtensionAPI) {+ for (const name of subscribedEvents) {+ // Every handler returns undefined. Beacon observes; it never blocks a tool call, revises a+ // tool's arguments, rewrites a prompt, or replaces a message. Oh My Pi reads a returned+ // object as a request to change behavior -- `{ block: true }` or `{ input }` on tool_call,+ // `{ result }` on user_bash and user_python, `{ content }` on tool_result -- 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 Oh My Pi instance.+ subscribedEvents: [...subscribedEvents],+ }+}++export default function beaconExtension(pi: OmpExtensionAPI) {+ createBeaconExtension().register(pi)+}