Skip to content

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

refactor(plugins): generate every plugin's safeClone from one shared source (#865) (#870)

claude[bot]ba04a725d014
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index aadf2fc3..086d8169 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -199,6 +199,9 @@ jobs:
cli/beacon-hooks
collector-builder/exporter/beaconjsonexporter
pkg/asymptoteobserve
+ - name: Check the plugins' shared serializer
+ working-directory: plugins/shared
+ run: bun run check && bun test
- name: Check OpenCode plugin
working-directory: plugins/opencode-beacon
run: bun run check && bun test
diff --git a/CLAUDE.md b/CLAUDE.md
index 2c1b5084..8bbc3425 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -142,7 +142,8 @@ for module in terraform/*/; do (cd "$module" && terraform init -backend=false &&
Run the managed runtime plugin/extension checks (each verifies the checked-in copy matches its embedded twin, then runs its tests):
```bash
-cd plugins/opencode-beacon && bun run check && bun test
+cd plugins/shared && bun run check && bun test
+cd ../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
@@ -156,6 +157,13 @@ embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`; a Go test fail
`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.
+The payload serializer (`safeClone` and its `maxDepth`) has one source, `plugins/shared/safe-clone.ts`.
+Every plugin except OpenCode carries a generated copy between `// BEGIN shared/safe-clone` and
+`// END shared/safe-clone`, because each installs as one self-contained file and cannot import it.
+Edit only the shared file, then run `bun run sync` in `plugins/shared` to rewrite every plugin source
+and embedded copy (OpenClaw's `.js` copy has its two type annotations stripped). Each plugin's
+`bun run check` and `plugins/shared`'s tests fail when any copy differs.
+
Run the lens sandbox browser tests (the real dashboard plus hostile fixture lenses; the hooks
binary must be built first). In a cloud session with a preinstalled Chromium, set `CHROMIUM_PATH`
instead of installing one:
@@ -562,7 +570,7 @@ unpacked through Chrome's developer mode.
`.github/workflows/ci.yml` runs these jobs on every pull request and on pushes to `main`:
-- `go-test` (macOS): `bun run check && bun test` in all seven `plugins/*` directories, then `make build-hooks-current`, then `go test ./...` in `cli/beacon`, `go test -race ./internal/endpoint/...`, `go test ./...` in `cli/beacon-hooks`, `collector-builder/exporter/beaconjsonexporter`, and `pkg/asymptoteobserve` (includes threat-rules pack conformance), then CLI help smoke checks that also assert removed commands stay unexposed.
+- `go-test` (macOS): `bun run check && bun test` in `plugins/shared` and all seven plugin directories, then `make build-hooks-current`, then `go test ./...` in `cli/beacon`, `go test -race ./internal/endpoint/...`, `go test ./...` in `cli/beacon-hooks`, `collector-builder/exporter/beaconjsonexporter`, and `pkg/asymptoteobserve` (includes threat-rules pack conformance), then CLI help smoke checks that also assert removed commands stay unexposed.
- `linux-test` (ubuntu) and `windows-test` (windows-2025) rerun the Go suites per platform. The Windows job tests a measured package list rather than `./...`; the excluded packages are tracked in #318, and the scope must not be widened back to `./...`.
- `typescript-sdk` (Node 20, 22, 24): `npm test`, `npm run check`, `npm run build`, `npm run pack:dry-run`, `npm run pack:smoke` in `packages/asymptote-sdk-js`.
- `browser-extension` (Node 22, matrix over `chromium` and `msedge`): `npm run check`, `npm run test:unit`, `npm run build`, a check that the build is a loadable MV3 extension, `npm run lint:firefox` (the Firefox build plus `addons-linter --warnings-as-errors`), and the Playwright replay e2e running the real extension headless in that leg's browser (`BROWSER_CHANNEL`) against a local HTTPS replay server; the HTML report and traces upload on failure. Brave, Opera, Vivaldi and Arc have no Playwright channel; `BROWSER_EXECUTABLE` runs the same e2e against their binaries for the manual checklist in `docs/runtimes/browser-extension-chromium.mdx`.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9021cb7b..e45b383a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -165,7 +165,10 @@ The browser extension's `npm test` builds the bundle and runs the Playwright
replay e2e, which needs `openssl` on PATH and a one-time
`npx playwright install chromium`. After editing a plugin or extension source
under `plugins/`, run `bun run sync` in its directory so the copy embedded in
-`cli/beacon` matches; a Go test fails if the two drift.
+`cli/beacon` matches; a Go test fails if the two drift. The payload serializer
+the plugins share lives only in `plugins/shared/safe-clone.ts`: edit it there and
+run `bun run sync` in `plugins/shared`, which rewrites the generated copy in every
+plugin.
If you cannot run a relevant check locally, mention that in the pull request and
explain why.
diff --git a/cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts
index b0d2bac8..9d5058ce 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts
@@ -17,9 +17,6 @@ const debugEnabled = process.env.BEACON_CLINE_DEBUG === "1"
// the worst case Beacon can add to a tool call.
const sendTimeoutMs = 2000
-// How deep into a hook context the serializer will walk before giving up.
-const maxDepth = 8
-
function debugLog(message: string, extra?: unknown) {
if (!debugEnabled) return
try {
@@ -30,45 +27,52 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a hook context into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload into something JSON.stringify accepts.
//
-// The contexts Cline passes are live SDK objects, not plain data: they carry functions, class
-// instances, and parent references. JSON.stringify throws on a circular reference and on a bigint,
-// and silently drops an Error to {}, so each of those is handled here rather than losing the whole
-// payload to one bad field.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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 workspace root referenced from two places -- is kept both times. A
-// WeakSet that never released would drop the second occurrence as if it were a cycle.
+// 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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts
index be5f7d63..aba6145e 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_OMO_DEBUG === "1"
// 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
-
// Senpi's own event objects, narrowed to the fields Beacon reads.
//
// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose -- and Senpi
@@ -91,12 +88,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a Senpi event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload 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.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -106,30 +110,30 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts
index 5cd1d44a..39be17dc 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_OMP_DEBUG === "1"
// continuing, so this is the worst case Beacon can add to a tool call.
const sendTimeoutMs = 2000
-// How deep into an event the serializer will walk before giving up.
-const maxDepth = 8
-
// Oh My Pi's own event objects, narrowed to the fields Beacon reads.
//
// Declared here rather than imported from @oh-my-pi/pi-coding-agent on purpose. The installed file
@@ -270,12 +267,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns an Oh My Pi event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload into something JSON.stringify accepts.
//
-// The events carry live objects: AbortSignals on the session events, AgentMessage arrays holding
-// class instances, and tool inputs that are mutable by design. JSON.stringify throws on a circular
-// reference and on a bigint, and silently flattens an Error to {}, so each is handled here rather
-// than losing the whole payload to one bad field.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -308,6 +312,7 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
seen.delete(value)
}
}
+// END shared/safe-clone
// The most of the hook binary's reply that is read. The reply is one small object, {"recorded": n}.
const maxReplyBytes = 4096
diff --git a/cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js b/cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js
index b99ffd4f..f9327393 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js
+++ b/cli/beacon/internal/endpoint/hooks/assets/openclaw/beacon.js
@@ -18,9 +18,6 @@ const debugEnabled = process.env.BEACON_OPENCLAW_DEBUG === "1"
// 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
@@ -121,22 +118,29 @@ function debugLog(message, extra) {
}
}
-// safeClone turns an OpenClaw hook payload into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime 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.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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 patch -- is kept both
-// times. A WeakSet that never released would drop the second occurrence as if it were a cycle.
+// 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, 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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
if (seen.has(value)) return undefined
@@ -159,6 +163,7 @@ function safeClone(value, depth = 0, seen = new WeakSet()) {
seen.delete(value)
}
}
+// END shared/safe-clone
// sendToBeacon spawns the hook binary and writes one envelope to its stdin.
//
diff --git a/cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts
index 971c3d7b..c6a24dec 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_PI_DEBUG === "1"
// continuing the agent loop, so this is the worst case Beacon can add to a tool call.
const sendTimeoutMs = 2000
-// How deep into an event the serializer will walk before giving up.
-const maxDepth = 8
-
// Pi's own event objects, narrowed to the fields Beacon reads.
//
// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose. The installed
@@ -76,12 +73,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a Pi event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload into something JSON.stringify accepts.
//
-// Pi's events carry live objects: an AbortSignal on the session events, AgentMessage arrays holding
-// class instances, and tool inputs that are mutable by design. JSON.stringify throws on a circular
-// reference and on a bigint, and silently flattens an Error to {}, so each is handled here rather
-// than losing the whole payload to one bad field.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -91,30 +95,30 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts
index 30513cd4..b6d1da40 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_PRIME_DEBUG === "1"
// 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
@@ -87,12 +84,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a Prime Agent event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload 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.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -102,30 +106,30 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/plugins/cline-beacon/package.json b/plugins/cline-beacon/package.json
index 7e6ef901..e069291e 100644
--- a/plugins/cline-beacon/package.json
+++ b/plugins/cline-beacon/package.json
@@ -5,8 +5,8 @@
"description": "Beacon endpoint telemetry adapter for Cline",
"type": "module",
"scripts": {
- "check": "bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts",
- "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts",
+ "check": "bun ../shared/sync-safe-clone.ts --check src/beacon.ts && bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts",
+ "sync": "bun ../shared/sync-safe-clone.ts src/beacon.ts && cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/cline/beacon.ts",
"test": "bun test src/beacon.test.ts"
},
"exports": {
diff --git a/plugins/cline-beacon/src/beacon.ts b/plugins/cline-beacon/src/beacon.ts
index b0d2bac8..9d5058ce 100644
--- a/plugins/cline-beacon/src/beacon.ts
+++ b/plugins/cline-beacon/src/beacon.ts
@@ -17,9 +17,6 @@ const debugEnabled = process.env.BEACON_CLINE_DEBUG === "1"
// the worst case Beacon can add to a tool call.
const sendTimeoutMs = 2000
-// How deep into a hook context the serializer will walk before giving up.
-const maxDepth = 8
-
function debugLog(message: string, extra?: unknown) {
if (!debugEnabled) return
try {
@@ -30,45 +27,52 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a hook context into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload into something JSON.stringify accepts.
//
-// The contexts Cline passes are live SDK objects, not plain data: they carry functions, class
-// instances, and parent references. JSON.stringify throws on a circular reference and on a bigint,
-// and silently drops an Error to {}, so each of those is handled here rather than losing the whole
-// payload to one bad field.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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 workspace root referenced from two places -- is kept both times. A
-// WeakSet that never released would drop the second occurrence as if it were a cycle.
+// 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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/plugins/omo-beacon/package.json b/plugins/omo-beacon/package.json
index 03040928..35bbdb8b 100644
--- a/plugins/omo-beacon/package.json
+++ b/plugins/omo-beacon/package.json
@@ -5,8 +5,8 @@
"description": "Beacon endpoint telemetry extension for Senpi (the standalone edition of oh-my-openagent)",
"type": "module",
"scripts": {
- "check": "bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts",
- "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts",
+ "check": "bun ../shared/sync-safe-clone.ts --check src/beacon.ts && bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts",
+ "sync": "bun ../shared/sync-safe-clone.ts src/beacon.ts && cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omo/beacon.ts",
"test": "bun test src/beacon.test.ts"
},
"exports": {
diff --git a/plugins/omo-beacon/src/beacon.ts b/plugins/omo-beacon/src/beacon.ts
index be5f7d63..aba6145e 100644
--- a/plugins/omo-beacon/src/beacon.ts
+++ b/plugins/omo-beacon/src/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_OMO_DEBUG === "1"
// 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
-
// Senpi's own event objects, narrowed to the fields Beacon reads.
//
// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose -- and Senpi
@@ -91,12 +88,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a Senpi event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload 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.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -106,30 +110,30 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/plugins/omp-beacon/package.json b/plugins/omp-beacon/package.json
index 526b1086..1ec39014 100644
--- a/plugins/omp-beacon/package.json
+++ b/plugins/omp-beacon/package.json
@@ -5,8 +5,8 @@
"description": "Beacon endpoint telemetry extension for Oh My Pi",
"type": "module",
"scripts": {
- "check": "bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts",
- "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts",
+ "check": "bun ../shared/sync-safe-clone.ts --check src/beacon.ts && bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts",
+ "sync": "bun ../shared/sync-safe-clone.ts src/beacon.ts && cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/omp/beacon.ts",
"test": "bun test src/beacon.test.ts"
},
"exports": {
diff --git a/plugins/omp-beacon/src/beacon.ts b/plugins/omp-beacon/src/beacon.ts
index 5cd1d44a..39be17dc 100644
--- a/plugins/omp-beacon/src/beacon.ts
+++ b/plugins/omp-beacon/src/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_OMP_DEBUG === "1"
// continuing, so this is the worst case Beacon can add to a tool call.
const sendTimeoutMs = 2000
-// How deep into an event the serializer will walk before giving up.
-const maxDepth = 8
-
// Oh My Pi's own event objects, narrowed to the fields Beacon reads.
//
// Declared here rather than imported from @oh-my-pi/pi-coding-agent on purpose. The installed file
@@ -270,12 +267,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns an Oh My Pi event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload into something JSON.stringify accepts.
//
-// The events carry live objects: AbortSignals on the session events, AgentMessage arrays holding
-// class instances, and tool inputs that are mutable by design. JSON.stringify throws on a circular
-// reference and on a bigint, and silently flattens an Error to {}, so each is handled here rather
-// than losing the whole payload to one bad field.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -308,6 +312,7 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
seen.delete(value)
}
}
+// END shared/safe-clone
// The most of the hook binary's reply that is read. The reply is one small object, {"recorded": n}.
const maxReplyBytes = 4096
diff --git a/plugins/openclaw-beacon/package.json b/plugins/openclaw-beacon/package.json
index 498794ac..01ee8999 100644
--- a/plugins/openclaw-beacon/package.json
+++ b/plugins/openclaw-beacon/package.json
@@ -5,8 +5,8 @@
"description": "Beacon endpoint telemetry plugin for OpenClaw Gateway",
"type": "module",
"scripts": {
- "check": "bun build --no-bundle src/beacon.js >/dev/null && 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/",
+ "check": "bun ../shared/sync-safe-clone.ts --check src/beacon.js && bun build --no-bundle src/beacon.js >/dev/null && 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": "bun ../shared/sync-safe-clone.ts src/beacon.js && 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": {
diff --git a/plugins/openclaw-beacon/src/beacon.js b/plugins/openclaw-beacon/src/beacon.js
index b99ffd4f..f9327393 100644
--- a/plugins/openclaw-beacon/src/beacon.js
+++ b/plugins/openclaw-beacon/src/beacon.js
@@ -18,9 +18,6 @@ const debugEnabled = process.env.BEACON_OPENCLAW_DEBUG === "1"
// 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
@@ -121,22 +118,29 @@ function debugLog(message, extra) {
}
}
-// safeClone turns an OpenClaw hook payload into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime 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.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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 patch -- is kept both
-// times. A WeakSet that never released would drop the second occurrence as if it were a cycle.
+// 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, 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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
if (seen.has(value)) return undefined
@@ -159,6 +163,7 @@ function safeClone(value, depth = 0, seen = new WeakSet()) {
seen.delete(value)
}
}
+// END shared/safe-clone
// sendToBeacon spawns the hook binary and writes one envelope to its stdin.
//
diff --git a/plugins/pi-beacon/package.json b/plugins/pi-beacon/package.json
index e6cb7da2..1a11572e 100644
--- a/plugins/pi-beacon/package.json
+++ b/plugins/pi-beacon/package.json
@@ -5,8 +5,8 @@
"description": "Beacon endpoint telemetry extension for Pi",
"type": "module",
"scripts": {
- "check": "bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts",
- "sync": "cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts",
+ "check": "bun ../shared/sync-safe-clone.ts --check src/beacon.ts && bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts",
+ "sync": "bun ../shared/sync-safe-clone.ts src/beacon.ts && cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/pi/beacon.ts",
"test": "bun test src/beacon.test.ts"
},
"exports": {
diff --git a/plugins/pi-beacon/src/beacon.ts b/plugins/pi-beacon/src/beacon.ts
index 971c3d7b..c6a24dec 100644
--- a/plugins/pi-beacon/src/beacon.ts
+++ b/plugins/pi-beacon/src/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_PI_DEBUG === "1"
// continuing the agent loop, so this is the worst case Beacon can add to a tool call.
const sendTimeoutMs = 2000
-// How deep into an event the serializer will walk before giving up.
-const maxDepth = 8
-
// Pi's own event objects, narrowed to the fields Beacon reads.
//
// Declared here rather than imported from @earendil-works/pi-coding-agent on purpose. The installed
@@ -76,12 +73,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a Pi event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload into something JSON.stringify accepts.
//
-// Pi's events carry live objects: an AbortSignal on the session events, AgentMessage arrays holding
-// class instances, and tool inputs that are mutable by design. JSON.stringify throws on a circular
-// reference and on a bigint, and silently flattens an Error to {}, so each is handled here rather
-// than losing the whole payload to one bad field.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -91,30 +95,30 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/plugins/prime-beacon/package.json b/plugins/prime-beacon/package.json
index 8209e5c7..300697f8 100644
--- a/plugins/prime-beacon/package.json
+++ b/plugins/prime-beacon/package.json
@@ -5,8 +5,8 @@
"description": "Beacon endpoint telemetry extension for Prime Agent",
"type": "module",
"scripts": {
- "check": "bun build --no-bundle src/beacon.ts >/dev/null && 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",
+ "check": "bun ../shared/sync-safe-clone.ts --check src/beacon.ts && bun build --no-bundle src/beacon.ts >/dev/null && cmp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts",
+ "sync": "bun ../shared/sync-safe-clone.ts src/beacon.ts && cp src/beacon.ts ../../cli/beacon/internal/endpoint/hooks/assets/prime/beacon.ts",
"test": "bun test src/beacon.test.ts"
},
"exports": {
diff --git a/plugins/prime-beacon/src/beacon.ts b/plugins/prime-beacon/src/beacon.ts
index 30513cd4..b6d1da40 100644
--- a/plugins/prime-beacon/src/beacon.ts
+++ b/plugins/prime-beacon/src/beacon.ts
@@ -16,9 +16,6 @@ const debugEnabled = process.env.BEACON_PRIME_DEBUG === "1"
// 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
@@ -87,12 +84,19 @@ function debugLog(message: string, extra?: unknown) {
}
}
-// safeClone turns a Prime Agent event into something JSON.stringify accepts.
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload 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.
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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.
@@ -102,30 +106,30 @@ function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unk
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 (typeof value !== "object") return value
if (depth >= maxDepth) return undefined
- const object = value as object
- if (seen.has(object)) return undefined
+ if (seen.has(value)) return undefined
if (value instanceof Error) return { name: value.name, message: value.message }
// Match native JSON: an invalid Date is null, not a lost event.
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
- seen.add(object)
+ seen.add(value)
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>)) {
+ 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(object)
+ seen.delete(value)
}
}
+// END shared/safe-clone
async function sendToBeacon(payload: Record<string, unknown>): Promise<void> {
// Flattened before anything else sees it, so every consumer of this function is handed plain
diff --git a/plugins/shared/package.json b/plugins/shared/package.json
new file mode 100644
index 00000000..2809d9e2
--- /dev/null
+++ b/plugins/shared/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "@asymptote-labs/plugins-shared",
+ "version": "0.0.0",
+ "private": true,
+ "description": "Source shared by the Beacon runtime plugins, written into each one by `bun run sync`",
+ "type": "module",
+ "scripts": {
+ "check": "bun build --no-bundle safe-clone.ts >/dev/null && bun sync-safe-clone.ts --check",
+ "sync": "bun sync-safe-clone.ts",
+ "test": "bun test"
+ }
+}
diff --git a/plugins/shared/safe-clone.test.ts b/plugins/shared/safe-clone.test.ts
new file mode 100644
index 00000000..7fe9f7b5
--- /dev/null
+++ b/plugins/shared/safe-clone.test.ts
@@ -0,0 +1,421 @@
+import { afterAll, describe, expect, test } from "bun:test"
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join, relative } from "node:path"
+
+import { safeClone as canonicalSafeClone } from "./safe-clone.ts"
+import {
+ beginMarker,
+ canonicalBlock,
+ consumers,
+ endMarker,
+ expectedBlock,
+ extractBlock,
+ jsRewrites,
+ pluginsDir,
+ replaceBlock,
+ repoRoot,
+ syncFile,
+ toJavaScript,
+} from "./sync-safe-clone.ts"
+
+type SafeClone = (value: unknown) => unknown
+
+const assetsDir = join(repoRoot, "cli/beacon/internal/endpoint/hooks/assets")
+const transpiler = new Bun.Transpiler({ loader: "ts" })
+
+// load evaluates the serializer exactly as a plugin file carries it. The region is self-contained
+// (it declares its own maxDepth), so it runs on its own; TypeScript regions are transpiled first,
+// JavaScript ones are run as written, which also proves the JavaScript copy has no TypeScript left.
+function load(path: string): SafeClone {
+ const block = extractBlock(readFileSync(path, "utf8"), path)
+ const code = path.endsWith(".js") ? block : transpiler.transformSync(block)
+ return new Function(`${code}\nreturn safeClone`)() as SafeClone
+}
+
+// chain builds `layers` nested objects around a leaf: chain(2, "x") is {child: {child: "x"}}. The
+// outermost object is at depth 0, so the innermost is at depth layers - 1.
+function chain(layers: number, leaf: unknown): unknown {
+ let value = leaf
+ for (let i = 0; i < layers; i++) value = { child: value }
+ return value
+}
+
+// Every serializer under test: the canonical module, and the copy in each plugin source and in
+// each embedded asset, evaluated from the file itself.
+const implementations: Array<[string, SafeClone]> = [
+ ["plugins/shared/safe-clone.ts", canonicalSafeClone],
+ ...consumers.flatMap(({ sourcePath, embeddedPath }) =>
+ [sourcePath, embeddedPath].map((path): [string, SafeClone] => [relative(repoRoot, path), load(path)])
+ ),
+]
+
+describe.each(implementations)("%s", (_name, safeClone) => {
+ describe("primitives", () => {
+ test("pass through unchanged", () => {
+ expect(safeClone("text")).toBe("text")
+ expect(safeClone("")).toBe("")
+ expect(safeClone(0)).toBe(0)
+ expect(safeClone(-1.5)).toBe(-1.5)
+ expect(safeClone(true)).toBe(true)
+ expect(safeClone(false)).toBe(false)
+ })
+
+ test("leave non-finite numbers to JSON.stringify, which writes null", () => {
+ expect(safeClone(Number.NaN)).toBeNaN()
+ expect(safeClone(Number.POSITIVE_INFINITY)).toBe(Number.POSITIVE_INFINITY)
+ expect(JSON.stringify(safeClone({ a: Number.NaN }))).toBe('{"a":null}')
+ })
+
+ test("keep null", () => {
+ expect(safeClone(null)).toBeNull()
+ expect(safeClone({ a: null })).toEqual({ a: null })
+ })
+
+ test("drop undefined, functions and symbols", () => {
+ expect(safeClone(undefined)).toBeUndefined()
+ expect(safeClone(() => 1)).toBeUndefined()
+ expect(safeClone(class Thing {})).toBeUndefined()
+ expect(safeClone(Symbol("s"))).toBeUndefined()
+ })
+
+ test("write a bigint as its decimal string instead of throwing", () => {
+ expect(safeClone(12n)).toBe("12")
+ expect(safeClone(-7n)).toBe("-7")
+ expect(safeClone(2n ** 70n)).toBe("1180591620717411303424")
+ expect(() => JSON.stringify({ n: 1n })).toThrow()
+ expect(JSON.stringify(safeClone({ n: 1n }))).toBe('{"n":"1"}')
+ })
+ })
+
+ describe("objects", () => {
+ test("drop keys whose values do not survive", () => {
+ const out = safeClone({ keep: 1, gone: undefined, fn() {}, sym: Symbol("s"), nul: null })
+ expect(out).toEqual({ keep: 1, nul: null })
+ expect(Object.keys(out as object)).toEqual(["keep", "nul"])
+ })
+
+ test("walk own enumerable string keys only", () => {
+ const value: Record<string | symbol, unknown> = { visible: 1, [Symbol("key")]: 2 }
+ Object.defineProperty(value, "hidden", { value: 3, enumerable: false })
+ expect(safeClone(Object.create({ inherited: 4 }, { own: { value: 5, enumerable: true } }))).toEqual({ own: 5 })
+ expect(safeClone(value)).toEqual({ visible: 1 })
+ })
+
+ test("flatten a class instance to its own fields, ignoring prototype getters and toJSON", () => {
+ class Message {
+ role = "user"
+ #secret = "private"
+ get upper() {
+ return this.role.toUpperCase() + this.#secret
+ }
+ toJSON() {
+ return "replaced"
+ }
+ }
+ expect(safeClone(new Message())).toEqual({ role: "user" })
+ expect(safeClone({ a: 1, toJSON: () => "replaced" })).toEqual({ a: 1 })
+ })
+
+ test("return a plain copy and leave the input untouched", () => {
+ const input = { nested: { list: [1, { deep: true }] }, fn: () => 1 }
+ const out = safeClone(input) as typeof input
+ expect(out).toEqual({ nested: { list: [1, { deep: true }] } } as unknown as typeof input)
+ expect(out).not.toBe(input)
+ expect(out.nested).not.toBe(input.nested)
+ expect(out.nested.list).not.toBe(input.nested.list)
+ expect(typeof input.fn).toBe("function")
+ })
+
+ test("never write a __proto__ key onto Object.prototype", () => {
+ const out = safeClone(JSON.parse('{"__proto__":{"polluted":true},"a":1}'))
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined()
+ expect(JSON.stringify(out)).toBe('{"a":1}')
+ })
+
+ test("walk containers with no enumerable entries to an empty object, as JSON.stringify does", () => {
+ expect(safeClone(new Map([["k", "v"]]))).toEqual({})
+ expect(safeClone(new Set([1, 2]))).toEqual({})
+ expect(safeClone(new WeakMap())).toEqual({})
+ expect(safeClone(new AbortController().signal)).toEqual({})
+ expect(JSON.stringify(new Map([["k", "v"]]))).toBe("{}")
+ })
+
+ test("write a typed array by its indices", () => {
+ expect(safeClone(new Uint8Array([7, 8]))).toEqual({ 0: 7, 1: 8 })
+ })
+ })
+
+ describe("arrays", () => {
+ test("keep every position, leaving dropped items as undefined for JSON.stringify to null", () => {
+ const out = safeClone([1, undefined, () => 1, Symbol("s"), "x"])
+ expect(out).toEqual([1, undefined, undefined, undefined, "x"])
+ expect((out as unknown[]).length).toBe(5)
+ expect(JSON.stringify(out)).toBe('[1,null,null,null,"x"]')
+ })
+
+ test("keep holes as holes", () => {
+ // eslint-disable-next-line no-sparse-arrays
+ const out = safeClone([, 1]) as unknown[]
+ expect(out.length).toBe(2)
+ expect(0 in out).toBe(false)
+ expect(JSON.stringify(out)).toBe("[null,1]")
+ })
+ })
+
+ describe("Error", () => {
+ test("keep only name and message, which JSON.stringify would lose", () => {
+ const err = Object.assign(new Error("boom", { cause: new Error("root") }), { code: "E_X" })
+ expect(JSON.stringify(err)).toBe('{"code":"E_X"}')
+ expect(safeClone(err)).toEqual({ name: "Error", message: "boom" })
+ })
+
+ test("keep the subclass name", () => {
+ expect(safeClone(new TypeError("bad"))).toEqual({ name: "TypeError", message: "bad" })
+ class ToolFailure extends Error {
+ override name = "ToolFailure"
+ }
+ expect(safeClone({ error: new ToolFailure("denied") })).toEqual({
+ error: { name: "ToolFailure", message: "denied" },
+ })
+ })
+ })
+
+ describe("Date", () => {
+ test("write a valid Date as its ISO string", () => {
+ expect(safeClone(new Date(0))).toBe("1970-01-01T00:00:00.000Z")
+ expect(safeClone({ at: new Date("2026-10-14T12:34:56.789Z") })).toEqual({ at: "2026-10-14T12:34:56.789Z" })
+ })
+
+ test("write an invalid Date as null, as JSON.stringify does, instead of throwing", () => {
+ const invalid = new Date(Number.NaN)
+ expect(() => invalid.toISOString()).toThrow()
+ expect(JSON.stringify({ at: invalid })).toBe('{"at":null}')
+ expect(safeClone(invalid)).toBeNull()
+ expect(safeClone({ at: invalid, keep: 1 })).toEqual({ at: null, keep: 1 })
+ expect(safeClone([invalid])).toEqual([null])
+ })
+ })
+
+ describe("cycles", () => {
+ test("drop a key that points back at an ancestor", () => {
+ const value: Record<string, unknown> = { id: "root" }
+ value.self = value
+ value.child = { parent: value, name: "child" }
+ expect(() => JSON.stringify(value)).toThrow()
+ expect(safeClone(value)).toEqual({ id: "root", child: { name: "child" } })
+ })
+
+ test("leave a cyclic array item undefined", () => {
+ const list: unknown[] = [1]
+ list.push(list)
+ expect(safeClone(list)).toEqual([1, undefined])
+ expect(JSON.stringify(safeClone(list))).toBe("[1,null]")
+ })
+
+ test("break a cycle through an Error's owner", () => {
+ const owner: Record<string, unknown> = { error: new Error("x") }
+ owner.loop = { back: owner }
+ expect(safeClone(owner)).toEqual({ error: { name: "Error", message: "x" }, loop: {} })
+ })
+
+ test("keep an object that appears twice without a cycle", () => {
+ const path = { file: "/repo/a.ts" }
+ const out = safeClone({ before: path, after: path, list: [path, path] }) as Record<string, unknown>
+ expect(out).toEqual({ before: path, after: path, list: [path, path] })
+ expect(out.before).not.toBe(out.after)
+ })
+ })
+
+ describe("depth limit", () => {
+ test("keep objects down to depth seven and a primitive at depth eight", () => {
+ const deepest = chain(8, "leaf")
+ expect(safeClone(deepest)).toEqual(deepest)
+ })
+
+ test("drop an object at depth eight, leaving its parent empty", () => {
+ expect(safeClone(chain(9, "leaf"))).toEqual(chain(7, {}))
+ expect(safeClone(chain(40, "leaf"))).toEqual(chain(7, {}))
+ })
+
+ test("count array nesting the same way", () => {
+ let kept: unknown = "leaf"
+ for (let i = 0; i < 8; i++) kept = [kept]
+ expect(safeClone(kept)).toEqual(kept)
+ expect(safeClone([kept])).toEqual([[[[[[[[undefined]]]]]]]])
+ })
+
+ test("drop an Error or a Date past the limit like any other object", () => {
+ expect(safeClone(chain(8, new Error("deep")))).toEqual(chain(7, {}))
+ expect(safeClone(chain(8, new Date(0)))).toEqual(chain(7, {}))
+ expect(safeClone(chain(7, new Error("ok")))).toEqual(chain(7, { name: "Error", message: "ok" }))
+ })
+
+ test("measure depth from the root along each branch", () => {
+ const out = safeClone({ deep: chain(9, "x"), shallow: { a: 1 } })
+ expect(out).toEqual({ deep: chain(6, {}), shallow: { a: 1 } })
+ })
+ })
+
+ describe("size", () => {
+ test("pass a wide or long payload through whole; size caps live in beacon-hooks", () => {
+ const wide = Object.fromEntries(Array.from({ length: 5000 }, (_, i) => [`k${i}`, i]))
+ const long = "x".repeat(1 << 20)
+ const out = safeClone({ wide, long, list: Array.from({ length: 5000 }, (_, i) => i) }) as {
+ wide: object
+ long: string
+ list: unknown[]
+ }
+ expect(Object.keys(out.wide).length).toBe(5000)
+ expect(out.long.length).toBe(1 << 20)
+ expect(out.list.length).toBe(5000)
+ })
+ })
+
+ test("always produce something JSON.stringify accepts", () => {
+ const hostile: Record<string, unknown> = {
+ big: 9007199254740993n,
+ err: new RangeError("r"),
+ when: new Date(Number.NaN),
+ fn: () => {},
+ signal: new AbortController().signal,
+ map: new Map([[1, 2]]),
+ deep: chain(30, 1n),
+ }
+ hostile.cycle = hostile
+ hostile.list = [hostile, 1n, new Error("e"), undefined]
+ const json = JSON.stringify(safeClone(hostile))
+ expect(JSON.parse(json)).toEqual({
+ big: "9007199254740993",
+ err: { name: "RangeError", message: "r" },
+ when: null,
+ signal: {},
+ map: {},
+ deep: chain(6, {}),
+ list: [null, "1", { name: "Error", message: "e" }, null],
+ })
+ })
+})
+
+describe("every plugin runs the shared serializer", () => {
+ const canonical = canonicalBlock()
+
+ test.each(consumers.map((c) => [c.plugin, c] as const))("%s source and embedded copy match", (_, c) => {
+ for (const path of [c.sourcePath, c.embeddedPath]) {
+ expect({ path: relative(repoRoot, path), block: extractBlock(readFileSync(path, "utf8"), path) }).toEqual({
+ path: relative(repoRoot, path),
+ block: expectedBlock(canonical, path),
+ })
+ }
+ })
+
+ // A copy written outside the markers would escape the drift check, so look for one everywhere a
+ // plugin lives: every plugin source and every embedded asset.
+ test("no plugin carries a serializer or depth limit of its own outside the shared block", () => {
+ const roots = [
+ ...readdirSync(pluginsDir).filter((dir) => dir !== "shared").map((dir) => join(pluginsDir, dir, "src")),
+ assetsDir,
+ ]
+ const sources = new Map(
+ roots
+ .filter((root) => existsSync(root))
+ .flatMap((root) => readdirSync(root, { recursive: true, encoding: "utf8" }).map((name) => join(root, name)))
+ .filter((path) => /\.[cm]?[jt]s$/.test(path) && !/\.test\.[jt]s$/.test(path))
+ .map((path) => [relative(repoRoot, path), readFileSync(path, "utf8")] as const)
+ .filter(([, source]) => /function safeClone\b/.test(source)),
+ )
+ const expected = consumers.flatMap((c) => [c.sourcePath, c.embeddedPath]).map((p) => relative(repoRoot, p))
+ expect([...sources.keys()].sort()).toEqual(expected.sort())
+
+ for (const [path, source] of sources) {
+ const outside = source.replace(extractBlock(source, path), "")
+ expect({ path, outside: /function safeClone\b|\bmaxDepth\s*=/.test(outside) }).toEqual({ path, outside: false })
+ }
+ })
+})
+
+describe("sync-safe-clone", () => {
+ const canonical = canonicalBlock()
+
+ test("the JavaScript copy differs from the TypeScript one only by the listed rewrites", () => {
+ const ts = canonical.split("\n")
+ const js = toJavaScript(canonical).split("\n")
+ expect(js.length).toBe(ts.length)
+ const changed = ts.flatMap((line, i) => (line === js[i] ? [] : [[line, js[i]]]))
+ expect(changed).toEqual(jsRewrites.map(([from, to]) => [from, to]))
+ expect(expectedBlock(canonical, "x/beacon.ts")).toBe(canonical)
+ expect(expectedBlock(canonical, "x/beacon.js")).toBe(toJavaScript(canonical))
+ })
+
+ test("refuses to emit JavaScript when a rewrite no longer matches exactly one line", () => {
+ const [signature] = jsRewrites[0]
+ expect(() => toJavaScript(canonical.replace(signature, `${signature} `))).toThrow(/found 0/)
+ expect(() => toJavaScript(`${canonical}\n${signature}`)).toThrow(/found 2/)
+ })
+
+ test("the generated JavaScript parses as JavaScript", () => {
+ expect(() => new Function(toJavaScript(canonical))).not.toThrow()
+ expect(() => new Function(canonical)).toThrow(SyntaxError)
+ })
+
+ test("extractBlock refuses missing, repeated or reversed markers", () => {
+ const block = `${beginMarker}\nx\n${endMarker}`
+ expect(extractBlock(`a\n${block}\nb`)).toBe(block)
+ expect(() => extractBlock("no markers")).toThrow(/no "/)
+ expect(() => extractBlock(`${beginMarker}\nx`)).toThrow(/no "/)
+ expect(() => extractBlock(`${block}\n${block}`)).toThrow(/more than once/)
+ expect(() => extractBlock(`${endMarker}\nx\n${beginMarker}`)).toThrow(/comes before/)
+ })
+
+ test("replaceBlock rewrites only the region and is idempotent", () => {
+ const before = `head\r\n ${beginMarker}\nold\n${endMarker} tail\n`
+ const replaced = replaceBlock(before, `${beginMarker}\nnew\n${endMarker}`)
+ expect(replaced).toBe(`head\r\n ${beginMarker}\nnew\n${endMarker} tail\n`)
+ expect(replaceBlock(replaced, `${beginMarker}\nnew\n${endMarker}`)).toBe(replaced)
+ })
+
+ describe("on a plugin file", () => {
+ const dir = mkdtempSync(join(tmpdir(), "safe-clone-sync-"))
+ const script = join(import.meta.dir, "sync-safe-clone.ts")
+ const run = (...args: string[]) => Bun.spawnSync(["bun", script, ...args], { stderr: "pipe", stdout: "pipe" })
+ const tampered = (name: string) => {
+ const path = join(dir, name)
+ const block = expectedBlock(canonical, path)
+ writeFileSync(path, `before\n${block.replace("const maxDepth = 8", "const maxDepth = 9")}\nafter\n`)
+ return path
+ }
+
+ test("check reports drift without writing, and sync repairs it", () => {
+ for (const name of ["plugin.ts", "plugin.js"]) {
+ const path = tampered(name)
+ const original = readFileSync(path, "utf8")
+ expect(syncFile(path, canonical, true)).toContain("differs from plugins/shared/safe-clone.ts")
+ expect(readFileSync(path, "utf8")).toBe(original)
+ expect(syncFile(path, canonical, false)).toBeUndefined()
+ expect(readFileSync(path, "utf8")).toBe(`before\n${expectedBlock(canonical, path)}\nafter\n`)
+ expect(syncFile(path, canonical, true)).toBeUndefined()
+ }
+ })
+
+ test("the command exits non-zero on drift and zero once synced", () => {
+ const path = tampered("cli.ts")
+ const failed = run("--check", path)
+ expect(failed.exitCode).toBe(1)
+ expect(failed.stderr.toString()).toContain("differs from plugins/shared/safe-clone.ts")
+ expect(run(path).exitCode).toBe(0)
+ expect(run("--check", path).exitCode).toBe(0)
+ })
+
+ test("the command fails on a file with no region rather than skipping it", () => {
+ const path = join(dir, "bare.ts")
+ writeFileSync(path, "function safeClone() {}\n")
+ const failed = run("--check", path)
+ expect(failed.exitCode).toBe(1)
+ expect(failed.stderr.toString()).toContain("no \"// BEGIN shared/safe-clone\"")
+ expect(run(path).exitCode).toBe(1)
+ expect(readFileSync(path, "utf8")).toBe("function safeClone() {}\n")
+ })
+
+ afterAll(() => rmSync(dir, { recursive: true, force: true }))
+ })
+})
diff --git a/plugins/shared/safe-clone.ts b/plugins/shared/safe-clone.ts
new file mode 100644
index 00000000..8d95e951
--- /dev/null
+++ b/plugins/shared/safe-clone.ts
@@ -0,0 +1,58 @@
+// The one source of the serializer every Beacon runtime plugin runs on its hook payloads.
+//
+// Each plugin installs as a single self-contained file that its runtime loads directly, so a plugin
+// cannot import this module at run time. Instead the region between the two markers below is
+// written into each plugin by `bun run sync` (sync-safe-clone.ts), verbatim into the TypeScript
+// plugins and with its two type annotations removed into OpenClaw's JavaScript one. `bun run check`
+// in every plugin, and `bun test` here, fail when any copy differs from this file.
+//
+// Edit the region here, never in a plugin, then run `bun run sync` in this directory.
+
+// BEGIN shared/safe-clone
+// Generated from plugins/shared/safe-clone.ts by `bun run sync`. Edit that file, not this block:
+// `bun run check` fails when the two differ.
+
+// How deep into a payload the serializer will walk before giving up.
+const maxDepth = 8
+
+// safeClone turns a live runtime payload into something JSON.stringify accepts.
+//
+// Runtimes hand plugins live objects, not plain data: AbortSignals, SDK class instances, parent
+// references, provider message objects, 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 (typeof value !== "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 }
+ // Match native JSON: an invalid Date is null, not a lost event.
+ if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
+
+ seen.add(value)
+ 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)) {
+ const cloned = safeClone(nested, depth + 1, seen)
+ if (cloned !== undefined) out[key] = cloned
+ }
+ return out
+ } finally {
+ seen.delete(value)
+ }
+}
+// END shared/safe-clone
+
+export { maxDepth, safeClone }
diff --git a/plugins/shared/sync-safe-clone.ts b/plugins/shared/sync-safe-clone.ts
new file mode 100644
index 00000000..17d7ace5
--- /dev/null
+++ b/plugins/shared/sync-safe-clone.ts
@@ -0,0 +1,151 @@
+// sync-safe-clone writes the shared serializer in safe-clone.ts into every plugin that runs it, and
+// checks that each one still matches.
+//
+// bun sync-safe-clone.ts write every plugin source and its embedded copy
+// bun sync-safe-clone.ts --check fail if any plugin source or embedded copy differs
+// bun sync-safe-clone.ts src/beacon.ts write one plugin source (a plugin's `bun run sync`)
+// bun sync-safe-clone.ts --check src/beacon.ts
+//
+// The plugins cannot import the serializer: each installs as one self-contained file its runtime
+// loads directly. So the region between the markers in safe-clone.ts is the source, and each plugin
+// carries a generated copy between the same markers. TypeScript plugins get the region verbatim.
+// OpenClaw's plugin is JavaScript, so its copy has the region's type annotations removed by the
+// exact line rewrites in jsRewrites below -- deliberately not a transpiler, whose output (comments
+// dropped, statements reflowed) would change with the Bun version and make the check flaky.
+
+import { existsSync, readFileSync, writeFileSync } from "node:fs"
+import { dirname, join, relative, resolve } from "node:path"
+
+export const beginMarker = "// BEGIN shared/safe-clone"
+export const endMarker = "// END shared/safe-clone"
+
+export const pluginsDir = resolve(import.meta.dir, "..")
+export const repoRoot = resolve(pluginsDir, "..")
+export const canonicalPath = join(import.meta.dir, "safe-clone.ts")
+const assetsDir = join(repoRoot, "cli/beacon/internal/endpoint/hooks/assets")
+
+// Every plugin that runs the shared serializer: its source and the copy embedded in the binary.
+// OpenCode is deliberately absent: it never serializes a live payload with safeClone, and its
+// structuredClone calls snapshot tool arguments for its own bookkeeping, where a depth limit or a
+// flattened Error would lose state the plugin reads back later.
+export const consumers = [
+ { plugin: "cline-beacon", source: "src/beacon.ts", embedded: "cline/beacon.ts" },
+ { plugin: "omo-beacon", source: "src/beacon.ts", embedded: "omo/beacon.ts" },
+ { plugin: "omp-beacon", source: "src/beacon.ts", embedded: "omp/beacon.ts" },
+ { plugin: "openclaw-beacon", source: "src/beacon.js", embedded: "openclaw/beacon.js" },
+ { plugin: "pi-beacon", source: "src/beacon.ts", embedded: "pi/beacon.ts" },
+ { plugin: "prime-beacon", source: "src/beacon.ts", embedded: "prime/beacon.ts" },
+].map((entry) => ({
+ ...entry,
+ sourcePath: join(pluginsDir, entry.plugin, entry.source),
+ embeddedPath: join(assetsDir, entry.embedded),
+}))
+
+// The only TypeScript in the region, and what it becomes in JavaScript. Each must match exactly one
+// line, so an edit that adds a type annotation anywhere else, or changes one of these lines, fails
+// the sync instead of writing TypeScript into a .js file.
+export const jsRewrites: ReadonlyArray<readonly [string, string]> = [
+ [
+ "function safeClone(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {",
+ "function safeClone(value, depth = 0, seen = new WeakSet()) {",
+ ],
+ [" const out: Record<string, unknown> = {}", " const out = {}"],
+]
+
+// extractBlock returns the region from the begin marker through the end marker, or throws when the
+// markers are missing, repeated, or out of order.
+export function extractBlock(source: string, label = "source"): string {
+ const { start, end } = blockBounds(source, label)
+ return source.slice(start, end)
+}
+
+function blockBounds(source: string, label: string): { start: number; end: number } {
+ const start = source.indexOf(beginMarker)
+ const endAt = source.indexOf(endMarker)
+ if (start < 0 || endAt < 0) {
+ throw new Error(`${label}: no "${beginMarker}" ... "${endMarker}" region`)
+ }
+ if (source.indexOf(beginMarker, start + 1) >= 0 || source.indexOf(endMarker, endAt + 1) >= 0) {
+ throw new Error(`${label}: the shared/safe-clone markers appear more than once`)
+ }
+ if (endAt < start) throw new Error(`${label}: "${endMarker}" comes before "${beginMarker}"`)
+ return { start, end: endAt + endMarker.length }
+}
+
+// toJavaScript applies jsRewrites to a TypeScript region.
+export function toJavaScript(block: string): string {
+ const lines = block.split("\n")
+ for (const [ts, js] of jsRewrites) {
+ const hits = lines.flatMap((line, index) => (line === ts ? [index] : []))
+ if (hits.length !== 1) {
+ throw new Error(
+ `safe-clone.ts: expected exactly one line ${JSON.stringify(ts)} to strip for JavaScript, ` +
+ `found ${hits.length}; update jsRewrites in sync-safe-clone.ts`,
+ )
+ }
+ lines[hits[0]] = js
+ }
+ return lines.join("\n")
+}
+
+// expectedBlock is the region a plugin file must carry, given the canonical region.
+export function expectedBlock(canonical: string, targetPath: string): string {
+ return targetPath.endsWith(".js") ? toJavaScript(canonical) : canonical
+}
+
+// replaceBlock returns source with its region replaced by block. Everything outside the markers is
+// left byte for byte as it was.
+export function replaceBlock(source: string, block: string, label = "source"): string {
+ const { start, end } = blockBounds(source, label)
+ return source.slice(0, start) + block + source.slice(end)
+}
+
+export function canonicalBlock(): string {
+ return extractBlock(readFileSync(canonicalPath, "utf8"), relative(repoRoot, canonicalPath))
+}
+
+// syncFile rewrites one plugin file's region, or in check mode returns a description of the drift.
+// Returns undefined when the file already matches.
+export function syncFile(path: string, canonical: string, check: boolean): string | undefined {
+ const label = relative(repoRoot, path)
+ const source = readFileSync(path, "utf8")
+ const next = replaceBlock(source, expectedBlock(canonical, path), label)
+ if (next === source) return undefined
+ if (check) return `${label}: the shared/safe-clone block differs from plugins/shared/safe-clone.ts`
+ writeFileSync(path, next)
+ return undefined
+}
+
+function main(argv: string[]): number {
+ const check = argv.includes("--check")
+ const files = argv.filter((arg) => arg !== "--check").map((arg) => resolve(arg))
+ const targets = files.length > 0
+ ? files
+ : consumers.flatMap(({ sourcePath, embeddedPath }) => [sourcePath, embeddedPath])
+
+ const canonical = canonicalBlock()
+ const drift: string[] = []
+ for (const path of targets) {
+ if (!existsSync(path)) {
+ drift.push(`${relative(repoRoot, path)}: no such file`)
+ continue
+ }
+ try {
+ const problem = syncFile(path, canonical, check)
+ if (problem) drift.push(problem)
+ } catch (err) {
+ drift.push(err instanceof Error ? err.message : String(err))
+ }
+ }
+ if (drift.length === 0) return 0
+ for (const line of drift) console.error(line)
+ if (check) {
+ console.error(
+ `Edit the serializer only in plugins/shared/safe-clone.ts, then run \`bun run sync\` in ` +
+ `${relative(process.cwd(), dirname(canonicalPath)) || "."} to rewrite every plugin.`,
+ )
+ }
+ return 1
+}
+
+if (import.meta.main) process.exit(main(process.argv.slice(2)))