@schlessera/brain-ui-server 0.17.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 (112) hide show
  1. package/README.md +1 -0
  2. package/dist/activity/digest.d.ts +29 -0
  3. package/dist/activity/digest.d.ts.map +1 -0
  4. package/dist/activity/digest.js +61 -0
  5. package/dist/activity/digest.js.map +1 -0
  6. package/dist/activity/notify.d.ts +62 -0
  7. package/dist/activity/notify.d.ts.map +1 -0
  8. package/dist/activity/notify.js +171 -0
  9. package/dist/activity/notify.js.map +1 -0
  10. package/dist/activity/push-sender.d.ts +63 -0
  11. package/dist/activity/push-sender.d.ts.map +1 -0
  12. package/dist/activity/push-sender.js +131 -0
  13. package/dist/activity/push-sender.js.map +1 -0
  14. package/dist/activity/query.d.ts +16 -0
  15. package/dist/activity/query.d.ts.map +1 -0
  16. package/dist/activity/query.js +128 -0
  17. package/dist/activity/query.js.map +1 -0
  18. package/dist/activity/recorder.d.ts +48 -0
  19. package/dist/activity/recorder.d.ts.map +1 -0
  20. package/dist/activity/recorder.js +205 -0
  21. package/dist/activity/recorder.js.map +1 -0
  22. package/dist/activity/runtime.d.ts +31 -0
  23. package/dist/activity/runtime.d.ts.map +1 -0
  24. package/dist/activity/runtime.js +109 -0
  25. package/dist/activity/runtime.js.map +1 -0
  26. package/dist/activity/span-sink.d.ts +22 -0
  27. package/dist/activity/span-sink.d.ts.map +1 -0
  28. package/dist/activity/span-sink.js +138 -0
  29. package/dist/activity/span-sink.js.map +1 -0
  30. package/dist/activity/store.d.ts +207 -0
  31. package/dist/activity/store.d.ts.map +1 -0
  32. package/dist/activity/store.js +440 -0
  33. package/dist/activity/store.js.map +1 -0
  34. package/dist/activity/stream.d.ts +45 -0
  35. package/dist/activity/stream.d.ts.map +1 -0
  36. package/dist/activity/stream.js +312 -0
  37. package/dist/activity/stream.js.map +1 -0
  38. package/dist/app.d.ts.map +1 -1
  39. package/dist/app.js +20 -1
  40. package/dist/app.js.map +1 -1
  41. package/dist/config/env.d.ts +5 -0
  42. package/dist/config/env.d.ts.map +1 -1
  43. package/dist/config/env.js +12 -0
  44. package/dist/config/env.js.map +1 -1
  45. package/dist/cron/scheduler.d.ts.map +1 -1
  46. package/dist/cron/scheduler.js +20 -5
  47. package/dist/cron/scheduler.js.map +1 -1
  48. package/dist/db/client.d.ts.map +1 -1
  49. package/dist/db/client.js +32 -6
  50. package/dist/db/client.js.map +1 -1
  51. package/dist/index.d.ts +4 -0
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +7 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/routes/activity.d.ts +20 -0
  56. package/dist/routes/activity.d.ts.map +1 -0
  57. package/dist/routes/activity.js +300 -0
  58. package/dist/routes/activity.js.map +1 -0
  59. package/dist/routes/push.d.ts +6 -0
  60. package/dist/routes/push.d.ts.map +1 -0
  61. package/dist/routes/push.js +73 -0
  62. package/dist/routes/push.js.map +1 -0
  63. package/dist/routes/sessions.d.ts.map +1 -1
  64. package/dist/routes/sessions.js +20 -4
  65. package/dist/routes/sessions.js.map +1 -1
  66. package/dist/ws/bridge.d.ts +2 -1
  67. package/dist/ws/bridge.d.ts.map +1 -1
  68. package/dist/ws/bridge.js +45 -3
  69. package/dist/ws/bridge.js.map +1 -1
  70. package/dist/ws/connection.d.ts.map +1 -1
  71. package/dist/ws/connection.js +41 -5
  72. package/dist/ws/connection.js.map +1 -1
  73. package/dist/ws/dispatch.d.ts.map +1 -1
  74. package/dist/ws/dispatch.js +11 -0
  75. package/dist/ws/dispatch.js.map +1 -1
  76. package/dist/ws/host.d.ts +16 -0
  77. package/dist/ws/host.d.ts.map +1 -1
  78. package/dist/ws/host.js +2 -0
  79. package/dist/ws/host.js.map +1 -1
  80. package/dist/ws/run-session.d.ts.map +1 -1
  81. package/dist/ws/run-session.js +25 -1
  82. package/dist/ws/run-session.js.map +1 -1
  83. package/dist/ws/turns.d.ts +22 -2
  84. package/dist/ws/turns.d.ts.map +1 -1
  85. package/dist/ws/turns.js +13 -0
  86. package/dist/ws/turns.js.map +1 -1
  87. package/migrations/007_activity.sql +114 -0
  88. package/migrations/008_push_subscriptions.sql +24 -0
  89. package/package.json +5 -3
  90. package/src/activity/digest.ts +92 -0
  91. package/src/activity/notify.ts +285 -0
  92. package/src/activity/push-sender.ts +215 -0
  93. package/src/activity/query.ts +160 -0
  94. package/src/activity/recorder.ts +261 -0
  95. package/src/activity/runtime.ts +141 -0
  96. package/src/activity/span-sink.ts +152 -0
  97. package/src/activity/store.ts +774 -0
  98. package/src/activity/stream.ts +366 -0
  99. package/src/app.ts +21 -1
  100. package/src/config/env.ts +19 -0
  101. package/src/cron/scheduler.ts +28 -8
  102. package/src/db/client.ts +31 -6
  103. package/src/index.ts +22 -0
  104. package/src/routes/activity.ts +363 -0
  105. package/src/routes/push.ts +90 -0
  106. package/src/routes/sessions.ts +24 -4
  107. package/src/ws/bridge.ts +47 -3
  108. package/src/ws/connection.ts +57 -5
  109. package/src/ws/dispatch.ts +13 -0
  110. package/src/ws/host.ts +18 -0
  111. package/src/ws/run-session.ts +32 -1
  112. package/src/ws/turns.ts +29 -1
@@ -0,0 +1,215 @@
1
+ /**
2
+ * The accelerator tier: web push delivery for pending notification intents.
3
+ *
4
+ * VAPID keys are generated at first boot into their own table (see migration
5
+ * 008 for why not the settings KV) and never leave the process. Payloads are
6
+ * MINIMIZED — title + outcome word + a deep link — because push renders on
7
+ * lock screens outside the app's auth; detail lives behind the authenticated
8
+ * tap-through.
9
+ *
10
+ * Delivery marks the intent sent/send_failed; the inbox (guaranteed tier)
11
+ * is untouched by any of it. A 404/410 response prunes the subscription —
12
+ * the push service says that device is gone. When every send in a pass
13
+ * fails, that is the all-devices signal (VAPID invalidated by a KV
14
+ * wipe/restore, typically) and it is logged loudly; the client surfaces a
15
+ * re-enable prompt when its subscription check disagrees with the server.
16
+ */
17
+ import type { Database } from "bun:sqlite";
18
+ import type { Logger } from "@opentelemetry/api-logs";
19
+ import webpush from "web-push";
20
+
21
+ import type { ActivityNotifier } from "./notify.js";
22
+
23
+ export interface PushSubscriptionRow {
24
+ endpoint: string;
25
+ p256dh: string;
26
+ auth: string;
27
+ label: string | null;
28
+ createdAt: number;
29
+ lastUsedAt: number | null;
30
+ }
31
+
32
+ export interface PushSender {
33
+ publicKey(): string;
34
+ subscribe(sub: { endpoint: string; keys: { p256dh: string; auth: string } }, label?: string): void;
35
+ unsubscribe(endpoint: string): boolean;
36
+ subscriptions(): PushSubscriptionRow[];
37
+ /** Deliver pending intents to every subscription. Returns sends attempted. */
38
+ deliverPending(notifier: ActivityNotifier): Promise<number>;
39
+ }
40
+
41
+ export interface CreatePushSenderOptions {
42
+ /** Injection seam for tests — the real webpush.sendNotification otherwise. */
43
+ send?: (
44
+ subscription: { endpoint: string; keys: { p256dh: string; auth: string } },
45
+ payload: string,
46
+ options: {
47
+ vapidDetails: { subject: string; publicKey: string; privateKey: string };
48
+ timeout?: number;
49
+ }
50
+ ) => Promise<unknown>;
51
+ /** `mailto:` or https contact required by the VAPID spec. */
52
+ subject?: string;
53
+ log?: Logger;
54
+ }
55
+
56
+ /** Per-send cap: a hung push service rejects instead of wedging the
57
+ * delivering guard (the tick's reentrancy flag) forever. */
58
+ const SEND_TIMEOUT_MS = 10_000;
59
+
60
+ export function createPushSender(
61
+ db: Database,
62
+ options: CreatePushSenderOptions = {}
63
+ ): PushSender {
64
+ const log = options.log;
65
+ const subject = options.subject ?? "mailto:admin@localhost";
66
+ const send =
67
+ options.send ??
68
+ ((sub, payload, opts) =>
69
+ webpush.sendNotification(
70
+ { endpoint: sub.endpoint, keys: sub.keys },
71
+ payload,
72
+ { vapidDetails: opts.vapidDetails, timeout: opts.timeout }
73
+ ));
74
+
75
+ // Generate-once VAPID keys. Concurrent first boots are safe: the INSERT is
76
+ // OR IGNORE and the read-back wins.
77
+ function vapid(): { publicKey: string; privateKey: string } {
78
+ const row = db
79
+ .query("SELECT public_key AS publicKey, private_key AS privateKey FROM vapid_keys WHERE id = 1")
80
+ .get() as { publicKey: string; privateKey: string } | null;
81
+ if (row) return row;
82
+ const generated = webpush.generateVAPIDKeys();
83
+ db.query(
84
+ "INSERT OR IGNORE INTO vapid_keys (id, public_key, private_key, created_at) VALUES (1, ?, ?, ?)"
85
+ ).run(generated.publicKey, generated.privateKey, Date.now());
86
+ return vapid();
87
+ }
88
+
89
+ function rows(): PushSubscriptionRow[] {
90
+ return (
91
+ db.query("SELECT * FROM push_subscriptions ORDER BY created_at").all() as any[]
92
+ ).map((r) => ({
93
+ endpoint: r.endpoint,
94
+ p256dh: r.p256dh,
95
+ auth: r.auth,
96
+ label: r.label,
97
+ createdAt: r.created_at,
98
+ lastUsedAt: r.last_used_at,
99
+ }));
100
+ }
101
+
102
+ return {
103
+ publicKey() {
104
+ return vapid().publicKey;
105
+ },
106
+
107
+ subscribe(sub, label) {
108
+ db.query(
109
+ `INSERT INTO push_subscriptions (endpoint, p256dh, auth, label, created_at)
110
+ VALUES (?, ?, ?, ?, ?)
111
+ ON CONFLICT(endpoint) DO UPDATE SET p256dh = excluded.p256dh, auth = excluded.auth`
112
+ ).run(sub.endpoint, sub.keys.p256dh, sub.keys.auth, label ?? null, Date.now());
113
+ },
114
+
115
+ unsubscribe(endpoint) {
116
+ return db.query("DELETE FROM push_subscriptions WHERE endpoint = ?").run(endpoint)
117
+ .changes > 0;
118
+ },
119
+
120
+ subscriptions: rows,
121
+
122
+ async deliverPending(notifier) {
123
+ const pending = notifier.pending();
124
+ if (pending.length === 0) return 0;
125
+ if (rows().length === 0) {
126
+ // No devices: the inbox already has it; nothing to deliver. Leave
127
+ // the intents pending so a device subscribing later still gets them
128
+ // if they are fresh, and the boot sweep can retry.
129
+ return 0;
130
+ }
131
+ const keys = vapid();
132
+ let attempts = 0;
133
+
134
+ for (const intent of pending) {
135
+ // Re-read per intent: an endpoint pruned as dead during the previous
136
+ // intent's pass must not be attempted again in this one.
137
+ const subs = rows();
138
+ if (subs.length === 0) break;
139
+ // Minimized payload; the tag coalesces repeats per run across devices.
140
+ const payload = JSON.stringify({
141
+ title: intent.title,
142
+ body: intent.body,
143
+ tag: `brain-activity:${intent.runId}`,
144
+ url: `/#/activity/${encodeURIComponent(intent.runId)}`,
145
+ });
146
+ attempts += subs.length;
147
+ const results = await Promise.allSettled(
148
+ subs.map((sub) =>
149
+ send(
150
+ { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
151
+ payload,
152
+ {
153
+ vapidDetails: { subject, publicKey: keys.publicKey, privateKey: keys.privateKey },
154
+ timeout: SEND_TIMEOUT_MS,
155
+ }
156
+ )
157
+ )
158
+ );
159
+ // DB writes only after the whole settled pass — never concurrent
160
+ // with in-flight sends against the same handle.
161
+ let delivered = 0;
162
+ const touched: string[] = [];
163
+ const dead: string[] = [];
164
+ results.forEach((result, i) => {
165
+ const sub = subs[i]!;
166
+ if (result.status === "fulfilled") {
167
+ delivered++;
168
+ touched.push(sub.endpoint);
169
+ return;
170
+ }
171
+ const err = result.reason;
172
+ const status = (err as { statusCode?: number }).statusCode;
173
+ if (status === 404 || status === 410) {
174
+ // The push service says this device is gone.
175
+ dead.push(sub.endpoint);
176
+ log?.emit({
177
+ severityText: "INFO",
178
+ body: "pruned dead push subscription",
179
+ attributes: { status: status },
180
+ });
181
+ } else {
182
+ log?.emit({
183
+ severityText: "WARN",
184
+ body: "push send failed",
185
+ attributes: {
186
+ error: err instanceof Error ? err.message : String(err),
187
+ ...(status ? { status } : {}),
188
+ },
189
+ });
190
+ }
191
+ });
192
+ for (const endpoint of touched) {
193
+ db.query("UPDATE push_subscriptions SET last_used_at = ? WHERE endpoint = ?").run(
194
+ Date.now(),
195
+ endpoint
196
+ );
197
+ }
198
+ for (const endpoint of dead) {
199
+ db.query("DELETE FROM push_subscriptions WHERE endpoint = ?").run(endpoint);
200
+ }
201
+ notifier.markDelivered(intent.id, delivered > 0 ? "sent" : "send_failed");
202
+ if (delivered === 0) {
203
+ // Every device failed — the all-devices signal (invalid VAPID after
204
+ // a restore, typically). Loud, because it is silent on every phone.
205
+ log?.emit({
206
+ severityText: "ERROR",
207
+ body: "push delivery failed on every subscription",
208
+ attributes: { subscriptions: subs.length },
209
+ });
210
+ }
211
+ }
212
+ return attempts;
213
+ },
214
+ };
215
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * The agent-facing read over the activity record — the same data the UI
3
+ * reads, shaped for model consumption and served through the backend
4
+ * bridge's `queryActivity` seam (the MCP tool calls it).
5
+ *
6
+ * Read-only by construction: nothing here writes. Free-text fields that
7
+ * originated outside the primary agent's own context (failure reasons /
8
+ * stderr tails, subagent transcript excerpts) are DATA, not instructions —
9
+ * the tool layer labels them as such before they reach a model.
10
+ */
11
+ import type { Database } from "bun:sqlite";
12
+ import type { ActivityQuery, ActivityQueryResult } from "@schlessera/brain-ui-sdk/server";
13
+ import { isFailureOutcome } from "@schlessera/brain-ui-sdk/protocol";
14
+
15
+ import { latestActivityDigest } from "./digest.js";
16
+ import type { ActivityNotifier } from "./notify.js";
17
+ import { rowToRunRollup, type ActivityStore, type SpanRow } from "./store.js";
18
+
19
+ export function runActivityQuery(
20
+ db: Database,
21
+ store: ActivityStore,
22
+ query: ActivityQuery,
23
+ notifier?: ActivityNotifier
24
+ ): ActivityQueryResult {
25
+ const limit = Math.min(Math.max(query.limit ?? 20, 1), 100);
26
+ const hoursBack = Math.min(Math.max(query.hoursBack ?? 24, 1), 24 * 90);
27
+ const since = Date.now() - hoursBack * 60 * 60 * 1000;
28
+
29
+ switch (query.scope) {
30
+ case "running": {
31
+ return {
32
+ running: store.openRootSpans().map(liveSummary),
33
+ };
34
+ }
35
+
36
+ case "recent": {
37
+ const rows = (
38
+ db
39
+ .query(
40
+ "SELECT * FROM activity_run_rollups WHERE started_at >= ? ORDER BY started_at DESC LIMIT ?"
41
+ )
42
+ .all(since, limit) as any[]
43
+ ).map(rowToRunRollup);
44
+ return {
45
+ windowHours: hoursBack,
46
+ running: store.openRootSpans().map(liveSummary),
47
+ finished: rows.map((r) => ({
48
+ runId: r.runId,
49
+ origin: r.origin,
50
+ name: r.name,
51
+ jobName: r.jobName,
52
+ sessionId: r.sessionId,
53
+ startedAt: iso(r.startedAt),
54
+ outcome: r.outcome,
55
+ durationMs: r.durationMs,
56
+ costUsd: r.costUsd,
57
+ failureReason: r.failureReason,
58
+ })),
59
+ };
60
+ }
61
+
62
+ case "run": {
63
+ if (!query.runId) return { error: "scope 'run' needs runId" };
64
+ const snapshot = store.snapshotRun(query.runId);
65
+ if (snapshot) {
66
+ return {
67
+ runId: query.runId,
68
+ spans: snapshot.spans.map((s) => ({
69
+ spanId: s.spanId,
70
+ parent: s.parentSpanId,
71
+ name: s.name,
72
+ kind: s.kind,
73
+ startedAt: iso(s.startedAt),
74
+ endedAt: s.endedAt ? iso(s.endedAt) : null,
75
+ outcome: s.outcome,
76
+ reason: s.outcomeReason,
77
+ costUsd: s.usage.costUsd,
78
+ tokens:
79
+ s.usage.inputTokens !== undefined || s.usage.outputTokens !== undefined
80
+ ? { in: s.usage.inputTokens, out: s.usage.outputTokens }
81
+ : undefined,
82
+ })),
83
+ };
84
+ }
85
+ const row = db
86
+ .query("SELECT * FROM activity_run_rollups WHERE run_id = ?")
87
+ .get(query.runId) as any;
88
+ if (!row) return { error: `unknown run ${query.runId}` };
89
+ const rollup = rowToRunRollup(row);
90
+ return {
91
+ runId: query.runId,
92
+ detailPruned: true,
93
+ rollup: {
94
+ name: rollup.name,
95
+ jobName: rollup.jobName,
96
+ outcome: rollup.outcome,
97
+ startedAt: iso(rollup.startedAt),
98
+ durationMs: rollup.durationMs,
99
+ costUsd: rollup.costUsd,
100
+ failureReason: rollup.failureReason,
101
+ },
102
+ };
103
+ }
104
+
105
+ case "rollups": {
106
+ const rows = (
107
+ db
108
+ .query("SELECT * FROM activity_run_rollups WHERE started_at >= ?")
109
+ .all(since) as any[]
110
+ ).map(rowToRunRollup);
111
+ const digest = latestActivityDigest(db);
112
+ return {
113
+ windowHours: hoursBack,
114
+ runs: rows.length,
115
+ failures: rows.filter((r) => isFailureOutcome(r.outcome)).length,
116
+ costUsd: round(rows.reduce((a, r) => a + (r.costUsd ?? 0), 0)),
117
+ inputTokens: rows.reduce((a, r) => a + (r.inputTokens ?? 0), 0),
118
+ outputTokens: rows.reduce((a, r) => a + (r.outputTokens ?? 0), 0),
119
+ ...(digest ? { lastDigestAt: iso(digest.generatedAt) } : {}),
120
+ };
121
+ }
122
+
123
+ case "inbox": {
124
+ // The unacknowledged notification inbox — the same list the UI shows.
125
+ if (!notifier) return { error: "inbox unavailable" };
126
+ return {
127
+ intents: notifier.inbox(limit).map((i) => ({
128
+ kind: i.kind,
129
+ title: i.title,
130
+ status: i.status,
131
+ createdAt: iso(i.createdAt),
132
+ runId: i.runId,
133
+ })),
134
+ };
135
+ }
136
+
137
+ default:
138
+ return { error: `unknown scope` };
139
+ }
140
+ }
141
+
142
+ function liveSummary(span: SpanRow) {
143
+ return {
144
+ runId: span.runId,
145
+ origin: span.origin,
146
+ name: span.name,
147
+ jobName: span.jobName,
148
+ sessionId: span.sessionId,
149
+ startedAt: iso(span.startedAt),
150
+ elapsedMs: Date.now() - span.startedAt,
151
+ };
152
+ }
153
+
154
+ function iso(ms: number): string {
155
+ return new Date(ms).toISOString();
156
+ }
157
+
158
+ function round(n: number): number {
159
+ return Math.round(n * 10000) / 10000;
160
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Per-turn span derivation: the host-side half of activity recording.
3
+ *
4
+ * The host already sees everything a baseline trace needs — the frames it
5
+ * relays (tool starts/results, the terminal result), its own approval flow
6
+ * (wait time, denials), and the turn lifecycle it owns (timeout, cancel).
7
+ * A `TurnRecorder` turns that stream into spans, so EVERY backend gets a
8
+ * full activity tree with zero backend work; the bridge's activity side
9
+ * channel enriches with what only the backend sees (subagent lifecycle,
10
+ * usage, transcripts).
11
+ *
12
+ * Terminal-write precedence (the write-once race): enrichment arrives on the
13
+ * same ordered call path as frames, and the recorder buffers the result
14
+ * frame's outcome/usage rather than closing the root span on sight. The ONE
15
+ * terminal write for the root happens in `finish()` — after the backend's
16
+ * startTurn resolved, when everything that could refine the outcome has
17
+ * drained. Frame-derived outcome is the fallback, never a competing writer.
18
+ *
19
+ * Nothing here may fail the observed turn: every public method catches and
20
+ * drops its own errors.
21
+ */
22
+ import type {
23
+ BackendActivityEvent,
24
+ ServerMessage,
25
+ TurnUsage,
26
+ } from "@schlessera/brain-ui-sdk/server";
27
+ import type { Logger } from "@opentelemetry/api-logs";
28
+
29
+ import type { ActivityStore, SpanOutcome, SpanUsage } from "./store.js";
30
+
31
+ export interface TurnRecorderDeps {
32
+ store: ActivityStore;
33
+ /** Called after any committed write so the live stream can pump. */
34
+ onWrite?: () => void;
35
+ log?: Logger;
36
+ }
37
+
38
+ export interface TurnRecorder {
39
+ /** The run id (one run per turn). */
40
+ readonly runId: string;
41
+ observeFrame(msg: ServerMessage): void;
42
+ observeActivity(event: BackendActivityEvent): void;
43
+ /** The user's approval decision arrived for a gated tool call. */
44
+ onApprovalDecision(toolUseId: string, allowed: boolean): void;
45
+ /**
46
+ * Close the turn: merge the buffered result enrichment into the root's
47
+ * single terminal write, cascade-cancel anything left open, roll up.
48
+ */
49
+ finish(disposition: "success" | "error" | "cancelled" | "timeout"): void;
50
+ }
51
+
52
+ export function createTurnRecorder(
53
+ deps: TurnRecorderDeps,
54
+ turn: { turnId: string; sessionId: string | null }
55
+ ): TurnRecorder {
56
+ const { store, onWrite, log } = deps;
57
+ const runId = turn.turnId;
58
+ const rootSpanId = `${runId}:turn`;
59
+ let sessionId = turn.sessionId ?? undefined;
60
+ let rootStarted = false;
61
+ let finished = false;
62
+ /** Buffered terminal enrichment from the result frame. */
63
+ let resultOutcome: SpanOutcome | null = null;
64
+ let resultUsage: SpanUsage | undefined;
65
+ let resultAttrs: Record<string, unknown> | undefined;
66
+
67
+ const guard = (fn: () => void) => {
68
+ try {
69
+ fn();
70
+ } catch (err) {
71
+ log?.emit({
72
+ severityText: "WARN",
73
+ body: "activity recording failed; dropping",
74
+ attributes: { error: err instanceof Error ? err.message : String(err) },
75
+ });
76
+ }
77
+ };
78
+
79
+ function ensureRoot() {
80
+ if (rootStarted) return;
81
+ rootStarted = true;
82
+ store.startSpan({
83
+ spanId: rootSpanId,
84
+ runId,
85
+ name: "invoke_agent",
86
+ kind: "turn",
87
+ origin: "session",
88
+ sessionId,
89
+ attrs: { "gen_ai.operation.name": "invoke_agent" },
90
+ });
91
+ onWrite?.();
92
+ }
93
+
94
+ function usageFromTurnUsage(usage: TurnUsage): SpanUsage {
95
+ const models = usage.perModel ? Object.keys(usage.perModel) : [];
96
+ return {
97
+ inputTokens: usage.inputTokens,
98
+ outputTokens: usage.outputTokens,
99
+ cacheReadTokens: usage.cacheReadTokens,
100
+ cacheCreationTokens: usage.cacheCreationTokens,
101
+ model: models.length === 1 ? models[0] : undefined,
102
+ };
103
+ }
104
+
105
+ return {
106
+ runId,
107
+
108
+ observeFrame(msg) {
109
+ guard(() => {
110
+ if (finished) return;
111
+ switch (msg.type) {
112
+ case "session_info": {
113
+ sessionId = msg.sessionId;
114
+ ensureRoot();
115
+ // The root may have been opened before the session had a name.
116
+ store.patchSpan(rootSpanId, { attrs: { "session.id": msg.sessionId } });
117
+ onWrite?.();
118
+ break;
119
+ }
120
+ case "tool_use_start": {
121
+ ensureRoot();
122
+ const isSubagent = msg.toolName === "Agent";
123
+ store.startSpan({
124
+ spanId: msg.toolUseId,
125
+ runId,
126
+ parentSpanId: msg.parentToolUseId ?? rootSpanId,
127
+ name: `execute_tool ${msg.toolName}`,
128
+ kind: isSubagent ? "subagent" : "tool",
129
+ origin: "session",
130
+ sessionId,
131
+ attrs: {
132
+ "gen_ai.operation.name": isSubagent ? "invoke_agent" : "execute_tool",
133
+ "gen_ai.tool.name": msg.toolName,
134
+ },
135
+ });
136
+ onWrite?.();
137
+ break;
138
+ }
139
+ case "tool_approval_request": {
140
+ // The span exists (tool_use_start preceded it). Nothing to write:
141
+ // startedAt already marks the wait's beginning; the grant stamps
142
+ // the wait/execution boundary.
143
+ break;
144
+ }
145
+ case "tool_result": {
146
+ // endSpan is write-once: a span already closed (a denial landed
147
+ // the outcome first) rejects this as a no-op, and an unknown
148
+ // span id is equally a no-op — no bookkeeping set needed.
149
+ const outcome: SpanOutcome = msg.isError ? "error" : "success";
150
+ store.endSpan(msg.toolUseId, {
151
+ outcome,
152
+ reason: outcome === "error" ? clip(msg.output, 500) : undefined,
153
+ });
154
+ onWrite?.();
155
+ break;
156
+ }
157
+ case "result": {
158
+ // Buffered — the single terminal write happens in finish().
159
+ resultOutcome =
160
+ msg.outcome === "success"
161
+ ? "success"
162
+ : msg.outcome === "cancelled"
163
+ ? "cancelled"
164
+ : msg.outcomeDetail === "max_turns" || msg.outcomeDetail === "max_budget"
165
+ ? "timeout"
166
+ : "error";
167
+ if (msg.usage) resultUsage = usageFromTurnUsage(msg.usage);
168
+ if (typeof msg.costUsd === "number") {
169
+ resultUsage = { ...(resultUsage ?? {}), costUsd: msg.costUsd };
170
+ }
171
+ resultAttrs = {
172
+ ...(msg.outcomeDetail ? { "outcome.detail": msg.outcomeDetail } : {}),
173
+ ...(msg.usage?.perModel
174
+ ? { "gen_ai.usage.per_model": msg.usage.perModel }
175
+ : {}),
176
+ };
177
+ break;
178
+ }
179
+ default:
180
+ break;
181
+ }
182
+ });
183
+ },
184
+
185
+ observeActivity(event) {
186
+ guard(() => {
187
+ if (finished) return;
188
+ switch (event.kind) {
189
+ case "subagent_started": {
190
+ store.patchSpan(event.toolUseId, {
191
+ attrs: {
192
+ "subagent.type": event.subagentType,
193
+ "subagent.description": event.description,
194
+ },
195
+ });
196
+ onWrite?.();
197
+ break;
198
+ }
199
+ case "subagent_status": {
200
+ const attrs = {
201
+ ...(event.usage ? { "subagent.total_tokens": event.usage.totalTokens } : {}),
202
+ ...(event.summary ? { "subagent.summary": event.summary } : {}),
203
+ };
204
+ if (Object.keys(attrs).length > 0) {
205
+ store.patchSpan(event.toolUseId, { attrs });
206
+ onWrite?.();
207
+ }
208
+ break;
209
+ }
210
+ case "subagent_transcript": {
211
+ store.appendEvent(event.toolUseId, `transcript_${event.role}`, event.text);
212
+ onWrite?.();
213
+ break;
214
+ }
215
+ }
216
+ });
217
+ },
218
+
219
+ onApprovalDecision(toolUseId, allowed) {
220
+ guard(() => {
221
+ if (allowed) {
222
+ // Everything before this moment was approval wait, not execution.
223
+ store.patchSpan(toolUseId, { waitUntil: Date.now() });
224
+ } else {
225
+ // The denied outcome lands now — write-once makes the backend's
226
+ // later error tool_result a no-op on this span.
227
+ store.endSpan(toolUseId, { outcome: "denied", reason: "user declined" });
228
+ }
229
+ onWrite?.();
230
+ });
231
+ },
232
+
233
+ finish(disposition) {
234
+ guard(() => {
235
+ if (finished) return;
236
+ finished = true;
237
+ ensureRoot();
238
+ // Merged precedence: the buffered result enrichment refines the
239
+ // host's own disposition; the host wins only where the backend said
240
+ // nothing. Cancellation/timeout are host-owned facts and always win.
241
+ const outcome: SpanOutcome =
242
+ disposition === "cancelled" || disposition === "timeout"
243
+ ? disposition
244
+ : (resultOutcome ?? disposition);
245
+ store.endSpan(rootSpanId, {
246
+ outcome,
247
+ usage: resultUsage,
248
+ attrs: resultAttrs,
249
+ });
250
+ // Anything still open died with the turn.
251
+ store.cascadeClose(runId, "cancelled", `turn ${outcome}`);
252
+ store.rollupRun(runId);
253
+ onWrite?.();
254
+ });
255
+ },
256
+ };
257
+ }
258
+
259
+ function clip(text: string, max: number): string {
260
+ return text.length > max ? text.slice(0, max) : text;
261
+ }