@schlessera/brain-ui-server 0.18.0 → 0.20.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 (130) hide show
  1. package/README.md +5 -1
  2. package/data/model-prices.json +63 -0
  3. package/dist/activity/digest.d.ts +29 -0
  4. package/dist/activity/digest.d.ts.map +1 -0
  5. package/dist/activity/digest.js +89 -0
  6. package/dist/activity/digest.js.map +1 -0
  7. package/dist/activity/notify.d.ts +62 -0
  8. package/dist/activity/notify.d.ts.map +1 -0
  9. package/dist/activity/notify.js +193 -0
  10. package/dist/activity/notify.js.map +1 -0
  11. package/dist/activity/push-sender.d.ts +63 -0
  12. package/dist/activity/push-sender.d.ts.map +1 -0
  13. package/dist/activity/push-sender.js +131 -0
  14. package/dist/activity/push-sender.js.map +1 -0
  15. package/dist/activity/query.d.ts +16 -0
  16. package/dist/activity/query.d.ts.map +1 -0
  17. package/dist/activity/query.js +155 -0
  18. package/dist/activity/query.js.map +1 -0
  19. package/dist/activity/recorder.d.ts +53 -0
  20. package/dist/activity/recorder.d.ts.map +1 -0
  21. package/dist/activity/recorder.js +238 -0
  22. package/dist/activity/recorder.js.map +1 -0
  23. package/dist/activity/runtime.d.ts +37 -0
  24. package/dist/activity/runtime.d.ts.map +1 -0
  25. package/dist/activity/runtime.js +127 -0
  26. package/dist/activity/runtime.js.map +1 -0
  27. package/dist/activity/span-sink.d.ts +22 -0
  28. package/dist/activity/span-sink.d.ts.map +1 -0
  29. package/dist/activity/span-sink.js +138 -0
  30. package/dist/activity/span-sink.js.map +1 -0
  31. package/dist/activity/store.d.ts +256 -0
  32. package/dist/activity/store.d.ts.map +1 -0
  33. package/dist/activity/store.js +657 -0
  34. package/dist/activity/store.js.map +1 -0
  35. package/dist/activity/stream.d.ts +49 -0
  36. package/dist/activity/stream.d.ts.map +1 -0
  37. package/dist/activity/stream.js +353 -0
  38. package/dist/activity/stream.js.map +1 -0
  39. package/dist/agent/backend.d.ts +13 -4
  40. package/dist/agent/backend.d.ts.map +1 -1
  41. package/dist/agent/backend.js +68 -5
  42. package/dist/agent/backend.js.map +1 -1
  43. package/dist/app.d.ts.map +1 -1
  44. package/dist/app.js +33 -2
  45. package/dist/app.js.map +1 -1
  46. package/dist/config/env.d.ts +36 -0
  47. package/dist/config/env.d.ts.map +1 -1
  48. package/dist/config/env.js +66 -2
  49. package/dist/config/env.js.map +1 -1
  50. package/dist/cron/scheduler.d.ts.map +1 -1
  51. package/dist/cron/scheduler.js +20 -5
  52. package/dist/cron/scheduler.js.map +1 -1
  53. package/dist/db/client.d.ts.map +1 -1
  54. package/dist/db/client.js +32 -6
  55. package/dist/db/client.js.map +1 -1
  56. package/dist/db/settings.d.ts +15 -0
  57. package/dist/db/settings.d.ts.map +1 -1
  58. package/dist/db/settings.js +43 -0
  59. package/dist/db/settings.js.map +1 -1
  60. package/dist/index.d.ts +4 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +7 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/pricing/model-pricing.d.ts +61 -0
  65. package/dist/pricing/model-pricing.d.ts.map +1 -0
  66. package/dist/pricing/model-pricing.js +379 -0
  67. package/dist/pricing/model-pricing.js.map +1 -0
  68. package/dist/routes/activity.d.ts +20 -0
  69. package/dist/routes/activity.d.ts.map +1 -0
  70. package/dist/routes/activity.js +308 -0
  71. package/dist/routes/activity.js.map +1 -0
  72. package/dist/routes/models.d.ts +6 -0
  73. package/dist/routes/models.d.ts.map +1 -1
  74. package/dist/routes/models.js +38 -3
  75. package/dist/routes/models.js.map +1 -1
  76. package/dist/routes/push.d.ts +6 -0
  77. package/dist/routes/push.d.ts.map +1 -0
  78. package/dist/routes/push.js +73 -0
  79. package/dist/routes/push.js.map +1 -0
  80. package/dist/routes/sessions.d.ts.map +1 -1
  81. package/dist/routes/sessions.js +20 -4
  82. package/dist/routes/sessions.js.map +1 -1
  83. package/dist/ws/bridge.d.ts +2 -1
  84. package/dist/ws/bridge.d.ts.map +1 -1
  85. package/dist/ws/bridge.js +27 -2
  86. package/dist/ws/bridge.js.map +1 -1
  87. package/dist/ws/connection.d.ts.map +1 -1
  88. package/dist/ws/connection.js +9 -1
  89. package/dist/ws/connection.js.map +1 -1
  90. package/dist/ws/dispatch.d.ts.map +1 -1
  91. package/dist/ws/dispatch.js +11 -0
  92. package/dist/ws/dispatch.js.map +1 -1
  93. package/dist/ws/host.d.ts +16 -0
  94. package/dist/ws/host.d.ts.map +1 -1
  95. package/dist/ws/host.js +2 -0
  96. package/dist/ws/host.js.map +1 -1
  97. package/dist/ws/run-session.d.ts.map +1 -1
  98. package/dist/ws/run-session.js +55 -1
  99. package/dist/ws/run-session.js.map +1 -1
  100. package/migrations/007_activity.sql +114 -0
  101. package/migrations/008_push_subscriptions.sql +24 -0
  102. package/migrations/009_activity_followups.sql +22 -0
  103. package/migrations/010_effective_cost.sql +21 -0
  104. package/package.json +6 -3
  105. package/src/activity/digest.ts +120 -0
  106. package/src/activity/notify.ts +307 -0
  107. package/src/activity/push-sender.ts +215 -0
  108. package/src/activity/query.ts +187 -0
  109. package/src/activity/recorder.ts +313 -0
  110. package/src/activity/runtime.ts +169 -0
  111. package/src/activity/span-sink.ts +152 -0
  112. package/src/activity/store.ts +1069 -0
  113. package/src/activity/stream.ts +396 -0
  114. package/src/agent/backend.ts +91 -10
  115. package/src/app.ts +35 -2
  116. package/src/config/env.ts +90 -2
  117. package/src/cron/scheduler.ts +28 -8
  118. package/src/db/client.ts +31 -6
  119. package/src/db/settings.ts +56 -0
  120. package/src/index.ts +23 -0
  121. package/src/pricing/model-pricing.ts +497 -0
  122. package/src/routes/activity.ts +371 -0
  123. package/src/routes/models.ts +57 -6
  124. package/src/routes/push.ts +90 -0
  125. package/src/routes/sessions.ts +24 -4
  126. package/src/ws/bridge.ts +29 -2
  127. package/src/ws/connection.ts +9 -1
  128. package/src/ws/dispatch.ts +13 -0
  129. package/src/ws/host.ts +18 -0
  130. package/src/ws/run-session.ts +71 -2
@@ -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,187 @@
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, sumEffectiveCost, 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
+ // Explicit nulls, never omitted: the model must be able to tell
58
+ // "unknown" (null) from "genuinely free" ($0) — AE3.
59
+ effectiveCostUsd: r.effectiveCostUsd,
60
+ billingMode: r.billingMode,
61
+ pricingEstimate: r.pricingEstimate,
62
+ failureReason: r.failureReason,
63
+ })),
64
+ };
65
+ }
66
+
67
+ case "run": {
68
+ if (!query.runId) return { error: "scope 'run' needs runId" };
69
+ const snapshot = store.snapshotRun(query.runId);
70
+ if (snapshot) {
71
+ // The cost facts live on the rollup, not the spans — attach them here
72
+ // the same way the REST detail route does, so the agent sees the
73
+ // frozen triple for a finished run without waiting for detail
74
+ // pruning. Explicit nulls (AE3): a still-running run has no rollup
75
+ // yet, and unknown must never read as $0.
76
+ const rollupRow = db
77
+ .query("SELECT * FROM activity_run_rollups WHERE run_id = ?")
78
+ .get(query.runId) as any;
79
+ const liveRollup = rollupRow ? rowToRunRollup(rollupRow) : null;
80
+ return {
81
+ runId: query.runId,
82
+ costUsd: liveRollup?.costUsd ?? null,
83
+ effectiveCostUsd: liveRollup?.effectiveCostUsd ?? null,
84
+ billingMode: liveRollup?.billingMode ?? null,
85
+ pricingEstimate: liveRollup?.pricingEstimate ?? null,
86
+ failureReason: liveRollup?.failureReason ?? null,
87
+ spans: snapshot.spans.map((s) => ({
88
+ spanId: s.spanId,
89
+ parent: s.parentSpanId,
90
+ name: s.name,
91
+ kind: s.kind,
92
+ startedAt: iso(s.startedAt),
93
+ endedAt: s.endedAt ? iso(s.endedAt) : null,
94
+ outcome: s.outcome,
95
+ reason: s.outcomeReason,
96
+ costUsd: s.usage.costUsd,
97
+ tokens:
98
+ s.usage.inputTokens !== undefined || s.usage.outputTokens !== undefined
99
+ ? { in: s.usage.inputTokens, out: s.usage.outputTokens }
100
+ : undefined,
101
+ })),
102
+ };
103
+ }
104
+ const row = db
105
+ .query("SELECT * FROM activity_run_rollups WHERE run_id = ?")
106
+ .get(query.runId) as any;
107
+ if (!row) return { error: `unknown run ${query.runId}` };
108
+ const rollup = rowToRunRollup(row);
109
+ return {
110
+ runId: query.runId,
111
+ detailPruned: true,
112
+ rollup: {
113
+ name: rollup.name,
114
+ jobName: rollup.jobName,
115
+ outcome: rollup.outcome,
116
+ startedAt: iso(rollup.startedAt),
117
+ durationMs: rollup.durationMs,
118
+ costUsd: rollup.costUsd,
119
+ effectiveCostUsd: rollup.effectiveCostUsd,
120
+ billingMode: rollup.billingMode,
121
+ pricingEstimate: rollup.pricingEstimate,
122
+ failureReason: rollup.failureReason,
123
+ },
124
+ };
125
+ }
126
+
127
+ case "rollups": {
128
+ const rows = (
129
+ db
130
+ .query("SELECT * FROM activity_run_rollups WHERE started_at >= ?")
131
+ .all(since) as any[]
132
+ ).map(rowToRunRollup);
133
+ const digest = latestActivityDigest(db);
134
+ const effective = sumEffectiveCost(rows);
135
+ return {
136
+ windowHours: hoursBack,
137
+ runs: rows.length,
138
+ failures: rows.filter((r) => isFailureOutcome(r.outcome)).length,
139
+ // Both sums are sum-of-KNOWNS; the runs excluded from the effective
140
+ // sum ride along as unpricedRuns so unknown never reads as $0 (AE3).
141
+ costUsd: round(rows.reduce((a, r) => a + (r.costUsd ?? 0), 0)),
142
+ effectiveCostUsd: round(effective.effectiveCostUsd),
143
+ unpricedRuns: effective.unpricedRuns,
144
+ inputTokens: rows.reduce((a, r) => a + (r.inputTokens ?? 0), 0),
145
+ outputTokens: rows.reduce((a, r) => a + (r.outputTokens ?? 0), 0),
146
+ ...(digest ? { lastDigestAt: iso(digest.generatedAt) } : {}),
147
+ };
148
+ }
149
+
150
+ case "inbox": {
151
+ // The unacknowledged notification inbox — the same list the UI shows.
152
+ if (!notifier) return { error: "inbox unavailable" };
153
+ return {
154
+ intents: notifier.inbox(limit).map((i) => ({
155
+ kind: i.kind,
156
+ title: i.title,
157
+ status: i.status,
158
+ createdAt: iso(i.createdAt),
159
+ runId: i.runId,
160
+ })),
161
+ };
162
+ }
163
+
164
+ default:
165
+ return { error: `unknown scope` };
166
+ }
167
+ }
168
+
169
+ function liveSummary(span: SpanRow) {
170
+ return {
171
+ runId: span.runId,
172
+ origin: span.origin,
173
+ name: span.name,
174
+ jobName: span.jobName,
175
+ sessionId: span.sessionId,
176
+ startedAt: iso(span.startedAt),
177
+ elapsedMs: Date.now() - span.startedAt,
178
+ };
179
+ }
180
+
181
+ function iso(ms: number): string {
182
+ return new Date(ms).toISOString();
183
+ }
184
+
185
+ function round(n: number): number {
186
+ return Math.round(n * 10000) / 10000;
187
+ }