wherever-dev 0.22.1 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/assistant-channels.d.ts +14 -0
  3. package/dist/assistant-channels.d.ts.map +1 -1
  4. package/dist/assistant-channels.js.map +1 -1
  5. package/dist/assistant-controller.d.ts.map +1 -1
  6. package/dist/assistant-controller.js +5 -2
  7. package/dist/assistant-controller.js.map +1 -1
  8. package/dist/assistant-folder.d.ts +14 -1
  9. package/dist/assistant-folder.d.ts.map +1 -1
  10. package/dist/assistant-folder.js +33 -2
  11. package/dist/assistant-folder.js.map +1 -1
  12. package/dist/assistant-tool-text.d.ts.map +1 -1
  13. package/dist/assistant-tool-text.js +5 -1
  14. package/dist/assistant-tool-text.js.map +1 -1
  15. package/dist/assistant-tools.d.ts +18 -3
  16. package/dist/assistant-tools.d.ts.map +1 -1
  17. package/dist/assistant-tools.js +58 -4
  18. package/dist/assistant-tools.js.map +1 -1
  19. package/dist/attach-file-tool.d.ts +17 -0
  20. package/dist/attach-file-tool.d.ts.map +1 -1
  21. package/dist/attach-file-tool.js +44 -37
  22. package/dist/attach-file-tool.js.map +1 -1
  23. package/dist/cli-requests.d.ts +2 -1
  24. package/dist/cli-requests.d.ts.map +1 -1
  25. package/dist/cli-requests.js.map +1 -1
  26. package/dist/delta-coalescer.d.ts +77 -0
  27. package/dist/delta-coalescer.d.ts.map +1 -0
  28. package/dist/delta-coalescer.js +117 -0
  29. package/dist/delta-coalescer.js.map +1 -0
  30. package/dist/frame-chunks.d.ts +41 -0
  31. package/dist/frame-chunks.d.ts.map +1 -0
  32. package/dist/frame-chunks.js +61 -0
  33. package/dist/frame-chunks.js.map +1 -0
  34. package/dist/history-images.d.ts +33 -0
  35. package/dist/history-images.d.ts.map +1 -0
  36. package/dist/history-images.js +47 -0
  37. package/dist/history-images.js.map +1 -0
  38. package/dist/index.js +141 -13
  39. package/dist/index.js.map +1 -1
  40. package/dist/session-pool.d.ts +9 -1
  41. package/dist/session-pool.d.ts.map +1 -1
  42. package/dist/session-pool.js +58 -2
  43. package/dist/session-pool.js.map +1 -1
  44. package/dist/session-transcript.d.ts +19 -0
  45. package/dist/session-transcript.d.ts.map +1 -1
  46. package/dist/session-transcript.js +67 -0
  47. package/dist/session-transcript.js.map +1 -1
  48. package/dist/session-types.d.ts +21 -2
  49. package/dist/session-types.d.ts.map +1 -1
  50. package/dist/static-compression.d.ts +15 -0
  51. package/dist/static-compression.d.ts.map +1 -0
  52. package/dist/static-compression.js +87 -0
  53. package/dist/static-compression.js.map +1 -0
  54. package/dist/telegram-channel.d.ts +14 -2
  55. package/dist/telegram-channel.d.ts.map +1 -1
  56. package/dist/telegram-channel.js +41 -8
  57. package/dist/telegram-channel.js.map +1 -1
  58. package/dist/telegram-replies.d.ts +18 -0
  59. package/dist/telegram-replies.d.ts.map +1 -1
  60. package/dist/telegram-replies.js +41 -23
  61. package/dist/telegram-replies.js.map +1 -1
  62. package/package.json +1 -1
  63. package/public/_app/immutable/chunks/{DSPDB3Gw.js → Ba0iJyN2.js} +2 -2
  64. package/public/_app/immutable/chunks/{DSPDB3Gw.js.map → Ba0iJyN2.js.map} +1 -1
  65. package/public/_app/immutable/chunks/BfCwf84t.js +2 -0
  66. package/public/_app/immutable/chunks/{DEUwJYqt.js.map → BfCwf84t.js.map} +1 -1
  67. package/public/_app/immutable/chunks/{Cuh9gHb6.js → jBzVXpuo.js} +2 -2
  68. package/public/_app/immutable/chunks/{Cuh9gHb6.js.map → jBzVXpuo.js.map} +1 -1
  69. package/public/_app/immutable/entry/{app.BkV4f8p8.js → app.CePvTLA2.js} +3 -3
  70. package/public/_app/immutable/entry/{app.BkV4f8p8.js.map → app.CePvTLA2.js.map} +1 -1
  71. package/public/_app/immutable/entry/start.MB6ZjVGe.js +2 -0
  72. package/public/_app/immutable/entry/start.MB6ZjVGe.js.map +1 -0
  73. package/public/_app/immutable/nodes/{0.DR4K9Ylw.js → 0.ydSaxbgZ.js} +2 -2
  74. package/public/_app/immutable/nodes/{0.DR4K9Ylw.js.map → 0.ydSaxbgZ.js.map} +1 -1
  75. package/public/_app/immutable/nodes/{1.DdqkeKC4.js → 1.T9BouUHS.js} +2 -2
  76. package/public/_app/immutable/nodes/{1.DdqkeKC4.js.map → 1.T9BouUHS.js.map} +1 -1
  77. package/public/_app/immutable/nodes/2.D_6BVhWL.js +123 -0
  78. package/public/_app/immutable/nodes/2.D_6BVhWL.js.map +1 -0
  79. package/public/_app/version.json +1 -1
  80. package/public/index.html +10 -10
  81. package/public/service-worker.js +1 -1
  82. package/public/_app/immutable/chunks/DEUwJYqt.js +0 -2
  83. package/public/_app/immutable/entry/start.D5TsAoxn.js +0 -2
  84. package/public/_app/immutable/entry/start.D5TsAoxn.js.map +0 -1
  85. package/public/_app/immutable/nodes/2.n5lfdeec.js +0 -122
  86. package/public/_app/immutable/nodes/2.n5lfdeec.js.map +0 -1
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Tool images by reference in `message_history`.
3
+ *
4
+ * A history window inlines every tool image as base64 (a `read` on a screenshot
5
+ * is often 1-3 MB), and the window is re-sent on every load AND on every
6
+ * reconnect. Over a slow link that made a session with a few screenshots take
7
+ * minutes to resync, every time the phone dropped its socket. A socket that asks
8
+ * for refs (`imageRefs=1` on the socket URL) gets large images WITHOUT their
9
+ * bytes; the web loads each one lazily from `GET /session/tool-image`, which the
10
+ * browser caches (a tool result never changes), so a reconnect costs text only.
11
+ *
12
+ * Opt-in so an older cached web build, which only knows inline `data`, keeps
13
+ * getting it. Only images with a `toolCallId` to address them by are stripped,
14
+ * and small ones stay inline (a fetch costs more than it saves).
15
+ */
16
+ import type { HistoryMessage } from './session-types.js';
17
+ export declare const IMAGE_REFS_PARAM = "imageRefs";
18
+ /** Base64 characters above which an image is sent by reference. */
19
+ export declare const INLINE_IMAGE_MAX_CHARS: number;
20
+ export declare function wantsImageRefs(searchParams: URLSearchParams): boolean;
21
+ /**
22
+ * A copy of `messages` with large tool images replaced by references. Messages
23
+ * without such images are returned as is (same objects), so the common case
24
+ * allocates nothing.
25
+ */
26
+ export declare function stripHistoryImages(messages: HistoryMessage[]): HistoryMessage[];
27
+ /**
28
+ * Raster types the endpoint will serve inline (and so the only ones sent by
29
+ * reference). SVG is excluded on purpose (it can carry script; see
30
+ * dispositionTypeFor in index.ts), as is anything unexpected.
31
+ */
32
+ export declare const SERVABLE_IMAGE_TYPES: Set<string>;
33
+ //# sourceMappingURL=history-images.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history-images.d.ts","sourceRoot":"","sources":["../src/history-images.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEzD,eAAO,MAAM,gBAAgB,cAAc,CAAC;AAC5C,mEAAmE;AACnE,eAAO,MAAM,sBAAsB,QAAY,CAAC;AAEhD,wBAAgB,cAAc,CAAC,YAAY,EAAE,eAAe,GAAG,OAAO,CAErE;AAQD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,cAAc,EAAE,GAAG,cAAc,EAAE,CAqB/E;AAMD;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,aAA6F,CAAC"}
@@ -0,0 +1,47 @@
1
+ export const IMAGE_REFS_PARAM = 'imageRefs';
2
+ /** Base64 characters above which an image is sent by reference. */
3
+ export const INLINE_IMAGE_MAX_CHARS = 16 * 1024;
4
+ export function wantsImageRefs(searchParams) {
5
+ return searchParams.get(IMAGE_REFS_PARAM) === '1';
6
+ }
7
+ /** Approximate decoded size of a base64 string. */
8
+ function base64Bytes(data) {
9
+ const pad = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
10
+ return Math.max(0, Math.floor((data.length * 3) / 4) - pad);
11
+ }
12
+ /**
13
+ * A copy of `messages` with large tool images replaced by references. Messages
14
+ * without such images are returned as is (same objects), so the common case
15
+ * allocates nothing.
16
+ */
17
+ export function stripHistoryImages(messages) {
18
+ let changed = false;
19
+ const out = messages.map((m) => {
20
+ if (!m.toolCallId || !m.images?.some(byRef))
21
+ return m;
22
+ changed = true;
23
+ return {
24
+ ...m,
25
+ images: m.images.map((i, index) => byRef(i)
26
+ ? {
27
+ mimeType: i.mimeType,
28
+ bytes: base64Bytes(i.data),
29
+ toolCallId: m.toolCallId,
30
+ ...(m.entryId ? { entryId: m.entryId } : {}),
31
+ index,
32
+ }
33
+ : i),
34
+ };
35
+ });
36
+ return changed ? out : messages;
37
+ }
38
+ function byRef(i) {
39
+ return typeof i.data === 'string' && i.data.length > INLINE_IMAGE_MAX_CHARS && SERVABLE_IMAGE_TYPES.has(i.mimeType);
40
+ }
41
+ /**
42
+ * Raster types the endpoint will serve inline (and so the only ones sent by
43
+ * reference). SVG is excluded on purpose (it can carry script; see
44
+ * dispositionTypeFor in index.ts), as is anything unexpected.
45
+ */
46
+ export const SERVABLE_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/avif']);
47
+ //# sourceMappingURL=history-images.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history-images.js","sourceRoot":"","sources":["../src/history-images.ts"],"names":[],"mappings":"AAiBA,MAAM,CAAC,MAAM,gBAAgB,GAAG,WAAW,CAAC;AAC5C,mEAAmE;AACnE,MAAM,CAAC,MAAM,sBAAsB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEhD,MAAM,UAAU,cAAc,CAAC,YAA6B;IAC1D,OAAO,YAAY,CAAC,GAAG,CAAC,gBAAgB,CAAC,KAAK,GAAG,CAAC;AACpD,CAAC;AAED,mDAAmD;AACnD,SAAS,WAAW,CAAC,IAAY;IAC/B,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC;AAC9D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,QAA0B;IAC3D,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;QAC7B,IAAI,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC;YAAE,OAAO,CAAC,CAAC;QACtD,OAAO,GAAG,IAAI,CAAC;QACf,OAAO;YACL,GAAG,CAAC;YACJ,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAChC,KAAK,CAAC,CAAC,CAAC;gBACN,CAAC,CAAC;oBACE,QAAQ,EAAE,CAAC,CAAC,QAAQ;oBACpB,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,IAAK,CAAC;oBAC3B,UAAU,EAAE,CAAC,CAAC,UAAU;oBACxB,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC5C,KAAK;iBACN;gBACH,CAAC,CAAC,CAAC,CACN;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;AAClC,CAAC;AAED,SAAS,KAAK,CAAC,CAAsC;IACnD,OAAO,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,sBAAsB,IAAI,oBAAoB,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AACtH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC,CAAC"}
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { connect as netConnect } from 'node:net';
5
5
  import { WebSocketServer, WebSocket } from 'ws';
6
6
  import { SessionPool, RELOADING_REFUSAL, getWhereverConfig, getWhereverCertsDir, getWhereverStateDir, detectRemoteRepo, normalizePath, invalidateFolderExistence } from './session-pool.js';
7
7
  import { readDrafts, addDraft, deleteDraft, validateDraftInput } from './drafts.js';
8
- import { startAssistantFolder } from './assistant-folder.js';
8
+ import { canonicalPath, startAssistantFolder } from './assistant-folder.js';
9
9
  import { AssistantController } from './assistant-controller.js';
10
10
  import { AssistantScheduler } from './assistant-scheduler.js';
11
11
  import { assistantNotActiveError, setTimezone, testNotification, WEB_TIMEZONE_SOURCE, } from './assistant-tools.js';
@@ -26,6 +26,11 @@ import { INITIAL_HISTORY_LIMIT, HISTORY_PAGE_SIZE } from './protocol.js';
26
26
  import { gateUploadFolder, gateUploadWrite, uploadMaxBytes, uploadTooLarge } from './upload-gate.js';
27
27
  import { readAttachGrants } from './download-grants.js';
28
28
  import { DEFAULT_DOWNLOAD_MAX_BYTES } from './attach-file-tool.js';
29
+ import { splitFrame, wantsFrameChunks, FRAME_CHUNK_CHARS } from './frame-chunks.js';
30
+ import { compressCached, isCompressible, negotiateEncoding } from './static-compression.js';
31
+ import { stripHistoryImages, wantsImageRefs, SERVABLE_IMAGE_TYPES } from './history-images.js';
32
+ import { readToolResultImage } from './session-transcript.js';
33
+ import { DeltaCoalescer } from './delta-coalescer.js';
29
34
  import { UploadStaging, UPLOAD_CAPABILITY, isValidUploadId, parseChunkFrame, CHUNK_FRAME_KIND } from './upload-staging.js';
30
35
  import fs from 'node:fs';
31
36
  import path from 'node:path';
@@ -272,7 +277,7 @@ async function resolveSafeDownloadPath(requested, cwd, roots, grants) {
272
277
  }
273
278
  return null;
274
279
  }
275
- function serveStaticFile(reqPath, res) {
280
+ function serveStaticFile(reqPath, res, acceptEncoding) {
276
281
  let filePath = path.join(staticDir, reqPath === '/' ? 'index.html' : reqPath);
277
282
  if (!filePath.startsWith(staticDir)) {
278
283
  res.writeHead(403);
@@ -313,8 +318,26 @@ function serveStaticFile(reqPath, res) {
313
318
  if (debugEnabled && filePath.endsWith('index.html')) {
314
319
  data = Buffer.from(data.toString().replace(ERUDA_PLUGINS_META_FALSE, ERUDA_PLUGINS_META_TRUE));
315
320
  }
316
- res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': cacheControl });
317
- res.end(data);
321
+ const encoding = isCompressible(contentType, data.length) ? negotiateEncoding(acceptEncoding) : null;
322
+ if (!encoding) {
323
+ res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': cacheControl, Vary: 'Accept-Encoding' });
324
+ res.end(data);
325
+ return;
326
+ }
327
+ const body = data;
328
+ compressCached(body, encoding).then((compressed) => {
329
+ res.writeHead(200, {
330
+ 'Content-Type': contentType,
331
+ 'Cache-Control': cacheControl,
332
+ 'Content-Encoding': encoding,
333
+ 'Content-Length': compressed.length,
334
+ Vary: 'Accept-Encoding',
335
+ });
336
+ res.end(compressed);
337
+ }, () => {
338
+ res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': cacheControl, Vary: 'Accept-Encoding' });
339
+ res.end(body);
340
+ });
318
341
  }
319
342
  });
320
343
  }
@@ -350,8 +373,8 @@ function resolveHeartbeatMs(raw) {
350
373
  // CLI bridges are deliberately left ALONE: their re-registration is already
351
374
  // handled by registerCliSession/unregisterCliSession, and tearing one down here
352
375
  // would race a cli_register arriving on the new socket against the old socket's
353
- // async close teardown, which could unregister the session that was just
354
- // re-registered.
376
+ // async close teardown. (That teardown itself only removes the entry its own
377
+ // socket owns, so a reconnect that lands first survives it.)
355
378
  function evictPreviousConnection(clientKey, clients, pool, onSessionsUpdated) {
356
379
  for (const prev of Array.from(clients.values())) {
357
380
  if (prev.clientKey !== clientKey || prev.isCliBridge)
@@ -866,10 +889,48 @@ function readBody(req, maxLimitBytes = 1e6) {
866
889
  req.on('error', (err) => reject(err));
867
890
  });
868
891
  }
892
+ // Sockets whose client asked for chunked frames (`frames=chunk.v1` on the socket
893
+ // URL, see frame-chunks.ts). Keyed by socket so every sender gets it for free.
894
+ const chunkingSockets = new WeakSet();
895
+ let nextFrameChunkId = 1;
896
+ // Sockets whose client loads large history images by reference (`imageRefs=1`,
897
+ // see history-images.ts) instead of receiving their base64 inline.
898
+ const imageRefSockets = new WeakSet();
899
+ // Per-socket coalescing of streamed deltas (delta-coalescer.ts): fewer, larger
900
+ // frames, frame order unchanged. "Backed up" = more than 64 KB still unsent.
901
+ const deltaCoalescers = new WeakMap();
902
+ const BACKED_UP_BYTES = 64 * 1024;
903
+ function coalescerFor(ws) {
904
+ let c = deltaCoalescers.get(ws);
905
+ if (!c) {
906
+ c = new DeltaCoalescer((m) => writeWS(ws, m), {
907
+ isBackedUp: () => ws.bufferedAmount > BACKED_UP_BYTES,
908
+ });
909
+ deltaCoalescers.set(ws, c);
910
+ ws.once('close', () => c.dispose());
911
+ }
912
+ return c;
913
+ }
869
914
  function sendWS(ws, msg) {
915
+ if (ws.readyState !== WebSocket.OPEN)
916
+ return;
917
+ coalescerFor(ws).send(msg);
918
+ }
919
+ function writeWS(ws, msg) {
870
920
  if (ws.readyState === WebSocket.OPEN) {
871
921
  try {
872
- ws.send(JSON.stringify(msg));
922
+ if ((msg.type === 'message_history' || msg.type === 'message_history_prepend') && imageRefSockets.has(ws)) {
923
+ msg = { ...msg, messages: stripHistoryImages(msg.messages) };
924
+ }
925
+ const json = JSON.stringify(msg);
926
+ if (chunkingSockets.has(ws) && json.length > FRAME_CHUNK_CHARS) {
927
+ // Back to back, so frame order on the socket is unchanged.
928
+ for (const piece of splitFrame(json, nextFrameChunkId++))
929
+ ws.send(piece);
930
+ }
931
+ else {
932
+ ws.send(json);
933
+ }
873
934
  }
874
935
  catch (err) {
875
936
  console.error('Failed to send WS message:', err);
@@ -900,6 +961,8 @@ function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
900
961
  };
901
962
  const timer = setTimeout(kill, flushTimeoutMs);
902
963
  timer.unref?.();
964
+ // Anything still held by the delta coalescer goes out first, in order.
965
+ deltaCoalescers.get(ws)?.flush();
903
966
  if (ws.readyState !== WebSocket.OPEN) {
904
967
  clearTimeout(timer);
905
968
  kill();
@@ -1165,8 +1228,11 @@ async function main() {
1165
1228
  // The CLI bridge's request/response path (ADR 0016, cli-requests.ts). Built
1166
1229
  // whether or not the assistant is active: `assistant_info` is how a terminal pi
1167
1230
  // learns it is NOT, and that answer is what keeps its tool twins inactive.
1231
+ // The folder goes out CANONICAL (symlinks resolved): the bridge compares it
1232
+ // with the terminal pi's real cwd, and a bridge cannot realpath a path on the
1233
+ // server's side of a symlink it may not share.
1168
1234
  const currentAssistantInfo = () => ({
1169
- assistantFolder: assistantController ? assistant.status.folder : null,
1235
+ assistantFolder: assistantController && assistant.status.folder ? canonicalPath(assistant.status.folder) : null,
1170
1236
  timezone: assistantController ? currentTimezone() : null,
1171
1237
  });
1172
1238
  const cliRequests = createCliRequestRouter({ assistantInfo: currentAssistantInfo, assistantHooks: () => assistantHooks });
@@ -1250,7 +1316,16 @@ async function main() {
1250
1316
  console.log(`Self-signed certificates generated successfully in ${certsDir}`);
1251
1317
  }
1252
1318
  catch (err) {
1253
- console.warn(`Failed to generate self-signed certificates in ${certsDir} using OpenSSL. Falling back to HTTP.`, err.message);
1319
+ const e = err;
1320
+ if (e.code === 'ENOENT' && e.syscall?.startsWith('spawn') && e.path === 'openssl') {
1321
+ // The binary itself is missing: say so, rather than the bare
1322
+ // `spawnSync openssl ENOENT` (the certs dir was created fine).
1323
+ console.warn(`Cannot generate self-signed certificates: \`openssl\` was not found on PATH. Falling back to HTTP. ` +
1324
+ `Install openssl (it is in the flake devshell, \`nix develop\`), pass --ssl-key/--ssl-cert, or pass --no-ssl to silence this.`);
1325
+ }
1326
+ else {
1327
+ console.warn(`Failed to generate self-signed certificates in ${certsDir} using OpenSSL. Falling back to HTTP.`, err.message);
1328
+ }
1254
1329
  isSecure = false;
1255
1330
  }
1256
1331
  }
@@ -1522,9 +1597,13 @@ async function main() {
1522
1597
  }
1523
1598
  }
1524
1599
  sessionPool.onEvent = broadcastAgentEvent;
1600
+ // DELETE is used only by Web Push's `/push/subscription`, so it is advertised
1601
+ // only while those routes exist: with the assistant off (or Web Push disabled)
1602
+ // the header is what it was before the assistant.
1603
+ const corsAllowMethods = webPushChannel ? 'GET, POST, DELETE, OPTIONS' : 'GET, POST, OPTIONS';
1525
1604
  const requestHandler = async (req, res) => {
1526
1605
  res.setHeader('Access-Control-Allow-Origin', '*');
1527
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
1606
+ res.setHeader('Access-Control-Allow-Methods', corsAllowMethods);
1528
1607
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
1529
1608
  if (req.method === 'OPTIONS') {
1530
1609
  res.writeHead(200);
@@ -2353,6 +2432,41 @@ async function main() {
2353
2432
  }
2354
2433
  return;
2355
2434
  }
2435
+ // A tool image sent by reference in message_history (history-images.ts).
2436
+ // Same token gate as every /session/ route. A tool result never changes once
2437
+ // written, so the browser may keep the image for good.
2438
+ if (pathname === '/session/tool-image' && req.method === 'GET') {
2439
+ const qSessionId = url.searchParams.get('sessionId') || '';
2440
+ const qToolCallId = url.searchParams.get('toolCallId') || '';
2441
+ const qEntryId = url.searchParams.get('entryId') || undefined;
2442
+ const qIndexRaw = url.searchParams.get('index');
2443
+ const qIndex = qIndexRaw ? Number(qIndexRaw) : NaN;
2444
+ if (!qSessionId || !qToolCallId || !Number.isInteger(qIndex) || qIndex < 0) {
2445
+ sendJSON(res, 400, { error: 'Missing sessionId, toolCallId or index' });
2446
+ return;
2447
+ }
2448
+ const located = await sessionPool.locateSession(qSessionId);
2449
+ const image = located
2450
+ ? await readToolResultImage(located.sessionFile, { toolCallId: qToolCallId, entryId: qEntryId }, qIndex)
2451
+ : null;
2452
+ if (!image) {
2453
+ sendJSON(res, 404, { error: 'Image not found' });
2454
+ return;
2455
+ }
2456
+ if (!SERVABLE_IMAGE_TYPES.has(image.mimeType)) {
2457
+ sendJSON(res, 415, { error: `Unsupported image type ${image.mimeType}` });
2458
+ return;
2459
+ }
2460
+ const bytes = Buffer.from(image.data, 'base64');
2461
+ res.writeHead(200, {
2462
+ 'Content-Type': image.mimeType,
2463
+ 'Content-Length': bytes.length,
2464
+ 'Cache-Control': 'private, max-age=31536000, immutable',
2465
+ 'X-Content-Type-Options': 'nosniff',
2466
+ });
2467
+ res.end(bytes);
2468
+ return;
2469
+ }
2356
2470
  if (pathname === '/session/download' && req.method === 'GET') {
2357
2471
  const config = getWhereverConfig();
2358
2472
  if (config.downloads?.enabled === false) {
@@ -2521,7 +2635,7 @@ async function main() {
2521
2635
  });
2522
2636
  return;
2523
2637
  }
2524
- serveStaticFile(pathname, res);
2638
+ serveStaticFile(pathname, res, req.headers['accept-encoding']);
2525
2639
  };
2526
2640
  let server;
2527
2641
  let httpServer = null;
@@ -2561,7 +2675,15 @@ async function main() {
2561
2675
  else {
2562
2676
  server = createHttpServer(requestHandler);
2563
2677
  }
2564
- const wss = new WebSocketServer({ noServer: true });
2678
+ // permessage-deflate: frames are JSON text (history, tool output, streamed
2679
+ // replies) that compresses several times over, which matters most on the slow
2680
+ // links phones are on. Browsers negotiate it natively; a client that does not
2681
+ // offer the extension simply gets uncompressed frames. Small frames (most
2682
+ // streaming deltas) are left alone: deflating them costs CPU for no gain.
2683
+ const wss = new WebSocketServer({
2684
+ noServer: true,
2685
+ perMessageDeflate: { threshold: 1024 },
2686
+ });
2565
2687
  // Connection-liveness heartbeat. A half-open TCP socket (peer vanished without
2566
2688
  // a clean FIN/RST: process restart, network blip, dropped upstream) stays in
2567
2689
  // ESTAB and fires neither 'close' nor 'error', so the connected agent/session
@@ -2633,6 +2755,10 @@ async function main() {
2633
2755
  else if (raw) {
2634
2756
  clientKey = raw;
2635
2757
  }
2758
+ if (wantsFrameChunks(url.searchParams))
2759
+ chunkingSockets.add(ws);
2760
+ if (wantsImageRefs(url.searchParams))
2761
+ imageRefSockets.add(ws);
2636
2762
  }
2637
2763
  catch { }
2638
2764
  if (clientKey) {
@@ -2718,7 +2844,9 @@ async function main() {
2718
2844
  ws.on('close', async () => {
2719
2845
  if (client.sessionId) {
2720
2846
  if (client.isCliBridge) {
2721
- await sessionPool.unregisterCliSession(client.sessionId);
2847
+ // Only this socket's own registration: a reconnect may already
2848
+ // have replaced it (see unregisterCliSession).
2849
+ await sessionPool.unregisterCliSession(client.sessionId, ws);
2722
2850
  }
2723
2851
  else {
2724
2852
  sessionPool.removeClient(client.sessionId, clientId);