@0perator/operator 0.1.276 → 0.1.282

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.
@@ -0,0 +1,574 @@
1
+ // Central session-tracking ingest — the engine half of Operator's per-account usage ledger. Where events.ts is the
2
+ // frozen local envelope (file + dashboard feed), this module projects the four kinds a ledger needs (session
3
+ // start/end, tool, turn) onto the LOCKED ingest wire shape and delivers them to the account backend:
4
+ //
5
+ // POST $KODE_EVENTS_URL (default http://127.0.0.1:8001/operator/events)
6
+ // Authorization: Bearer <op_ token> body { "events": [IngestEvent, …] }, batch <= 50
7
+ // response { ok, accepted, duplicate } the server is idempotent on `eid`, so a resend is always safe
8
+ //
9
+ // Guarantees, in order of importance: it NEVER throws into or waits on the turn path; an event survives a down
10
+ // server (disk outbox, drained on the next flush and at startup); nothing leaves the machine unless an account is
11
+ // signed in; and the bearer only ever goes to a host the operator token is already trusted by.
12
+ //
13
+ // Node-lazy (opaque specifier, same discipline as events.ts/audit.ts) so this stays loadable from the JSCore/browser
14
+ // bundle: there the poster is simply never active (no token, no node) and a mobile host injects its own sink.
15
+ import { redactSecrets } from "../engine/redact.js";
16
+ import { getOperatorToken, operatorTrustedUrl } from "../engine/aurora.js";
17
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
18
+ export const DEFAULT_INGEST_URL = "http://127.0.0.1:8001/operator/events";
19
+ export const INGEST_BATCH_MAX = 50;
20
+ export const OUTBOX_MAX_LINES = 10_000;
21
+ const FLUSH_MS = 2_000;
22
+ const POST_TIMEOUT_MS = 5_000;
23
+ const BACKOFF_BASE_MS = 2_000;
24
+ const BACKOFF_MAX_MS = 5 * 60_000;
25
+ const STALE_CLAIM_MS = 120_000;
26
+ // A persistently failing event must never wedge the queue. It is dropped (and logged) after MAX_ATTEMPTS failures the
27
+ // server attributed to THAT event, or once it has been failing for MAX_AGE_MS — whichever comes first.
28
+ const MAX_ATTEMPTS = 8;
29
+ const MAX_AGE_MS = 24 * 3_600_000;
30
+ const LONE_FAILURES_BEFORE_STALL = 3; // this many single events rejected with nothing accepted ⇒ the server is unwell, not the events
31
+ const GATEWAY_5XX = new Set([502, 503, 504]); // a proxy/overload answer: about the server, never about one event
32
+ const LOG_MAX_BYTES = 1_000_000;
33
+ // Mirrors auth/client.ts (not imported: that module reads process.env at load, which the neutral bundle must not).
34
+ const DEFAULT_AUTH_BASE = "https://gate.authgate.cloud";
35
+ /** Project a local OperatorEvent onto the ingest shape, or null when it has no central form (service/rc/policy
36
+ * control events, or a lifecycle/tool event missing what the ledger needs). Pure. */
37
+ export function toIngestEvent(e) {
38
+ if (!e.eid || !e.session)
39
+ return null; // no stable id → no safe dedupe; no session → an orphan the ledger cannot place
40
+ const base = { eid: e.eid, session_id: e.session, ts: e.ts };
41
+ const argHash = e.tool?.argHash;
42
+ if (e.kind === "tool" && e.tool && argHash) {
43
+ const t = e.tool;
44
+ return {
45
+ ...base, kind: "tool",
46
+ tool: {
47
+ tool: t.name, argHash, status: t.outcome,
48
+ ...(t.durationMs !== undefined ? { duration_ms: Math.round(t.durationMs) } : {}),
49
+ ...(t.connectorId ? { connectorId: t.connectorId } : {}),
50
+ },
51
+ };
52
+ }
53
+ if (e.kind === "turn" && e.turn) {
54
+ const t = e.turn;
55
+ return {
56
+ ...base, kind: "turn",
57
+ turn: {
58
+ model: t.model ?? "unknown", promptTokens: t.promptTokens ?? 0, completionTokens: t.completionTokens ?? t.tokens,
59
+ ...(t.cachedTokens !== undefined ? { cachedTokens: t.cachedTokens } : {}),
60
+ },
61
+ };
62
+ }
63
+ // Lifecycle rides on control events, and only the STRUCTURED ones (carrying model / outcome): the audited
64
+ // boot-context `session_start` (detail string only) fires for every CLI entry — `auth`, `doctor`, `--version` —
65
+ // and would otherwise mint phantom sessions that never end.
66
+ if (e.kind === "control" && e.control?.event === "session_start" && e.control.model !== undefined) {
67
+ return { ...base, kind: "session_start", session_start: { model: e.control.model, surface: e.actor.surface, version: e.control.version ?? "" } };
68
+ }
69
+ if (e.kind === "control" && e.control?.event === "session_end" && e.control.outcome !== undefined) {
70
+ return { ...base, kind: "session_end", session_end: { outcome: e.control.outcome, ...(e.control.turns !== undefined ? { turns: e.control.turns } : {}) } };
71
+ }
72
+ return null;
73
+ }
74
+ const envOf = (name) => globalThis.process?.env?.[name];
75
+ const hostOf = (u) => { try {
76
+ return new URL(u).hostname.toLowerCase();
77
+ }
78
+ catch {
79
+ return "";
80
+ } };
81
+ /** KODE_EVENTS_URL as the owner set it, or undefined when unset OR switched off (`""`, `off`, `0`, `false`, `none`). */
82
+ export function configuredIngestUrl() {
83
+ const v = envOf("KODE_EVENTS_URL")?.trim();
84
+ return v && !/^(off|0|false|none)$/i.test(v) ? v : undefined;
85
+ }
86
+ /** KODE_EVENTS_URL explicitly switched off — the central ingest is disabled outright (tests; air-gapped owners). */
87
+ const disabledByEnv = () => envOf("KODE_EVENTS_URL") !== undefined && configuredIngestUrl() === undefined;
88
+ /** Where undelivered events wait. Machine-wide like events.jsonl (NOT profile-scoped): the outbox belongs to the OS
89
+ * user whose account the events are billed against. Unexpanded `~/` — resolved where node is available. */
90
+ export function defaultOutboxFile() {
91
+ return envOf("KODE_EVENTS_OUTBOX") || (envOf("KODE_HOME") ? envOf("KODE_HOME") + "/outbox.jsonl" : "~/.axe/operator/outbox.jsonl");
92
+ }
93
+ // 401 = signed out/rotated (a re-login fixes it); 404 = the route is not deployed yet; 408/425/429 = try later.
94
+ // Any other 4xx is a request the server will reject every time — keeping it would wedge the outbox behind it.
95
+ const RETRYABLE_4XX = new Set([401, 404, 408, 425, 429]);
96
+ /** Could this failure be one EVENT's fault (a malformed event the server rejects or 500s on) rather than the server's? */
97
+ const eventScoped = (o) => o.kind === "drop" || (o.kind === "retry" && o.status !== undefined && o.status >= 500 && !GATEWAY_5XX.has(o.status));
98
+ export class Ingest {
99
+ urlOpt;
100
+ tokenFn;
101
+ outboxOpt;
102
+ fetchImpl;
103
+ flushMs;
104
+ timeoutMs;
105
+ backoffBaseMs;
106
+ maxAttempts;
107
+ maxAgeMs;
108
+ now;
109
+ enabled = true;
110
+ started = false;
111
+ buffer = [];
112
+ pending = []; // taken from the buffer, not yet acknowledged: persisted too if the process dies mid-delivery (dup-safe)
113
+ history = new Map();
114
+ timer;
115
+ flushing = null;
116
+ failures = 0;
117
+ retryAt = 0;
118
+ mayHaveOutbox = true; // true at startup (leftovers from a previous run), and after any spill
119
+ claimSeq = 0;
120
+ outboxLines = -1; // lazily counted on the first append
121
+ logBytes = -1;
122
+ ioP;
123
+ stats = { accepted: 0, duplicate: 0, dropped: 0, spilled: 0 };
124
+ constructor(opts = {}) {
125
+ this.urlOpt = opts.url;
126
+ this.tokenFn = opts.token ?? getOperatorToken;
127
+ this.outboxOpt = opts.outbox;
128
+ this.fetchImpl = opts.fetchImpl;
129
+ this.flushMs = opts.flushMs ?? FLUSH_MS;
130
+ this.timeoutMs = opts.timeoutMs ?? POST_TIMEOUT_MS;
131
+ this.backoffBaseMs = opts.backoffBaseMs ?? BACKOFF_BASE_MS;
132
+ this.maxAttempts = opts.maxAttempts ?? MAX_ATTEMPTS;
133
+ this.maxAgeMs = opts.maxAgeMs ?? MAX_AGE_MS;
134
+ this.now = opts.now ?? Date.now;
135
+ }
136
+ setEnabled(on) { this.enabled = on; }
137
+ url() { return this.urlOpt ?? configuredIngestUrl() ?? DEFAULT_INGEST_URL; }
138
+ /** The bearer may only go where the operator token is already trusted: AXE/LAN/loopback hosts and the AuthGate it
139
+ * authenticates against. A KODE_EVENTS_URL pointing anywhere else is refused, never sent. */
140
+ trusted() {
141
+ const u = this.url();
142
+ const h = hostOf(u);
143
+ return !!h && (operatorTrustedUrl(u) || h === hostOf(envOf("AXE_AUTH_URL") ?? DEFAULT_AUTH_BASE));
144
+ }
145
+ /** Signed in (a token is held) and the destination is one the token may go to: events are delivered centrally. */
146
+ active() { return this.enabled && !(this.urlOpt === undefined && disabledByEnv()) && !!this.tokenFn() && this.trusted(); }
147
+ /** The owner pointed the ingest somewhere explicitly — enough to RECORD locally even before sign-in (nothing is
148
+ * sent without a token). */
149
+ configured() { return this.enabled && (this.urlOpt !== undefined || configuredIngestUrl() !== undefined); }
150
+ /** Queue one event. Fire-and-forget, never throws, never awaits: the flush happens off the turn path. */
151
+ push(e) {
152
+ try {
153
+ if (!this.active())
154
+ return; // signed out → local only
155
+ const ie = toIngestEvent(e);
156
+ if (!ie)
157
+ return;
158
+ this.buffer.push(ie);
159
+ // The process's first event flushes at once (it is also what drains the previous run's outbox); a full
160
+ // batch flushes at once (also bounds memory while backing off); the rest ride the batch timer.
161
+ const now = !this.started || this.buffer.length >= INGEST_BATCH_MAX;
162
+ this.started = true;
163
+ this.schedule(now ? 0 : this.flushMs);
164
+ }
165
+ catch { /* observability is not a gate */ }
166
+ }
167
+ schedule(ms) {
168
+ if (this.timer) {
169
+ if (ms > 0)
170
+ return;
171
+ clearTimeout(this.timer);
172
+ }
173
+ const t = setTimeout(() => { this.timer = undefined; void this.flush(); }, ms);
174
+ t.unref?.(); // an idle process must not be held open by the batch timer
175
+ this.timer = t;
176
+ }
177
+ /** Send what is buffered (outbox first). Single-flight; resolves when settled, never rejects. */
178
+ flush() {
179
+ if (this.flushing)
180
+ return this.flushing;
181
+ this.flushing = this.run().catch(() => { }).finally(() => {
182
+ this.flushing = null;
183
+ if (this.buffer.length && this.active())
184
+ this.schedule(this.flushMs);
185
+ });
186
+ return this.flushing;
187
+ }
188
+ takeBuffer() { const b = this.buffer; this.buffer = []; return b; }
189
+ async run() {
190
+ for (;;) {
191
+ const token = this.tokenFn();
192
+ if (!this.active() || !token) {
193
+ this.buffer = [];
194
+ return;
195
+ } // signed out since these were queued: local only
196
+ if (this.now() < this.retryAt) {
197
+ await this.parkWhileBackingOff();
198
+ return;
199
+ } // backing off: park on disk
200
+ // ONE pass over the previous runs' outbox (older first) and this run's buffer: a failure can only be blamed on a
201
+ // single event if the server demonstrably accepted others, so the canaries must be in the same pass.
202
+ const claimed = await this.claimOutbox();
203
+ this.pending = [...claimed.events, ...this.takeBuffer()];
204
+ if (this.pending.length) {
205
+ const { keep, retryIn } = await this.deliver(this.pending, token, true);
206
+ this.pending = keep; // still owed: persisted by the exit backstop if we die before the append below lands
207
+ await this.appendOutbox(keep);
208
+ if (retryIn !== undefined)
209
+ this.schedule(retryIn);
210
+ }
211
+ await this.releaseClaims(claimed.files); // only now: a crash before this leaves the claim to be adopted, not lost
212
+ this.pending = [];
213
+ if (!this.buffer.length)
214
+ return; // events pushed during delivery get another pass
215
+ }
216
+ }
217
+ /** Backing off: park what is queued on disk (memory stays bounded) and make sure SOMETHING will try again — an idle
218
+ * session emits nothing to re-arm the batch timer, and the parked events must not wait for the next startup. */
219
+ async parkWhileBackingOff() {
220
+ await this.appendOutbox(this.takeBuffer());
221
+ this.schedule(Math.max(this.flushMs, this.retryAt - this.now()));
222
+ }
223
+ onSuccess() { this.failures = 0; this.retryAt = 0; }
224
+ onFailure() {
225
+ this.failures += 1;
226
+ const delay = Math.min(BACKOFF_MAX_MS, this.backoffBaseMs * 2 ** (this.failures - 1));
227
+ this.retryAt = this.now() + delay;
228
+ this.mayHaveOutbox = true;
229
+ this.schedule(delay); // the retry timer; unref'd, so a process that exits first leaves the outbox for next startup
230
+ }
231
+ async post(events, token) {
232
+ const ctrl = new AbortController();
233
+ const t = setTimeout(() => ctrl.abort(), this.timeoutMs);
234
+ try {
235
+ const res = await (this.fetchImpl ?? fetch)(this.url(), {
236
+ method: "POST",
237
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
238
+ body: redactSecrets(JSON.stringify({ events })), // H4: same mask the legacy POST sink applies
239
+ signal: ctrl.signal,
240
+ });
241
+ if (res.ok) {
242
+ try {
243
+ const j = (await res.json());
244
+ this.stats.accepted += j.accepted ?? 0;
245
+ this.stats.duplicate += j.duplicate ?? 0;
246
+ }
247
+ catch { /* a body-less 2xx is still a delivery */ }
248
+ return { kind: "ok" };
249
+ }
250
+ if (res.status >= 400 && res.status < 500 && !RETRYABLE_4XX.has(res.status))
251
+ return { kind: "drop", status: res.status };
252
+ return { kind: "retry", status: res.status };
253
+ }
254
+ catch {
255
+ return { kind: "retry" }; // network down, DNS, timeout/abort
256
+ }
257
+ finally {
258
+ clearTimeout(t);
259
+ }
260
+ }
261
+ // ---- delivery: never let one event wedge the queue ------------------------------------------------------------
262
+ /** Deliver `events` in order (<= 50 per request) and return what must be KEPT, undelivered. Ordinary failure is the
263
+ * server's: everything left waits out one shared backoff. But a batch the server rejects can be one event's fault, so
264
+ * such a batch is bisected down to the offender while the rest is delivered. A lone event is only BLAMED (attempt++,
265
+ * paced by its own backoff) when the server accepted other events in the same pass — an outage burns no attempts,
266
+ * so a ten-minute outage cannot expire a healthy queue. After `maxAttempts` blamed failures, or `maxAgeMs` of
267
+ * failing for any reason but 401 (which keeps: a re-login fixes it), the event is dropped and logged. 4xx drops at once. */
268
+ async deliver(events, token, track) {
269
+ const keep = [];
270
+ const suspects = [];
271
+ const due = [];
272
+ const t0 = this.now();
273
+ for (const e of events)
274
+ (this.history.get(e.eid)?.at ?? 0) > t0 ? keep.push(e) : due.push(e); // a blamed event waits out its own pacing
275
+ let accepted = false; // the canary: proof the server is up and taking events this pass
276
+ let stalled = false; // a server-level failure: everything not yet sent waits
277
+ let authFailed = false;
278
+ let lone = 0; // single events rejected so far this pass
279
+ const settle = (batch) => {
280
+ if (!track)
281
+ return;
282
+ const ids = new Set(batch.map((e) => e.eid));
283
+ this.pending = this.pending.filter((e) => !ids.has(e.eid));
284
+ };
285
+ const send = async (batch) => {
286
+ if (stalled) {
287
+ keep.push(...batch);
288
+ return;
289
+ }
290
+ const r = await this.post(batch, token);
291
+ if (r.kind === "ok") {
292
+ accepted = true;
293
+ for (const e of batch)
294
+ this.history.delete(e.eid);
295
+ settle(batch);
296
+ return;
297
+ }
298
+ if (eventScoped(r)) {
299
+ if (batch.length > 1 && (accepted || lone < LONE_FAILURES_BEFORE_STALL)) { // find the offender, deliver the rest
300
+ const mid = Math.ceil(batch.length / 2);
301
+ await send(batch.slice(0, mid));
302
+ await send(batch.slice(mid));
303
+ return;
304
+ }
305
+ if (batch.length === 1)
306
+ lone += 1;
307
+ if (r.kind === "drop") {
308
+ settle(batch);
309
+ await this.dropEvents(batch, `http-${r.status}`);
310
+ return;
311
+ }
312
+ if (batch.length === 1 && (accepted || lone < LONE_FAILURES_BEFORE_STALL)) {
313
+ suspects.push(batch[0]);
314
+ keep.push(batch[0]);
315
+ return;
316
+ }
317
+ }
318
+ stalled = true; // network, 401/404/408/425/429, a gateway 5xx, or nothing but rejections: the server, not the events
319
+ authFailed = authFailed || (r.kind === "retry" && r.status === 401);
320
+ keep.push(...batch);
321
+ };
322
+ for (let i = 0; i < due.length; i += INGEST_BATCH_MAX)
323
+ await send(due.slice(i, i + INGEST_BATCH_MAX));
324
+ if (!accepted && suspects.length)
325
+ stalled = true; // nobody else got through: those rejections were the server's
326
+ if (accepted)
327
+ this.onSuccess();
328
+ if (stalled)
329
+ this.onFailure();
330
+ const t1 = this.now();
331
+ if (!authFailed)
332
+ for (const e of keep) {
333
+ const h = this.history.get(e.eid) ?? { n: 0 };
334
+ h.t ??= t1;
335
+ this.history.set(e.eid, h);
336
+ }
337
+ if (accepted) {
338
+ for (const e of suspects) {
339
+ const h = this.history.get(e.eid);
340
+ h.n += 1;
341
+ h.at = t1 + Math.min(BACKOFF_MAX_MS, this.backoffBaseMs * 2 ** h.n);
342
+ }
343
+ }
344
+ const kept = [];
345
+ let next;
346
+ for (const e of keep) {
347
+ const h = this.history.get(e.eid);
348
+ const why = !h ? undefined
349
+ : h.n >= this.maxAttempts ? `attempts(${h.n})`
350
+ : h.t !== undefined && t1 - h.t >= this.maxAgeMs ? `age(${Math.round((t1 - h.t) / 3_600_000)}h)`
351
+ : undefined;
352
+ if (why) {
353
+ settle([e]);
354
+ await this.dropEvents([e], why);
355
+ continue;
356
+ }
357
+ kept.push(e);
358
+ if (h?.at !== undefined)
359
+ next = Math.min(next ?? Infinity, h.at - t1);
360
+ }
361
+ return { keep: kept, retryIn: next === undefined ? undefined : Math.max(this.flushMs, next) };
362
+ }
363
+ /** Drop events for good and say so: one line each in the local log (ids only — never content). */
364
+ async dropEvents(events, reason) {
365
+ this.stats.dropped += events.length;
366
+ for (const e of events)
367
+ this.history.delete(e.eid);
368
+ await this.log(events.map((e) => `dropped eid=${e.eid} kind=${e.kind} session=${e.session_id} reason=${reason}`));
369
+ }
370
+ /** Append lines to the outbox's sibling `.log` (0600, stops growing at ~1MB). Best-effort, never throws. */
371
+ async log(lines) {
372
+ try {
373
+ const io = await this.io();
374
+ if (!io || !lines.length)
375
+ return;
376
+ const file = io.file.replace(/\.jsonl$/, "") + ".log";
377
+ if (this.logBytes < 0)
378
+ this.logBytes = await io.fsp.stat(file).then((st) => st.size, () => 0);
379
+ if (this.logBytes > LOG_MAX_BYTES)
380
+ return;
381
+ const text = lines.map((l) => `${new Date(this.now()).toISOString()} ingest ${l}`).join("\n") + "\n";
382
+ await io.fsp.mkdir(io.dirname(io.file), { recursive: true, mode: 0o700 });
383
+ await io.fsp.appendFile(file, text, { encoding: "utf8", mode: 0o600 });
384
+ this.logBytes += text.length;
385
+ }
386
+ catch { /* a log that cannot be written must not become a second failure */ }
387
+ }
388
+ // ---- disk outbox ---------------------------------------------------------------------------------------------
389
+ io() {
390
+ return (this.ioP ??= (async () => {
391
+ try {
392
+ const [fsp, os, path] = await Promise.all([nodeImport("node:fs/promises"), nodeImport("node:os"), nodeImport("node:path")]);
393
+ const raw = this.outboxOpt ?? defaultOutboxFile();
394
+ const file = raw.startsWith("~/") ? path.join(os.homedir(), raw.slice(2)) : raw;
395
+ return { fsp, join: path.join, dirname: path.dirname, basename: path.basename, file };
396
+ }
397
+ catch {
398
+ return null;
399
+ } // no fs (mobile): events that cannot be delivered are simply not kept
400
+ })());
401
+ }
402
+ /** One outbox line: the event plus its delivery history (`_t/_n/_at`), which the wire never carries. */
403
+ line(e) {
404
+ const h = this.history.get(e.eid);
405
+ return JSON.stringify(h ? { ...e, _t: h.t, _n: h.n || undefined, _at: h.at } : e);
406
+ }
407
+ parse(text) {
408
+ const out = [];
409
+ for (const l of text.split("\n")) {
410
+ if (!l)
411
+ continue;
412
+ try {
413
+ const { _t, _n, _at, ...ev } = JSON.parse(l);
414
+ if (typeof ev.eid !== "string")
415
+ throw new Error("not an event");
416
+ if (_t !== undefined || _n || _at !== undefined)
417
+ this.history.set(ev.eid, { t: _t, n: _n ?? 0, at: _at });
418
+ out.push(ev);
419
+ }
420
+ catch {
421
+ this.stats.dropped += 1;
422
+ } // a torn line is not worth wedging the queue
423
+ }
424
+ return out;
425
+ }
426
+ /** Park events for a later attempt (0600 JSONL). Past OUTBOX_MAX_LINES the OLDEST are dropped. Never throws. */
427
+ async appendOutbox(events) {
428
+ if (!events.length)
429
+ return;
430
+ try {
431
+ const io = await this.io();
432
+ if (!io)
433
+ return;
434
+ await io.fsp.mkdir(io.dirname(io.file), { recursive: true, mode: 0o700 });
435
+ await io.fsp.appendFile(io.file, events.map((e) => this.line(e)).join("\n") + "\n", { encoding: "utf8", mode: 0o600 });
436
+ this.mayHaveOutbox = true;
437
+ this.stats.spilled += events.length;
438
+ if (this.outboxLines < 0)
439
+ this.outboxLines = (await io.fsp.readFile(io.file, "utf8")).split("\n").filter(Boolean).length;
440
+ else
441
+ this.outboxLines += events.length;
442
+ if (this.outboxLines > OUTBOX_MAX_LINES)
443
+ await this.trimOutbox(io);
444
+ }
445
+ catch { /* disk full / read-only: the event is lost, the turn is not */ }
446
+ }
447
+ /** Keep the newest OUTBOX_MAX_LINES. Claim-by-rename so a concurrent appender never has a line clobbered. */
448
+ async trimOutbox(io) {
449
+ const claim = `${io.file}.claim-${process.pid}-${++this.claimSeq}`;
450
+ try {
451
+ await io.fsp.rename(io.file, claim);
452
+ }
453
+ catch {
454
+ return;
455
+ }
456
+ try {
457
+ const lines = (await io.fsp.readFile(claim, "utf8")).split("\n").filter(Boolean);
458
+ const keep = lines.slice(-OUTBOX_MAX_LINES);
459
+ await io.fsp.appendFile(io.file, keep.join("\n") + "\n", { encoding: "utf8", mode: 0o600 });
460
+ this.stats.dropped += lines.length - keep.length;
461
+ this.outboxLines = keep.length;
462
+ await this.log([`outbox over ${OUTBOX_MAX_LINES} lines: dropped the ${lines.length - keep.length} oldest`]);
463
+ }
464
+ finally {
465
+ await io.fsp.rm(claim, { force: true });
466
+ }
467
+ }
468
+ /** Take over what a previous run (or this one, earlier) could not deliver. The outbox is claimed by rename, so two
469
+ * Operator processes never double-read a line (and the server dedupes on eid if a crash ever makes them). */
470
+ async claimOutbox() {
471
+ const none = { events: [], files: [] };
472
+ if (!this.mayHaveOutbox)
473
+ return none;
474
+ const io = await this.io();
475
+ if (!io)
476
+ return none;
477
+ const files = [];
478
+ try {
479
+ const mine = `${io.file}.claim-${process.pid}-${++this.claimSeq}`;
480
+ try {
481
+ await io.fsp.rename(io.file, mine);
482
+ files.push(mine);
483
+ }
484
+ catch { /* no outbox */ }
485
+ const dir = io.dirname(io.file);
486
+ const prefix = io.basename(io.file) + ".claim-";
487
+ for (const n of (await io.fsp.readdir(dir).catch(() => []))) {
488
+ if (!n.startsWith(prefix))
489
+ continue;
490
+ const p = io.join(dir, n);
491
+ if (files.includes(p))
492
+ continue;
493
+ try { // a claim a crashed sibling never finished: adopt it once it is clearly orphaned
494
+ if (this.now() - (await io.fsp.stat(p)).mtimeMs < STALE_CLAIM_MS)
495
+ continue;
496
+ const adopted = `${io.file}.claim-${process.pid}-${++this.claimSeq}`;
497
+ await io.fsp.rename(p, adopted);
498
+ files.push(adopted);
499
+ }
500
+ catch { /* raced with its owner */ }
501
+ }
502
+ }
503
+ catch {
504
+ return none;
505
+ }
506
+ this.mayHaveOutbox = false; // anything still undeliverable is re-parked by appendOutbox, which sets it again
507
+ const events = [];
508
+ for (const f of files) {
509
+ try {
510
+ events.push(...this.parse(await io.fsp.readFile(f, "utf8")));
511
+ }
512
+ catch { /* unreadable claim: skipped */ }
513
+ }
514
+ return { events, files };
515
+ }
516
+ async releaseClaims(files) {
517
+ if (!files.length)
518
+ return;
519
+ const io = await this.io();
520
+ for (const f of files) {
521
+ try {
522
+ await io?.fsp.rm(f, { force: true });
523
+ }
524
+ catch { /* best-effort */ }
525
+ }
526
+ }
527
+ /** Exit backstop: no network, no await — whatever is still queued (or on the wire) goes to the outbox synchronously
528
+ * so the next startup delivers it. Safe in a `process.on("exit")` handler. */
529
+ persistSync() {
530
+ try {
531
+ const events = [...this.pending, ...this.buffer];
532
+ if (!events.length)
533
+ return;
534
+ const proc = globalThis.process;
535
+ const fs = proc?.getBuiltinModule?.("node:fs");
536
+ const os = proc?.getBuiltinModule?.("node:os");
537
+ const path = proc?.getBuiltinModule?.("node:path");
538
+ if (!fs || !os || !path)
539
+ return;
540
+ const raw = this.outboxOpt ?? defaultOutboxFile();
541
+ const file = raw.startsWith("~/") ? path.join(os.homedir(), raw.slice(2)) : raw;
542
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
543
+ fs.appendFileSync(file, events.map((e) => this.line(e)).join("\n") + "\n", { encoding: "utf8", mode: 0o600 });
544
+ this.buffer = [];
545
+ this.pending = [];
546
+ }
547
+ catch { /* best-effort */ }
548
+ }
549
+ /** Graceful end: one bounded attempt to deliver, then anything left is persisted for the next run. */
550
+ async shutdown(timeoutMs = 2_000) {
551
+ try {
552
+ if (this.timer) {
553
+ clearTimeout(this.timer);
554
+ this.timer = undefined;
555
+ }
556
+ let timeout;
557
+ const deadline = new Promise((r) => { timeout = setTimeout(r, timeoutMs); });
558
+ const drain = (async () => { for (let i = 0; i < 3 && (this.buffer.length || this.flushing); i++)
559
+ await this.flush(); })();
560
+ await Promise.race([drain, deadline]);
561
+ clearTimeout(timeout);
562
+ }
563
+ catch { /* fall through to the sync persist */ }
564
+ this.persistSync();
565
+ }
566
+ }
567
+ let _default;
568
+ /** The process-wide ingest every EventSink feeds by default (one batcher, one outbox drain per process). */
569
+ export function defaultIngest() { return (_default ??= new Ingest()); }
570
+ /** cli.tsx projects `settings.telemetry.enabled` here: with metrics off, nothing is recorded centrally. */
571
+ export function setCentralEnabled(on) { defaultIngest().setEnabled(on); }
572
+ /** Should this process RECORD events for central tracking: signed in, or an events URL was set explicitly. The widened
573
+ * gate beside `policy.audits` — which stays config-derived and pure. */
574
+ export function centralRecording() { const i = defaultIngest(); return i.active() || i.configured(); }
@@ -16,3 +16,38 @@ export async function auditControl(settings, event, detail, sub, sink = new Even
16
16
  });
17
17
  await sink.flushed();
18
18
  }
19
+ /** One tracked session's lifecycle for the central ledger: a structured `session_start` (model + version; surface comes
20
+ * from the actor) and exactly one `session_end` (outcome + turns). Only a session that actually started can end, so an
21
+ * entry that never runs a session (`operator auth …`, `--version`) mints no phantom session. `enabled` is the same
22
+ * gate the permission wrapper uses (audited seat, or signed in / events URL configured) so a signed-out owner stays inert. */
23
+ export class SessionTracker {
24
+ sink;
25
+ session;
26
+ actor;
27
+ version;
28
+ enabled;
29
+ started = false;
30
+ ended = false;
31
+ turns = 0;
32
+ constructor(sink, session, actor, version, enabled) {
33
+ this.sink = sink;
34
+ this.session = session;
35
+ this.actor = actor;
36
+ this.version = version;
37
+ this.enabled = enabled;
38
+ }
39
+ start(model) {
40
+ if (this.started || !this.enabled())
41
+ return;
42
+ this.started = true;
43
+ this.sink.emit({ kind: "control", session: this.session, actor: this.actor, control: { event: "session_start", detail: `surface=${this.actor.surface}`, model, version: this.version } });
44
+ }
45
+ /** One user prompt handled (completed, interrupted or failed). */
46
+ noteTurn() { this.turns += 1; }
47
+ end(outcome) {
48
+ if (!this.started || this.ended)
49
+ return;
50
+ this.ended = true;
51
+ this.sink.emit({ kind: "control", session: this.session, actor: this.actor, control: { event: "session_end", detail: outcome, outcome, turns: this.turns } });
52
+ }
53
+ }