@schlessera/brain-ui-server 0.18.0 → 0.19.0

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 (101) hide show
  1. package/dist/activity/digest.d.ts +29 -0
  2. package/dist/activity/digest.d.ts.map +1 -0
  3. package/dist/activity/digest.js +61 -0
  4. package/dist/activity/digest.js.map +1 -0
  5. package/dist/activity/notify.d.ts +62 -0
  6. package/dist/activity/notify.d.ts.map +1 -0
  7. package/dist/activity/notify.js +171 -0
  8. package/dist/activity/notify.js.map +1 -0
  9. package/dist/activity/push-sender.d.ts +63 -0
  10. package/dist/activity/push-sender.d.ts.map +1 -0
  11. package/dist/activity/push-sender.js +131 -0
  12. package/dist/activity/push-sender.js.map +1 -0
  13. package/dist/activity/query.d.ts +16 -0
  14. package/dist/activity/query.d.ts.map +1 -0
  15. package/dist/activity/query.js +128 -0
  16. package/dist/activity/query.js.map +1 -0
  17. package/dist/activity/recorder.d.ts +48 -0
  18. package/dist/activity/recorder.d.ts.map +1 -0
  19. package/dist/activity/recorder.js +205 -0
  20. package/dist/activity/recorder.js.map +1 -0
  21. package/dist/activity/runtime.d.ts +31 -0
  22. package/dist/activity/runtime.d.ts.map +1 -0
  23. package/dist/activity/runtime.js +109 -0
  24. package/dist/activity/runtime.js.map +1 -0
  25. package/dist/activity/span-sink.d.ts +22 -0
  26. package/dist/activity/span-sink.d.ts.map +1 -0
  27. package/dist/activity/span-sink.js +138 -0
  28. package/dist/activity/span-sink.js.map +1 -0
  29. package/dist/activity/store.d.ts +207 -0
  30. package/dist/activity/store.d.ts.map +1 -0
  31. package/dist/activity/store.js +440 -0
  32. package/dist/activity/store.js.map +1 -0
  33. package/dist/activity/stream.d.ts +45 -0
  34. package/dist/activity/stream.d.ts.map +1 -0
  35. package/dist/activity/stream.js +312 -0
  36. package/dist/activity/stream.js.map +1 -0
  37. package/dist/app.d.ts.map +1 -1
  38. package/dist/app.js +16 -0
  39. package/dist/app.js.map +1 -1
  40. package/dist/cron/scheduler.d.ts.map +1 -1
  41. package/dist/cron/scheduler.js +20 -5
  42. package/dist/cron/scheduler.js.map +1 -1
  43. package/dist/db/client.d.ts.map +1 -1
  44. package/dist/db/client.js +32 -6
  45. package/dist/db/client.js.map +1 -1
  46. package/dist/index.d.ts +4 -0
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +7 -0
  49. package/dist/index.js.map +1 -1
  50. package/dist/routes/activity.d.ts +20 -0
  51. package/dist/routes/activity.d.ts.map +1 -0
  52. package/dist/routes/activity.js +300 -0
  53. package/dist/routes/activity.js.map +1 -0
  54. package/dist/routes/push.d.ts +6 -0
  55. package/dist/routes/push.d.ts.map +1 -0
  56. package/dist/routes/push.js +73 -0
  57. package/dist/routes/push.js.map +1 -0
  58. package/dist/routes/sessions.d.ts.map +1 -1
  59. package/dist/routes/sessions.js +20 -4
  60. package/dist/routes/sessions.js.map +1 -1
  61. package/dist/ws/bridge.d.ts +2 -1
  62. package/dist/ws/bridge.d.ts.map +1 -1
  63. package/dist/ws/bridge.js +27 -2
  64. package/dist/ws/bridge.js.map +1 -1
  65. package/dist/ws/connection.d.ts.map +1 -1
  66. package/dist/ws/connection.js +9 -1
  67. package/dist/ws/connection.js.map +1 -1
  68. package/dist/ws/dispatch.d.ts.map +1 -1
  69. package/dist/ws/dispatch.js +11 -0
  70. package/dist/ws/dispatch.js.map +1 -1
  71. package/dist/ws/host.d.ts +16 -0
  72. package/dist/ws/host.d.ts.map +1 -1
  73. package/dist/ws/host.js +2 -0
  74. package/dist/ws/host.js.map +1 -1
  75. package/dist/ws/run-session.d.ts.map +1 -1
  76. package/dist/ws/run-session.js +21 -1
  77. package/dist/ws/run-session.js.map +1 -1
  78. package/migrations/007_activity.sql +114 -0
  79. package/migrations/008_push_subscriptions.sql +24 -0
  80. package/package.json +5 -3
  81. package/src/activity/digest.ts +92 -0
  82. package/src/activity/notify.ts +285 -0
  83. package/src/activity/push-sender.ts +215 -0
  84. package/src/activity/query.ts +160 -0
  85. package/src/activity/recorder.ts +261 -0
  86. package/src/activity/runtime.ts +141 -0
  87. package/src/activity/span-sink.ts +152 -0
  88. package/src/activity/store.ts +774 -0
  89. package/src/activity/stream.ts +366 -0
  90. package/src/app.ts +17 -0
  91. package/src/cron/scheduler.ts +28 -8
  92. package/src/db/client.ts +31 -6
  93. package/src/index.ts +22 -0
  94. package/src/routes/activity.ts +363 -0
  95. package/src/routes/push.ts +90 -0
  96. package/src/routes/sessions.ts +24 -4
  97. package/src/ws/bridge.ts +29 -2
  98. package/src/ws/connection.ts +9 -1
  99. package/src/ws/dispatch.ts +13 -0
  100. package/src/ws/host.ts +18 -0
  101. package/src/ws/run-session.ts +28 -1
@@ -0,0 +1,774 @@
1
+ /**
2
+ * The activity store: the canonical record of agent activity (migration 007).
3
+ *
4
+ * Every unit of agent work — a turn, a tool call, a subagent run, a cron run —
5
+ * is a span row forming a tree per run. Spans are written AT START (a
6
+ * non-terminal row exists while the work runs — that is what makes
7
+ * glance-checks, stuck-run detection, and "what is running?" queries
8
+ * possible) and updated to a write-once terminal outcome.
9
+ *
10
+ * Ordering has two primitives, both minted here inside the write transaction:
11
+ *
12
+ * - `seq` is per-run monotonic and totally orders every delta-visible write
13
+ * within a run. A snapshot carries the run's high-water seq; a client
14
+ * discards deltas at or below it. Deltas are derived from committed rows —
15
+ * persist-then-emit — so the stream can never show what the store does not
16
+ * hold.
17
+ * - `change_id` (AUTOINCREMENT rowid of activity_changes) is the GLOBAL
18
+ * cursor. It exists because per-run seq cannot discover a run the poller
19
+ * has never seen: a foreign writer's brand-new root span is visible only
20
+ * as "a change with a higher change_id than my cursor".
21
+ *
22
+ * Every write runs under an IMMEDIATE transaction: two processes write this
23
+ * database (server + cron wrapper), and a deferred transaction losing the
24
+ * upgrade race throws SQLITE_BUSY instead of waiting. `createUiDb` sets
25
+ * `busy_timeout` so immediate transactions queue rather than throw.
26
+ *
27
+ * Nothing in here may ever fail the work being observed: callers that
28
+ * instrument live turns wrap calls in try/catch and drop on error
29
+ * (observability must not break the observed) — but the STORE itself throws
30
+ * on programmer error, because a silent half-written record is worse than a
31
+ * loud one.
32
+ */
33
+ import type { Database } from "bun:sqlite";
34
+
35
+ export const SPAN_OUTCOMES = [
36
+ "success",
37
+ "error",
38
+ "timeout",
39
+ "cancelled",
40
+ "denied",
41
+ "interrupted",
42
+ ] as const;
43
+ export type SpanOutcome = (typeof SPAN_OUTCOMES)[number];
44
+
45
+ export type SpanKind = "turn" | "tool" | "subagent" | "cron";
46
+ export type SpanOrigin = "session" | "cron";
47
+
48
+ /** Token usage as spans carry it — OTel GenAI attribute semantics. */
49
+ export interface SpanUsage {
50
+ inputTokens?: number;
51
+ outputTokens?: number;
52
+ cacheReadTokens?: number;
53
+ cacheCreationTokens?: number;
54
+ costUsd?: number;
55
+ model?: string;
56
+ }
57
+
58
+ export interface SpanRow {
59
+ spanId: string;
60
+ runId: string;
61
+ parentSpanId: string | null;
62
+ name: string;
63
+ kind: SpanKind;
64
+ origin: SpanOrigin;
65
+ sessionId: string | null;
66
+ jobName: string | null;
67
+ attrs: Record<string, unknown>;
68
+ startedAt: number;
69
+ waitUntil: number | null;
70
+ endedAt: number | null;
71
+ outcome: SpanOutcome | null;
72
+ outcomeReason: string | null;
73
+ usage: SpanUsage;
74
+ writer: string;
75
+ lastHeartbeatAt: number | null;
76
+ }
77
+
78
+ export interface SpanEventRow {
79
+ spanId: string;
80
+ eventIndex: number;
81
+ ts: number;
82
+ eventType: string;
83
+ payload: unknown;
84
+ truncated: boolean;
85
+ }
86
+
87
+ /** One `activity_run_rollups` row, snake→camel. */
88
+ export interface RunRollupRow {
89
+ runId: string;
90
+ origin: SpanOrigin;
91
+ name: string;
92
+ sessionId: string | null;
93
+ jobName: string | null;
94
+ startedAt: number;
95
+ endedAt: number | null;
96
+ outcome: SpanOutcome | null;
97
+ durationMs: number | null;
98
+ spanCount: number;
99
+ inputTokens: number | null;
100
+ outputTokens: number | null;
101
+ cacheReadTokens: number | null;
102
+ cacheCreationTokens: number | null;
103
+ costUsd: number | null;
104
+ failureReason: string | null;
105
+ detailPruned: boolean;
106
+ }
107
+
108
+ /** The one snake→camel mapper for rollup rows — every reader shares it. */
109
+ export function rowToRunRollup(r: any): RunRollupRow {
110
+ return {
111
+ runId: r.run_id,
112
+ origin: r.origin,
113
+ name: r.name,
114
+ sessionId: r.session_id,
115
+ jobName: r.job_name,
116
+ startedAt: r.started_at,
117
+ endedAt: r.ended_at,
118
+ outcome: r.outcome,
119
+ durationMs: r.duration_ms,
120
+ spanCount: r.span_count,
121
+ inputTokens: r.input_tokens,
122
+ outputTokens: r.output_tokens,
123
+ cacheReadTokens: r.cache_read_tokens,
124
+ cacheCreationTokens: r.cache_creation_tokens,
125
+ costUsd: r.cost_usd,
126
+ failureReason: r.failure_reason,
127
+ detailPruned: r.detail_pruned === 1,
128
+ };
129
+ }
130
+
131
+ /** One committed write, as the delta stream sees it. */
132
+ export type ActivityChange =
133
+ | { changeId: number; runId: string; seq: number; kind: "span"; span: SpanRow }
134
+ | { changeId: number; runId: string; seq: number; kind: "event"; event: SpanEventRow };
135
+
136
+ export interface StartSpanInput {
137
+ spanId: string;
138
+ runId: string;
139
+ parentSpanId?: string;
140
+ name: string;
141
+ kind: SpanKind;
142
+ origin: SpanOrigin;
143
+ sessionId?: string;
144
+ jobName?: string;
145
+ attrs?: Record<string, unknown>;
146
+ startedAt?: number;
147
+ }
148
+
149
+ export interface EndSpanInput {
150
+ outcome: SpanOutcome;
151
+ reason?: string;
152
+ endedAt?: number;
153
+ usage?: SpanUsage;
154
+ attrs?: Record<string, unknown>;
155
+ }
156
+
157
+ export interface RunSnapshot {
158
+ runId: string;
159
+ spans: SpanRow[];
160
+ events: SpanEventRow[];
161
+ /** Per-run high-water seq at the moment of the read, in the SAME
162
+ * transaction as the reads — the poller/subscriber baseline. */
163
+ highWaterSeq: number;
164
+ /** Global cursor at the same moment, for pinning a poller baseline. */
165
+ changeCursor: number;
166
+ }
167
+
168
+ export interface PruneOptions {
169
+ /** Spans of runs that ended before this are prunable (digest floor).
170
+ * Absolute epoch ms, not an offset. */
171
+ digestFloorAt: number;
172
+ /** Runs older than this are pruned REGARDLESS of the digest floor. */
173
+ hardCeilingMs: number;
174
+ now?: number;
175
+ /** Max runs pruned per call — pruning is batched so writers are not starved. */
176
+ batch?: number;
177
+ }
178
+
179
+ /** A single event payload is capped so no delta can approach the WS frame cap. */
180
+ export const MAX_EVENT_PAYLOAD_BYTES = 16_384;
181
+ export const TRUNCATION_MARKER = "…[truncated]";
182
+
183
+ export interface ActivityStore {
184
+ readonly writer: string;
185
+ startSpan(input: StartSpanInput): SpanRow;
186
+ /**
187
+ * Terminal write. Write-once: returns false (and writes nothing) if the
188
+ * span is already terminal or unknown. Merged-outcome precedence lives in
189
+ * the CALLER (the host merges reporter enrichment before its single
190
+ * terminal write); the store just enforces once-ness.
191
+ */
192
+ endSpan(spanId: string, input: EndSpanInput): boolean;
193
+ /** Non-terminal field updates (usage enrichment, wait boundary, attrs). */
194
+ patchSpan(
195
+ spanId: string,
196
+ patch: { attrs?: Record<string, unknown>; usage?: SpanUsage; waitUntil?: number }
197
+ ): boolean;
198
+ appendEvent(spanId: string, eventType: string, payload: unknown, ts?: number): SpanEventRow | null;
199
+ /** External writers touch their root span so staleness is heartbeat-age based. */
200
+ heartbeat(spanId: string, at?: number): void;
201
+ /** Close every open span of a run as `outcome` (children first), reason on all. */
202
+ cascadeClose(runId: string, outcome: SpanOutcome, reason: string): number;
203
+ /** Boot sweep: close THIS writer's leftover open spans as interrupted. */
204
+ sweepOwnOrphans(): number;
205
+ /** Close open spans whose root heartbeat (or own writer liveness) went stale. */
206
+ sweepStale(staleAfterMs: number, now?: number): number;
207
+ /** Open root spans running longer than the threshold — the watchdog signal. */
208
+ findStuck(thresholdMs: number, now?: number): SpanRow[];
209
+ changesSince(changeCursor: number, limit?: number): ActivityChange[];
210
+ /**
211
+ * Changes past the cursor whose span is a TERMINAL ROOT — the notifier's
212
+ * detection query, filtered and joined SQL-side. One row per span (the
213
+ * highest change_id it appears under).
214
+ */
215
+ terminalRootChangesSince(
216
+ changeCursor: number,
217
+ limit?: number
218
+ ): Array<{ changeId: number; span: SpanRow }>;
219
+ latestChangeCursor(): number;
220
+ snapshotRun(runId: string): RunSnapshot | null;
221
+ /** The run's high-water seq — what a full snapshot carries, without the reads. */
222
+ runHighWaterSeq(runId: string): number;
223
+ getSpan(spanId: string): SpanRow | null;
224
+ openRootSpans(): SpanRow[];
225
+ /** Upsert the run's rollup row from current span state (call on terminal). */
226
+ rollupRun(runId: string): void;
227
+ prune(options: PruneOptions): { runsPruned: number; spansDeleted: number };
228
+ }
229
+
230
+ export interface CreateActivityStoreOptions {
231
+ /** Process identity stamped on every span this store writes. */
232
+ writer?: string;
233
+ }
234
+
235
+ export function createActivityStore(
236
+ db: Database,
237
+ options: CreateActivityStoreOptions = {}
238
+ ): ActivityStore {
239
+ const writer = options.writer ?? `pid:${process.pid}:${Date.now()}`;
240
+
241
+ // bun:sqlite transactions: `.immediate` takes the write lock up front, so a
242
+ // concurrent writer waits (busy_timeout) instead of failing mid-upgrade.
243
+ const inWrite = <T>(fn: () => T): T => db.transaction(fn).immediate();
244
+
245
+ function nextSeq(runId: string): number {
246
+ const row = db
247
+ .query("SELECT COALESCE(MAX(seq), 0) AS hi FROM activity_changes WHERE run_id = ?")
248
+ .get(runId) as { hi: number };
249
+ return row.hi + 1;
250
+ }
251
+
252
+ function logChange(runId: string, seq: number, spanId: string, eventIndex?: number) {
253
+ db.query(
254
+ "INSERT INTO activity_changes (run_id, seq, span_id, event_index) VALUES (?, ?, ?, ?)"
255
+ ).run(runId, seq, spanId, eventIndex ?? null);
256
+ }
257
+
258
+ function rowToSpan(r: any): SpanRow {
259
+ return {
260
+ spanId: r.span_id,
261
+ runId: r.run_id,
262
+ parentSpanId: r.parent_span_id,
263
+ name: r.name,
264
+ kind: r.kind,
265
+ origin: r.origin,
266
+ sessionId: r.session_id,
267
+ jobName: r.job_name,
268
+ attrs: safeParse(r.attrs) ?? {},
269
+ startedAt: r.started_at,
270
+ waitUntil: r.wait_until,
271
+ endedAt: r.ended_at,
272
+ outcome: r.outcome,
273
+ outcomeReason: r.outcome_reason,
274
+ usage: {
275
+ inputTokens: r.input_tokens ?? undefined,
276
+ outputTokens: r.output_tokens ?? undefined,
277
+ cacheReadTokens: r.cache_read_tokens ?? undefined,
278
+ cacheCreationTokens: r.cache_creation_tokens ?? undefined,
279
+ costUsd: r.cost_usd ?? undefined,
280
+ model: r.model ?? undefined,
281
+ },
282
+ writer: r.writer,
283
+ lastHeartbeatAt: r.last_heartbeat_at,
284
+ };
285
+ }
286
+
287
+ function rowToEvent(r: any): SpanEventRow {
288
+ const parsed = safeParse(r.payload) as { v?: unknown; truncated?: boolean } | undefined;
289
+ return {
290
+ spanId: r.span_id,
291
+ eventIndex: r.event_index,
292
+ ts: r.ts,
293
+ eventType: r.event_type,
294
+ payload: parsed?.v,
295
+ truncated: parsed?.truncated === true,
296
+ };
297
+ }
298
+
299
+ function getSpanRaw(spanId: string): SpanRow | null {
300
+ const r = db.query("SELECT * FROM activity_spans WHERE span_id = ?").get(spanId);
301
+ return r ? rowToSpan(r) : null;
302
+ }
303
+
304
+ function runHighWaterSeqRaw(runId: string): number {
305
+ const row = db
306
+ .query("SELECT COALESCE(MAX(seq), 0) AS hi FROM activity_changes WHERE run_id = ?")
307
+ .get(runId) as { hi: number };
308
+ return row.hi;
309
+ }
310
+
311
+ function endSpanInTx(spanId: string, input: EndSpanInput): boolean {
312
+ const existing = db
313
+ .query("SELECT run_id, outcome, attrs FROM activity_spans WHERE span_id = ?")
314
+ .get(spanId) as { run_id: string; outcome: string | null; attrs: string | null } | null;
315
+ if (!existing || existing.outcome !== null) return false;
316
+
317
+ const endedAt = input.endedAt ?? Date.now();
318
+ const attrs = input.attrs
319
+ ? JSON.stringify({ ...(safeParse(existing.attrs) ?? {}), ...input.attrs })
320
+ : existing.attrs;
321
+ const u = input.usage ?? {};
322
+ db.query(
323
+ `UPDATE activity_spans SET outcome = ?, outcome_reason = ?, ended_at = ?, attrs = ?,
324
+ input_tokens = COALESCE(?, input_tokens),
325
+ output_tokens = COALESCE(?, output_tokens),
326
+ cache_read_tokens = COALESCE(?, cache_read_tokens),
327
+ cache_creation_tokens = COALESCE(?, cache_creation_tokens),
328
+ cost_usd = COALESCE(?, cost_usd),
329
+ model = COALESCE(?, model)
330
+ WHERE span_id = ?`
331
+ ).run(
332
+ input.outcome,
333
+ input.reason ?? null,
334
+ endedAt,
335
+ attrs,
336
+ u.inputTokens ?? null,
337
+ u.outputTokens ?? null,
338
+ u.cacheReadTokens ?? null,
339
+ u.cacheCreationTokens ?? null,
340
+ u.costUsd ?? null,
341
+ u.model ?? null,
342
+ spanId
343
+ );
344
+ logChange(existing.run_id, nextSeq(existing.run_id), spanId);
345
+ return true;
346
+ }
347
+
348
+ /** Close every open span of the run (children first) and roll it up. */
349
+ function closeRunInTx(runId: string, outcome: SpanOutcome, reason: string): number {
350
+ const open = db
351
+ .query(
352
+ "SELECT span_id FROM activity_spans WHERE run_id = ? AND outcome IS NULL ORDER BY started_at DESC"
353
+ )
354
+ .all(runId) as Array<{ span_id: string }>;
355
+ let closed = 0;
356
+ for (const { span_id } of open) {
357
+ if (endSpanInTx(span_id, { outcome, reason })) closed++;
358
+ }
359
+ if (closed > 0) rollupRunInTx(runId);
360
+ return closed;
361
+ }
362
+
363
+ function rollupRunInTx(runId: string) {
364
+ const spans = db
365
+ .query("SELECT * FROM activity_spans WHERE run_id = ? ORDER BY started_at")
366
+ .all(runId)
367
+ .map(rowToSpan);
368
+ if (spans.length === 0) return;
369
+ const root = spans.find((s) => s.parentSpanId === null) ?? spans[0]!;
370
+ // Aggregation scope: ROOT spans only. Result-level accounting (the
371
+ // SDK's modelUsage) already includes subagent consumption — summing the
372
+ // tree would double-count every fan-out. Verified empirically (plan U3
373
+ // smoke test).
374
+ const failure =
375
+ spans.find(
376
+ (s) => (s.outcome === "error" || s.outcome === "timeout") && s.outcomeReason != null
377
+ )?.outcomeReason ?? (root.outcome === "interrupted" ? "interrupted" : null);
378
+ db.query(
379
+ `INSERT INTO activity_run_rollups
380
+ (run_id, origin, name, session_id, job_name, started_at, ended_at, outcome,
381
+ duration_ms, span_count, input_tokens, output_tokens, cache_read_tokens,
382
+ cache_creation_tokens, cost_usd, failure_reason, detail_pruned)
383
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
384
+ ON CONFLICT(run_id) DO UPDATE SET
385
+ ended_at = excluded.ended_at, outcome = excluded.outcome,
386
+ duration_ms = excluded.duration_ms, span_count = excluded.span_count,
387
+ input_tokens = excluded.input_tokens, output_tokens = excluded.output_tokens,
388
+ cache_read_tokens = excluded.cache_read_tokens,
389
+ cache_creation_tokens = excluded.cache_creation_tokens,
390
+ cost_usd = excluded.cost_usd, failure_reason = excluded.failure_reason`
391
+ ).run(
392
+ runId,
393
+ root.origin,
394
+ root.name,
395
+ root.sessionId,
396
+ root.jobName,
397
+ root.startedAt,
398
+ root.endedAt,
399
+ root.outcome,
400
+ root.endedAt !== null ? root.endedAt - root.startedAt : null,
401
+ spans.length,
402
+ root.usage.inputTokens ?? null,
403
+ root.usage.outputTokens ?? null,
404
+ root.usage.cacheReadTokens ?? null,
405
+ root.usage.cacheCreationTokens ?? null,
406
+ root.usage.costUsd ?? null,
407
+ failure
408
+ );
409
+ }
410
+
411
+ return {
412
+ writer,
413
+
414
+ startSpan(input) {
415
+ return inWrite(() => {
416
+ const startedAt = input.startedAt ?? Date.now();
417
+ db.query(
418
+ `INSERT INTO activity_spans
419
+ (span_id, run_id, parent_span_id, name, kind, origin, session_id, job_name,
420
+ attrs, started_at, writer, last_heartbeat_at)
421
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
422
+ ).run(
423
+ input.spanId,
424
+ input.runId,
425
+ input.parentSpanId ?? null,
426
+ input.name,
427
+ input.kind,
428
+ input.origin,
429
+ input.sessionId ?? null,
430
+ input.jobName ?? null,
431
+ input.attrs ? JSON.stringify(input.attrs) : null,
432
+ startedAt,
433
+ writer,
434
+ input.parentSpanId ? null : startedAt
435
+ );
436
+ logChange(input.runId, nextSeq(input.runId), input.spanId);
437
+ return getSpanRaw(input.spanId)!;
438
+ });
439
+ },
440
+
441
+ endSpan(spanId, input) {
442
+ return inWrite(() => endSpanInTx(spanId, input));
443
+ },
444
+
445
+ patchSpan(spanId, patch) {
446
+ return inWrite(() => {
447
+ const existing = db
448
+ .query("SELECT run_id, outcome, attrs FROM activity_spans WHERE span_id = ?")
449
+ .get(spanId) as { run_id: string; outcome: string | null; attrs: string | null } | null;
450
+ if (!existing || existing.outcome !== null) return false;
451
+ const attrs = patch.attrs
452
+ ? JSON.stringify({ ...(safeParse(existing.attrs) ?? {}), ...patch.attrs })
453
+ : existing.attrs;
454
+ const u = patch.usage ?? {};
455
+ db.query(
456
+ `UPDATE activity_spans SET attrs = ?, wait_until = COALESCE(?, wait_until),
457
+ input_tokens = COALESCE(?, input_tokens),
458
+ output_tokens = COALESCE(?, output_tokens),
459
+ cache_read_tokens = COALESCE(?, cache_read_tokens),
460
+ cache_creation_tokens = COALESCE(?, cache_creation_tokens),
461
+ cost_usd = COALESCE(?, cost_usd),
462
+ model = COALESCE(?, model)
463
+ WHERE span_id = ?`
464
+ ).run(
465
+ attrs,
466
+ patch.waitUntil ?? null,
467
+ u.inputTokens ?? null,
468
+ u.outputTokens ?? null,
469
+ u.cacheReadTokens ?? null,
470
+ u.cacheCreationTokens ?? null,
471
+ u.costUsd ?? null,
472
+ u.model ?? null,
473
+ spanId
474
+ );
475
+ logChange(existing.run_id, nextSeq(existing.run_id), spanId);
476
+ return true;
477
+ });
478
+ },
479
+
480
+ appendEvent(spanId, eventType, payload, ts) {
481
+ return inWrite(() => {
482
+ const span = db
483
+ .query("SELECT run_id FROM activity_spans WHERE span_id = ?")
484
+ .get(spanId) as { run_id: string } | null;
485
+ if (!span) return null;
486
+ const next = db
487
+ .query(
488
+ "SELECT COALESCE(MAX(event_index), -1) + 1 AS idx FROM activity_events WHERE span_id = ?"
489
+ )
490
+ .get(spanId) as { idx: number };
491
+ const stored = capPayload(payload);
492
+ db.query(
493
+ "INSERT INTO activity_events (span_id, event_index, ts, event_type, payload) VALUES (?, ?, ?, ?, ?)"
494
+ ).run(spanId, next.idx, ts ?? Date.now(), eventType, JSON.stringify(stored));
495
+ logChange(span.run_id, nextSeq(span.run_id), spanId, next.idx);
496
+ const r = db
497
+ .query("SELECT * FROM activity_events WHERE span_id = ? AND event_index = ?")
498
+ .get(spanId, next.idx);
499
+ return rowToEvent(r);
500
+ });
501
+ },
502
+
503
+ heartbeat(spanId, at) {
504
+ inWrite(() => {
505
+ // Deliberately NOT change-logged: a heartbeat is liveness metadata,
506
+ // not activity the client needs a delta for.
507
+ db.query(
508
+ "UPDATE activity_spans SET last_heartbeat_at = ? WHERE span_id = ? AND outcome IS NULL"
509
+ ).run(at ?? Date.now(), spanId);
510
+ });
511
+ },
512
+
513
+ cascadeClose(runId, outcome, reason) {
514
+ return inWrite(() => closeRunInTx(runId, outcome, reason));
515
+ },
516
+
517
+ sweepOwnOrphans() {
518
+ // "Own" means this PROCESS IDENTITY's rows from a previous life. The
519
+ // writer stamp includes the start time, so rows written by the
520
+ // current instance never match a fresh store's sweep... but a boot
521
+ // sweep runs before any spans are written, so sweeping by pid-prefix
522
+ // alone would be wrong across pid reuse. Sweep every session-origin
523
+ // open span instead: only THIS server writes session spans, and at
524
+ // boot none of ours can legitimately be open.
525
+ //
526
+ // Candidates are read OUTSIDE the write transaction — the common case
527
+ // finds nothing and must not take the exclusive lock for it. The close
528
+ // loop re-checks open-ness inside the transaction (endSpanInTx is
529
+ // write-once), so a race just skips.
530
+ const open = db
531
+ .query(
532
+ "SELECT DISTINCT run_id FROM activity_spans WHERE outcome IS NULL AND origin = 'session'"
533
+ )
534
+ .all() as Array<{ run_id: string }>;
535
+ if (open.length === 0) return 0;
536
+ return inWrite(() => {
537
+ let closed = 0;
538
+ for (const { run_id } of open) {
539
+ closed += closeRunInTx(run_id, "interrupted", "server restarted");
540
+ }
541
+ return closed;
542
+ });
543
+ },
544
+
545
+ sweepStale(staleAfterMs, now) {
546
+ const cutoff = (now ?? Date.now()) - staleAfterMs;
547
+ // Staleness is judged on ROOT heartbeat age — never span age — so a
548
+ // legitimately long, quiet run with a live writer is never killed.
549
+ // Candidate read outside the write transaction, same as sweepOwnOrphans.
550
+ const staleRoots = db
551
+ .query(
552
+ `SELECT span_id, run_id FROM activity_spans
553
+ WHERE outcome IS NULL AND parent_span_id IS NULL
554
+ AND writer != ? AND COALESCE(last_heartbeat_at, started_at) < ?`
555
+ )
556
+ .all(writer, cutoff) as Array<{ span_id: string; run_id: string }>;
557
+ if (staleRoots.length === 0) return 0;
558
+ return inWrite(() => {
559
+ let closed = 0;
560
+ for (const { run_id } of staleRoots) {
561
+ closed += closeRunInTx(run_id, "interrupted", "writer went silent");
562
+ }
563
+ return closed;
564
+ });
565
+ },
566
+
567
+ findStuck(thresholdMs, now) {
568
+ const cutoff = (now ?? Date.now()) - thresholdMs;
569
+ return (
570
+ db
571
+ .query(
572
+ "SELECT * FROM activity_spans WHERE outcome IS NULL AND parent_span_id IS NULL AND started_at < ?"
573
+ )
574
+ .all(cutoff) as any[]
575
+ ).map(rowToSpan);
576
+ },
577
+
578
+ changesSince(changeCursor, limit = 500) {
579
+ // Set-based: one join per change kind instead of a lookup per row. A
580
+ // change whose span/event row was pruned drops out via the join, same
581
+ // as the old per-row miss.
582
+ const spanRows = db
583
+ .query(
584
+ `SELECT c.change_id, c.run_id, c.seq, s.*
585
+ FROM activity_changes c
586
+ JOIN activity_spans s ON s.span_id = c.span_id
587
+ WHERE c.change_id > ? AND c.event_index IS NULL
588
+ ORDER BY c.change_id LIMIT ?`
589
+ )
590
+ .all(changeCursor, limit) as any[];
591
+ const eventRows = db
592
+ .query(
593
+ `SELECT c.change_id, c.run_id, c.seq, e.*
594
+ FROM activity_changes c
595
+ JOIN activity_events e
596
+ ON e.span_id = c.span_id AND e.event_index = c.event_index
597
+ WHERE c.change_id > ? AND c.event_index IS NOT NULL
598
+ ORDER BY c.change_id LIMIT ?`
599
+ )
600
+ .all(changeCursor, limit) as any[];
601
+ const changes: ActivityChange[] = [
602
+ ...spanRows.map(
603
+ (r): ActivityChange => ({
604
+ changeId: r.change_id,
605
+ runId: r.run_id,
606
+ seq: r.seq,
607
+ kind: "span",
608
+ span: rowToSpan(r),
609
+ })
610
+ ),
611
+ ...eventRows.map(
612
+ (r): ActivityChange => ({
613
+ changeId: r.change_id,
614
+ runId: r.run_id,
615
+ seq: r.seq,
616
+ kind: "event",
617
+ event: rowToEvent(r),
618
+ })
619
+ ),
620
+ ];
621
+ changes.sort((a, b) => a.changeId - b.changeId);
622
+ return changes.length > limit ? changes.slice(0, limit) : changes;
623
+ },
624
+
625
+ terminalRootChangesSince(changeCursor, limit = 500) {
626
+ const rows = db
627
+ .query(
628
+ `SELECT MAX(c.change_id) AS change_id, s.*
629
+ FROM activity_changes c
630
+ JOIN activity_spans s ON s.span_id = c.span_id
631
+ WHERE c.change_id > ? AND c.event_index IS NULL
632
+ AND s.parent_span_id IS NULL AND s.outcome IS NOT NULL
633
+ GROUP BY s.span_id
634
+ ORDER BY change_id LIMIT ?`
635
+ )
636
+ .all(changeCursor, limit) as any[];
637
+ return rows.map((r) => ({ changeId: r.change_id, span: rowToSpan(r) }));
638
+ },
639
+
640
+ latestChangeCursor() {
641
+ const row = db
642
+ .query("SELECT COALESCE(MAX(change_id), 0) AS hi FROM activity_changes")
643
+ .get() as { hi: number };
644
+ return row.hi;
645
+ },
646
+
647
+ snapshotRun(runId) {
648
+ // A read transaction so spans, events, high-water seq, and the global
649
+ // cursor are one consistent picture — the poller baseline is pinned to
650
+ // exactly this moment (no gap between snapshot and first delta).
651
+ return db.transaction(() => {
652
+ const spans = (
653
+ db
654
+ .query("SELECT * FROM activity_spans WHERE run_id = ? ORDER BY started_at")
655
+ .all(runId) as any[]
656
+ ).map(rowToSpan);
657
+ if (spans.length === 0) return null;
658
+ const events = (
659
+ db
660
+ .query(
661
+ `SELECT e.* FROM activity_events e
662
+ JOIN activity_spans s ON s.span_id = e.span_id
663
+ WHERE s.run_id = ? ORDER BY e.ts, e.event_index`
664
+ )
665
+ .all(runId) as any[]
666
+ ).map(rowToEvent);
667
+ const cursor = db
668
+ .query("SELECT COALESCE(MAX(change_id), 0) AS hi FROM activity_changes")
669
+ .get() as { hi: number };
670
+ return {
671
+ runId,
672
+ spans,
673
+ events,
674
+ highWaterSeq: runHighWaterSeqRaw(runId),
675
+ changeCursor: cursor.hi,
676
+ };
677
+ })();
678
+ },
679
+
680
+ runHighWaterSeq: runHighWaterSeqRaw,
681
+
682
+ getSpan: getSpanRaw,
683
+
684
+ openRootSpans() {
685
+ return (
686
+ db
687
+ .query(
688
+ "SELECT * FROM activity_spans WHERE outcome IS NULL AND parent_span_id IS NULL ORDER BY started_at DESC"
689
+ )
690
+ .all() as any[]
691
+ ).map(rowToSpan);
692
+ },
693
+
694
+ rollupRun(runId) {
695
+ inWrite(() => rollupRunInTx(runId));
696
+ },
697
+
698
+ prune(options) {
699
+ const now = options.now ?? Date.now();
700
+ const batch = options.batch ?? 50;
701
+ // The digest floor gates pruning, but a dead digest job must not freeze
702
+ // it forever: the hard ceiling prunes regardless (marking the rollup so
703
+ // the coverage gap is visible).
704
+ const floor = Math.max(options.digestFloorAt, 0);
705
+ const ceiling = now - options.hardCeilingMs;
706
+ return inWrite(() => {
707
+ // Candidates come from the rollups (they exist for every finished
708
+ // run — that terminal write is what made the run prunable), guarded
709
+ // against any run that still has an open span.
710
+ const candidates = db
711
+ .query(
712
+ `SELECT run_id, ended_at AS ended FROM activity_run_rollups r
713
+ WHERE detail_pruned = 0 AND ended_at IS NOT NULL
714
+ AND (ended_at < ? OR ended_at < ?)
715
+ AND NOT EXISTS (
716
+ SELECT 1 FROM activity_spans s
717
+ WHERE s.run_id = r.run_id AND s.outcome IS NULL
718
+ )
719
+ LIMIT ?`
720
+ )
721
+ .all(floor, ceiling, batch) as Array<{ run_id: string; ended: number }>;
722
+ let spansDeleted = 0;
723
+ for (const { run_id, ended } of candidates) {
724
+ db.query(
725
+ "UPDATE activity_run_rollups SET detail_pruned = 1 WHERE run_id = ?"
726
+ ).run(run_id);
727
+ if (ended >= floor) {
728
+ // Pruned by the hard ceiling alone — the digest never covered
729
+ // this run; make the coverage gap visible on the rollup.
730
+ db.query(
731
+ "UPDATE activity_run_rollups SET failure_reason = COALESCE(failure_reason, 'digest coverage gap') WHERE run_id = ?"
732
+ ).run(run_id);
733
+ }
734
+ db.query(
735
+ `DELETE FROM activity_events WHERE span_id IN
736
+ (SELECT span_id FROM activity_spans WHERE run_id = ?)`
737
+ ).run(run_id);
738
+ const res = db.query("DELETE FROM activity_spans WHERE run_id = ?").run(run_id);
739
+ spansDeleted += res.changes;
740
+ db.query("DELETE FROM activity_changes WHERE run_id = ?").run(run_id);
741
+ }
742
+ // The change log only serves live polling; rows this deep in the past
743
+ // are unreachable by any live cursor. Keep runs with open spans.
744
+ db.query(
745
+ `DELETE FROM activity_changes WHERE change_id < (
746
+ SELECT COALESCE(MAX(change_id), 0) FROM activity_changes
747
+ ) - 100000 AND run_id NOT IN (
748
+ SELECT DISTINCT run_id FROM activity_spans WHERE outcome IS NULL
749
+ )`
750
+ ).run();
751
+ return { runsPruned: candidates.length, spansDeleted };
752
+ });
753
+ },
754
+ };
755
+ }
756
+
757
+ function safeParse(text: string | null): Record<string, unknown> | undefined {
758
+ if (!text) return undefined;
759
+ try {
760
+ return JSON.parse(text);
761
+ } catch {
762
+ return undefined;
763
+ }
764
+ }
765
+
766
+ /** Cap a payload's serialized size, storing an explicit truncation marker. */
767
+ function capPayload(payload: unknown): { v: unknown; truncated?: boolean } {
768
+ const json = JSON.stringify(payload ?? null);
769
+ if (json.length <= MAX_EVENT_PAYLOAD_BYTES) return { v: payload ?? null };
770
+ if (typeof payload === "string") {
771
+ return { v: payload.slice(0, MAX_EVENT_PAYLOAD_BYTES) + TRUNCATION_MARKER, truncated: true };
772
+ }
773
+ return { v: json.slice(0, MAX_EVENT_PAYLOAD_BYTES) + TRUNCATION_MARKER, truncated: true };
774
+ }