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
Add the Prime Agent managed extension and installer
Claudefda8989deea7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2afba1d1..5c17c88b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -175,6 +175,9 @@ jobs:- name: Check Oh My Pi extensionworking-directory: plugins/omp-beaconrun: bun run check && bun test+ - name: Check Prime Agent extension+ working-directory: plugins/prime-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.goindex 707bb578..21aaa7e3 100644--- a/cli/beacon-hooks/cmd/pi_family_subscription_test.go+++ b/cli/beacon-hooks/cmd/pi_family_subscription_test.go@@ -27,6 +27,7 @@ func TestManagedExtensionSubscriptionsMatchTheirMappers(t *testing.T) {}{{"pi", filepath.Join("..", "..", "..", "plugins", "pi-beacon", "src", "beacon.ts"), supportedPiEventTypes()},{"omp", filepath.Join("..", "..", "..", "plugins", "omp-beacon", "src", "beacon.ts"), supportedOmpEventTypes()},+ {"prime", filepath.Join("..", "..", "..", "plugins", "prime-beacon", "src", "beacon.ts"), supportedPrimeEventTypes()},} {t.Run(tc.runtime, func(t *testing.T) {subscribed := subscribedEventTypes(t, tc.source)@@ -60,6 +61,7 @@ func TestEverySubscribedTypeIsMappedToAnEvent(t *testing.T) {}{{piRuntime, filepath.Join("..", "..", "..", "plugins", "pi-beacon", "src", "beacon.ts")},{ompRuntime, filepath.Join("..", "..", "..", "plugins", "omp-beacon", "src", "beacon.ts")},+ {primeRuntime, filepath.Join("..", "..", "..", "plugins", "prime-beacon", "src", "beacon.ts")},} {t.Run(tc.runtime.platform, func(t *testing.T) {for _, name := range subscribedEventTypes(t, tc.source) {diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex 4e38dbaa..e8b61f41 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -957,7 +957,7 @@ var userScopeOnlyHookTargets = map[string]bool{}func allHookTargetsForLevel() []string {- all := []string{"cursor", "codex", "vscode", "factory", "opencode", "openhands", "kiro", "cline", "pi", "omp", "grok", "qwen", "muse", "hermes", "devin-cli", "devin-desktop", "antigravity"}+ all := []string{"cursor", "codex", "vscode", "factory", "opencode", "openhands", "kiro", "cline", "pi", "omp", "prime", "grok", "qwen", "muse", "hermes", "devin-cli", "devin-desktop", "antigravity"}if endpointOpts.hookLevel != "project" {return all}@@ -1014,6 +1014,9 @@ func hookStatusesWithConfig(targets []string, cfg endpointconfig.Config) map[strcase "omp":status := endpointhooks.OmpHookStatus(endpointhooks.OmpOptions{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 "prime":+ status := endpointhooks.PrimeHookStatus(endpointhooks.PrimeOptions{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.goindex b5ac779d..69ba44c4 100644--- a/cli/beacon/cmd/endpoint_hooks.go+++ b/cli/beacon/cmd/endpoint_hooks.go@@ -163,6 +163,16 @@ func installEndpointHookTarget(name string, cfg endpointconfig.Config) error {return err}fmt.Printf("Oh My Pi extension installed: %s\n", status.ExtensionPath)+ case "prime":+ status, err := endpointhooks.InstallPrime(endpointhooks.PrimeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })+ if err != nil {+ return err+ }+ fmt.Printf("Prime Agent extension installed: %s\n", status.ExtensionPath)if endpointhooks.Level(endpointOpts.hookLevel) == endpointhooks.LevelProject {// Unlike Pi, Oh My Pi has no per-directory trust gate -- its own isProjectTrusted()// always returns true because `.omp` project inputs are loaded unconditionally. So the@@ -410,6 +420,16 @@ func uninstallEndpointHookTarget(name string, cfg endpointconfig.Config) error {return err}fmt.Println(status.Message)+ case "prime":+ status, err := endpointhooks.UninstallPrime(endpointhooks.PrimeOptions{+ 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),@@ -566,6 +586,12 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {LogPath: cfg.LogPath,UserMode: cfg.UserMode,})+ case "prime":+ statuses["prime"] = endpointhooks.PrimeHookStatus(endpointhooks.PrimeOptions{+ Level: endpointhooks.Level(endpointOpts.hookLevel),+ LogPath: cfg.LogPath,+ UserMode: cfg.UserMode,+ })case "grok":statuses["grok"] = endpointhooks.GrokHookStatus(endpointhooks.GrokOptions{Level: endpointhooks.Level(endpointOpts.hookLevel),@@ -660,6 +686,10 @@ func runEndpointHooksStatus(cmd *cobra.Command, args []string) error {status := statuses["omp"].(endpointhooks.OmpStatus)fmt.Printf("Oh My Pi extension: installed=%t path=%s\n", status.Installed, status.ExtensionPath)fmt.Println(status.Message)+ case "prime":+ status := statuses["prime"].(endpointhooks.PrimeStatus)+ fmt.Printf("Prime Agent 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.goindex b40e3657..3e068210 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", "openhands", "kiro", "cline", "pi", "omp", "grok", "qwen", "muse", "hermes", "devin-cli", "devin-desktop", "antigravity"}+ return []string{"claude", "codex", "cursor", "vscode", "factory", "opencode", "openhands", "kiro", "cline", "pi", "omp", "prime", "grok", "qwen", "muse", "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.goindex 91f74bbe..335cc4b7 100644--- a/cli/beacon/cmd/endpoint_targets.go+++ b/cli/beacon/cmd/endpoint_targets.go@@ -56,6 +56,15 @@ var harnessTargets = []harnessTarget{// for the other's. "oh-my-pi" is accepted because it is the repository name people reach for;// "omp" is the binary, and the canonical harness name events are written under.{name: "omp", endpointKind: endpointTargetHook, endpointAliases: []string{"omp", "oh-my-pi", "ohmypi"}, hookAliases: []string{"omp", "oh-my-pi", "ohmypi"}},+ // Prime Agent is a third row rather than an alias of either, for the reason Oh My Pi is a+ // second: it is a separately installed product with its own config root, and folding a spelling+ // into another runtime would install that runtime's extension while the operator asked for this+ // one. "prime" is the --platform value and the shortest unambiguous spelling; "prime-agent" is+ // what the binary is called; "prime_agent" is the canonical harness name events are written+ // under, so a row read out of the runtime log and passed back to --harness resolves to the+ // runtime it names. Prime Intellect's model names are deliberately not aliases -- accepting one+ // would let someone ask to install an extension for a model.+ {name: "prime", endpointKind: endpointTargetHook, endpointAliases: []string{"prime", "prime-agent", "prime_agent", "primeagent"}, hookAliases: []string{"prime", "prime-agent", "prime_agent", "primeagent"}},// OpenHands. "open-hands" is accepted because the product is written as two words as often as// one, and normalizeHarnessKey folds "open_hands" onto it. "openhands" is also the canonical// harness name events are written under, so a row read out of the runtime log and passed backdiff --git a/cli/beacon/cmd/prime_target_test.go b/cli/beacon/cmd/prime_target_test.gonew file mode 100644index 00000000..4111a944--- /dev/null+++ b/cli/beacon/cmd/prime_target_test.go@@ -0,0 +1,120 @@+package cmd++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ endpointhooks "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++// The spellings an operator actually types. "prime" is the --platform value and the shortest+// unambiguous name; "prime-agent" is the binary; the underscore form arrives from anyone copying+// the canonical harness name out of a log, since normalizeHarnessKey maps `_` to `-`.+func TestPrimeHookTargetAliases(t *testing.T) {+ for _, in := range []string{"prime", "PRIME", " prime ", "prime-agent", "prime_agent", "primeagent", "Prime-Agent"} {+ t.Run(in, func(t *testing.T) {+ got, ok := normalizeHookTarget(in)+ if !ok {+ t.Fatalf("normalizeHookTarget(%q) was not recognized", in)+ }+ if got != "prime" {+ t.Fatalf("normalizeHookTarget(%q) = %q, want prime", in, got)+ }+ })+ }+}++// Pi, Oh My Pi and Prime Agent are separately installed products. A `--harness` value for one must+// never resolve to another, or an operator asking to instrument one gets another's extension+// written into a directory the runtime they meant does not read.+func TestPrimePiAndOmpTargetsDoNotAlias(t *testing.T) {+ for in, want := range map[string]string{+ "pi": "pi",+ "pi-cli": "pi",+ "omp": "omp",+ "oh-my-pi": "omp",+ "prime": "prime",+ "prime-agent": "prime",+ "prime_agent": "prime",+ "primeagent": "prime",+ } {+ t.Run(in, func(t *testing.T) {+ got, ok := normalizeHookTarget(in)+ if !ok || got != want {+ t.Fatalf("normalizeHookTarget(%q) = (%q, %v), want %q", in, got, ok, want)+ }+ })+ }+}++// Prime Agent is a hook (extension) target, not an OTLP one: it exports no OpenTelemetry, so an+// endpoint install has nothing to point at it.+func TestPrimeEndpointTargetIsHookShaped(t *testing.T) {+ got, ok := normalizeEndpointTarget("prime")+ if !ok {+ t.Fatal("normalizeEndpointTarget(prime) was not recognized")+ }+ if got.Name != "prime" || got.Kind != endpointTargetHook {+ t.Fatalf("normalizeEndpointTarget(prime) = %+v, want a prime hook target", got)+ }+}++// The wiring test. A harness the target table advertises but the install switch has no case for+// falls through to `unsupported hook harness`, so this is what catches a runtime added to the table+// and nowhere else -- the way a half-added integration ships.+func TestInstallEndpointHookTargetHandlesPrime(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv("PRIME_AGENT_CODING_AGENT_DIR", "")++ previousLevel := endpointOpts.hookLevel+ endpointOpts.hookLevel = string(endpointhooks.LevelUser)+ t.Cleanup(func() { endpointOpts.hookLevel = previousLevel })++ cfg := endpointconfig.Config{+ LogPath: filepath.Join(t.TempDir(), "runtime.jsonl"),+ UserMode: true,+ }++ if err := installEndpointHookTarget("prime", cfg); err != nil {+ t.Fatalf("installEndpointHookTarget(prime) returned error: %v", err)+ }++ path := filepath.Join(home, ".prime", "agent", "extensions", "beacon.ts")+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("the install wrote no extension at %s: %v", path, err)+ }+ if !strings.Contains(string(data), endpointhooks.PrimeManagedExtensionMarker) {+ t.Fatal("the installed extension carries no Beacon marker")+ }+ // The invocation has to name Prime Agent's own mapper. `pi-event` here would attribute every+ // Prime Agent session to Pi, which is the failure the separate harness name exists to prevent.+ if !strings.Contains(string(data), `"prime-event"`) {+ t.Fatalf("the installed extension does not invoke prime-event:\n%s", data)+ }+ for _, foreign := range []string{`"pi-event"`, `"omp-event"`} {+ if strings.Contains(string(data), foreign) {+ t.Fatalf("the installed Prime Agent extension invokes %s", foreign)+ }+ }++ // Installing Prime Agent must not touch either sibling's directory.+ for _, sibling := range []string{".pi", ".omp"} {+ if _, err := os.Stat(filepath.Join(home, sibling)); !os.IsNotExist(err) {+ t.Fatalf("installing Prime Agent created %s: %v", sibling, err)+ }+ }++ // And the same command removes it again.+ if err := uninstallEndpointHookTarget("prime", cfg); err != nil {+ t.Fatalf("uninstallEndpointHookTarget(prime) returned error: %v", err)+ }+ if _, err := os.Stat(path); !os.IsNotExist(err) {+ t.Fatalf("the extension survived uninstall: %v", err)+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/prime/beacon.tsnew file mode 100644index 00000000..7d95d7d7--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts@@ -0,0 +1,290 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry extension for Prime Agent.+// Managed by beacon endpoint hooks install --harness prime.++// 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. Prime Agent 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_PRIME_DEBUG === "1"++// A send that has not finished in this long is abandoned. Prime Agent 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++// Prime Agent's own event objects, narrowed to the fields Beacon reads.+//+// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose -- and Prime+// Agent really does publish under that name, because it is a hard fork of pi-mono that kept the+// upstream package names. The installed file sits in ~/.prime/agent/extensions with no node_modules+// beside it, and Prime Agent 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 Prime Agent's definitions and buy a file that loads wherever Prime+// Agent does.+type PrimeEvent = Record<string, unknown> & { type: string }++interface PrimeSessionManager {+ getSessionId?: () => string+ getCwd?: () => string+}++interface PrimeContext {+ cwd?: string+ sessionManager?: PrimeSessionManager+ model?: { id?: string; name?: string; provider?: string } | undefined+ hasUI?: boolean+}++// The events Beacon subscribes to, and nothing else.+//+// Prime Agent publishes upwards of forty event types: provider request and response internals,+// streaming message updates, compaction, refinement and tree-navigation signals, resource discovery+// and TUI plumbing. Most 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 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. On this runtime that is nearly+// everything, because its only default tool is `ipython` -- a persistent Python kernel through+// which the agent reads files, writes files and runs shell commands via a `bash()` helper -- so a+// cell's code and the diffs its kernel streams are the agent's actions rather than a detail of one+// tool. `user_bash` is a command the human ran with the `!` prefix, which no tool event covers.+//+// Deliberately absent: any approval event. Prime Agent's `tool_call` handler can block a call, but+// that is an extension deciding, not an operator being asked -- it 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, exactly as it does for Pi and Cline.+//+// Also absent, and not an omission: `user_python`. Oh My Pi added a `$` operator prefix that runs+// Python outside the agent loop and subscribes to its event; Prime Agent forked pi-mono separately+// and has no such prefix. Its operator surface is `!` alone.+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-prime]", message, extra ?? "")+ } catch {+ // Debug logging must stay best-effort.+ }+}++// safeClone turns a Prime Agent event into something JSON.stringify accepts.+//+// Its 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 Prime Agent event with cycles and functions still attached.+ const safe = safeClone(payload)++ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.prime.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+ // Prime Agent 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 Prime Agent 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 Prime Agent execution.+ }+}++// identity lifts the session and workspace fields Beacon needs to the top level of the envelope.+//+// Prime Agent 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: PrimeContext | 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) {+ // Prime Agent'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+ }+ // Whether the session has a user-facing surface at all: false in print (`-p`) and JSON mode, true+ // in interactive and RPC mode. Prime Agent exposes no `mode` string the way Pi and Oh My Pi do,+ // and this is the fact those were read for -- an unattended run is not a run somebody was+ // watching, which is what a reader needs to know before drawing a conclusion from an absent+ // objection.+ if (typeof ctx.hasUI === "boolean") fields.primeHasUi = ctx.hasUI+ return fields+}++type PrimeExtensionAPI = {+ on: (event: string, handler: (event: PrimeEvent, ctx: PrimeContext) => Promise<void> | void) => void+}++// createBeaconExtension is exported for tests; Prime Agent loads the default export below.+export function createBeaconExtension() {+ const forward = async (event: PrimeEvent, ctx: PrimeContext) => {+ try {+ // The event is spread last so a field it carries itself wins over the context's: `user_bash`+ // carries its own cwd, and that is the one describing 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: PrimeExtensionAPI) {+ for (const name of subscribedEvents) {+ // Every handler returns undefined. Beacon observes; it never blocks a tool call, patches a+ // tool's arguments, rewrites a prompt, transforms input, or replaces a message. Prime Agent+ // reads a returned object as a request to change behavior -- `{ block: true }` on+ // tool_call, `{ action: "transform" }` on input, `{ content }` on tool_result,+ // `{ operations }` or `{ result }` on user_bash, `{ message }` on message_end -- 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 Prime Agent instance.+ subscribedEvents: [...subscribedEvents],+ }+}++export default function beaconExtension(pi: PrimeExtensionAPI) {+ createBeaconExtension().register(pi)+}diff --git a/cli/beacon/internal/endpoint/hooks/assets/prime/embed.go b/cli/beacon/internal/endpoint/hooks/assets/prime/embed.gonew file mode 100644index 00000000..c74b4777--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/assets/prime/embed.go@@ -0,0 +1,10 @@+package prime++import _ "embed"++// Template embeds the checked copy used by Beacon's Go installer.+// The root source of truth lives at plugins/prime-beacon/src/beacon.ts.+// Tests fail if this copy drifts.+//+//go:embed beacon.ts+var Template stringdiff --git a/cli/beacon/internal/endpoint/hooks/prime.go b/cli/beacon/internal/endpoint/hooks/prime.gonew file mode 100644index 00000000..cf1a0ce0--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/prime.go@@ -0,0 +1,202 @@+package hooks++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"++ primeextension "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks/assets/prime"+)++// Prime Agent (Prime Intellect) 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 and Oh My+// Pi's.+//+// The extension file is a separate source from Pi's rather than the same file installed twice.+// Prime Agent carries its own debug variable, its own test-sender symbol and its own comments about+// which of its events exist, and -- more to the point -- its own marker, so an install of one is+// never mistaken for an install of another.+const (+ primeExtensionFileName = "beacon.ts"++ // PrimeManagedExtensionMarker identifies an extension file as one Beacon wrote for Prime Agent.+ //+ // Distinct from PiManagedExtensionMarker and OmpManagedExtensionMarker on purpose. The three+ // 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 any of them ever moved+ // -- and an uninstall keyed on the wrong marker removes the wrong file. Exported for the same+ // three-package reason Pi's is: `hooks` writes it, `harness` reads it to report telemetry+ // status, and `inventory` reads it to decide whether a file it found is Beacon-managed.+ //+ // 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.+ PrimeManagedExtensionMarker = "beacon-managed-prime-extension:v1"++ // primeConfigDirName is the config directory Prime Agent keeps, at both scopes.+ //+ // Two path segments rather than one, and that is the runtime's own shape rather than a+ // convenience here: its CONFIG_DIR_NAME is the literal ".prime/agent", and it joins that whole+ // string under the home directory *and* under the working directory. So its project scope has+ // the `agent` segment that Pi's and Oh My Pi's project scopes do not. Copying either of those+ // layouts would write the file where Prime Agent does not look -- and the install would report+ // success and collect nothing.+ primeConfigDirName = ".prime/agent"++ // primeAgentDirEnv replaces the user-level agent directory outright.+ //+ // The name is derived rather than fixed upstream: Prime Agent builds it from the `piConfig.name`+ // in its own package.json, which is "prime-agent", so the shipped build reads+ // PRIME_AGENT_CODING_AGENT_DIR. PI_CODING_AGENT_DIR is what the same code produces for upstream+ // Pi and for Oh My Pi, and is deliberately not honored here: reading another product's variable+ // would move this install whenever an operator had set it for that one.+ primeAgentDirEnv = "PRIME_AGENT_CODING_AGENT_DIR"+)++type PrimeOptions struct {+ Level Level+ LogPath string+ UserMode bool+}++type PrimeStatus struct {+ Installed bool `json:"installed"`+ BinaryPath string `json:"binary_path,omitempty"`+ ExtensionPath string `json:"extension_path,omitempty"`+ Message string `json:"message,omitempty"`+}++var primeExtension = managedExtension{+ platform: "prime",+ displayName: "Prime Agent",+ marker: PrimeManagedExtensionMarker,+ template: primeextension.Template,+ configPath: PrimeExtensionPath,+}++var primeRuntime = primeExtension.runtime()++func InstallPrime(opts PrimeOptions) (PrimeStatus, error) {+ status, err := installRuntimeHooks(primeRuntime, RuntimeOptions(opts))+ if err != nil {+ return PrimeStatus{}, err+ }+ return primeStatusFromRuntime(status), nil+}++func UninstallPrime(opts PrimeOptions) (PrimeStatus, error) {+ status, err := uninstallRuntimeHooks(primeRuntime, RuntimeOptions(opts))+ if err != nil {+ return PrimeStatus{}, err+ }+ return primeStatusFromRuntime(status), nil+}++func PrimeHookStatus(opts PrimeOptions) PrimeStatus {+ return primeStatusFromRuntime(runtimeHookStatus(primeRuntime, RuntimeOptions(opts)))+}++func IsPrimeInstalled(opts PrimeOptions) bool {+ return isRuntimeInstalled(primeRuntime, RuntimeOptions(opts))+}++// primeStatusFromRuntime reports installed only when the extension can actually reach the binary.+func primeStatusFromRuntime(status runtimeStatus) PrimeStatus {+ status = primeExtension.reachableStatus(status)+ return PrimeStatus{+ Installed: status.Installed,+ BinaryPath: status.BinaryPath,+ ExtensionPath: status.ConfigPath,+ Message: status.Message,+ }+}++func primeEmbeddedExtensionSourcePath() string {+ return filepath.Clean(filepath.Join("assets", "prime", "beacon.ts"))+}++func primeRootExtensionSourcePath() string {+ return filepath.Clean(filepath.Join("..", "..", "..", "..", "..", "plugins", "prime-beacon", "src", "beacon.ts"))+}++// PrimeExtensionPath returns the extension file Beacon manages for a given install level.+//+// Prime Agent auto-discovers extension modules from both scopes with no trust prompt on either. A+// user-level install is still the default, because it follows the operator rather than one checkout.+func PrimeExtensionPath(level Level) (string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ // Only the user level needs a home directory. Failing here for a project install would+ // refuse a path that does not depend on the value that could not be read.+ if level == LevelProject {+ return PrimeExtensionPathForHome("", level)+ }+ return "", err+ }+ return PrimeExtensionPathForHome(home, level)+}++// PrimeExtensionPathForHome is PrimeExtensionPath against a caller-supplied home directory.+//+// Exported for inventory, which scans a home directory it was handed rather than the process's own+// -- a scan of another user's tree, or of a fixture. Sharing the resolution rather than rebuilding+// the path there is what keeps inventory from reporting on a file the installer does not write:+// this path is not a fixed string, since PRIME_AGENT_CODING_AGENT_DIR moves it.+func PrimeExtensionPathForHome(home string, level Level) (string, error) {+ dir, err := primeExtensionDir(home, level)+ if err != nil {+ return "", err+ }+ return filepath.Join(dir, primeExtensionFileName), nil+}++// primeExtensionDir resolves the directory Prime Agent actually scans for extension modules.+//+// The env override applies only to the user root, matching the runtime: it replaces getAgentDir(),+// and the project root is joined from the working directory with no variable consulted at all.+func primeExtensionDir(home string, level Level) (string, error) {+ switch level {+ case "", LevelUser:+ if agentDir := os.Getenv(primeAgentDirEnv); agentDir != "" {+ expanded, err := primeExpandTilde(agentDir, home)+ if err != nil {+ return "", err+ }+ return filepath.Join(expanded, "extensions"), nil+ }+ if home == "" {+ return "", fmt.Errorf("home directory is required to resolve the Prime Agent extension path")+ }+ return filepath.Join(home, filepath.FromSlash(primeConfigDirName), "extensions"), nil+ case LevelProject:+ cwd, err := os.Getwd()+ if err != nil {+ return "", err+ }+ return filepath.Join(cwd, filepath.FromSlash(primeConfigDirName), "extensions"), nil+ default:+ return "", fmt.Errorf("unknown hook level %q", level)+ }+}++// primeExpandTilde resolves a leading `~` in the agent-directory override.+//+// Prime Agent expands it itself before using the value, so a Beacon install that did not would+// create a literal `~` directory beside the working directory and report success while the runtime+// kept reading the real home. Only a bare `~` or a `~/`-rooted path is expanded, which is the+// runtime's own rule -- `~user/...` is left alone by both.+func primeExpandTilde(path, home string) (string, error) {+ if path != "~" && !strings.HasPrefix(path, "~/") && !strings.HasPrefix(path, `~\`) {+ return path, nil+ }+ if home == "" {+ return "", fmt.Errorf("home directory is required to resolve %s=%q", primeAgentDirEnv, path)+ }+ if path == "~" {+ return home, nil+ }+ return filepath.Join(home, filepath.FromSlash(path[2:])), nil+}diff --git a/cli/beacon/internal/endpoint/hooks/prime_test.go b/cli/beacon/internal/endpoint/hooks/prime_test.gonew file mode 100644index 00000000..462aa877--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/prime_test.go@@ -0,0 +1,329 @@+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 TestPrimeExtensionPathDefaultsToUserLevel(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv(primeAgentDirEnv, "")++ want := filepath.Join(home, ".prime", "agent", "extensions", "beacon.ts")+ for _, level := range []Level{"", LevelUser} {+ got, err := PrimeExtensionPath(level)+ if err != nil {+ t.Fatalf("PrimeExtensionPath(%q) returned error: %v", level, err)+ }+ if got != want {+ t.Fatalf("PrimeExtensionPath(%q) = %q, want %q", level, got, want)+ }+ }+}++// Prime Agent's project extension directory keeps the `agent` segment -- `.prime/agent/extensions`+// -- where Pi's and Oh My Pi's project directories drop it. That is the runtime's own shape: its+// CONFIG_DIR_NAME is the literal ".prime/agent" and it joins that whole string under the working+// directory as well as under the home directory. Copying either sibling's layout would write the+// file where Prime Agent does not look, and the install would report success and collect nothing.+func TestPrimeExtensionPathProjectLevelKeepsAgentSegment(t *testing.T) {+ cwd := t.TempDir()+ t.Chdir(cwd)++ got, err := PrimeExtensionPath(LevelProject)+ if err != nil {+ t.Fatalf("PrimeExtensionPath(project) returned error: %v", err)+ }+ want := filepath.Join(cwd, ".prime", "agent", "extensions", "beacon.ts")+ if got != want {+ t.Fatalf("PrimeExtensionPath(project) = %q, want %q", got, want)+ }+}++// PRIME_AGENT_CODING_AGENT_DIR replaces the user agent directory outright. The runtime reads it+// itself, and its own self-update path sets it on the process it re-execs, so an install performed+// from inside such a session has to land where that session will look.+func TestPrimeExtensionPathHonorsTheAgentDirOverride(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ agentDir := filepath.Join(home, "elsewhere", "agent")+ t.Setenv(primeAgentDirEnv, agentDir)++ got, err := PrimeExtensionPath(LevelUser)+ if err != nil {+ t.Fatalf("PrimeExtensionPath returned error: %v", err)+ }+ want := filepath.Join(agentDir, "extensions", "beacon.ts")+ if got != want {+ t.Fatalf("PrimeExtensionPath = %q, want %q -- an install that ignores the override writes "++ "where the runtime does not look", got, want)+ }+}++// The runtime expands a leading `~` in that variable before using it. An install that did not would+// create a literal `~` directory beside the working directory and report success while Prime Agent+// went on reading the real home.+func TestPrimeExtensionPathExpandsTildeInTheAgentDirOverride(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv(primeAgentDirEnv, "~/custom/agent")++ got, err := PrimeExtensionPath(LevelUser)+ if err != nil {+ t.Fatalf("PrimeExtensionPath returned error: %v", err)+ }+ want := filepath.Join(home, "custom", "agent", "extensions", "beacon.ts")+ if got != want {+ t.Fatalf("PrimeExtensionPath = %q, want %q", got, want)+ }+}++// The override applies to the user root only. The runtime joins the project directory from the+// working directory with no variable consulted at all, so an install that applied it to both would+// miss the project directory entirely -- the same mistake the Oh My Pi path guards against for its+// own config-dir rename.+func TestPrimeAgentDirOverrideDoesNotMoveTheProjectPath(t *testing.T) {+ home := t.TempDir()+ cwd := t.TempDir()+ testenv.SetHome(t, home)+ t.Chdir(cwd)+ t.Setenv(primeAgentDirEnv, filepath.Join(home, "elsewhere", "agent"))++ got, err := PrimeExtensionPath(LevelProject)+ if err != nil {+ t.Fatalf("PrimeExtensionPath(project) returned error: %v", err)+ }+ want := filepath.Join(cwd, ".prime", "agent", "extensions", "beacon.ts")+ if got != want {+ t.Fatalf("PrimeExtensionPath(project) = %q, want %q", got, want)+ }+}++// PI_CODING_AGENT_DIR is what the same upstream code produces for Pi and Oh My Pi. Prime Agent+// derives its variable from its own package name, so reading Pi's would move this install whenever+// an operator had set it for that product instead.+func TestPrimeExtensionPathIgnoresPisAgentDirOverride(t *testing.T) {+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv(primeAgentDirEnv, "")+ t.Setenv("PI_CODING_AGENT_DIR", filepath.Join(home, "pi-profile", "agent"))++ got, err := PrimeExtensionPath(LevelUser)+ if err != nil {+ t.Fatalf("PrimeExtensionPath returned error: %v", err)+ }+ want := filepath.Join(home, ".prime", "agent", "extensions", "beacon.ts")+ if got != want {+ t.Fatalf("PrimeExtensionPath = %q, want %q -- another product's variable must not move "++ "this install", got, want)+ }+}++func TestPrimeExtensionPathRejectsUnknownLevel(t *testing.T) {+ if _, err := PrimeExtensionPath(Level("machine")); err == nil {+ t.Fatal("PrimeExtensionPath accepted an unknown level; a typo in a scope flag must fail " ++ "loudly rather than silently installing at the default scope")+ }+}++// The three pi-family runtimes are separately installed products that one machine can run side by+// side. One writing into another's extension directory would attribute a whole runtime's activity+// to the wrong harness.+func TestPrimePiAndOmpInstallToDifferentDirectories(t *testing.T) {+ home := t.TempDir()+ cwd := t.TempDir()+ testenv.SetHome(t, home)+ t.Chdir(cwd)+ t.Setenv(primeAgentDirEnv, "")+ t.Setenv(ompAgentDirEnv, "")+ t.Setenv(ompConfigDirEnv, "")++ for _, level := range []Level{LevelUser, LevelProject} {+ prime, err := PrimeExtensionPath(level)+ if err != nil {+ t.Fatal(err)+ }+ pi, err := PiExtensionPath(level)+ if err != nil {+ t.Fatal(err)+ }+ omp, err := OmpExtensionPath(level)+ if err != nil {+ t.Fatal(err)+ }+ if prime == pi || prime == omp {+ t.Fatalf("Prime Agent shares its %s extension path %q with another pi-family runtime", level, prime)+ }+ }+}++// 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 TestPrimeManagedExtensionMarkerIsStable(t *testing.T) {+ if PrimeManagedExtensionMarker != "beacon-managed-prime-extension:v1" {+ t.Fatalf("PrimeManagedExtensionMarker = %q; changing it strands extensions installed by "++ "earlier builds, which uninstall then refuses to remove", PrimeManagedExtensionMarker)+ }+}++// Each pi-family runtime's marker has to be its own. The three 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 any of them ever moved -- and an uninstall keyed on the wrong marker+// removes the wrong file.+func TestPiFamilyMarkersAreDistinct(t *testing.T) {+ markers := map[string]string{+ "pi": PiManagedExtensionMarker,+ "omp": OmpManagedExtensionMarker,+ "prime": PrimeManagedExtensionMarker,+ }+ seen := map[string]string{}+ for runtime, marker := range markers {+ if other, ok := seen[marker]; ok {+ t.Fatalf("%s and %s share the marker %q", runtime, other, marker)+ }+ seen[marker] = runtime+ }+}++// primeRenderedArgv 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 primeRenderedArgv(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 TestInstallPrimeExtensionWritesAnExecutableInvocation(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 := primeExtension.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, PrimeManagedExtensionMarker) {+ t.Fatal("the installed extension carries no Beacon marker; uninstall would refuse to remove it")+ }++ argv := primeRenderedArgv(t, source)+ if argv[0] != binary {+ t.Fatalf("argv[0] = %q, want the hook binary %q", argv[0], binary)+ }+ if argv[len(argv)-1] != "prime-event" {+ t.Fatalf("argv ends with %q, want prime-event -- any other subcommand attributes Prime "++ "Agent's payloads to a different runtime", argv[len(argv)-1])+ }+ joined := strings.Join(argv, " ")+ for _, want := range []string{"--platform prime", "--log " + logPath, "--config /etc/beacon/endpoint.yaml"} {+ if !strings.Contains(joined, want) {+ t.Fatalf("argv %v is missing %q", argv, want)+ }+ }+}++// A file at this path that Beacon did not write belongs to somebody else. Overwriting it would+// destroy an operator's own extension, and the refusal is what makes the marker load-bearing.+func TestInstallPrimeRefusesToOverwriteAnUnmanagedExtension(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ if err := os.WriteFile(path, []byte("export default function () {}\n"), 0o644); err != nil {+ t.Fatal(err)+ }++ if err := primeExtension.install(path, "/opt/beacon/bin/beacon-hooks", "/tmp/runtime.jsonl", ""); err == nil {+ t.Fatal("install overwrote an extension Beacon did not write")+ }++ data, _ := os.ReadFile(path)+ if string(data) != "export default function () {}\n" {+ t.Fatalf("the operator's extension was modified: %s", data)+ }+}++// Uninstall removes only a file carrying this runtime's marker. A Pi or Oh My Pi extension found at+// this path -- which should not happen, since the three read different directories, but the markers+// are distinct precisely so the answer does not depend on that staying true -- is left alone.+func TestUninstallPrimeLeavesAnotherRuntimesExtensionAlone(t *testing.T) {+ path := filepath.Join(t.TempDir(), "beacon.ts")+ if err := os.WriteFile(path, []byte("// "+PiManagedExtensionMarker+"\n"), 0o644); err != nil {+ t.Fatal(err)+ }++ removed, err := primeExtension.remove(path)+ if err != nil {+ t.Fatalf("remove returned error: %v", err)+ }+ if removed {+ t.Fatal("uninstalling Prime Agent removed a file carrying Pi's marker")+ }+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("the Pi extension was deleted: %v", err)+ }+}++// A Windows path is the case that makes argv worth encoding as JSON rather than as a command line.+func TestRenderPrimeExtensionEncodesWindowsPaths(t *testing.T) {+ source, err := primeExtension.render(`C:\Program Files\beacon\beacon-hooks.exe`, `C:\ProgramData\beacon\runtime.jsonl`, "")+ if err != nil {+ t.Fatalf("render returned error: %v", err)+ }+ argv := primeRenderedArgv(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 TestPrimeEmbeddedExtensionMatchesRootSource(t *testing.T) {+ embedded, err := os.ReadFile(primeEmbeddedExtensionSourcePath())+ if err != nil {+ t.Fatalf("embedded extension source is unreadable: %v", err)+ }+ root, err := os.ReadFile(primeRootExtensionSourcePath())+ if err != nil {+ t.Fatalf("root extension source is unreadable: %v", err)+ }+ if string(embedded) != string(root) {+ t.Fatal("plugins/prime-beacon/src/beacon.ts and its embedded copy have drifted; " ++ "run `bun run sync` in plugins/prime-beacon")+ }+}++// Prime Agent publishes no approval event, and Beacon refuses to synthesize one from a blocking+// tool handler. Asserted against the shipped source so the absence is a property of what installs+// rather than of what somebody remembered not to add.+func TestPrimeExtensionSubscribesToNoApprovalEvent(t *testing.T) {+ for _, forbidden := range []string{"tool_approval_requested", "tool_approval_resolved", "user_python"} {+ if strings.Contains(primeExtension.template, `"`+forbidden+`"`) {+ t.Fatalf("the Prime Agent extension subscribes to %q, which this runtime does not "++ "publish; those are Oh My Pi's events", forbidden)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 8e32b37e..04c60848 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -1048,6 +1048,8 @@ func configureHarnesses(cfg endpointconfig.Config) ([]string, error) {return paths, fmt.Errorf("Pi telemetry is installed with `beacon endpoint hooks install --harness pi`, not endpoint install")case "omp", "oh_my_pi", "oh-my-pi":return paths, fmt.Errorf("Oh My Pi telemetry is installed with `beacon endpoint hooks install --harness omp`, not endpoint install")+ case "prime", "prime_agent", "prime-agent":+ return paths, fmt.Errorf("Prime Agent telemetry is installed with `beacon endpoint hooks install --harness prime`, not endpoint install")// Qwen Code has no OpenTelemetry export to point at the local collector, so `endpoint// install --harness qwen` has nothing to configure. Saying so beats the generic// "unsupported harness", which reads as "Beacon does not support Qwen Code" when thediff --git a/plugins/prime-beacon/package.json b/plugins/prime-beacon/package.jsonnew file mode 100644index 00000000..2987c903--- /dev/null+++ b/plugins/prime-beacon/package.json@@ -0,0 +1,21 @@+{+ "name": "@asymptote-labs/prime-beacon",+ "version": "0.0.0",+ "private": true,+ "description": "Beacon endpoint telemetry extension for Prime Agent",+ "type": "module",+ "scripts": {+ "check": "bun --check src/beacon.ts && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts",+ "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/prime/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/prime-beacon/src/beacon.test.ts b/plugins/prime-beacon/src/beacon.test.tsnew file mode 100644index 00000000..7e98faf4--- /dev/null+++ b/plugins/prime-beacon/src/beacon.test.ts@@ -0,0 +1,299 @@+import { afterEach, describe, expect, test } from "bun:test"++import { createBeaconExtension } from "./beacon"++const senderKey = Symbol.for("beacon.prime.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 Prime Agent'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 prime agent extension", () => {+ // These strings are the contract between this extension and the prime-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",+ ])+ })++ // Prime Agent publishes many more events than these, most of them provider-request, refinement+ // 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",+ "resources_discover",+ "session_before_refine",+ "refine_complete",+ "thinking_level_select",+ ]) {+ 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")+ })++ // Prime Agent 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, a fork and `/tree` all+ // replace the session without reloading the extension, so a cached id would be silently wrong.+ 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")+ })++ // Prime Agent'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 an edge+ // case. Its `ipython` results go further: they carry kernel attachments and streamed diffs.+ 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: "ipython", 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. Prime Agent reads a returned object as a request to+ // change behavior -- `{ block: true }` on tool_call, `{ action: "transform" }` on input,+ // `{ operations }` on user_bash -- so a handler that returned anything would turn this observer+ // into an enforcer.+ test("handlers return nothing so Prime Agent 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 Prime Agent+ // 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")+ })++ // Prime Agent's only default tool. The mapper reads the cell's code off `input.code` and the+ // outcome off `details`, so an envelope that dropped either would leave the runtime's entire+ // agent surface unrecorded.+ test("forwards an ipython cell with its code and kernel details", async () => {+ const sent = captureSends()+ const pi = fakePi()+ createBeaconExtension().register(pi.api)++ await pi.fire(+ {+ type: "tool_result",+ toolName: "ipython",+ toolCallId: "call-1",+ input: { code: "open('a.py','w').write('x')" },+ details: {+ status: "ok",+ durationMs: 12,+ stdout: "done\n",+ diffs: [{ path: "/repo/a.py", oldStr: "x = 1", newStr: "x = 2" }],+ },+ },+ context(),+ )++ const details = sent[0].details as Record<string, unknown>+ expect((sent[0].input as Record<string, unknown>).code).toBe("open('a.py','w').write('x')")+ expect(details.status).toBe("ok")+ expect((details.diffs as unknown[]).length).toBe(1)+ })++ // Prime Agent exposes no `mode` string the way Pi and Oh My Pi do. `hasUI` is the fact those were+ // read for: an unattended print or JSON run is not a run somebody was watching.+ test("records whether the session had a user-facing surface", async () => {+ const sent = captureSends()+ const pi = fakePi()+ createBeaconExtension().register(pi.api)++ await pi.fire({ type: "input", text: "hello" }, context({ hasUI: false }))+ await pi.fire({ type: "input", text: "hello" }, context())++ expect(sent[0].primeHasUi).toBe(false)+ // Absent rather than defaulted: a host that did not report it should not be recorded as one+ // that reported "no".+ expect(sent[1].primeHasUi).toBeUndefined()+ })++ // The runtime publishes no approval event, and Beacon refuses to synthesize one from a blocking+ // tool handler. This pins the absence from the extension's side: the Go mapper cannot invent an+ // approval for a runtime that never sends one.+ test("subscribes to no approval event", () => {+ const pi = fakePi()+ createBeaconExtension().register(pi.api)++ for (const name of [...pi.handlers.keys()]) {+ expect(name).not.toContain("approval")+ }+ })+})diff --git a/plugins/prime-beacon/src/beacon.ts b/plugins/prime-beacon/src/beacon.tsnew file mode 100644index 00000000..7d95d7d7--- /dev/null+++ b/plugins/prime-beacon/src/beacon.ts@@ -0,0 +1,290 @@+// __BEACON_MANAGED_MARKER__+// Beacon endpoint telemetry extension for Prime Agent.+// Managed by beacon endpoint hooks install --harness prime.++// 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. Prime Agent 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_PRIME_DEBUG === "1"++// A send that has not finished in this long is abandoned. Prime Agent 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++// Prime Agent's own event objects, narrowed to the fields Beacon reads.+//+// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose -- and Prime+// Agent really does publish under that name, because it is a hard fork of pi-mono that kept the+// upstream package names. The installed file sits in ~/.prime/agent/extensions with no node_modules+// beside it, and Prime Agent 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 Prime Agent's definitions and buy a file that loads wherever Prime+// Agent does.+type PrimeEvent = Record<string, unknown> & { type: string }++interface PrimeSessionManager {+ getSessionId?: () => string+ getCwd?: () => string+}++interface PrimeContext {+ cwd?: string+ sessionManager?: PrimeSessionManager+ model?: { id?: string; name?: string; provider?: string } | undefined+ hasUI?: boolean+}++// The events Beacon subscribes to, and nothing else.+//+// Prime Agent publishes upwards of forty event types: provider request and response internals,+// streaming message updates, compaction, refinement and tree-navigation signals, resource discovery+// and TUI plumbing. Most 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 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. On this runtime that is nearly+// everything, because its only default tool is `ipython` -- a persistent Python kernel through+// which the agent reads files, writes files and runs shell commands via a `bash()` helper -- so a+// cell's code and the diffs its kernel streams are the agent's actions rather than a detail of one+// tool. `user_bash` is a command the human ran with the `!` prefix, which no tool event covers.+//+// Deliberately absent: any approval event. Prime Agent's `tool_call` handler can block a call, but+// that is an extension deciding, not an operator being asked -- it 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, exactly as it does for Pi and Cline.+//+// Also absent, and not an omission: `user_python`. Oh My Pi added a `$` operator prefix that runs+// Python outside the agent loop and subscribes to its event; Prime Agent forked pi-mono separately+// and has no such prefix. Its operator surface is `!` alone.+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-prime]", message, extra ?? "")+ } catch {+ // Debug logging must stay best-effort.+ }+}++// safeClone turns a Prime Agent event into something JSON.stringify accepts.+//+// Its 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 Prime Agent event with cycles and functions still attached.+ const safe = safeClone(payload)++ const testSender = (globalThis as Record<symbol, unknown>)[Symbol.for("beacon.prime.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+ // Prime Agent 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 Prime Agent 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 Prime Agent execution.+ }+}++// identity lifts the session and workspace fields Beacon needs to the top level of the envelope.+//+// Prime Agent 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: PrimeContext | 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) {+ // Prime Agent'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+ }+ // Whether the session has a user-facing surface at all: false in print (`-p`) and JSON mode, true+ // in interactive and RPC mode. Prime Agent exposes no `mode` string the way Pi and Oh My Pi do,+ // and this is the fact those were read for -- an unattended run is not a run somebody was+ // watching, which is what a reader needs to know before drawing a conclusion from an absent+ // objection.+ if (typeof ctx.hasUI === "boolean") fields.primeHasUi = ctx.hasUI+ return fields+}++type PrimeExtensionAPI = {+ on: (event: string, handler: (event: PrimeEvent, ctx: PrimeContext) => Promise<void> | void) => void+}++// createBeaconExtension is exported for tests; Prime Agent loads the default export below.+export function createBeaconExtension() {+ const forward = async (event: PrimeEvent, ctx: PrimeContext) => {+ try {+ // The event is spread last so a field it carries itself wins over the context's: `user_bash`+ // carries its own cwd, and that is the one describing 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: PrimeExtensionAPI) {+ for (const name of subscribedEvents) {+ // Every handler returns undefined. Beacon observes; it never blocks a tool call, patches a+ // tool's arguments, rewrites a prompt, transforms input, or replaces a message. Prime Agent+ // reads a returned object as a request to change behavior -- `{ block: true }` on+ // tool_call, `{ action: "transform" }` on input, `{ content }` on tool_result,+ // `{ operations }` or `{ result }` on user_bash, `{ message }` on message_end -- 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 Prime Agent instance.+ subscribedEvents: [...subscribedEvents],+ }+}++export default function beaconExtension(pi: PrimeExtensionAPI) {+ createBeaconExtension().register(pi)+}