synabun 2.4.1 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +56 -14
  4. package/browser-extension/engine.js +158 -8
  5. package/browser-extension/manifest.json +3 -1
  6. package/browser-extension/protocol.js +91 -6
  7. package/browser-extension/service-worker.js +13 -5
  8. package/browser-extension/tokens.css +1 -1
  9. package/docs/browser-extension-bridge.md +24 -4
  10. package/lib/data-home-files.js +4 -2
  11. package/lib/first-launch-protection.js +8 -2
  12. package/lib/update-snapshot.js +11 -4
  13. package/mcp-server/dist/http.d.ts.map +1 -1
  14. package/mcp-server/dist/http.js +25 -2
  15. package/mcp-server/dist/http.js.map +1 -1
  16. package/mcp-server/dist/index.d.ts.map +1 -1
  17. package/mcp-server/dist/index.js +62 -17
  18. package/mcp-server/dist/index.js.map +1 -1
  19. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  20. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  21. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  22. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  23. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  24. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  25. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  26. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  27. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  28. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  29. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  30. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  31. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  32. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  33. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  34. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  35. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  36. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  37. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  38. package/mcp-server/dist/services/memory-schema.js +190 -13
  39. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  40. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  41. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  42. package/mcp-server/dist/services/memory-sessions.js +56 -20
  43. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  44. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  45. package/mcp-server/dist/services/memory-verification.js +8 -5
  46. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  47. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  48. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  49. package/mcp-server/dist/services/neural-interface.js +19 -2
  50. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  51. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  52. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  53. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  54. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  55. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  56. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  57. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  58. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  59. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  60. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  61. package/mcp-server/dist/services/sqlite-write.js +94 -0
  62. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  63. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  64. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  65. package/mcp-server/dist/services/sqlite.js +249 -8
  66. package/mcp-server/dist/services/sqlite.js.map +1 -1
  67. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  68. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  69. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  70. package/mcp-server/dist/services/typesafe-config.js +32 -10
  71. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  72. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  73. package/mcp-server/dist/services/typesafe.js +9 -7
  74. package/mcp-server/dist/services/typesafe.js.map +1 -1
  75. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  76. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  77. package/mcp-server/dist/services/vector-cache.js +161 -8
  78. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  79. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  80. package/mcp-server/dist/tools/agents.d.ts +11 -7
  81. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  82. package/mcp-server/dist/tools/agents.js +27 -9
  83. package/mcp-server/dist/tools/agents.js.map +1 -1
  84. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  85. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  86. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  87. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  88. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  89. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  90. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  91. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  92. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  93. package/mcp-server/dist/tools/browser-interact.js +6 -1
  94. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  95. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  96. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  97. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  98. package/mcp-server/package-lock.json +2 -2
  99. package/mcp-server/package.json +1 -1
  100. package/mcp-server/src/http.ts +20 -2
  101. package/mcp-server/src/index.ts +59 -17
  102. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  103. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  104. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  105. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  106. package/mcp-server/src/services/memory-schema.ts +194 -12
  107. package/mcp-server/src/services/memory-sessions.ts +54 -21
  108. package/mcp-server/src/services/memory-verification.ts +7 -4
  109. package/mcp-server/src/services/neural-interface.ts +22 -2
  110. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  111. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  112. package/mcp-server/src/services/sqlite-write.ts +60 -0
  113. package/mcp-server/src/services/sqlite.ts +246 -8
  114. package/mcp-server/src/services/typesafe-config.ts +25 -6
  115. package/mcp-server/src/services/typesafe.ts +9 -7
  116. package/mcp-server/src/services/vector-cache.ts +154 -9
  117. package/mcp-server/src/tools/agents.ts +26 -9
  118. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  119. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  120. package/mcp-server/src/tools/browser-interact.ts +5 -1
  121. package/neural-interface/i18n/en.json +263 -1
  122. package/neural-interface/i18n/pt-BR.json +264 -2
  123. package/neural-interface/lib/agents/split.js +32 -4
  124. package/neural-interface/lib/assistant-api.js +19 -8
  125. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  126. package/neural-interface/lib/assistant-catalog.js +2 -2
  127. package/neural-interface/lib/assistant-config.js +0 -7
  128. package/neural-interface/lib/assistant-dispatch.js +257 -95
  129. package/neural-interface/lib/assistant-persona.js +16 -4
  130. package/neural-interface/lib/assistant-pricing.js +65 -14
  131. package/neural-interface/lib/assistant-router.js +131 -47
  132. package/neural-interface/lib/assistant-run-wait.js +45 -28
  133. package/neural-interface/lib/assistant-runtime.js +39 -33
  134. package/neural-interface/lib/backup-contents.js +158 -0
  135. package/neural-interface/lib/backup-crypto-io.js +330 -0
  136. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  137. package/neural-interface/lib/backup-crypto.js +525 -0
  138. package/neural-interface/lib/backup-download.js +268 -0
  139. package/neural-interface/lib/backup-encryption.js +318 -0
  140. package/neural-interface/lib/backup-groups.js +287 -0
  141. package/neural-interface/lib/backup-restore-session.js +176 -0
  142. package/neural-interface/lib/backup-restore-stage.js +60 -0
  143. package/neural-interface/lib/backup-service.js +788 -233
  144. package/neural-interface/lib/backup-zip-reader.js +30 -18
  145. package/neural-interface/lib/backup-zip-writer.js +34 -10
  146. package/neural-interface/lib/browser-extension-adapter.js +89 -13
  147. package/neural-interface/lib/browser-extension-bridge.js +18 -7
  148. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  149. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  150. package/neural-interface/lib/cli-update-planner.js +105 -6
  151. package/neural-interface/lib/client-diagnostics.js +42 -0
  152. package/neural-interface/lib/confined-fs.js +7 -2
  153. package/neural-interface/lib/coordination/README.md +8 -2
  154. package/neural-interface/lib/coordination/contract.js +161 -0
  155. package/neural-interface/lib/coordination/database.js +999 -0
  156. package/neural-interface/lib/coordination/operations.js +436 -0
  157. package/neural-interface/lib/coordination/service.js +68 -537
  158. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  159. package/neural-interface/lib/coordination/store.js +219 -1111
  160. package/neural-interface/lib/db.js +70 -32
  161. package/neural-interface/lib/health-count.js +37 -0
  162. package/neural-interface/lib/loop-stall.js +139 -0
  163. package/neural-interface/lib/maritaca/client.js +2 -2
  164. package/neural-interface/lib/maritaca/models.js +12 -17
  165. package/neural-interface/lib/maritaca/opencode.js +4 -2
  166. package/neural-interface/lib/memory-api.js +9 -1
  167. package/neural-interface/lib/memory-session-capture.js +42 -10
  168. package/neural-interface/lib/memory-store-gate.js +313 -0
  169. package/neural-interface/lib/memory-store-migrate.js +65 -0
  170. package/neural-interface/lib/memory-timers.js +7 -7
  171. package/neural-interface/lib/native-loop-providers.js +13 -16
  172. package/neural-interface/lib/native-loop-runtime.js +28 -7
  173. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  174. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  175. package/neural-interface/lib/opencode-provider-view.js +14 -3
  176. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  177. package/neural-interface/lib/opencode2-client.js +2 -1
  178. package/neural-interface/lib/recall-impact.js +122 -0
  179. package/neural-interface/lib/scratch-evidence.js +420 -0
  180. package/neural-interface/lib/scratch-process-guard.js +139 -0
  181. package/neural-interface/lib/scratch-references.js +279 -0
  182. package/neural-interface/lib/scratch-retention-core.js +385 -0
  183. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  184. package/neural-interface/lib/scratch-retention.js +151 -0
  185. package/neural-interface/lib/session-cache-builder.js +31 -43
  186. package/neural-interface/lib/session-cache-worker.js +157 -0
  187. package/neural-interface/lib/session-indexer.js +28 -21
  188. package/neural-interface/lib/session-search-index.js +85 -0
  189. package/neural-interface/lib/skills/creation.js +1 -1
  190. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  191. package/neural-interface/lib/style-guide/store.js +43 -3
  192. package/neural-interface/lib/system-restore.js +50 -0
  193. package/neural-interface/lib/teams/api.js +15 -6
  194. package/neural-interface/lib/teams/claims.js +67 -31
  195. package/neural-interface/lib/teams/index.js +7 -7
  196. package/neural-interface/lib/teams/integration.js +40 -40
  197. package/neural-interface/lib/teams/landing.js +6 -6
  198. package/neural-interface/lib/teams/recovery.js +24 -23
  199. package/neural-interface/lib/teams/scheduler.js +194 -95
  200. package/neural-interface/lib/teams/state.js +14 -14
  201. package/neural-interface/lib/teams/worktrees.js +27 -27
  202. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  203. package/neural-interface/lib/worker-confinement.js +47 -2
  204. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  205. package/neural-interface/lib/worker-resume.js +5 -0
  206. package/neural-interface/lib/worker-stop.js +86 -0
  207. package/neural-interface/package-lock.json +2 -2
  208. package/neural-interface/package.json +1 -1
  209. package/neural-interface/public/index.html +233 -24
  210. package/neural-interface/public/onboarding.html +259 -34
  211. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  212. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  213. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  214. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  215. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  216. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  217. package/neural-interface/public/shared/api.js +1 -1
  218. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  219. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  220. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  221. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  222. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  223. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  224. package/neural-interface/public/shared/assistant/asst-render.js +105 -38
  225. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  226. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  229. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  230. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  231. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  232. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  233. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  234. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  235. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  236. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  237. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  238. package/neural-interface/public/shared/effort-i18n.js +118 -0
  239. package/neural-interface/public/shared/html-shell.js +4 -52
  240. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  241. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  242. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  243. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  244. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  245. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  246. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  247. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  248. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  249. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  250. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  251. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  252. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  253. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  254. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  255. package/neural-interface/public/shared/output-format.js +294 -0
  256. package/neural-interface/public/shared/provider-icons.js +6 -0
  257. package/neural-interface/public/shared/schedules-view.js +2 -1
  258. package/neural-interface/public/shared/server-presence.js +77 -0
  259. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  260. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  261. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  262. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  263. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  264. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  265. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  266. package/neural-interface/public/shared/studio-attention.js +6 -0
  267. package/neural-interface/public/shared/styles.css +341 -437
  268. package/neural-interface/public/shared/transcript-rows.js +28 -3
  269. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  270. package/neural-interface/public/shared/ui-agents.js +1 -2
  271. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  272. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  273. package/neural-interface/public/shared/ui-loading.js +124 -17
  274. package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
  275. package/neural-interface/public/shared/ui-navbar.js +2 -1
  276. package/neural-interface/public/shared/ui-output.js +533 -0
  277. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  278. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  279. package/neural-interface/public/shared/ui-sessions.js +2 -2
  280. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  281. package/neural-interface/public/shared/ui-settings.js +224 -65
  282. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  283. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  284. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  285. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  286. package/neural-interface/public/shared/worker-end.js +9 -4
  287. package/neural-interface/public/variant/2d/main.js +5 -0
  288. package/neural-interface/public/variant/3d/app.js +10 -0
  289. package/neural-interface/public/variant/3d/main.js +5 -1
  290. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  291. package/neural-interface/server.js +477 -139
  292. package/npm-shrinkwrap.json +2 -2
  293. package/package.json +1 -1
  294. package/scripts/restore-data-home-from-backup.mjs +175 -8
  295. package/setup.js +18 -4
@@ -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']);
@@ -1767,6 +1769,8 @@ export function createAssistantRuntime({
1767
1769
  // Pending background work re-arms this timer through the `done` of the turn
1768
1770
  // the CLI starts when that work reports back.
1769
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; }
1770
1774
  disposeBrain(live, 'idle').catch(() => {});
1771
1775
  }, settings.idleDisposeMs);
1772
1776
  live.disposeTimer.unref?.();
@@ -2330,7 +2334,8 @@ export function createAssistantRuntime({
2330
2334
  live.brainComputerMode = null;
2331
2335
  // A "do it here" continuation goes with its brain; the plan's turn does not (it starts the next brain).
2332
2336
  dropWork(live, 'continuation');
2333
- 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 {}
2334
2339
  // Clarify cards outlive a brain (the answers reach the next one as a mailbox turn), not the session.
2335
2340
  if (reason === 'closed') { try { clarifier?.cancelForSession?.(live.record.id, 'session_closed'); } catch {} }
2336
2341
  live.record.status = reason === 'closed' ? 'ended' : 'idle';
@@ -2803,17 +2808,17 @@ export function createAssistantRuntime({
2803
2808
  // at once when the session is free;
2804
2809
  // everything else waits `mailboxDebounceMs` (150 ms at most) so results that arrive together go in one turn;
2805
2810
  // while the brain is busy everything waits in the store, low-priority progress folded, and goes when it is free.
2806
- function mailboxCount(live, options) {
2807
- 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; }
2808
2813
  }
2809
2814
  /** A look at what a session has open (the `live.mailbox` view): nothing is handed out or acknowledged. */
2810
- function mailboxPeek(sessionId) {
2811
- 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 []; }
2812
2817
  }
2813
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). */
2814
- function enqueueMailbox(live, item) {
2815
- try { coordination.mailbox.post(live.record.id, item); }
2816
- 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; }
2817
2822
  // The store's wake-up (onMailboxEvent) schedules the delivery.
2818
2823
  }
2819
2824
  /** An event was addressed to this session (the store's wake-up, after its append committed). */
@@ -2869,8 +2874,8 @@ export function createAssistantRuntime({
2869
2874
  return !!mark && Number(mark.turn) >= turn;
2870
2875
  }
2871
2876
  /** Events the brain read by itself meanwhile are settled without a turn. → how many. */
2872
- function settleRead(live) {
2873
- 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; }
2874
2879
  }
2875
2880
  /**
2876
2881
  * Out of money: the events wait (a raise or No limit re-schedules them), said once. The brain's
@@ -2898,7 +2903,8 @@ export function createAssistantRuntime({
2898
2903
  return false;
2899
2904
  }
2900
2905
  /** The mailbox now, if the scheduler would start it (no debounce: it is asked for). */
2901
- function deliverMailbox(live) {
2906
+ async function deliverMailbox(live) {
2907
+ if (!await coordination.mailbox.count(live.record.id)) return null;
2902
2908
  if (shuttingDown || live.closing || !mailboxCount(live) || sessions.get(live.record.id) !== live || live.record.status === 'ended') return Promise.resolve(null);
2903
2909
  if (sessionBusy(live) || live.planCard || nextWork(live) || !mailboxAllowed(live)) { pumpSoon(live); return Promise.resolve(null); }
2904
2910
  return startWork(live, { kind: 'mailbox', gen: null });
@@ -2907,9 +2913,9 @@ export function createAssistantRuntime({
2907
2913
  async function runMailboxTurn(live) {
2908
2914
  // Read while it waited (inside the debounce, or while the brain was busy with the turn that waited for it):
2909
2915
  // not news any more.
2910
- settleRead(live);
2916
+ await settleRead(live);
2911
2917
  let batch = null;
2912
- try { batch = coordination.mailbox.pending(live.record.id, { limit: settings.mailboxItems }); }
2918
+ try { batch = await coordination.mailbox.pending(live.record.id, { limit: settings.mailboxItems }); }
2913
2919
  catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); return null; }
2914
2920
  let unread = batch.items;
2915
2921
  let more = batch.more;
@@ -2949,7 +2955,7 @@ export function createAssistantRuntime({
2949
2955
  if (result?.ok) {
2950
2956
  // The turn that carries them was started: only now are they acknowledged. A turn that was refused, failed
2951
2957
  // or found the brain busy leaves every one of them open, also across a restart.
2952
- 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)); }
2953
2959
  catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); }
2954
2960
  live.mailboxAttempts = 0;
2955
2961
  return result;
@@ -2960,12 +2966,12 @@ export function createAssistantRuntime({
2960
2966
  if (result?.code !== 'ASSISTANT_BUSY' && result?.code !== 'TURN_CANCELLED') holdMailbox(live, result);
2961
2967
  return result;
2962
2968
  }
2963
- function onDispatchEvent(payload) {
2969
+ async function onDispatchEvent(payload) {
2964
2970
  const run = payload?.run;
2965
2971
  if (!run?.assistantSessionId) return;
2966
2972
  const live = sessions.get(run.assistantSessionId);
2967
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.
2968
- if (!live) { dropMailbox(run.assistantSessionId); return; }
2974
+ if (!live) { await dropMailbox(run.assistantSessionId); return; }
2969
2975
  // The conversation's thread record: its runs, their outcomes and follow-ups.
2970
2976
  try { userContext?.onDispatch(live.record, payload); } catch {}
2971
2977
  if (!live.record.dispatchRunIds?.includes(run.runId)) { live.record.dispatchRunIds = [...(live.record.dispatchRunIds || []), run.runId].slice(-100); touch(live); }
@@ -2979,14 +2985,14 @@ export function createAssistantRuntime({
2979
2985
  // Agents P2: the event is in the coordination log. The dispatcher appended it in the step that changed the run;
2980
2986
  // recording it here again stores nothing (same id), and is what a dispatcher without the service relies on.
2981
2987
  // Which reasons reach the brain, and how urgently, is the service's rule. The store's wake-up schedules the turn.
2982
- const recorded = coordination.recordDispatch(payload);
2988
+ const recorded = await coordination.recordDispatch(payload);
2983
2989
  // Already read by the brain (agent_wait in the same turn that dispatched it): no second turn. Only this event is
2984
2990
  // looked at here; the whole mailbox is gone through once, when a turn is composed.
2985
2991
  if (recorded?.delivered && alreadyRead({ kind: payload.reason === 'turn_completed' ? 'result' : payload.reason, turn: payload.turn, run })) {
2986
- try { coordination.mailbox.ack(live.record.id, [recorded.id]); } catch {}
2992
+ try { await coordination.mailbox.ack(live.record.id, [recorded.id]); } catch {}
2987
2993
  }
2988
2994
  }
2989
- function onRunRemoved(payload) {
2995
+ async function onRunRemoved(payload) {
2990
2996
  const live = payload?.assistantSessionId ? sessions.get(payload.assistantSessionId) : null;
2991
2997
  if (!live) return;
2992
2998
  const removed = new Set((payload.runIds || []).map(String));
@@ -2998,7 +3004,7 @@ export function createAssistantRuntime({
2998
3004
  }
2999
3005
  // A result can be waiting in the mailbox while the user clears its run.
3000
3006
  // Do not let that stale result (or its memory reminder) start another turn.
3001
- 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 {}
3002
3008
  if (!mailboxCount(live) && live.mailboxTimer) {
3003
3009
  clearTimeout(live.mailboxTimer);
3004
3010
  live.mailboxTimer = null;
@@ -3008,32 +3014,32 @@ export function createAssistantRuntime({
3008
3014
  * Everything open for a session that no longer exists is settled (nobody will ever read it). Never while the
3009
3015
  * sessions index could not be read: a session this start does not know yet may be there after the next one.
3010
3016
  */
3011
- function dropMailbox(sessionId) {
3017
+ async function dropMailbox(sessionId) {
3012
3018
  if (!indexReady) return;
3013
- 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 {}
3014
3020
  }
3015
3021
  /**
3016
3022
  * After a restart: what a session's brain was not told before the server went down is still open in the store,
3017
3023
  * and is delivered now. A session that was removed gets nothing; one that is closed waits until it is opened again.
3018
3024
  */
3019
- function resumeMailboxes() {
3025
+ async function resumeMailboxes() {
3020
3026
  if (shuttingDown) return;
3021
3027
  let open = [];
3022
- try { open = coordination.mailbox.sessions(); } catch { open = []; }
3028
+ try { open = await coordination.mailbox.sessions(); } catch { open = []; }
3023
3029
  for (const { sessionId } of open) {
3024
3030
  const live = sessions.get(sessionId);
3025
- if (!live) { dropMailbox(sessionId); continue; }
3031
+ if (!live) { await dropMailbox(sessionId); continue; }
3026
3032
  if (live.record.status === 'ended') continue;
3027
3033
  scheduleMailbox(live, 0);
3028
3034
  }
3029
3035
  }
3030
- function onPermissionBroadcast(message) {
3036
+ async function onPermissionBroadcast(message) {
3031
3037
  const live = message?.assistantSessionId ? sessions.get(message.assistantSessionId) : null;
3032
3038
  if (!live) return;
3033
3039
  if (message.type === 'assistant:permission-request') {
3034
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 } });
3035
3041
  } else if (message.type === 'assistant:permission-resolved') {
3036
- 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 {}
3037
3043
  sendToSockets(live, { type: 'event', event: { type: 'synabun.dispatch_control_resolved', runId: message.runId, request_id: message.requestId, resolvedBy: message.resolvedBy, behavior: message.behavior } });
3038
3044
  }
3039
3045
  }
@@ -3330,7 +3336,7 @@ export function createAssistantRuntime({
3330
3336
  sessions.delete(id);
3331
3337
  if (live.mailboxTimer) { clearTimeout(live.mailboxTimer); live.mailboxTimer = null; }
3332
3338
  if (live.mailboxRetryTimer) { clearTimeout(live.mailboxRetryTimer); live.mailboxRetryTimer = null; }
3333
- dropMailbox(id);
3339
+ await dropMailbox(id);
3334
3340
  const usageTimer = usageTimers.get(id);
3335
3341
  if (usageTimer) clearTimeout(usageTimer);
3336
3342
  usageTimers.delete(id);
@@ -3461,7 +3467,7 @@ export function createAssistantRuntime({
3461
3467
  // A remote session: computer use stops with the turn, before the brain is even asked to (its
3462
3468
  // approval, its open request, the live grant; an action in progress is aborted).
3463
3469
  endComputerTurn(live, 'stopped');
3464
- 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 {}
3465
3471
  if (origin !== 'ui') log('assistant:stop', `${live.record.id}: turn stopped from ${origin}`);
3466
3472
  try { await live.brain?.abort?.(); } catch (error) { return { ok: false, code: 'STOP_FAILED', message: error?.message || String(error) }; }
3467
3473
  return { ok: true };
@@ -3885,7 +3891,7 @@ export function createAssistantRuntime({
3885
3891
  }
3886
3892
  if (phase !== 'card' && phase !== 'pending' && phase !== 'auto') publishPendingRoutes(live);
3887
3893
  }
3888
- 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); }
3889
3895
  /** agent_route answered (or failed) for this session: the route gate follows it (`meta.taskClass`: a chat route holds). */
3890
3896
  function routerRouted(id, result, meta = {}) { const live = sessions.get(id); if (live) ensureGate(live)?.onRouteResult(result, meta); }
3891
3897
  function routerRouteFailed(id, error) {
@@ -4389,7 +4395,7 @@ export function createAssistantRuntime({
4389
4395
  metered('flush', () => usage?.flush?.());
4390
4396
  // A coordination service this runtime made for itself goes with it (a shared one is closed by its owner).
4391
4397
  // What a brain was not told stays open in the store and is delivered by the next start.
4392
- if (ownsCoordination) coordination.close();
4398
+ if (ownsCoordination) await coordination.close();
4393
4399
  }
4394
4400
 
4395
4401
  loadIndex();
@@ -4399,8 +4405,8 @@ export function createAssistantRuntime({
4399
4405
  }
4400
4406
  if (dispatcher?.subscribe) {
4401
4407
  unsubscribeDispatcher = dispatcher.subscribe((payload) => {
4402
- if (payload?.type === 'assistant:dispatch') onDispatchEvent(payload);
4403
- 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);
4404
4410
  });
4405
4411
  }
4406
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
+ }