litepaseo 0.4.0 → 0.4.2

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/CHANGELOG.md +36 -0
  2. package/README.md +2 -1
  3. package/dist/server/cli.mjs +259 -3787
  4. package/dist/server/worker-BxtQnBVZ.mjs +3619 -0
  5. package/dist/web/assets/{CodeBlockNode-BOQ7WC72.js → CodeBlockNode-Dg9n5ezc.js} +1 -1
  6. package/dist/web/assets/CodeBlockNode-Dg9n5ezc.js.br +0 -0
  7. package/dist/web/assets/CodeBlockNode-Dg9n5ezc.js.gz +0 -0
  8. package/dist/web/assets/{FileViewer-16UXxzOe.js → FileViewer-BqAUo_AP.js} +1 -1
  9. package/dist/web/assets/FileViewer-BqAUo_AP.js.br +0 -0
  10. package/dist/web/assets/FileViewer-BqAUo_AP.js.gz +0 -0
  11. package/dist/web/assets/{FilesPanel-CdDybrQn.js → FilesPanel-Bl65Hz3k.js} +1 -1
  12. package/dist/web/assets/FilesPanel-Bl65Hz3k.js.br +0 -0
  13. package/dist/web/assets/FilesPanel-Bl65Hz3k.js.gz +0 -0
  14. package/dist/web/assets/{MarkdownMessage-Bm42-B56.js → MarkdownMessage-j-M1z3-u.js} +5 -5
  15. package/dist/web/assets/MarkdownMessage-j-M1z3-u.js.br +0 -0
  16. package/dist/web/assets/MarkdownMessage-j-M1z3-u.js.gz +0 -0
  17. package/dist/web/assets/{PreCodeBlock-BiQ6xAvM.js → PreCodeBlock-B8fBuBdP.js} +1 -1
  18. package/dist/web/assets/{PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js → PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js} +1 -1
  19. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js.br +0 -0
  20. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-Cj9vGyzE.js.gz +0 -0
  21. package/dist/web/assets/TerminalPanel-ZkVJFLM1.js +3 -0
  22. package/dist/web/assets/TerminalPanel-ZkVJFLM1.js.br +0 -0
  23. package/dist/web/assets/TerminalPanel-ZkVJFLM1.js.gz +0 -0
  24. package/dist/web/assets/{TerminalPanel-DvfBWyiQ.css → TerminalPanel-mJ-uVP4H.css} +1 -1
  25. package/dist/web/assets/TerminalPanel-mJ-uVP4H.css.br +0 -0
  26. package/dist/web/assets/TerminalPanel-mJ-uVP4H.css.gz +0 -0
  27. package/dist/web/assets/{Tooltip-ClqPy17d.js → Tooltip-Jdp8zjwT.js} +1 -1
  28. package/dist/web/assets/Tooltip-Jdp8zjwT.js.br +0 -0
  29. package/dist/web/assets/Tooltip-Jdp8zjwT.js.gz +0 -0
  30. package/dist/web/assets/addon-unicode11-C82cyeHQ.js +7 -0
  31. package/dist/web/assets/addon-unicode11-C82cyeHQ.js.br +0 -0
  32. package/dist/web/assets/addon-unicode11-C82cyeHQ.js.gz +0 -0
  33. package/dist/web/assets/addon-webgl-C3a5wC6k.js +64 -0
  34. package/dist/web/assets/addon-webgl-C3a5wC6k.js.br +0 -0
  35. package/dist/web/assets/addon-webgl-C3a5wC6k.js.gz +0 -0
  36. package/dist/web/assets/index-Cf1QB007.js +32 -0
  37. package/dist/web/assets/index-Cf1QB007.js.br +0 -0
  38. package/dist/web/assets/index-Cf1QB007.js.gz +0 -0
  39. package/dist/web/assets/{index-CITaZKmy.css → index-Dzid_5f9.css} +1 -1
  40. package/dist/web/assets/index-Dzid_5f9.css.br +0 -0
  41. package/dist/web/assets/index-Dzid_5f9.css.gz +0 -0
  42. package/dist/web/assets/{index10-BG65E54y.js → index10-EuskhiaE.js} +1 -1
  43. package/dist/web/assets/index10-EuskhiaE.js.br +0 -0
  44. package/dist/web/assets/index10-EuskhiaE.js.gz +0 -0
  45. package/dist/web/assets/index3-bqHD_tAN.js +1 -0
  46. package/dist/web/assets/index4-CnpLIN0Y.js +1 -0
  47. package/dist/web/assets/{index5-CzcXp9wR.js → index5-CIMd5e5U.js} +1 -1
  48. package/dist/web/assets/index5-CIMd5e5U.js.br +0 -0
  49. package/dist/web/assets/index5-CIMd5e5U.js.gz +0 -0
  50. package/dist/web/assets/{index6-DPLyU-vO.js → index6-DrnWk0rr.js} +1 -1
  51. package/dist/web/assets/index6-DrnWk0rr.js.br +0 -0
  52. package/dist/web/assets/index6-DrnWk0rr.js.gz +0 -0
  53. package/dist/web/assets/{index7-6uQOIsxo.js → index7-BCl4u4Ci.js} +1 -1
  54. package/dist/web/assets/index7-BCl4u4Ci.js.br +0 -0
  55. package/dist/web/assets/index7-BCl4u4Ci.js.gz +0 -0
  56. package/dist/web/assets/{index8-DUBqmq2E.js → index8-tfhmdpKZ.js} +1 -1
  57. package/dist/web/assets/index8-tfhmdpKZ.js.br +0 -0
  58. package/dist/web/assets/index8-tfhmdpKZ.js.gz +0 -0
  59. package/dist/web/assets/{index9-Czv_zULn.js → index9-Co0BXJFT.js} +1 -1
  60. package/dist/web/assets/index9-Co0BXJFT.js.br +0 -0
  61. package/dist/web/assets/index9-Co0BXJFT.js.gz +0 -0
  62. package/dist/web/index.html +2 -2
  63. package/dist/web/index.html.br +0 -0
  64. package/dist/web/index.html.gz +0 -0
  65. package/package.json +5 -3
  66. package/dist/web/assets/CodeBlockNode-BOQ7WC72.js.br +0 -0
  67. package/dist/web/assets/CodeBlockNode-BOQ7WC72.js.gz +0 -0
  68. package/dist/web/assets/FileViewer-16UXxzOe.js.br +0 -0
  69. package/dist/web/assets/FileViewer-16UXxzOe.js.gz +0 -0
  70. package/dist/web/assets/FilesPanel-CdDybrQn.js.br +0 -0
  71. package/dist/web/assets/FilesPanel-CdDybrQn.js.gz +0 -0
  72. package/dist/web/assets/MarkdownMessage-Bm42-B56.js.br +0 -0
  73. package/dist/web/assets/MarkdownMessage-Bm42-B56.js.gz +0 -0
  74. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js.br +0 -0
  75. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DUZXIc-h.js.gz +0 -0
  76. package/dist/web/assets/TerminalPanel-B5K5NCf0.js +0 -3
  77. package/dist/web/assets/TerminalPanel-B5K5NCf0.js.br +0 -0
  78. package/dist/web/assets/TerminalPanel-B5K5NCf0.js.gz +0 -0
  79. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.br +0 -0
  80. package/dist/web/assets/TerminalPanel-DvfBWyiQ.css.gz +0 -0
  81. package/dist/web/assets/Tooltip-ClqPy17d.js.br +0 -0
  82. package/dist/web/assets/Tooltip-ClqPy17d.js.gz +0 -0
  83. package/dist/web/assets/index-By8I8BM7.js +0 -32
  84. package/dist/web/assets/index-By8I8BM7.js.br +0 -0
  85. package/dist/web/assets/index-By8I8BM7.js.gz +0 -0
  86. package/dist/web/assets/index-CITaZKmy.css.br +0 -0
  87. package/dist/web/assets/index-CITaZKmy.css.gz +0 -0
  88. package/dist/web/assets/index10-BG65E54y.js.br +0 -0
  89. package/dist/web/assets/index10-BG65E54y.js.gz +0 -0
  90. package/dist/web/assets/index3-6tLrzhUa.js +0 -1
  91. package/dist/web/assets/index4-CZn-viSK.js +0 -1
  92. package/dist/web/assets/index5-CzcXp9wR.js.br +0 -0
  93. package/dist/web/assets/index5-CzcXp9wR.js.gz +0 -0
  94. package/dist/web/assets/index6-DPLyU-vO.js.br +0 -0
  95. package/dist/web/assets/index6-DPLyU-vO.js.gz +0 -0
  96. package/dist/web/assets/index7-6uQOIsxo.js.br +0 -0
  97. package/dist/web/assets/index7-6uQOIsxo.js.gz +0 -0
  98. package/dist/web/assets/index8-DUBqmq2E.js.br +0 -0
  99. package/dist/web/assets/index8-DUBqmq2E.js.gz +0 -0
  100. package/dist/web/assets/index9-Czv_zULn.js.br +0 -0
  101. package/dist/web/assets/index9-Czv_zULn.js.gz +0 -0
@@ -0,0 +1,3619 @@
1
+ import { a as tokenFile, i as generateToken, n as Auth, o as Store, r as SESSION_TTL_MS, s as VERSION, t as effectiveConfig } from "./cli.mjs";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { randomUUID } from "node:crypto";
4
+ import { basename, dirname, isAbsolute, join, normalize } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { serve } from "@hono/node-server";
7
+ import { createHostClient, parseHostTarget } from "@getpaseo/client/node";
8
+ import { createPaseoApi } from "@getpaseo/client";
9
+ import { deriveAgentStateBucket } from "@getpaseo/protocol/agent-state-bucket";
10
+ import { timelineItemIdentity } from "@getpaseo/protocol/timeline-identity";
11
+ import { z } from "zod";
12
+ import { lstat, readFile, realpath } from "node:fs/promises";
13
+ import { Hono } from "hono";
14
+ import { bodyLimit } from "hono/body-limit";
15
+ import { serveStatic } from "@hono/node-server/serve-static";
16
+ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
17
+ import QRCode from "qrcode";
18
+ import { AgentPermissionResponseSchema } from "@getpaseo/protocol/messages";
19
+ import webpush from "web-push";
20
+ import WebSocket, { WebSocketServer } from "ws";
21
+ // src/server/diagnostics.ts
22
+ /** Classify untrusted SDK failures without copying URLs, credentials or remote text into logs/UI. */
23
+ function connectionProblem(value) {
24
+ const e = value;
25
+ const text = [
26
+ e?.reason,
27
+ e?.failureCode,
28
+ e?.message,
29
+ e?.code
30
+ ].filter((v) => typeof v === "string").join(" ").toLowerCase();
31
+ if (/password.required|password required/.test(text)) return {
32
+ code: "password_required",
33
+ message: "Authentication required. Add this host using a password-bearing connection URL or a pairing offer."
34
+ };
35
+ if (/incorrect.password|unauthorized|authentication|auth.failed|forbidden/.test(text)) return {
36
+ code: "authentication_failed",
37
+ message: "Authentication failed. Check the host credentials or create a new pairing offer."
38
+ };
39
+ if (/version|protocol|incompatible/.test(text)) return {
40
+ code: "incompatible",
41
+ message: "Protocol negotiation failed. Check the daemon and client versions."
42
+ };
43
+ if (/enotfound|eai_again|dns/.test(text)) return {
44
+ code: "dns",
45
+ message: "Host name could not be resolved. Check the address and DNS."
46
+ };
47
+ if (/econnrefused|connection refused/.test(text)) return {
48
+ code: "refused",
49
+ message: "Connection refused. Check that the daemon is running and the port is reachable."
50
+ };
51
+ if (/timed?.?out|timeout/.test(text)) return {
52
+ code: "timeout",
53
+ message: "Connection timed out. Check the network, tunnel and firewall."
54
+ };
55
+ if (/cert|tls|ssl/.test(text)) return {
56
+ code: "tls",
57
+ message: "Secure connection failed. Check the server certificate and TLS configuration."
58
+ };
59
+ return {
60
+ code: "disconnected",
61
+ message: "Connection lost. Check the daemon, network and connection settings."
62
+ };
63
+ }
64
+ // src/server/versioned-collection.ts
65
+ /**
66
+ * Keyed values ordered by their last change. Every write moves the entry to the tail, so
67
+ * `changesSince(seq)` walks back only over entries changed after `seq`: O(changes), never
68
+ * O(collection). Deletions stay as tombstones until the bounded tombstone budget evicts them;
69
+ * readers older than the evicted horizon (`floor`) must take a snapshot instead.
70
+ */
71
+ var VersionedCollection = class {
72
+ generation = randomUUID();
73
+ nodes = /* @__PURE__ */ new Map();
74
+ head = null;
75
+ tail = null;
76
+ current = 0;
77
+ floor = 0;
78
+ live = 0;
79
+ tombstones = [];
80
+ tombstoneHead = 0;
81
+ maxTombstones;
82
+ constructor(maxTombstones = 4096) {
83
+ this.maxTombstones = maxTombstones;
84
+ }
85
+ get seq() {
86
+ return this.current;
87
+ }
88
+ get size() {
89
+ return this.live;
90
+ }
91
+ get(key) {
92
+ const node = this.nodes.get(key);
93
+ return node && node.value !== null ? node.value : void 0;
94
+ }
95
+ set(key, value) {
96
+ let node = this.nodes.get(key);
97
+ if (node) {
98
+ if (node.value === null) this.live++;
99
+ this.unlink(node);
100
+ } else {
101
+ node = {
102
+ key,
103
+ value,
104
+ seq: 0,
105
+ prev: null,
106
+ next: null
107
+ };
108
+ this.nodes.set(key, node);
109
+ this.live++;
110
+ }
111
+ node.value = value;
112
+ node.seq = ++this.current;
113
+ this.append(node);
114
+ }
115
+ delete(key) {
116
+ const node = this.nodes.get(key);
117
+ if (!node || node.value === null) return false;
118
+ this.live--;
119
+ node.value = null;
120
+ node.seq = ++this.current;
121
+ this.unlink(node);
122
+ this.append(node);
123
+ this.tombstones.push({
124
+ node,
125
+ seq: node.seq
126
+ });
127
+ this.evictTombstones();
128
+ return true;
129
+ }
130
+ /** Latest value of each entry changed after `after`, oldest first; null when a snapshot is required. */
131
+ changesSince(after) {
132
+ if (after < this.floor || after > this.current) return null;
133
+ const out = [];
134
+ for (let node = this.tail; node && node.seq > after; node = node.prev) out.push({
135
+ key: node.key,
136
+ value: node.value
137
+ });
138
+ return out.reverse();
139
+ }
140
+ /** Full contents. O(n); only for first loads and readers past the tombstone horizon. */
141
+ snapshot() {
142
+ const out = [];
143
+ for (let node = this.head; node; node = node.next) if (node.value !== null) out.push(node.value);
144
+ return out;
145
+ }
146
+ evictTombstones() {
147
+ while (this.tombstones.length - this.tombstoneHead > this.maxTombstones) {
148
+ const { node, seq } = this.tombstones[this.tombstoneHead++];
149
+ if (node.value !== null || node.seq !== seq || this.nodes.get(node.key) !== node) continue;
150
+ this.unlink(node);
151
+ this.nodes.delete(node.key);
152
+ this.floor = Math.max(this.floor, seq);
153
+ }
154
+ if (this.tombstoneHead > 1024 && this.tombstoneHead * 2 > this.tombstones.length) {
155
+ this.tombstones = this.tombstones.slice(this.tombstoneHead);
156
+ this.tombstoneHead = 0;
157
+ }
158
+ }
159
+ unlink(node) {
160
+ if (node.prev) node.prev.next = node.next;
161
+ else this.head = node.next;
162
+ if (node.next) node.next.prev = node.prev;
163
+ else this.tail = node.prev;
164
+ node.prev = node.next = null;
165
+ }
166
+ append(node) {
167
+ node.prev = this.tail;
168
+ node.next = null;
169
+ if (this.tail) this.tail.next = node;
170
+ else this.head = node;
171
+ this.tail = node;
172
+ }
173
+ };
174
+ // src/server/host-directory.ts
175
+ const PAGE = 200;
176
+ const RETRY_MS$1 = 2e3;
177
+ const basename$1 = (path) => path.replace(/\/+$/, "").split("/").pop() || path;
178
+ const time = (value) => value ? Date.parse(value) || 0 : 0;
179
+ /**
180
+ * Mirrors one daemon directory into a shared collection. After the first snapshot it consumes
181
+ * only update deltas; reconnects resume from the daemon's directory-sync cursor, so
182
+ * steady-state cost is proportional to changes. Summaries that did not change are dropped.
183
+ */
184
+ var HostMirror = class {
185
+ cursor;
186
+ members = /* @__PURE__ */ new Map();
187
+ subscription = null;
188
+ token = 0;
189
+ stopStatus = null;
190
+ retry;
191
+ /** Items touched by live updates while a paged (non-sync) snapshot is being read. */
192
+ liveTouched = null;
193
+ adapter;
194
+ hostId;
195
+ driver;
196
+ collection;
197
+ changed;
198
+ transition;
199
+ constructor(adapter, hostId, driver, collection, changed, transition = () => {}) {
200
+ this.adapter = adapter;
201
+ this.hostId = hostId;
202
+ this.driver = driver;
203
+ this.collection = collection;
204
+ this.changed = changed;
205
+ this.transition = transition;
206
+ }
207
+ /** What the adapter retained for a member, from the latest update; O(1). */
208
+ retained(id) {
209
+ return this.members.get(id)?.retained;
210
+ }
211
+ start() {
212
+ this.stopStatus = this.driver.subscribeConnectionStatus((state) => this.onStatus(state.status));
213
+ this.onStatus(this.driver.getConnectionState().status);
214
+ }
215
+ dispose() {
216
+ const released = this.close();
217
+ this.stopStatus?.();
218
+ for (const [id, member] of this.members) {
219
+ this.collection.delete(this.key(id));
220
+ this.transition(member.summary, null);
221
+ }
222
+ if (this.members.size) this.changed();
223
+ this.members.clear();
224
+ return released;
225
+ }
226
+ key(id) {
227
+ return `${this.hostId}:${id}`;
228
+ }
229
+ onStatus(status) {
230
+ if (status === "connected") {
231
+ if (!this.subscription) this.open();
232
+ } else this.close();
233
+ }
234
+ open() {
235
+ clearTimeout(this.retry);
236
+ const token = ++this.token;
237
+ const sync = this.driver.getLastServerInfoMessage()?.features?.directorySync === true;
238
+ const { base } = this.adapter;
239
+ const subscription = this.adapter.observe(this.driver, sync ? {
240
+ ...base,
241
+ sync: this.cursor ?? {}
242
+ } : {
243
+ ...base,
244
+ page: { limit: PAGE }
245
+ });
246
+ this.subscription = subscription;
247
+ subscription.subscribe({
248
+ snapshot: (payload) => {
249
+ if (token === this.token) this.onSnapshot(payload, token, sync).catch(() => this.fail(token));
250
+ },
251
+ update: (message) => {
252
+ if (token === this.token && message.type === this.adapter.updateType) this.onUpdate(this.adapter.update(message.payload));
253
+ },
254
+ error: () => this.fail(token)
255
+ });
256
+ }
257
+ close() {
258
+ this.token++;
259
+ clearTimeout(this.retry);
260
+ this.liveTouched = null;
261
+ const subscription = this.subscription;
262
+ this.subscription = null;
263
+ return subscription?.release().catch(() => {}) ?? Promise.resolve();
264
+ }
265
+ fail(token) {
266
+ if (token !== this.token) return;
267
+ this.close();
268
+ this.cursor = void 0;
269
+ this.retry = setTimeout(() => {
270
+ if (!this.subscription && this.driver.getConnectionState().status === "connected") this.open();
271
+ }, RETRY_MS$1);
272
+ this.retry.unref?.();
273
+ }
274
+ async onSnapshot(payload, token, sync) {
275
+ if (payload.sync?.mode === "changes") {
276
+ if (this.cursor?.generation !== payload.sync.generation) {
277
+ this.cursor = void 0;
278
+ this.close();
279
+ this.open();
280
+ return;
281
+ }
282
+ for (const e of payload.entries) {
283
+ const { raw, seq, extra } = this.adapter.entry(e);
284
+ this.upsert(raw, seq, false, extra);
285
+ }
286
+ for (const removal of payload.sync.removals) this.remove(removal.id, removal.seq);
287
+ this.cursor = {
288
+ generation: payload.sync.generation,
289
+ afterSeq: payload.sync.headSeq
290
+ };
291
+ return;
292
+ }
293
+ let entries = payload.entries;
294
+ if (!sync && payload.pageInfo.hasMore) {
295
+ this.liveTouched = /* @__PURE__ */ new Set();
296
+ entries = [...entries];
297
+ let next = payload.pageInfo.nextCursor;
298
+ while (next) {
299
+ const page = await this.adapter.fetch(this.driver, {
300
+ ...this.adapter.base,
301
+ page: {
302
+ limit: PAGE,
303
+ cursor: next
304
+ }
305
+ });
306
+ if (token !== this.token) return;
307
+ entries.push(...page.entries);
308
+ next = page.pageInfo.hasMore ? page.pageInfo.nextCursor : null;
309
+ }
310
+ }
311
+ const seen = /* @__PURE__ */ new Set();
312
+ for (const e of entries) {
313
+ const { raw, seq, extra } = this.adapter.entry(e);
314
+ seen.add(this.adapter.id(raw));
315
+ this.upsert(raw, sync ? seq : void 0, sync, extra);
316
+ }
317
+ for (const id of [...this.members.keys()]) if (!seen.has(id) && !this.liveTouched?.has(id)) this.remove(id);
318
+ this.liveTouched = null;
319
+ this.cursor = payload.sync ? {
320
+ generation: payload.sync.generation,
321
+ afterSeq: payload.sync.headSeq
322
+ } : void 0;
323
+ }
324
+ onUpdate(update) {
325
+ if (update.generation && this.cursor && update.generation !== this.cursor.generation) {
326
+ this.cursor = void 0;
327
+ this.close();
328
+ this.open();
329
+ return;
330
+ }
331
+ const id = update.kind === "upsert" ? this.adapter.id(update.raw) : update.id;
332
+ this.liveTouched?.add(id);
333
+ if (update.kind === "upsert") this.upsert(update.raw, update.seq, false, update.extra);
334
+ else this.remove(update.id, update.seq);
335
+ if (update.seq !== void 0 && this.cursor) this.cursor.afterSeq = Math.max(this.cursor.afterSeq, update.seq);
336
+ }
337
+ upsert(raw, version, force = false, extra) {
338
+ const id = this.adapter.id(raw);
339
+ if (this.adapter.excluded(raw)) return this.remove(id, version, force);
340
+ const member = this.members.get(id);
341
+ if (!force && member?.version !== void 0 && version !== void 0 && version < member.version) return;
342
+ const kept = extra === void 0 ? member?.extra : extra;
343
+ const { summary, memo } = this.adapter.summarize(this.hostId, raw, kept, member?.memo);
344
+ const fingerprint = JSON.stringify(summary);
345
+ const next = {
346
+ fingerprint,
347
+ version,
348
+ extra: kept,
349
+ memo,
350
+ summary,
351
+ retained: this.adapter.retain?.(raw)
352
+ };
353
+ this.members.set(id, next);
354
+ if (member?.fingerprint === fingerprint) {
355
+ next.summary = member.summary;
356
+ return;
357
+ }
358
+ this.collection.set(summary.key, summary);
359
+ this.changed();
360
+ this.transition(member?.summary ?? null, summary);
361
+ }
362
+ remove(id, version, force = false) {
363
+ const member = this.members.get(id);
364
+ if (!member) return;
365
+ if (!force && member.version !== void 0 && version !== void 0 && version < member.version) return;
366
+ this.members.delete(id);
367
+ this.collection.delete(this.key(id));
368
+ this.changed();
369
+ this.transition(member.summary, null);
370
+ }
371
+ };
372
+ const isRunning = (agent) => agent.status === "running" || !!agent.activeTurn;
373
+ /**
374
+ * When the session was last *used*: the moment its most recent turn ended. It holds still while
375
+ * a turn runs and ignores idle metadata changes, so the sidebar does not reshuffle mid-turn.
376
+ * The daemon has no turn-end timestamp, so it is derived from observed transitions:
377
+ * - first sight, idle: the last change (normally the turn end);
378
+ * - first sight, running: the turn start, else the last user message;
379
+ * - running → idle: the change time at that moment;
380
+ * - idle, but a new user message appeared (a turn we missed while disconnected): the change time.
381
+ */
382
+ function deriveActivity(current, previous) {
383
+ const memo = (activityAt) => ({
384
+ activityAt,
385
+ running: current.running,
386
+ lastUserMessageAt: current.lastUserMessageAt
387
+ });
388
+ if (!previous) return memo(current.running ? current.startedAt || current.lastUserMessageAt || current.changedAt : current.changedAt);
389
+ if (current.running) return memo(previous.activityAt);
390
+ if (previous.running || current.lastUserMessageAt > previous.lastUserMessageAt) return memo(Math.max(current.changedAt, previous.activityAt));
391
+ return memo(previous.activityAt);
392
+ }
393
+ function summarize(hostId, agent, project, activity = time(agent.updatedAt)) {
394
+ const permissions = agent.pendingPermissions ?? [];
395
+ const bucket = deriveAgentStateBucket({
396
+ status: agent.status,
397
+ pendingPermissionCount: permissions.length,
398
+ requiresAttention: agent.requiresAttention,
399
+ attentionReason: agent.attentionReason
400
+ });
401
+ const state = agent.status === "initializing" && bucket === "done" ? "running" : bucket === "attention" ? "unread" : bucket;
402
+ const turnActive = isRunning(agent) || agent.status === "initializing";
403
+ return {
404
+ key: `${hostId}:${agent.id}`,
405
+ hostId,
406
+ id: agent.id,
407
+ workspaceId: agent.workspaceId ?? null,
408
+ title: agent.title ?? null,
409
+ status: agent.status,
410
+ turnActive,
411
+ provider: agent.provider,
412
+ cwd: agent.cwd,
413
+ project: project?.projectName || basename$1(agent.cwd) || "Other",
414
+ projectKey: project?.projectKey ?? null,
415
+ activityAt: activity,
416
+ turnStartedAt: turnActive ? time(agent.activeTurn?.startedAt) || time(agent.lastUserMessageAt) || null : null,
417
+ attention: state === "needs_input",
418
+ state,
419
+ unread: agent.requiresAttention === true && state !== "needs_input",
420
+ lastError: agent.lastError ? agent.lastError.slice(0, 300) : null,
421
+ pendingPermissions: permissions,
422
+ model: agent.model ?? agent.runtimeInfo?.model ?? null,
423
+ thinking: agent.effectiveThinkingOptionId ?? agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
424
+ modeId: agent.currentModeId ?? null,
425
+ contextUsed: agent.lastUsage?.contextWindowUsedTokens ?? null,
426
+ contextMax: agent.lastUsage?.contextWindowMaxTokens ?? null,
427
+ rewind: rewindModes(agent.capabilities)
428
+ };
429
+ }
430
+ /** The rewind modes a provider supports, in Paseo's menu order. */
431
+ function rewindModes(capabilities) {
432
+ const c = capabilities ?? {};
433
+ const modes = [];
434
+ if (c.supportsRewindConversation === true) modes.push("conversation");
435
+ if (c.supportsRewindFiles === true) modes.push("files");
436
+ if (c.supportsRewindBoth === true) modes.push("both");
437
+ return modes;
438
+ }
439
+ const agentAdapter = {
440
+ updateType: "agent_update",
441
+ base: { scope: "active" },
442
+ observe: (driver, options) => driver.observeAgents(options),
443
+ fetch: (driver, options) => driver.fetchAgents(options),
444
+ entry: (e) => {
445
+ const entry = e;
446
+ return {
447
+ raw: entry.agent,
448
+ seq: entry.syncSeq,
449
+ extra: entry.project
450
+ };
451
+ },
452
+ update: (p) => {
453
+ const u = p;
454
+ return u.kind === "upsert" ? {
455
+ kind: "upsert",
456
+ raw: u.agent,
457
+ extra: u.project,
458
+ generation: u.generation,
459
+ seq: u.seq
460
+ } : {
461
+ kind: "remove",
462
+ id: u.agentId,
463
+ generation: u.generation,
464
+ seq: u.seq
465
+ };
466
+ },
467
+ id: (agent) => agent.id,
468
+ excluded: (agent) => !!agent.archivedAt || !!agent.internal,
469
+ summarize: (hostId, agent, project, previous) => {
470
+ const memo = deriveActivity({
471
+ running: isRunning(agent),
472
+ changedAt: time(agent.updatedAt),
473
+ startedAt: time(agent.activeTurn?.startedAt),
474
+ lastUserMessageAt: time(agent.lastUserMessageAt)
475
+ }, previous);
476
+ return {
477
+ summary: summarize(hostId, agent, project, memo.activityAt),
478
+ memo
479
+ };
480
+ },
481
+ retain: (agent) => ({
482
+ provider: agent.provider,
483
+ capabilities: agent.capabilities,
484
+ availableModes: agent.availableModes ?? [],
485
+ features: agent.features ?? []
486
+ })
487
+ };
488
+ /** One daemon's active agents. */
489
+ var HostDirectory = class extends HostMirror {
490
+ constructor(hostId, driver, collection, changed, transition) {
491
+ super(agentAdapter, hostId, driver, collection, changed, transition);
492
+ }
493
+ /** Provider and capabilities from the live directory; undefined if the agent is not listed. */
494
+ facts(agentId) {
495
+ return this.retained(agentId);
496
+ }
497
+ };
498
+ /**
499
+ * A workspace (a "thread" in Paseo's sidebar). Its state is the daemon's own aggregate over the
500
+ * workspace's agents; recency follows the same turn-end rule as agents.
501
+ */
502
+ function summarizeWorkspace(hostId, ws, activity) {
503
+ const state = ws.status === "attention" ? "unread" : ws.status;
504
+ return {
505
+ key: `${hostId}:${ws.id}`,
506
+ hostId,
507
+ id: ws.id,
508
+ name: ws.name,
509
+ title: ws.title ?? null,
510
+ project: ws.project?.projectName || ws.projectDisplayName || basename$1(ws.projectRootPath) || "Other",
511
+ projectKey: ws.project?.projectKey ?? ws.projectId,
512
+ rootPath: ws.projectRootPath,
513
+ directory: ws.workspaceDirectory ?? ws.projectRootPath,
514
+ kind: ws.workspaceKind,
515
+ branch: ws.gitRuntime?.currentBranch ?? null,
516
+ pinnedAt: time(ws.pinnedAt),
517
+ activityAt: activity,
518
+ state,
519
+ attention: state === "needs_input",
520
+ unread: state === "unread" || state === "failed"
521
+ };
522
+ }
523
+ const workspaceAdapter = {
524
+ updateType: "workspace_update",
525
+ base: {},
526
+ observe: (driver, options) => {
527
+ if (!driver.observeWorkspaces) throw new Error("Workspaces unsupported");
528
+ return driver.observeWorkspaces(options);
529
+ },
530
+ fetch: (driver, options) => {
531
+ if (!driver.fetchWorkspaces) throw new Error("Workspaces unsupported");
532
+ return driver.fetchWorkspaces(options);
533
+ },
534
+ entry: (e) => {
535
+ const ws = e;
536
+ return {
537
+ raw: ws,
538
+ seq: ws.syncSeq
539
+ };
540
+ },
541
+ update: (p) => {
542
+ const u = p;
543
+ return u.kind === "upsert" ? {
544
+ kind: "upsert",
545
+ raw: u.workspace,
546
+ generation: u.generation,
547
+ seq: u.seq
548
+ } : {
549
+ kind: "remove",
550
+ id: u.id,
551
+ generation: u.generation,
552
+ seq: u.seq
553
+ };
554
+ },
555
+ id: (ws) => ws.id,
556
+ excluded: (ws) => !!ws.archivingAt || !!ws.internal || !!ws.background,
557
+ summarize: (hostId, ws, _extra, previous) => {
558
+ const memo = deriveActivity({
559
+ running: ws.status === "running",
560
+ changedAt: time(ws.statusEnteredAt) || time(ws.activityAt),
561
+ startedAt: ws.status === "running" ? time(ws.statusEnteredAt) : 0,
562
+ lastUserMessageAt: time(ws.lastUserMessageAt)
563
+ }, previous);
564
+ const activity = previous || ws.status === "running" ? memo.activityAt : time(ws.activityAt) || memo.activityAt || time(ws.createdAt);
565
+ return {
566
+ summary: summarizeWorkspace(hostId, ws, activity),
567
+ memo: {
568
+ ...memo,
569
+ activityAt: activity
570
+ }
571
+ };
572
+ }
573
+ };
574
+ /** One daemon's workspaces (Paseo's threads). */
575
+ var HostWorkspaces = class extends HostMirror {
576
+ constructor(hostId, driver, collection, changed) {
577
+ super(workspaceAdapter, hostId, driver, collection, changed);
578
+ }
579
+ };
580
+ // src/server/timeline-view.ts
581
+ const TAIL_LIMIT = 60;
582
+ const CATCH_UP_PAGE = 200;
583
+ /** Rows kept per view; older rows are dropped and stay reachable through history pages. */
584
+ const MAX_ROWS = 600;
585
+ const KEEP_ROWS = 500;
586
+ /** Rows sent to a client that (re)joins; older ones load on demand. */
587
+ const RESET_ROWS = 200;
588
+ const MAX_BUFFER = 5e3;
589
+ const FLUSH_MS = 500;
590
+ const RETRY_MS = 2e3;
591
+ /** Same fold the daemon's TimelineProjection applies when a tool call reports again. */
592
+ function mergeToolCallItems(existing, incoming) {
593
+ const a = existing.detail, b = incoming.detail;
594
+ const detail = a?.type === "unknown" && b?.type !== "unknown" ? b : b?.type === "unknown" && a?.type !== "unknown" ? a : b;
595
+ const metadata = existing.metadata || incoming.metadata ? {
596
+ ...existing.metadata,
597
+ ...incoming.metadata
598
+ } : void 0;
599
+ const merged = {
600
+ ...existing,
601
+ ...incoming,
602
+ detail,
603
+ metadata
604
+ };
605
+ if (incoming.status === "failed") merged.error = incoming.error;
606
+ else if (incoming.status === "completed" || incoming.status === "canceled") merged.error = null;
607
+ else if (incoming.error !== void 0) merged.error = incoming.error;
608
+ return merged;
609
+ }
610
+ function textMergeable(previous, entry) {
611
+ const a = previous.item, b = entry.item;
612
+ if (a.type !== b.type || previous.seqEnd + 1 !== entry.seqStart || previous.turnId !== entry.turnId) return false;
613
+ if (a.type === "reasoning") return true;
614
+ return a.type === "assistant_message" && (b.messageId === void 0 || a.messageId === b.messageId);
615
+ }
616
+ /**
617
+ * Live projection of one agent's timeline, shared by every browser viewing it. Daemon stream
618
+ * events are folded with the daemon's own projection rules, so each event costs O(1) work and
619
+ * reaches browsers as a small upsert/append op. Gaps, unknown identities and reconnects fall
620
+ * back to an incremental `after` fetch, which returns only rows touched since the cursor.
621
+ */
622
+ var TimelineView = class {
623
+ rows = [];
624
+ bySeqStart = /* @__PURE__ */ new Map();
625
+ identities = /* @__PURE__ */ new Map();
626
+ epoch = "";
627
+ lastSeq = -1;
628
+ hasOlder = false;
629
+ startCursor = null;
630
+ /** True while rows reach back to the first projected row, so unseen identities are new. */
631
+ complete = false;
632
+ state = "loading";
633
+ buffer = [];
634
+ overflowed = false;
635
+ watchers = /* @__PURE__ */ new Set();
636
+ /** seqStart → pending change since the last flush; full means send the whole row. */
637
+ pending = /* @__PURE__ */ new Map();
638
+ pendingReset = false;
639
+ flushTimer;
640
+ retryTimer;
641
+ subscription = null;
642
+ token = 0;
643
+ loads = 0;
644
+ driver;
645
+ agentId;
646
+ constructor(driver, agentId) {
647
+ this.driver = driver;
648
+ this.agentId = agentId;
649
+ }
650
+ get watcherCount() {
651
+ return this.watchers.size;
652
+ }
653
+ start() {
654
+ const token = ++this.token;
655
+ this.state = "loading";
656
+ const subscription = this.driver.subscribeAgentTimeline(this.agentId, (message) => {
657
+ if (token === this.token) this.onMessage(message);
658
+ });
659
+ this.subscription = subscription;
660
+ subscription.ready.then(() => token === this.token ? this.reload() : void 0, () => this.fail(token));
661
+ }
662
+ dispose() {
663
+ this.token++;
664
+ this.state = "disposed";
665
+ clearTimeout(this.flushTimer);
666
+ clearTimeout(this.retryTimer);
667
+ this.watchers.clear();
668
+ const released = this.subscription?.release().catch(() => {}) ?? Promise.resolve();
669
+ this.subscription = null;
670
+ return released;
671
+ }
672
+ watch(watcher) {
673
+ if (this.state === "live" || this.state === "catching-up") {
674
+ this.flush();
675
+ watcher([this.resetOp()]);
676
+ }
677
+ this.watchers.add(watcher);
678
+ return () => this.watchers.delete(watcher);
679
+ }
680
+ onMessage(message) {
681
+ switch (message.type) {
682
+ case "agent_stream": {
683
+ const payload = message.payload;
684
+ if (payload.event.type !== "timeline" || payload.seq === void 0) return;
685
+ if (this.state !== "live") return this.bufferEvent(payload);
686
+ return this.process(payload);
687
+ }
688
+ case "agent.timeline.replacement":
689
+ this.reload();
690
+ return;
691
+ case "agent.timeline.subscription_restored":
692
+ this.state === "live" && this.catchUp();
693
+ return;
694
+ case "agent.timeline.error": return this.fail(this.token);
695
+ }
696
+ }
697
+ bufferEvent(payload) {
698
+ if (this.overflowed) return;
699
+ if (this.buffer.length >= MAX_BUFFER) {
700
+ this.buffer = [];
701
+ this.overflowed = true;
702
+ return;
703
+ }
704
+ this.buffer.push(payload);
705
+ }
706
+ process(payload) {
707
+ const seq = payload.seq;
708
+ if (payload.epoch !== void 0 && payload.epoch !== this.epoch) return void this.reload();
709
+ if (seq <= this.lastSeq) return;
710
+ if (seq > this.lastSeq + 1) {
711
+ this.bufferEvent(payload);
712
+ this.catchUp();
713
+ return;
714
+ }
715
+ if (!this.applyLive(payload)) return void this.catchUp();
716
+ this.lastSeq = seq;
717
+ }
718
+ /** Folds one source event; false when the view cannot decide locally. */
719
+ applyLive(payload) {
720
+ const entry = {
721
+ seqStart: payload.seq,
722
+ seqEnd: payload.seq,
723
+ timestamp: payload.timestamp,
724
+ provider: payload.event.provider ?? "",
725
+ ...payload.event.turnId ? { turnId: payload.event.turnId } : {},
726
+ item: payload.event.item
727
+ };
728
+ const identity = timelineItemIdentity(entry.item);
729
+ if (identity !== null) {
730
+ const existing = this.identities.get(identity);
731
+ if (existing) {
732
+ if (entry.item.type === "tool_call") {
733
+ if (existing.item.type === "tool_call" && existing.turnId === entry.turnId) {
734
+ existing.item = mergeToolCallItems(existing.item, entry.item);
735
+ existing.timestamp = entry.timestamp;
736
+ existing.seqEnd = Math.max(existing.seqEnd, entry.seqEnd);
737
+ this.mark(existing.seqStart, true);
738
+ return true;
739
+ }
740
+ } else if (entry.item.type === "plugin" && existing.item.type === "plugin") {
741
+ Object.assign(existing, {
742
+ ...entry,
743
+ seqStart: existing.seqStart
744
+ });
745
+ this.mark(existing.seqStart, true);
746
+ return true;
747
+ }
748
+ } else if (!this.complete) return false;
749
+ }
750
+ const previous = this.rows.at(-1);
751
+ if (previous && textMergeable(previous, entry)) {
752
+ const text = entry.item.text ?? "";
753
+ previous.item = {
754
+ type: previous.item.type,
755
+ text: (previous.item.text ?? "") + text,
756
+ ...previous.item.type === "assistant_message" && previous.item.messageId ? { messageId: previous.item.messageId } : {}
757
+ };
758
+ previous.timestamp = entry.timestamp;
759
+ previous.seqEnd = entry.seqEnd;
760
+ this.mark(previous.seqStart, false, text);
761
+ return true;
762
+ }
763
+ this.insert(entry);
764
+ return true;
765
+ }
766
+ async reload() {
767
+ const token = this.token;
768
+ const load = ++this.loads;
769
+ this.state = "loading";
770
+ try {
771
+ const page = await this.driver.fetchAgentTimeline(this.agentId, {
772
+ direction: "tail",
773
+ limit: TAIL_LIMIT,
774
+ projection: "projected",
775
+ wholeTurns: true
776
+ });
777
+ if (token !== this.token || load !== this.loads) return;
778
+ this.replaceWith(page);
779
+ this.settle();
780
+ } catch {
781
+ this.fail(token);
782
+ }
783
+ }
784
+ async catchUp() {
785
+ if (this.state === "catching-up" || this.state === "loading") return;
786
+ const token = this.token;
787
+ this.state = "catching-up";
788
+ try {
789
+ for (;;) {
790
+ const page = await this.driver.fetchAgentTimeline(this.agentId, {
791
+ direction: "after",
792
+ cursor: {
793
+ epoch: this.epoch,
794
+ seq: Math.max(0, this.lastSeq)
795
+ },
796
+ limit: CATCH_UP_PAGE,
797
+ projection: "projected"
798
+ });
799
+ if (token !== this.token) return;
800
+ if (page.reset || page.epoch !== this.epoch) {
801
+ this.replaceWith(page);
802
+ break;
803
+ }
804
+ for (const entry of page.entries) this.upsertFetched(entry);
805
+ const end = page.endCursor?.seq ?? (page.hasNewer ? null : page.window.maxSeq);
806
+ if (end === null) break;
807
+ this.lastSeq = Math.max(this.lastSeq, end);
808
+ if (!page.hasNewer) break;
809
+ }
810
+ this.settle();
811
+ } catch {
812
+ this.fail(token);
813
+ }
814
+ }
815
+ /** Back to live: replay what arrived meanwhile, or reload if the buffer overflowed. */
816
+ settle() {
817
+ if (this.overflowed) {
818
+ this.overflowed = false;
819
+ this.buffer = [];
820
+ this.reload();
821
+ return;
822
+ }
823
+ this.state = "live";
824
+ const events = this.buffer;
825
+ this.buffer = [];
826
+ for (let i = 0; i < events.length; i++) {
827
+ if (this.state !== "live") {
828
+ this.buffer = events.slice(i).concat(this.buffer);
829
+ return;
830
+ }
831
+ this.process(events[i]);
832
+ }
833
+ }
834
+ fail(token) {
835
+ if (token !== this.token || this.state === "disposed") return;
836
+ this.state = "failed";
837
+ this.broadcast([{
838
+ type: "error",
839
+ message: "Timeline sync interrupted; retrying"
840
+ }]);
841
+ clearTimeout(this.retryTimer);
842
+ this.retryTimer = setTimeout(() => {
843
+ if (this.state !== "failed" || token !== this.token) return;
844
+ this.subscription?.release().catch(() => {});
845
+ this.start();
846
+ }, RETRY_MS);
847
+ this.retryTimer.unref?.();
848
+ }
849
+ replaceWith(page) {
850
+ this.rows = [];
851
+ this.bySeqStart.clear();
852
+ this.identities.clear();
853
+ this.pending.clear();
854
+ this.epoch = page.epoch;
855
+ this.lastSeq = page.window.maxSeq;
856
+ this.hasOlder = page.hasOlder;
857
+ this.startCursor = page.startCursor;
858
+ this.complete = !page.hasOlder;
859
+ for (const entry of page.entries) this.upsertFetched(entry, false);
860
+ this.buffer = this.buffer.filter((e) => e.epoch === this.epoch && e.seq > this.lastSeq);
861
+ this.pending.clear();
862
+ this.pendingReset = true;
863
+ this.scheduleFlush();
864
+ }
865
+ upsertFetched(entry, notify = true) {
866
+ const row = {
867
+ seqStart: entry.seqStart,
868
+ seqEnd: entry.seqEnd,
869
+ timestamp: entry.timestamp,
870
+ provider: entry.provider,
871
+ ...entry.turnId ? { turnId: entry.turnId } : {},
872
+ item: entry.item
873
+ };
874
+ const existing = this.bySeqStart.get(row.seqStart);
875
+ if (existing) {
876
+ Object.assign(existing, row);
877
+ if (!row.turnId) delete existing.turnId;
878
+ this.noteIdentity(existing);
879
+ if (notify) this.mark(existing.seqStart, true);
880
+ return;
881
+ }
882
+ this.insert(row, notify);
883
+ }
884
+ insert(row, notify = true) {
885
+ let index = this.rows.length;
886
+ if (index && this.rows[index - 1].seqStart > row.seqStart) {
887
+ let low = 0, high = index;
888
+ while (low < high) {
889
+ const middle = low + high >>> 1;
890
+ if (this.rows[middle].seqStart < row.seqStart) low = middle + 1;
891
+ else high = middle;
892
+ }
893
+ index = low;
894
+ }
895
+ if (index === this.rows.length) this.rows.push(row);
896
+ else this.rows.splice(index, 0, row);
897
+ this.bySeqStart.set(row.seqStart, row);
898
+ this.noteIdentity(row);
899
+ if (notify) this.mark(row.seqStart, true);
900
+ if (this.rows.length > MAX_ROWS) this.trim();
901
+ }
902
+ /** Like the daemon, an identity resolves to its most recent row. */
903
+ noteIdentity(row) {
904
+ const identity = timelineItemIdentity(row.item);
905
+ if (identity === null) return;
906
+ const current = this.identities.get(identity);
907
+ if (!current || current.seqStart <= row.seqStart) this.identities.set(identity, row);
908
+ }
909
+ trim() {
910
+ const removed = this.rows.splice(0, this.rows.length - KEEP_ROWS);
911
+ for (const row of removed) {
912
+ this.bySeqStart.delete(row.seqStart);
913
+ this.pending.delete(row.seqStart);
914
+ const identity = timelineItemIdentity(row.item);
915
+ if (identity !== null && this.identities.get(identity) === row) this.identities.delete(identity);
916
+ }
917
+ this.complete = false;
918
+ this.hasOlder = true;
919
+ this.startCursor = {
920
+ epoch: this.epoch,
921
+ seq: this.rows[0].seqStart
922
+ };
923
+ }
924
+ mark(seqStart, full, text = "") {
925
+ if (this.pendingReset) return;
926
+ const pending = this.pending.get(seqStart);
927
+ if (!pending) this.pending.set(seqStart, {
928
+ full,
929
+ text: full ? "" : text
930
+ });
931
+ else if (full) {
932
+ pending.full = true;
933
+ pending.text = "";
934
+ } else if (!pending.full) pending.text += text;
935
+ this.scheduleFlush();
936
+ }
937
+ scheduleFlush() {
938
+ if (this.flushTimer || !this.watchers.size) return;
939
+ this.flushTimer = setTimeout(() => this.flush(), FLUSH_MS);
940
+ }
941
+ flush() {
942
+ clearTimeout(this.flushTimer);
943
+ this.flushTimer = void 0;
944
+ if (this.pendingReset) {
945
+ this.pendingReset = false;
946
+ this.pending.clear();
947
+ return this.broadcast([this.resetOp()]);
948
+ }
949
+ if (!this.pending.size) return;
950
+ const ops = [];
951
+ for (const [seqStart, change] of this.pending) {
952
+ const row = this.bySeqStart.get(seqStart);
953
+ if (!row) continue;
954
+ ops.push(change.full ? {
955
+ type: "upsert",
956
+ row: { ...row }
957
+ } : {
958
+ type: "append",
959
+ seqStart,
960
+ seqEnd: row.seqEnd,
961
+ timestamp: row.timestamp,
962
+ text: change.text
963
+ });
964
+ }
965
+ this.pending.clear();
966
+ if (ops.length) this.broadcast(ops);
967
+ }
968
+ resetOp() {
969
+ const start = Math.max(0, this.rows.length - RESET_ROWS);
970
+ const rows = this.rows.slice(start).map((row) => ({ ...row }));
971
+ return {
972
+ type: "reset",
973
+ epoch: this.epoch,
974
+ rows,
975
+ hasOlder: this.hasOlder || start > 0,
976
+ startCursor: start > 0 ? {
977
+ epoch: this.epoch,
978
+ seq: rows[0].seqStart
979
+ } : this.startCursor
980
+ };
981
+ }
982
+ broadcast(ops) {
983
+ for (const watcher of this.watchers) watcher(ops);
984
+ }
985
+ };
986
+ // src/server/hosts.ts
987
+ var UnknownHostError = class extends Error {
988
+ constructor() {
989
+ super("Unknown host");
990
+ }
991
+ };
992
+ /** Idle grace before an unwatched timeline releases its daemon subscription. */
993
+ const TIMELINE_GRACE_MS = 3e4;
994
+ var Hosts = class {
995
+ agents = new VersionedCollection();
996
+ workspaces = new VersionedCollection();
997
+ clients = /* @__PURE__ */ new Map();
998
+ diagnostics = /* @__PURE__ */ new Map();
999
+ labels = /* @__PURE__ */ new Map();
1000
+ timelines = /* @__PURE__ */ new Map();
1001
+ agentListeners = /* @__PURE__ */ new Set();
1002
+ hostListeners = /* @__PURE__ */ new Set();
1003
+ transitionListeners = /* @__PURE__ */ new Set();
1004
+ add(host) {
1005
+ const driver = createHostClient(host.connection, {
1006
+ clientId: `litepaseo-${host.id}`,
1007
+ clientType: "cli",
1008
+ connectTimeoutMs: 5e3,
1009
+ reconnect: { enabled: true },
1010
+ logger: {
1011
+ debug() {},
1012
+ info() {},
1013
+ warn() {},
1014
+ error() {}
1015
+ }
1016
+ });
1017
+ this.labels.set(host.id, host.label);
1018
+ this.attach(host.id, driver, createPaseoApi(driver));
1019
+ driver.connect().catch((error) => {
1020
+ if (this.clients.get(host.id)?.driver !== driver) return;
1021
+ this.noteFailure(host.id, error);
1022
+ this.emit(this.hostListeners);
1023
+ });
1024
+ }
1025
+ /** Wires a connected-or-connecting driver; separate from `add` so tests can inject doubles. */
1026
+ attach(hostId, driver, api) {
1027
+ const directory = new HostDirectory(hostId, driver, this.agents, () => this.emit(this.agentListeners), (previous, next) => {
1028
+ for (const listener of this.transitionListeners) listener(previous, next);
1029
+ });
1030
+ const workspaces = new HostWorkspaces(hostId, driver, this.workspaces, () => this.emit(this.agentListeners));
1031
+ const update = (state) => {
1032
+ const previous = this.diagnostics.get(hostId) ?? {};
1033
+ if (state.status === "connected") this.diagnostics.set(hostId, { lastConnectedAt: (/* @__PURE__ */ new Date()).toISOString() });
1034
+ else if (state.status === "connecting") this.diagnostics.set(hostId, {
1035
+ ...previous,
1036
+ nextRetryAt: void 0,
1037
+ attempt: state.attempt
1038
+ });
1039
+ else if (state.status === "disconnected") {
1040
+ this.noteFailure(hostId, state);
1041
+ const retry = state.nextRetryAt && Date.parse(state.nextRetryAt);
1042
+ this.diagnostics.set(hostId, {
1043
+ ...this.diagnostics.get(hostId),
1044
+ nextRetryAt: retry && Number.isFinite(retry) ? new Date(retry).toISOString() : void 0
1045
+ });
1046
+ }
1047
+ this.emit(this.hostListeners);
1048
+ };
1049
+ const stopStatus = driver.subscribeConnectionStatus(update);
1050
+ update(driver.getConnectionState());
1051
+ this.clients.set(hostId, {
1052
+ driver,
1053
+ api,
1054
+ directory,
1055
+ workspaces,
1056
+ stopStatus
1057
+ });
1058
+ directory.start();
1059
+ if (driver.observeWorkspaces) workspaces.start();
1060
+ this.emit(this.hostListeners);
1061
+ }
1062
+ get(id) {
1063
+ const c = this.clients.get(id);
1064
+ if (!c) throw new UnknownHostError();
1065
+ return c;
1066
+ }
1067
+ diagnostic(id) {
1068
+ return this.diagnostics.get(id);
1069
+ }
1070
+ noteFailure(id, failure) {
1071
+ const error = connectionProblem(failure);
1072
+ const previous = this.diagnostics.get(id) ?? {};
1073
+ if (previous.error?.code !== error.code) console.warn(JSON.stringify({
1074
+ event: "host_connection_failed",
1075
+ hostId: id,
1076
+ code: error.code
1077
+ }));
1078
+ this.diagnostics.set(id, {
1079
+ ...previous,
1080
+ error
1081
+ });
1082
+ }
1083
+ state(id) {
1084
+ return this.clients.get(id)?.driver.getConnectionState().status ?? "offline";
1085
+ }
1086
+ async remove(id) {
1087
+ const c = this.clients.get(id);
1088
+ this.clients.delete(id);
1089
+ const releases = [];
1090
+ for (const [key, entry] of this.timelines) if (entry.hostId === id) {
1091
+ clearTimeout(entry.idle);
1092
+ releases.push(entry.view.dispose());
1093
+ this.timelines.delete(key);
1094
+ }
1095
+ if (c) {
1096
+ await Promise.all([
1097
+ ...releases,
1098
+ c.directory.dispose(),
1099
+ c.workspaces.dispose()
1100
+ ]);
1101
+ c.stopStatus();
1102
+ await c.api.dispose();
1103
+ await c.driver.close();
1104
+ }
1105
+ this.diagnostics.delete(id);
1106
+ this.labels.delete(id);
1107
+ this.emit(this.hostListeners);
1108
+ }
1109
+ async close() {
1110
+ await Promise.allSettled([...this.clients.keys()].map((id) => this.remove(id)));
1111
+ }
1112
+ onAgentsChanged(listener) {
1113
+ this.agentListeners.add(listener);
1114
+ return () => this.agentListeners.delete(listener);
1115
+ }
1116
+ /** Per-agent summary changes, for event detection (notifications). */
1117
+ onTransition(listener) {
1118
+ this.transitionListeners.add(listener);
1119
+ return () => this.transitionListeners.delete(listener);
1120
+ }
1121
+ /** Whether some browser is looking at this conversation right now. */
1122
+ isViewing(key) {
1123
+ return (this.timelines.get(key)?.view.watcherCount ?? 0) > 0;
1124
+ }
1125
+ label(hostId) {
1126
+ return this.labels.get(hostId) ?? "";
1127
+ }
1128
+ setLabel(hostId, label) {
1129
+ this.labels.set(hostId, label);
1130
+ }
1131
+ onHostsChanged(listener) {
1132
+ this.hostListeners.add(listener);
1133
+ return () => this.hostListeners.delete(listener);
1134
+ }
1135
+ /** Shares one live timeline per agent across all watching browsers. */
1136
+ watchTimeline(hostId, agentId, watcher) {
1137
+ const client = this.get(hostId);
1138
+ const key = `${hostId}:${agentId}`;
1139
+ let entry = this.timelines.get(key);
1140
+ if (!entry) {
1141
+ const view = new TimelineView(client.driver, agentId);
1142
+ entry = {
1143
+ view,
1144
+ hostId
1145
+ };
1146
+ this.timelines.set(key, entry);
1147
+ view.start();
1148
+ }
1149
+ clearTimeout(entry.idle);
1150
+ entry.idle = void 0;
1151
+ const stop = entry.view.watch(watcher);
1152
+ const current = entry;
1153
+ return () => {
1154
+ stop();
1155
+ if (current.view.watcherCount || this.timelines.get(key) !== current) return;
1156
+ current.idle = setTimeout(() => {
1157
+ if (current.view.watcherCount || this.timelines.get(key) !== current) return;
1158
+ current.view.dispose();
1159
+ this.timelines.delete(key);
1160
+ }, TIMELINE_GRACE_MS);
1161
+ current.idle.unref?.();
1162
+ };
1163
+ }
1164
+ emit(listeners) {
1165
+ for (const listener of listeners) listener();
1166
+ }
1167
+ };
1168
+ // src/server/sse.ts
1169
+ const HEARTBEAT_MS = 2e4;
1170
+ /** Server-sent events over a plain fetch response, so the bearer header still authenticates. */
1171
+ function eventStream(signal, open, valid = () => true) {
1172
+ const encoder = new TextEncoder();
1173
+ let cleanup;
1174
+ const stop = () => {
1175
+ cleanup?.();
1176
+ cleanup = void 0;
1177
+ };
1178
+ const body = new ReadableStream({
1179
+ start(controller) {
1180
+ const write = (text) => {
1181
+ try {
1182
+ controller.enqueue(encoder.encode(text));
1183
+ } catch {
1184
+ stop();
1185
+ }
1186
+ };
1187
+ const heartbeat = setInterval(() => {
1188
+ if (valid()) return write(": ping\n\n");
1189
+ stop();
1190
+ try {
1191
+ controller.close();
1192
+ } catch {}
1193
+ }, HEARTBEAT_MS);
1194
+ const close = open((data) => write(`data: ${JSON.stringify(data)}\n\n`));
1195
+ cleanup = () => {
1196
+ clearInterval(heartbeat);
1197
+ close();
1198
+ };
1199
+ signal.addEventListener("abort", () => {
1200
+ stop();
1201
+ try {
1202
+ controller.close();
1203
+ } catch {}
1204
+ });
1205
+ },
1206
+ cancel: stop
1207
+ });
1208
+ return new Response(body, { headers: {
1209
+ "Content-Type": "text/event-stream",
1210
+ "Cache-Control": "no-cache, no-transform",
1211
+ "X-Accel-Buffering": "no"
1212
+ } });
1213
+ }
1214
+ // src/server/media.ts
1215
+ /** Raster images only: an SVG opened directly could run script on this origin. */
1216
+ const IMAGE_MIME = {
1217
+ png: "image/png",
1218
+ jpg: "image/jpeg",
1219
+ jpeg: "image/jpeg",
1220
+ webp: "image/webp",
1221
+ gif: "image/gif",
1222
+ bmp: "image/bmp",
1223
+ avif: "image/avif"
1224
+ };
1225
+ const MAX_IMAGE_BYTES = 16777216;
1226
+ const extension = (path) => /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? "";
1227
+ const imageMime = (path) => IMAGE_MIME[extension(path)] ?? null;
1228
+ /** True when the daemon runs on this machine (loopback TCP/WebSocket or a local socket). */
1229
+ function isLocalConnection(connection) {
1230
+ try {
1231
+ const target = parseHostTarget(connection);
1232
+ if (target.kind !== "socket") return false;
1233
+ if (target.socketPath) return true;
1234
+ const host = new URL(target.url ?? "").hostname.replace(/^\[|\]$/g, "");
1235
+ return host === "localhost" || host === "::1" || /^127\./.test(host);
1236
+ } catch {
1237
+ return false;
1238
+ }
1239
+ }
1240
+ /**
1241
+ * Images a provider returned inline (screenshots, `read` of a PNG) are written by the daemon to
1242
+ * `<tmp>/paseo-attachments-XXXXXX/<sha256>.<ext>` and referenced from the message as file:// URLs.
1243
+ * The daemon's file API is confined to the workspace, so these are read from disk, and only when
1244
+ * the daemon shares this machine. The name pattern admits nothing but those materialized files.
1245
+ */
1246
+ function isMaterializedImagePath(path) {
1247
+ if (!isAbsolute(path) || normalize(path) !== path || !imageMime(path)) return false;
1248
+ const directory = dirname(path);
1249
+ return /^[a-f0-9]{64}\.[a-z0-9]+$/.test(basename(path)) && /^paseo-attachments-[A-Za-z0-9_-]{1,32}$/.test(basename(directory)) && [tmpdir(), "/tmp"].includes(dirname(directory));
1250
+ }
1251
+ async function readMaterializedImage(path) {
1252
+ if (!isMaterializedImagePath(path)) return null;
1253
+ try {
1254
+ const stats = await lstat(path);
1255
+ if (!stats.isFile() || stats.size > 16777216) return null;
1256
+ if (!isMaterializedImagePath(await realpath(path))) return null;
1257
+ return await readFile(path);
1258
+ } catch {
1259
+ return null;
1260
+ }
1261
+ }
1262
+ /** Small LRU for project icons: a sidebar asks for each project once per page load. */
1263
+ var IconCache = class {
1264
+ entries = /* @__PURE__ */ new Map();
1265
+ limit;
1266
+ ttlMs;
1267
+ constructor(limit = 256, ttlMs = 6e5) {
1268
+ this.limit = limit;
1269
+ this.ttlMs = ttlMs;
1270
+ }
1271
+ get(key) {
1272
+ const entry = this.entries.get(key);
1273
+ if (!entry) return void 0;
1274
+ if (Date.now() - entry.at > this.ttlMs) {
1275
+ this.entries.delete(key);
1276
+ return;
1277
+ }
1278
+ this.entries.delete(key);
1279
+ this.entries.set(key, entry);
1280
+ return entry.icon;
1281
+ }
1282
+ set(key, icon) {
1283
+ this.entries.delete(key);
1284
+ this.entries.set(key, {
1285
+ at: Date.now(),
1286
+ icon
1287
+ });
1288
+ if (this.entries.size > this.limit) this.entries.delete(this.entries.keys().next().value);
1289
+ }
1290
+ };
1291
+ // src/server/workspace-routes.ts
1292
+ /** Text files larger than this open truncated: the viewer is for reading, not for dumps. */
1293
+ const MAX_TEXT_BYTES = 1048576;
1294
+ const MAX_ENTRIES = 2e3;
1295
+ /** Terminal output is coalesced into one event per frame-ish interval. */
1296
+ const TERMINAL_FLUSH_MS = 16;
1297
+ const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0"));
1298
+ /**
1299
+ * The workspace side panel (files, terminals) and schedules. Every call goes to the host's
1300
+ * daemon, which confines file access to the workspace and owns the terminals; nothing here
1301
+ * keeps state beyond an open terminal stream.
1302
+ */
1303
+ function registerWorkspaceRoutes(app, hosts, store, valid) {
1304
+ app.get("/api/hosts/:host/fs/list", async (c) => {
1305
+ const cwd = path.parse(c.req.query("cwd"));
1306
+ const dir = c.req.query("path") || ".";
1307
+ const { driver } = hosts.get(c.req.param("host"));
1308
+ try {
1309
+ const result = await driver.listDirectory(cwd, dir);
1310
+ const entries = (result.entries ?? []).map((e) => ({
1311
+ name: e.name,
1312
+ path: e.path,
1313
+ kind: e.kind,
1314
+ size: e.size
1315
+ })).sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name, void 0, { numeric: true }) : a.kind === "directory" ? -1 : 1);
1316
+ return c.json({
1317
+ path: result.path,
1318
+ entries: entries.slice(0, MAX_ENTRIES),
1319
+ truncated: entries.length > MAX_ENTRIES
1320
+ });
1321
+ } catch (error) {
1322
+ return c.json({ error: error.message || "Directory unavailable" }, 404);
1323
+ }
1324
+ });
1325
+ app.get("/api/hosts/:host/fs/read", async (c) => {
1326
+ const cwd = path.parse(c.req.query("cwd"));
1327
+ const file = path.parse(c.req.query("path"));
1328
+ const { driver } = hosts.get(c.req.param("host"));
1329
+ try {
1330
+ const result = await driver.readFile(cwd, file, void 0, 1048577);
1331
+ const text = result.kind === "text" ? new TextDecoder().decode(result.bytes.subarray(0, MAX_TEXT_BYTES)) : void 0;
1332
+ return c.json({
1333
+ path: result.path,
1334
+ kind: result.kind,
1335
+ mime: result.mime,
1336
+ size: result.size,
1337
+ modifiedAt: result.modifiedAt,
1338
+ ...text !== void 0 ? {
1339
+ text,
1340
+ truncated: result.size > MAX_TEXT_BYTES
1341
+ } : {}
1342
+ });
1343
+ } catch (error) {
1344
+ return c.json({ error: error.message || "File unavailable" }, 404);
1345
+ }
1346
+ });
1347
+ app.get("/api/hosts/:host/fs/raw", async (c) => {
1348
+ const cwd = path.parse(c.req.query("cwd"));
1349
+ const file = path.parse(c.req.query("path"));
1350
+ const mime = imageMime(file);
1351
+ if (!mime) return c.json({ error: "Only images can be opened raw" }, 415);
1352
+ const { driver } = hosts.get(c.req.param("host"));
1353
+ try {
1354
+ const result = await driver.readFile(cwd, file, void 0, MAX_IMAGE_BYTES);
1355
+ return c.body(result.bytes, 200, {
1356
+ "Content-Type": mime,
1357
+ "Cache-Control": "private, max-age=60"
1358
+ });
1359
+ } catch {
1360
+ return c.json({ error: "Image unavailable" }, 404);
1361
+ }
1362
+ });
1363
+ app.get("/api/hosts/:host/terminals", async (c) => {
1364
+ const cwd = path.parse(c.req.query("cwd"));
1365
+ const result = await hosts.get(c.req.param("host")).driver.listTerminals(cwd);
1366
+ return c.json((result.terminals ?? []).map((t) => ({
1367
+ id: t.id,
1368
+ name: t.name,
1369
+ title: t.title ?? null,
1370
+ cwd: t.cwd
1371
+ })));
1372
+ });
1373
+ app.post("/api/hosts/:host/terminals", async (c) => {
1374
+ const input = z.object({
1375
+ cwd: path,
1376
+ rows: z.number().int().min(4).max(500),
1377
+ cols: z.number().int().min(10).max(1e3),
1378
+ name: z.string().max(80).optional()
1379
+ }).parse(await c.req.json());
1380
+ const result = await hosts.get(c.req.param("host")).driver.createTerminal(input.cwd, input.name, void 0, { size: {
1381
+ rows: input.rows,
1382
+ cols: input.cols
1383
+ } });
1384
+ if (!result.terminal) return c.json({ error: result.error ?? "Could not open a terminal" }, 502);
1385
+ return c.json({
1386
+ id: result.terminal.id,
1387
+ name: result.terminal.name,
1388
+ title: result.terminal.title ?? null,
1389
+ cwd: result.terminal.cwd
1390
+ }, 201);
1391
+ });
1392
+ app.delete("/api/hosts/:host/terminals/:id", async (c) => {
1393
+ await hosts.get(c.req.param("host")).driver.killTerminal(c.req.param("id"));
1394
+ return c.json({ ok: true });
1395
+ });
1396
+ app.post("/api/hosts/:host/terminals/:id/input", async (c) => {
1397
+ const input = z.union([z.object({ data: z.string().min(1).max(65536) }), z.object({
1398
+ rows: z.number().int().min(4).max(500),
1399
+ cols: z.number().int().min(10).max(1e3)
1400
+ })]).parse(await c.req.json());
1401
+ const { driver } = hosts.get(c.req.param("host"));
1402
+ driver.sendTerminalInput(c.req.param("id"), "data" in input ? {
1403
+ type: "input",
1404
+ data: input.data
1405
+ } : {
1406
+ type: "resize",
1407
+ rows: input.rows,
1408
+ cols: input.cols
1409
+ });
1410
+ return c.json({ ok: true });
1411
+ });
1412
+ /** Live output as SSE: a full replay first (scrollback), then coalesced output chunks. */
1413
+ app.get("/api/hosts/:host/terminals/:id/stream", (c) => {
1414
+ const { driver } = hosts.get(c.req.param("host"));
1415
+ const id = c.req.param("id");
1416
+ const rows = Number(c.req.query("rows")) || 24, cols = Number(c.req.query("cols")) || 80;
1417
+ return eventStream(c.req.raw.signal, (send) => {
1418
+ let pending = [];
1419
+ let timer;
1420
+ const flush = () => {
1421
+ timer = void 0;
1422
+ if (!pending.length) return;
1423
+ send({
1424
+ t: "o",
1425
+ d: Buffer.concat(pending).toString("base64")
1426
+ });
1427
+ pending = [];
1428
+ };
1429
+ const push = (bytes) => {
1430
+ pending.push(bytes);
1431
+ timer ??= setTimeout(flush, TERMINAL_FLUSH_MS);
1432
+ };
1433
+ const subscription = driver.observeTerminal(id, (event) => {
1434
+ if (event.type === "output") push(event.data);
1435
+ else if (event.replay.type === "begin") {
1436
+ pending = [];
1437
+ send({ t: "reset" });
1438
+ } else if (event.replay.type === "data") push(event.replay.data);
1439
+ }, { restore: {
1440
+ mode: "full-snapshot",
1441
+ scrollbackLines: 2e3,
1442
+ size: {
1443
+ rows,
1444
+ cols
1445
+ }
1446
+ } });
1447
+ const stop = subscription.subscribe({
1448
+ snapshot: () => {},
1449
+ update: (message) => {
1450
+ if (message.type === "terminal_stream_exit") send({ t: "exit" });
1451
+ },
1452
+ error: () => send({ t: "exit" })
1453
+ });
1454
+ subscription.ready.catch(() => send({ t: "exit" }));
1455
+ return () => {
1456
+ clearTimeout(timer);
1457
+ stop();
1458
+ subscription.release().catch(() => {});
1459
+ };
1460
+ }, valid(c));
1461
+ });
1462
+ /** Every connected host's schedules; a host that fails reports its error instead. */
1463
+ app.get("/api/schedules", async (c) => {
1464
+ const results = await Promise.all(store.hosts().map(async (h) => {
1465
+ try {
1466
+ if (hosts.state(h.id) !== "connected") return {
1467
+ hostId: h.id,
1468
+ schedules: [],
1469
+ error: "Host is offline"
1470
+ };
1471
+ const list = await hosts.get(h.id).driver.scheduleList();
1472
+ return {
1473
+ hostId: h.id,
1474
+ schedules: list.schedules ?? [],
1475
+ error: list.error ?? null
1476
+ };
1477
+ } catch (error) {
1478
+ return {
1479
+ hostId: h.id,
1480
+ schedules: [],
1481
+ error: error.message || "Schedules unavailable"
1482
+ };
1483
+ }
1484
+ }));
1485
+ return c.json(results);
1486
+ });
1487
+ app.post("/api/hosts/:host/schedules", async (c) => {
1488
+ const input = z.object({
1489
+ name: z.string().trim().max(120).optional(),
1490
+ prompt: z.string().trim().min(1).max(2e4),
1491
+ cron: z.string().trim().min(9).max(120),
1492
+ timezone: z.string().max(80).optional(),
1493
+ cwd: path,
1494
+ provider: z.string().min(1).max(200),
1495
+ model: z.string().min(1).max(300).optional(),
1496
+ thinkingOptionId: z.string().min(1).max(200).optional(),
1497
+ archiveOnFinish: z.boolean().default(true),
1498
+ runOnCreate: z.boolean().default(false)
1499
+ }).parse(await c.req.json());
1500
+ const result = await hosts.get(c.req.param("host")).driver.scheduleCreate({
1501
+ prompt: input.prompt,
1502
+ name: input.name || null,
1503
+ cadence: {
1504
+ type: "cron",
1505
+ expression: input.cron,
1506
+ ...input.timezone ? { timezone: input.timezone } : {}
1507
+ },
1508
+ target: {
1509
+ type: "new-agent",
1510
+ config: {
1511
+ provider: input.provider,
1512
+ cwd: input.cwd,
1513
+ ...input.model ? { model: input.model } : {},
1514
+ ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {},
1515
+ archiveOnFinish: input.archiveOnFinish,
1516
+ isolation: "local",
1517
+ title: input.name || null
1518
+ }
1519
+ },
1520
+ runOnCreate: input.runOnCreate
1521
+ });
1522
+ if (result.error) return c.json({ error: result.error }, 400);
1523
+ return c.json(result.schedule, 201);
1524
+ });
1525
+ app.patch("/api/hosts/:host/schedules/:id", async (c) => {
1526
+ const input = z.object({
1527
+ name: z.string().trim().max(120).nullable().optional(),
1528
+ prompt: z.string().trim().min(1).max(2e4).optional(),
1529
+ cron: z.string().trim().min(9).max(120).optional(),
1530
+ timezone: z.string().max(80).optional(),
1531
+ cwd: path.optional(),
1532
+ provider: z.string().min(1).max(200).optional(),
1533
+ model: z.string().min(1).max(300).nullable().optional(),
1534
+ archiveOnFinish: z.boolean().optional()
1535
+ }).parse(await c.req.json());
1536
+ const agentConfig = {
1537
+ ...input.provider ? { provider: input.provider } : {},
1538
+ ...input.model !== void 0 ? { model: input.model } : {},
1539
+ ...input.cwd ? { cwd: input.cwd } : {},
1540
+ ...input.archiveOnFinish !== void 0 ? { archiveOnFinish: input.archiveOnFinish } : {}
1541
+ };
1542
+ const result = await hosts.get(c.req.param("host")).driver.scheduleUpdate({
1543
+ id: c.req.param("id"),
1544
+ ...input.name !== void 0 ? { name: input.name || null } : {},
1545
+ ...input.prompt ? { prompt: input.prompt } : {},
1546
+ ...input.cron ? { cadence: {
1547
+ type: "cron",
1548
+ expression: input.cron,
1549
+ ...input.timezone ? { timezone: input.timezone } : {}
1550
+ } } : {},
1551
+ ...Object.keys(agentConfig).length ? { newAgentConfig: agentConfig } : {}
1552
+ });
1553
+ if (result?.error) return c.json({ error: result.error }, 400);
1554
+ return c.json(result?.schedule ?? { ok: true });
1555
+ });
1556
+ const action = (name) => async (c) => {
1557
+ const { driver } = hosts.get(c.req.param("host"));
1558
+ const options = { id: c.req.param("id") };
1559
+ const result = name === "pause" ? await driver.schedulePause(options) : name === "resume" ? await driver.scheduleResume(options) : name === "run" ? await driver.scheduleRunOnce(options) : name === "delete" ? await driver.scheduleDelete(options) : await driver.scheduleLogs(options);
1560
+ if (result?.error) return c.json({ error: result.error }, 400);
1561
+ return c.json(name === "logs" ? { runs: (result.runs ?? []).slice(-50).reverse() } : { ok: true });
1562
+ };
1563
+ app.post("/api/hosts/:host/schedules/:id/pause", action("pause"));
1564
+ app.post("/api/hosts/:host/schedules/:id/resume", action("resume"));
1565
+ app.post("/api/hosts/:host/schedules/:id/run", action("run"));
1566
+ app.delete("/api/hosts/:host/schedules/:id", action("delete"));
1567
+ app.get("/api/hosts/:host/schedules/:id/logs", action("logs"));
1568
+ }
1569
+ // src/server/attachments.ts
1570
+ const MAX_FILE_BYTES = 8388608;
1571
+ const MAX_TOTAL = 67108864;
1572
+ const TTL = 12e5;
1573
+ const IMAGE_TYPES = /* @__PURE__ */ new Set([
1574
+ "image/png",
1575
+ "image/jpeg",
1576
+ "image/webp",
1577
+ "image/gif"
1578
+ ]);
1579
+ const MAX_FILES = 256;
1580
+ var Attachments = class {
1581
+ /** Insertion order is expiry order (fixed TTL), so pruning stops at the first live entry. */
1582
+ entries = /* @__PURE__ */ new Map();
1583
+ totalBytes = 0;
1584
+ owners = /* @__PURE__ */ new Map();
1585
+ timer = setInterval(() => this.prune(), 6e4);
1586
+ constructor() {
1587
+ this.timer.unref();
1588
+ }
1589
+ close() {
1590
+ clearInterval(this.timer);
1591
+ this.entries.clear();
1592
+ this.owners.clear();
1593
+ this.totalBytes = 0;
1594
+ }
1595
+ delete(id) {
1596
+ const entry = this.entries.get(id);
1597
+ if (!entry) return;
1598
+ this.entries.delete(id);
1599
+ this.totalBytes -= entry.bytes.length;
1600
+ const own = this.owners.get(entry.owner);
1601
+ own.bytes -= entry.bytes.length;
1602
+ if (!--own.files) this.owners.delete(entry.owner);
1603
+ }
1604
+ /** O(expired entries). */
1605
+ prune(now = Date.now()) {
1606
+ for (const [id, entry] of this.entries) {
1607
+ if (entry.expires > now) break;
1608
+ this.delete(id);
1609
+ }
1610
+ }
1611
+ clearOwner(owner) {
1612
+ if (!this.owners.has(owner)) return;
1613
+ for (const [id, entry] of this.entries) if (entry.owner === owner) this.delete(id);
1614
+ }
1615
+ put(owner, host, agent, name, mime, bytes) {
1616
+ this.prune();
1617
+ if (!name || name.length > 200 || /[\x00-\x1f/\\]/.test(name)) throw new Error("Use a file name without path separators.");
1618
+ if (!bytes.length || bytes.length > 8388608) throw new Error("Files must be between 1 byte and 8 MiB.");
1619
+ const own = this.owners.get(owner) ?? {
1620
+ bytes: 0,
1621
+ files: 0
1622
+ };
1623
+ if (this.totalBytes + bytes.length > MAX_TOTAL || own.bytes + bytes.length > 25165824 || own.files >= 16 || this.entries.size >= MAX_FILES) throw new Error("Attachment staging is full. Remove files or wait for them to expire.");
1624
+ if (IMAGE_TYPES.has(mime)) {
1625
+ if (!(mime === "image/png" ? bytes.subarray(0, 8).equals(Buffer.from([
1626
+ 137,
1627
+ 80,
1628
+ 78,
1629
+ 71,
1630
+ 13,
1631
+ 10,
1632
+ 26,
1633
+ 10
1634
+ ])) : mime === "image/jpeg" ? bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 : mime === "image/gif" ? /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) : bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP")) throw new Error("Image content does not match its file type.");
1635
+ }
1636
+ const entry = {
1637
+ id: randomUUID(),
1638
+ owner,
1639
+ host,
1640
+ agent,
1641
+ name,
1642
+ mime,
1643
+ bytes,
1644
+ expires: Date.now() + TTL
1645
+ };
1646
+ this.entries.set(entry.id, entry);
1647
+ this.totalBytes += bytes.length;
1648
+ this.owners.set(owner, {
1649
+ bytes: own.bytes + bytes.length,
1650
+ files: own.files + 1
1651
+ });
1652
+ return {
1653
+ id: entry.id,
1654
+ name,
1655
+ mimeType: mime,
1656
+ size: bytes.length,
1657
+ expires: entry.expires
1658
+ };
1659
+ }
1660
+ get(id, owner, host, agent) {
1661
+ this.prune();
1662
+ const entry = this.entries.get(id);
1663
+ if (entry && entry.expires <= Date.now()) this.delete(id);
1664
+ if (!entry || entry.expires <= Date.now() || entry.owner !== owner || entry.host !== host || entry.agent !== agent) throw new Error("Attachment expired or belongs to another session. Select it again.");
1665
+ return entry;
1666
+ }
1667
+ remove(id, owner, host, agent) {
1668
+ this.get(id, owner, host, agent);
1669
+ this.delete(id);
1670
+ }
1671
+ async capabilities(hosts, host, agent) {
1672
+ const client = hosts.get(host);
1673
+ let facts = client.directory.facts(agent);
1674
+ if (!facts) {
1675
+ const ref = client.api.agents.ref(agent);
1676
+ await ref.refresh();
1677
+ facts = {
1678
+ provider: ref.current()?.provider,
1679
+ capabilities: ref.capabilities
1680
+ };
1681
+ }
1682
+ const provider = facts.provider ?? "";
1683
+ return {
1684
+ images: [
1685
+ "codex",
1686
+ "claude",
1687
+ "pi"
1688
+ ].includes(provider) && facts.capabilities?.supportsImages !== false,
1689
+ files: facts.capabilities?.supportsToolInvocations === true,
1690
+ maxBytes: MAX_FILE_BYTES,
1691
+ note: "Images require a vision-capable model. Other files are uploaded to the daemon for the agent to read with its tools."
1692
+ };
1693
+ }
1694
+ async prepare(hosts, owner, host, agent, ids) {
1695
+ const entries = ids.map((id) => this.get(id, owner, host, agent));
1696
+ if (!entries.length) return {
1697
+ images: [],
1698
+ attachments: []
1699
+ };
1700
+ const caps = await this.capabilities(hosts, host, agent).catch(() => {
1701
+ throw new Error("Could not verify attachment support. Reconnect the host and retry.");
1702
+ });
1703
+ const images = [], attachments = [];
1704
+ for (const entry of entries) if (IMAGE_TYPES.has(entry.mime)) {
1705
+ if (!caps.images) throw new Error("This provider does not support image attachments.");
1706
+ images.push({
1707
+ data: entry.bytes.toString("base64"),
1708
+ mimeType: entry.mime
1709
+ });
1710
+ } else {
1711
+ if (!caps.files) throw new Error("This agent cannot read uploaded files.");
1712
+ if (!entry.remote) {
1713
+ const uploaded = await hosts.get(host).driver.uploadFile({
1714
+ fileName: entry.name,
1715
+ mimeType: entry.mime,
1716
+ bytes: entry.bytes
1717
+ }).catch(() => {
1718
+ throw new Error("Daemon file upload failed. Retry the upload before sending.");
1719
+ });
1720
+ if (uploaded.error || !uploaded.file) throw new Error("Daemon file upload failed. Retry the upload before sending.");
1721
+ entry.remote = uploaded.file;
1722
+ }
1723
+ attachments.push(entry.remote);
1724
+ }
1725
+ return {
1726
+ images,
1727
+ attachments
1728
+ };
1729
+ }
1730
+ consumed(ids) {
1731
+ for (const id of ids) this.delete(id);
1732
+ }
1733
+ };
1734
+ // src/server/message-status.ts
1735
+ /** Positive evidence only. Missing, rewound, or out-of-window messages remain uncertain. */
1736
+ async function confirmedMessages(driver, agentId, ids, maxPages = 5) {
1737
+ const wanted = new Set(ids), confirmed = /* @__PURE__ */ new Set();
1738
+ let cursor = null;
1739
+ const seen = /* @__PURE__ */ new Set();
1740
+ for (let pageNumber = 0; pageNumber < maxPages && confirmed.size < wanted.size; pageNumber++) {
1741
+ const page = await driver.fetchAgentTimeline(agentId, {
1742
+ direction: cursor ? "before" : "tail",
1743
+ ...cursor ? { cursor } : {},
1744
+ limit: 200,
1745
+ projection: "projected"
1746
+ });
1747
+ for (const entry of page.entries) {
1748
+ const item = entry.item;
1749
+ if (item.type !== "user_message") continue;
1750
+ const id = item.clientMessageId ?? item.messageId;
1751
+ if (typeof id === "string" && wanted.has(id)) confirmed.add(id);
1752
+ }
1753
+ if (!page.hasOlder || !page.startCursor) break;
1754
+ const key = JSON.stringify(page.startCursor);
1755
+ if (seen.has(key)) break;
1756
+ seen.add(key);
1757
+ cursor = page.startCursor;
1758
+ }
1759
+ return [...confirmed];
1760
+ }
1761
+ // src/shared/wire.ts
1762
+ /** "Run npm test" → "run npm test", for use mid-sentence ("wants to run npm test"). */
1763
+ const midSentence = (text) => /^[A-Z][a-z]/.test(text) ? text[0].toLowerCase() + text.slice(1) : text;
1764
+ // src/server/notifier.ts
1765
+ /** Repeats of the same event for the same session within this window are dropped. */
1766
+ const DEDUPE_MS = 15e3;
1767
+ /** Turn ends older than this (seen late, e.g. after a reconnect) are not announced. */
1768
+ const STALE_MS = 6e5;
1769
+ function vapidKeys(store) {
1770
+ const saved = store.setting("vapid");
1771
+ if (saved) return JSON.parse(saved);
1772
+ const keys = webpush.generateVAPIDKeys();
1773
+ store.setSetting("vapid", JSON.stringify(keys));
1774
+ return keys;
1775
+ }
1776
+ /** Real delivery through the browser vendor's push service. */
1777
+ function webPushSender(store, subject) {
1778
+ const keys = vapidKeys(store);
1779
+ return { async send(subscription, payload) {
1780
+ await webpush.sendNotification({
1781
+ endpoint: subscription.endpoint,
1782
+ keys: {
1783
+ p256dh: subscription.p256dh,
1784
+ auth: subscription.auth
1785
+ }
1786
+ }, payload, {
1787
+ vapidDetails: {
1788
+ subject,
1789
+ publicKey: keys.publicKey,
1790
+ privateKey: keys.privateKey
1791
+ },
1792
+ TTL: 21600,
1793
+ urgency: "high"
1794
+ });
1795
+ } };
1796
+ }
1797
+ /**
1798
+ * Turns directory transitions into push notifications: a session starting to need the user
1799
+ * (a permission or question appears) and a turn finishing or failing. Detection is per
1800
+ * transition, O(1); delivery fans out to the (few) subscribed devices.
1801
+ */
1802
+ var Notifier = class {
1803
+ store;
1804
+ sender;
1805
+ isViewing;
1806
+ hostLabel;
1807
+ waiting = /* @__PURE__ */ new Set();
1808
+ recent = /* @__PURE__ */ new Map();
1809
+ now;
1810
+ constructor(options) {
1811
+ this.store = options.store;
1812
+ this.sender = options.sender;
1813
+ this.isViewing = options.isViewing;
1814
+ this.hostLabel = options.hostLabel;
1815
+ this.now = options.now ?? Date.now;
1816
+ }
1817
+ get waitingCount() {
1818
+ return this.waiting.size;
1819
+ }
1820
+ /** Feed every summary transition here (HostDirectory → Hosts.onTransition). */
1821
+ transition(previous, next) {
1822
+ const key = next?.key ?? previous.key;
1823
+ if (next?.attention) this.waiting.add(key);
1824
+ else this.waiting.delete(key);
1825
+ if (!previous || !next) return;
1826
+ const newPermission = next.pendingPermissions.some((p) => !previous.pendingPermissions.some((q) => q.id === p.id));
1827
+ if (next.attention && !previous.attention || newPermission) {
1828
+ const permission = next.pendingPermissions[0];
1829
+ const what = permission ? permission.kind === "question" ? `asks: ${permission.title || permission.name}` : `wants to ${midSentence(permission.title || permission.name)}` : "is waiting for you";
1830
+ this.emit("attention", next, `${next.project} · needs your input`, `${next.title || "Session"} ${what}`);
1831
+ } else if (previous.status === "running" && next.status !== "running") {
1832
+ if (this.now() - next.activityAt > STALE_MS) return;
1833
+ const failed = next.status === "error";
1834
+ this.emit(failed ? "turn-failed" : "turn-done", next, `${next.project} · ${failed ? "turn failed" : "turn finished"}`, next.title || "Session");
1835
+ }
1836
+ }
1837
+ async test(sessionId) {
1838
+ const subs = this.store.pushSubscriptions().filter((s) => s.sessionId === sessionId);
1839
+ await Promise.all(subs.map((s) => this.deliver(s, {
1840
+ title: "LitePaseo notifications work",
1841
+ body: "You'll hear from your agents when they need you or finish a turn.",
1842
+ tag: "litepaseo-test",
1843
+ url: "/",
1844
+ kind: "test",
1845
+ badge: this.waiting.size
1846
+ })));
1847
+ return subs.length;
1848
+ }
1849
+ emit(kind, agent, title, body) {
1850
+ const dedupeKey = `${kind}:${agent.key}`;
1851
+ const now = this.now();
1852
+ if (now - (this.recent.get(dedupeKey) ?? -Infinity) < DEDUPE_MS) return;
1853
+ this.recent.set(dedupeKey, now);
1854
+ if (this.recent.size > 5e3) this.recent.clear();
1855
+ const message = {
1856
+ title,
1857
+ body: `${body} — ${this.hostLabel(agent.hostId)}`.slice(0, 240),
1858
+ tag: agent.key,
1859
+ url: `/?session=${encodeURIComponent(agent.key)}`,
1860
+ kind,
1861
+ badge: this.waiting.size
1862
+ };
1863
+ const pref = kind === "attention" ? "attention" : "turns";
1864
+ for (const subscription of this.store.pushSubscriptions()) if (subscription.prefs[pref] && !this.isViewing(agent.key, subscription.sessionId)) this.deliver(subscription, message);
1865
+ }
1866
+ async deliver(subscription, message) {
1867
+ const session = this.store.sessionById(subscription.sessionId);
1868
+ if (!session || session.expires <= this.now()) {
1869
+ this.store.removePushSubscription(subscription.endpoint, subscription.sessionId);
1870
+ return;
1871
+ }
1872
+ try {
1873
+ await this.sender.send(subscription, JSON.stringify(message));
1874
+ } catch (error) {
1875
+ const status = error.statusCode;
1876
+ if (status === 404 || status === 410) this.store.removePushSubscription(subscription.endpoint);
1877
+ }
1878
+ }
1879
+ };
1880
+ // src/server/usage.ts
1881
+ /** Paseo's daemon caches usage for 5 minutes; reading more often only re-reads its copy. */
1882
+ const FRESH_MS = 3e5;
1883
+ const FAILED_RETRY_MS = 6e4;
1884
+ /**
1885
+ * Usage across every connected host. Each host is read at most once per freshness window and
1886
+ * only when someone asks (nothing polls while no screen shows usage); concurrent requests share
1887
+ * one in-flight read per host.
1888
+ */
1889
+ var UsageService = class {
1890
+ hosts;
1891
+ cache = /* @__PURE__ */ new Map();
1892
+ inflight = /* @__PURE__ */ new Map();
1893
+ now;
1894
+ constructor(hosts, now = Date.now) {
1895
+ this.hosts = hosts;
1896
+ this.now = now;
1897
+ }
1898
+ async report(force = false) {
1899
+ const ids = [...this.hosts.clients.keys()].filter((id) => this.hosts.state(id) === "connected");
1900
+ const results = await Promise.all(ids.map(async (id) => [id, await this.read(id, force)]));
1901
+ const accounts = /* @__PURE__ */ new Map();
1902
+ const unavailableHosts = [];
1903
+ let newest = 0;
1904
+ for (const [hostId, usage] of results) {
1905
+ const label = this.hosts.label(hostId) || hostId;
1906
+ if (!usage.ok) {
1907
+ unavailableHosts.push({
1908
+ hostId,
1909
+ label,
1910
+ error: usage.error ?? "Usage unavailable"
1911
+ });
1912
+ continue;
1913
+ }
1914
+ newest = Math.max(newest, usage.at);
1915
+ for (const p of usage.providers) {
1916
+ const windows = (p.windows ?? []).map((w) => ({
1917
+ id: String(w.id),
1918
+ label: String(w.label),
1919
+ shortLabel: w.shortLabel ?? null,
1920
+ remainingPct: typeof w.remainingPct === "number" ? w.remainingPct : typeof w.usedPct === "number" ? Math.max(0, 100 - w.usedPct) : null,
1921
+ resetsAt: w.resetsAt ?? null,
1922
+ tone: w.tone ?? null
1923
+ }));
1924
+ if (!windows.length && p.status === "unavailable") continue;
1925
+ const key = [
1926
+ p.providerId,
1927
+ p.planLabel ?? "",
1928
+ p.sourceLabel ?? "",
1929
+ ...windows.map((w) => `${w.id}@${w.resetsAt ?? ""}`)
1930
+ ].join("|");
1931
+ const existing = accounts.get(key);
1932
+ if (existing) existing.hosts.push(label);
1933
+ else accounts.set(key, {
1934
+ key,
1935
+ providerId: String(p.providerId),
1936
+ name: String(p.displayName ?? p.providerId),
1937
+ plan: p.planLabel ?? null,
1938
+ source: p.sourceLabel ?? null,
1939
+ status: String(p.status),
1940
+ error: p.error ?? null,
1941
+ windows,
1942
+ hosts: [label]
1943
+ });
1944
+ }
1945
+ }
1946
+ return {
1947
+ fetchedAt: newest ? new Date(newest).toISOString() : null,
1948
+ accounts: [...accounts.values()].sort((a, b) => a.name.localeCompare(b.name) || (a.plan ?? "").localeCompare(b.plan ?? "") || a.key.localeCompare(b.key)),
1949
+ unavailableHosts
1950
+ };
1951
+ }
1952
+ read(hostId, force) {
1953
+ const cached = this.cache.get(hostId);
1954
+ const age = cached ? this.now() - cached.at : Infinity;
1955
+ if (cached && age < (cached.ok ? FRESH_MS : FAILED_RETRY_MS) && !(force && age > 3e4)) return Promise.resolve(cached);
1956
+ const pending = this.inflight.get(hostId);
1957
+ if (pending) return pending;
1958
+ const request = (async () => {
1959
+ try {
1960
+ const result = await this.hosts.get(hostId).api.providers.listUsage();
1961
+ return {
1962
+ at: this.now(),
1963
+ ok: true,
1964
+ providers: result.providers ?? []
1965
+ };
1966
+ } catch (error) {
1967
+ return {
1968
+ at: this.now(),
1969
+ ok: false,
1970
+ providers: [],
1971
+ error: error.message || "Usage unavailable"
1972
+ };
1973
+ }
1974
+ })().then((usage) => {
1975
+ this.cache.set(hostId, usage);
1976
+ this.inflight.delete(hostId);
1977
+ return usage;
1978
+ });
1979
+ this.inflight.set(hostId, request);
1980
+ return request;
1981
+ }
1982
+ };
1983
+ // src/server/dictation.ts
1984
+ /**
1985
+ * File transcription for phrases from dictation-stream and complete clips from older clients.
1986
+ * Wraps mono PCM as WAV for an OpenAI-compatible `/audio/transcriptions` endpoint.
1987
+ * Voice input is configured in LitePaseo; no Paseo host is involved.
1988
+ *
1989
+ * Request shape differs by model generation (OpenAI speech-to-text guide, 2026):
1990
+ * - `gpt-transcribe` takes `languages[]` (several expected languages, for code-switching) and
1991
+ * `keywords[]`; it "replaces the singular `language` field. Don't send both fields."
1992
+ * - `whisper-1`, `gpt-4o(-mini)-transcribe` and most compatible providers (Groq, local Whisper
1993
+ * servers) take a single `language` and a free-text `prompt`.
1994
+ * Paseo always sends `language` (default "en"), which is what breaks `gpt-transcribe` there.
1995
+ * Here the shape follows the model name, and a 400 about the language field retries once with
1996
+ * the other shape, so unknown models on compatible providers still work.
1997
+ */
1998
+ const DEFAULT_BASE_URL = "https://api.openai.com/v1";
1999
+ /** Five minutes of 16 kHz, 16-bit mono speech (9.6 MB as WAV, under the 25 MB upload limit). */
2000
+ const MAX_DICTATION_BYTES = 96e5;
2001
+ const SETTING = "dictation";
2002
+ const UPSTREAM_TIMEOUT_MS = 11e4;
2003
+ /** Whisper reads at most 224 prompt tokens; keep the folded vocabulary well under that. */
2004
+ const LEGACY_PROMPT_CHARS = 600;
2005
+ const baseUrl = z.string().trim().max(500).transform((v) => (v || "https://api.openai.com/v1").replace(/\/+$/, "")).refine((v) => {
2006
+ try {
2007
+ return ["http:", "https:"].includes(new URL(v).protocol);
2008
+ } catch {
2009
+ return false;
2010
+ }
2011
+ }, "Base URL must be an http(s) address");
2012
+ const languageCode = z.string().trim().transform((v) => v.toLowerCase().replace("_", "-")).refine((v) => /^[a-z]{2,3}(-[a-z]{2})?$/.test(v), "Languages must be codes such as en, zh or zh-tw");
2013
+ /** The API rejects the whole request for a keyword with <, > or a line break. */
2014
+ const keyword = z.string().trim().min(1).max(100, "Each vocabulary term must be under 100 characters").refine((v) => !/[<>\r\n]/.test(v), "Vocabulary terms cannot contain < or >");
2015
+ const unique = (values) => [...new Set(values)];
2016
+ const DictationUpdate = z.object({
2017
+ baseUrl: baseUrl.optional().default(DEFAULT_BASE_URL),
2018
+ /** Omitted or empty keeps the saved key. */
2019
+ apiKey: z.string().trim().max(1e3).optional(),
2020
+ model: z.string().trim().max(200).optional().transform((v) => v || "gpt-transcribe"),
2021
+ languages: z.array(languageCode).max(10, "At most 10 languages").optional().default([]).transform(unique),
2022
+ keywords: z.array(keyword).max(100, "At most 100 vocabulary terms").optional().default([]).transform(unique)
2023
+ });
2024
+ function dictationConfig(store) {
2025
+ const raw = store.setting(SETTING);
2026
+ if (!raw) return null;
2027
+ try {
2028
+ const value = JSON.parse(raw);
2029
+ if (!value.apiKey || !value.baseUrl || !value.model) return null;
2030
+ return {
2031
+ baseUrl: value.baseUrl,
2032
+ apiKey: value.apiKey,
2033
+ model: value.model,
2034
+ languages: value.languages ?? [],
2035
+ keywords: value.keywords ?? []
2036
+ };
2037
+ } catch {
2038
+ return null;
2039
+ }
2040
+ }
2041
+ function dictationSettings(store) {
2042
+ const config = dictationConfig(store);
2043
+ return {
2044
+ configured: !!config,
2045
+ baseUrl: config?.baseUrl ?? "https://api.openai.com/v1",
2046
+ model: config?.model ?? "gpt-transcribe",
2047
+ languages: config?.languages ?? [],
2048
+ keywords: config?.keywords ?? [],
2049
+ keyHint: config ? "…" + config.apiKey.slice(-4) : ""
2050
+ };
2051
+ }
2052
+ function saveDictation(store, input) {
2053
+ const update = DictationUpdate.parse(input);
2054
+ const apiKey = update.apiKey || dictationConfig(store)?.apiKey;
2055
+ if (!apiKey) throw new Error("An API key is required");
2056
+ const config = {
2057
+ baseUrl: update.baseUrl,
2058
+ apiKey,
2059
+ model: update.model,
2060
+ languages: update.languages,
2061
+ keywords: update.keywords
2062
+ };
2063
+ store.setSetting(SETTING, JSON.stringify(config));
2064
+ return dictationSettings(store);
2065
+ }
2066
+ function clearDictation(store) {
2067
+ store.setSetting(SETTING, null);
2068
+ }
2069
+ /** A 44-byte RIFF header makes raw PCM16 a file every transcription API accepts. */
2070
+ function wav(pcm, rate) {
2071
+ const out = Buffer.alloc(44 + pcm.length);
2072
+ out.write("RIFF", 0);
2073
+ out.writeUInt32LE(36 + pcm.length, 4);
2074
+ out.write("WAVE", 8);
2075
+ out.write("fmt ", 12);
2076
+ out.writeUInt32LE(16, 16);
2077
+ out.writeUInt16LE(1, 20);
2078
+ out.writeUInt16LE(1, 22);
2079
+ out.writeUInt32LE(rate, 24);
2080
+ out.writeUInt32LE(rate * 2, 28);
2081
+ out.writeUInt16LE(2, 32);
2082
+ out.writeUInt16LE(16, 34);
2083
+ out.write("data", 36);
2084
+ out.writeUInt32LE(pcm.length, 40);
2085
+ out.set(pcm, 44);
2086
+ return out;
2087
+ }
2088
+ const shapeFor = (model) => /(^|\/)gpt-transcribe\b/i.test(model) ? "hints" : "single";
2089
+ /** The multipart fields besides the file, for one request shape. */
2090
+ function transcriptionFields(config, shape) {
2091
+ const fields = [["model", config.model], ["response_format", "json"]];
2092
+ if (shape === "hints") {
2093
+ for (const code of config.languages) fields.push(["languages[]", code]);
2094
+ for (const term of config.keywords) fields.push(["keywords[]", term]);
2095
+ return fields;
2096
+ }
2097
+ if (config.languages.length === 1) fields.push(["language", config.languages[0].split("-")[0]]);
2098
+ if (config.keywords.length) {
2099
+ let prompt = "";
2100
+ for (const term of config.keywords) {
2101
+ const next = prompt ? `${prompt}, ${term}` : term;
2102
+ if (next.length > LEGACY_PROMPT_CHARS) break;
2103
+ prompt = next;
2104
+ }
2105
+ fields.push(["prompt", prompt]);
2106
+ }
2107
+ return fields;
2108
+ }
2109
+ var DictationError = class extends Error {
2110
+ status;
2111
+ constructor(message, status) {
2112
+ super(message);
2113
+ this.status = status;
2114
+ }
2115
+ };
2116
+ async function send(config, file, shape, fetchImpl, signal) {
2117
+ const form = new FormData();
2118
+ form.append("file", file, "dictation.wav");
2119
+ for (const [name, value] of transcriptionFields(config, shape)) form.append(name, value);
2120
+ let response;
2121
+ try {
2122
+ response = await fetchImpl(config.baseUrl + "/audio/transcriptions", {
2123
+ method: "POST",
2124
+ headers: { authorization: `Bearer ${config.apiKey}` },
2125
+ body: form,
2126
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)]) : AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
2127
+ });
2128
+ } catch (error) {
2129
+ const timeout = error.name === "TimeoutError";
2130
+ throw new DictationError(timeout ? "The transcription service did not answer in time" : `Could not reach the transcription service: ${error.message}`.slice(0, 300), timeout ? 504 : 502);
2131
+ }
2132
+ const body = await response.text();
2133
+ let data = {};
2134
+ try {
2135
+ data = JSON.parse(body);
2136
+ } catch {}
2137
+ const detail = typeof data.error === "string" ? data.error : typeof data.error?.message === "string" ? data.error.message : response.ok ? "" : body;
2138
+ return {
2139
+ ok: response.ok,
2140
+ status: response.status,
2141
+ text: typeof data.text === "string" ? data.text : void 0,
2142
+ detail: String(detail)
2143
+ };
2144
+ }
2145
+ async function transcribe(config, pcm, rate, fetchImpl = fetch, signal) {
2146
+ const file = new Blob([wav(pcm, rate)], { type: "audio/wav" });
2147
+ const shape = shapeFor(config.model);
2148
+ let result = await send(config, file, shape, fetchImpl, signal);
2149
+ const hinted = config.languages.length > 0 || config.keywords.length > 0;
2150
+ if (!result.ok && result.status === 400 && hinted && /language|keyword|prompt/i.test(result.detail)) result = await send(config, file, shape === "hints" ? "single" : "hints", fetchImpl, signal).then((retry) => retry.ok ? retry : result);
2151
+ if (!result.ok) {
2152
+ const scrubbed = result.detail.split(config.apiKey).join("…").replace(/\s+/g, " ").trim().slice(0, 200);
2153
+ throw new DictationError(`Transcription failed (${result.status})${scrubbed ? ": " + scrubbed : ""}`, 502);
2154
+ }
2155
+ if (result.text === void 0) throw new DictationError("The transcription service returned no text", 502);
2156
+ return result.text.trim();
2157
+ }
2158
+ // src/server/dictation-stream.ts
2159
+ const DICTATION_RATE = 24e3;
2160
+ const BYTES_PER_SECOND = DICTATION_RATE * 2;
2161
+ const MAX_BYTES = BYTES_PER_SECOND * 300;
2162
+ const MAX_BUFFERED = BYTES_PER_SECOND * 10;
2163
+ /** One-use, short-lived tickets keep credentials out of WebSocket URLs. */
2164
+ var DictationStreams = class {
2165
+ tickets = /* @__PURE__ */ new Map();
2166
+ sessions = /* @__PURE__ */ new Set();
2167
+ unsupported = /* @__PURE__ */ new Map();
2168
+ wss = new WebSocketServer({
2169
+ noServer: true,
2170
+ maxPayload: BYTES_PER_SECOND,
2171
+ perMessageDeflate: false
2172
+ });
2173
+ fetchImpl;
2174
+ log;
2175
+ constructor(fetchImpl = fetch, log = () => {}) {
2176
+ this.fetchImpl = fetchImpl;
2177
+ this.log = log;
2178
+ }
2179
+ issue(config, valid) {
2180
+ for (const [key, ticket] of this.tickets) if (ticket.expires < Date.now()) this.tickets.delete(key);
2181
+ if (this.tickets.size + this.sessions.size >= 16) throw new Error("Too many voice sessions. Try again shortly.");
2182
+ const ticket = randomUUID();
2183
+ this.tickets.set(ticket, {
2184
+ config,
2185
+ valid,
2186
+ expires: Date.now() + 3e4
2187
+ });
2188
+ return {
2189
+ ticket,
2190
+ rate: DICTATION_RATE
2191
+ };
2192
+ }
2193
+ attach(server) {
2194
+ server.on("upgrade", (request, socket, head) => {
2195
+ const url = new URL(request.url ?? "/", "http://localhost");
2196
+ if (url.pathname !== "/api/dictation/stream") {
2197
+ socket.destroy();
2198
+ return;
2199
+ }
2200
+ const key = url.searchParams.get("ticket") ?? "";
2201
+ const ticket = this.tickets.get(key);
2202
+ this.tickets.delete(key);
2203
+ if (!ticket || ticket.expires < Date.now() || !ticket.valid()) {
2204
+ socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
2205
+ return;
2206
+ }
2207
+ this.wss.handleUpgrade(request, socket, head, (client) => {
2208
+ const cacheKey = ticket.config.baseUrl + ":" + ticket.config.model;
2209
+ const stream = new DictationStream(client, ticket.config, ticket.valid, {
2210
+ fetch: this.fetchImpl,
2211
+ skipRealtime: (this.unsupported.get(cacheKey) ?? 0) > Date.now(),
2212
+ unsupported: () => {
2213
+ for (const [key, until] of this.unsupported) if (until < Date.now()) this.unsupported.delete(key);
2214
+ this.unsupported.set(cacheKey, Date.now() + 3e5);
2215
+ },
2216
+ closed: () => this.sessions.delete(stream),
2217
+ log: this.log
2218
+ });
2219
+ this.sessions.add(stream);
2220
+ stream.start();
2221
+ });
2222
+ });
2223
+ }
2224
+ close() {
2225
+ for (const stream of this.sessions) stream.close();
2226
+ this.tickets.clear();
2227
+ this.unsupported.clear();
2228
+ this.wss.close();
2229
+ }
2230
+ };
2231
+ /** Audio flows while recording. Realtime is preferred; file-only services transcribe phrases. */
2232
+ var DictationStream = class {
2233
+ upstream;
2234
+ mode = "connecting";
2235
+ closed = false;
2236
+ finishing = false;
2237
+ totalBytes = 0;
2238
+ segmentBytes = 0;
2239
+ silenceBytes = 0;
2240
+ speech = false;
2241
+ chunks = [];
2242
+ segments = [];
2243
+ commits = [];
2244
+ items = /* @__PURE__ */ new Map();
2245
+ jobs = [];
2246
+ activeJobs = 0;
2247
+ abort = new AbortController();
2248
+ started = Date.now();
2249
+ stopped = 0;
2250
+ firstText = null;
2251
+ deadline;
2252
+ heartbeat;
2253
+ client;
2254
+ config;
2255
+ valid;
2256
+ options;
2257
+ constructor(client, config, valid, options) {
2258
+ this.client = client;
2259
+ this.config = config;
2260
+ this.valid = valid;
2261
+ this.options = options;
2262
+ this.heartbeat = setInterval(() => {
2263
+ if (!valid()) this.fail("Your session ended. Sign in again.");
2264
+ else if (Date.now() - this.started > 43e4) this.fail("Voice session timed out.");
2265
+ else if (client.readyState === WebSocket.OPEN) client.ping();
2266
+ }, 1e4);
2267
+ this.heartbeat.unref();
2268
+ client.on("message", (data, binary) => {
2269
+ if (this.closed) return;
2270
+ if (!valid()) {
2271
+ this.fail("Your session ended. Sign in again.");
2272
+ return;
2273
+ }
2274
+ try {
2275
+ if (binary) this.append(Buffer.from(data));
2276
+ else {
2277
+ const event = JSON.parse(data.toString());
2278
+ if (event.type === "stop") this.finish();
2279
+ else if (event.type === "cancel") this.close();
2280
+ else this.fail("Unknown voice command.");
2281
+ }
2282
+ } catch {
2283
+ this.fail("Invalid voice data.");
2284
+ }
2285
+ });
2286
+ client.on("error", () => this.close());
2287
+ client.on("close", () => this.close());
2288
+ }
2289
+ async start() {
2290
+ const realtimeModel = /^(gpt-transcribe|gpt-live-transcribe|gpt-4o(-mini)?-transcribe|whisper-1)$/.test(this.config.model);
2291
+ if (this.options.skipRealtime || !realtimeModel) {
2292
+ this.ready("segmented");
2293
+ return;
2294
+ }
2295
+ try {
2296
+ await this.connectRealtime();
2297
+ if (!this.closed) this.ready("realtime");
2298
+ } catch (error) {
2299
+ if (this.closed) return;
2300
+ if (error instanceof Unavailable) {
2301
+ this.options.unsupported();
2302
+ this.ready("segmented");
2303
+ } else this.fail(error.message);
2304
+ }
2305
+ }
2306
+ connectRealtime() {
2307
+ return new Promise((resolve, reject) => {
2308
+ const url = new URL(this.config.baseUrl + "/realtime");
2309
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
2310
+ url.searchParams.set("intent", "transcription");
2311
+ const ws = this.upstream = new WebSocket(url, {
2312
+ headers: { Authorization: `Bearer ${this.config.apiKey}` },
2313
+ handshakeTimeout: 4e3,
2314
+ maxPayload: 1048576
2315
+ });
2316
+ let settled = false;
2317
+ const finish = (error) => {
2318
+ if (settled) return;
2319
+ settled = true;
2320
+ clearTimeout(timeout);
2321
+ if (error) {
2322
+ this.upstream = void 0;
2323
+ ws.terminate();
2324
+ reject(error);
2325
+ } else resolve();
2326
+ };
2327
+ const timeout = setTimeout(() => finish(new Unavailable("Realtime connection timed out")), 5e3);
2328
+ ws.on("open", () => {
2329
+ const hints = /^(gpt-transcribe|gpt-live-transcribe)$/.test(this.config.model);
2330
+ const transcription = {
2331
+ model: this.config.model,
2332
+ ...hints ? {
2333
+ ...this.config.languages.length ? { languages: this.config.languages } : {},
2334
+ ...this.config.keywords.length ? { keywords: this.config.keywords } : {}
2335
+ } : {
2336
+ ...this.config.languages.length === 1 ? { language: this.config.languages[0].split("-")[0] } : {},
2337
+ ...this.config.keywords.length ? { prompt: this.config.keywords.join(", ").slice(0, 600) } : {}
2338
+ }
2339
+ };
2340
+ ws.send(JSON.stringify({
2341
+ type: "session.update",
2342
+ session: {
2343
+ type: "transcription",
2344
+ audio: { input: {
2345
+ format: {
2346
+ type: "audio/pcm",
2347
+ rate: DICTATION_RATE
2348
+ },
2349
+ transcription,
2350
+ turn_detection: null
2351
+ } }
2352
+ }
2353
+ }));
2354
+ });
2355
+ ws.on("unexpected-response", (_, response) => {
2356
+ const status = response.statusCode;
2357
+ response.destroy();
2358
+ finish([
2359
+ 400,
2360
+ 404,
2361
+ 405,
2362
+ 501
2363
+ ].includes(status ?? 0) ? new Unavailable("Realtime is not supported") : /* @__PURE__ */ new Error(`Voice connection failed (${status}). Check the transcription service settings.`));
2364
+ });
2365
+ ws.on("message", (data) => {
2366
+ let event;
2367
+ try {
2368
+ event = JSON.parse(data.toString());
2369
+ } catch {
2370
+ finish(/* @__PURE__ */ new Error("Invalid transcription service response."));
2371
+ return;
2372
+ }
2373
+ if (!settled) {
2374
+ if (event.type === "session.updated") finish();
2375
+ else if (event.type === "error") finish(new Unavailable("Realtime configuration is not supported"));
2376
+ } else if (this.mode === "realtime" && !this.closed) this.upstreamEvent(event);
2377
+ });
2378
+ ws.on("error", () => {
2379
+ if (!settled) finish(new Unavailable("Realtime is unavailable"));
2380
+ else if (this.mode === "realtime") this.fail("Voice connection interrupted. Please try again.");
2381
+ });
2382
+ ws.on("close", () => {
2383
+ if (!settled) finish(new Unavailable("Realtime is unavailable"));
2384
+ else if (this.mode === "realtime" && !this.closed) this.fail("Voice connection interrupted. Please try again.");
2385
+ });
2386
+ });
2387
+ }
2388
+ ready(mode) {
2389
+ if (this.closed) return;
2390
+ if (mode === "segmented" && this.config.model === "gpt-live-transcribe") {
2391
+ this.fail("This service does not support realtime transcription. Choose gpt-transcribe or a realtime-compatible service.");
2392
+ return;
2393
+ }
2394
+ this.mode = mode;
2395
+ this.send({
2396
+ type: "ready",
2397
+ mode,
2398
+ rate: DICTATION_RATE
2399
+ });
2400
+ }
2401
+ append(audio) {
2402
+ if (this.finishing || this.mode === "connecting") {
2403
+ this.fail("Voice session is not recording.");
2404
+ return;
2405
+ }
2406
+ if (!audio.length || audio.length % 2 || audio.length > BYTES_PER_SECOND) {
2407
+ this.fail("Invalid audio chunk.");
2408
+ return;
2409
+ }
2410
+ this.totalBytes += audio.length;
2411
+ if (this.totalBytes > MAX_BYTES) {
2412
+ this.fail("Recording exceeds five minutes.");
2413
+ return;
2414
+ }
2415
+ this.chunks.push(audio);
2416
+ this.segmentBytes += audio.length;
2417
+ let energy = 0;
2418
+ for (let i = 0; i < audio.length; i += 2) {
2419
+ const sample = audio.readInt16LE(i) / 32768;
2420
+ energy += sample * sample;
2421
+ }
2422
+ if (Math.sqrt(energy / (audio.length / 2)) >= .006) {
2423
+ this.speech = true;
2424
+ this.silenceBytes = 0;
2425
+ } else this.silenceBytes += audio.length;
2426
+ if (this.mode === "realtime") {
2427
+ if (!this.upstream || this.upstream.bufferedAmount > MAX_BUFFERED) {
2428
+ this.fail("Voice upload cannot keep up with recording.");
2429
+ return;
2430
+ }
2431
+ this.upstream.send(JSON.stringify({
2432
+ type: "input_audio_buffer.append",
2433
+ audio: audio.toString("base64")
2434
+ }));
2435
+ }
2436
+ if (this.speech && (this.segmentBytes >= BYTES_PER_SECOND && this.silenceBytes >= BYTES_PER_SECOND * .7 || this.segmentBytes >= BYTES_PER_SECOND * 30)) this.commit();
2437
+ else if (!this.speech && this.segmentBytes >= BYTES_PER_SECOND * 2) this.clearAudio();
2438
+ }
2439
+ clearAudio() {
2440
+ this.chunks = [];
2441
+ this.segmentBytes = this.silenceBytes = 0;
2442
+ this.speech = false;
2443
+ if (this.mode === "realtime") this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.clear" }));
2444
+ }
2445
+ commit() {
2446
+ if (!this.segmentBytes) return;
2447
+ const segment = {
2448
+ text: "",
2449
+ done: false
2450
+ };
2451
+ this.segments.push(segment);
2452
+ if (this.mode === "realtime") {
2453
+ if (this.segmentBytes < BYTES_PER_SECOND / 10) this.upstream?.send(JSON.stringify({
2454
+ type: "input_audio_buffer.append",
2455
+ audio: Buffer.alloc(BYTES_PER_SECOND / 10 - this.segmentBytes).toString("base64")
2456
+ }));
2457
+ this.commits.push(segment);
2458
+ this.upstream?.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
2459
+ } else {
2460
+ this.jobs.push({
2461
+ audio: Buffer.concat(this.chunks),
2462
+ segment
2463
+ });
2464
+ this.pump();
2465
+ }
2466
+ this.chunks = [];
2467
+ this.segmentBytes = this.silenceBytes = 0;
2468
+ this.speech = false;
2469
+ }
2470
+ pump() {
2471
+ while (!this.closed && this.activeJobs < 2 && this.jobs.length) {
2472
+ const job = this.jobs.shift();
2473
+ this.activeJobs++;
2474
+ transcribe(this.config, job.audio, DICTATION_RATE, this.options.fetch, this.abort.signal).then((text) => {
2475
+ if (this.closed) return;
2476
+ job.segment.text = text;
2477
+ job.segment.done = true;
2478
+ this.publish();
2479
+ }).catch(() => {
2480
+ if (!this.closed) this.fail("Transcription failed. Please try again or check the service settings.");
2481
+ }).finally(() => {
2482
+ this.activeJobs--;
2483
+ this.pump();
2484
+ });
2485
+ }
2486
+ }
2487
+ upstreamEvent(event) {
2488
+ const id = typeof event.item_id === "string" ? event.item_id : "";
2489
+ if (event.type === "input_audio_buffer.committed") {
2490
+ const segment = this.commits.shift();
2491
+ if (!segment || !id) {
2492
+ this.fail("Unexpected transcription sequence.");
2493
+ return;
2494
+ }
2495
+ const draft = this.items.get(id);
2496
+ if (draft) {
2497
+ segment.text = draft.text;
2498
+ segment.done = draft.done;
2499
+ }
2500
+ segment.id = id;
2501
+ this.items.set(id, segment);
2502
+ this.publish();
2503
+ } else if (event.type === "conversation.item.input_audio_transcription.delta" || event.type === "conversation.item.input_audio_transcription.completed") {
2504
+ let segment = this.items.get(id);
2505
+ if (!segment) {
2506
+ segment = {
2507
+ text: "",
2508
+ done: false,
2509
+ id
2510
+ };
2511
+ this.items.set(id, segment);
2512
+ }
2513
+ if (event.type.endsWith(".completed")) {
2514
+ segment.text = String(event.transcript ?? "");
2515
+ segment.done = true;
2516
+ } else if (!segment.done) segment.text += String(event.delta ?? "");
2517
+ this.publish();
2518
+ } else if (event.type === "error" || event.type === "conversation.item.input_audio_transcription.failed") this.fail("The transcription service could not process this recording.");
2519
+ }
2520
+ text() {
2521
+ const parts = [];
2522
+ for (const segment of this.segments) {
2523
+ if (segment.text.trim()) parts.push(segment.text.trim());
2524
+ if (!segment.done) break;
2525
+ }
2526
+ if (this.mode === "realtime" && this.config.model === "gpt-live-transcribe") {
2527
+ for (const segment of this.items.values()) if (!this.segments.includes(segment) && segment.text.trim()) parts.push(segment.text.trim());
2528
+ }
2529
+ return parts.join(" ");
2530
+ }
2531
+ publish() {
2532
+ if (this.closed) return;
2533
+ const text = this.text();
2534
+ if (text && this.firstText === null) this.firstText = Date.now() - this.started;
2535
+ if (this.finishing && this.segments.every((s) => s.done)) {
2536
+ this.options.log({
2537
+ mode: this.mode,
2538
+ audioMs: this.totalBytes / BYTES_PER_SECOND * 1e3,
2539
+ firstTextMs: this.firstText,
2540
+ finishMs: Date.now() - this.stopped
2541
+ });
2542
+ this.send({
2543
+ type: "done",
2544
+ text
2545
+ });
2546
+ this.close();
2547
+ } else this.send({
2548
+ type: "partial",
2549
+ text
2550
+ });
2551
+ }
2552
+ finish() {
2553
+ if (this.finishing || this.closed) return;
2554
+ if (this.mode === "connecting") {
2555
+ this.fail("Voice session is still connecting.");
2556
+ return;
2557
+ }
2558
+ this.finishing = true;
2559
+ this.stopped = Date.now();
2560
+ if (this.speech) this.commit();
2561
+ else this.clearAudio();
2562
+ this.deadline = setTimeout(() => this.fail("Timed out waiting for transcription."), 12e4);
2563
+ this.publish();
2564
+ }
2565
+ send(event) {
2566
+ if (this.client.readyState === WebSocket.OPEN) {
2567
+ if (this.client.bufferedAmount > 1048576) {
2568
+ this.close();
2569
+ return;
2570
+ }
2571
+ this.client.send(JSON.stringify(event));
2572
+ }
2573
+ }
2574
+ fail(message) {
2575
+ if (this.closed) return;
2576
+ this.send({
2577
+ type: "error",
2578
+ message,
2579
+ text: this.text()
2580
+ });
2581
+ this.close();
2582
+ }
2583
+ close() {
2584
+ if (this.closed) return;
2585
+ this.closed = true;
2586
+ clearInterval(this.heartbeat);
2587
+ clearTimeout(this.deadline);
2588
+ this.abort.abort();
2589
+ this.upstream?.terminate();
2590
+ this.chunks = [];
2591
+ this.jobs = [];
2592
+ this.client.close();
2593
+ this.options.closed();
2594
+ }
2595
+ };
2596
+ var Unavailable = class extends Error {};
2597
+ // src/server/app.ts
2598
+ const AGENT_FLUSH_MS = 100;
2599
+ const HOST_FLUSH_MS = 100;
2600
+ function parseJson(text) {
2601
+ try {
2602
+ return JSON.parse(text ?? "null");
2603
+ } catch {
2604
+ return null;
2605
+ }
2606
+ }
2607
+ const CARD_DESCRIPTION_MAX = 2e4;
2608
+ const CARD_COMMENT_MAX = 5e3;
2609
+ const cardComment = z.object({
2610
+ id: z.string().uuid(),
2611
+ text: z.string().trim().min(1).max(CARD_COMMENT_MAX),
2612
+ at: z.number().int().nonnegative()
2613
+ });
2614
+ const card = z.object({
2615
+ id: z.string().uuid(),
2616
+ title: z.string().min(1).max(300),
2617
+ column: z.enum([
2618
+ "Todo",
2619
+ "Doing",
2620
+ "Done"
2621
+ ]),
2622
+ hostId: z.string().nullable(),
2623
+ agentId: z.string().nullable(),
2624
+ description: z.string().max(CARD_DESCRIPTION_MAX).optional(),
2625
+ comments: z.array(cardComment).max(200).optional(),
2626
+ createdAt: z.number().int().nonnegative().optional(),
2627
+ updatedAt: z.number().int().nonnegative().optional()
2628
+ }).refine((c) => c.hostId === null === (c.agentId === null));
2629
+ /** One card's editable fields; omitted fields are left as they are. */
2630
+ const cardPatch = z.object({
2631
+ title: z.string().trim().min(1).max(300),
2632
+ column: z.enum([
2633
+ "Todo",
2634
+ "Doing",
2635
+ "Done"
2636
+ ]),
2637
+ description: z.string().max(CARD_DESCRIPTION_MAX),
2638
+ link: z.object({
2639
+ hostId: z.string(),
2640
+ agentId: z.string()
2641
+ }).nullable()
2642
+ }).partial();
2643
+ const SESSION_COOKIE = "lp_session";
2644
+ /** Cookie-authenticated writes must carry this header; a cross-site form or image cannot. */
2645
+ const CSRF_HEADER = "x-litepaseo";
2646
+ const PUBLIC_API = /* @__PURE__ */ new Set(["/api/auth", "/api/login"]);
2647
+ /**
2648
+ * Requests that arrived through a tunnel or reverse proxy. A bearer token is never accepted from
2649
+ * them: over the network, only the browser sign-in (with its rate limits and optional
2650
+ * authenticator code) admits anyone.
2651
+ */
2652
+ const proxied = (c) => [
2653
+ "cf-connecting-ip",
2654
+ "x-forwarded-for",
2655
+ "x-real-ip",
2656
+ "forwarded"
2657
+ ].some((name) => c.req.header(name) !== void 0);
2658
+ /** `token` is the access token, or a function returning the current one (it can be rotated). */
2659
+ function createApp(store, hosts, token, webRoot, options = {}) {
2660
+ const app = new Hono();
2661
+ const auth = new Auth(store, token);
2662
+ const dictationStreams = new DictationStreams(options.fetch, (metrics) => console.info(JSON.stringify({
2663
+ event: "dictation_complete",
2664
+ ...metrics
2665
+ })));
2666
+ const attachments = new Attachments();
2667
+ const projectIcons = new IconCache();
2668
+ const viewers = /* @__PURE__ */ new Map();
2669
+ const notifier = new Notifier({
2670
+ store,
2671
+ sender: options.pushSender ?? webPushSender(store, options.pushSubject ?? "mailto:litepaseo@example.com"),
2672
+ isViewing: (key, sessionId) => (viewers.get(key)?.get(sessionId) ?? 0) > 0,
2673
+ hostLabel: (id) => hosts.label(id) || store.hosts().find((h) => h.id === id)?.label || ""
2674
+ });
2675
+ hosts.onTransition((previous, next) => notifier.transition(previous, next));
2676
+ const usage = new UsageService(hosts);
2677
+ store.pruneSessions(Date.now());
2678
+ const secure = (c) => c.req.header("x-forwarded-proto") === "https" || c.req.url.startsWith("https:");
2679
+ const clientId = (c) => c.req.header("cf-connecting-ip") ?? c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "direct";
2680
+ app.use("*", async (c, next) => {
2681
+ await next();
2682
+ c.header("X-Content-Type-Options", "nosniff");
2683
+ c.header("Referrer-Policy", "no-referrer");
2684
+ c.header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self'; manifest-src 'self'; frame-ancestors 'none'");
2685
+ });
2686
+ app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path === "/api/dictation/transcribe" ? MAX_DICTATION_BYTES : 1048576 })(c, next));
2687
+ app.use("/api/*", async (c, next) => {
2688
+ c.header("Cache-Control", "no-store");
2689
+ c.set("bearer", null);
2690
+ const bearer = /^Bearer (.+)$/.exec(c.req.header("authorization") ?? "")?.[1];
2691
+ if (bearer && !PUBLIC_API.has(c.req.path) && !auth.totpEnabled() && !proxied(c)) {
2692
+ const result = auth.bearer(bearer, clientId(c));
2693
+ if (!result.ok) {
2694
+ if (result.retryAfter) c.header("Retry-After", String(result.retryAfter));
2695
+ return c.json({ error: result.status === 429 ? "Too many attempts. Try again later." : "Sign in required" }, result.status);
2696
+ }
2697
+ c.set("session", null);
2698
+ c.set("bearer", bearer);
2699
+ return next();
2700
+ }
2701
+ const secret = getCookie(c, SESSION_COOKIE);
2702
+ const found = auth.authenticate(secret);
2703
+ const session = found?.session ?? null;
2704
+ if (found?.renewed && secret && c.req.path !== "/api/login" && c.req.path !== "/api/logout") setCookie(c, SESSION_COOKIE, secret, {
2705
+ httpOnly: true,
2706
+ secure: secure(c),
2707
+ sameSite: "Strict",
2708
+ path: "/",
2709
+ maxAge: Math.floor(SESSION_TTL_MS / 1e3)
2710
+ });
2711
+ if (PUBLIC_API.has(c.req.path)) {
2712
+ c.set("session", session);
2713
+ return next();
2714
+ }
2715
+ if (!session) return c.json({ error: "Sign in required" }, 401);
2716
+ if (!["GET", "HEAD"].includes(c.req.method) && c.req.header(CSRF_HEADER) !== "1") return c.json({ error: "Missing request header" }, 403);
2717
+ c.set("session", session);
2718
+ await next();
2719
+ });
2720
+ app.get("/api/auth", (c) => c.json({
2721
+ authenticated: !!c.get("session"),
2722
+ totp: auth.totpEnabled()
2723
+ }));
2724
+ app.post("/api/login", async (c) => {
2725
+ const input = z.object({
2726
+ token: z.string().min(1).max(200).optional(),
2727
+ code: z.string().regex(/^\d{6}$/).optional()
2728
+ }).refine((x) => !!x.token || !!x.code).parse(await c.req.json());
2729
+ const userAgent = c.req.header("user-agent") ?? "";
2730
+ const label = (/iPhone|iPad/.test(userAgent) ? "iOS" : /Android/.test(userAgent) ? "Android" : /Mac OS/.test(userAgent) ? "macOS" : /Windows/.test(userAgent) ? "Windows" : /Linux/.test(userAgent) ? "Linux" : "Browser") + (/Edg\//.test(userAgent) ? " · Edge" : /Chrome\//.test(userAgent) ? " · Chrome" : /Firefox\//.test(userAgent) ? " · Firefox" : /Safari\//.test(userAgent) ? " · Safari" : "");
2731
+ const result = auth.login(input, clientId(c), label);
2732
+ if (!result.ok) {
2733
+ if (result.retryAfter) c.header("Retry-After", String(result.retryAfter));
2734
+ return c.json({ error: result.status === 429 ? "Too many attempts. Try again later." : "That did not match." }, result.status);
2735
+ }
2736
+ setCookie(c, SESSION_COOKIE, result.secret, {
2737
+ httpOnly: true,
2738
+ secure: secure(c),
2739
+ sameSite: "Strict",
2740
+ path: "/",
2741
+ maxAge: SESSION_TTL_MS / 1e3
2742
+ });
2743
+ return c.json({ ok: true });
2744
+ });
2745
+ app.post("/api/logout", (c) => {
2746
+ const session = c.get("session");
2747
+ if (session) {
2748
+ auth.revoke(session.id);
2749
+ attachments.clearOwner(session.id);
2750
+ }
2751
+ deleteCookie(c, SESSION_COOKIE, { path: "/" });
2752
+ return c.json({ ok: true });
2753
+ });
2754
+ app.get("/api/sessions", (c) => c.json(store.sessions().map((s) => ({
2755
+ id: s.id,
2756
+ label: s.label,
2757
+ created: s.created,
2758
+ lastSeen: s.lastSeen,
2759
+ current: s.id === c.get("session")?.id
2760
+ }))));
2761
+ app.delete("/api/sessions/:id", (c) => {
2762
+ auth.revoke(c.req.param("id"));
2763
+ if (c.req.param("id") === c.get("session")?.id) deleteCookie(c, SESSION_COOKIE, { path: "/" });
2764
+ return c.json({ ok: true });
2765
+ });
2766
+ app.post("/api/sessions/revoke-all", (c) => {
2767
+ auth.revoke();
2768
+ deleteCookie(c, SESSION_COOKIE, { path: "/" });
2769
+ return c.json({ ok: true });
2770
+ });
2771
+ const requireSession = (session) => {
2772
+ if (!session) throw new z.ZodError([{
2773
+ code: "custom",
2774
+ path: [],
2775
+ message: "A browser session is required",
2776
+ input: null
2777
+ }]);
2778
+ return session;
2779
+ };
2780
+ app.post("/api/totp/setup", async (c) => {
2781
+ const session = requireSession(c.get("session"));
2782
+ if (auth.totpEnabled()) return c.json({ error: "Disable the current authenticator before replacing it." }, 409);
2783
+ const { secret, uri } = auth.beginTotp(session.id);
2784
+ const qr = await QRCode.toString(uri, {
2785
+ type: "svg",
2786
+ margin: 1,
2787
+ errorCorrectionLevel: "M"
2788
+ });
2789
+ return c.json({
2790
+ secret,
2791
+ uri,
2792
+ qr: "data:image/svg+xml;base64," + Buffer.from(qr).toString("base64")
2793
+ });
2794
+ });
2795
+ app.post("/api/totp/confirm", async (c) => {
2796
+ const session = requireSession(c.get("session"));
2797
+ const { code } = z.object({ code: z.string().regex(/^\d{6}$/) }).parse(await c.req.json());
2798
+ if (!auth.confirmTotp(session.id, code)) return c.json({ error: "That code did not match. Try the next one." }, 400);
2799
+ return c.json({ ok: true });
2800
+ });
2801
+ app.post("/api/totp/disable", async (c) => {
2802
+ const { code } = z.object({ code: z.string().regex(/^\d{6}$/) }).parse(await c.req.json());
2803
+ if (!auth.disableTotp(code)) return c.json({ error: "That code did not match." }, 400);
2804
+ return c.json({ ok: true });
2805
+ });
2806
+ const prefsSchema = z.object({
2807
+ attention: z.boolean(),
2808
+ turns: z.boolean()
2809
+ });
2810
+ app.get("/api/push/key", (c) => c.json({ publicKey: vapidKeys(store).publicKey }));
2811
+ app.post("/api/push/subscribe", async (c) => {
2812
+ const session = requireSession(c.get("session"));
2813
+ const input = z.object({
2814
+ subscription: z.object({
2815
+ endpoint: z.string().url().max(2e3).refine((u) => u.startsWith("https://")),
2816
+ keys: z.object({
2817
+ p256dh: z.string().min(1).max(200),
2818
+ auth: z.string().min(1).max(100)
2819
+ })
2820
+ }),
2821
+ prefs: prefsSchema
2822
+ }).parse(await c.req.json());
2823
+ store.savePushSubscription({
2824
+ endpoint: input.subscription.endpoint,
2825
+ sessionId: session.id,
2826
+ p256dh: input.subscription.keys.p256dh,
2827
+ auth: input.subscription.keys.auth,
2828
+ prefs: input.prefs,
2829
+ created: Date.now()
2830
+ });
2831
+ return c.json({ ok: true });
2832
+ });
2833
+ app.post("/api/push/status", async (c) => {
2834
+ const { endpoint } = z.object({ endpoint: z.string().max(2e3) }).parse(await c.req.json());
2835
+ const found = store.pushSubscriptions().find((s) => s.endpoint === endpoint);
2836
+ return c.json(found ? {
2837
+ subscribed: true,
2838
+ prefs: found.prefs
2839
+ } : { subscribed: false });
2840
+ });
2841
+ app.post("/api/push/unsubscribe", async (c) => {
2842
+ const { endpoint } = z.object({ endpoint: z.string().max(2e3) }).parse(await c.req.json());
2843
+ store.removePushSubscription(endpoint);
2844
+ return c.json({ ok: true });
2845
+ });
2846
+ app.post("/api/push/test", async (c) => {
2847
+ const session = requireSession(c.get("session"));
2848
+ return c.json({ sent: await notifier.test(session.id) });
2849
+ });
2850
+ app.onError((error, c) => {
2851
+ if (error instanceof UnknownHostError) return c.json({ error: "Unknown host" }, 404);
2852
+ if (error instanceof z.ZodError) return c.json({
2853
+ error: "Invalid request",
2854
+ detail: error.issues
2855
+ }, 400);
2856
+ const requestId = randomUUID();
2857
+ const failure = error;
2858
+ const cause = failure.cause instanceof Error ? failure.cause : null;
2859
+ console.error(JSON.stringify({
2860
+ event: "api_operation_failed",
2861
+ requestId,
2862
+ method: c.req.method,
2863
+ path: c.req.path,
2864
+ route: c.req.routePath,
2865
+ error: failure.name,
2866
+ ...typeof failure.code === "string" ? { code: failure.code } : {},
2867
+ message: String(failure.message ?? "").slice(0, 500),
2868
+ ...cause ? { cause: `${cause.name}: ${cause.message}`.slice(0, 300) } : {},
2869
+ at: failure.stack?.split("\n").slice(1, 4).map((line) => line.trim())
2870
+ }));
2871
+ return c.json({
2872
+ error: "Operation failed; refresh state before retrying",
2873
+ requestId
2874
+ }, 502);
2875
+ });
2876
+ app.get("/api/health", (c) => c.json({
2877
+ ok: true,
2878
+ version: VERSION,
2879
+ waiting: notifier.waitingCount
2880
+ }));
2881
+ const hostStates = () => store.hosts().map((h) => ({
2882
+ id: h.id,
2883
+ label: h.label,
2884
+ state: hosts.state(h.id),
2885
+ diagnostic: hosts.diagnostic(h.id)
2886
+ }));
2887
+ app.get("/api/hosts", (c) => c.json(hostStates()));
2888
+ const directoryStreams = /* @__PURE__ */ new Set();
2889
+ let agentFlush;
2890
+ let hostFlush;
2891
+ /** Set on shutdown: closing the hosts still reports changes, but the store is about to close. */
2892
+ let disposed = false;
2893
+ const deliverAgents = (stream) => {
2894
+ deliverWorkspaces(stream);
2895
+ const { agents } = hosts;
2896
+ const changes = agents.changesSince(stream.last);
2897
+ if (changes === null) stream.send({
2898
+ type: "snapshot",
2899
+ generation: agents.generation,
2900
+ seq: agents.seq,
2901
+ agents: agents.snapshot()
2902
+ });
2903
+ else if (changes.length) stream.send({
2904
+ type: "changes",
2905
+ generation: agents.generation,
2906
+ seq: agents.seq,
2907
+ changes
2908
+ });
2909
+ stream.last = agents.seq;
2910
+ };
2911
+ const deliverWorkspaces = (stream) => {
2912
+ const { workspaces } = hosts;
2913
+ const changes = workspaces.changesSince(stream.lastWorkspaces);
2914
+ if (changes === null) stream.send({
2915
+ type: "workspaces-snapshot",
2916
+ generation: workspaces.generation,
2917
+ seq: workspaces.seq,
2918
+ workspaces: workspaces.snapshot()
2919
+ });
2920
+ else if (changes.length) stream.send({
2921
+ type: "workspaces-changes",
2922
+ generation: workspaces.generation,
2923
+ seq: workspaces.seq,
2924
+ changes
2925
+ });
2926
+ stream.lastWorkspaces = workspaces.seq;
2927
+ };
2928
+ hosts.onAgentsChanged(() => {
2929
+ if (disposed || agentFlush || !directoryStreams.size) return;
2930
+ agentFlush = setTimeout(() => {
2931
+ agentFlush = void 0;
2932
+ for (const stream of directoryStreams) deliverAgents(stream);
2933
+ }, AGENT_FLUSH_MS);
2934
+ });
2935
+ hosts.onHostsChanged(() => {
2936
+ if (disposed || hostFlush || !directoryStreams.size) return;
2937
+ hostFlush = setTimeout(() => {
2938
+ hostFlush = void 0;
2939
+ const message = {
2940
+ type: "hosts",
2941
+ hosts: hostStates()
2942
+ };
2943
+ for (const stream of directoryStreams) stream.send(message);
2944
+ }, HOST_FLUSH_MS);
2945
+ });
2946
+ /** Re-checked on heartbeat: a revoked session, or a rotated token, loses its open streams. */
2947
+ const streamValidity = (c) => {
2948
+ const session = c.get("session"), bearer = c.get("bearer");
2949
+ if (session) return () => auth.stillValid(session.id);
2950
+ return () => !!bearer && !auth.totpEnabled() && auth.checkToken(bearer);
2951
+ };
2952
+ app.get("/api/stream", (c) => {
2953
+ const since = Number(c.req.query("since"));
2954
+ const resumable = c.req.query("generation") === hosts.agents.generation && Number.isInteger(since);
2955
+ const wsince = Number(c.req.query("wsince"));
2956
+ const wresumable = c.req.query("wgeneration") === hosts.workspaces.generation && Number.isInteger(wsince);
2957
+ return eventStream(c.req.raw.signal, (send) => {
2958
+ const stream = {
2959
+ last: resumable ? since : -1,
2960
+ lastWorkspaces: wresumable ? wsince : -1,
2961
+ send
2962
+ };
2963
+ send({
2964
+ type: "hosts",
2965
+ hosts: hostStates()
2966
+ });
2967
+ deliverAgents(stream);
2968
+ directoryStreams.add(stream);
2969
+ return () => directoryStreams.delete(stream);
2970
+ }, streamValidity(c));
2971
+ });
2972
+ app.post("/api/hosts", async (c) => {
2973
+ const input = z.object({
2974
+ label: z.string().trim().min(1).max(80),
2975
+ connection: z.string().trim().min(1).max(16e3)
2976
+ }).parse(await c.req.json());
2977
+ parseHostTarget(input.connection);
2978
+ const host = store.addHost(input.label, input.connection);
2979
+ try {
2980
+ hosts.add(host);
2981
+ } catch (e) {
2982
+ store.removeHost(host.id);
2983
+ throw e;
2984
+ }
2985
+ return c.json({
2986
+ id: host.id,
2987
+ label: host.label
2988
+ }, 201);
2989
+ });
2990
+ app.delete("/api/hosts/:host", async (c) => {
2991
+ await hosts.remove(c.req.param("host"));
2992
+ store.removeHost(c.req.param("host"));
2993
+ return c.json({ ok: true });
2994
+ });
2995
+ /** Providers the host can start right now, read from the daemon's provider snapshot. */
2996
+ app.get("/api/hosts/:host/providers", async (c) => {
2997
+ const providers = (await hosts.get(c.req.param("host")).api.providers.snapshot()).entries.filter((entry) => entry.enabled !== false && entry.status !== "unavailable").map((entry) => ({
2998
+ id: entry.provider,
2999
+ label: entry.label ?? entry.provider,
3000
+ status: entry.status,
3001
+ ...entry.error ? { error: entry.error } : {},
3002
+ defaultModeId: entry.defaultModeId ?? null,
3003
+ modes: (entry.modes ?? []).map((m) => ({
3004
+ id: m.id,
3005
+ label: m.label,
3006
+ ...m.description ? { description: m.description } : {}
3007
+ })),
3008
+ models: (entry.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
3009
+ id: m.id,
3010
+ label: m.label,
3011
+ ...m.description ? { description: m.description } : {},
3012
+ isDefault: m.isDefault === true,
3013
+ thinking: (m.thinkingOptions ?? []).map((t) => ({
3014
+ id: t.id,
3015
+ label: t.label
3016
+ })),
3017
+ defaultThinkingId: m.defaultThinkingOptionId ?? null
3018
+ }))
3019
+ }));
3020
+ return c.json(providers);
3021
+ });
3022
+ /** Projects the daemon knows, as starting points for a new session. */
3023
+ app.get("/api/hosts/:host/projects", async (c) => {
3024
+ const projects = (await hosts.get(c.req.param("host")).api.projects.list()).projects.map((p) => ({
3025
+ key: p.projectKey ?? p.projectId,
3026
+ name: p.projectCustomName || p.projectDisplayName,
3027
+ rootPath: p.projectRootPath,
3028
+ kind: p.projectKind
3029
+ }));
3030
+ return c.json(projects);
3031
+ });
3032
+ /**
3033
+ * Starts a session. The browser's idempotency key travels to the daemon, so retrying after an
3034
+ * unknown outcome cannot create a second session.
3035
+ */
3036
+ app.post("/api/hosts/:host/agents", async (c) => {
3037
+ const input = z.object({
3038
+ idempotencyKey: z.string().uuid(),
3039
+ cwd: z.string().trim().min(1).max(4096),
3040
+ provider: z.string().trim().min(1).max(200).regex(/^[^/]+$/),
3041
+ model: z.string().trim().min(1).max(300).optional(),
3042
+ modeId: z.string().trim().min(1).max(200).optional(),
3043
+ thinkingOptionId: z.string().trim().min(1).max(200).optional(),
3044
+ prompt: z.string().max(1e5).optional(),
3045
+ worktreeBranch: z.string().trim().min(1).max(200).optional()
3046
+ }).parse(await c.req.json());
3047
+ const hostId = c.req.param("host");
3048
+ const { api } = hosts.get(hostId);
3049
+ try {
3050
+ let model = input.model;
3051
+ if (!model) {
3052
+ const models = (await api.providers.snapshot()).entries.find((p) => p.provider === input.provider && p.enabled !== false && p.status !== "unavailable")?.models?.filter((m) => m.isSelectable !== false) ?? [];
3053
+ model = models.find((m) => m.isDefault)?.id ?? models[0]?.id;
3054
+ if (!model) return c.json({ error: "No selectable model is available for this provider. Refresh providers and select a model." }, 400);
3055
+ }
3056
+ const agent = await api.agents.create({
3057
+ idempotencyKey: input.idempotencyKey,
3058
+ cwd: input.cwd,
3059
+ config: {
3060
+ provider: `${input.provider}/${model}`,
3061
+ ...input.modeId ? { modeId: input.modeId } : {},
3062
+ ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}
3063
+ },
3064
+ ...input.prompt?.trim() ? { prompt: input.prompt } : {},
3065
+ ...input.worktreeBranch ? { worktree: {
3066
+ mode: "branch-off",
3067
+ newBranch: input.worktreeBranch
3068
+ } } : {}
3069
+ });
3070
+ return c.json({
3071
+ id: agent.id,
3072
+ key: `${hostId}:${agent.id}`
3073
+ }, 201);
3074
+ } catch (error) {
3075
+ return c.json({ error: error instanceof Error && error.message ? `Could not start the session: ${error.message}` : "Creation outcome unknown. Check the session list before retrying." }, 502);
3076
+ }
3077
+ });
3078
+ app.get("/api/hosts/:host/agents/:agent/timeline/stream", (c) => {
3079
+ hosts.get(c.req.param("host"));
3080
+ return eventStream(c.req.raw.signal, (send) => {
3081
+ const sessionId = c.get("session")?.id;
3082
+ const key = `${c.req.param("host")}:${c.req.param("agent")}`;
3083
+ const stop = hosts.watchTimeline(c.req.param("host"), c.req.param("agent"), (ops) => send({
3084
+ type: "ops",
3085
+ ops
3086
+ }));
3087
+ if (sessionId) {
3088
+ let devices = viewers.get(key);
3089
+ if (!devices) viewers.set(key, devices = /* @__PURE__ */ new Map());
3090
+ devices.set(sessionId, (devices.get(sessionId) ?? 0) + 1);
3091
+ }
3092
+ return () => {
3093
+ stop();
3094
+ const devices = viewers.get(key);
3095
+ if (sessionId && devices) {
3096
+ const count = (devices.get(sessionId) ?? 1) - 1;
3097
+ if (count) devices.set(sessionId, count);
3098
+ else devices.delete(sessionId);
3099
+ if (!devices.size) viewers.delete(key);
3100
+ }
3101
+ };
3102
+ }, streamValidity(c));
3103
+ });
3104
+ /** Bounded history pages; the browser bookmarks boundaries for forward navigation. */
3105
+ app.get("/api/hosts/:host/agents/:agent/timeline", async (c) => {
3106
+ const cursor = z.object({
3107
+ epoch: z.string().min(1),
3108
+ seq: z.number().int().nonnegative()
3109
+ }).parse(parseJson(c.req.query("cursor")));
3110
+ const page = await hosts.get(c.req.param("host")).driver.fetchAgentTimeline(c.req.param("agent"), {
3111
+ direction: "before",
3112
+ cursor,
3113
+ limit: 100,
3114
+ projection: "projected",
3115
+ wholeTurns: false
3116
+ });
3117
+ return c.json({
3118
+ epoch: page.epoch,
3119
+ hasOlder: page.hasOlder,
3120
+ startCursor: page.startCursor,
3121
+ rows: page.entries.map((e) => ({
3122
+ seqStart: e.seqStart,
3123
+ seqEnd: e.seqEnd,
3124
+ timestamp: e.timestamp,
3125
+ provider: e.provider,
3126
+ ...e.turnId ? { turnId: e.turnId } : {},
3127
+ item: e.item
3128
+ }))
3129
+ });
3130
+ });
3131
+ /** The conversation's user prompts (seq + short preview), for the outline rail. */
3132
+ app.get("/api/hosts/:host/agents/:agent/timeline/prompts", async (c) => {
3133
+ const client = hosts.get(c.req.param("host"));
3134
+ try {
3135
+ const page = await client.driver.listAgentTimelinePrompts(c.req.param("agent"), { timeout: 15e3 });
3136
+ return c.json({
3137
+ epoch: page.epoch,
3138
+ prompts: page.prompts.map((p) => ({
3139
+ seq: p.seq,
3140
+ preview: p.preview.replace(/\s+/g, " ").trim().slice(0, 240)
3141
+ }))
3142
+ });
3143
+ } catch (error) {
3144
+ return c.json({ error: error.message || "Prompt index unavailable" }, 501);
3145
+ }
3146
+ });
3147
+ /**
3148
+ * Rewinds to just before a user message: the conversation, the tracked files, or both, as
3149
+ * the provider supports. Cannot be undone; the timeline is replaced (new epoch) on success.
3150
+ */
3151
+ app.post("/api/hosts/:host/agents/:agent/rewind", async (c) => {
3152
+ const { messageId, mode } = z.object({
3153
+ messageId: z.string().min(1).max(500),
3154
+ mode: z.enum([
3155
+ "conversation",
3156
+ "files",
3157
+ "both"
3158
+ ])
3159
+ }).parse(await c.req.json());
3160
+ const client = hosts.get(c.req.param("host"));
3161
+ const facts = client.directory.facts(c.req.param("agent"));
3162
+ if (!facts) return c.json({ error: "Unknown agent" }, 404);
3163
+ if (!rewindModes(facts.capabilities).includes(mode)) return c.json({ error: "This agent cannot rewind that way." }, 400);
3164
+ try {
3165
+ await client.driver.rewindAgent(c.req.param("agent"), messageId, mode);
3166
+ return c.json({ ok: true });
3167
+ } catch (error) {
3168
+ return c.json({ error: error.message || "Rewind failed" }, 502);
3169
+ }
3170
+ });
3171
+ /**
3172
+ * An image an agent referenced in a message (`![](file:///…)`, an absolute or workspace path).
3173
+ * Workspace files go through the daemon's file API; images the daemon materialized from
3174
+ * provider output live outside the workspace and are read from disk when the daemon is local.
3175
+ */
3176
+ app.get("/api/hosts/:host/agents/:agent/image", async (c) => {
3177
+ const hostId = c.req.param("host");
3178
+ const path = z.string().min(1).max(4096).refine((p) => !p.includes("\0")).parse(c.req.query("path"));
3179
+ const mime = imageMime(path);
3180
+ if (!mime) return c.json({ error: "Not an image" }, 415);
3181
+ const { driver } = hosts.get(hostId);
3182
+ const cwd = hosts.agents.get(`${hostId}:${c.req.param("agent")}`)?.cwd;
3183
+ let bytes = null;
3184
+ if (isMaterializedImagePath(path)) {
3185
+ const host = store.hosts().find((h) => h.id === hostId);
3186
+ if (host && isLocalConnection(host.connection)) bytes = await readMaterializedImage(path);
3187
+ } else if (cwd) try {
3188
+ const file = await driver.readFile(cwd, path, void 0, MAX_IMAGE_BYTES);
3189
+ if (file.size <= 16777216) bytes = file.bytes;
3190
+ } catch {
3191
+ bytes = null;
3192
+ }
3193
+ if (!bytes) return c.json({ error: "Image unavailable from this host" }, 404);
3194
+ return c.body(bytes, 200, {
3195
+ "Content-Type": mime,
3196
+ "Cache-Control": "private, max-age=86400",
3197
+ "Content-Disposition": "inline"
3198
+ });
3199
+ });
3200
+ /** A project's icon (favicon/logo the daemon found in its root), cached briefly per host. */
3201
+ app.get("/api/hosts/:host/project-icon", async (c) => {
3202
+ const hostId = c.req.param("host");
3203
+ const cwd = z.string().min(1).max(4096).parse(c.req.query("cwd"));
3204
+ const key = `${hostId}\n${cwd}`;
3205
+ let icon = projectIcons.get(key);
3206
+ if (icon === void 0) {
3207
+ try {
3208
+ const result = await hosts.get(hostId).driver.requestProjectIcon(cwd);
3209
+ icon = result.icon && /^image\/(png|jpeg|webp|gif|x-icon|vnd\.microsoft\.icon)$/.test(result.icon.mimeType) ? {
3210
+ data: Buffer.from(result.icon.data, "base64"),
3211
+ mimeType: result.icon.mimeType
3212
+ } : null;
3213
+ } catch (error) {
3214
+ if (error instanceof UnknownHostError) throw error;
3215
+ return c.json({ error: "Icon unavailable" }, 502);
3216
+ }
3217
+ projectIcons.set(key, icon);
3218
+ }
3219
+ if (!icon) return c.body(null, 204, { "Cache-Control": "private, max-age=600" });
3220
+ return c.body(icon.data, 200, {
3221
+ "Content-Type": icon.mimeType,
3222
+ "Cache-Control": "private, max-age=600"
3223
+ });
3224
+ });
3225
+ /** What the open agent can switch to. Modes/features come from the live directory (no round trip). */
3226
+ app.get("/api/hosts/:host/agents/:agent/config", async (c) => {
3227
+ const hostId = c.req.param("host");
3228
+ const client = hosts.get(hostId);
3229
+ const facts = client.directory.facts(c.req.param("agent"));
3230
+ if (!facts) return c.json({ error: "Unknown agent" }, 404);
3231
+ const options = {
3232
+ models: ((await client.api.providers.snapshot()).entries.find((p) => p.provider === facts.provider)?.models ?? []).filter((m) => m.isSelectable !== false).map((m) => ({
3233
+ id: m.id,
3234
+ label: m.label,
3235
+ thinking: (m.thinkingOptions ?? []).map((t) => ({
3236
+ id: t.id,
3237
+ label: t.label
3238
+ })),
3239
+ defaultThinkingId: m.defaultThinkingOptionId ?? null
3240
+ })),
3241
+ modes: facts.availableModes.map((m) => ({
3242
+ id: m.id,
3243
+ label: m.label,
3244
+ ...m.description ? { description: m.description } : {}
3245
+ })),
3246
+ features: facts.features.map((f) => f.type === "toggle" ? {
3247
+ type: "toggle",
3248
+ id: f.id,
3249
+ label: f.label,
3250
+ ...f.tooltip ? { tooltip: f.tooltip } : {},
3251
+ value: f.value
3252
+ } : {
3253
+ type: "select",
3254
+ id: f.id,
3255
+ label: f.label,
3256
+ ...f.tooltip ? { tooltip: f.tooltip } : {},
3257
+ value: f.value,
3258
+ options: f.options.map((o) => ({
3259
+ id: o.id,
3260
+ label: o.label
3261
+ }))
3262
+ })
3263
+ };
3264
+ return c.json(options);
3265
+ });
3266
+ app.post("/api/hosts/:host/agents/:agent/config", async (c) => {
3267
+ const change = z.object({
3268
+ model: z.string().min(1).max(300).optional(),
3269
+ thinkingOptionId: z.string().min(1).max(200).optional(),
3270
+ modeId: z.string().min(1).max(200).optional(),
3271
+ feature: z.object({
3272
+ id: z.string().min(1).max(200),
3273
+ value: z.union([z.string().max(200), z.boolean()])
3274
+ }).optional()
3275
+ }).refine((v) => Object.values(v).filter((x) => x !== void 0).length === 1).parse(await c.req.json());
3276
+ const { driver } = hosts.get(c.req.param("host"));
3277
+ const agent = c.req.param("agent");
3278
+ let notice = null;
3279
+ if (change.model) await driver.setAgentModel(agent, change.model);
3280
+ else if (change.thinkingOptionId) notice = await driver.setAgentThinkingOption(agent, change.thinkingOptionId);
3281
+ else if (change.modeId) notice = await driver.setAgentMode(agent, change.modeId);
3282
+ else if (change.feature) await driver.setAgentFeature(agent, change.feature.id, change.feature.value);
3283
+ return c.json({
3284
+ ok: true,
3285
+ notice
3286
+ });
3287
+ });
3288
+ /**
3289
+ * Speech to text through the transcription service configured here, once for every host. The
3290
+ * browser streams PCM over a short-lived socket. The file endpoint remains for older
3291
+ * clients. The API key never leaves the server.
3292
+ */
3293
+ app.get("/api/dictation", (c) => c.json(dictationSettings(store)));
3294
+ app.post("/api/dictation/session", (c) => {
3295
+ const config = dictationConfig(store);
3296
+ if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
3297
+ try {
3298
+ return c.json(dictationStreams.issue(config, streamValidity(c)));
3299
+ } catch (error) {
3300
+ return c.json({ error: error.message }, 429);
3301
+ }
3302
+ });
3303
+ app.put("/api/dictation", async (c) => {
3304
+ try {
3305
+ return c.json(saveDictation(store, await c.req.json()));
3306
+ } catch (error) {
3307
+ const message = error instanceof z.ZodError ? error.issues[0]?.message ?? "Invalid settings" : error.message;
3308
+ return c.json({ error: message }, 400);
3309
+ }
3310
+ });
3311
+ app.delete("/api/dictation", (c) => {
3312
+ clearDictation(store);
3313
+ return c.json(dictationSettings(store));
3314
+ });
3315
+ app.post("/api/dictation/transcribe", async (c) => {
3316
+ const config = dictationConfig(store);
3317
+ if (!config) return c.json({ error: "Voice input is not set up. Add a transcription service in Settings." }, 409);
3318
+ const format = /^audio\/pcm;rate=(\d{4,6});bits=16$/.exec(c.req.header("x-audio-format") ?? "");
3319
+ if (!format) return c.json({ error: "Unsupported audio format" }, 415);
3320
+ const audio = new Uint8Array(await c.req.arrayBuffer());
3321
+ if (audio.length < 3200 || audio.length % 2) return c.json({ error: "Recording too short" }, 400);
3322
+ try {
3323
+ return c.json({ text: await transcribe(config, audio, Number(format[1]), options.fetch) });
3324
+ } catch (error) {
3325
+ if (error instanceof DictationError) return c.json({ error: error.message }, error.status);
3326
+ throw error;
3327
+ }
3328
+ });
3329
+ const attachmentOwner = (c) => c.get("session")?.id ?? "bearer";
3330
+ app.get("/api/hosts/:host/agents/:agent/attachments/capabilities", async (c) => c.json(await attachments.capabilities(hosts, c.req.param("host"), c.req.param("agent"))));
3331
+ app.post("/api/hosts/:host/agents/:agent/attachments", async (c) => {
3332
+ hosts.get(c.req.param("host"));
3333
+ try {
3334
+ const name = decodeURIComponent(c.req.header("x-file-name") ?? "");
3335
+ const mime = c.req.header("content-type")?.split(";")[0] ?? "application/octet-stream";
3336
+ return c.json(attachments.put(attachmentOwner(c), c.req.param("host"), c.req.param("agent"), name, mime, Buffer.from(await c.req.arrayBuffer())), 201);
3337
+ } catch (error) {
3338
+ return c.json({ error: error.message }, 400);
3339
+ }
3340
+ });
3341
+ app.delete("/api/hosts/:host/agents/:agent/attachments/:id", (c) => {
3342
+ try {
3343
+ attachments.remove(c.req.param("id"), attachmentOwner(c), c.req.param("host"), c.req.param("agent"));
3344
+ } catch {
3345
+ return c.json({ error: "Attachment already expired or unavailable" }, 404);
3346
+ }
3347
+ return c.json({ ok: true });
3348
+ });
3349
+ app.post("/api/hosts/:host/agents/:agent/messages/status", async (c) => {
3350
+ const { messageIds } = z.object({ messageIds: z.array(z.string().uuid()).min(1).max(20) }).parse(await c.req.json());
3351
+ const { driver } = hosts.get(c.req.param("host"));
3352
+ return c.json({ confirmed: await confirmedMessages(driver, c.req.param("agent"), messageIds) });
3353
+ });
3354
+ app.post("/api/hosts/:host/agents/:agent/messages", async (c) => {
3355
+ const input = z.object({
3356
+ text: z.string().trim().max(1e5),
3357
+ attachmentIds: z.array(z.string().uuid()).max(4).refine((ids) => new Set(ids).size === ids.length).default([]),
3358
+ messageId: z.string().uuid(),
3359
+ behavior: z.enum(["steer", "interrupt"])
3360
+ }).refine((input) => !!input.text || input.attachmentIds.length > 0).parse(await c.req.json());
3361
+ let prepared;
3362
+ try {
3363
+ prepared = await attachments.prepare(hosts, attachmentOwner(c), c.req.param("host"), c.req.param("agent"), input.attachmentIds);
3364
+ } catch (error) {
3365
+ return c.json({
3366
+ error: error.message,
3367
+ delivery: "not-sent"
3368
+ }, 400);
3369
+ }
3370
+ try {
3371
+ await hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent")).send(input.text, {
3372
+ messageId: input.messageId,
3373
+ activeTurnBehavior: input.behavior,
3374
+ ...prepared.images.length ? { images: prepared.images } : {},
3375
+ ...prepared.attachments.length ? { attachments: prepared.attachments } : {}
3376
+ });
3377
+ attachments.consumed(input.attachmentIds);
3378
+ return c.json({
3379
+ status: "acknowledged",
3380
+ messageId: input.messageId
3381
+ });
3382
+ } catch {
3383
+ return c.json({
3384
+ error: "Delivery outcome unknown. Refresh the conversation before retrying.",
3385
+ messageId: input.messageId
3386
+ }, 502);
3387
+ }
3388
+ });
3389
+ app.post("/api/hosts/:host/agents/:agent/stop", async (c) => {
3390
+ await hosts.get(c.req.param("host")).driver.cancelAgent(c.req.param("agent"));
3391
+ return c.json({ status: "acknowledged" });
3392
+ });
3393
+ app.post("/api/hosts/:host/agents/:agent/permissions/:permission", async (c) => {
3394
+ const response = AgentPermissionResponseSchema.parse(await c.req.json());
3395
+ const agent = hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent"));
3396
+ await agent.refresh();
3397
+ if (!agent.pendingPermissions?.some((p) => p.id === c.req.param("permission"))) return c.json({ error: "Permission no longer pending. Refresh the conversation." }, 409);
3398
+ await agent.respondToPermission({
3399
+ requestId: c.req.param("permission"),
3400
+ response
3401
+ });
3402
+ return c.json({ status: "acknowledged" });
3403
+ });
3404
+ /** Marks a settled turn as seen (Paseo's attention flag), moving it out of "review". */
3405
+ app.post("/api/hosts/:host/agents/:agent/read", async (c) => {
3406
+ await hosts.get(c.req.param("host")).driver.clearAgentAttention(c.req.param("agent"));
3407
+ return c.json({ ok: true });
3408
+ });
3409
+ app.post("/api/hosts/:host/agents/:agent/archive", async (c) => {
3410
+ await hosts.get(c.req.param("host")).api.agents.ref(c.req.param("agent")).archive();
3411
+ return c.json({ ok: true });
3412
+ });
3413
+ const workspace = (c) => ({
3414
+ driver: hosts.get(c.req.param("host")).driver,
3415
+ id: c.req.param("workspace")
3416
+ });
3417
+ /** Rename; null resets to the name derived from the branch or directory. */
3418
+ app.post("/api/hosts/:host/workspaces/:workspace/title", async (c) => {
3419
+ const { title } = z.object({ title: z.string().trim().max(200).nullable() }).parse(await c.req.json());
3420
+ const { driver, id } = workspace(c);
3421
+ await driver.setWorkspaceTitle(id, title ? title : null);
3422
+ return c.json({ ok: true });
3423
+ });
3424
+ app.post("/api/hosts/:host/workspaces/:workspace/pin", async (c) => {
3425
+ const { pinned } = z.object({ pinned: z.boolean() }).parse(await c.req.json());
3426
+ const { driver, id } = workspace(c);
3427
+ await driver.setWorkspacePinned(id, pinned);
3428
+ return c.json({ ok: true });
3429
+ });
3430
+ app.post("/api/hosts/:host/workspaces/:workspace/unread", async (c) => {
3431
+ const { driver, id } = workspace(c);
3432
+ await driver.markWorkspaceUnread(id);
3433
+ return c.json({ ok: true });
3434
+ });
3435
+ app.post("/api/hosts/:host/workspaces/:workspace/read", async (c) => {
3436
+ const { driver, id } = workspace(c);
3437
+ await driver.clearWorkspaceAttention(id);
3438
+ return c.json({ ok: true });
3439
+ });
3440
+ app.post("/api/hosts/:host/workspaces/:workspace/archive", async (c) => {
3441
+ const { driver, id } = workspace(c);
3442
+ await driver.archiveWorkspace(id);
3443
+ return c.json({ ok: true });
3444
+ });
3445
+ /**
3446
+ * next-input: the daemon appends a placeholder row after a completed turn; prediction runs only
3447
+ * when a client that shows the row asks. Only this one plugin method is reachable from here.
3448
+ */
3449
+ app.post("/api/hosts/:host/agents/:agent/suggestion", async (c) => {
3450
+ const { token } = z.object({ token: z.string().min(1).max(200) }).parse(await c.req.json());
3451
+ try {
3452
+ const output = await hosts.get(c.req.param("host")).driver.invokePluginRpc("next-input", "suggestions.predict", {
3453
+ agentId: c.req.param("agent"),
3454
+ token
3455
+ });
3456
+ return c.json({
3457
+ status: String(output?.status ?? "error"),
3458
+ text: String(output?.text ?? "")
3459
+ });
3460
+ } catch (error) {
3461
+ if (error instanceof UnknownHostError) throw error;
3462
+ return c.json({
3463
+ status: "unavailable",
3464
+ text: ""
3465
+ });
3466
+ }
3467
+ });
3468
+ registerWorkspaceRoutes(app, hosts, store, (c) => streamValidity(c));
3469
+ app.get("/api/usage", async (c) => c.json(await usage.report(c.req.query("refresh") === "1")));
3470
+ app.get("/api/board", (c) => c.json(store.board()));
3471
+ app.put("/api/board", async (c) => {
3472
+ const b = z.object({
3473
+ revision: z.number().int().nonnegative(),
3474
+ cards: z.array(card).max(1e3)
3475
+ }).parse(await c.req.json());
3476
+ if (new Set(b.cards.map((c) => c.id)).size !== b.cards.length) return c.json({ error: "Duplicate card ID" }, 400);
3477
+ if (!store.saveBoard(b.revision, b.cards)) return c.json({ error: "Board changed. Reload before editing." }, 409);
3478
+ return c.json(store.board());
3479
+ });
3480
+ const cardEdit = (id, change) => store.updateCard(id, change) ? store.board() : null;
3481
+ app.patch("/api/board/cards/:id", async (c) => {
3482
+ const p = cardPatch.parse(await c.req.json());
3483
+ const board = cardEdit(c.req.param("id"), (card) => ({
3484
+ ...card,
3485
+ ...p.title !== void 0 ? { title: p.title } : {},
3486
+ ...p.column !== void 0 ? { column: p.column } : {},
3487
+ ...p.description !== void 0 ? { description: p.description } : {},
3488
+ ...p.link !== void 0 ? {
3489
+ hostId: p.link?.hostId ?? null,
3490
+ agentId: p.link?.agentId ?? null
3491
+ } : {},
3492
+ updatedAt: Date.now()
3493
+ }));
3494
+ return board ? c.json(board) : c.json({ error: "Task not found" }, 404);
3495
+ });
3496
+ app.post("/api/board/cards/:id/comments", async (c) => {
3497
+ const { text } = z.object({ text: z.string().trim().min(1).max(CARD_COMMENT_MAX) }).parse(await c.req.json());
3498
+ let full = false;
3499
+ const board = cardEdit(c.req.param("id"), (card) => {
3500
+ const comments = card.comments ?? [];
3501
+ if (comments.length >= 200) return full = true, null;
3502
+ return {
3503
+ ...card,
3504
+ comments: [...comments, {
3505
+ id: randomUUID(),
3506
+ text,
3507
+ at: Date.now()
3508
+ }],
3509
+ updatedAt: Date.now()
3510
+ };
3511
+ });
3512
+ if (full) return c.json({ error: `A task holds up to 200 comments.` }, 400);
3513
+ return board ? c.json(board, 201) : c.json({ error: "Task not found" }, 404);
3514
+ });
3515
+ app.delete("/api/board/cards/:id/comments/:comment", (c) => {
3516
+ const board = cardEdit(c.req.param("id"), (card) => ({
3517
+ ...card,
3518
+ comments: (card.comments ?? []).filter((m) => m.id !== c.req.param("comment")),
3519
+ updatedAt: Date.now()
3520
+ }));
3521
+ return board ? c.json(board) : c.json({ error: "Task not found" }, 404);
3522
+ });
3523
+ app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
3524
+ for (const [file, type] of [["sw.js", "text/javascript; charset=utf-8"], ["manifest.webmanifest", "application/manifest+json"]]) app.get("/" + file, (c) => {
3525
+ try {
3526
+ return c.body(readFileSync(join(webRoot, file)), 200, {
3527
+ "Content-Type": type,
3528
+ "Cache-Control": "no-cache"
3529
+ });
3530
+ } catch {
3531
+ return c.notFound();
3532
+ }
3533
+ });
3534
+ app.use("/assets/*", async (c, next) => {
3535
+ await next();
3536
+ if (c.res.ok) c.header("Cache-Control", "public, max-age=31536000, immutable");
3537
+ });
3538
+ app.use("/*", async (c, next) => {
3539
+ await next();
3540
+ if (c.res.headers.get("Content-Type")?.startsWith("text/html")) c.header("Cache-Control", "no-cache");
3541
+ });
3542
+ app.use("/*", serveStatic({
3543
+ root: webRoot,
3544
+ precompressed: true
3545
+ }));
3546
+ return Object.assign(app, {
3547
+ dictationStreams,
3548
+ /** Open directory streams; lets tests prove that disconnects release them. */
3549
+ openStreams: () => directoryStreams.size,
3550
+ dispose: () => {
3551
+ disposed = true;
3552
+ clearTimeout(agentFlush);
3553
+ clearTimeout(hostFlush);
3554
+ agentFlush = hostFlush = void 0;
3555
+ attachments.close();
3556
+ dictationStreams.close();
3557
+ }
3558
+ });
3559
+ }
3560
+ // src/server/worker.ts
3561
+ async function runWorker(directory, webRoot) {
3562
+ if (!process.send) throw new Error("worker is an internal supervised command");
3563
+ const tokenPath = join(directory, "token");
3564
+ if (!existsSync(tokenPath)) writeFileSync(tokenPath, generateToken(), {
3565
+ mode: 384,
3566
+ flag: "wx"
3567
+ });
3568
+ const store = new Store(directory), hosts = new Hosts();
3569
+ for (const host of store.hosts()) try {
3570
+ hosts.add(host);
3571
+ } catch {
3572
+ console.error("Could not initialize host", host.id);
3573
+ }
3574
+ const config = effectiveConfig(store, process.env);
3575
+ const port = Number(config.port.value), hostname = config.bind.value;
3576
+ const app = createApp(store, hosts, tokenFile(tokenPath), webRoot, { pushSubject: config["push-subject"].value });
3577
+ const server = serve({
3578
+ fetch: app.fetch,
3579
+ port,
3580
+ hostname
3581
+ });
3582
+ app.dictationStreams.attach(server);
3583
+ let stopping = false;
3584
+ const shutdown = async () => {
3585
+ if (stopping) return;
3586
+ stopping = true;
3587
+ setTimeout(() => process.exit(1), 5e3).unref();
3588
+ app.dispose();
3589
+ await hosts.close();
3590
+ if ("closeAllConnections" in server) server.closeAllConnections();
3591
+ await new Promise((resolve) => server.close(() => resolve()));
3592
+ store.close();
3593
+ if (process.connected) process.disconnect();
3594
+ };
3595
+ process.once("SIGINT", () => void shutdown());
3596
+ process.once("SIGTERM", () => void shutdown());
3597
+ process.once("disconnect", () => void shutdown());
3598
+ server.once("error", (error) => {
3599
+ const message = error.code === "EADDRINUSE" ? `Port ${port} on ${hostname} is already in use (choose another with: litepaseo config set port <number>)` : error.code === "EACCES" ? `Not permitted to listen on ${hostname}:${port}` : error.message;
3600
+ console.error(message);
3601
+ process.send?.({
3602
+ type: "fatal",
3603
+ error: message
3604
+ });
3605
+ process.exitCode = 1;
3606
+ shutdown();
3607
+ });
3608
+ server.once("listening", () => {
3609
+ const address = server.address();
3610
+ const actualPort = typeof address === "object" && address ? address.port : port;
3611
+ const url = `http://${hostname}:${actualPort}`;
3612
+ console.log(`LitePaseo ready at ${url}`);
3613
+ process.send?.({
3614
+ type: "ready",
3615
+ url
3616
+ });
3617
+ });
3618
+ }
3619
+ export { runWorker };