synabun 2.4.1 → 2.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 (295) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +56 -14
  4. package/browser-extension/engine.js +158 -8
  5. package/browser-extension/manifest.json +3 -1
  6. package/browser-extension/protocol.js +91 -6
  7. package/browser-extension/service-worker.js +13 -5
  8. package/browser-extension/tokens.css +1 -1
  9. package/docs/browser-extension-bridge.md +24 -4
  10. package/lib/data-home-files.js +4 -2
  11. package/lib/first-launch-protection.js +8 -2
  12. package/lib/update-snapshot.js +11 -4
  13. package/mcp-server/dist/http.d.ts.map +1 -1
  14. package/mcp-server/dist/http.js +25 -2
  15. package/mcp-server/dist/http.js.map +1 -1
  16. package/mcp-server/dist/index.d.ts.map +1 -1
  17. package/mcp-server/dist/index.js +62 -17
  18. package/mcp-server/dist/index.js.map +1 -1
  19. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  20. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  21. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  22. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  23. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  24. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  25. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  26. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  27. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  28. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  29. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  30. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  31. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  32. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  33. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  34. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  35. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  36. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  37. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  38. package/mcp-server/dist/services/memory-schema.js +190 -13
  39. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  40. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  41. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  42. package/mcp-server/dist/services/memory-sessions.js +56 -20
  43. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  44. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  45. package/mcp-server/dist/services/memory-verification.js +8 -5
  46. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  47. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  48. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  49. package/mcp-server/dist/services/neural-interface.js +19 -2
  50. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  51. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  52. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  53. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  54. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  55. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  56. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  57. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  58. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  59. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  60. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  61. package/mcp-server/dist/services/sqlite-write.js +94 -0
  62. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  63. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  64. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  65. package/mcp-server/dist/services/sqlite.js +249 -8
  66. package/mcp-server/dist/services/sqlite.js.map +1 -1
  67. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  68. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  69. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  70. package/mcp-server/dist/services/typesafe-config.js +32 -10
  71. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  72. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  73. package/mcp-server/dist/services/typesafe.js +9 -7
  74. package/mcp-server/dist/services/typesafe.js.map +1 -1
  75. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  76. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  77. package/mcp-server/dist/services/vector-cache.js +161 -8
  78. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  79. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  80. package/mcp-server/dist/tools/agents.d.ts +11 -7
  81. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  82. package/mcp-server/dist/tools/agents.js +27 -9
  83. package/mcp-server/dist/tools/agents.js.map +1 -1
  84. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  85. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  86. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  87. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  88. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  89. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  90. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  91. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  92. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  93. package/mcp-server/dist/tools/browser-interact.js +6 -1
  94. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  95. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  96. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  97. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  98. package/mcp-server/package-lock.json +2 -2
  99. package/mcp-server/package.json +1 -1
  100. package/mcp-server/src/http.ts +20 -2
  101. package/mcp-server/src/index.ts +59 -17
  102. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  103. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  104. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  105. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  106. package/mcp-server/src/services/memory-schema.ts +194 -12
  107. package/mcp-server/src/services/memory-sessions.ts +54 -21
  108. package/mcp-server/src/services/memory-verification.ts +7 -4
  109. package/mcp-server/src/services/neural-interface.ts +22 -2
  110. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  111. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  112. package/mcp-server/src/services/sqlite-write.ts +60 -0
  113. package/mcp-server/src/services/sqlite.ts +246 -8
  114. package/mcp-server/src/services/typesafe-config.ts +25 -6
  115. package/mcp-server/src/services/typesafe.ts +9 -7
  116. package/mcp-server/src/services/vector-cache.ts +154 -9
  117. package/mcp-server/src/tools/agents.ts +26 -9
  118. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  119. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  120. package/mcp-server/src/tools/browser-interact.ts +5 -1
  121. package/neural-interface/i18n/en.json +263 -1
  122. package/neural-interface/i18n/pt-BR.json +264 -2
  123. package/neural-interface/lib/agents/split.js +32 -4
  124. package/neural-interface/lib/assistant-api.js +19 -8
  125. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  126. package/neural-interface/lib/assistant-catalog.js +2 -2
  127. package/neural-interface/lib/assistant-config.js +0 -7
  128. package/neural-interface/lib/assistant-dispatch.js +257 -95
  129. package/neural-interface/lib/assistant-persona.js +16 -4
  130. package/neural-interface/lib/assistant-pricing.js +65 -14
  131. package/neural-interface/lib/assistant-router.js +131 -47
  132. package/neural-interface/lib/assistant-run-wait.js +45 -28
  133. package/neural-interface/lib/assistant-runtime.js +39 -33
  134. package/neural-interface/lib/backup-contents.js +158 -0
  135. package/neural-interface/lib/backup-crypto-io.js +330 -0
  136. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  137. package/neural-interface/lib/backup-crypto.js +525 -0
  138. package/neural-interface/lib/backup-download.js +268 -0
  139. package/neural-interface/lib/backup-encryption.js +318 -0
  140. package/neural-interface/lib/backup-groups.js +287 -0
  141. package/neural-interface/lib/backup-restore-session.js +176 -0
  142. package/neural-interface/lib/backup-restore-stage.js +60 -0
  143. package/neural-interface/lib/backup-service.js +788 -233
  144. package/neural-interface/lib/backup-zip-reader.js +30 -18
  145. package/neural-interface/lib/backup-zip-writer.js +34 -10
  146. package/neural-interface/lib/browser-extension-adapter.js +89 -13
  147. package/neural-interface/lib/browser-extension-bridge.js +18 -7
  148. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  149. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  150. package/neural-interface/lib/cli-update-planner.js +105 -6
  151. package/neural-interface/lib/client-diagnostics.js +42 -0
  152. package/neural-interface/lib/confined-fs.js +7 -2
  153. package/neural-interface/lib/coordination/README.md +8 -2
  154. package/neural-interface/lib/coordination/contract.js +161 -0
  155. package/neural-interface/lib/coordination/database.js +999 -0
  156. package/neural-interface/lib/coordination/operations.js +436 -0
  157. package/neural-interface/lib/coordination/service.js +68 -537
  158. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  159. package/neural-interface/lib/coordination/store.js +219 -1111
  160. package/neural-interface/lib/db.js +70 -32
  161. package/neural-interface/lib/health-count.js +37 -0
  162. package/neural-interface/lib/loop-stall.js +139 -0
  163. package/neural-interface/lib/maritaca/client.js +2 -2
  164. package/neural-interface/lib/maritaca/models.js +12 -17
  165. package/neural-interface/lib/maritaca/opencode.js +4 -2
  166. package/neural-interface/lib/memory-api.js +9 -1
  167. package/neural-interface/lib/memory-session-capture.js +42 -10
  168. package/neural-interface/lib/memory-store-gate.js +313 -0
  169. package/neural-interface/lib/memory-store-migrate.js +65 -0
  170. package/neural-interface/lib/memory-timers.js +7 -7
  171. package/neural-interface/lib/native-loop-providers.js +13 -16
  172. package/neural-interface/lib/native-loop-runtime.js +28 -7
  173. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  174. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  175. package/neural-interface/lib/opencode-provider-view.js +14 -3
  176. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  177. package/neural-interface/lib/opencode2-client.js +2 -1
  178. package/neural-interface/lib/recall-impact.js +122 -0
  179. package/neural-interface/lib/scratch-evidence.js +420 -0
  180. package/neural-interface/lib/scratch-process-guard.js +139 -0
  181. package/neural-interface/lib/scratch-references.js +279 -0
  182. package/neural-interface/lib/scratch-retention-core.js +385 -0
  183. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  184. package/neural-interface/lib/scratch-retention.js +151 -0
  185. package/neural-interface/lib/session-cache-builder.js +31 -43
  186. package/neural-interface/lib/session-cache-worker.js +157 -0
  187. package/neural-interface/lib/session-indexer.js +28 -21
  188. package/neural-interface/lib/session-search-index.js +85 -0
  189. package/neural-interface/lib/skills/creation.js +1 -1
  190. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  191. package/neural-interface/lib/style-guide/store.js +43 -3
  192. package/neural-interface/lib/system-restore.js +50 -0
  193. package/neural-interface/lib/teams/api.js +15 -6
  194. package/neural-interface/lib/teams/claims.js +67 -31
  195. package/neural-interface/lib/teams/index.js +7 -7
  196. package/neural-interface/lib/teams/integration.js +40 -40
  197. package/neural-interface/lib/teams/landing.js +6 -6
  198. package/neural-interface/lib/teams/recovery.js +24 -23
  199. package/neural-interface/lib/teams/scheduler.js +194 -95
  200. package/neural-interface/lib/teams/state.js +14 -14
  201. package/neural-interface/lib/teams/worktrees.js +27 -27
  202. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  203. package/neural-interface/lib/worker-confinement.js +47 -2
  204. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  205. package/neural-interface/lib/worker-resume.js +5 -0
  206. package/neural-interface/lib/worker-stop.js +86 -0
  207. package/neural-interface/package-lock.json +2 -2
  208. package/neural-interface/package.json +1 -1
  209. package/neural-interface/public/index.html +233 -24
  210. package/neural-interface/public/onboarding.html +259 -34
  211. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  212. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  213. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  214. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  215. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  216. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  217. package/neural-interface/public/shared/api.js +1 -1
  218. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  219. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  220. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  221. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  222. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  223. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  224. package/neural-interface/public/shared/assistant/asst-render.js +105 -38
  225. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  226. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  229. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  230. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  231. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  232. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  233. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  234. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  235. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  236. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  237. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  238. package/neural-interface/public/shared/effort-i18n.js +118 -0
  239. package/neural-interface/public/shared/html-shell.js +4 -52
  240. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  241. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  242. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  243. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  244. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  245. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  246. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  247. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  248. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  249. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  250. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  251. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  252. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  253. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  254. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  255. package/neural-interface/public/shared/output-format.js +294 -0
  256. package/neural-interface/public/shared/provider-icons.js +6 -0
  257. package/neural-interface/public/shared/schedules-view.js +2 -1
  258. package/neural-interface/public/shared/server-presence.js +77 -0
  259. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  260. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  261. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  262. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  263. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  264. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  265. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  266. package/neural-interface/public/shared/studio-attention.js +6 -0
  267. package/neural-interface/public/shared/styles.css +341 -437
  268. package/neural-interface/public/shared/transcript-rows.js +28 -3
  269. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  270. package/neural-interface/public/shared/ui-agents.js +1 -2
  271. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  272. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  273. package/neural-interface/public/shared/ui-loading.js +124 -17
  274. package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
  275. package/neural-interface/public/shared/ui-navbar.js +2 -1
  276. package/neural-interface/public/shared/ui-output.js +533 -0
  277. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  278. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  279. package/neural-interface/public/shared/ui-sessions.js +2 -2
  280. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  281. package/neural-interface/public/shared/ui-settings.js +224 -65
  282. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  283. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  284. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  285. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  286. package/neural-interface/public/shared/worker-end.js +9 -4
  287. package/neural-interface/public/variant/2d/main.js +5 -0
  288. package/neural-interface/public/variant/3d/app.js +10 -0
  289. package/neural-interface/public/variant/3d/main.js +5 -1
  290. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  291. package/neural-interface/server.js +477 -139
  292. package/npm-shrinkwrap.json +2 -2
  293. package/package.json +1 -1
  294. package/scripts/restore-data-home-from-backup.mjs +175 -8
  295. package/setup.js +18 -4
@@ -1,10 +1,10 @@
1
- import { createReadStream, createWriteStream, mkdirSync, renameSync, rmSync } from 'node:fs';
2
- import { open } from 'node:fs/promises';
1
+ import { createWriteStream, mkdirSync, renameSync, rmSync } from 'node:fs';
3
2
  import { createHash } from 'node:crypto';
4
3
  import { Readable, Transform, Writable } from 'node:stream';
5
4
  import { pipeline } from 'node:stream/promises';
6
5
  import { createInflateRaw, crc32 } from 'node:zlib';
7
6
  import { dirname } from 'node:path';
7
+ import { openPlainBackupSource } from './backup-crypto-io.js';
8
8
 
9
9
  /**
10
10
  * Streaming ZIP reader for backup archives.
@@ -28,15 +28,9 @@ const EOCD_MAX_SCAN = EOCD_MIN + 0xffff;
28
28
  const MAX_CENTRAL_DIRECTORY_BYTES = 512 * 1024 * 1024;
29
29
  const MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
30
30
 
31
- async function readAt(handle, position, length) {
32
- const buffer = Buffer.alloc(length);
33
- let offset = 0;
34
- while (offset < length) {
35
- const { bytesRead } = await handle.read(buffer, offset, length - offset, position + offset);
36
- if (bytesRead === 0) throw new Error('Invalid ZIP: unexpected end of file');
37
- offset += bytesRead;
38
- }
39
- return buffer;
31
+ // `handle` is a source (backup-crypto-io.js): the file itself, or the plaintext of an encrypted backup by position.
32
+ function readAt(handle, position, length) {
33
+ return handle.read(position, length);
40
34
  }
41
35
 
42
36
  function readUInt64(buffer, offset) {
@@ -157,10 +151,16 @@ function integrityCheck(entry) {
157
151
  });
158
152
  }
159
153
 
160
- export async function openZipArchive(path) {
161
- const handle = await open(path, 'r');
154
+ /**
155
+ * `source`: what the ZIP is read through, { size, read(position, length), stream(start, endInclusive), close() }
156
+ * (backup-crypto-io.js). Without one it is the file at `path`; an encrypted backup's source gives the ZIP inside it,
157
+ * decrypted and checked chunk by chunk as it is read, so no plaintext copy of the archive is ever written. Closing
158
+ * the archive closes its source.
159
+ */
160
+ export async function openZipArchive(path, { source = null } = {}) {
161
+ const handle = source || await openPlainBackupSource(path);
162
162
  try {
163
- const { size: fileSize } = await handle.stat();
163
+ const fileSize = handle.size;
164
164
  const directory = await locateCentralDirectory(handle, fileSize);
165
165
  const buffer = await readAt(handle, directory.offset, directory.size);
166
166
  const entries = parseCentralDirectory(buffer, directory.entryCount);
@@ -178,6 +178,9 @@ export async function openZipArchive(path) {
178
178
  return {
179
179
  path,
180
180
  size: fileSize,
181
+ /** True when the ZIP was read out of an encrypted backup. */
182
+ encrypted: handle.encrypted === true,
183
+ source: handle,
181
184
  entries,
182
185
  getEntry: name => byName.get(name) || null,
183
186
  /** Stream one entry's uncompressed bytes into `sink`, checking CRC and size. */
@@ -186,7 +189,7 @@ export async function openZipArchive(path) {
186
189
  if (entry.method !== 0 && entry.method !== 8) throw new Error(`Unsupported ZIP: ${entry.name} uses compression method ${entry.method}`);
187
190
  const { start, length } = await dataRange(entry);
188
191
  const stages = [length > 0
189
- ? createReadStream(path, { start, end: start + length - 1, highWaterMark: 1024 * 1024 })
192
+ ? handle.stream(start, start + length - 1)
190
193
  : Readable.from([])];
191
194
  if (entry.method === 8) stages.push(createInflateRaw());
192
195
  stages.push(integrityCheck(entry), sink);
@@ -254,14 +257,23 @@ export function backupEntryName(prefix, archivePath) {
254
257
  return prefix ? `${prefix}/${archivePath}` : archivePath;
255
258
  }
256
259
 
257
- /** Stream every manifest-listed entry through sha256 and compare. `onBytes`: as for hashZipEntry. */
258
- export async function verifyBackupChecksums(zip, { prefix, manifest, label = 'Backup verification failed', onBytes = null }) {
260
+ /**
261
+ * Stream every manifest-listed entry through sha256 and compare. `onBytes`: as for hashZipEntry. `signal`: an
262
+ * AbortSignal looked at between two entries; an aborted check throws an error whose code is BACKUP_CANCELLED.
263
+ */
264
+ export async function verifyBackupChecksums(zip, { prefix, manifest, label = 'Backup verification failed', onBytes = null, signal = null }) {
259
265
  for (const [archivePath, expected] of Object.entries(manifest.checksums || {})) {
266
+ if (signal?.aborted) throw Object.assign(new Error('The backup was cancelled.'), { code: 'BACKUP_CANCELLED' });
260
267
  const entry = zip.getEntry(backupEntryName(prefix, archivePath));
261
268
  if (!entry) throw new Error(`${label}: ${archivePath} is missing`);
262
269
  let actual;
263
270
  try { actual = `sha256:${await hashZipEntry(zip, entry, { onBytes })}`; }
264
- catch (error) { throw new Error(`${label}: ${archivePath} is unreadable (${error.message})`); }
271
+ catch (error) {
272
+ // A failure of the encrypted container under the ZIP keeps its code (BACKUP_ENC_DAMAGED): the caller tells a
273
+ // changed file from an unreadable entry by it.
274
+ const code = typeof error?.code === 'string' && error.code.startsWith('BACKUP_') ? { code: error.code } : {};
275
+ throw Object.assign(new Error(`${label}: ${archivePath} is unreadable (${error.message})`), code);
276
+ }
265
277
  if (actual !== expected) throw new Error(`${label}: checksum mismatch for ${archivePath}`);
266
278
  }
267
279
  }
@@ -26,6 +26,9 @@ const SIG_EOCD = 0x06054b50;
26
26
  const SIG_ZIP64_EOCD = 0x06064b50;
27
27
  const SIG_ZIP64_LOCATOR = 0x07064b50;
28
28
  const UTF8_NAMES = 0x0800;
29
+ const SIG_DESCRIPTOR = 0x08074b50;
30
+ /** General-purpose bit 3: the entry's CRC-32 follows its data, in a data descriptor. */
31
+ const HAS_DESCRIPTOR = 0x0008;
29
32
  const MAX32 = 0xffffffff;
30
33
  const MAX16 = 0xffff;
31
34
  const CHUNK = 4 * 1024 * 1024;
@@ -57,9 +60,14 @@ function zip64Extra(fields) {
57
60
  * sha256 }]): a manifest that lists the checksums of the entries before it
58
61
  * onProgress({ bytes, totalBytes }) as data goes in, at most every 64 MB and at the end
59
62
  * forceZip64 write ZIP64 records even when nothing needs them (tests)
63
+ * sink where the bytes go instead of a file at `path`: { write(buffer) → Promise, finish() → Promise,
64
+ * abort() → Promise } (the encrypted backup writer of backup-crypto-io.js, which copies what it is
65
+ * given). A sink only takes bytes in order, so nothing can be patched afterwards: a streamed entry's
66
+ * CRC-32 then follows its data in a data descriptor (its sizes are known and stay in its header).
67
+ * backup-zip-reader.js reads sizes and CRCs from the central directory, so it reads both shapes
60
68
  * Resolves { bytes, entries: [{ name, size, crc32, sha256 }] } (sha256 in hex).
61
69
  */
62
- export async function writeZipArchive(path, entries, { onProgress = null, now = () => new Date(), forceZip64 = false } = {}) {
70
+ export async function writeZipArchive(path, entries, { onProgress = null, now = () => new Date(), forceZip64 = false, sink = null } = {}) {
63
71
  const report = typeof onProgress === 'function' ? onProgress : () => {};
64
72
  const stamp = dosDateTime(now());
65
73
  // Sizes first, so the progress has a total and a stored entry's headers carry its real size.
@@ -88,11 +96,13 @@ export async function writeZipArchive(path, entries, { onProgress = null, now =
88
96
  }
89
97
  };
90
98
 
91
- const handle = await open(path, 'wx');
99
+ const handle = sink ? null : await open(path, 'wx');
92
100
  const written = [];
93
101
  let offset = 0;
102
+ let finished = false;
94
103
  try {
95
104
  const write = async (buffer) => {
105
+ if (sink) { await sink.write(buffer); offset += buffer.length; return; }
96
106
  let at = 0;
97
107
  while (at < buffer.length) {
98
108
  const { bytesWritten } = await handle.write(buffer, at, buffer.length - at, offset + at);
@@ -125,13 +135,15 @@ export async function writeZipArchive(path, entries, { onProgress = null, now =
125
135
  payload = deflateRawSync(data, { level: 6 });
126
136
  }
127
137
  const method = item.store ? 0 : 8;
138
+ // Streamed into a sink: the CRC is only known after the last byte and cannot be written back.
139
+ const flags = UTF8_NAMES | (sink && !payload ? HAS_DESCRIPTOR : 0);
128
140
  const compressedSize = payload ? payload.length : item.size;
129
141
  const zip64 = forceZip64 || item.size >= MAX32 || compressedSize >= MAX32 || localOffset >= MAX32;
130
142
  const localExtra = zip64 ? zip64Extra([item.size, compressedSize]) : Buffer.alloc(0);
131
143
  const header = Buffer.alloc(30);
132
144
  header.writeUInt32LE(SIG_LOCAL, 0);
133
145
  header.writeUInt16LE(zip64 ? 45 : method === 8 ? 20 : 10, 4);
134
- header.writeUInt16LE(UTF8_NAMES, 6);
146
+ header.writeUInt16LE(flags, 6);
135
147
  header.writeUInt16LE(method, 8);
136
148
  header.writeUInt16LE(stamp.time, 10);
137
149
  header.writeUInt16LE(stamp.date, 12);
@@ -174,11 +186,20 @@ export async function writeZipArchive(path, entries, { onProgress = null, now =
174
186
  } finally {
175
187
  await source.close();
176
188
  }
177
- const crcBuffer = Buffer.alloc(4);
178
- crcBuffer.writeUInt32LE(crc >>> 0, 0);
179
- await handle.write(crcBuffer, 0, 4, localOffset + 14);
189
+ if (sink) {
190
+ const descriptor = Buffer.alloc(zip64 ? 24 : 16);
191
+ descriptor.writeUInt32LE(SIG_DESCRIPTOR, 0);
192
+ descriptor.writeUInt32LE(crc >>> 0, 4);
193
+ if (zip64) { descriptor.writeBigUInt64LE(BigInt(compressedSize), 8); descriptor.writeBigUInt64LE(BigInt(item.size), 16); }
194
+ else { descriptor.writeUInt32LE(compressedSize, 8); descriptor.writeUInt32LE(item.size, 12); }
195
+ await write(descriptor);
196
+ } else {
197
+ const crcBuffer = Buffer.alloc(4);
198
+ crcBuffer.writeUInt32LE(crc >>> 0, 0);
199
+ await handle.write(crcBuffer, 0, 4, localOffset + 14);
200
+ }
180
201
  }
181
- written.push({ name: item.name, nameBytes, method, crc: crc >>> 0, size: item.size, compressedSize, localOffset, zip64, sha256: digest.digest('hex') });
202
+ written.push({ name: item.name, nameBytes, method, flags, crc: crc >>> 0, size: item.size, compressedSize, localOffset, zip64, sha256: digest.digest('hex') });
182
203
  }
183
204
 
184
205
  // The central directory: one record per entry, then the end records.
@@ -194,7 +215,7 @@ export async function writeZipArchive(path, entries, { onProgress = null, now =
194
215
  record.writeUInt32LE(SIG_CENTRAL, 0);
195
216
  record.writeUInt16LE((3 << 8) | 45, 4);
196
217
  record.writeUInt16LE(entry.zip64 ? 45 : entry.method === 8 ? 20 : 10, 6);
197
- record.writeUInt16LE(UTF8_NAMES, 8);
218
+ record.writeUInt16LE(entry.flags, 8);
198
219
  record.writeUInt16LE(entry.method, 10);
199
220
  record.writeUInt16LE(stamp.time, 12);
200
221
  record.writeUInt16LE(stamp.date, 14);
@@ -245,10 +266,13 @@ export async function writeZipArchive(path, entries, { onProgress = null, now =
245
266
  end.writeUInt32LE(needs64 ? MAX32 : directoryOffset, 16);
246
267
  end.writeUInt16LE(0, 20);
247
268
  await write(end);
248
- await handle.sync();
269
+ if (sink) await sink.finish();
270
+ else await handle.sync();
271
+ finished = true;
249
272
  progress(true);
250
273
  } finally {
251
- await handle.close();
274
+ if (handle) await handle.close();
275
+ else if (!finished) await sink.abort().catch(() => {});
252
276
  }
253
277
  return {
254
278
  bytes: offset,
@@ -1,17 +1,31 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { basename, isAbsolute, resolve } from 'node:path';
3
- import { readConfinedFile } from './confined-fs.js';
2
+ import { basename, extname, isAbsolute, resolve } from 'node:path';
3
+ import express from 'express';
4
+ import { readConfinedFileWithMetadata } from './confined-fs.js';
4
5
  import { fileURLToPath } from 'node:url';
5
- import { fail, handle, HISTORY, MAX_FILE, safeError } from '../../browser-extension/protocol.js';
6
+ import { EVALUATE_SCRIPT_MAX, EVALUATE_TIMEOUT_MAX, EVALUATE_WORLDS, fail, handle, HISTORY, LOAD_STATES, MAX_FILE, NETWORK_IDLE_TIMEOUT_MAX, safeError } from '../../browser-extension/protocol.js';
6
7
  import sharp from 'sharp';
7
8
  import { parseScreenshotOptions, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './browser-screenshot.js';
8
9
  import { ownerOnlyCreateFields } from './browser-automation-routes.js';
9
10
 
10
11
  export const EXTENSION_FOLDER = fileURLToPath(new URL('../../browser-extension/', import.meta.url));
12
+ // Use the server's static-file MIME table. Its bundled table predates these image formats.
13
+ export function uploadMimeType(name) {
14
+ const ext = extname(name).toLowerCase();
15
+ if (['.heic', '.heif', '.avif'].includes(ext)) return 'image/' + ext.slice(1);
16
+ return express.static.mime.lookup(ext);
17
+ }
11
18
  const aliases = { 'screenshot-base64': 'screenshot' };
12
- const supported = new Set(['navigate', 'back', 'forward', 'reload', 'snapshot', 'click', 'hover', 'fill', 'type', 'press', 'select', 'scroll', 'wait', 'content', 'screenshot', 'upload']);
19
+ const supported = new Set(['navigate', 'back', 'forward', 'reload', 'snapshot', 'click', 'hover', 'fill', 'type', 'press', 'select', 'scroll', 'wait', 'content', 'screenshot', 'upload', 'evaluate']);
13
20
  const argumentKeys = ['url', 'ref', 'selector', 'nthMatch', 'value', 'text', 'key', 'direction', 'distance', 'maxChars', 'offset', 'timeout', 'state'];
14
21
  const unsupported = reason => Object.assign(new Error(reason), { code: 'UNSUPPORTED_IN_EXTENSION_MODE' });
22
+ // A whole number of milliseconds from a request body, 1 to `most`; undefined when none (or nothing usable) was given.
23
+ const milliseconds = (value, most) => { const n = Number(value); return Number.isFinite(n) && n >= 1 ? Math.min(most, Math.floor(n)) : undefined; };
24
+ // A refusal always says what its code means, also when the extension answered the code alone.
25
+ const worded = result => (result && result.ok === false && result.code && typeof result.error !== 'string' ? { ...result, error: safeError(result).error } : result);
26
+ // evaluate refusals after which the page's script certainly did not run (a paced write then takes no slot).
27
+ const NOTHING_RAN = ['USER_SCRIPTS_DISABLED', 'USER_SCRIPTS_UNSUPPORTED', 'EXTENSION_RELOAD_REQUIRED', 'EXTENSION_NOT_CONNECTED', 'BLANK_PAGE', 'FRAME_NOT_FOUND',
28
+ 'RESTRICTED_PAGE', 'SYNABUN_PAGE_BLOCKED', 'SITE_NOT_APPROVED', 'NOT_OWNED', 'AUTH_FAILED', 'INVALID_MESSAGE'];
15
29
  // What an agent may see of its tab's address. Full control: the address. Restricted mode: an approved site's URL, or
16
30
  // the blank start page; a page that history (or a redirect) took the tab to on an unapproved site stays the owner's:
17
31
  // the session listing shows no URL for it.
@@ -32,7 +46,11 @@ export function listedUrl(url) {
32
46
  const HISTORY_DESTINATION = 'The page this history step reached is not on an approved site (or an approval was revoked meanwhile). No page content was returned. The tab stays there and refuses commands until the owner shares that site in the extension popup (or switches to full control); release the session to stop using it.';
33
47
 
34
48
  /** Owns routing only; extension sessions intentionally expose no Playwright/CDP surface. */
35
- export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, ownerPage, selected, dataHome, log = () => {} }) {
49
+ // `evaluateGate` holds page JavaScript to the rules the Playwright evaluate route holds a loop's tab to (server.js):
50
+ // `refusal({ session, req, tabId, script })` answers the X publish gate's refusal (or null), `run({ session, req, execute })`
51
+ // spaces a social write (`pace` in the body) and answers { result } or { paced } with it. Without one, nothing is gated
52
+ // (tests of the adapter alone).
53
+ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, ownerPage, selected, dataHome, log = () => {}, evaluateGate = null }) {
36
54
  const salt = randomBytes(32).toString('hex');
37
55
  const agent = owner => createHash('sha256').update(`${salt}:${owner}`).digest('hex');
38
56
  let sessionId = null, chain = Promise.resolve();
@@ -130,9 +148,9 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
130
148
  names: paths.map(path => basename(path)),
131
149
  read(index) {
132
150
  try {
133
- const bytes = readConfinedFile(uploadRoot, resolve(paths[index]), { maxBytes: remaining });
134
- remaining -= bytes.length;
135
- return bytes;
151
+ const file = readConfinedFileWithMetadata(uploadRoot, resolve(paths[index]), { maxBytes: remaining });
152
+ remaining -= file.bytes.length;
153
+ return { ...file, type: uploadMimeType(paths[index]) };
136
154
  } catch (error) {
137
155
  if (error.status === 404) fail('UPLOAD_FILE_MISSING');
138
156
  if (error.status === 413) fail('UPLOAD_TOO_LARGE');
@@ -141,19 +159,72 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
141
159
  },
142
160
  };
143
161
  }
144
- async function operation(s, owner, tab, action, body = {}) {
162
+ // Page JavaScript (extension 1.4.0 and later): the script of the Playwright route's body, as one expression, through
163
+ // chrome.userScripts.execute in the agent's own tab. The answer has that route's shape: { ok, result } with the
164
+ // script's value, or { ok: false, error }. Before anything is sent: the bridge's own rules for the tab (and its
165
+ // version gate), then the publish gate; a paced write then waits its gap and runs only if the agent still holds the tab.
166
+ async function evaluate(s, owner, tab, body, req) {
167
+ const script = body.script;
168
+ if (typeof script !== 'string' || !script.trim()) return { ok: false, error: 'script required' };
169
+ if (script.length > EVALUATE_SCRIPT_MAX) return { ok: false, error: `script exceeds ${EVALUATE_SCRIPT_MAX} characters` };
170
+ const args = { expression: script };
171
+ const timeout = milliseconds(body.timeout, EVALUATE_TIMEOUT_MAX), maxChars = milliseconds(body.maxChars, 1000000);
172
+ if (timeout) args.timeout = timeout;
173
+ if (maxChars) args.maxChars = maxChars;
174
+ if (body.world !== undefined && body.world !== null) { if (!EVALUATE_WORLDS.includes(body.world)) return { ok: false, error: `Invalid world. Use: ${EVALUATE_WORLDS.join(', ')}` }; args.world = body.world; }
175
+ if (body.frame !== undefined && body.frame !== null) { if (!Number.isSafeInteger(Number(body.frame)) || Number(body.frame) < 0) return { ok: false, error: 'Invalid frame id' }; args.frame = Number(body.frame); }
176
+ bridge.authorize('evaluate', tab, agent(owner), args);
177
+ const refusal = evaluateGate?.refusal?.({ session: s, req, tabId: tab, script }) || null;
178
+ if (refusal) return { ok: false, ...refusal };
179
+ let cut = null;
180
+ const execute = async () => {
181
+ // A paced write may have waited a minute: it runs only in the tab this request named, if the agent still holds it.
182
+ if (sessions.get(s.id) !== s || !ownsTab(s, owner, tab)) throw Object.assign(new Error('TAB_CLOSED'), { code: 'TAB_CLOSED', writeStarted: false });
183
+ let result;
184
+ try { result = finish(s, tab, await bridge.request('evaluate', tab, agent(owner), args)); }
185
+ catch (error) { if (NOTHING_RAN.includes(error?.code)) error.writeStarted = false; throw error; }
186
+ if (result.ok) {
187
+ // `value` is the JSON text of what the script returned. One that was cut is the beginning of that text (not
188
+ // valid JSON): it is answered as that text, flagged.
189
+ if (result.truncated) { cut = { truncated: true, valueLength: result.valueLength }; return result.value; }
190
+ try { return JSON.parse(result.value); } catch { fail('OPERATION_FAILED'); }
191
+ }
192
+ let answer = worded(result);
193
+ if (result.code === 'PAGE_ERROR') {
194
+ // What the page's script threw, in the words of a Playwright failure. No stack: the script did not compile.
195
+ const message = result.errorMessage || 'The script threw.';
196
+ answer = { ok: false, code: 'PAGE_ERROR', error: `page.evaluate: ${message}${result.errorStack ? '' : ' browser_evaluate takes one JavaScript expression: wrap statements in a function, (() => { …; return value; })().'}`,
197
+ ...(result.errorStack ? { errorStack: result.errorStack } : {}) };
198
+ }
199
+ throw Object.assign(new Error(result.code || 'OPERATION_FAILED'), { answer, ...(NOTHING_RAN.includes(result.code) ? { writeStarted: false } : {}) });
200
+ };
201
+ let outcome;
202
+ try { outcome = evaluateGate?.run ? await evaluateGate.run({ session: s, req, execute }) : { result: await execute() }; }
203
+ catch (error) { if (error?.answer) return error.answer; throw error; }
204
+ if (outcome.paced?.pending) return { ok: true, paced: outcome.paced };
205
+ return { ok: true, result: outcome.result === undefined ? null : outcome.result, ...(cut || {}), ...(outcome.paced ? { paced: outcome.paced } : {}) };
206
+ }
207
+ async function operation(s, owner, tab, action, body = {}, req = null) {
145
208
  if (!bridge.status().connected) fail('EXTENSION_NOT_CONNECTED');
146
209
  if (!s || !tab || !s.tabs.has(tab)) fail('TAB_CLOSED');
147
210
  if (!ownsTab(s, owner, tab)) fail('NOT_OWNED');
148
211
  const op = aliases[action] || action;
149
- if (!supported.has(op)) throw unsupported('This operation is not supported by the extension backend. No debugger or arbitrary JavaScript is enabled.');
212
+ if (!supported.has(op)) throw unsupported('This operation is not supported by the extension backend. No debugger is attached; page JavaScript runs through browser_evaluate only.');
213
+ if (op === 'evaluate') return evaluate(s, owner, tab, body, req);
150
214
  let shot;
151
215
  if (op === 'screenshot') {
152
216
  shot = parseScreenshotOptions(body);
153
217
  if (shot.fullPage || shot.width || shot.height || ['selector', 'ref', 'clip', 'region'].some(k => body[k])) throw unsupported('Only the visible viewport can be captured: the extension has no debugger for viewport emulation, element crops or full-page capture. Use maxWidth to downscale the captured image.');
154
218
  if (shot.path && screenshotPathRefusal(shot.path, { dataHome })) fail('SCREENSHOT_PATH_REFUSED');
155
219
  }
156
- if (op === 'wait' && body.loadState) throw unsupported('Extension waits support selectors and fixed delays, not browser network/load states.');
220
+ if (op === 'wait' && body.loadState) {
221
+ // A load-state wait (extension 1.4.0 and later): 'load' and 'networkidle', for the tab, not for an element (as in
222
+ // the Playwright route, a selector sent with it is not used). The extension has no DOMContentLoaded signal.
223
+ if (body.loadState === 'domcontentloaded') throw unsupported('Extension waits support loadState "load" and "networkidle" (and selectors and fixed delays), not "domcontentloaded".');
224
+ if (!LOAD_STATES.includes(body.loadState)) return { ok: false, error: 'Invalid loadState. Use: load, domcontentloaded, networkidle' };
225
+ const timeout = milliseconds(body.timeout, NETWORK_IDLE_TIMEOUT_MAX);
226
+ return worded(finish(s, tab, await bridge.request('wait', tab, agent(owner), { loadState: body.loadState, ...(timeout ? { timeout } : {}) })));
227
+ }
157
228
  if (op === 'snapshot' && body.mode && body.mode !== 'ai') throw unsupported('Extension snapshots support mode="ai" (DOM refs) only.');
158
229
  if (HISTORY.includes(op)) {
159
230
  // Back and forward take no arguments on the wire; the server and the extension check the landing page.
@@ -170,6 +241,10 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
170
241
  args.files = upload.names;
171
242
  }
172
243
  const result = finish(s, tab, await bridge.request(op, tab, agent(owner), args, upload));
244
+ if (op === 'upload' && result.ok && !result.files) {
245
+ // A still-loaded 1.3.0 extension may already have dispatched events. Do not replay it.
246
+ return { ok: false, error: 'The extension returned no file details. Check the page before retrying and reload SynaBun Browser Bridge.' };
247
+ }
173
248
  if (op === 'wait' && result.ok) result.state = body.state || 'visible';
174
249
  if (op === 'screenshot' && result.ok) {
175
250
  const raw = Buffer.from(result.base64, 'base64'), meta = await sharp(raw).metadata();
@@ -256,8 +331,9 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
256
331
  const tab = body.tabId || s._tabOwners.get(owner);
257
332
  if (!['GET', 'POST'].includes(req.method)) throw unsupported('Tab management is through the extension popup.');
258
333
  // Every extension session endpoint is intercepted, including CDP, raw screenshot and UI routes.
259
- const result = await operation(s, owner, tab, match[2], body);
260
- return res.status(result.ok ? 200 : result.code === 'TAB_CLOSED' ? 410 : 400).json(result);
334
+ const result = await operation(s, owner, tab, match[2], body, req);
335
+ // 409: the publish gate's refusal, as the Playwright routes answer it.
336
+ return res.status(result.ok ? 200 : result.code === 'TAB_CLOSED' ? 410 : result.quoteGuard ? 409 : 400).json(result);
261
337
  } catch (error) { try { log({ command: supported.has(match?.[2]) ? match[2] : 'session', tab: null, code: safeError(error).code }); } catch {} return denied(res, error); }
262
338
  }
263
339
  return { acquire, release, destroy, sync, operation, middleware, agent, session, ownerTabs, ownsTab };
@@ -5,7 +5,7 @@ import { compareVersions } from './browser-extension-folder.js';
5
5
  import { dirname } from 'node:path';
6
6
  import { lookup } from 'node:dns/promises';
7
7
  import { WebSocketServer } from 'ws';
8
- import { anyOrigin, channel, command, COMMAND_WAIT, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, safeError, string } from '../../browser-extension/protocol.js';
8
+ import { anyOrigin, channel, command, COMMAND_WAIT, commandWait as operationWait, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, LONG_OPS_SINCE, longOp, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, safeError, string } from '../../browser-extension/protocol.js';
9
9
 
10
10
  const manifest = JSON.parse(readFileSync(new URL('../../browser-extension/manifest.json', import.meta.url), 'utf8'));
11
11
  export const EXTENSION_ID = createHash('sha256').update(Buffer.from(manifest.key, 'base64')).digest('hex').slice(0, 32).replace(/[0-9a-f]/g, c => String.fromCharCode(97 + parseInt(c, 16)));
@@ -52,6 +52,8 @@ export function createBridgeStore(path) {
52
52
  /** Isolated loopback transport. Constructing it neither listens nor reads/writes user data (restore() does). */
53
53
  // `commandWait` is how long a request waits for the extension's answer (COMMAND_WAIT; smaller only in tests), on the
54
54
  // monotonic `clock`. Each command carries what is left of that wait when it is sent, as its `deadline`.
55
+ // A long operation (protocol.js longOp: `evaluate`, `wait` with `loadState`) waits its own time instead: its timeout
56
+ // plus a margin, at most LONG_WAIT (protocol.js commandWait). A smaller `commandWait` (tests) bounds those too.
55
57
  // `fullControl` is the mode before the owner chose one (on: agents may use any http(s) site and any tab of the paired
56
58
  // browser; off: only what the owner shares). `store` keeps the pairing and the mode across restarts (createBridgeStore).
57
59
  // SynaBun's own addresses stay out of reach in both modes: `forbiddenOrigins` (its public aliases, any port),
@@ -61,6 +63,7 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
61
63
  commandWait = COMMAND_WAIT, clock = () => performance.now(), fullControl = true, store = null, blockedPorts = () => [], selfHosts = () => [],
62
64
  lookupAddresses = host => lookup(host, { all: true }) } = {}) {
63
65
  if (!Number.isSafeInteger(commandWait) || commandWait < 1 || commandWait > COMMAND_WAIT) fail('INVALID_MESSAGE');
66
+ const waitOf = (op, args) => commandWait < COMMAND_WAIT ? commandWait : operationWait(op, args);
64
67
  let server, wss, listening, pair = null, credential = null, peer = null, state = empty(), enabled = true;
65
68
  // The owner's mode and its version. The newer version wins on either side: the server's (Settings) or the
66
69
  // extension's (its popup, reported in an inventory). Only the owner changes it: setMode() behind the owner route,
@@ -188,8 +191,9 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
188
191
  }
189
192
  try {
190
193
  authorize('upload', p.tab, p.owner, p.args);
191
- const bytes = p.upload.read(p.nextFile++);
192
- res.writeHead(200, { 'Cache-Control': 'no-store', 'Content-Type': 'application/octet-stream', 'Content-Length': bytes.length }).end(bytes);
194
+ const { bytes, type, lastModified } = p.upload.read(p.nextFile++);
195
+ res.writeHead(200, { 'Cache-Control': 'no-store', 'Content-Type': type, 'Content-Length': bytes.length,
196
+ 'X-Content-Type-Options': 'nosniff', 'X-SynaBun-Last-Modified': lastModified }).end(bytes);
193
197
  } catch (error) {
194
198
  res.writeHead(400, { 'Cache-Control': 'no-store' }).end(safeError(error).code);
195
199
  }
@@ -224,7 +228,8 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
224
228
  outbound = outbound.catch(() => {}).then(async () => {
225
229
  if (body.type === 'command') {
226
230
  check();
227
- body = command({ ...body, deadline: Math.max(1, Math.min(commandWait, Math.floor(pending.get(body.id).expires - clock()))) });
231
+ const p = pending.get(body.id);
232
+ body = command({ ...body, deadline: Math.max(1, Math.min(p.wait, Math.floor(p.expires - clock()))) });
228
233
  }
229
234
  await wire.encode(body, raw => { check(); if (ws.readyState !== 1) fail('NOT_CONNECTED'); ws.send(raw); });
230
235
  }); return outbound;
@@ -295,6 +300,9 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
295
300
  function authorize(op, tab, owner, args = {}) {
296
301
  authorizeAccess(op, tab, owner, args);
297
302
  if (op === 'upload' && compareVersions(peer.version, '1.3.0') < 0) fail('UPLOAD_RELOAD_REQUIRED');
303
+ // An extension from before the long operations ends the connection on a command it does not know (its payload()
304
+ // throws while it authenticates the message): it is never sent one. The owner reloads the extension instead.
305
+ if (longOp(op, args) && compareVersions(peer.version, LONG_OPS_SINCE) < 0) fail('EXTENSION_RELOAD_REQUIRED');
298
306
  }
299
307
  function authorizeAccess(op, tab, owner, args) {
300
308
  if (!enabled || !peer || peer.ws.readyState !== 1) fail('EXTENSION_NOT_CONNECTED');
@@ -325,7 +333,10 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
325
333
  // The revocation generation this command was issued in; an owner revocation that begins later cancels it.
326
334
  const issued = revocations, stale = () => !CONTROL.includes(op) && issued !== revocations;
327
335
  if (pending.size >= 32) fail('TIMEOUT');
328
- const msg = command({ type: 'command', id: nonce(), op, tab, owner, args, ...targets(), deadline: commandWait });
336
+ // This command's wait: an ordinary command's, or a long operation's own. The timer, `expires` and the deadline the
337
+ // command carries are all this one number.
338
+ const wait = waitOf(op, args);
339
+ const msg = command({ type: 'command', id: nonce(), op, tab, owner, args, ...targets(), deadline: wait });
329
340
  try {
330
341
  authorize(op, tab, owner, args);
331
342
  const version = revision, connection = peer, full = mode.fullControl;
@@ -347,8 +358,8 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
347
358
  const timer = setTimeout(() => {
348
359
  pending.delete(msg.id); reject(Object.assign(new Error('TIMEOUT'), { code: 'TIMEOUT' }));
349
360
  if (peer === via && via.ws.readyState === 1) void via.send({ type: 'cancel', id: msg.id }).catch(() => {});
350
- }, commandWait);
351
- pending.set(msg.id, { resolve, reject, timer, op, tab, owner, args, upload, nextFile: 0, issued, expires: clock() + commandWait });
361
+ }, wait);
362
+ pending.set(msg.id, { resolve, reject, timer, op, tab, owner, args, upload, nextFile: 0, issued, wait, expires: clock() + wait });
352
363
  via.send(msg).catch(error => { clearTimeout(timer); pending.delete(msg.id); reject(['CANCELLED', 'TIMEOUT'].includes(error?.code) ? coded(error.code)() : notConnected()); });
353
364
  });
354
365
  if (HISTORY.includes(op) && result.ok) {
@@ -747,6 +747,7 @@ export class ClaudeSession {
747
747
  SynaBun: {
748
748
  type: 'http',
749
749
  url: deps.mcpUrl,
750
+ ...(sessionOpts.synabunDiscoveryCache === false ? { discoveryCache: false } : {}),
750
751
  headers: {
751
752
  'X-Synabun-Terminal': this.synabunOwnerKey,
752
753
  'X-Synabun-Project': memoryProject(workDir),
@@ -56,7 +56,10 @@ export function deleteSessionRows(db, sessionId, provider) {
56
56
  if (!isSessionId(sessionId)) return out;
57
57
  const failures = [];
58
58
  const drop = (key, table, sql, ...params) => {
59
- try { out[key] = Number(db.prepare(sql).run(...params).changes) || 0; }
59
+ try {
60
+ const changes = db.prepare(sql).run(...params).changes;
61
+ if (key) out[key] = Number(changes) || 0;
62
+ }
60
63
  catch (err) {
61
64
  const message = String(err?.message || err);
62
65
  if (/no such table/i.test(message)) return;
@@ -65,6 +68,7 @@ export function deleteSessionRows(db, sessionId, provider) {
65
68
  };
66
69
  drop('chunks', 'session_chunks', 'DELETE FROM session_chunks WHERE session_id = ?', sessionId);
67
70
  drop('fts', 'session_fts', 'DELETE FROM session_fts WHERE session_id = ? AND provider = ?', sessionId, provider);
71
+ drop(null, 'session_fts_lookup', 'DELETE FROM session_fts_lookup WHERE session_id = ? AND provider = ?', sessionId, provider);
68
72
  drop('cache', 'session_cache', 'DELETE FROM session_cache WHERE session_id = ? AND provider = ?', sessionId, provider);
69
73
  if (failures.length) throw Object.assign(new Error(failures.join('; ')), { partial: out });
70
74
  return out;
@@ -16,6 +16,8 @@
16
16
  // PATH, so the update silently does nothing and the badge never clears.
17
17
  // ═══════════════════════════════════════════
18
18
 
19
+ import { semverNewer } from './synabun-version.js';
20
+
19
21
  /**
20
22
  * npm package name per tool key. OpenCode has none: npm's opencode-ai is
21
23
  * OpenCode 1, which SynaBun does not drive, and OpenCode 2 is installed by its
@@ -57,6 +59,67 @@ export const BREW_KINDS = {
57
59
  'opencode': 'formula',
58
60
  };
59
61
 
62
+ /**
63
+ * Where OpenCode 2 publishes its newest version, per install channel (checked
64
+ * 2026-11-21 against OpenCode 2.3.2). It has no npm package SynaBun could ask
65
+ * the registry about under the old name (opencode-ai is OpenCode 1), so without
66
+ * these the update check had nothing to compare an install with.
67
+ * vendor what OpenCode's own installer reads to find the release it
68
+ * downloads (https://opencode.ai/v2/install): JSON with a
69
+ * `version`. The yardstick of every install Homebrew does not own.
70
+ * brewFormula the formula of OpenCode's Homebrew tap as it is published.
71
+ * `brew outdated` only knows the local clone of a tap, which
72
+ * nothing refreshes until the user runs brew themselves (the
73
+ * probe runs with HOMEBREW_NO_AUTO_UPDATE), so a tap install
74
+ * never showed an update. The formula is exactly what
75
+ * `brew upgrade` installs once the tap is refreshed, so it can
76
+ * never run ahead of Homebrew the way npm does for a cask.
77
+ * brewToken the formula that file is (the tap's `opencode` is OpenCode 1).
78
+ */
79
+ export const OPENCODE_UPDATE_SOURCES = Object.freeze({
80
+ vendor: 'https://opencode.ai/update/api/latest/cli/npm',
81
+ brewFormula: 'https://raw.githubusercontent.com/anomalyco/homebrew-tap/HEAD/opencode-v2.rb',
82
+ brewToken: 'opencode-v2',
83
+ });
84
+
85
+ const PLAIN_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
86
+ const plainVersion = (value) => {
87
+ const text = typeof value === 'string' ? value.trim().replace(/^v(?=\d)/i, '') : '';
88
+ return PLAIN_VERSION_RE.test(text) ? text : null;
89
+ };
90
+
91
+ /** The `version` of OpenCode's update API answer (`{"version":"2.3.2",…}`), or null. */
92
+ export function parseVendorLatest(body) {
93
+ let data = body;
94
+ if (typeof body === 'string') {
95
+ try { data = JSON.parse(body); } catch { return null; }
96
+ }
97
+ if (!data || typeof data !== 'object' || data.active === false) return null;
98
+ return plainVersion(data.version);
99
+ }
100
+
101
+ /** The `version "…"` line of a Homebrew formula file, or null. */
102
+ export function parseFormulaVersion(text) {
103
+ const match = String(text ?? '').match(/^[ \t]*version[ \t]+["']([^"'\s]+)["'][ \t]*$/m);
104
+ return match ? plainVersion(match[1]) : null;
105
+ }
106
+
107
+ /**
108
+ * Where a tool's newest version is read from when it has no npm package:
109
+ * `{ url, channel, read(text) }`, or null (an npm tool, a tool with no such
110
+ * source, a Homebrew install of a formula SynaBun does not know the tap of:
111
+ * `brew outdated` alone speaks for that one).
112
+ */
113
+ export function upstreamVersionSource(toolKey, installSource, brewToken = null) {
114
+ if (toolKey !== 'opencode') return null;
115
+ if (isBrewSource(installSource)) {
116
+ const bare = String(brewToken || '').split('/').pop();
117
+ if (installSource !== 'brew-formula' || bare !== OPENCODE_UPDATE_SOURCES.brewToken) return null;
118
+ return { url: OPENCODE_UPDATE_SOURCES.brewFormula, channel: 'brew-formula', read: parseFormulaVersion };
119
+ }
120
+ return { url: OPENCODE_UPDATE_SOURCES.vendor, channel: 'vendor', read: parseVendorLatest };
121
+ }
122
+
60
123
  /** Tools that can update themselves when they own their own install. */
61
124
  const SELF_UPDATERS = {
62
125
  'claude-code': 'claude update',
@@ -226,9 +289,16 @@ export function quoteCommandPath(file, platform = process.platform) {
226
289
  * very installation the panels use, also when a terminal's PATH does not name
227
290
  * its folder (a Windows server started before the CLI was installed, a folder
228
291
  * found among the known install locations).
292
+ *
293
+ * `refreshBrew` (brewNeedsRefresh): the newer version is in the tap as it is
294
+ * published, and this machine's Homebrew has not heard of it yet. `brew
295
+ * upgrade` refreshes by itself only once in a while (HOMEBREW_AUTO_UPDATE_SECS,
296
+ * a day by default) and would answer "already installed", leaving the badge
297
+ * lit: the command refreshes first.
229
298
  */
230
- export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null } = {}) {
231
- const command = planUpdateCommand(toolKey, installSource, { brewToken, platform });
299
+ export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null, refreshBrew = false } = {}) {
300
+ const planned = planUpdateCommand(toolKey, installSource, { brewToken, platform });
301
+ const command = planned && refreshBrew && isBrewSource(installSource) ? `brew update && ${planned}` : planned;
232
302
  const name = TOOL_COMMANDS[toolKey];
233
303
  if (!command || !binPath || !name) return command;
234
304
  if (command !== name && !command.startsWith(`${name} `)) return command;
@@ -331,22 +401,51 @@ export function parseBrewOutdated(raw) {
331
401
  *
332
402
  * When the brew probe itself failed we fail CLOSED (latest = installed)
333
403
  * rather than falling back to npm, for the same reason.
404
+ *
405
+ * `npmLatest` is the upstream version of an install Homebrew does not own: the
406
+ * npm registry's for Claude Code and Codex, OpenCode's own update API for
407
+ * OpenCode 2 (upstreamVersionSource). `brewUpstream` is the version of the
408
+ * tool's formula as its tap publishes it (OpenCode's tap only): what Homebrew
409
+ * installs once the tap is refreshed, so it counts when it is newer than the
410
+ * install and `brew outdated` has not heard of it yet.
334
411
  */
335
412
  export function resolveLatest({
336
413
  installSource,
337
414
  brewToken = null,
338
415
  brewOutdated = null,
339
416
  npmLatest = null,
417
+ brewUpstream = null,
340
418
  installed = null,
341
419
  } = {}) {
342
420
  if (!isBrewSource(installSource)) return npmLatest;
343
421
  if (!installed) return null;
344
422
  if (!brewOutdated) return installed;
423
+ const hit = brewOutdatedVersion(brewOutdated, brewToken);
424
+ if (hit) return hit;
425
+ return brewUpstream && semverNewer(installed, brewUpstream) ? brewUpstream : installed;
426
+ }
427
+
428
+ function brewOutdatedVersion(brewOutdated, brewToken) {
345
429
  const token = brewToken || null;
346
- const hit = (token && brewOutdated.get(token))
347
- || (token && brewOutdated.get(String(token).split('/').pop()))
348
- || null;
349
- return hit || installed;
430
+ if (!token || !brewOutdated) return null;
431
+ return brewOutdated.get(token) || brewOutdated.get(String(token).split('/').pop()) || null;
432
+ }
433
+
434
+ /**
435
+ * Whether the update of a Homebrew install has to refresh Homebrew first
436
+ * (buildUpdateCommand `refreshBrew`): the tap publishes a newer version than
437
+ * the one installed, and `brew outdated` does not list the tool.
438
+ */
439
+ export function brewNeedsRefresh({
440
+ installSource,
441
+ brewToken = null,
442
+ brewOutdated = null,
443
+ brewUpstream = null,
444
+ installed = null,
445
+ } = {}) {
446
+ if (!isBrewSource(installSource) || !installed || !brewOutdated || !brewUpstream) return false;
447
+ if (brewOutdatedVersion(brewOutdated, brewToken)) return false;
448
+ return semverNewer(installed, brewUpstream);
350
449
  }
351
450
 
352
451
  /**