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
@@ -41,7 +41,7 @@ export function createRunWaits({ entries, view, isTerminal, coordination, now =
41
41
  /** A run changed: every wait looks again. */
42
42
  function notify() {
43
43
  for (const waiter of [...waiters]) {
44
- try { if (waiter.check()) { waiters.delete(waiter); waiter.resolve(); } } catch { /* a wait that cannot look keeps waiting for its timeout */ }
44
+ waiter.wake();
45
45
  }
46
46
  }
47
47
 
@@ -111,15 +111,14 @@ export function createRunWaits({ entries, view, isTerminal, coordination, now =
111
111
  from = Number(afterSeq);
112
112
  if (!Number.isInteger(from) || from < 0) throw fail('INVALID_CURSOR', 'after_seq is a whole number from 0: the cursor of an earlier agent_wait answer.', { status: 400 });
113
113
  } else {
114
- from = lastSeq();
114
+ from = await lastSeq();
115
115
  // The brain itself asks: what it has not been told yet counts, though it happened before this call.
116
- if (unseenFor) from = Math.min(from, unseenStart(String(unseenFor), ids, from));
116
+ if (unseenFor) from = Math.min(from, await unseenStart(String(unseenFor), ids, from));
117
117
  }
118
118
  }
119
- const eventsNow = () => {
119
+ const eventsNow = async () => {
120
120
  if (!typed) return [];
121
- try { return coordination.runEvents({ runIds: ids, afterSeq: from, kinds: wanted, limit: RUN_WAIT_LIMITS.maxEvents }); }
122
- catch { return []; }
121
+ return coordination.runEvents({ runIds: ids, afterSeq: from, kinds: wanted, limit: RUN_WAIT_LIMITS.maxEvents });
123
122
  };
124
123
  const satisfied = (events) => ids.filter((id) => {
125
124
  const entry = entries.get(id);
@@ -130,21 +129,41 @@ export function createRunWaits({ entries, view, isTerminal, coordination, now =
130
129
  if (!cursorGiven && (entry.state === 'awaiting_permission' || entry.state === 'awaiting_route')) return true;
131
130
  return events.some((event) => event.runId === id);
132
131
  });
133
- const check = () => {
132
+ const check = async () => {
134
133
  ids = members();
135
- const done = satisfied(eventsNow());
134
+ const done = satisfied(await eventsNow());
136
135
  return mode === 'any' ? done.length > 0 : done.length === ids.length;
137
136
  };
138
- if (!check()) {
139
- await new Promise((resolveWait) => {
140
- const waiter = { check, resolve: () => { clearTimeout(timer); resolveWait(); } };
141
- const timer = setTimeout(() => { waiters.delete(waiter); resolveWait(); }, budget);
142
- timer.unref?.();
143
- waiters.add(waiter);
144
- });
145
- }
137
+ // Subscribe before the first read. Coalesce notifications while a read is
138
+ // outstanding so an event between that read and its reply still wakes us.
139
+ await new Promise((resolveWait, rejectWait) => {
140
+ let checking = false, again = false;
141
+ function finish(error) {
142
+ if (!waiters.delete(waiter)) return;
143
+ clearTimeout(timer);
144
+ if (error) rejectWait(error); else resolveWait();
145
+ }
146
+ const waiter = { async wake() {
147
+ if (checking) { again = true; return; }
148
+ checking = true;
149
+ try {
150
+ do {
151
+ again = false;
152
+ if (await check()) { finish(); break; }
153
+ } while (again && waiters.has(waiter));
154
+ } catch (error) { finish(error); }
155
+ checking = false;
156
+ } };
157
+ const timer = setTimeout(finish, budget);
158
+ timer.unref?.();
159
+ waiters.add(waiter);
160
+ waiter.wake();
161
+ });
146
162
  ids = members();
147
- const events = eventsNow();
163
+ // Sample the watermark before fetching the rows. A later commit must
164
+ // appear in this answer or remain above the returned cursor.
165
+ const watermark = await lastSeq();
166
+ const events = await eventsNow();
148
167
  const done = satisfied(events);
149
168
  const pendingIds = ids.filter((id) => !done.includes(id));
150
169
  const timedOut = !(mode === 'any' ? done.length > 0 : done.length === ids.length);
@@ -158,25 +177,23 @@ export function createRunWaits({ entries, view, isTerminal, coordination, now =
158
177
  if (typed) {
159
178
  out.events = events;
160
179
  // Pass it back as after_seq to go on from here. A full page stops at its last event: more may follow.
161
- out.cursor = events.length >= RUN_WAIT_LIMITS.maxEvents ? events[events.length - 1].seq : Math.max(from, lastSeq());
180
+ out.cursor = events.length >= RUN_WAIT_LIMITS.maxEvents ? events[events.length - 1].seq : Math.max(from, watermark, events.at(-1)?.seq || 0);
162
181
  } else {
163
- out.cursor = lastSeq();
182
+ out.cursor = watermark;
164
183
  }
165
184
  if (overflow) out.notWaitedFor = overflow;
166
185
  return out;
167
186
  }
168
187
 
169
- function lastSeq() {
170
- try { return Number(coordination.lastSeq()) || 0; } catch { return 0; }
188
+ async function lastSeq() {
189
+ return Number(await coordination.lastSeq()) || 0;
171
190
  }
172
191
  /** Just before the oldest event of these runs the session's brain was not told yet (`fallback` when there is none). */
173
- function unseenStart(sessionId, ids, fallback) {
174
- try {
175
- const wantedRuns = new Set(ids);
176
- const { items } = coordination.mailbox.pending(sessionId, { limit: 1000, peek: true });
177
- const seqs = items.filter((item) => item.run?.runId && wantedRuns.has(String(item.run.runId))).map((item) => Number(item.seq)).filter((seq) => Number.isFinite(seq));
178
- return seqs.length ? Math.min(...seqs) - 1 : fallback;
179
- } catch { return fallback; }
192
+ async function unseenStart(sessionId, ids, fallback) {
193
+ const wantedRuns = new Set(ids);
194
+ const { items } = await coordination.mailbox.pending(sessionId, { limit: 1000, peek: true });
195
+ const seqs = items.filter((item) => item.run?.runId && wantedRuns.has(String(item.run.runId))).map((item) => Number(item.seq)).filter((seq) => Number.isFinite(seq));
196
+ return seqs.length ? Math.min(...seqs) - 1 : fallback;
180
197
  }
181
198
 
182
199
  return { wait, notify, satisfies, pending: () => waiters.size };
@@ -97,6 +97,8 @@ export const BRAIN_CREDENTIAL_RE = /^sbb_[A-Za-z0-9_-]{43}$/;
97
97
  export function mintBrainCredential() { return `sbb_${randomBytes(32).toString('base64url')}`; }
98
98
  /** The brains whose SynaBun MCP names the session id as its pin (the Claude CLI's header, agy's environment). */
99
99
  const BRAIN_PIN_PROVIDERS = new Set(['claude-code', 'antigravity']);
100
+ // Route cards raised by the brain's own turn: they close with that brain. A held dispatch's card outlives it.
101
+ const BRAIN_CARD_ORIGINS = ['agent_route', 'vision_guard'];
100
102
  // An OpenCode brain of a remote session reaches the web through these on its own
101
103
  // (no SynaBun browser, no approval): the gate plugin refuses them.
102
104
  const REMOTE_OPENCODE_WEB_TOOLS = new Set(['webfetch', 'websearch', 'codesearch']);
@@ -931,6 +933,7 @@ export function createAssistantRuntime({
931
933
  */
932
934
  function brainNeedsRestart(live) {
933
935
  if (!live?.brain) return false;
936
+ if (live.brain.needsRestart?.()) return true;
934
937
  // Its persona was built with (or without) a user-context layer that was switched since.
935
938
  if (userContext && live.brainUserContext !== null) {
936
939
  let key = null;
@@ -1766,6 +1769,8 @@ export function createAssistantRuntime({
1766
1769
  // Pending background work re-arms this timer through the `done` of the turn
1767
1770
  // the CLI starts when that work reports back.
1768
1771
  if (live.sockets.size || sessionBusy(live) || live.brain?.hasPendingWork?.()) return;
1772
+ // A model choice waits for the user with no time limit: disposing this brain would close its card.
1773
+ if ((router?.pendingCards?.(live.record.id) || []).some((card) => BRAIN_CARD_ORIGINS.includes(card?.request?.origin))) { scheduleDispose(live); return; }
1769
1774
  disposeBrain(live, 'idle').catch(() => {});
1770
1775
  }, settings.idleDisposeMs);
1771
1776
  live.disposeTimer.unref?.();
@@ -2329,7 +2334,8 @@ export function createAssistantRuntime({
2329
2334
  live.brainComputerMode = null;
2330
2335
  // A "do it here" continuation goes with its brain; the plan's turn does not (it starts the next brain).
2331
2336
  dropWork(live, 'continuation');
2332
- try { router?.cancelForSession?.(live.record.id, reason === 'closed' ? 'session_closed' : 'brain_disposed', { origins: ['agent_route', 'vision_guard'] }); } catch {}
2337
+ // Closing the session ends every card, a held dispatch's too: cards have no deadline, so nothing else would release its run.
2338
+ try { router?.cancelForSession?.(live.record.id, reason === 'closed' ? 'session_closed' : 'brain_disposed', reason === 'closed' ? {} : { origins: BRAIN_CARD_ORIGINS }); } catch {}
2333
2339
  // Clarify cards outlive a brain (the answers reach the next one as a mailbox turn), not the session.
2334
2340
  if (reason === 'closed') { try { clarifier?.cancelForSession?.(live.record.id, 'session_closed'); } catch {} }
2335
2341
  live.record.status = reason === 'closed' ? 'ended' : 'idle';
@@ -2504,7 +2510,7 @@ export function createAssistantRuntime({
2504
2510
  await disposeBrain(live, 'budget');
2505
2511
  if (cancelled()) return dropTurn(live, request);
2506
2512
  }
2507
- // A Claude brain built for another remote level restarts (resuming its conversation).
2513
+ // A dead OpenCode serve or stale brain policy needs a fresh brain with the same conversation.
2508
2514
  if (live.brain && !live.running && brainNeedsRestart(live)) {
2509
2515
  await disposeBrain(live, 'policy');
2510
2516
  if (cancelled()) return dropTurn(live, request);
@@ -2751,6 +2757,13 @@ export function createAssistantRuntime({
2751
2757
  try { router?.continuationStarted?.(work.routeId); } catch (error) { log('assistant:route-continuation', error?.message || String(error)); }
2752
2758
  }
2753
2759
  } catch (error) {
2760
+ if (error?.code === 'OPENCODE_SERVE_EXITED') {
2761
+ const message = error.message;
2762
+ // The exit listener normally closed the turn. If the serve died before
2763
+ // the brain entered the turn, close it here with the same single packet.
2764
+ if (live.running) onBrainPacket(live, { type: 'error', message });
2765
+ return { ok: false, code: 'TURN_FAILED', message };
2766
+ }
2754
2767
  live.running = false;
2755
2768
  live.turnRun = previousRun;
2756
2769
  endComputerTurn(live, 'turn_failed');
@@ -2795,17 +2808,17 @@ export function createAssistantRuntime({
2795
2808
  // at once when the session is free;
2796
2809
  // everything else waits `mailboxDebounceMs` (150 ms at most) so results that arrive together go in one turn;
2797
2810
  // while the brain is busy everything waits in the store, low-priority progress folded, and goes when it is free.
2798
- function mailboxCount(live, options) {
2799
- try { return coordination.mailbox.count(live.record.id, options); } catch { return 0; }
2811
+ function mailboxCount(live) {
2812
+ try { return coordination.mailbox.cachedCount(live.record.id); } catch { return 0; }
2800
2813
  }
2801
2814
  /** A look at what a session has open (the `live.mailbox` view): nothing is handed out or acknowledged. */
2802
- function mailboxPeek(sessionId) {
2803
- try { return coordination.mailbox.pending(sessionId, { limit: 1000, peek: true }).items; } catch { return []; }
2815
+ async function mailboxPeek(sessionId) {
2816
+ try { return (await coordination.mailbox.pending(sessionId, { limit: 1000, peek: true })).items; } catch { return []; }
2804
2817
  }
2805
2818
  /** Something the brain must hear that is not a run's own event (a memory reminder, a route's or a clarify card's outcome). */
2806
- function enqueueMailbox(live, item) {
2807
- try { coordination.mailbox.post(live.record.id, item); }
2808
- catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); }
2819
+ async function enqueueMailbox(live, item) {
2820
+ try { await coordination.mailbox.post(live.record.id, item); return true; }
2821
+ catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); return false; }
2809
2822
  // The store's wake-up (onMailboxEvent) schedules the delivery.
2810
2823
  }
2811
2824
  /** An event was addressed to this session (the store's wake-up, after its append committed). */
@@ -2861,8 +2874,8 @@ export function createAssistantRuntime({
2861
2874
  return !!mark && Number(mark.turn) >= turn;
2862
2875
  }
2863
2876
  /** Events the brain read by itself meanwhile are settled without a turn. → how many. */
2864
- function settleRead(live) {
2865
- try { return coordination.mailbox.discard(live.record.id, (item) => alreadyRead(item)); } catch { return 0; }
2877
+ async function settleRead(live) {
2878
+ try { return await coordination.mailbox.discard(live.record.id, (item) => alreadyRead(item)); } catch { return 0; }
2866
2879
  }
2867
2880
  /**
2868
2881
  * Out of money: the events wait (a raise or No limit re-schedules them), said once. The brain's
@@ -2890,7 +2903,8 @@ export function createAssistantRuntime({
2890
2903
  return false;
2891
2904
  }
2892
2905
  /** The mailbox now, if the scheduler would start it (no debounce: it is asked for). */
2893
- function deliverMailbox(live) {
2906
+ async function deliverMailbox(live) {
2907
+ if (!await coordination.mailbox.count(live.record.id)) return null;
2894
2908
  if (shuttingDown || live.closing || !mailboxCount(live) || sessions.get(live.record.id) !== live || live.record.status === 'ended') return Promise.resolve(null);
2895
2909
  if (sessionBusy(live) || live.planCard || nextWork(live) || !mailboxAllowed(live)) { pumpSoon(live); return Promise.resolve(null); }
2896
2910
  return startWork(live, { kind: 'mailbox', gen: null });
@@ -2899,9 +2913,9 @@ export function createAssistantRuntime({
2899
2913
  async function runMailboxTurn(live) {
2900
2914
  // Read while it waited (inside the debounce, or while the brain was busy with the turn that waited for it):
2901
2915
  // not news any more.
2902
- settleRead(live);
2916
+ await settleRead(live);
2903
2917
  let batch = null;
2904
- try { batch = coordination.mailbox.pending(live.record.id, { limit: settings.mailboxItems }); }
2918
+ try { batch = await coordination.mailbox.pending(live.record.id, { limit: settings.mailboxItems }); }
2905
2919
  catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); return null; }
2906
2920
  let unread = batch.items;
2907
2921
  let more = batch.more;
@@ -2941,7 +2955,7 @@ export function createAssistantRuntime({
2941
2955
  if (result?.ok) {
2942
2956
  // The turn that carries them was started: only now are they acknowledged. A turn that was refused, failed
2943
2957
  // or found the brain busy leaves every one of them open, also across a restart.
2944
- try { coordination.mailbox.ack(live.record.id, items.map((item) => item.eventId).filter(Boolean)); }
2958
+ try { await coordination.mailbox.ack(live.record.id, items.map((item) => item.eventId).filter(Boolean)); }
2945
2959
  catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); }
2946
2960
  live.mailboxAttempts = 0;
2947
2961
  return result;
@@ -2952,12 +2966,12 @@ export function createAssistantRuntime({
2952
2966
  if (result?.code !== 'ASSISTANT_BUSY' && result?.code !== 'TURN_CANCELLED') holdMailbox(live, result);
2953
2967
  return result;
2954
2968
  }
2955
- function onDispatchEvent(payload) {
2969
+ async function onDispatchEvent(payload) {
2956
2970
  const run = payload?.run;
2957
2971
  if (!run?.assistantSessionId) return;
2958
2972
  const live = sessions.get(run.assistantSessionId);
2959
2973
  // A session that is gone hears nothing: what was addressed to it is settled, so it does not wait in the store for good.
2960
- if (!live) { dropMailbox(run.assistantSessionId); return; }
2974
+ if (!live) { await dropMailbox(run.assistantSessionId); return; }
2961
2975
  // The conversation's thread record: its runs, their outcomes and follow-ups.
2962
2976
  try { userContext?.onDispatch(live.record, payload); } catch {}
2963
2977
  if (!live.record.dispatchRunIds?.includes(run.runId)) { live.record.dispatchRunIds = [...(live.record.dispatchRunIds || []), run.runId].slice(-100); touch(live); }
@@ -2971,14 +2985,14 @@ export function createAssistantRuntime({
2971
2985
  // Agents P2: the event is in the coordination log. The dispatcher appended it in the step that changed the run;
2972
2986
  // recording it here again stores nothing (same id), and is what a dispatcher without the service relies on.
2973
2987
  // Which reasons reach the brain, and how urgently, is the service's rule. The store's wake-up schedules the turn.
2974
- const recorded = coordination.recordDispatch(payload);
2988
+ const recorded = await coordination.recordDispatch(payload);
2975
2989
  // Already read by the brain (agent_wait in the same turn that dispatched it): no second turn. Only this event is
2976
2990
  // looked at here; the whole mailbox is gone through once, when a turn is composed.
2977
2991
  if (recorded?.delivered && alreadyRead({ kind: payload.reason === 'turn_completed' ? 'result' : payload.reason, turn: payload.turn, run })) {
2978
- try { coordination.mailbox.ack(live.record.id, [recorded.id]); } catch {}
2992
+ try { await coordination.mailbox.ack(live.record.id, [recorded.id]); } catch {}
2979
2993
  }
2980
2994
  }
2981
- function onRunRemoved(payload) {
2995
+ async function onRunRemoved(payload) {
2982
2996
  const live = payload?.assistantSessionId ? sessions.get(payload.assistantSessionId) : null;
2983
2997
  if (!live) return;
2984
2998
  const removed = new Set((payload.runIds || []).map(String));
@@ -2990,7 +3004,7 @@ export function createAssistantRuntime({
2990
3004
  }
2991
3005
  // A result can be waiting in the mailbox while the user clears its run.
2992
3006
  // Do not let that stale result (or its memory reminder) start another turn.
2993
- try { coordination.mailbox.discard(live.record.id, (item) => removed.has(String(item?.run?.runId || item?.runId || ''))); } catch {}
3007
+ try { await coordination.mailbox.discard(live.record.id, (item) => removed.has(String(item?.run?.runId || item?.runId || ''))); } catch {}
2994
3008
  if (!mailboxCount(live) && live.mailboxTimer) {
2995
3009
  clearTimeout(live.mailboxTimer);
2996
3010
  live.mailboxTimer = null;
@@ -3000,32 +3014,32 @@ export function createAssistantRuntime({
3000
3014
  * Everything open for a session that no longer exists is settled (nobody will ever read it). Never while the
3001
3015
  * sessions index could not be read: a session this start does not know yet may be there after the next one.
3002
3016
  */
3003
- function dropMailbox(sessionId) {
3017
+ async function dropMailbox(sessionId) {
3004
3018
  if (!indexReady) return;
3005
- try { if (coordination.mailbox.count(sessionId)) coordination.mailbox.discard(sessionId, null); } catch {}
3019
+ try { if (await coordination.mailbox.count(sessionId)) await coordination.mailbox.discard(sessionId, null); } catch {}
3006
3020
  }
3007
3021
  /**
3008
3022
  * After a restart: what a session's brain was not told before the server went down is still open in the store,
3009
3023
  * and is delivered now. A session that was removed gets nothing; one that is closed waits until it is opened again.
3010
3024
  */
3011
- function resumeMailboxes() {
3025
+ async function resumeMailboxes() {
3012
3026
  if (shuttingDown) return;
3013
3027
  let open = [];
3014
- try { open = coordination.mailbox.sessions(); } catch { open = []; }
3028
+ try { open = await coordination.mailbox.sessions(); } catch { open = []; }
3015
3029
  for (const { sessionId } of open) {
3016
3030
  const live = sessions.get(sessionId);
3017
- if (!live) { dropMailbox(sessionId); continue; }
3031
+ if (!live) { await dropMailbox(sessionId); continue; }
3018
3032
  if (live.record.status === 'ended') continue;
3019
3033
  scheduleMailbox(live, 0);
3020
3034
  }
3021
3035
  }
3022
- function onPermissionBroadcast(message) {
3036
+ async function onPermissionBroadcast(message) {
3023
3037
  const live = message?.assistantSessionId ? sessions.get(message.assistantSessionId) : null;
3024
3038
  if (!live) return;
3025
3039
  if (message.type === 'assistant:permission-request') {
3026
3040
  sendToSockets(live, { type: 'event', event: { type: 'synabun.dispatch_control_request', runId: message.runId, request_id: message.request?.requestId, provider: dispatcher?.get?.(message.runId)?.provider || null, request: message.request } });
3027
3041
  } else if (message.type === 'assistant:permission-resolved') {
3028
- try { coordination.mailbox.discard(live.record.id, (item) => item.run?.runId === message.runId && item.request?.requestId === message.requestId); } catch {}
3042
+ try { await coordination.mailbox.discard(live.record.id, (item) => item.run?.runId === message.runId && item.request?.requestId === message.requestId); } catch {}
3029
3043
  sendToSockets(live, { type: 'event', event: { type: 'synabun.dispatch_control_resolved', runId: message.runId, request_id: message.requestId, resolvedBy: message.resolvedBy, behavior: message.behavior } });
3030
3044
  }
3031
3045
  }
@@ -3322,7 +3336,7 @@ export function createAssistantRuntime({
3322
3336
  sessions.delete(id);
3323
3337
  if (live.mailboxTimer) { clearTimeout(live.mailboxTimer); live.mailboxTimer = null; }
3324
3338
  if (live.mailboxRetryTimer) { clearTimeout(live.mailboxRetryTimer); live.mailboxRetryTimer = null; }
3325
- dropMailbox(id);
3339
+ await dropMailbox(id);
3326
3340
  const usageTimer = usageTimers.get(id);
3327
3341
  if (usageTimer) clearTimeout(usageTimer);
3328
3342
  usageTimers.delete(id);
@@ -3453,7 +3467,7 @@ export function createAssistantRuntime({
3453
3467
  // A remote session: computer use stops with the turn, before the brain is even asked to (its
3454
3468
  // approval, its open request, the live grant; an action in progress is aborted).
3455
3469
  endComputerTurn(live, 'stopped');
3456
- try { router?.cancelForSession?.(live.record.id, 'aborted', { origins: ['agent_route', 'vision_guard'] }); } catch {}
3470
+ try { router?.cancelForSession?.(live.record.id, 'aborted', { origins: BRAIN_CARD_ORIGINS }); } catch {}
3457
3471
  if (origin !== 'ui') log('assistant:stop', `${live.record.id}: turn stopped from ${origin}`);
3458
3472
  try { await live.brain?.abort?.(); } catch (error) { return { ok: false, code: 'STOP_FAILED', message: error?.message || String(error) }; }
3459
3473
  return { ok: true };
@@ -3877,7 +3891,7 @@ export function createAssistantRuntime({
3877
3891
  }
3878
3892
  if (phase !== 'card' && phase !== 'pending' && phase !== 'auto') publishPendingRoutes(live);
3879
3893
  }
3880
- function routerMailbox(id, item) { const live = sessions.get(id); if (live && item) enqueueMailbox(live, item); }
3894
+ function routerMailbox(id, item) { const live = sessions.get(id); if (live && item) return enqueueMailbox(live, item); }
3881
3895
  /** agent_route answered (or failed) for this session: the route gate follows it (`meta.taskClass`: a chat route holds). */
3882
3896
  function routerRouted(id, result, meta = {}) { const live = sessions.get(id); if (live) ensureGate(live)?.onRouteResult(result, meta); }
3883
3897
  function routerRouteFailed(id, error) {
@@ -4381,7 +4395,7 @@ export function createAssistantRuntime({
4381
4395
  metered('flush', () => usage?.flush?.());
4382
4396
  // A coordination service this runtime made for itself goes with it (a shared one is closed by its owner).
4383
4397
  // What a brain was not told stays open in the store and is delivered by the next start.
4384
- if (ownsCoordination) coordination.close();
4398
+ if (ownsCoordination) await coordination.close();
4385
4399
  }
4386
4400
 
4387
4401
  loadIndex();
@@ -4391,8 +4405,8 @@ export function createAssistantRuntime({
4391
4405
  }
4392
4406
  if (dispatcher?.subscribe) {
4393
4407
  unsubscribeDispatcher = dispatcher.subscribe((payload) => {
4394
- if (payload?.type === 'assistant:dispatch') onDispatchEvent(payload);
4395
- else if (payload?.type === 'assistant:run-removed') onRunRemoved(payload);
4408
+ if (payload?.type === 'assistant:dispatch') return onDispatchEvent(payload);
4409
+ else if (payload?.type === 'assistant:run-removed') return onRunRemoved(payload);
4396
4410
  });
4397
4411
  }
4398
4412
  // Agents P2: the store wakes the mailbox of the session an event was addressed to (after its append committed).
@@ -0,0 +1,158 @@
1
+ // ═══════════════════════════════════════════
2
+ // BACKUP CONTENTS — the owner's choice of what a backup holds, and how big it is
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // Settings → Backups → What to back up. One choice for every backup this server makes on request or on schedule
6
+ // (the download into a folder, the browser download, the scheduled backup, Back up now), kept in
7
+ // DATA_HOME/data/backup-selection.json as { version, groups: { id: boolean } }. A group nothing was said about has
8
+ // its default (backup-groups.js): everything that cannot be made again is on, caches and working folders are off.
9
+ //
10
+ // The sizes next to the switches are measured on a worker thread (backup-service.js measureBackupContents: names and
11
+ // sizes, no file opened), never in a request: a request only reads the last measurement and, when it is missing, old
12
+ // or asked for again, starts one. The page asks again while `estimate.state` is `measuring`.
13
+ //
14
+ // createBackupContentsService({ configPath, measure, … }) the choice and the measurement
15
+ // backupContentsHandlers(service) GET and PUT /api/system/backup/contents
16
+ // ═══════════════════════════════════════════
17
+
18
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
19
+ import { dirname } from 'node:path';
20
+ import { BACKUP_GROUPS, BACKUP_GROUP_IDS, irreplaceableLeftOut, normalizeBackupSelection, selectedBackupGroups } from './backup-groups.js';
21
+
22
+ export const BACKUP_ESTIMATE_TTL_MS = 5 * 60_000;
23
+
24
+ const emptySize = () => ({ files: 0, bytes: 0, archiveBytes: 0 });
25
+
26
+ /**
27
+ * @param {object} o
28
+ * @param {string} o.configPath where the choice is kept
29
+ * @param {() => Promise<{ groups: object, never: object }>} o.measure one measurement (a worker thread)
30
+ * @param {number} [o.ttlMs] how long a measurement is shown before a new one is made
31
+ * @param {() => number} [o.now]
32
+ * @param {(line: string) => void} [o.log]
33
+ */
34
+ export function createBackupContentsService({ configPath, measure, ttlMs = BACKUP_ESTIMATE_TTL_MS, now = Date.now, log = () => {} } = {}) {
35
+ if (!configPath || typeof measure !== 'function') throw new Error('configPath and measure are required');
36
+ let measured = null; // { at, groups, never }
37
+ let measuring = null; // the measurement under way
38
+ let failure = null; // the last one's error, until one succeeds
39
+
40
+ function selection() {
41
+ try { return normalizeBackupSelection(JSON.parse(readFileSync(configPath, 'utf-8'))?.groups); }
42
+ catch { return normalizeBackupSelection(null); }
43
+ }
44
+
45
+ /** The ids a backup made now would hold. */
46
+ const groups = () => selectedBackupGroups(selection());
47
+
48
+ function save(value) {
49
+ mkdirSync(dirname(configPath), { recursive: true });
50
+ const temp = `${configPath}.${process.pid}.tmp`;
51
+ try {
52
+ writeFileSync(temp, `${JSON.stringify({ version: 1, groups: value }, null, 2)}\n`, 'utf-8');
53
+ renameSync(temp, configPath);
54
+ } catch (error) {
55
+ try { if (existsSync(temp)) unlinkSync(temp); } catch { /* nothing to remove */ }
56
+ throw error;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Switch groups on or off: `patch` is { id: boolean } for the groups that change. Refused (status 400): anything
62
+ * but booleans for known groups, and a choice that leaves nothing to back up.
63
+ */
64
+ function setSelection(patch) {
65
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
66
+ throw Object.assign(new Error('Say which groups to switch: { groups: { id: true | false } }.'), { status: 400, code: 'SELECTION_INVALID' });
67
+ }
68
+ const next = selection();
69
+ for (const [id, value] of Object.entries(patch)) {
70
+ if (!BACKUP_GROUP_IDS.includes(id)) throw Object.assign(new Error(`There is no backup group "${String(id).slice(0, 40)}".`), { status: 400, code: 'GROUP_UNKNOWN' });
71
+ if (typeof value !== 'boolean') throw Object.assign(new Error(`"${id}" is switched with true or false.`), { status: 400, code: 'SELECTION_INVALID' });
72
+ next[id] = value;
73
+ }
74
+ if (!selectedBackupGroups(next).length) {
75
+ throw Object.assign(new Error('A backup needs at least one group switched on.'), { status: 400, code: 'NOTHING_SELECTED' });
76
+ }
77
+ save(next);
78
+ return next;
79
+ }
80
+
81
+ /** Start a measurement unless one is running; the one under way otherwise. Never throws, never rejects. */
82
+ function measureNow() {
83
+ if (measuring) return measuring;
84
+ measuring = Promise.resolve()
85
+ .then(() => measure())
86
+ .then((result) => {
87
+ const sizes = {};
88
+ for (const id of BACKUP_GROUP_IDS) {
89
+ const got = result?.groups?.[id] || {};
90
+ sizes[id] = { files: Number(got.files) || 0, bytes: Number(got.bytes) || 0, archiveBytes: Number(got.archiveBytes) || 0 };
91
+ }
92
+ measured = { at: now(), groups: sizes, never: { files: Number(result?.never?.files) || 0, bytes: Number(result?.never?.bytes) || 0 } };
93
+ failure = null;
94
+ }, (error) => {
95
+ failure = error?.message || String(error);
96
+ log(`[backup] The size of the backup groups could not be measured: ${failure}`);
97
+ })
98
+ .finally(() => { measuring = null; });
99
+ return measuring;
100
+ }
101
+
102
+ /**
103
+ * What the page shows. Reads the last measurement and starts a new one when there is none, when it is older than
104
+ * `ttlMs`, or when `refresh` asks; the answer never waits for it.
105
+ */
106
+ function snapshot({ refresh = false } = {}) {
107
+ const chosen = selection();
108
+ if (refresh || !measured || now() - measured.at >= ttlMs) measureNow();
109
+ const selected = emptySize();
110
+ const everything = emptySize();
111
+ const rows = BACKUP_GROUPS.map((group) => {
112
+ const size = measured ? measured.groups[group.id] : null;
113
+ if (size) {
114
+ for (const key of ['files', 'bytes', 'archiveBytes']) {
115
+ everything[key] += size[key];
116
+ if (chosen[group.id]) selected[key] += size[key];
117
+ }
118
+ }
119
+ return { id: group.id, kind: group.kind, default: group.default, enabled: chosen[group.id], ...(size || { files: null, bytes: null, archiveBytes: null }) };
120
+ });
121
+ return {
122
+ ok: true,
123
+ groups: rows,
124
+ totals: measured ? { selected, everything } : null,
125
+ never: measured ? measured.never : null,
126
+ irreplaceableOff: irreplaceableLeftOut(chosen),
127
+ estimate: {
128
+ state: measuring ? 'measuring' : measured ? 'ready' : failure ? 'failed' : 'none',
129
+ measuredAt: measured ? new Date(measured.at).toISOString() : null,
130
+ error: failure,
131
+ },
132
+ };
133
+ }
134
+
135
+ return {
136
+ selection, groups, setSelection, snapshot,
137
+ /** Settles when the measurement under way ended (tests, shutdown). */
138
+ idle: () => (measuring || Promise.resolve()),
139
+ /** The data changed in a way a measurement cannot know (a restore): the next reading measures again. */
140
+ invalidate: () => { measured = null; },
141
+ };
142
+ }
143
+
144
+ /**
145
+ * GET (the state; `?refresh=1` measures again) and PUT ({ groups: { id: boolean } }) of /api/system/backup/contents.
146
+ * @param {ReturnType<typeof createBackupContentsService>} service
147
+ */
148
+ export function backupContentsHandlers(service) {
149
+ const refuse = (res, error) => res.status(Number(error?.status) || 500).json({ ok: false, error: error?.message || String(error), code: error?.code || null });
150
+ return {
151
+ status(req, res) {
152
+ try { res.json(service.snapshot({ refresh: req.query?.refresh === '1' })); } catch (error) { refuse(res, error); }
153
+ },
154
+ update(req, res) {
155
+ try { service.setSelection(req.body?.groups); res.json(service.snapshot()); } catch (error) { refuse(res, error); }
156
+ },
157
+ };
158
+ }