synabun 2.4.0 → 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 (319) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +73 -11
  4. package/browser-extension/engine.js +196 -15
  5. package/browser-extension/manifest.json +4 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +102 -11
  12. package/browser-extension/service-worker.js +20 -4
  13. package/browser-extension/tokens.css +1 -1
  14. package/docs/browser-extension-bridge.md +25 -5
  15. package/lib/data-home-files.js +47 -0
  16. package/lib/data-home-migration.js +34 -58
  17. package/lib/first-launch-protection.js +8 -2
  18. package/lib/update-snapshot.js +11 -4
  19. package/mcp-server/dist/http.d.ts.map +1 -1
  20. package/mcp-server/dist/http.js +25 -2
  21. package/mcp-server/dist/http.js.map +1 -1
  22. package/mcp-server/dist/index.d.ts.map +1 -1
  23. package/mcp-server/dist/index.js +62 -17
  24. package/mcp-server/dist/index.js.map +1 -1
  25. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  26. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  27. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  28. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  29. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  30. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  31. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  32. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  33. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  34. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  35. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  36. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  37. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  38. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  39. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  41. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  42. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  43. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  44. package/mcp-server/dist/services/memory-schema.js +190 -13
  45. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  46. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  47. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  48. package/mcp-server/dist/services/memory-sessions.js +56 -20
  49. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  50. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  51. package/mcp-server/dist/services/memory-verification.js +8 -5
  52. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  53. package/mcp-server/dist/services/neural-interface.d.ts +6 -0
  54. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  55. package/mcp-server/dist/services/neural-interface.js +19 -2
  56. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  57. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  58. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  59. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  60. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  61. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  62. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  63. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  64. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  65. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  66. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  67. package/mcp-server/dist/services/sqlite-write.js +94 -0
  68. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  69. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  70. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  71. package/mcp-server/dist/services/sqlite.js +249 -8
  72. package/mcp-server/dist/services/sqlite.js.map +1 -1
  73. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  74. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  75. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  76. package/mcp-server/dist/services/typesafe-config.js +32 -10
  77. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  78. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  79. package/mcp-server/dist/services/typesafe.js +9 -7
  80. package/mcp-server/dist/services/typesafe.js.map +1 -1
  81. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  82. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  83. package/mcp-server/dist/services/vector-cache.js +161 -8
  84. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  85. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  86. package/mcp-server/dist/tools/agents.d.ts +13 -8
  87. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/agents.js +35 -15
  89. package/mcp-server/dist/tools/agents.js.map +1 -1
  90. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  91. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  92. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  93. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  94. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  95. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  96. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  97. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  98. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  99. package/mcp-server/dist/tools/browser-interact.js +6 -1
  100. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  101. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  102. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  103. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  104. package/mcp-server/package-lock.json +2 -2
  105. package/mcp-server/package.json +1 -1
  106. package/mcp-server/src/http.ts +20 -2
  107. package/mcp-server/src/index.ts +59 -17
  108. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  109. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  110. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  111. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  112. package/mcp-server/src/services/memory-schema.ts +194 -12
  113. package/mcp-server/src/services/memory-sessions.ts +54 -21
  114. package/mcp-server/src/services/memory-verification.ts +7 -4
  115. package/mcp-server/src/services/neural-interface.ts +23 -2
  116. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  117. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  118. package/mcp-server/src/services/sqlite-write.ts +60 -0
  119. package/mcp-server/src/services/sqlite.ts +246 -8
  120. package/mcp-server/src/services/typesafe-config.ts +25 -6
  121. package/mcp-server/src/services/typesafe.ts +9 -7
  122. package/mcp-server/src/services/vector-cache.ts +154 -9
  123. package/mcp-server/src/tools/agents.ts +33 -14
  124. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  125. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  126. package/mcp-server/src/tools/browser-interact.ts +5 -1
  127. package/neural-interface/i18n/en.json +266 -2
  128. package/neural-interface/i18n/pt-BR.json +267 -3
  129. package/neural-interface/lib/agents/builtins.json +207 -0
  130. package/neural-interface/lib/agents/registry.js +60 -15
  131. package/neural-interface/lib/agents/resolve.js +69 -10
  132. package/neural-interface/lib/agents/split.js +32 -4
  133. package/neural-interface/lib/assistant-api.js +19 -8
  134. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  135. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  136. package/neural-interface/lib/assistant-catalog.js +2 -2
  137. package/neural-interface/lib/assistant-config.js +0 -7
  138. package/neural-interface/lib/assistant-dispatch.js +384 -119
  139. package/neural-interface/lib/assistant-persona.js +17 -5
  140. package/neural-interface/lib/assistant-pricing.js +65 -14
  141. package/neural-interface/lib/assistant-router.js +181 -54
  142. package/neural-interface/lib/assistant-run-wait.js +45 -28
  143. package/neural-interface/lib/assistant-runtime.js +48 -34
  144. package/neural-interface/lib/backup-contents.js +158 -0
  145. package/neural-interface/lib/backup-crypto-io.js +330 -0
  146. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  147. package/neural-interface/lib/backup-crypto.js +525 -0
  148. package/neural-interface/lib/backup-download.js +268 -0
  149. package/neural-interface/lib/backup-encryption.js +318 -0
  150. package/neural-interface/lib/backup-groups.js +287 -0
  151. package/neural-interface/lib/backup-restore-session.js +176 -0
  152. package/neural-interface/lib/backup-restore-stage.js +60 -0
  153. package/neural-interface/lib/backup-service.js +836 -322
  154. package/neural-interface/lib/backup-zip-reader.js +30 -18
  155. package/neural-interface/lib/backup-zip-writer.js +34 -10
  156. package/neural-interface/lib/browser-extension-adapter.js +109 -24
  157. package/neural-interface/lib/browser-extension-bridge.js +42 -8
  158. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  159. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  160. package/neural-interface/lib/cli-update-planner.js +105 -6
  161. package/neural-interface/lib/client-diagnostics.js +42 -0
  162. package/neural-interface/lib/confined-fs.js +7 -2
  163. package/neural-interface/lib/coordination/README.md +8 -2
  164. package/neural-interface/lib/coordination/contract.js +161 -0
  165. package/neural-interface/lib/coordination/database.js +999 -0
  166. package/neural-interface/lib/coordination/operations.js +436 -0
  167. package/neural-interface/lib/coordination/service.js +68 -537
  168. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  169. package/neural-interface/lib/coordination/store.js +219 -1111
  170. package/neural-interface/lib/db.js +70 -32
  171. package/neural-interface/lib/health-count.js +37 -0
  172. package/neural-interface/lib/loop-stall.js +139 -0
  173. package/neural-interface/lib/maritaca/client.js +2 -2
  174. package/neural-interface/lib/maritaca/models.js +12 -17
  175. package/neural-interface/lib/maritaca/opencode.js +4 -2
  176. package/neural-interface/lib/memory-api.js +9 -1
  177. package/neural-interface/lib/memory-session-capture.js +42 -10
  178. package/neural-interface/lib/memory-store-gate.js +313 -0
  179. package/neural-interface/lib/memory-store-migrate.js +65 -0
  180. package/neural-interface/lib/memory-timers.js +7 -7
  181. package/neural-interface/lib/native-loop-providers.js +13 -16
  182. package/neural-interface/lib/native-loop-runtime.js +34 -14
  183. package/neural-interface/lib/opencode-build-preflight.js +30 -8
  184. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  185. package/neural-interface/lib/opencode-provider-view.js +14 -3
  186. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  187. package/neural-interface/lib/opencode2-client.js +2 -1
  188. package/neural-interface/lib/peer-identity.js +13 -8
  189. package/neural-interface/lib/recall-impact.js +122 -0
  190. package/neural-interface/lib/scratch-evidence.js +420 -0
  191. package/neural-interface/lib/scratch-process-guard.js +139 -0
  192. package/neural-interface/lib/scratch-references.js +279 -0
  193. package/neural-interface/lib/scratch-retention-core.js +385 -0
  194. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  195. package/neural-interface/lib/scratch-retention.js +151 -0
  196. package/neural-interface/lib/session-cache-builder.js +70 -44
  197. package/neural-interface/lib/session-cache-worker.js +157 -0
  198. package/neural-interface/lib/session-indexer.js +28 -21
  199. package/neural-interface/lib/session-search-index.js +85 -0
  200. package/neural-interface/lib/skills/creation.js +1 -1
  201. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  202. package/neural-interface/lib/style-guide/store.js +43 -3
  203. package/neural-interface/lib/system-restore.js +50 -0
  204. package/neural-interface/lib/teams/api.js +15 -6
  205. package/neural-interface/lib/teams/claims.js +67 -31
  206. package/neural-interface/lib/teams/index.js +7 -7
  207. package/neural-interface/lib/teams/integration.js +40 -40
  208. package/neural-interface/lib/teams/landing.js +6 -6
  209. package/neural-interface/lib/teams/recovery.js +24 -23
  210. package/neural-interface/lib/teams/scheduler.js +196 -97
  211. package/neural-interface/lib/teams/schema.js +1 -1
  212. package/neural-interface/lib/teams/state.js +14 -14
  213. package/neural-interface/lib/teams/worktrees.js +27 -27
  214. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  215. package/neural-interface/lib/worker-confinement.js +47 -2
  216. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  217. package/neural-interface/lib/worker-resume.js +5 -0
  218. package/neural-interface/lib/worker-stop.js +86 -0
  219. package/neural-interface/package-lock.json +2 -2
  220. package/neural-interface/package.json +1 -1
  221. package/neural-interface/public/index.html +260 -0
  222. package/neural-interface/public/offline.html +4 -3
  223. package/neural-interface/public/onboarding.html +259 -34
  224. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  225. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  226. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  227. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  228. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  229. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  230. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  231. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  232. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  233. package/neural-interface/public/shared/api.js +3 -2
  234. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  235. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  236. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  237. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  238. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  239. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  240. package/neural-interface/public/shared/assistant/asst-render.js +106 -38
  241. package/neural-interface/public/shared/assistant/asst-route.js +102 -21
  242. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  243. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  244. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  245. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  246. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  247. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  248. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  249. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  250. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  251. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  252. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  253. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  254. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  255. package/neural-interface/public/shared/effort-i18n.js +118 -0
  256. package/neural-interface/public/shared/html-shell.js +4 -51
  257. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  258. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  259. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  260. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  261. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  262. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  272. package/neural-interface/public/shared/output-format.js +294 -0
  273. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  274. package/neural-interface/public/shared/page-session.js +1 -1
  275. package/neural-interface/public/shared/provider-icons.js +6 -0
  276. package/neural-interface/public/shared/schedules-view.js +2 -1
  277. package/neural-interface/public/shared/server-presence.js +77 -0
  278. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  279. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  280. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  281. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  282. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  284. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  285. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  286. package/neural-interface/public/shared/start-bridge.js +2 -2
  287. package/neural-interface/public/shared/studio-attention.js +6 -0
  288. package/neural-interface/public/shared/styles.css +354 -438
  289. package/neural-interface/public/shared/transcript-rows.js +28 -3
  290. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  291. package/neural-interface/public/shared/ui-agents.js +1 -2
  292. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  293. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  294. package/neural-interface/public/shared/ui-loading.js +185 -25
  295. package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
  296. package/neural-interface/public/shared/ui-navbar.js +2 -1
  297. package/neural-interface/public/shared/ui-output.js +533 -0
  298. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  299. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  300. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  301. package/neural-interface/public/shared/ui-sessions.js +2 -2
  302. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  303. package/neural-interface/public/shared/ui-settings.js +234 -67
  304. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  305. package/neural-interface/public/shared/ui-sync.js +1 -0
  306. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  307. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  308. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  309. package/neural-interface/public/shared/worker-end.js +9 -4
  310. package/neural-interface/public/sw.js +4 -3
  311. package/neural-interface/public/variant/2d/main.js +5 -0
  312. package/neural-interface/public/variant/3d/app.js +10 -0
  313. package/neural-interface/public/variant/3d/main.js +17 -4
  314. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  315. package/neural-interface/server.js +507 -160
  316. package/npm-shrinkwrap.json +2 -2
  317. package/package.json +2 -1
  318. package/scripts/restore-data-home-from-backup.mjs +175 -8
  319. 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, 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();
@@ -122,32 +140,91 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
122
140
  for (const owner of [...s._tabOwners.keys()]) await release(id, owner);
123
141
  sessions.delete(id); if (sessionId === id) sessionId = null;
124
142
  }
125
- async function files(paths) {
126
- if (!Array.isArray(paths) || !paths.length || paths.length > 4) fail('INVALID_MESSAGE');
127
- const result = []; let size = 0;
128
- for (const path of paths) {
129
- if (typeof path !== 'string') fail('INVALID_MESSAGE');
130
- let bytes;
131
- try { bytes = readConfinedFile(uploadRoot, resolve(path), { maxBytes: MAX_FILE - size }); }
132
- catch (error) { fail(error.status === 413 ? 'MESSAGE_TOO_LARGE' : 'PERMISSION_REQUIRED'); }
133
- size += bytes.length;
134
- result.push({ name: basename(path), base64: bytes.toString('base64') });
135
- }
136
- return result;
143
+ function uploadFiles(paths) {
144
+ if (!Array.isArray(paths) || !paths.length || paths.length > 4 ||
145
+ paths.some(path => typeof path !== 'string' || !isAbsolute(path))) fail('INVALID_MESSAGE');
146
+ let remaining = MAX_FILE;
147
+ return {
148
+ names: paths.map(path => basename(path)),
149
+ read(index) {
150
+ try {
151
+ const file = readConfinedFileWithMetadata(uploadRoot, resolve(paths[index]), { maxBytes: remaining });
152
+ remaining -= file.bytes.length;
153
+ return { ...file, type: uploadMimeType(paths[index]) };
154
+ } catch (error) {
155
+ if (error.status === 404) fail('UPLOAD_FILE_MISSING');
156
+ if (error.status === 413) fail('UPLOAD_TOO_LARGE');
157
+ fail('UPLOAD_FILE_REFUSED');
158
+ }
159
+ },
160
+ };
137
161
  }
138
- 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) {
139
208
  if (!bridge.status().connected) fail('EXTENSION_NOT_CONNECTED');
140
209
  if (!s || !tab || !s.tabs.has(tab)) fail('TAB_CLOSED');
141
210
  if (!ownsTab(s, owner, tab)) fail('NOT_OWNED');
142
211
  const op = aliases[action] || action;
143
- 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);
144
214
  let shot;
145
215
  if (op === 'screenshot') {
146
216
  shot = parseScreenshotOptions(body);
147
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.');
148
218
  if (shot.path && screenshotPathRefusal(shot.path, { dataHome })) fail('SCREENSHOT_PATH_REFUSED');
149
219
  }
150
- 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
+ }
151
228
  if (op === 'snapshot' && body.mode && body.mode !== 'ai') throw unsupported('Extension snapshots support mode="ai" (DOM refs) only.');
152
229
  if (HISTORY.includes(op)) {
153
230
  // Back and forward take no arguments on the wire; the server and the extension check the landing page.
@@ -157,10 +234,17 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
157
234
  }
158
235
  const args = {};
159
236
  for (const k of argumentKeys) if (body[k] !== undefined && body[k] !== null) args[k] = ['nthMatch', 'distance', 'maxChars', 'offset', 'timeout'].includes(k) ? Number(body[k]) : body[k];
237
+ let upload;
160
238
  if (op === 'upload') {
161
- bridge.authorize(op, tab, agent(owner), args); args.files = await files(body.filePaths);
239
+ bridge.authorize(op, tab, agent(owner), args);
240
+ upload = uploadFiles(body.filePaths);
241
+ args.files = upload.names;
242
+ }
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.' };
162
247
  }
163
- const result = finish(s, tab, await bridge.request(op, tab, agent(owner), args));
164
248
  if (op === 'wait' && result.ok) result.state = body.state || 'visible';
165
249
  if (op === 'screenshot' && result.ok) {
166
250
  const raw = Buffer.from(result.base64, 'base64'), meta = await sharp(raw).metadata();
@@ -247,8 +331,9 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
247
331
  const tab = body.tabId || s._tabOwners.get(owner);
248
332
  if (!['GET', 'POST'].includes(req.method)) throw unsupported('Tab management is through the extension popup.');
249
333
  // Every extension session endpoint is intercepted, including CDP, raw screenshot and UI routes.
250
- const result = await operation(s, owner, tab, match[2], body);
251
- 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);
252
337
  } catch (error) { try { log({ command: supported.has(match?.[2]) ? match[2] : 'session', tab: null, code: safeError(error).code }); } catch {} return denied(res, error); }
253
338
  }
254
339
  return { acquire, release, destroy, sync, operation, middleware, agent, session, ownerTabs, ownsTab };
@@ -1,10 +1,11 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { createHash, randomBytes } from 'node:crypto';
3
3
  import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { compareVersions } from './browser-extension-folder.js';
4
5
  import { dirname } from 'node:path';
5
6
  import { lookup } from 'node:dns/promises';
6
7
  import { WebSocketServer } from 'ws';
7
- 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';
8
9
 
9
10
  const manifest = JSON.parse(readFileSync(new URL('../../browser-extension/manifest.json', import.meta.url), 'utf8'));
10
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)));
@@ -51,6 +52,8 @@ export function createBridgeStore(path) {
51
52
  /** Isolated loopback transport. Constructing it neither listens nor reads/writes user data (restore() does). */
52
53
  // `commandWait` is how long a request waits for the extension's answer (COMMAND_WAIT; smaller only in tests), on the
53
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.
54
57
  // `fullControl` is the mode before the owner chose one (on: agents may use any http(s) site and any tab of the paired
55
58
  // browser; off: only what the owner shares). `store` keeps the pairing and the mode across restarts (createBridgeStore).
56
59
  // SynaBun's own addresses stay out of reach in both modes: `forbiddenOrigins` (its public aliases, any port),
@@ -60,6 +63,7 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
60
63
  commandWait = COMMAND_WAIT, clock = () => performance.now(), fullControl = true, store = null, blockedPorts = () => [], selfHosts = () => [],
61
64
  lookupAddresses = host => lookup(host, { all: true }) } = {}) {
62
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);
63
67
  let server, wss, listening, pair = null, credential = null, peer = null, state = empty(), enabled = true;
64
68
  // The owner's mode and its version. The newer version wins on either side: the server's (Settings) or the
65
69
  // extension's (its popup, reported in an inventory). Only the owner changes it: setMode() behind the owner route,
@@ -174,7 +178,26 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
174
178
  async function start() {
175
179
  if (listening) return listening;
176
180
  listening = new Promise((resolve, reject) => {
177
- server = createServer((_req, res) => { res.writeHead(404); res.end(); });
181
+ // An upload command id doubles as a short-lived capability. Only the paired extension
182
+ // receives it. Each file can be read once, in order, while its command is authorized.
183
+ server = createServer((req, res) => {
184
+ const match = /^Bearer ([a-f0-9]{32})$/.exec(req.headers.authorization || '');
185
+ const p = match && pending.get(match[1]);
186
+ if (!p?.upload || req.method !== 'POST' || req.url !== '/upload/' + p.nextFile ||
187
+ p.nextFile >= p.args.files.length || req.headers.origin !== `chrome-extension://${EXTENSION_ID}` ||
188
+ req.headers.host !== `127.0.0.1:${server.address()?.port}` ||
189
+ p.issued !== revocations || clock() >= p.expires) {
190
+ res.writeHead(404).end(); return;
191
+ }
192
+ try {
193
+ authorize('upload', p.tab, p.owner, p.args);
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);
197
+ } catch (error) {
198
+ res.writeHead(400, { 'Cache-Control': 'no-store' }).end(safeError(error).code);
199
+ }
200
+ });
178
201
  wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, perMessageDeflate: false });
179
202
  server.on('upgrade', (req, socket, head) => {
180
203
  if (req.socket.remoteAddress !== '127.0.0.1' || req.headers.origin !== `chrome-extension://${EXTENSION_ID}` || req.url !== '/bridge'
@@ -205,7 +228,8 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
205
228
  outbound = outbound.catch(() => {}).then(async () => {
206
229
  if (body.type === 'command') {
207
230
  check();
208
- 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()))) });
209
233
  }
210
234
  await wire.encode(body, raw => { check(); if (ws.readyState !== 1) fail('NOT_CONNECTED'); ws.send(raw); });
211
235
  }); return outbound;
@@ -274,6 +298,13 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
274
298
  });
275
299
  }
276
300
  function authorize(op, tab, owner, args = {}) {
301
+ authorizeAccess(op, tab, owner, args);
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');
306
+ }
307
+ function authorizeAccess(op, tab, owner, args) {
277
308
  if (!enabled || !peer || peer.ws.readyState !== 1) fail('EXTENSION_NOT_CONNECTED');
278
309
  // The peer must hold the credential that is current now, admitted in the current generation: a replaced credential
279
310
  // is refused even before it would have expired.
@@ -296,13 +327,16 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
296
327
  if (t.url !== 'about:blank' && !state.sites.includes(publicOrigin(t.url))) fail('SITE_NOT_APPROVED');
297
328
  if (t.url === 'about:blank' && op !== 'navigate' && !HISTORY.includes(op)) fail('SITE_NOT_APPROVED');
298
329
  if (args.url && !state.sites.includes(publicOrigin(args.url))) fail('SITE_NOT_APPROVED');
299
- if (op === 'upload' && !state.uploads || op === 'download' && !state.downloads) fail('PERMISSION_REQUIRED');
330
+ if (op === 'download' && !state.downloads) fail('PERMISSION_REQUIRED');
300
331
  }
301
- async function request(op, tab, owner, args = {}) {
332
+ async function request(op, tab, owner, args = {}, upload) {
302
333
  // The revocation generation this command was issued in; an owner revocation that begins later cancels it.
303
334
  const issued = revocations, stale = () => !CONTROL.includes(op) && issued !== revocations;
304
335
  if (pending.size >= 32) fail('TIMEOUT');
305
- 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 });
306
340
  try {
307
341
  authorize(op, tab, owner, args);
308
342
  const version = revision, connection = peer, full = mode.fullControl;
@@ -324,8 +358,8 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
324
358
  const timer = setTimeout(() => {
325
359
  pending.delete(msg.id); reject(Object.assign(new Error('TIMEOUT'), { code: 'TIMEOUT' }));
326
360
  if (peer === via && via.ws.readyState === 1) void via.send({ type: 'cancel', id: msg.id }).catch(() => {});
327
- }, commandWait);
328
- pending.set(msg.id, { resolve, reject, timer, op, tab, owner, args, 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 });
329
363
  via.send(msg).catch(error => { clearTimeout(timer); pending.delete(msg.id); reject(['CANCELLED', 'TIMEOUT'].includes(error?.code) ? coded(error.code)() : notConnected()); });
330
364
  });
331
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;