Skip to content

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

Add the openclaw-beacon managed plugin

Claudeebee22824e67
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2afba1d1..d5eae1d1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -175,6 +175,9 @@ jobs:
- name: Check Oh My Pi extension
working-directory: plugins/omp-beacon
run: bun run check && bun test
+ - name: Check OpenClaw plugin
+ working-directory: plugins/openclaw-beacon
+ run: bun run check && bun test
- name: Build embedded hooks binary
working-directory: cli/beacon
# hooks.bin is gitignored (build-time artifact). The CLI embeds it via
diff --git a/CLAUDE.md b/CLAUDE.md
index ebde4abd..5a56c47a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -124,10 +124,13 @@ cd plugins/opencode-beacon && bun run check && bun test
cd ../cline-beacon && bun run check && bun test
cd ../pi-beacon && bun run check && bun test
cd ../omp-beacon && bun run check && bun test
+cd ../openclaw-beacon && bun run check && bun test
```
After editing a plugin or extension source, run `bun run sync` in its directory to update the
embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`; a Go test fails if the two drift.
+`openclaw-beacon` syncs three files rather than one, because OpenClaw discovers a plugin as a
+directory: the entry plus the two manifests it is declared in.
Run TypeScript SDK checks:
diff --git a/cli/beacon-hooks/cmd/openclaw_event_test.go b/cli/beacon-hooks/cmd/openclaw_event_test.go
index 8ca56164..5bfe7d86 100644
--- a/cli/beacon-hooks/cmd/openclaw_event_test.go
+++ b/cli/beacon-hooks/cmd/openclaw_event_test.go
@@ -2,6 +2,10 @@ package cmd
import (
"encoding/json"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sort"
"strings"
"testing"
@@ -591,3 +595,71 @@ func TestOpenClawHarnessName(t *testing.T) {
}
}
}
+
+// The contract between the managed plugin's registration list and this mapper's switch.
+//
+// A name misspelled on either side produces no error anywhere -- OpenClaw dispatches nothing, the
+// mapper is never called, and the only symptom is a category of agent activity silently missing
+// from the log. Read out of the shipped plugin source rather than duplicated here, so this test
+// cannot pass against a list that only exists in the test.
+func TestOpenClawPluginRegistrationsMatchTheMapper(t *testing.T) {
+ registered := openClawSubscribedHooks(t)
+ want := append([]string(nil), supportedOpenClawHooks()...)
+ sort.Strings(want)
+ sort.Strings(registered)
+
+ if len(registered) != len(want) {
+ t.Fatalf("the plugin registers %v but the mapper handles %v", registered, want)
+ }
+ for i := range registered {
+ if registered[i] != want[i] {
+ t.Fatalf("the plugin registers %v but the mapper handles %v; a name on either side "+
+ "that the other does not have produces no telemetry and no error", registered, want)
+ }
+ }
+}
+
+// Registering any of these would ask OpenClaw for a power Beacon must not hold: rewriting a
+// prompt, claiming a message before the agent sees it, gating an install, or voting on whether a
+// skill may be created. Asserted against the shipped source, not just the plugin's own test,
+// because this is the property that keeps Beacon an observer.
+func TestOpenClawPluginRegistersNoMutatingHook(t *testing.T) {
+ registered := map[string]bool{}
+ for _, hook := range openClawSubscribedHooks(t) {
+ registered[hook] = true
+ }
+ for _, forbidden := range []string{
+ "before_prompt_build", "agent_turn_prepare", "heartbeat_prompt_contribution",
+ "before_agent_reply", "before_agent_run", "before_agent_finalize",
+ "inbound_claim", "before_dispatch", "reply_dispatch",
+ "message_sending", "reply_payload_sending", "before_message_write",
+ "tool_result_persist", "resolve_exec_env", "before_install",
+ "skill_proposal_evaluate", "subagent_delivery_target", "before_model_resolve",
+ } {
+ if registered[forbidden] {
+ t.Fatalf("the OpenClaw plugin registers %q, which can change what the agent does", forbidden)
+ }
+ }
+}
+
+// openClawSubscribedHooks reads the `subscribedHooks` array out of the shipped plugin source.
+func openClawSubscribedHooks(t *testing.T) []string {
+ t.Helper()
+ path := filepath.Join("..", "..", "..", "plugins", "openclaw-beacon", "src", "beacon.js")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("plugin source is unreadable: %v", err)
+ }
+ block := regexp.MustCompile(`(?s)const subscribedHooks = \[(.*?)\n\]`).FindSubmatch(data)
+ if len(block) != 2 {
+ t.Fatalf("%s has no subscribedHooks 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 registers no hooks", path)
+ }
+ return names
+}
diff --git a/cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js b/cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js
new file mode 100644
index 00000000..0ce3bbf8
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js
@@ -0,0 +1,379 @@
+// __BEACON_MANAGED_MARKER__
+// Beacon endpoint telemetry plugin for OpenClaw Gateway.
+// Managed by beacon endpoint hooks install --harness openclaw.
+
+// 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-family extensions use one. OpenClaw runs
+// as a long-lived gateway on macOS, Linux and Windows alike, so there is no single shell whose
+// quoting rules would hold.
+const beaconArgv = ["__BEACON_ARGV__"]
+
+const debugEnabled = process.env.BEACON_OPENCLAW_DEBUG === "1"
+
+// A send that has not finished in this long is abandoned.
+//
+// Well under OpenClaw's 15 s default hook budget on purpose, and the number only matters for the
+// observe hooks: `before_tool_call` never waits at all (see dispatch below).
+const sendTimeoutMs = 2000
+
+// How deep into an event the serializer will walk before giving up.
+const maxDepth = 8
+
+// The hooks this plugin registers, and nothing else.
+//
+// OpenClaw publishes forty-one typed hooks. These ten are the ones that describe what the agent
+// did; the rest describe how the gateway got its work done. The full reasoning for each exclusion
+// lives beside supportedOpenClawHooks() in cli/beacon-hooks/cmd/openclaw_event.go, which is the
+// mapper half of this contract -- a name that disagrees between the two files produces no
+// telemetry rather than an error, so both sides pin the list and a test asserts they match.
+//
+// Three exclusions are worth repeating here, because they are about what this plugin is allowed to
+// be rather than about payload volume. `before_prompt_build` and `agent_turn_prepare` are prompt
+// *injection* hooks; `inbound_claim` and the claim-kind delivery hooks can swallow a message
+// outright; and `skill_proposal_evaluate` makes its handler a voting evaluator on whether a skill
+// may be installed. Beacon observes. Registering any of them would ask OpenClaw for a power Beacon
+// must not hold, and would do so silently.
+const subscribedHooks = [
+ "session_start",
+ "session_end",
+ "message_received",
+ "before_tool_call",
+ "after_tool_call",
+ "llm_output",
+ "before_compaction",
+ "after_compaction",
+ "subagent_spawned",
+ "subagent_ended",
+]
+
+// The hooks whose handler must never make OpenClaw wait.
+//
+// `before_tool_call` is registered fail-closed by OpenClaw itself: its default failure policy for
+// this hook is "fail-closed", so a handler that throws or exceeds its timeout *blocks the tool
+// call*. Beacon telemetry must never be able to stop an agent from working, so this handler
+// dispatches its send and returns synchronously, without awaiting and without a promise for
+// OpenClaw to wait on. The gateway is a long-lived process, so an unawaited child still runs to
+// completion.
+//
+// The cost is ordering: a `tool.invoked` row can land in the log after the `tool.completed` row
+// for the same call. That is acceptable because ordering was never the join -- `gen_ai.tool.call.id`
+// is, and both halves carry it.
+const nonBlockingHooks = new Set(["before_tool_call"])
+
+// How many in-flight tool calls the apply_patch enrichment below will remember at once.
+//
+// Bounded because the map is cleared by `after_tool_call`, and a call that never produces one --
+// an aborted run, a gateway restart mid-tool -- would otherwise leave an entry behind for the life
+// of the process. A gateway fans several conversations into one process, so this is set well above
+// a single agent's working set and is still only a few kilobytes at worst.
+const maxPendingToolCalls = 256
+
+// The destination paths OpenClaw derived for a proposed tool call, keyed by its own tool call id.
+//
+// This exists for one reason: `before_tool_call` carries `derivedPaths` and `after_tool_call` does
+// not. `apply_patch` takes the whole patch envelope as a single string argument, so without those
+// paths a completed patch is a tool call with a blob attached and no file rows at all -- and every
+// file-scoped detection Beacon ships matches on `file.path`.
+//
+// The join is OpenClaw's own call id rather than a timestamp or a guess, and both halves fire in
+// this same process, so remembering the value until the call completes is exact.
+const pendingDerivedPaths = new Map()
+
+function rememberDerivedPaths(event) {
+ const id = typeof event?.toolCallId === "string" ? event.toolCallId : ""
+ if (!id || !Array.isArray(event.derivedPaths) || event.derivedPaths.length === 0) return
+ // Re-inserting moves the entry to the end of the Map's insertion order, which is what makes the
+ // eviction below drop the genuinely oldest call rather than the least recently seen one.
+ pendingDerivedPaths.delete(id)
+ pendingDerivedPaths.set(id, event.derivedPaths)
+ while (pendingDerivedPaths.size > maxPendingToolCalls) {
+ const oldest = pendingDerivedPaths.keys().next()
+ if (oldest.done) break
+ pendingDerivedPaths.delete(oldest.value)
+ }
+}
+
+// takeDerivedPaths returns and forgets the paths remembered for a completed call.
+//
+// Absent rather than guessed when the call is unknown: a patch event enriched with some other
+// call's paths would be worse than one with none, because it would read as evidence that those
+// files changed.
+function takeDerivedPaths(event) {
+ const id = typeof event?.toolCallId === "string" ? event.toolCallId : ""
+ if (!id) return undefined
+ const paths = pendingDerivedPaths.get(id)
+ pendingDerivedPaths.delete(id)
+ return paths
+}
+
+function debugLog(message, extra) {
+ if (!debugEnabled) return
+ try {
+ console.error("[beacon-openclaw]", message, extra ?? "")
+ } catch {
+ // Debug logging must stay best-effort.
+ }
+}
+
+// safeClone turns an OpenClaw hook payload into something JSON.stringify accepts.
+//
+// The payloads carry live objects: an AbortSignal on the tool context, provider message objects on
+// `llm_output`, and tool params 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 patch -- is kept both
+// times. A WeakSet that never released would drop the second occurrence as if it were a cycle.
+function safeClone(value, depth = 0, seen = new WeakSet()) {
+ 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
+
+ if (seen.has(value)) return undefined
+ if (value instanceof Error) return { name: value.name, message: value.message }
+ if (value instanceof Date) return value.toISOString()
+
+ seen.add(value)
+ try {
+ if (Array.isArray(value)) {
+ return value.map((item) => safeClone(item, depth + 1, seen))
+ }
+ const out = {}
+ for (const [key, nested] of Object.entries(value)) {
+ const cloned = safeClone(nested, depth + 1, seen)
+ if (cloned !== undefined) out[key] = cloned
+ }
+ return out
+ } finally {
+ seen.delete(value)
+ }
+}
+
+// sendToBeacon spawns the hook binary and writes one envelope to its stdin.
+//
+// Returns a promise that always resolves. Nothing in this file rejects: a handler that rejects is
+// a handler that can break the run it was observing, and on `before_tool_call` it would block the
+// tool call outright.
+function sendToBeacon(payload) {
+ try {
+ return dispatch(payload)
+ } catch (err) {
+ // A synchronous throw would escape the handler, and on `before_tool_call` that blocks the
+ // tool call. The body below is written not to throw; this is the guard that makes "not to
+ // throw" a property of the function rather than a property of its current shape.
+ debugLog("send failed", err)
+ return Promise.resolve()
+ }
+}
+
+function dispatch(payload) {
+ // Flattened before anything else sees it, so every consumer is handed plain data rather than a
+ // live payload with cycles and functions still attached.
+ const safe = safeClone(payload)
+
+ const testSender = globalThis[Symbol.for("beacon.openclaw.testSender")]
+ if (typeof testSender === "function") {
+ return Promise.resolve(testSender(safe))
+ }
+
+ let body
+ try {
+ body = JSON.stringify(safe)
+ } catch (err) {
+ debugLog("payload could not be serialized", err)
+ return Promise.resolve()
+ }
+ if (!body) return Promise.resolve()
+
+ // 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 operator as a broken plugin, and
+ // OpenClaw disables a plugin that throws while loading rather than continuing without it.
+ return import("node:child_process")
+ .then(
+ ({ spawn }) =>
+ new Promise((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", { hook: payload?.hook })
+ finish()
+ }, sendTimeoutMs)
+ // An unreferenced timer cannot keep the gateway 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 gateway 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)
+ })
+}
+
+// identity lifts the session and workspace fields Beacon needs out of the hook context.
+//
+// Read per event rather than captured once at load, because a gateway process serves many
+// conversations at once: a session id cached at registration would label every later event with
+// whichever conversation happened to be first.
+//
+// `sessionKey` is carried alongside `sessionId` rather than instead of it. The two are not
+// interchangeable -- `sessionKey` is the canonical conversation, stable across the session-id
+// rotation a compaction causes, while `sessionId` is one generation of it. Beacon groups events by
+// the session and keeps the conversation key beside them.
+//
+// `workspaceDir` is absent for a chat turn that never touched a repository, and is left absent
+// rather than defaulted to the gateway's own working directory, which would attribute the work to
+// wherever the daemon happened to be started.
+function identity(ctx) {
+ const fields = {}
+ if (!ctx || typeof ctx !== "object") return fields
+ for (const [target, source] of [
+ ["sessionId", "sessionId"],
+ ["sessionKey", "sessionKey"],
+ ["runId", "runId"],
+ ["agentId", "agentId"],
+ ["channel", "channel"],
+ ["accountId", "accountId"],
+ ["trigger", "trigger"],
+ ]) {
+ const value = ctx[source]
+ if (typeof value === "string" && value) fields[target] = value
+ }
+ if (typeof ctx.workspaceDir === "string" && ctx.workspaceDir) fields.cwd = ctx.workspaceDir
+ // OpenClaw keeps the provider and the model id apart on the hook context. Joined here into the
+ // one provider-prefixed string every other Beacon collection path reports, which the writer
+ // then splits back into the canonical model name and `gen_ai.provider.name`. Sending the bare
+ // model id would leave the provider unrecorded, and a gateway routes one model through several.
+ if (typeof ctx.modelId === "string" && ctx.modelId) {
+ fields.model =
+ typeof ctx.modelProviderId === "string" && ctx.modelProviderId
+ ? `${ctx.modelProviderId}/${ctx.modelId}`
+ : ctx.modelId
+ }
+ return fields
+}
+
+// buildEnvelope assembles what the hook binary reads from stdin.
+//
+// The hook event stays nested under `event` rather than being spread onto the envelope. OpenClaw
+// hands a handler `(event, ctx)` as two objects whose field names overlap -- `runId`, `sessionKey`
+// and `sessionId` are on both -- and `before_tool_call` carries a `params` object whose keys belong
+// to the model rather than to OpenClaw. A flattened envelope would let a tool argument named
+// `sessionId` overwrite the session the event belongs to. One level of nesting makes that
+// impossible, and the mapper is written against it.
+function buildEnvelope(hook, event, ctx) {
+ const envelope = identity(ctx)
+ envelope.hook = hook
+ // A hook whose event carries its own session identity wins over the context's: `session_start`,
+ // `session_end` and `message_received` each name the session they are about, and the context is
+ // the more general answer.
+ if (event && typeof event === "object") {
+ for (const key of ["sessionId", "sessionKey", "runId"]) {
+ const value = event[key]
+ if (typeof value === "string" && value) envelope[key] = value
+ }
+ }
+ envelope.event = event ?? {}
+ return envelope
+}
+
+// createBeaconPlugin is exported for tests; OpenClaw loads the default export below.
+export function createBeaconPlugin() {
+ const handlerFor = (hook) => (event, ctx) => {
+ let envelope
+ try {
+ envelope = buildEnvelope(hook, event, ctx)
+
+ if (hook === "before_tool_call") {
+ rememberDerivedPaths(event)
+ } else if (hook === "after_tool_call") {
+ // OpenClaw does not repeat `derivedPaths` on the completion, so the value remembered from
+ // the proposal is attached here under the same key the mapper already reads.
+ const derived = takeDerivedPaths(event)
+ if (derived !== undefined && envelope.event && typeof envelope.event === "object") {
+ envelope.event = { ...envelope.event, derivedPaths: derived }
+ }
+ } else if (hook === "session_end") {
+ // A session ending abandons any call still in flight for it. Clearing keeps those paths
+ // from being joined to an unrelated call id in a later session.
+ pendingDerivedPaths.clear()
+ }
+ } catch (err) {
+ // Unreachable in practice, and caught anyway: a throw here on `before_tool_call` would block
+ // the tool call, because OpenClaw registers that hook fail-closed.
+ debugLog("envelope could not be built", err)
+ return undefined
+ }
+
+ if (nonBlockingHooks.has(hook)) {
+ // Dispatched without awaiting and without returning a promise. See nonBlockingHooks.
+ void sendToBeacon(envelope)
+ return undefined
+ }
+ // Returns a promise that always resolves to undefined. OpenClaw reads a returned object on its
+ // modify-kind hooks as a request to change behavior; returning nothing is what keeps this
+ // plugin an observer. Enforcement lives behind the policy provider seam in the hook adapter,
+ // not here.
+ return sendToBeacon(envelope).then(() => undefined)
+ }
+
+ return {
+ register(api) {
+ for (const hook of subscribedHooks) {
+ api.on(hook, handlerFor(hook))
+ }
+ },
+ // Exposed so a test can assert the subscription list without a live gateway.
+ subscribedHooks: [...subscribedHooks],
+ }
+}
+
+export default {
+ id: "beacon-endpoint",
+ name: "Beacon Endpoint Telemetry",
+ description: "Records OpenClaw agent activity to the local Beacon endpoint log.",
+ register(api) {
+ createBeaconPlugin().register(api)
+ },
+}
diff --git a/cli/beacon/internal/endpoint/hooks/assets/openclaw/embed.go b/cli/beacon/internal/endpoint/hooks/assets/openclaw/embed.go
new file mode 100644
index 00000000..2f84ef61
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/assets/openclaw/embed.go
@@ -0,0 +1,36 @@
+package openclawplugin
+
+import _ "embed"
+
+// OpenClaw discovers a plugin as a directory rather than a single file, so three artifacts are
+// embedded here where the other managed runtimes embed one.
+//
+// The root source of truth for all three lives at plugins/openclaw-beacon/src/. Tests fail if
+// these copies drift, and `bun run sync` in that directory is what updates them.
+
+// Template embeds the plugin entry Beacon renders and writes.
+//
+//go:embed beacon.js
+var Template string
+
+// PackageManifest embeds the plugin's own package.json.
+//
+// It is named plugin.package.json in the source tree so it cannot be mistaken for -- or picked up
+// by tooling as -- the workspace package.json that sits beside it. It is written to disk as
+// `package.json`, which is the name OpenClaw reads.
+//
+// It declares the entry under both `openclaw.extensions` and `openclaw.runtimeExtensions`.
+// OpenClaw treats the first as a source entrypoint and the second as a built-JavaScript one for
+// installed packages, and a plugin Beacon writes into the global extensions directory is reached
+// through whichever path the host takes. The entry is plain JavaScript, so both descriptions are
+// true of the same file and no transpilation step stands between OpenClaw and the plugin.
+//
+//go:embed plugin.package.json
+var PackageManifest string
+
+// PluginManifest embeds openclaw.plugin.json, the pre-runtime manifest OpenClaw reads before it
+// loads any plugin code. `activation.onStartup` is what makes the gateway load the plugin without
+// an agent run to trigger it, which is required for the session and gateway-level hooks.
+//
+//go:embed openclaw.plugin.json
+var PluginManifest string
diff --git a/cli/beacon/internal/endpoint/hooks/assets/openclaw/embed_test.go b/cli/beacon/internal/endpoint/hooks/assets/openclaw/embed_test.go
new file mode 100644
index 00000000..87a5b883
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/assets/openclaw/embed_test.go
@@ -0,0 +1,106 @@
+package openclawplugin
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// rootSource returns a file in the plugin's source tree, which is the source of truth for the
+// copies embedded beside this test.
+func rootSource(name string) string {
+ return filepath.Clean(filepath.Join("..", "..", "..", "..", "..", "..", "..", "plugins", "openclaw-beacon", "src", name))
+}
+
+// The checked-in plugin and its embedded copy are two files with the same content, and nothing but
+// a test keeps them that way. 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 TestEmbeddedPluginMatchesRootSource(t *testing.T) {
+ for _, tc := range []struct {
+ embedded string
+ root string
+ content string
+ }{
+ {"beacon.js", "beacon.js", Template},
+ {"plugin.package.json", "plugin.package.json", PackageManifest},
+ {"openclaw.plugin.json", "openclaw.plugin.json", PluginManifest},
+ } {
+ t.Run(tc.embedded, func(t *testing.T) {
+ root, err := os.ReadFile(rootSource(tc.root))
+ if err != nil {
+ t.Fatalf("root source is unreadable: %v", err)
+ }
+ if string(root) != tc.content {
+ t.Fatalf("plugins/openclaw-beacon/src/%s and its embedded copy have drifted; "+
+ "run `bun run sync` in plugins/openclaw-beacon", tc.root)
+ }
+ })
+ }
+}
+
+// The entry carries the two placeholders the installer substitutes. A template edit that renamed
+// either would install a plugin that spawns nothing and reports success.
+func TestEmbeddedPluginCarriesInstallerPlaceholders(t *testing.T) {
+ for _, placeholder := range []string{`["__BEACON_ARGV__"]`, "__BEACON_MANAGED_MARKER__"} {
+ if !strings.Contains(Template, placeholder) {
+ t.Fatalf("the OpenClaw plugin entry is missing the %s placeholder", placeholder)
+ }
+ }
+}
+
+// Both manifests must be valid JSON before an installer writes them: OpenClaw rejects a plugin
+// whose manifest does not parse, and it does so during discovery rather than at the call site, so
+// a malformed file shows up as a plugin that simply never loads.
+func TestEmbeddedManifestsAreValid(t *testing.T) {
+ var pkg struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ OpenClaw struct {
+ Extensions []string `json:"extensions"`
+ RuntimeExtensions []string `json:"runtimeExtensions"`
+ } `json:"openclaw"`
+ }
+ if err := json.Unmarshal([]byte(PackageManifest), &pkg); err != nil {
+ t.Fatalf("plugin package.json does not parse: %v", err)
+ }
+ // ESM. The entry uses `export default`, and OpenClaw imports it as a module.
+ if pkg.Type != "module" {
+ t.Fatalf(`package.json "type" = %q, want "module"`, pkg.Type)
+ }
+ // Declared under both entrypoint fields, because a plugin Beacon writes into the extensions
+ // directory is reached through whichever one the host build takes.
+ for _, entries := range [][]string{pkg.OpenClaw.Extensions, pkg.OpenClaw.RuntimeExtensions} {
+ if len(entries) != 1 || entries[0] != "./beacon.js" {
+ t.Fatalf("package.json entrypoints = %v, want [./beacon.js]", entries)
+ }
+ }
+
+ var manifest struct {
+ ID string `json:"id"`
+ Activation struct {
+ OnStartup bool `json:"onStartup"`
+ } `json:"activation"`
+ }
+ if err := json.Unmarshal([]byte(PluginManifest), &manifest); err != nil {
+ t.Fatalf("openclaw.plugin.json does not parse: %v", err)
+ }
+ if manifest.ID != "beacon-endpoint" {
+ t.Fatalf(`plugin id = %q, want "beacon-endpoint"`, manifest.ID)
+ }
+ // Without onStartup the gateway loads the plugin lazily, and the session and gateway-level
+ // hooks would never be registered in time to see the events they exist for.
+ if !manifest.Activation.OnStartup {
+ t.Fatal("openclaw.plugin.json does not activate on startup; session hooks would never register")
+ }
+}
+
+// The manifest's id and the entry's id are read at two different times -- the first before any
+// plugin code loads, the second from the module -- and OpenClaw keys config, enablement and
+// `plugins reload` on the manifest's. A mismatch loads a plugin the operator cannot address.
+func TestPluginIDIsConsistentBetweenManifestAndEntry(t *testing.T) {
+ if !strings.Contains(Template, `id: "beacon-endpoint"`) {
+ t.Fatal("the plugin entry does not declare id beacon-endpoint, which openclaw.plugin.json does")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/assets/openclaw/openclaw.plugin.json b/cli/beacon/internal/endpoint/hooks/assets/openclaw/openclaw.plugin.json
new file mode 100644
index 00000000..0a939ccf
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/assets/openclaw/openclaw.plugin.json
@@ -0,0 +1,8 @@
+{
+ "id": "beacon-endpoint",
+ "name": "Beacon Endpoint Telemetry",
+ "description": "Records OpenClaw agent activity to the local Beacon endpoint log.",
+ "categories": ["other"],
+ "activation": { "onStartup": true },
+ "configSchema": { "type": "object", "additionalProperties": false }
+}
diff --git a/cli/beacon/internal/endpoint/hooks/assets/openclaw/plugin.package.json b/cli/beacon/internal/endpoint/hooks/assets/openclaw/plugin.package.json
new file mode 100644
index 00000000..6ab6e14c
--- /dev/null
+++ b/cli/beacon/internal/endpoint/hooks/assets/openclaw/plugin.package.json
@@ -0,0 +1,11 @@
+{
+ "name": "@asymptote-labs/openclaw-beacon-endpoint",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Beacon endpoint telemetry plugin for OpenClaw Gateway",
+ "type": "module",
+ "openclaw": {
+ "extensions": ["./beacon.js"],
+ "runtimeExtensions": ["./beacon.js"]
+ }
+}
diff --git a/plugins/openclaw-beacon/package.json b/plugins/openclaw-beacon/package.json
new file mode 100644
index 00000000..59051820
--- /dev/null
+++ b/plugins/openclaw-beacon/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@asymptote-labs/openclaw-beacon",
+ "version": "0.0.0",
+ "private": true,
+ "description": "Beacon endpoint telemetry plugin for OpenClaw Gateway",
+ "type": "module",
+ "scripts": {
+ "check": "bun --check src/beacon.js && cmp src/beacon.js ../../cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js && cmp src/plugin.package.json ../../cli/beacon/internal/endpoint/hooks/assets/openclaw/plugin.package.json && cmp src/openclaw.plugin.json ../../cli/beacon/internal/endpoint/hooks/assets/openclaw/openclaw.plugin.json",
+ "sync": "cp src/beacon.js src/plugin.package.json src/openclaw.plugin.json ../../cli/beacon/internal/endpoint/hooks/assets/openclaw/",
+ "test": "bun test src/beacon.test.ts"
+ },
+ "exports": {
+ ".": "./src/beacon.js"
+ },
+ "files": [
+ "src/"
+ ]
+}
diff --git a/plugins/openclaw-beacon/src/beacon.js b/plugins/openclaw-beacon/src/beacon.js
new file mode 100644
index 00000000..0ce3bbf8
--- /dev/null
+++ b/plugins/openclaw-beacon/src/beacon.js
@@ -0,0 +1,379 @@
+// __BEACON_MANAGED_MARKER__
+// Beacon endpoint telemetry plugin for OpenClaw Gateway.
+// Managed by beacon endpoint hooks install --harness openclaw.
+
+// 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-family extensions use one. OpenClaw runs
+// as a long-lived gateway on macOS, Linux and Windows alike, so there is no single shell whose
+// quoting rules would hold.
+const beaconArgv = ["__BEACON_ARGV__"]
+
+const debugEnabled = process.env.BEACON_OPENCLAW_DEBUG === "1"
+
+// A send that has not finished in this long is abandoned.
+//
+// Well under OpenClaw's 15 s default hook budget on purpose, and the number only matters for the
+// observe hooks: `before_tool_call` never waits at all (see dispatch below).
+const sendTimeoutMs = 2000
+
+// How deep into an event the serializer will walk before giving up.
+const maxDepth = 8
+
+// The hooks this plugin registers, and nothing else.
+//
+// OpenClaw publishes forty-one typed hooks. These ten are the ones that describe what the agent
+// did; the rest describe how the gateway got its work done. The full reasoning for each exclusion
+// lives beside supportedOpenClawHooks() in cli/beacon-hooks/cmd/openclaw_event.go, which is the
+// mapper half of this contract -- a name that disagrees between the two files produces no
+// telemetry rather than an error, so both sides pin the list and a test asserts they match.
+//
+// Three exclusions are worth repeating here, because they are about what this plugin is allowed to
+// be rather than about payload volume. `before_prompt_build` and `agent_turn_prepare` are prompt
+// *injection* hooks; `inbound_claim` and the claim-kind delivery hooks can swallow a message
+// outright; and `skill_proposal_evaluate` makes its handler a voting evaluator on whether a skill
+// may be installed. Beacon observes. Registering any of them would ask OpenClaw for a power Beacon
+// must not hold, and would do so silently.
+const subscribedHooks = [
+ "session_start",
+ "session_end",
+ "message_received",
+ "before_tool_call",
+ "after_tool_call",
+ "llm_output",
+ "before_compaction",
+ "after_compaction",
+ "subagent_spawned",
+ "subagent_ended",
+]
+
+// The hooks whose handler must never make OpenClaw wait.
+//
+// `before_tool_call` is registered fail-closed by OpenClaw itself: its default failure policy for
+// this hook is "fail-closed", so a handler that throws or exceeds its timeout *blocks the tool
+// call*. Beacon telemetry must never be able to stop an agent from working, so this handler
+// dispatches its send and returns synchronously, without awaiting and without a promise for
+// OpenClaw to wait on. The gateway is a long-lived process, so an unawaited child still runs to
+// completion.
+//
+// The cost is ordering: a `tool.invoked` row can land in the log after the `tool.completed` row
+// for the same call. That is acceptable because ordering was never the join -- `gen_ai.tool.call.id`
+// is, and both halves carry it.
+const nonBlockingHooks = new Set(["before_tool_call"])
+
+// How many in-flight tool calls the apply_patch enrichment below will remember at once.
+//
+// Bounded because the map is cleared by `after_tool_call`, and a call that never produces one --
+// an aborted run, a gateway restart mid-tool -- would otherwise leave an entry behind for the life
+// of the process. A gateway fans several conversations into one process, so this is set well above
+// a single agent's working set and is still only a few kilobytes at worst.
+const maxPendingToolCalls = 256
+
+// The destination paths OpenClaw derived for a proposed tool call, keyed by its own tool call id.
+//
+// This exists for one reason: `before_tool_call` carries `derivedPaths` and `after_tool_call` does
+// not. `apply_patch` takes the whole patch envelope as a single string argument, so without those
+// paths a completed patch is a tool call with a blob attached and no file rows at all -- and every
+// file-scoped detection Beacon ships matches on `file.path`.
+//
+// The join is OpenClaw's own call id rather than a timestamp or a guess, and both halves fire in
+// this same process, so remembering the value until the call completes is exact.
+const pendingDerivedPaths = new Map()
+
+function rememberDerivedPaths(event) {
+ const id = typeof event?.toolCallId === "string" ? event.toolCallId : ""
+ if (!id || !Array.isArray(event.derivedPaths) || event.derivedPaths.length === 0) return
+ // Re-inserting moves the entry to the end of the Map's insertion order, which is what makes the
+ // eviction below drop the genuinely oldest call rather than the least recently seen one.
+ pendingDerivedPaths.delete(id)
+ pendingDerivedPaths.set(id, event.derivedPaths)
+ while (pendingDerivedPaths.size > maxPendingToolCalls) {
+ const oldest = pendingDerivedPaths.keys().next()
+ if (oldest.done) break
+ pendingDerivedPaths.delete(oldest.value)
+ }
+}
+
+// takeDerivedPaths returns and forgets the paths remembered for a completed call.
+//
+// Absent rather than guessed when the call is unknown: a patch event enriched with some other
+// call's paths would be worse than one with none, because it would read as evidence that those
+// files changed.
+function takeDerivedPaths(event) {
+ const id = typeof event?.toolCallId === "string" ? event.toolCallId : ""
+ if (!id) return undefined
+ const paths = pendingDerivedPaths.get(id)
+ pendingDerivedPaths.delete(id)
+ return paths
+}
+
+function debugLog(message, extra) {
+ if (!debugEnabled) return
+ try {
+ console.error("[beacon-openclaw]", message, extra ?? "")
+ } catch {
+ // Debug logging must stay best-effort.
+ }
+}
+
+// safeClone turns an OpenClaw hook payload into something JSON.stringify accepts.
+//
+// The payloads carry live objects: an AbortSignal on the tool context, provider message objects on
+// `llm_output`, and tool params 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 patch -- is kept both
+// times. A WeakSet that never released would drop the second occurrence as if it were a cycle.
+function safeClone(value, depth = 0, seen = new WeakSet()) {
+ 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
+
+ if (seen.has(value)) return undefined
+ if (value instanceof Error) return { name: value.name, message: value.message }
+ if (value instanceof Date) return value.toISOString()
+
+ seen.add(value)
+ try {
+ if (Array.isArray(value)) {
+ return value.map((item) => safeClone(item, depth + 1, seen))
+ }
+ const out = {}
+ for (const [key, nested] of Object.entries(value)) {
+ const cloned = safeClone(nested, depth + 1, seen)
+ if (cloned !== undefined) out[key] = cloned
+ }
+ return out
+ } finally {
+ seen.delete(value)
+ }
+}
+
+// sendToBeacon spawns the hook binary and writes one envelope to its stdin.
+//
+// Returns a promise that always resolves. Nothing in this file rejects: a handler that rejects is
+// a handler that can break the run it was observing, and on `before_tool_call` it would block the
+// tool call outright.
+function sendToBeacon(payload) {
+ try {
+ return dispatch(payload)
+ } catch (err) {
+ // A synchronous throw would escape the handler, and on `before_tool_call` that blocks the
+ // tool call. The body below is written not to throw; this is the guard that makes "not to
+ // throw" a property of the function rather than a property of its current shape.
+ debugLog("send failed", err)
+ return Promise.resolve()
+ }
+}
+
+function dispatch(payload) {
+ // Flattened before anything else sees it, so every consumer is handed plain data rather than a
+ // live payload with cycles and functions still attached.
+ const safe = safeClone(payload)
+
+ const testSender = globalThis[Symbol.for("beacon.openclaw.testSender")]
+ if (typeof testSender === "function") {
+ return Promise.resolve(testSender(safe))
+ }
+
+ let body
+ try {
+ body = JSON.stringify(safe)
+ } catch (err) {
+ debugLog("payload could not be serialized", err)
+ return Promise.resolve()
+ }
+ if (!body) return Promise.resolve()
+
+ // 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 operator as a broken plugin, and
+ // OpenClaw disables a plugin that throws while loading rather than continuing without it.
+ return import("node:child_process")
+ .then(
+ ({ spawn }) =>
+ new Promise((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", { hook: payload?.hook })
+ finish()
+ }, sendTimeoutMs)
+ // An unreferenced timer cannot keep the gateway 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 gateway 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)
+ })
+}
+
+// identity lifts the session and workspace fields Beacon needs out of the hook context.
+//
+// Read per event rather than captured once at load, because a gateway process serves many
+// conversations at once: a session id cached at registration would label every later event with
+// whichever conversation happened to be first.
+//
+// `sessionKey` is carried alongside `sessionId` rather than instead of it. The two are not
+// interchangeable -- `sessionKey` is the canonical conversation, stable across the session-id
+// rotation a compaction causes, while `sessionId` is one generation of it. Beacon groups events by
+// the session and keeps the conversation key beside them.
+//
+// `workspaceDir` is absent for a chat turn that never touched a repository, and is left absent
+// rather than defaulted to the gateway's own working directory, which would attribute the work to
+// wherever the daemon happened to be started.
+function identity(ctx) {
+ const fields = {}
+ if (!ctx || typeof ctx !== "object") return fields
+ for (const [target, source] of [
+ ["sessionId", "sessionId"],
+ ["sessionKey", "sessionKey"],
+ ["runId", "runId"],
+ ["agentId", "agentId"],
+ ["channel", "channel"],
+ ["accountId", "accountId"],
+ ["trigger", "trigger"],
+ ]) {
+ const value = ctx[source]
+ if (typeof value === "string" && value) fields[target] = value
+ }
+ if (typeof ctx.workspaceDir === "string" && ctx.workspaceDir) fields.cwd = ctx.workspaceDir
+ // OpenClaw keeps the provider and the model id apart on the hook context. Joined here into the
+ // one provider-prefixed string every other Beacon collection path reports, which the writer
+ // then splits back into the canonical model name and `gen_ai.provider.name`. Sending the bare
+ // model id would leave the provider unrecorded, and a gateway routes one model through several.
+ if (typeof ctx.modelId === "string" && ctx.modelId) {
+ fields.model =
+ typeof ctx.modelProviderId === "string" && ctx.modelProviderId
+ ? `${ctx.modelProviderId}/${ctx.modelId}`
+ : ctx.modelId
+ }
+ return fields
+}
+
+// buildEnvelope assembles what the hook binary reads from stdin.
+//
+// The hook event stays nested under `event` rather than being spread onto the envelope. OpenClaw
+// hands a handler `(event, ctx)` as two objects whose field names overlap -- `runId`, `sessionKey`
+// and `sessionId` are on both -- and `before_tool_call` carries a `params` object whose keys belong
+// to the model rather than to OpenClaw. A flattened envelope would let a tool argument named
+// `sessionId` overwrite the session the event belongs to. One level of nesting makes that
+// impossible, and the mapper is written against it.
+function buildEnvelope(hook, event, ctx) {
+ const envelope = identity(ctx)
+ envelope.hook = hook
+ // A hook whose event carries its own session identity wins over the context's: `session_start`,
+ // `session_end` and `message_received` each name the session they are about, and the context is
+ // the more general answer.
+ if (event && typeof event === "object") {
+ for (const key of ["sessionId", "sessionKey", "runId"]) {
+ const value = event[key]
+ if (typeof value === "string" && value) envelope[key] = value
+ }
+ }
+ envelope.event = event ?? {}
+ return envelope
+}
+
+// createBeaconPlugin is exported for tests; OpenClaw loads the default export below.
+export function createBeaconPlugin() {
+ const handlerFor = (hook) => (event, ctx) => {
+ let envelope
+ try {
+ envelope = buildEnvelope(hook, event, ctx)
+
+ if (hook === "before_tool_call") {
+ rememberDerivedPaths(event)
+ } else if (hook === "after_tool_call") {
+ // OpenClaw does not repeat `derivedPaths` on the completion, so the value remembered from
+ // the proposal is attached here under the same key the mapper already reads.
+ const derived = takeDerivedPaths(event)
+ if (derived !== undefined && envelope.event && typeof envelope.event === "object") {
+ envelope.event = { ...envelope.event, derivedPaths: derived }
+ }
+ } else if (hook === "session_end") {
+ // A session ending abandons any call still in flight for it. Clearing keeps those paths
+ // from being joined to an unrelated call id in a later session.
+ pendingDerivedPaths.clear()
+ }
+ } catch (err) {
+ // Unreachable in practice, and caught anyway: a throw here on `before_tool_call` would block
+ // the tool call, because OpenClaw registers that hook fail-closed.
+ debugLog("envelope could not be built", err)
+ return undefined
+ }
+
+ if (nonBlockingHooks.has(hook)) {
+ // Dispatched without awaiting and without returning a promise. See nonBlockingHooks.
+ void sendToBeacon(envelope)
+ return undefined
+ }
+ // Returns a promise that always resolves to undefined. OpenClaw reads a returned object on its
+ // modify-kind hooks as a request to change behavior; returning nothing is what keeps this
+ // plugin an observer. Enforcement lives behind the policy provider seam in the hook adapter,
+ // not here.
+ return sendToBeacon(envelope).then(() => undefined)
+ }
+
+ return {
+ register(api) {
+ for (const hook of subscribedHooks) {
+ api.on(hook, handlerFor(hook))
+ }
+ },
+ // Exposed so a test can assert the subscription list without a live gateway.
+ subscribedHooks: [...subscribedHooks],
+ }
+}
+
+export default {
+ id: "beacon-endpoint",
+ name: "Beacon Endpoint Telemetry",
+ description: "Records OpenClaw agent activity to the local Beacon endpoint log.",
+ register(api) {
+ createBeaconPlugin().register(api)
+ },
+}
diff --git a/plugins/openclaw-beacon/src/beacon.test.ts b/plugins/openclaw-beacon/src/beacon.test.ts
new file mode 100644
index 00000000..5d31608b
--- /dev/null
+++ b/plugins/openclaw-beacon/src/beacon.test.ts
@@ -0,0 +1,323 @@
+import { afterEach, describe, expect, test } from "bun:test"
+
+import entry, { createBeaconPlugin } from "./beacon.js"
+
+const senderKey = Symbol.for("beacon.openclaw.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
+}
+
+type Handler = (event: Record<string, unknown>, ctx: unknown) => unknown
+
+// A stand-in for OpenClaw's plugin API that records registrations and lets a test fire one.
+function fakeGateway() {
+ const handlers = new Map<string, Handler>()
+ return {
+ api: {
+ on(hook: string, handler: Handler) {
+ handlers.set(hook, handler)
+ },
+ },
+ handlers,
+ async fire(hook: string, event: Record<string, unknown>, ctx?: unknown) {
+ const handler = handlers.get(hook)
+ if (!handler) throw new Error(`no handler registered for ${hook}`)
+ return await handler(event, ctx)
+ },
+ // fireSync returns whatever the handler returned without awaiting, which is how a test
+ // observes that a handler did not hand OpenClaw a promise to wait on.
+ fireSync(hook: string, event: Record<string, unknown>, ctx?: unknown) {
+ const handler = handlers.get(hook)
+ if (!handler) throw new Error(`no handler registered for ${hook}`)
+ return handler(event, ctx)
+ },
+ }
+}
+
+function context(overrides: Record<string, unknown> = {}) {
+ return {
+ sessionId: "sess-1",
+ sessionKey: "discord:chan-9",
+ runId: "run-7",
+ agentId: "main",
+ workspaceDir: "/workspace/repo",
+ modelProviderId: "openai",
+ modelId: "gpt-5",
+ channel: "discord",
+ ...overrides,
+ }
+}
+
+afterEach(() => {
+ delete (globalThis as Record<symbol, unknown>)[senderKey]
+ // The pending-paths cache is module state, so a test that leaves an entry behind would change
+ // the next test's result. A session_end clears it through the plugin's own path.
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+ void gateway.fire("session_end", { sessionId: "cleanup" }, context())
+})
+
+describe("beacon openclaw plugin", () => {
+ // These strings are the contract between this plugin and the openclaw-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("registers exactly the hooks the mapper handles", () => {
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ expect([...gateway.handlers.keys()].sort()).toEqual([
+ "after_compaction",
+ "after_tool_call",
+ "before_compaction",
+ "before_tool_call",
+ "llm_output",
+ "message_received",
+ "session_end",
+ "session_start",
+ "subagent_ended",
+ "subagent_spawned",
+ ])
+ })
+
+ // Registering any of these would ask OpenClaw for a power Beacon must not hold: rewriting a
+ // prompt, claiming a message before the agent sees it, or voting on whether a skill installs.
+ test("never registers a prompt-injection, claim, or evaluate hook", () => {
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ for (const forbidden of [
+ "before_prompt_build",
+ "agent_turn_prepare",
+ "heartbeat_prompt_contribution",
+ "inbound_claim",
+ "before_dispatch",
+ "reply_dispatch",
+ "before_agent_reply",
+ "skill_proposal_evaluate",
+ "before_install",
+ "message_sending",
+ "reply_payload_sending",
+ "tool_result_persist",
+ "before_message_write",
+ ]) {
+ expect(gateway.handlers.has(forbidden)).toBe(false)
+ }
+ })
+
+ test("the default export is a loadable plugin entry", () => {
+ const gateway = fakeGateway()
+ expect(entry.id).toBe("beacon-endpoint")
+ entry.register(gateway.api)
+ expect(gateway.handlers.size).toBe(10)
+ })
+
+ test("lifts session, run, workspace, and model identity onto the envelope", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire("session_start", { sessionId: "sess-1" }, context())
+
+ expect(sent).toHaveLength(1)
+ expect(sent[0]).toMatchObject({
+ hook: "session_start",
+ sessionId: "sess-1",
+ sessionKey: "discord:chan-9",
+ runId: "run-7",
+ agentId: "main",
+ channel: "discord",
+ cwd: "/workspace/repo",
+ model: "openai/gpt-5",
+ })
+ })
+
+ // A chat turn that never touched a repository genuinely has no workspace. Defaulting to the
+ // gateway's own directory would attribute the work to wherever the daemon was started.
+ test("omits the workspace when OpenClaw reports none", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire("session_start", { sessionId: "sess-1" }, context({ workspaceDir: undefined }))
+
+ expect(sent[0]).not.toHaveProperty("cwd")
+ })
+
+ test("reports a model with no provider prefix as its bare id", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire("session_start", { sessionId: "sess-1" }, context({ modelProviderId: undefined }))
+
+ expect(sent[0]?.model).toBe("gpt-5")
+ })
+
+ // The reason the hook event is nested rather than spread: `params` keys belong to the model.
+ test("a tool argument cannot overwrite the envelope's identity", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire(
+ "after_tool_call",
+ {
+ toolName: "exec",
+ toolCallId: "call-1",
+ params: { command: "echo hi", sessionId: "attacker", cwd: "/etc", hook: "session_end" },
+ },
+ context(),
+ )
+
+ expect(sent[0]?.sessionId).toBe("sess-1")
+ expect(sent[0]?.cwd).toBe("/workspace/repo")
+ expect(sent[0]?.hook).toBe("after_tool_call")
+ expect((sent[0]?.event as Record<string, unknown>).params).toMatchObject({ command: "echo hi" })
+ })
+
+ // OpenClaw registers before_tool_call fail-closed: a handler that throws or exceeds its timeout
+ // blocks the tool call. This handler must therefore never hand OpenClaw something to wait on.
+ test("before_tool_call returns synchronously without a promise", () => {
+ captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ const returned = gateway.fireSync(
+ "before_tool_call",
+ { toolName: "exec", toolCallId: "call-1", params: { command: "ls" } },
+ context(),
+ )
+
+ expect(returned).toBeUndefined()
+ })
+
+ // Every observe handler must resolve to undefined: OpenClaw reads a returned object on its
+ // modify-kind hooks as a request to change behavior.
+ test("observe handlers resolve to undefined", async () => {
+ captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ for (const hook of ["session_start", "after_tool_call", "llm_output", "message_received"]) {
+ expect(await gateway.fire(hook, {}, context())).toBeUndefined()
+ }
+ })
+
+ // apply_patch takes one opaque patch string, so without the paths carried forward from the
+ // proposal a completed patch produces no file rows at all.
+ test("carries derivedPaths forward from before_tool_call to after_tool_call", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire(
+ "before_tool_call",
+ {
+ toolName: "apply_patch",
+ toolCallId: "call-42",
+ params: { input: "*** Begin Patch\n*** End Patch\n" },
+ derivedPaths: ["/workspace/repo/a.go", "/workspace/repo/b.go"],
+ },
+ context(),
+ )
+ await gateway.fire(
+ "after_tool_call",
+ { toolName: "apply_patch", toolCallId: "call-42", params: { input: "*** Begin Patch\n*** End Patch\n" } },
+ context(),
+ )
+
+ const completion = sent.at(-1)?.event as Record<string, unknown>
+ expect(completion.derivedPaths).toEqual(["/workspace/repo/a.go", "/workspace/repo/b.go"])
+ })
+
+ // A patch event enriched with another call's paths would read as evidence that those files
+ // changed. Absent is the only safe answer.
+ test("does not attach paths from a different tool call", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire(
+ "before_tool_call",
+ { toolName: "apply_patch", toolCallId: "call-1", params: {}, derivedPaths: ["/a.go"] },
+ context(),
+ )
+ await gateway.fire("after_tool_call", { toolName: "apply_patch", toolCallId: "call-2", params: {} }, context())
+
+ const completion = sent.at(-1)?.event as Record<string, unknown>
+ expect(completion.derivedPaths).toBeUndefined()
+ })
+
+ // The paths are consumed by the completion they belong to, so a second completion for the same
+ // id cannot pick them up again.
+ test("forgets derivedPaths once their call completes", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire(
+ "before_tool_call",
+ { toolName: "apply_patch", toolCallId: "call-1", params: {}, derivedPaths: ["/a.go"] },
+ context(),
+ )
+ await gateway.fire("after_tool_call", { toolName: "apply_patch", toolCallId: "call-1", params: {} }, context())
+ await gateway.fire("after_tool_call", { toolName: "apply_patch", toolCallId: "call-1", params: {} }, context())
+
+ expect((sent.at(-2)?.event as Record<string, unknown>).derivedPaths).toEqual(["/a.go"])
+ expect((sent.at(-1)?.event as Record<string, unknown>).derivedPaths).toBeUndefined()
+ })
+
+ // An event that names its own session is more specific than the handler context, which is the
+ // gateway's more general answer.
+ test("an event's own session identity wins over the context's", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ await gateway.fire("session_end", { sessionId: "sess-9", reason: "idle" }, context())
+
+ expect(sent[0]?.sessionId).toBe("sess-9")
+ })
+
+ // A payload carrying a cycle, a bigint, or an AbortSignal must not cost the whole event.
+ test("serializes payloads that JSON.stringify would reject", async () => {
+ const sent = captureSends()
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ const cyclic: Record<string, unknown> = { toolName: "exec", params: { command: "ls" } }
+ cyclic.self = cyclic
+ await gateway.fire("after_tool_call", cyclic, {
+ ...context(),
+ abortSignal: new AbortController().signal,
+ tokens: 10n,
+ })
+
+ const event = sent[0]?.event as Record<string, unknown>
+ expect(event.toolName).toBe("exec")
+ expect(event.self).toBeUndefined()
+ expect(() => JSON.stringify(sent[0])).not.toThrow()
+ })
+
+ // A handler that throws on before_tool_call blocks the tool call, so nothing in this plugin may
+ // propagate an error -- not even a sender that fails outright.
+ test("a failing sender never reaches the gateway", async () => {
+ ;(globalThis as Record<symbol, unknown>)[senderKey] = () => {
+ throw new Error("sender exploded")
+ }
+ const gateway = fakeGateway()
+ createBeaconPlugin().register(gateway.api)
+
+ expect(() =>
+ gateway.fireSync("before_tool_call", { toolName: "exec", params: {} }, context()),
+ ).not.toThrow()
+ await expect(gateway.fire("session_start", { sessionId: "sess-1" }, context())).resolves.toBeUndefined()
+ })
+})
diff --git a/plugins/openclaw-beacon/src/openclaw.plugin.json b/plugins/openclaw-beacon/src/openclaw.plugin.json
new file mode 100644
index 00000000..0a939ccf
--- /dev/null
+++ b/plugins/openclaw-beacon/src/openclaw.plugin.json
@@ -0,0 +1,8 @@
+{
+ "id": "beacon-endpoint",
+ "name": "Beacon Endpoint Telemetry",
+ "description": "Records OpenClaw agent activity to the local Beacon endpoint log.",
+ "categories": ["other"],
+ "activation": { "onStartup": true },
+ "configSchema": { "type": "object", "additionalProperties": false }
+}
diff --git a/plugins/openclaw-beacon/src/plugin.package.json b/plugins/openclaw-beacon/src/plugin.package.json
new file mode 100644
index 00000000..6ab6e14c
--- /dev/null
+++ b/plugins/openclaw-beacon/src/plugin.package.json
@@ -0,0 +1,11 @@
+{
+ "name": "@asymptote-labs/openclaw-beacon-endpoint",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Beacon endpoint telemetry plugin for OpenClaw Gateway",
+ "type": "module",
+ "openclaw": {
+ "extensions": ["./beacon.js"],
+ "runtimeExtensions": ["./beacon.js"]
+ }
+}