@xtrom-ai/sdk 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +185 -2
  3. package/dist/allowances.js +74 -0
  4. package/dist/cli.js +268 -0
  5. package/dist/credentials.js +37 -0
  6. package/dist/directive.js +57 -0
  7. package/dist/enforce.js +972 -0
  8. package/dist/index.js +31 -0
  9. package/dist/inspect.js +135 -0
  10. package/dist/local/agents.js +378 -0
  11. package/dist/local/appliers.js +61 -0
  12. package/dist/local/browser.js +135 -0
  13. package/dist/local/discover.js +154 -0
  14. package/dist/local/hook.js +778 -0
  15. package/dist/local/install.js +238 -0
  16. package/dist/local/inventory.js +219 -0
  17. package/dist/local/reasonText.js +29 -0
  18. package/dist/local/shipper.js +251 -0
  19. package/dist/local/spool.js +178 -0
  20. package/dist/local/updateKeys.js +3 -0
  21. package/dist/local/updater.js +224 -0
  22. package/dist/local/view.js +110 -0
  23. package/dist/memory.js +172 -0
  24. package/dist/reporter.js +336 -0
  25. package/dist/session.js +439 -0
  26. package/dist/version.js +2 -0
  27. package/dist/workspace.js +72 -0
  28. package/package.json +23 -4
  29. package/src/allowances.ts +74 -0
  30. package/src/cli.ts +268 -0
  31. package/src/credentials.ts +37 -0
  32. package/src/directive.ts +57 -0
  33. package/src/enforce.ts +972 -0
  34. package/src/index.ts +31 -0
  35. package/src/inspect.ts +135 -0
  36. package/src/local/agents.ts +378 -0
  37. package/src/local/appliers.ts +61 -0
  38. package/src/local/browser.ts +135 -0
  39. package/src/local/discover.ts +154 -0
  40. package/src/local/hook.ts +778 -0
  41. package/src/local/install.ts +238 -0
  42. package/src/local/inventory.ts +219 -0
  43. package/src/local/reasonText.ts +29 -0
  44. package/src/local/shipper.ts +251 -0
  45. package/src/local/spool.ts +178 -0
  46. package/src/local/updateKeys.ts +3 -0
  47. package/src/local/updater.ts +224 -0
  48. package/src/local/view.ts +110 -0
  49. package/src/memory.ts +172 -0
  50. package/src/reporter.ts +336 -0
  51. package/src/session.ts +439 -0
  52. package/src/version.ts +2 -0
  53. package/src/workspace.ts +72 -0
@@ -0,0 +1,251 @@
1
+ // Background decision shipper — drains the local spool to the control plane. Port of
2
+ // xtrom_sdk/local/shipper.py. Spawned detached by the coding-agent hook (see spool.ensureShipper),
3
+ // it outlives any single short-lived hook process. Exactly one runs per machine (single-instance
4
+ // lock); it:
5
+ // 1. acquires the lock (a fresh lock ⇒ another shipper is draining, so exit),
6
+ // 2. drains spooled events in batches via reporter.postEvents — the SAME delivery path as the
7
+ // in-process SDK, so classification/retry/backoff are identical,
8
+ // 3. deletes a spool file ONLY after the control plane accepts (ok) or definitively rejects it; a
9
+ // transient failure KEEPS the file (durable — redelivered next run), an auth failure stops,
10
+ // 4. emits a liveness heartbeat every interval so the console's Enforcement-health screen can tell
11
+ // "no attacks" from "enforcement stopped",
12
+ // 5. idle-exits after a quiet grace period, releasing the lock.
13
+ import { closeSync, openSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs";
14
+ import { fileURLToPath } from "node:url";
15
+ import { homedir, hostname } from "node:os";
16
+ import { dirname, join } from "node:path";
17
+ import { INGEST_PATH, postEvents, requireSecureUrl, type WireEvent } from "../reporter.ts";
18
+ import { SDK_VERSION } from "../version.ts";
19
+ import { deviceLabel, paths, readConfig, resolveMode, writeWorkspaceMode, type LocalPaths } from "./hook.ts";
20
+ import { hooked } from "./install.ts";
21
+ import { buildInventory, inventoryFingerprint, type Inventory } from "./inventory.ts";
22
+ import type { WorkspaceMode } from "../workspace.ts";
23
+ import { ensureBase, instanceId, ledger, lockPath, LOCK_STALE_MS, recordDropped, spoolFiles } from "./spool.ts";
24
+ import { pinnedKeys, runUpdateCheck } from "./updater.ts";
25
+
26
+ export const BATCH = 50;
27
+ export const POLL_MS = 1000;
28
+ export const IDLE_EXIT_MS = 30_000;
29
+ export const HEARTBEAT_INTERVAL_MS = 60_000;
30
+ export const MAX_RETRIES = 6;
31
+ export const HEARTBEAT_MAX_IDENTITIES = 200;
32
+ export const BACKOFF_MIN_MS = 2_000;
33
+ export const BACKOFF_MAX_MS = 300_000;
34
+ const MEDIATOR = "sdk-ts";
35
+
36
+ function creds(p: LocalPaths): [string | undefined, string | undefined] {
37
+ const cfg = readConfig(p);
38
+ return [process.env.XTROM_CONTROL_PLANE_URL || (cfg.control_plane_url as string | undefined),
39
+ process.env.XTROM_TOKEN || (cfg.token as string | undefined)];
40
+ }
41
+
42
+ /** Single-instance guard via O_CREAT|O_EXCL ('wx'); a stale lock (crashed shipper) is stolen. Returns
43
+ * false when a live shipper already holds it. */
44
+ export function acquireLock(p: LocalPaths, now = Date.now()): boolean {
45
+ ensureBase(p);
46
+ const lp = lockPath(p);
47
+ for (let i = 0; i < 2; i++) {
48
+ try {
49
+ const fd = openSync(lp, "wx", 0o600);
50
+ try { writeSync(fd, String(process.pid)); } finally { closeSync(fd); }
51
+ return true;
52
+ } catch (e) {
53
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") return false;
54
+ let age = Infinity;
55
+ try { age = now - statSync(lp).mtimeMs; } catch { /* vanished: retry the create */ }
56
+ if (age < LOCK_STALE_MS) return false; // a live shipper holds it
57
+ try { unlinkSync(lp); } catch { return false; } // steal the dead lock, then retry
58
+ }
59
+ }
60
+ return false;
61
+ }
62
+
63
+ export function refreshLock(p: LocalPaths): void {
64
+ try { const t = new Date(); utimesSync(lockPath(p), t, t); } catch { /* best-effort */ }
65
+ }
66
+
67
+ export function releaseLock(p: LocalPaths): void {
68
+ try { rmSync(lockPath(p), { force: true }); } catch { /* best-effort */ }
69
+ }
70
+
71
+ function isoNow(now: number): string {
72
+ return new Date(now).toISOString().replace(/\.\d{3}Z$/, "Z");
73
+ }
74
+
75
+ function heartbeat(instance: string, counts: Record<string, number>, ids: Set<string>, now: number, mode: string, status?: string, modeSource?: string, accounting: Record<string, unknown> = {}): WireEvent {
76
+ const hb: WireEvent = {
77
+ kind: "heartbeat", mediator: MEDIATOR, mediator_version: SDK_VERSION,
78
+ instance_id: instance, interval_s: HEARTBEAT_INTERVAL_MS / 1000,
79
+ ts: isoNow(now), counts: { ...counts }, dropped: 0, mode,
80
+ ...accounting, // stream / last_seq / dropped_total / pending (see spool.ledger)
81
+ };
82
+ if (modeSource) hb.mode_source = modeSource; // dev_override / env_ignored flag a loosening attempt
83
+ if (ids.size) hb.identities = [...ids].sort().slice(0, HEARTBEAT_MAX_IDENTITIES);
84
+ // A clean idle-exit sends status="stopped" so the console retires this (stable) point instead of
85
+ // paging it as "enforcement stopped reporting" — going quiet is normal for an ephemeral hook.
86
+ if (status) hb.status = status;
87
+ return hb;
88
+ }
89
+
90
+ /** Console-driven SDK self-update. INERT unless a release key is pinned in this build —
91
+ * runUpdateCheck short-circuits before any network when the key is empty, so by default this is a
92
+ * no-op with zero update traffic. Never throws into the shipper. */
93
+ async function updateCheck(p: LocalPaths, baseUrl: string, token: string): Promise<void> {
94
+ try {
95
+ if (!Object.keys(pinnedKeys()).length) return;
96
+ const { RuntimeSwapApplier, systemTarExtract } = await import("./appliers.ts");
97
+ const { deployRuntime } = await import("./install.ts");
98
+ const runtimeTarget = dirname(dirname(fileURLToPath(import.meta.url))); // …/runtime/sdk-ts
99
+ const auth = { authorization: "Bearer " + token, "x-xtrom-api-version": "1" };
100
+ const directiveUrl = baseUrl.replace(/\/+$/, "") + "/v1/update-directive";
101
+ await runUpdateCheck({
102
+ mediator: MEDIATOR, currentVersion: SDK_VERSION, stableId: hostname(),
103
+ trustPath: join(p.base, "update-trust.json"), // revocations + newest manifest seen
104
+ deps: {
105
+ fetchDirective: async () => {
106
+ const res = await fetch(directiveUrl, { headers: auth, redirect: "manual", signal: AbortSignal.timeout(10_000) });
107
+ if (!res.ok) throw new Error(`update directive: ${res.status}`); // a redirect never carries the token
108
+ return res.json();
109
+ },
110
+ // The signed manifest + artifact are PUBLIC signed objects — fetched with NO token, so the
111
+ // enrollment token is never sent to the (operator-set) pkgs host.
112
+ fetchText: async (u) => (await fetch(u, { signal: AbortSignal.timeout(15_000) })).text(),
113
+ fetchArtifact: async (u) => Buffer.from(await (await fetch(u, { signal: AbortSignal.timeout(60_000) })).arrayBuffer()),
114
+ applier: new RuntimeSwapApplier({
115
+ extract: systemTarExtract, deploy: deployRuntime,
116
+ runtimeTarget, tmpRoot: join(p.base, "updates"),
117
+ }),
118
+ },
119
+ });
120
+ } catch { /* an update check must never break the shipper */ }
121
+ }
122
+
123
+ const INVENTORY_RESEND_MS = 24 * 3600 * 1000;
124
+ const INVENTORY_CHECK_MS = 3600 * 1000; // configs can be large (~/.claude.json): look for changes at most hourly
125
+
126
+ /** The machine's inventory (docs/design/LOCAL-INVENTORY.md), sent when it changed or a day passed. A refusal
127
+ * (an older control plane) is remembered too, so it is retried daily, not on every run. Never throws. */
128
+ async function sendInventory(p: LocalPaths, full: string, token: string, instance: string, post: typeof postEvents,
129
+ nowMs: number, build: () => Inventory, hear: (wm: WorkspaceMode) => void): Promise<void> {
130
+ try {
131
+ const statePath = join(p.base, "inventory-sent.json");
132
+ let prev: { fp?: unknown; at?: unknown; checked?: unknown } = {};
133
+ try { prev = JSON.parse(readFileSync(statePath, "utf8")); } catch { /* first send */ }
134
+ if (typeof prev.checked === "number" && nowMs - prev.checked >= 0 && nowMs - prev.checked < INVENTORY_CHECK_MS) return;
135
+ const inv = build();
136
+ const fp = inventoryFingerprint(inv);
137
+ if (prev.fp === fp && typeof prev.at === "number" && nowMs - prev.at >= 0 && nowMs - prev.at < INVENTORY_RESEND_MS) {
138
+ writeFileSync(statePath, JSON.stringify({ ...prev, checked: nowMs }), { mode: 0o600 });
139
+ return;
140
+ }
141
+ const ev = { kind: "local_inventory", mediator: MEDIATOR, mediator_version: SDK_VERSION, instance_id: instance,
142
+ machine: deviceLabel(), ts: isoNow(nowMs), ...inv } as unknown as WireEvent;
143
+ const [result] = await post(full, token, [ev], undefined, undefined, hear);
144
+ if (result === "ok" || result === "reject") writeFileSync(statePath, JSON.stringify({ fp, at: nowMs, checked: nowMs }), { mode: 0o600 });
145
+ } catch { /* the inventory is advisory: it never breaks the shipper */ }
146
+ }
147
+
148
+ export interface ShipperDeps {
149
+ now?: () => number;
150
+ sleep?: (ms: number) => Promise<void>;
151
+ post?: typeof postEvents;
152
+ inventory?: () => Inventory;
153
+ }
154
+
155
+ /** Drain the spool until idle, then exit. Deps are injectable for tests. Never throws. */
156
+ export async function run(p: LocalPaths = paths(), deps: ShipperDeps = {}): Promise<number> {
157
+ const now = deps.now ?? Date.now;
158
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
159
+ const post = deps.post ?? postEvents;
160
+ const [url, token] = creds(p);
161
+ if (!url || !token) return 0;
162
+ let full: string;
163
+ try { full = requireSecureUrl(url).replace(/\/+$/, "") + INGEST_PATH; } catch { return 0; }
164
+ if (!acquireLock(p, now())) return 0;
165
+ const instance = instanceId(p.base); // STABLE per install — one enforcement point, not one per process
166
+ let [mode, modeSource] = resolveMode(p);
167
+ // The workspace mode rides on every ingest answer: save it for the hook, and report what applies.
168
+ const hear = (wm: WorkspaceMode): void => {
169
+ writeWorkspaceMode(p, wm, now());
170
+ [mode, modeSource] = resolveMode(p, now());
171
+ };
172
+ await updateCheck(p, url, token); // inert unless a release key is pinned in this build
173
+ await sendInventory(p, full, token, instance, post, now(),
174
+ deps.inventory ?? (() => buildInventory({ home: homedir(), env: process.env, hooked: (a) => hooked(a) })), hear);
175
+ let counts: Record<string, number> = { allow: 0, step_up: 0, block: 0 };
176
+ let ids = new Set<string>();
177
+ let hbNext = now(); // beat promptly so even a <60s burst registers one live heartbeat
178
+ let attempt = 0;
179
+ let idle = 0;
180
+ let broke = false; // a break (token revoked / retries exhausted) is NOT a clean exit
181
+ try {
182
+ while (idle < IDLE_EXIT_MS) {
183
+ refreshLock(p);
184
+ const files = spoolFiles(p).slice(0, BATCH);
185
+ if (files.length) {
186
+ const events: WireEvent[] = [];
187
+ const good: string[] = [];
188
+ for (const f of files) {
189
+ try { events.push(JSON.parse(readFileSync(f, "utf8"))); good.push(f); }
190
+ catch { unlink(f); recordDropped(p); } // corrupt spool file → drop it, never wedge the queue
191
+ }
192
+ if (!events.length) { idle = 0; continue; }
193
+ const [result, retryAfter] = await post(full, token, events, undefined, undefined, hear);
194
+ if (result === "ok" || result === "reject") {
195
+ for (const f of good) unlink(f);
196
+ if (result === "reject") recordDropped(p, good.length); // definitively refused: these never arrive
197
+ idle = 0; attempt = 0;
198
+ if (result === "ok") {
199
+ for (const ev of events) {
200
+ const v = String(ev.verdict ?? "").toLowerCase();
201
+ if (v in counts) counts[v] += 1;
202
+ const id = ev.identity;
203
+ if (typeof id === "string" && id && ids.size < HEARTBEAT_MAX_IDENTITIES) ids.add(id);
204
+ }
205
+ }
206
+ } else if (result === "pause") {
207
+ broke = true; break; // token revoked/rotated: stop; a later run retries the kept files
208
+ } else { // transient: keep the files and back off
209
+ attempt += 1;
210
+ if (attempt > MAX_RETRIES) { broke = true; break; }
211
+ const delay = retryAfter ?? Math.min(BACKOFF_MAX_MS, BACKOFF_MIN_MS * 2 ** (attempt - 1));
212
+ await sleep(Math.min(delay, 30_000));
213
+ }
214
+ } else {
215
+ idle += POLL_MS;
216
+ await sleep(POLL_MS);
217
+ }
218
+ if (now() >= hbNext) {
219
+ await post(full, token, [heartbeat(instance, counts, ids, now(), mode, undefined, modeSource, ledger(p))],
220
+ undefined, undefined, hear);
221
+ counts = { allow: 0, step_up: 0, block: 0 };
222
+ ids = new Set();
223
+ hbNext = now() + HEARTBEAT_INTERVAL_MS;
224
+ }
225
+ }
226
+ if (!broke) {
227
+ // Clean idle-exit: tell the console so this point goes "stopped" rather than aging into a stale
228
+ // "enforcement stopped reporting" page. (On a break a final POST would only fail.)
229
+ try { await post(full, token, [heartbeat(instance, counts, ids, now(), mode, "stopped", modeSource, ledger(p))]); }
230
+ catch { /* best effort */ }
231
+ }
232
+ } finally {
233
+ releaseLock(p);
234
+ }
235
+ return 0;
236
+ }
237
+
238
+ function unlink(f: string): void {
239
+ try { unlinkSync(f); } catch { /* raced with another run */ }
240
+ }
241
+
242
+ export async function main(argv: string[] = []): Promise<number> {
243
+ try {
244
+ const i = argv.indexOf("--home");
245
+ const base = i >= 0 ? argv[i + 1] : undefined;
246
+ const p: LocalPaths | undefined = base
247
+ ? { base, sessions: join(base, "sessions"), audit: join(base, "audit.jsonl"), config: join(base, "config.json") }
248
+ : undefined;
249
+ return await run(p);
250
+ } catch { return 0; }
251
+ }
@@ -0,0 +1,178 @@
1
+ // Local decision spool + detached background-shipper launcher. Port of xtrom_sdk/local/spool.py.
2
+ //
3
+ // A coding-agent hook is a short-lived process: it runs for one tool call and exits. A fresh remote
4
+ // HTTPS round-trip (cold DNS + TLS) routinely outlives it, so posting inline either blocks the tool
5
+ // call or is killed mid-flight when the process exits. Delivery is therefore DECOUPLED from the hook:
6
+ // • the hook calls spoolEvent() — a few-millisecond local write of ONE metadata event to its own
7
+ // file under the local spool dir (never blocks, never touches the network), then
8
+ // • ensureShipper() makes sure a single detached `shipper` process is running; it drains the spool
9
+ // to the control plane with retry/backoff + liveness heartbeats, on its own lifetime.
10
+ //
11
+ // The spool is durable across hook-process exits and reboots. Same tamper-protected local home as the
12
+ // rest of the hook (see hook.paths). Cross-platform: POSIX detaches via { detached: true } +
13
+ // start-new-session; Windows keeps the child alive with { detached: true, windowsHide: true }.
14
+ import { spawn } from "node:child_process";
15
+ import { createHash, randomBytes } from "node:crypto";
16
+ import { chmodSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync, writeSync } from "node:fs";
17
+ import { hostname } from "node:os";
18
+ import { dirname, extname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { devOverrides, type LocalPaths } from "./hook.ts";
21
+
22
+ export const SPOOL_DIRNAME = "spool";
23
+ export const LOCK_NAME = "shipper.lock";
24
+ // Backpressure bound: match the reporter's in-memory queue. Past this the hook drops (enforcement
25
+ // first — a telemetry backlog must never wedge the agent); the shipper reports the loss via `dropped`.
26
+ export let MAX_SPOOL_FILES = 10_000;
27
+ export function setMaxSpoolFiles(n: number) { MAX_SPOOL_FILES = n; } // tests
28
+ // A lock whose mtime is older than this is assumed dead (crashed shipper) and may be stolen. The live
29
+ // shipper touches it every loop (< 1s), so this only trips on an actual crash/kill.
30
+ export const LOCK_STALE_MS = 120_000;
31
+ const SAFE_HOST = /[^A-Za-z0-9._-]/g;
32
+
33
+ export const spoolDir = (p: LocalPaths) => join(p.base, SPOOL_DIRNAME);
34
+ export const lockPath = (p: LocalPaths) => join(p.base, LOCK_NAME);
35
+
36
+ function chmodQuiet(path: string, mode: number) {
37
+ try { chmodSync(path, mode); } catch { /* non-POSIX fs */ }
38
+ }
39
+
40
+ function ensureSpool(p: LocalPaths): string {
41
+ const d = spoolDir(p);
42
+ mkdirSync(d, { recursive: true });
43
+ chmodQuiet(p.base, 0o700);
44
+ chmodQuiet(d, 0o700);
45
+ return d;
46
+ }
47
+
48
+ /** Spooled event files oldest-first (names begin with a zero-padded epoch-ms → lexical == chronological). */
49
+ export function spoolFiles(p: LocalPaths): string[] {
50
+ try {
51
+ return readdirSync(spoolDir(p)).filter((n) => n.endsWith(".json")).sort().map((n) => join(spoolDir(p), n));
52
+ } catch { return []; }
53
+ }
54
+
55
+ // Delivery accounting (parity with the Python spool): hook processes are short-lived and concurrent,
56
+ // so the count lives on disk. Each spooled event appends one byte to seq.log and takes the resulting
57
+ // size as its seq; an event that couldn't be spooled, or that the control plane rejected, appends to
58
+ // dropped.log. The shipper's heartbeat reports both plus the files still waiting.
59
+ export const SEQ_LOG = "seq.log";
60
+ export const DROPPED_LOG = "dropped.log";
61
+ export const STREAM_FILE = "stream";
62
+
63
+ function append(path: string, n = 1): number {
64
+ const fd = openSync(path, "a", 0o600);
65
+ try {
66
+ writeSync(fd, ".".repeat(n));
67
+ return fstatSync(fd).size;
68
+ } finally { closeSync(fd); }
69
+ }
70
+
71
+ /** This install's delivery-accounting stream (created once; concurrent creators agree). */
72
+ export function streamId(p: LocalPaths): string {
73
+ const f = join(p.base, STREAM_FILE);
74
+ try { writeFileSync(f, randomBytes(8).toString("hex"), { flag: "wx", mode: 0o600 }); } catch { /* exists */ }
75
+ const v = readFileSync(f, "utf8").trim();
76
+ return /^[a-f0-9]{16,32}$/.test(v) ? v : "";
77
+ }
78
+
79
+ /** Count events that will never reach the control plane (shed or rejected). Never throws. */
80
+ export function recordDropped(p: LocalPaths, n = 1): void {
81
+ if (n <= 0) return;
82
+ try { append(join(p.base, DROPPED_LOG), n); } catch { /* best-effort */ }
83
+ }
84
+
85
+ /** Heartbeat accounting: {stream, last_seq, dropped_total, pending}, or {} if unavailable. */
86
+ export function ledger(p: LocalPaths): Record<string, unknown> {
87
+ try {
88
+ const stream = streamId(p);
89
+ if (!stream) return {};
90
+ const size = (name: string) => { try { return statSync(join(p.base, name)).size; } catch { return 0; } };
91
+ return { stream, last_seq: size(SEQ_LOG), dropped_total: size(DROPPED_LOG), pending: spoolFiles(p).length };
92
+ } catch { return {}; }
93
+ }
94
+
95
+ /** Write ONE metadata event to its own spool file (atomic, 0600). Returns false (dropped) if the spool
96
+ * is at its bound — never blocks and never throws into the hook's decision path. */
97
+ export function spoolEvent(p: LocalPaths, event: Record<string, unknown>, now = Date.now()): boolean {
98
+ let numbered = false;
99
+ try {
100
+ const d = ensureSpool(p);
101
+ // Number the event first, so even one that is shed below is accounted for.
102
+ const stream = streamId(p);
103
+ if (stream) {
104
+ event = { ...event, stream, seq: append(join(p.base, SEQ_LOG)) };
105
+ numbered = true;
106
+ }
107
+ if (readdirSync(d).filter((n) => n.endsWith(".json")).length >= MAX_SPOOL_FILES) {
108
+ if (numbered) recordDropped(p);
109
+ return false;
110
+ }
111
+ const name = `${String(now).padStart(15, "0")}-${process.pid}-${randomBytes(4).toString("hex")}.json`;
112
+ const final = join(d, name);
113
+ const tmp = `${final}.new`;
114
+ writeFileSync(tmp, JSON.stringify(event), { mode: 0o600 });
115
+ renameSync(tmp, final);
116
+ chmodQuiet(final, 0o600);
117
+ return true;
118
+ } catch {
119
+ if (numbered) recordDropped(p);
120
+ return false;
121
+ }
122
+ }
123
+
124
+ /** True if a lock exists and is fresh (a live shipper is draining). A stale lock (crashed shipper)
125
+ * reads as not-running so ensureShipper respawns — the shipper's own lock steal makes that safe. */
126
+ export function shipperRunning(p: LocalPaths, now = Date.now()): boolean {
127
+ try { return now - statSync(lockPath(p)).mtimeMs < LOCK_STALE_MS; } catch { return false; }
128
+ }
129
+
130
+ /** Absolute path of the cli entry in the same (installed) runtime this module runs from, plus the node
131
+ * flags it needs (type-stripping only when running a .ts checkout). */
132
+ function shipperCommand(): [string, string[]] {
133
+ const here = fileURLToPath(import.meta.url); // .../runtime/sdk-ts/local/spool.(js|ts)
134
+ const ext = extname(here);
135
+ const cli = join(dirname(dirname(here)), `cli${ext}`); // .../runtime/sdk-ts/cli.(js|ts)
136
+ const flags = ext === ".ts" ? ["--experimental-strip-types", "--no-warnings"] : [];
137
+ return [cli, flags];
138
+ }
139
+
140
+ /** Spawn a detached shipper unless one is already running. Best-effort: a failure just means delivery
141
+ * waits for the next hook call. Double-spawn is harmless — the second shipper can't take the lock and
142
+ * exits immediately. */
143
+ export function ensureShipper(p: LocalPaths): void {
144
+ try {
145
+ if (shipperRunning(p)) return;
146
+ if (process.env.XTROM_SHIPPER_DISABLE && devOverrides()) return; // tests / debugging only
147
+ const [cli, flags] = shipperCommand();
148
+ // The base dir goes as `--home` (an env var would need XTROM_DEV_OVERRIDES).
149
+ const child = spawn(process.execPath, [...flags, cli, "__ship", "--home", p.base], {
150
+ detached: true,
151
+ stdio: "ignore",
152
+ windowsHide: true,
153
+ cwd: p.base,
154
+ env: { ...process.env },
155
+ });
156
+ child.unref(); // the agent process must not wait on the shipper
157
+ } catch { /* delivery just waits for the next hook call */ }
158
+ }
159
+
160
+ /** STABLE per-install heartbeat id — ONE enforcement point per machine/install, NOT per shipper
161
+ * process. The shipper is single-instance (lock-guarded), so a restarted shipper reuses the same
162
+ * identity; a pid+random id made a single agent show up as many churning "stale" points in fleet
163
+ * health. Keyed on host + the local-home path. Canary cohorting uses stableId() separately. */
164
+ export function instanceId(base?: string): string {
165
+ let host = "";
166
+ try { host = hostname(); } catch { /* sandboxed */ }
167
+ const h = host.replace(SAFE_HOST, "-").slice(0, 40) || "sdk";
168
+ const home = base ?? (devOverrides() ? process.env.XTROM_LOCAL_HOME : undefined) ?? h;
169
+ const suffix = createHash("sha256").update(`${h}|${home}`).digest("hex").slice(0, 8);
170
+ return `${h}-${suffix}`.slice(0, 64);
171
+ }
172
+
173
+ // Internal, used by the shipper's lock acquisition.
174
+ export function ensureBase(p: LocalPaths) {
175
+ mkdirSync(p.base, { recursive: true });
176
+ chmodQuiet(p.base, 0o700);
177
+ if (!existsSync(spoolDir(p))) ensureSpool(p);
178
+ }
@@ -0,0 +1,3 @@
1
+ // GENERATED by product/scripts/bake_update_key.py — do not edit. The release keyring {kid: PEM}: public halves of
2
+ // the ES256 keys that sign update manifests. Empty verifies nothing, so auto-update stays off until a key is baked.
3
+ export const RELEASE_KEYS: Record<string, string> = {};
@@ -0,0 +1,224 @@
1
+ // Console-driven, SIGNED self-update of the local hook runtime. Security-critical: this is
2
+ // the one place the client fetches and executes new code, so the enforcement tool must not become the
3
+ // hijack vector. The trust model (see also updater.py — byte-for-byte the same):
4
+ //
5
+ // 1. DIRECTIVE ≠ ARTIFACT. The control plane only ever tells the client a *target version* + policy
6
+ // + (approve mode) an approval. The client fetches the artifact from the trusted distribution and
7
+ // verifies it LOCALLY against a public key PINNED IN THIS BUILD — never a key or bytes from the
8
+ // control plane. So a fully-compromised control plane / stolen token can at worst pin you to a
9
+ // validly-signed, published release — never arbitrary code.
10
+ // 2. VERIFY-THEN-PARSE. The manifest is signed as RAW BYTES (ES256/DER). We verify the signature over
11
+ // the exact received bytes with the pinned key BEFORE parsing — no fragile cross-language JSON
12
+ // canonicalization, and malformed/hostile JSON never reaches a parser until it's authenticated.
13
+ // 3. HASH PINNING. The signed manifest pins each artifact's SHA-256; the downloaded bytes are checked
14
+ // against it before anything is applied.
15
+ // 4. FORWARD-ONLY. The client never "updates" to a version <= its current one (anti-rollback).
16
+ // 5. FAIL-CLOSED. Any verification/hash/apply failure keeps the OLD working runtime — an update can
17
+ // never disable enforcement. The Applier does an atomic swap with a self-test + rollback.
18
+ //
19
+ // Dependency note: Node verifies ES256 with the stdlib `node:crypto` (zero extra deps). The Python port
20
+ // needs `cryptography` as an OPTIONAL extra (stdlib has no asymmetric verify); absent → auto-apply is
21
+ // disabled, fail-closed, and the console still surfaces "update available".
22
+ import { createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
23
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
24
+ import { RELEASE_KEYS } from "./updateKeys.ts";
25
+
26
+ export type UpdatePolicy = "off" | "approve" | "auto";
27
+
28
+ export interface Artifact { version: string; url: string; sha256: string }
29
+ /** issued_at: epoch seconds (freeze/rollback guard); revoked_kids: keys this manifest revokes. */
30
+ export interface Manifest { schema: number; issued_at?: number; revoked_kids?: string[]; artifacts: Record<string, Artifact>; _kid?: string }
31
+ /** The signed wrapper served at the pkgs index: base64 payload (the raw manifest JSON) + base64 DER sig,
32
+ * plus the `kid` of the pinned key that signed it. */
33
+ export interface SignedManifest { payload: string; sig: string; alg?: string; kid: string }
34
+ /** The client's update-trust state, kept in the local home: revoked kids + newest issued_at accepted. */
35
+ export interface UpdateTrust { revoked: string[]; last_issued_at: number }
36
+
37
+ // The pinned release KEYRING {kid: PEM} (updateKeys.ts, written by scripts/bake_update_key.py; parity with
38
+ // updater.py). Rotation = ship a build pinning old + new keys, then sign with the new kid; a manifest signed by
39
+ // a trusted key may revoke others (see nextTrust). XTROM_UPDATE_KEYS_JSON replaces it for tests and staging only.
40
+ export const PINNED_UPDATE_KEYS: Record<string, string> = (() => {
41
+ let ring: unknown = RELEASE_KEYS;
42
+ try {
43
+ const override = JSON.parse(process.env.XTROM_UPDATE_KEYS_JSON || "null");
44
+ if (override && typeof override === "object") ring = override;
45
+ } catch { /* malformed override → the baked keyring */ }
46
+ return Object.fromEntries(Object.entries(ring as Record<string, unknown>)
47
+ .filter(([k, v]) => k && typeof v === "string" && v)) as Record<string, string>;
48
+ })();
49
+
50
+ /** The keyring to verify with: explicit `keys`, else the build's. */
51
+ export function pinnedKeys(keys?: Record<string, string>): Record<string, string> {
52
+ return { ...(keys ?? PINNED_UPDATE_KEYS) };
53
+ }
54
+
55
+ export function loadTrust(path?: string): UpdateTrust {
56
+ try {
57
+ const t = JSON.parse(readFileSync(path as string, "utf8"));
58
+ return { revoked: [...new Set((t.revoked ?? []).map(String))].sort() as string[], last_issued_at: Number.parseInt(t.last_issued_at, 10) || 0 };
59
+ } catch { return { revoked: [], last_issued_at: 0 }; }
60
+ }
61
+
62
+ export function saveTrust(path: string | undefined, trust: UpdateTrust): void {
63
+ if (!path) return;
64
+ try { writeFileSync(path + ".new", JSON.stringify(trust), { mode: 0o600 }); renameSync(path + ".new", path); } catch { /* best-effort */ }
65
+ }
66
+
67
+ /** Trust after accepting `m`: its revocations added (never its own signing kid), newest issued_at kept.
68
+ * Monotonic — nothing is ever un-revoked. */
69
+ export function nextTrust(trust: UpdateTrust | undefined, m: Manifest): UpdateTrust {
70
+ const t = trust ?? { revoked: [], last_issued_at: 0 };
71
+ const add = (Array.isArray(m.revoked_kids) ? m.revoked_kids : []).filter((k) => typeof k === "string" && k !== (m._kid ?? ""));
72
+ return { revoked: [...new Set([...t.revoked, ...add])].sort(), last_issued_at: Math.max(t.last_issued_at, Number.isInteger(m.issued_at) ? (m.issued_at as number) : 0) };
73
+ }
74
+
75
+ /** Lenient dotted-numeric compare — matches mediators.version_behind on the control plane. */
76
+ export function versionTuple(v: string): number[] {
77
+ return String(v || "").split(".").map((p) => {
78
+ let d = "";
79
+ for (const ch of p) { if (ch >= "0" && ch <= "9") d += ch; else break; }
80
+ return d ? parseInt(d, 10) : 0;
81
+ });
82
+ }
83
+ export function versionBehind(reported: string, target: string): boolean {
84
+ if (!reported || !target) return false;
85
+ const a = versionTuple(reported), b = versionTuple(target);
86
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
87
+ const x = a[i] ?? 0, y = b[i] ?? 0;
88
+ if (x !== y) return x < y;
89
+ }
90
+ return false;
91
+ }
92
+
93
+ /** Verify the signed wrapper against the pinned keyring, THEN parse. Returns the Manifest (with `_kid`)
94
+ * or null (never throws, never parses unauthenticated bytes). No pinned key, an unknown or revoked kid,
95
+ * or an issued_at older than one already accepted → null (fail-closed). */
96
+ export function verifyManifest(signedJson: string, opts: { keys?: Record<string, string>; trust?: UpdateTrust } = {}): Manifest | null {
97
+ try {
98
+ const ring = pinnedKeys(opts.keys);
99
+ if (!Object.keys(ring).length) return null; // no pinned key → verify nothing, apply nothing
100
+ const wrapper = JSON.parse(signedJson) as SignedManifest;
101
+ if (!wrapper || typeof wrapper.payload !== "string" || typeof wrapper.sig !== "string") return null;
102
+ const kid = wrapper.kid;
103
+ if (typeof kid !== "string" || !kid || !Object.hasOwn(ring, kid)) return null; // unknown key → refuse
104
+ const trust = opts.trust ?? { revoked: [], last_issued_at: 0 };
105
+ if (trust.revoked.includes(kid)) return null; // a revoked key never signs again
106
+ const payload = Buffer.from(wrapper.payload, "base64");
107
+ const sig = Buffer.from(wrapper.sig, "base64");
108
+ const key = createPublicKey(ring[kid]);
109
+ if (!cryptoVerify("sha256", payload, key, sig)) return null; // ES256 over the RAW bytes (DER sig)
110
+ const m = JSON.parse(payload.toString("utf8")) as Manifest; // verify-then-parse
111
+ if (!m || typeof m !== "object" || typeof m.artifacts !== "object") return null;
112
+ const issued = m.issued_at ?? 0;
113
+ if (!Number.isInteger(issued) || issued < trust.last_issued_at) return null; // older than accepted → replay
114
+ return { ...m, _kid: kid };
115
+ } catch {
116
+ return null; // any crypto/parse error → fail closed
117
+ }
118
+ }
119
+
120
+ export function sha256Hex(bytes: Buffer | Uint8Array): string {
121
+ return createHash("sha256").update(bytes).digest("hex");
122
+ }
123
+
124
+ export interface UpdatePlan { mediator: string; version: string; url: string; sha256: string }
125
+
126
+ /** Decide whether to update THIS mediator, given a verified manifest and the console directive.
127
+ * Pure + dependency-free (the security gate, independent of crypto). Returns null = do nothing. */
128
+ export function planUpdate(
129
+ manifest: Manifest | null, mediator: string, currentVersion: string,
130
+ policy: UpdatePolicy, approvedTarget?: string | null,
131
+ ): UpdatePlan | null {
132
+ if (!manifest || policy === "off") return null;
133
+ const art = manifest.artifacts?.[mediator];
134
+ if (!art || !art.version || !art.url || !/^[0-9a-f]{64}$/.test(art.sha256 || "")) return null;
135
+ if (!versionBehind(currentVersion, art.version)) return null; // forward-only (never downgrade/equal)
136
+ if (policy === "approve" && approvedTarget !== art.version) return null; // operator must approve THIS target
137
+ return { mediator, version: art.version, url: art.url, sha256: art.sha256 };
138
+ }
139
+
140
+ /** OS-specific install, injected so it's testable and so the network/pip/npm swap stays out of this
141
+ * verified core. A real Applier downloads nothing — it receives already-verified bytes, swaps the
142
+ * runtime atomically with a self-test, and rolls back on failure (fail-closed). */
143
+ export interface Applier {
144
+ apply(plan: UpdatePlan, artifact: Buffer): Promise<boolean>;
145
+ }
146
+ export interface UpdateDeps {
147
+ fetchArtifact: (url: string) => Promise<Buffer>;
148
+ applier: Applier;
149
+ }
150
+
151
+ /** Download → hash-pin → apply. Returns the new version on success, else null (old runtime kept). */
152
+ export async function applyUpdate(plan: UpdatePlan, deps: UpdateDeps): Promise<string | null> {
153
+ try {
154
+ const bytes = await deps.fetchArtifact(plan.url);
155
+ if (sha256Hex(bytes) !== plan.sha256) return null; // artifact doesn't match the signed hash → refuse
156
+ const ok = await deps.applier.apply(plan, bytes);
157
+ return ok ? plan.version : null;
158
+ } catch {
159
+ return null; // never let an update failure break the agent
160
+ }
161
+ }
162
+
163
+ /** End-to-end gate used by the shipper: verify the signed manifest, plan under the directive, apply.
164
+ * Everything network/OS is injected; the verified decision core is what's exercised in tests. */
165
+ export async function maybeUpdate(args: {
166
+ signedManifestJson: string; mediator: string; currentVersion: string;
167
+ policy: UpdatePolicy; approvedTarget?: string | null; keys?: Record<string, string>;
168
+ trustPath?: string; deps: UpdateDeps;
169
+ }): Promise<string | null> {
170
+ // A verified manifest updates the trust file (revocations, newest issued_at) even with nothing to install.
171
+ const trust = loadTrust(args.trustPath);
172
+ const manifest = verifyManifest(args.signedManifestJson, { keys: args.keys, trust });
173
+ if (manifest) saveTrust(args.trustPath, nextTrust(trust, manifest));
174
+ const plan = planUpdate(manifest, args.mediator, args.currentVersion, args.policy, args.approvedTarget);
175
+ if (!plan) return null;
176
+ return applyUpdate(plan, args.deps);
177
+ }
178
+
179
+ export interface Directive {
180
+ policy?: UpdatePolicy; targets?: Record<string, string>; approved?: Record<string, string>;
181
+ manifest_url?: string; rollout_percent?: number;
182
+ }
183
+
184
+ /** Stable canary membership: in the cohort iff a stable hash of the id falls under the rollout percent.
185
+ * Deterministic per id, so an agent never flips in/out of the canary between runs. */
186
+ export function inRolloutCohort(stableId: string, percent: unknown): boolean {
187
+ let p = Number(percent);
188
+ if (!Number.isFinite(p)) p = 100;
189
+ if (p >= 100) return true;
190
+ if (p <= 0) return false;
191
+ const h = parseInt(createHash("sha256").update(String(stableId ?? "")).digest("hex").slice(0, 8), 16);
192
+ return (h % 100) < p;
193
+ }
194
+ export interface UpdateCheckDeps extends UpdateDeps {
195
+ fetchDirective: () => Promise<Directive>;
196
+ fetchText: (url: string) => Promise<string>;
197
+ }
198
+
199
+ /** Orchestration the shipper calls on an interval. INERT by default: an empty pinned key (no release
200
+ * key baked in) short-circuits BEFORE any network, so a keyless build makes zero update traffic.
201
+ * Cheap/local gates first, signed-artifact fetch last. The manifest URL comes FROM the directive
202
+ * (operator/platform-set) — the client never guesses a distribution URL. Fully testable offline. */
203
+ export async function runUpdateCheck(args: {
204
+ mediator: string; currentVersion: string; keys?: Record<string, string>; trustPath?: string;
205
+ stableId?: string; deps: UpdateCheckDeps;
206
+ }): Promise<string | null> {
207
+ try {
208
+ if (!Object.keys(pinnedKeys(args.keys)).length) return null; // no release key → disabled, no traffic
209
+ const d = (await args.deps.fetchDirective()) || {};
210
+ const policy = (d.policy ?? "approve") as UpdatePolicy;
211
+ if (policy === "off") return null;
212
+ const target = d.targets?.[args.mediator];
213
+ if (!target || !versionBehind(args.currentVersion, target)) return null; // forward-only
214
+ if (!inRolloutCohort(args.stableId ?? "", d.rollout_percent ?? 100)) return null; // not in the canary cohort yet
215
+ if (!d.manifest_url) return null; // no distribution configured
216
+ const signed = await args.deps.fetchText(d.manifest_url);
217
+ return maybeUpdate({
218
+ signedManifestJson: signed, mediator: args.mediator, currentVersion: args.currentVersion,
219
+ policy, approvedTarget: d.approved?.[args.mediator], keys: args.keys, trustPath: args.trustPath, deps: args.deps,
220
+ });
221
+ } catch {
222
+ return null; // an update check must never break the shipper
223
+ }
224
+ }