synabun 2.3.1 → 2.4.1

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 (370) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +189 -0
  4. package/browser-extension/engine.js +508 -0
  5. package/browser-extension/icons/icon-128.png +0 -0
  6. package/browser-extension/icons/icon-16.png +0 -0
  7. package/browser-extension/icons/icon-32.png +0 -0
  8. package/browser-extension/icons/icon-48.png +0 -0
  9. package/browser-extension/icons/status-off-16.png +0 -0
  10. package/browser-extension/icons/status-off-32.png +0 -0
  11. package/browser-extension/icons/status-off-48.png +0 -0
  12. package/browser-extension/icons/status-on-16.png +0 -0
  13. package/browser-extension/icons/status-on-32.png +0 -0
  14. package/browser-extension/icons/status-on-48.png +0 -0
  15. package/browser-extension/manifest.json +56 -0
  16. package/browser-extension/popup-strings.js +250 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +166 -0
  19. package/browser-extension/popup.html +108 -0
  20. package/browser-extension/popup.js +359 -0
  21. package/browser-extension/protocol.js +232 -0
  22. package/browser-extension/service-worker.js +275 -0
  23. package/browser-extension/setup-content.js +36 -0
  24. package/browser-extension/tokens.css +326 -0
  25. package/docs/browser-extension-bridge.md +84 -0
  26. package/docs/whatsapp.md +1 -1
  27. package/lib/data-home-files.js +45 -0
  28. package/lib/data-home-migration.js +34 -58
  29. package/mcp-server/dist/http.d.ts +2 -0
  30. package/mcp-server/dist/http.d.ts.map +1 -1
  31. package/mcp-server/dist/http.js +9 -1
  32. package/mcp-server/dist/http.js.map +1 -1
  33. package/mcp-server/dist/index.d.ts +11 -0
  34. package/mcp-server/dist/index.d.ts.map +1 -1
  35. package/mcp-server/dist/index.js +38 -3
  36. package/mcp-server/dist/index.js.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  38. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  39. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  40. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  41. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  42. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  43. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.d.ts +95 -3
  45. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  46. package/mcp-server/dist/services/neural-interface.js +168 -23
  47. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  48. package/mcp-server/dist/services/team-context.d.ts +18 -0
  49. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  50. package/mcp-server/dist/services/team-context.js +29 -0
  51. package/mcp-server/dist/services/team-context.js.map +1 -0
  52. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  53. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  54. package/mcp-server/dist/services/tool-catalog.js +22 -6
  55. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  56. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  57. package/mcp-server/dist/services/tool-list.js +4 -0
  58. package/mcp-server/dist/services/tool-list.js.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  60. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  61. package/mcp-server/dist/services/tool-runtime.js +18 -1
  62. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  63. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  64. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  65. package/mcp-server/dist/tools/agent-definition.js +483 -0
  66. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  67. package/mcp-server/dist/tools/agents.d.ts +92 -9
  68. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  69. package/mcp-server/dist/tools/agents.js +163 -20
  70. package/mcp-server/dist/tools/agents.js.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  72. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  73. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  74. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  76. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/git-tools.js +283 -2
  78. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  80. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/morelogin.js +22 -5
  82. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  83. package/mcp-server/dist/tools/team.d.ts +32 -0
  84. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/team.js +87 -0
  86. package/mcp-server/dist/tools/team.js.map +1 -0
  87. package/mcp-server/package-lock.json +2 -2
  88. package/mcp-server/package.json +1 -1
  89. package/mcp-server/src/http.ts +9 -1
  90. package/mcp-server/src/index.ts +34 -4
  91. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  92. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  93. package/mcp-server/src/services/neural-interface.ts +191 -29
  94. package/mcp-server/src/services/team-context.ts +27 -0
  95. package/mcp-server/src/services/tool-catalog.ts +26 -8
  96. package/mcp-server/src/services/tool-list.ts +4 -0
  97. package/mcp-server/src/services/tool-runtime.ts +21 -2
  98. package/mcp-server/src/tools/agent-definition.ts +458 -0
  99. package/mcp-server/src/tools/agents.ts +177 -19
  100. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  101. package/mcp-server/src/tools/git-tools.ts +249 -3
  102. package/mcp-server/src/tools/morelogin.ts +20 -5
  103. package/mcp-server/src/tools/team.ts +97 -0
  104. package/neural-interface/i18n/en.json +1119 -47
  105. package/neural-interface/i18n/pt-BR.json +1119 -47
  106. package/neural-interface/lib/account-usage.js +1 -1
  107. package/neural-interface/lib/agents/builtins.json +207 -0
  108. package/neural-interface/lib/agents/density.js +101 -0
  109. package/neural-interface/lib/agents/forge-host.js +223 -0
  110. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  111. package/neural-interface/lib/agents/native-export.js +365 -0
  112. package/neural-interface/lib/agents/registry.js +885 -0
  113. package/neural-interface/lib/agents/resolve.js +603 -0
  114. package/neural-interface/lib/agents/schema.js +642 -0
  115. package/neural-interface/lib/agents/split.js +37 -0
  116. package/neural-interface/lib/agents-studio-api.js +591 -0
  117. package/neural-interface/lib/assistant-api.js +76 -7
  118. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  119. package/neural-interface/lib/assistant-catalog.js +2 -0
  120. package/neural-interface/lib/assistant-continuity.js +49 -0
  121. package/neural-interface/lib/assistant-dispatch.js +351 -121
  122. package/neural-interface/lib/assistant-persona.js +105 -8
  123. package/neural-interface/lib/assistant-route-gate.js +24 -9
  124. package/neural-interface/lib/assistant-router.js +432 -47
  125. package/neural-interface/lib/assistant-run-tail.js +151 -0
  126. package/neural-interface/lib/assistant-run-wait.js +183 -0
  127. package/neural-interface/lib/assistant-runtime.js +449 -94
  128. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  129. package/neural-interface/lib/assistant-usage.js +3 -2
  130. package/neural-interface/lib/automation-approval.js +2 -2
  131. package/neural-interface/lib/backup-service.js +64 -105
  132. package/neural-interface/lib/browser-close-evidence.js +80 -0
  133. package/neural-interface/lib/browser-default.js +210 -0
  134. package/neural-interface/lib/browser-extension-adapter.js +264 -0
  135. package/neural-interface/lib/browser-extension-bridge.js +441 -0
  136. package/neural-interface/lib/browser-extension-folder.js +116 -0
  137. package/neural-interface/lib/browser-extension-setup.js +140 -0
  138. package/neural-interface/lib/browser-profile-choices.js +3 -3
  139. package/neural-interface/lib/browser-tool-policy.js +1 -1
  140. package/neural-interface/lib/claude-account-links.js +301 -0
  141. package/neural-interface/lib/claude-accounts.js +45 -20
  142. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  143. package/neural-interface/lib/claude-model-catalog.js +6 -0
  144. package/neural-interface/lib/claude-panel-session.js +33 -0
  145. package/neural-interface/lib/codex-accounts.js +67 -24
  146. package/neural-interface/lib/coordination/README.md +384 -0
  147. package/neural-interface/lib/coordination/service.js +563 -0
  148. package/neural-interface/lib/coordination/store.js +1138 -0
  149. package/neural-interface/lib/db.js +22 -1
  150. package/neural-interface/lib/effort-levels.js +10 -1
  151. package/neural-interface/lib/memory-list-page.js +49 -0
  152. package/neural-interface/lib/memory-list-stamp.js +60 -0
  153. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  154. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  155. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  156. package/neural-interface/lib/morelogin.js +194 -8
  157. package/neural-interface/lib/native-loop-runtime.js +26 -7
  158. package/neural-interface/lib/opencode-build-preflight.js +28 -8
  159. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  160. package/neural-interface/lib/opencode-serve-records.js +14 -9
  161. package/neural-interface/lib/page-session.js +1 -1
  162. package/neural-interface/lib/peer-identity.js +73 -29
  163. package/neural-interface/lib/process-identity.js +68 -7
  164. package/neural-interface/lib/request-gate.js +3 -0
  165. package/neural-interface/lib/screenshot-location.js +33 -0
  166. package/neural-interface/lib/session-cache-builder.js +41 -3
  167. package/neural-interface/lib/skills/creation.js +1 -1
  168. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  169. package/neural-interface/lib/studio-attention.js +56 -0
  170. package/neural-interface/lib/teams/README.md +382 -0
  171. package/neural-interface/lib/teams/api.js +287 -0
  172. package/neural-interface/lib/teams/brief.js +185 -0
  173. package/neural-interface/lib/teams/claims.js +315 -0
  174. package/neural-interface/lib/teams/git.js +293 -0
  175. package/neural-interface/lib/teams/index.js +122 -0
  176. package/neural-interface/lib/teams/integration.js +580 -0
  177. package/neural-interface/lib/teams/landing.js +184 -0
  178. package/neural-interface/lib/teams/recovery.js +256 -0
  179. package/neural-interface/lib/teams/scheduler.js +1474 -0
  180. package/neural-interface/lib/teams/schema.js +559 -0
  181. package/neural-interface/lib/teams/state.js +181 -0
  182. package/neural-interface/lib/teams/test-runner.js +86 -0
  183. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  184. package/neural-interface/lib/teams/worktrees.js +757 -0
  185. package/neural-interface/lib/tool-permission-choices.js +226 -0
  186. package/neural-interface/lib/whatsapp/cards.js +24 -10
  187. package/neural-interface/lib/worker-confinement.js +206 -6
  188. package/neural-interface/package-lock.json +2 -2
  189. package/neural-interface/package.json +1 -1
  190. package/neural-interface/public/extension-setup.html +107 -0
  191. package/neural-interface/public/index.html +103 -12
  192. package/neural-interface/public/offline.html +4 -3
  193. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  194. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  195. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  196. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  197. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  198. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  199. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  200. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  201. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  202. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  203. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  204. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  205. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  206. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  207. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  208. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  209. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  210. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  211. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  212. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  213. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  214. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  215. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  216. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  217. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  218. package/neural-interface/public/shared/api.js +2 -1
  219. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  220. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  221. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  222. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  223. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  224. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  225. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  226. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  227. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  228. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  229. package/neural-interface/public/shared/assistant/asst-render.js +37 -6
  230. package/neural-interface/public/shared/assistant/asst-route.js +80 -12
  231. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  232. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  233. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  234. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  235. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  236. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  237. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  238. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  239. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  240. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  241. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  242. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  243. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  244. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  245. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  246. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  247. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  248. package/neural-interface/public/shared/code-copy.js +120 -0
  249. package/neural-interface/public/shared/constants.js +7 -0
  250. package/neural-interface/public/shared/context-menu-model.js +1 -0
  251. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  252. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  253. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  254. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  255. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  256. package/neural-interface/public/shared/dom-morph.js +124 -0
  257. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  258. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  259. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  260. package/neural-interface/public/shared/html-shell.js +34 -4
  261. package/neural-interface/public/shared/i18n.js +14 -1
  262. package/neural-interface/public/shared/idle-queue.js +78 -0
  263. package/neural-interface/public/shared/iface-config.js +227 -0
  264. package/neural-interface/public/shared/lazy-module.js +108 -0
  265. package/neural-interface/public/shared/memory-list.js +117 -0
  266. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  267. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  268. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  269. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  278. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  279. package/neural-interface/public/shared/page-session.js +1 -1
  280. package/neural-interface/public/shared/schedules-view.js +2 -2
  281. package/neural-interface/public/shared/session-project-items.js +11 -0
  282. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  283. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  284. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  285. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  286. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  287. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  288. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  289. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  290. package/neural-interface/public/shared/start-bridge.js +2 -2
  291. package/neural-interface/public/shared/storage.js +6 -1
  292. package/neural-interface/public/shared/studio-attention.js +83 -0
  293. package/neural-interface/public/shared/styles.css +694 -50
  294. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  295. package/neural-interface/public/shared/transcript-rows.js +334 -0
  296. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  297. package/neural-interface/public/shared/ui-agents.js +97 -0
  298. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  299. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  300. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  301. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  302. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  303. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  304. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  305. package/neural-interface/public/shared/ui-games.js +1 -1
  306. package/neural-interface/public/shared/ui-loading.js +83 -19
  307. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  308. package/neural-interface/public/shared/ui-menubar.js +23 -0
  309. package/neural-interface/public/shared/ui-native-loop-router.js +50 -21
  310. package/neural-interface/public/shared/ui-navbar.js +15 -9
  311. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  312. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  313. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  314. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  315. package/neural-interface/public/shared/ui-sessions.js +3 -3
  316. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  317. package/neural-interface/public/shared/ui-settings.js +363 -400
  318. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  319. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  320. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  321. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  322. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  323. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  324. package/neural-interface/public/shared/ui-sync.js +6 -0
  325. package/neural-interface/public/shared/ui-terminal.js +13 -9
  326. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  327. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  328. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  329. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  330. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  331. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  332. package/neural-interface/public/shared/window-keys.js +71 -0
  333. package/neural-interface/public/sw.js +4 -3
  334. package/neural-interface/public/variant/2d/main.js +2 -0
  335. package/neural-interface/public/variant/3d/app.js +620 -0
  336. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  337. package/neural-interface/public/variant/3d/main.js +30 -544
  338. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  339. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  340. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  341. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  342. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  343. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  346. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  347. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  348. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  349. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  350. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  351. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  352. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  353. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  354. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  355. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  356. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  357. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  358. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  359. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  360. package/neural-interface/scripts/boot-graph.mjs +270 -0
  361. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  362. package/neural-interface/server.js +1083 -164
  363. package/npm-shrinkwrap.json +2 -2
  364. package/package.json +4 -1
  365. package/skills/agent-forge/SKILL.md +182 -0
  366. package/skills/agent-forge/evals/evals.json +56 -0
  367. package/skills/agent-forge/references/definition-fields.md +61 -0
  368. package/skills/agent-forge/references/examples.md +105 -0
  369. package/skills/agent-forge/references/instructions.md +51 -0
  370. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -1,3 +1,4 @@
1
+ import { buildAssistantHandoff, providerBinding } from './assistant-continuity.js';
1
2
  import { OPENCODE_BRAIN_TOOLS } from './assistant-tools.js';
2
3
  import { storedToolList, toolListRecord } from './tool-lists.js';
3
4
  // ═══════════════════════════════════════════
@@ -21,7 +22,10 @@ import { acpPolicyInput, acpReadOnlyKind, acpToolName } from './antigravity/tool
21
22
  import { antigravityUsageTokens } from './assistant-usage.js';
22
23
  import { UNPRICED_PROVIDER_REASON } from './assistant-budget-split.js';
23
24
  import { buildAssistantPersona, formatMailbox, reconcileRouteItems } from './assistant-persona.js';
25
+ // Agents P2: the mailbox lives in the coordination store (durable, acknowledged, critical first).
26
+ import { createCoordinationService, sharedCoordinationService } from './coordination/service.js';
24
27
  import { normalizeTestDensity, testDensityStamp } from './assistant-test-density.js';
28
+ import { agentDensityStamp, normalizeAgentDensity } from './agents/density.js'; // agents-p4
25
29
  import { codexUsageCostUsd, floorCents } from './assistant-budget.js';
26
30
  import { MIN_SPEND_USD } from './assistant-budget-split.js';
27
31
  import { CLAUDE_ESTIMATE_SOURCE, createClaudeMeter, createCodexMeter, createOpenCodeMeter, totalTokens, withTotal, zeroTokens } from './assistant-usage.js';
@@ -30,7 +34,7 @@ import { normalizeRouteMode } from './assistant-config.js';
30
34
  import { TASK_CLASS_META } from './assistant-router.js';
31
35
  import { chooseUsageAccount } from './account-usage.js';
32
36
  import { defaultIsHidden, enabledStandIn, findModel, providerAllHidden, selectSheetModels } from './assistant-catalog.js';
33
- import { normalizeEffort } from './effort-levels.js';
37
+ import { EFFORT_OFF, normalizeEffort } from './effort-levels.js';
34
38
  import { claudeRouteAvailability, createRouteGate, isReplyTool, mcpStatusRouteAvailability, ROUTE_GATE_LOOP_MESSAGE } from './assistant-route-gate.js';
35
39
  import { claudeReadOnlyPermission, planDenyMessage, planToolDecision, readOnlyDenyMessage, readOnlyToolDecision } from './assistant-plan-permissions.js';
36
40
  import { codexRouteGateBootstrap } from './assistant-route-gate-codex.js';
@@ -47,11 +51,8 @@ export const BRAIN_PROVIDERS = new Set(['claude-code', 'codex', 'opencode', 'ant
47
51
  // the first prompt. Legacy "Assistant N" titles still count as unnamed.
48
52
  export const DEFAULT_SESSION_TITLE = 'SynaBun';
49
53
  export function isDefaultSessionTitle(title) { return !title || /^(?:SynaBun|Assistant(?: \d+)?)$/.test(String(title).trim()); }
50
- // suspended / resumed: a Claude Code worker a server restart cut off, and its resume on the next start
51
- // (lib/assistant-dispatch.js); a run that could not be resumed arrives as interrupted, with why.
52
- const MAILBOX_REASONS = new Set(['turn_completed', 'needs_input', 'permission_request', 'failed', 'interrupted', 'stalled', 'budget_warning', 'budget_exceeded', 'budget_unpriced', 'queue_started', 'user_intervened', 'stopped', 'suspended', 'resumed']);
53
- // A stopped run reaches the brain when the user stopped it or it ran out of money.
54
- const MAILBOX_STOP_REASONS = new Set(['user', 'budget_cap', 'session_budget_cap', 'budget_unpriced', 'budget_share']);
54
+ // Which dispatcher events reach a session's mailbox, and with what priority, is decided where they are recorded:
55
+ // lib/coordination/service.js (RUN_EVENT_REASONS, MAILBOX_STOP_REASONS).
55
56
  /** The `[SynaBun Budget]` line: a change of the session budget reaches the brain as one line before its next turn. */
56
57
  export const BUDGET_HEADER = '[SynaBun Budget]';
57
58
  /**
@@ -186,6 +187,7 @@ export function normalizeBrain(input = {}, defaults = {}, { catalog = null, cust
186
187
  agent: input?.agent ? String(input.agent) : null,
187
188
  // OpenCode and Antigravity sign in inside their own CLI: SynaBun keeps no account of theirs.
188
189
  accountId: provider === 'antigravity' ? null : input?.accountId ? String(input.accountId) : (provider === 'opencode' ? null : 'default'),
190
+ accountPolicy: ['claude-code', 'codex'].includes(provider) && (input?.accountId === 'auto' || input?.accountPolicy === 'auto') ? 'auto' : 'manual',
189
191
  cwd: input?.cwd ? String(input.cwd) : (input?.project ? String(input.project) : (defaults.cwd || null)),
190
192
  tools: provider === 'opencode' ? (storedToolList(input, { customPresets }) ?? storedToolList(defaults, { customPresets }) ?? [...OPENCODE_BRAIN_TOOLS]) : ['all'],
191
193
  permissionMode: input?.permissionMode && !legacyPlan ? String(input.permissionMode) : 'default',
@@ -284,8 +286,15 @@ export function createAssistantRuntime({
284
286
  // X-Synabun-Terminal, and that id is proven by the brain's launch credential (bind), never by a second secret;
285
287
  // revoked when the brain goes. (Codex and OpenCode brains name a pin server.js binds where it starts their process.)
286
288
  terminalTokens = null,
289
+ // The coordination service (lib/coordination/service.js): the durable mailbox. Given none, the runtime takes the
290
+ // dispatcher's, else the one server.js shares (shareCoordinationService), else one in memory (a test: nothing
291
+ // survives the process).
292
+ coordination: givenCoordination = null,
287
293
  } = {}) {
288
294
  if (!dataDir) throw new Error('createAssistantRuntime requires dataDir');
295
+ const borrowedCoordination = givenCoordination || dispatcher?.coordination || sharedCoordinationService();
296
+ const coordination = borrowedCoordination || createCoordinationService({ log });
297
+ const ownsCoordination = !borrowedCoordination;
289
298
  const normalizeSessionBrain = (input, defaults, options) => normalizeBrain(input, defaults, { ...options, ...toolListOptions() });
290
299
  const settings = {
291
300
  idleDisposeMs: Math.max(60_000, Number(config.idleDisposeMinutes || 120) * 60_000),
@@ -297,7 +306,21 @@ export function createAssistantRuntime({
297
306
  // reconcile); past it the turn is settled as not reconciled and the next turn may start.
298
307
  openCodeReconcileMs: Number(config.openCodeReconcileMs) > 0 ? Number(config.openCodeReconcileMs) : 10_000,
299
308
  bufferCap: 500,
300
- mailboxBatchMs: Number(config.mailboxBatchMs) || 2000,
309
+ // Agents P2: there is no batch window any more. A critical event (a question, a permission, a failure, a stall)
310
+ // starts its turn at once when the session is free. Other events wait this long first, so results that arrive
311
+ // together go in one turn: 150 ms at most (`mailboxBatchMs`, the old 2 s window's name, is read as this).
312
+ mailboxDebounceMs: Math.max(0, Math.min(150, Number(config.mailboxDebounceMs ?? config.mailboxBatchMs ?? 100) || 0)),
313
+ // While the brain is busy the mailbox waits for its turn to end; this covers a brain that frees up without one.
314
+ busyRecheckMs: Math.max(10, Number(config.busyRecheckMs ?? config.mailboxBatchMs ?? 1000) || 1000),
315
+ // A mailbox turn that could not be started leaves its events open and is tried again after these waits; then
316
+ // it holds until a turn of the session ends, a new event arrives or the budget changes.
317
+ mailboxRetryDelaysMs: Array.isArray(config.mailboxRetryDelaysMs) ? config.mailboxRetryDelaysMs.map((ms) => Math.max(0, Number(ms) || 0)) : [1000, 5000, 30_000],
318
+ // Events one mailbox message carries; more follow in the next one (none is dropped).
319
+ mailboxItems: Math.max(1, Number(config.mailboxItems) || coordination.limits.mailboxItems),
320
+ // After a restart: how long after the server answers the open mailboxes are delivered again.
321
+ mailboxBootDelayMs: Math.max(0, Number(config.mailboxBootDelayMs ?? 1500) || 0),
322
+ // false: the scheduler never starts a mailbox turn by itself (a test starts each one with deliverMailbox).
323
+ mailboxAuto: config.mailboxAuto !== false,
301
324
  retention: 200,
302
325
  defaultBrain: config.defaultBrain || {},
303
326
  personaExtra: config.persona?.extra || '',
@@ -315,6 +338,8 @@ export function createAssistantRuntime({
315
338
  let unsubscribeDispatcher = null;
316
339
  let unsubscribePolicy = null;
317
340
  let unsubscribeUsage = null;
341
+ let unsubscribeMailbox = null;
342
+ let mailboxBootTimer = null;
318
343
  const usageTimers = new Map();
319
344
  const usageSentAt = new Map();
320
345
  const meters = { 'claude-code': createClaudeMeter, codex: createCodexMeter, opencode: createOpenCodeMeter, ...(meterFactories || {}) };
@@ -456,7 +481,12 @@ export function createAssistantRuntime({
456
481
  // A draft: opened by a panel and not chatted in yet. Kept in memory only, listed nowhere, and
457
482
  // gone when it is closed or left without a socket (draftTimer); its first prompt stores it (startChat).
458
483
  draft: false, draftTimer: null,
459
- mailbox: [], mailboxTimer: null, obligations: new Set(), rememberedThisTurn: false, disposeTimer: null, personaText: '',
484
+ // Agents P2: what the brain has not been told yet is read from the coordination store (a look, nothing is
485
+ // handed out); nothing of it is kept here. mailboxTimer: the debounce of non-critical events; mailboxRetry*:
486
+ // a turn that could not be started is tried again.
487
+ get mailbox() { return mailboxPeek(this.record.id); },
488
+ mailboxTimer: null, mailboxAttempts: 0, mailboxRetryTimer: null, mailboxHeld: false,
489
+ obligations: new Set(), rememberedThisTurn: false, disposeTimer: null, personaText: '',
460
490
  // The last human prompt and where it came from ('ui', 'whatsapp', 'api'): a route continuation
461
491
  // answers there (lastPromptOrigin; the transcript's after a restart).
462
492
  lastPrompt: '', lastPromptOrigin: null, mailboxTurn: false, nudgedRuns: new Set(),
@@ -505,6 +535,10 @@ export function createAssistantRuntime({
505
535
  // fallback retry, and the generation each route card was raised in.
506
536
  // Closing (endSessionWork): the close under way (a promise), and the generation it started.
507
537
  gen: 0, work: new Map(), workActive: null, workTimer: null, workPumpQueued: false, routeGens: new Map(),
538
+ // The routes whose "do it here" continuation reached the brain (routerContinue never runs one twice).
539
+ continuedRoutes: new Set(),
540
+ // What the running (or last) turn was sent on: { model, effort } (runTurn), null for a new brain.
541
+ turnRun: null,
508
542
  closing: null, closedGen: 0,
509
543
  // User context (assistant-user-context.js): what the live brain was built for (a layer
510
544
  // switched since restarts an idle brain), the human turns sent and not ended yet (oldest
@@ -897,6 +931,7 @@ export function createAssistantRuntime({
897
931
  */
898
932
  function brainNeedsRestart(live) {
899
933
  if (!live?.brain) return false;
934
+ if (live.brain.needsRestart?.()) return true;
900
935
  // Its persona was built with (or without) a user-context layer that was switched since.
901
936
  if (userContext && live.brainUserContext !== null) {
902
937
  let key = null;
@@ -925,6 +960,8 @@ export function createAssistantRuntime({
925
960
  }
926
961
  /** The session's Test density: its own value, else the default level (assistant-test-density.js). */
927
962
  function testDensityOf(record) { return normalizeTestDensity(record?.testDensity); }
963
+ /** agents-p4: the session's Agent density: its own value, else the default level, Solo (lib/agents/density.js). */
964
+ function agentDensityOf(record) { return normalizeAgentDensity(record?.agentDensity); }
928
965
  function computerSupported() { try { return !!desktop?.isSupported?.(); } catch { return false; } }
929
966
  /**
930
967
  * Effective computer toggle: explicit per-session value, else the service default (ON after setup).
@@ -1007,6 +1044,7 @@ export function createAssistantRuntime({
1007
1044
  if (!persisted) delete out.usageState;
1008
1045
  // The user-context state (frozen digest, delivery ledgers) is the server's own.
1009
1046
  if (!persisted) delete out.userContext;
1047
+ if (!persisted) { delete out.providerBinding; delete out.providerHandoff; delete out.accountLimits; }
1010
1048
  if (withLive && live) {
1011
1049
  out.running = live.running;
1012
1050
  out.attached = live.sockets.size;
@@ -1024,10 +1062,14 @@ export function createAssistantRuntime({
1024
1062
  out.computerRemote = computer ? { state: computer.state, reason: computer.reason, level: computer.level, approved: live.computerTurn?.approved === true } : null;
1025
1063
  out.testDensity = testDensityOf(record);
1026
1064
  out.testDensityExplicit = normalizeTestDensity(record.testDensity, null);
1065
+ // agents-p4: how many workers one task may get (the control next to Test density); null = not set, the default.
1066
+ out.agentDensity = agentDensityOf(record);
1067
+ out.agentDensityExplicit = normalizeAgentDensity(record.agentDensity, null);
1027
1068
  // `rename`: this server keeps a rename on the record (userRenamed), so a panel writes it here.
1028
1069
  // `adminSandbox`: the global setting is served here (PUT /api/assistant/admin-sandbox).
1029
1070
  // `drafts`: a session is stored and listed from its first prompt on; `remove`: DELETE stops its work and purges it.
1030
- out.features = { routing: !!router, computer: computerSupported(), testDensity: true, rename: true, adminSandbox: !!adminSandbox, drafts: true, remove: true };
1071
+ // `agentDensity` (agents-p4): this server keeps the session's Agent density and enforces it on teams.
1072
+ out.features = { routing: !!router, computer: computerSupported(), testDensity: true, agentDensity: true, rename: true, adminSandbox: !!adminSandbox, drafts: true, remove: true };
1031
1073
  out.draft = live.draft === true;
1032
1074
  if (adminSandbox) { try { out.adminSandbox = adminSandbox.enabled() === true; } catch { out.adminSandbox = false; } }
1033
1075
  out.budget = sessionMoney(record.id);
@@ -1074,9 +1116,18 @@ export function createAssistantRuntime({
1074
1116
  const live = sessions.get(sessionId);
1075
1117
  return live?.turnTaskId || live?.record.taskId || metered('task', () => usage?.currentTask?.(sessionId)?.id) || null;
1076
1118
  }
1119
+ // Task identity also works when metering is absent or unavailable; continue the existing task sequence.
1120
+ function nextTaskId(live) {
1121
+ const prior = Number(/^task-(\d+)$/.exec(live.record.taskId || '')?.[1]) || 0;
1122
+ live.record.taskSequence = Math.max(live.record.taskSequence || 0, prior) + 1;
1123
+ return `task-${live.record.taskSequence}`;
1124
+ }
1077
1125
  /** The session's current task, made when it has none yet. Never throws. */
1078
1126
  function ensureTaskId(sessionId) {
1079
- return metered('task', () => usage?.ensureTask?.(sessionId)?.id) || null;
1127
+ const live = sessions.get(sessionId);
1128
+ const taskId = metered('task', () => usage?.ensureTask?.(sessionId)?.id) || live?.record.taskId || (live ? nextTaskId(live) : null);
1129
+ if (live && !live.record.taskId) live.record.taskId = taskId;
1130
+ return taskId;
1080
1131
  }
1081
1132
  /**
1082
1133
  * What the gauge, the usage endpoint and agent_usage show. `session` is the headline: every
@@ -1151,8 +1202,17 @@ export function createAssistantRuntime({
1151
1202
  for (const ws of sockets) { if (ws.readyState === 1) { try { ws.send(raw); } catch {} } }
1152
1203
  }
1153
1204
  /** `next`: a limitNotice() value. True when the session's notice changed (and the sockets heard). */
1154
- function setLimit(live, next) {
1155
- if (next === undefined || limitKey(next) === limitKey(live.limit)) return false;
1205
+ function setLimit(live, next, { remember = true } = {}) {
1206
+ if (next === undefined) return false;
1207
+ const key = providerBinding(live.record);
1208
+ live.record.accountLimits ||= {};
1209
+ if (remember) {
1210
+ const previous = live.record.accountLimits[key];
1211
+ if (next?.status === 'rejected') live.record.accountLimits[key] = { ...next };
1212
+ else delete live.record.accountLimits[key];
1213
+ if (JSON.stringify(previous) !== JSON.stringify(live.record.accountLimits[key])) touch(live);
1214
+ }
1215
+ if (limitKey(next) === limitKey(live.limit)) return false;
1156
1216
  live.limit = next ? { ...next, provider: live.brainProvider || live.record.brain?.provider || null, at: iso(now()) } : null;
1157
1217
  sendLimit(live);
1158
1218
  return true;
@@ -1433,7 +1493,8 @@ export function createAssistantRuntime({
1433
1493
  // The CLI began a turn on its own (a background agent finished, a wakeup fired).
1434
1494
  if (packet.type === 'turn_started' && !live.running) {
1435
1495
  // A turn the CLI started itself is a new turn for the route gate too.
1436
- live.gate?.startTurn();
1496
+ const priorGate = live.gate?.snapshot();
1497
+ live.gate?.startTurn({ open: priorGate?.state === 'open' && priorGate.taskId === live.record.taskId, taskId: live.record.taskId, cli: true });
1437
1498
  live.running = true;
1438
1499
  beginComputerTurn(live);
1439
1500
  if (usage) {
@@ -1668,6 +1729,8 @@ export function createAssistantRuntime({
1668
1729
  }
1669
1730
  function onTurnFinished(live) {
1670
1731
  if (live.mailboxTurn) { live.mailboxTurn = false; }
1732
+ // The brain just worked: a mailbox held after a turn that could not be started is tried again.
1733
+ releaseMailboxHold(live);
1671
1734
  // Non-Claude brains have no Stop hook: nudge once per run when obligations remain.
1672
1735
  if (live.brainProvider !== 'claude-code' && live.obligations.size && !live.rememberedThisTurn) {
1673
1736
  for (const runId of [...live.obligations]) {
@@ -1800,11 +1863,11 @@ export function createAssistantRuntime({
1800
1863
  if (live.workTimer) { clearTimeout(live.workTimer); live.workTimer = null; }
1801
1864
  if (shuttingDown || live.closing || sessions.get(live.record.id) !== live || live.record.status === 'ended' || activeWork(live)) return;
1802
1865
  const entry = nextWork(live);
1803
- // The mailbox waits for its batch window and the plan card.
1804
- if (!entry && !(live.mailbox.length && !live.mailboxTimer && !live.planCard)) return;
1866
+ // The mailbox waits for its debounce, the plan card, and the retry of a turn that could not be started.
1867
+ if (!entry && !(settings.mailboxAuto && !live.mailboxTimer && !live.planCard && !live.mailboxRetryTimer && !live.mailboxHeld && mailboxCount(live))) return;
1805
1868
  if (sessionBusy(live)) {
1806
1869
  // The running turn's end pumps again; this covers a brain that frees up without one.
1807
- live.workTimer = setTimeout(() => { live.workTimer = null; pumpWork(live); }, settings.mailboxBatchMs);
1870
+ live.workTimer = setTimeout(() => { live.workTimer = null; pumpWork(live); }, settings.busyRecheckMs);
1808
1871
  live.workTimer.unref?.();
1809
1872
  return;
1810
1873
  }
@@ -1976,7 +2039,7 @@ export function createAssistantRuntime({
1976
2039
  function onBudgetSplit(sessionId, budget = null, { reason = null } = {}) {
1977
2040
  sendBudget(sessionId, budget, { reason });
1978
2041
  const live = sessions.get(String(sessionId || ''));
1979
- if (live && live.mailbox.length && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; live.budgetShareTriedAt = 0; scheduleMailbox(live, 0); }
2042
+ if (live && mailboxCount(live) && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; live.budgetShareTriedAt = 0; scheduleMailbox(live, 0); }
1980
2043
  }
1981
2044
  /**
1982
2045
  * Before a brain turn: when the brain's provider share is used up but the session has money left,
@@ -2014,7 +2077,7 @@ export function createAssistantRuntime({
2014
2077
  try { dispatcher?.checkSession?.(live.record.id); } catch {}
2015
2078
  sendCost(live);
2016
2079
  sendBudget(live.record.id, null, { reason: 'budget_changed' });
2017
- if (live.mailbox.length && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; scheduleMailbox(live, 0); }
2080
+ if (mailboxCount(live) && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; scheduleMailbox(live, 0); }
2018
2081
  }
2019
2082
  }
2020
2083
  async function personaFor(live) {
@@ -2029,6 +2092,8 @@ export function createAssistantRuntime({
2029
2092
  try { setupState = desktop?.setupState?.() || null; } catch {}
2030
2093
  // This prompt states the level: a "[SynaBun Tests]" line follows only a later change.
2031
2094
  live.testDensityStamp = testDensityStamp(testDensityOf(live.record));
2095
+ // agents-p4: …and the Agent density: a "[SynaBun Agents]" line follows only a later change.
2096
+ live.agentDensityStamp = agentDensityStamp(agentDensityOf(live.record));
2032
2097
  // …and the budget: a "[SynaBun Budget]" line follows only a later change of the setting.
2033
2098
  const budgetSetting = budgetSettingNow();
2034
2099
  const money = sessionMoney(live.record.id);
@@ -2052,6 +2117,8 @@ export function createAssistantRuntime({
2052
2117
  computer: { available: computerSupported(), enabled: computerEffective(live.record), setupState, remote: computerDecision(live, { untrusted: false }) },
2053
2118
  taskClasses: TASK_CLASS_META,
2054
2119
  testDensity: testDensityOf(live.record),
2120
+ // agents-p4: the cap on workers per task, and the teams section that goes with it.
2121
+ agentDensity: agentDensityOf(live.record),
2055
2122
  // The session budget as the brain starts: the setting and, with a budget, the split so far.
2056
2123
  budget: budgetSetting ? { ...budgetSetting, view: money } : null,
2057
2124
  clarify: !!clarifier,
@@ -2074,10 +2141,24 @@ export function createAssistantRuntime({
2074
2141
  const remote = remotePolicyFor(live);
2075
2142
  if (remote) live.record.brain = clampedBrain(live, live.record.brain);
2076
2143
  const brain = live.record.brain;
2077
- const sink = { send: (packet) => onBrainPacket(live, packet) };
2144
+ // A bare legacy/mismatched id has no proven account owner. Seed from our journal.
2145
+ const binding = providerBinding(live.record);
2146
+ if (live.record.providerBinding !== binding) {
2147
+ live.record.providerSessionId = null;
2148
+ live.record.providerThreadId = null;
2149
+ live.record.providerHandoff = null;
2150
+ }
2151
+ live.record.providerBinding = binding;
2152
+ if (!live.record.providerSessionId && !live.record.providerThreadId) {
2153
+ const runs = dispatcher?.list?.({ assistantSessionId: live.record.id, limit: 500 }) || [];
2154
+ live.record.providerHandoff = buildAssistantHandoff(live.record, readTranscript(live.record.id, 10000), runs);
2155
+ }
2078
2156
  const basePersona = await personaFor(live);
2079
2157
  if (stale()) return null;
2080
2158
  if (live.brain) return live.brain;
2159
+ const epoch = live.brainEpoch = (live.brainEpoch || 0) + 1;
2160
+ const current = () => live.brainEpoch === epoch;
2161
+ const sink = { send: (packet) => { if (current()) onBrainPacket(live, packet); } };
2081
2162
  // What SynaBun has learned about the user rides after the persona, in the same system-level
2082
2163
  // slot (Claude systemPromptAppend, Codex developerInstructions, OpenCode agent prompt), frozen
2083
2164
  // per provider conversation so the prompt cache holds.
@@ -2086,7 +2167,7 @@ export function createAssistantRuntime({
2086
2167
  try { userSuffix = userContext.personaSuffix(live.record) || userSuffix; }
2087
2168
  catch (error) { log('assistant:user-context', error?.message || String(error)); }
2088
2169
  }
2089
- const persona = userSuffix.text ? `${basePersona}\n\n${userSuffix.text}` : basePersona;
2170
+ const persona = [basePersona, userSuffix.text, live.record.providerHandoff].filter(Boolean).join('\n\n');
2090
2171
  live.personaText = persona;
2091
2172
  // Computer use: one unforgeable grant per brain (the MCP `computer` group is
2092
2173
  // advertised only to callers presenting it). Revoked when the brain goes.
@@ -2128,11 +2209,11 @@ export function createAssistantRuntime({
2128
2209
  const extended = /\[extended\]$/.test(String(live.record.brain?.model || info.id || ''));
2129
2210
  return codexUsageCostUsd(usage, price, { contextWindow: extended ? info.contextWindow || null : null });
2130
2211
  },
2131
- onCodexThread: (threadId) => { if (threadId) live.record.providerThreadId = threadId; if (live.turnTaskId) pollCodex(live, { force: true }); },
2132
- onCodexUsage: () => { if (live.turnTaskId) pollCodex(live); },
2133
- onOpenCodeEvent: (type, event) => openCodeEvent(live, type, event),
2212
+ onCodexThread: (threadId) => { if (!current()) return; if (threadId) live.record.providerThreadId = threadId; if (live.turnTaskId) pollCodex(live, { force: true }); },
2213
+ onCodexUsage: () => { if (current() && live.turnTaskId) pollCodex(live); },
2214
+ onOpenCodeEvent: (type, event) => { if (current()) openCodeEvent(live, type, event); },
2134
2215
  // Also a resume into another session: what the meter counts as the main loop follows it.
2135
- onOpenCodeRoot: (sessionId) => { live.record.providerSessionId = sessionId; metered('meter-state', () => live.brainMeter?.setRoot?.(sessionId)); saveMeter(live); },
2216
+ onOpenCodeRoot: (sessionId) => { if (!current()) return; live.record.providerSessionId = sessionId; metered('meter-state', () => live.brainMeter?.setRoot?.(sessionId)); saveMeter(live); },
2136
2217
  desktopGrant: live.desktopGrant || null,
2137
2218
  brainCredential: live.brainCredential || null,
2138
2219
  // A remote session's level (lib/remote-policy.js): the Claude brain allows
@@ -2208,6 +2289,7 @@ export function createAssistantRuntime({
2208
2289
  if (identity.providerSessionId) live.record.providerSessionId = identity.providerSessionId;
2209
2290
  if (identity.providerThreadId) live.record.providerThreadId = identity.providerThreadId;
2210
2291
  } catch {}
2292
+ live.brainEpoch = (live.brainEpoch || 0) + 1;
2211
2293
  live.brain = null;
2212
2294
  // Its credential dies with it: a file send presenting it is refused from here on, and so is its pin.
2213
2295
  live.brainCredential = null;
@@ -2223,6 +2305,8 @@ export function createAssistantRuntime({
2223
2305
  live.turnTasks.length = 0;
2224
2306
  live.turnTaskId = null;
2225
2307
  live.running = false;
2308
+ // The next brain starts on the session's own model and effort.
2309
+ live.turnRun = null;
2226
2310
  closePlanCard(live, 'brain_disposed');
2227
2311
  live.planTurn = false;
2228
2312
  live.brainUserContext = null;
@@ -2391,6 +2475,19 @@ export function createAssistantRuntime({
2391
2475
  budgetBlock = brainBudgetBlock(live);
2392
2476
  }
2393
2477
  if (budgetBlock) return refuse(live, budgetBlock.code, budgetBlock.message, { request });
2478
+ if (live.switching) await live.switching;
2479
+ if (cancelled()) return dropTurn(live, request);
2480
+ if (live.record.brain.accountPolicy === 'auto') {
2481
+ await accountUsage?.refresh(live.record.brain.provider);
2482
+ if (cancelled()) return dropTurn(live, request);
2483
+ const rows = conversationAccounts(live.record.brain, live);
2484
+ const active = rows.find(row => row.id === live.record.brain.accountId);
2485
+ if (!active || active.signedIn !== true || active.mode !== 'subscription' || active.usage?.limited) {
2486
+ try { await updateSession(live.record.id, { brain: { accountId: 'auto' } }, { fromTurn: true }); }
2487
+ catch (error) { return refuse(live, error.code || 'ACCOUNT_UNAVAILABLE', error.message, { request }); }
2488
+ if (cancelled()) return dropTurn(live, request);
2489
+ }
2490
+ }
2394
2491
  // A Claude brain whose account cannot run (signed out, its key unreadable, removed) is refused with
2395
2492
  // why, before a process starts under it: the CLI would only answer "not logged in" mid-turn.
2396
2493
  if (!live.brain && ['claude-code', 'codex'].includes(live.record.brain?.provider)) {
@@ -2408,7 +2505,7 @@ export function createAssistantRuntime({
2408
2505
  await disposeBrain(live, 'budget');
2409
2506
  if (cancelled()) return dropTurn(live, request);
2410
2507
  }
2411
- // A Claude brain built for another remote level restarts (resuming its conversation).
2508
+ // A dead OpenCode serve or stale brain policy needs a fresh brain with the same conversation.
2412
2509
  if (live.brain && !live.running && brainNeedsRestart(live)) {
2413
2510
  await disposeBrain(live, 'policy');
2414
2511
  if (cancelled()) return dropTurn(live, request);
@@ -2437,6 +2534,7 @@ export function createAssistantRuntime({
2437
2534
  // A Codex / OpenCode turn's recall result, for the user-context block below.
2438
2535
  let turnRecalled = null;
2439
2536
  if (!system) {
2537
+ if (origin === 'ui' && !untrusted) { live.record.lastOwnerTurnAt = now(); persist(); }
2440
2538
  live.lastPrompt = prompt;
2441
2539
  live.lastPromptOrigin = origin ? String(origin) : null;
2442
2540
  // A prompt from elsewhere (WhatsApp, the API) is news to the panel: it goes live too.
@@ -2488,6 +2586,15 @@ export function createAssistantRuntime({
2488
2586
  live.testDensityStamp = tests;
2489
2587
  }
2490
2588
  } catch {}
2589
+ // agents-p4: Agent density changed since the brain last saw it: one "[SynaBun Agents]" line, in the same place.
2590
+ try {
2591
+ const agents = agentDensityStamp(agentDensityOf(live.record));
2592
+ if (live.agentDensityStamp === undefined) live.agentDensityStamp = agents;
2593
+ else if (live.agentDensityStamp !== agents) {
2594
+ finalText = finalText.endsWith(prompt) ? `${finalText.slice(0, finalText.length - prompt.length)}${agents}\n\n${prompt}` : `${agents}\n\n${finalText}`;
2595
+ live.agentDensityStamp = agents;
2596
+ }
2597
+ } catch {}
2491
2598
  // The budget changed since the brain last saw it: one "[SynaBun Budget]" line, in the same place.
2492
2599
  const budgetNote = budgetLine(live);
2493
2600
  if (budgetNote) finalText = finalText.endsWith(prompt) ? `${finalText.slice(0, finalText.length - prompt.length)}${budgetNote}\n\n${prompt}` : `${budgetNote}\n\n${finalText}`;
@@ -2500,9 +2607,10 @@ export function createAssistantRuntime({
2500
2607
  finalText = finalText.endsWith(prompt) ? `${finalText.slice(0, finalText.length - prompt.length)}${clarified.note}\n\n${prompt}` : `${clarified.note}\n\n${finalText}`;
2501
2608
  }
2502
2609
  // A human prompt is a new task; the reply to a clarify question stays in the one that asked.
2503
- if (usage) taskId = clarified?.note
2610
+ taskId = clarified?.note
2504
2611
  ? (live.record.taskId || ensureTaskId(live.record.id))
2505
- : metered('task', () => usage.beginTask(live.record.id, { title: prompt.split('\n')[0].slice(0, 80), at: now() })?.id);
2612
+ : metered('task', () => usage?.beginTask(live.record.id, { title: prompt.split('\n')[0].slice(0, 80), at: now(), afterSequence: live.record.taskSequence || 0 })?.id) || nextTaskId(live);
2613
+ router?.expireOtherTasks?.(live.record.id, taskId);
2506
2614
  // An image the brain's model cannot see: run this turn on a vision model
2507
2615
  // of the same provider (the conversation stays in the same session).
2508
2616
  if (Array.isArray(images) && images.length && !turnModel) {
@@ -2535,7 +2643,7 @@ export function createAssistantRuntime({
2535
2643
  appendTranscript(live.record.id, { at: iso(now()), packet: continued });
2536
2644
  sendToSockets(live, continued);
2537
2645
  }
2538
- if (usage) {
2646
+ {
2539
2647
  taskId ||= live.record.taskId || ensureTaskId(live.record.id);
2540
2648
  // record.taskId is the latest human task: a system turn that carries its own names only its turn.
2541
2649
  if (!system || !live.record.taskId) live.record.taskId = taskId;
@@ -2569,7 +2677,20 @@ export function createAssistantRuntime({
2569
2677
  // Every turn names its model: the brain was built from an older snapshot of
2570
2678
  // the record, and routed/continuation turns override it for one turn only.
2571
2679
  const effectiveModel = turnModel || live.record.brain.model || null;
2572
- const effectiveEffort = brainEffort(live.record.brain.provider, effectiveModel, turnEffort || live.record.brain.effort || null);
2680
+ const askedEffort = turnEffort || live.record.brain.effort || null;
2681
+ const effectiveEffort = brainEffort(live.record.brain.provider, effectiveModel, askedEffort);
2682
+ // Off (`none`) asked of a Claude model that cannot turn its thinking off runs at the lowest level
2683
+ // (effort-levels.js thinkingAlwaysOn): said once per model in this session, so nothing claims "thinking off".
2684
+ if (String(askedEffort || '').toLowerCase() === EFFORT_OFF && effectiveEffort && effectiveEffort !== EFFORT_OFF && effectiveEffort !== 'off' && live.record.brain.provider === 'claude-code') {
2685
+ const said = live.effortOffNoted || (live.effortOffNoted = new Set());
2686
+ const key = String(effectiveModel || 'default');
2687
+ if (!said.has(key)) {
2688
+ said.add(key);
2689
+ const packet = { type: 'event', event: { type: 'system', subtype: 'status', text: `Effort none runs as ${effectiveEffort} on ${effectiveModel || 'the default model'}: this model cannot turn its thinking off.` } };
2690
+ appendTranscript(live.record.id, { at: iso(now()), packet });
2691
+ sendToSockets(live, packet);
2692
+ }
2693
+ }
2573
2694
  // User context (assistant-user-context.js): a human turn's trace and learning start here.
2574
2695
  // A Codex / OpenCode turn gets its per-turn block now (its recall result is known); a Claude
2575
2696
  // turn gets it in the in-process UserPromptSubmit hook, which finds the handle in turnMeta.
@@ -2617,11 +2738,29 @@ export function createAssistantRuntime({
2617
2738
  // Every turn starts unrouted; a continuation or a route_decided "here" turn starts open.
2618
2739
  // Plan mode never routes: the brain explores read-only (the plan policy) and
2619
2740
  // the approved plan is routed on the next turn.
2620
- ensureGate(live)?.startTurn({ open: gateOpen || live.record.brain?.planMode === true, carry: gateCarry });
2741
+ ensureGate(live)?.startTurn({ open: gateOpen || live.record.brain?.planMode === true, carry: gateCarry, taskId });
2742
+ // What this turn runs on, as the router compares a re-routed task with it (routerSession `turn`). The
2743
+ // brain process keeps it: a turn the CLI starts by itself afterwards (a task notification) runs on it too.
2744
+ const previousRun = live.turnRun;
2745
+ live.turnRun = { model: effectiveModel, effort: askedEffort };
2621
2746
  try {
2622
2747
  await brain.sendUserTurn({ text: finalText, images, cwd, model: effectiveModel, effort: effectiveEffort, permissionMode: permissionMode || remote ? live.record.brain.permissionMode : null, planMode: live.record.brain.planMode === true });
2748
+ if (system && work?.kind === 'continuation' && work.routeId) {
2749
+ const continued = live.continuedRoutes || (live.continuedRoutes = new Set());
2750
+ continued.add(String(work.routeId));
2751
+ while (continued.size > 100) continued.delete(continued.values().next().value);
2752
+ try { router?.continuationStarted?.(work.routeId); } catch (error) { log('assistant:route-continuation', error?.message || String(error)); }
2753
+ }
2623
2754
  } catch (error) {
2755
+ if (error?.code === 'OPENCODE_SERVE_EXITED') {
2756
+ const message = error.message;
2757
+ // The exit listener normally closed the turn. If the serve died before
2758
+ // the brain entered the turn, close it here with the same single packet.
2759
+ if (live.running) onBrainPacket(live, { type: 'error', message });
2760
+ return { ok: false, code: 'TURN_FAILED', message };
2761
+ }
2624
2762
  live.running = false;
2763
+ live.turnRun = previousRun;
2625
2764
  endComputerTurn(live, 'turn_failed');
2626
2765
  // The prompt never reached the brain: its task leaves the FIFO, a turn still in flight keeps its own.
2627
2766
  const queued = live.turnTasks.lastIndexOf(taskId);
@@ -2656,18 +2795,65 @@ export function createAssistantRuntime({
2656
2795
  return true;
2657
2796
  }
2658
2797
 
2659
- // ── mailbox ────────────────────────────────────────────────────────────────
2798
+ // ── mailbox (Agents P2: the coordination store) ────────────────────────────
2799
+ // What a session's brain has not been told yet is the open events addressed to it in the coordination store
2800
+ // (lib/coordination/service.js), not a list in memory: nothing is dropped for being many, a restart loses
2801
+ // nothing, and an event is acknowledged only once the turn that carries it was started.
2802
+ // critical (a question, a permission, a failure, a stall, an interrupted run, the budget spent): its turn starts
2803
+ // at once when the session is free;
2804
+ // everything else waits `mailboxDebounceMs` (150 ms at most) so results that arrive together go in one turn;
2805
+ // 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; }
2808
+ }
2809
+ /** 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 []; }
2812
+ }
2813
+ /** 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). */
2660
2814
  function enqueueMailbox(live, item) {
2661
- live.mailbox.push({ ...item, at: iso(now()) });
2662
- if (live.mailbox.length > 40) live.mailbox.splice(0, live.mailbox.length - 40);
2663
- scheduleMailbox(live);
2815
+ try { coordination.mailbox.post(live.record.id, item); }
2816
+ catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); }
2817
+ // The store's wake-up (onMailboxEvent) schedules the delivery.
2818
+ }
2819
+ /** An event was addressed to this session (the store's wake-up, after its append committed). */
2820
+ function onMailboxEvent(live, event) {
2821
+ // News is a reason to try a held mailbox again.
2822
+ releaseMailboxHold(live, { pump: false });
2823
+ scheduleMailbox(live, event?.priority === 'critical' ? 0 : settings.mailboxDebounceMs);
2664
2824
  }
2665
- /** Items that arrive together go in one turn: the scheduler delivers them once this window closes. */
2666
- function scheduleMailbox(live, delay = settings.mailboxBatchMs) {
2667
- if (!live.mailbox.length || live.mailboxTimer) return;
2825
+ /**
2826
+ * `delay` 0: now, as soon as the session is free (a critical event, a budget that was raised). Otherwise events
2827
+ * that arrive together go in one turn: the scheduler delivers them once this short window closes.
2828
+ */
2829
+ function scheduleMailbox(live, delay = settings.mailboxDebounceMs) {
2830
+ if (!(delay > 0)) {
2831
+ if (live.mailboxTimer) { clearTimeout(live.mailboxTimer); live.mailboxTimer = null; }
2832
+ releaseMailboxHold(live, { pump: false });
2833
+ pumpSoon(live);
2834
+ return;
2835
+ }
2836
+ if (live.mailboxTimer || !mailboxCount(live)) return;
2668
2837
  live.mailboxTimer = setTimeout(() => { live.mailboxTimer = null; pumpWork(live); }, delay);
2669
2838
  live.mailboxTimer.unref?.();
2670
2839
  }
2840
+ /** A mailbox turn that could not be started waits (mailboxRetryDelaysMs), then holds; this lets it go again. */
2841
+ function releaseMailboxHold(live, { pump = true } = {}) {
2842
+ const held = live.mailboxHeld || !!live.mailboxRetryTimer;
2843
+ if (live.mailboxRetryTimer) { clearTimeout(live.mailboxRetryTimer); live.mailboxRetryTimer = null; }
2844
+ live.mailboxHeld = false;
2845
+ live.mailboxAttempts = 0;
2846
+ if (held && pump) pumpSoon(live);
2847
+ }
2848
+ function holdMailbox(live, result) {
2849
+ live.mailboxAttempts = (Number(live.mailboxAttempts) || 0) + 1;
2850
+ const delay = settings.mailboxRetryDelaysMs[live.mailboxAttempts - 1];
2851
+ log('assistant:mailbox', `${live.record.id}: the mailbox turn did not start (${result?.code || 'no result'}); its events stay open${delay === undefined ? ' until the session works again' : `, next try in ${delay} ms`}`);
2852
+ if (delay === undefined) { live.mailboxHeld = true; return; }
2853
+ if (live.mailboxRetryTimer) clearTimeout(live.mailboxRetryTimer);
2854
+ live.mailboxRetryTimer = setTimeout(() => { live.mailboxRetryTimer = null; pumpWork(live); }, delay);
2855
+ live.mailboxRetryTimer.unref?.();
2856
+ }
2671
2857
  /**
2672
2858
  * A result / needs_input item for a turn the brain already read with
2673
2859
  * agent_wait, agent_read or agent_status (the dispatcher's delivery mark).
@@ -2682,6 +2868,10 @@ export function createAssistantRuntime({
2682
2868
  try { mark = dispatcher?.deliveryState?.(item.run.runId) || null; } catch { mark = null; }
2683
2869
  return !!mark && Number(mark.turn) >= turn;
2684
2870
  }
2871
+ /** 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; }
2874
+ }
2685
2875
  /**
2686
2876
  * Out of money: the events wait (a raise or No limit re-schedules them), said once. The brain's
2687
2877
  * provider share used up while the session has money left: the budget is divided again, then the
@@ -2695,35 +2885,41 @@ export function createAssistantRuntime({
2695
2885
  coverBrainTurn(live).then((covered) => {
2696
2886
  live.budgetCovering = false;
2697
2887
  live.budgetShareTriedAt = covered ? 0 : now();
2698
- if (live.mailbox.length) scheduleMailbox(live, 0);
2888
+ if (mailboxCount(live)) scheduleMailbox(live, 0);
2699
2889
  }).catch(() => { live.budgetCovering = false; live.budgetShareTriedAt = now(); });
2700
2890
  return false;
2701
2891
  }
2702
2892
  if (live.budgetCovering) return false;
2703
2893
  if (!live.budgetHoldNotified) {
2704
2894
  live.budgetHoldNotified = true;
2705
- sendToSockets(live, { type: 'error', code: budgetBlock.code, message: `${budgetBlock.message} ${live.mailbox.length} agent event${live.mailbox.length === 1 ? '' : 's'} will reach the brain after that.` });
2895
+ const waiting = mailboxCount(live);
2896
+ sendToSockets(live, { type: 'error', code: budgetBlock.code, message: `${budgetBlock.message} ${waiting} agent event${waiting === 1 ? '' : 's'} will reach the brain after that.` });
2706
2897
  }
2707
2898
  return false;
2708
2899
  }
2709
- /** The mailbox now, if the scheduler would start it (no batch window: it is asked for). */
2900
+ /** The mailbox now, if the scheduler would start it (no debounce: it is asked for). */
2710
2901
  function deliverMailbox(live) {
2711
- if (shuttingDown || live.closing || !live.mailbox.length || sessions.get(live.record.id) !== live || live.record.status === 'ended') return Promise.resolve(null);
2902
+ if (shuttingDown || live.closing || !mailboxCount(live) || sessions.get(live.record.id) !== live || live.record.status === 'ended') return Promise.resolve(null);
2712
2903
  if (sessionBusy(live) || live.planCard || nextWork(live) || !mailboxAllowed(live)) { pumpSoon(live); return Promise.resolve(null); }
2713
2904
  return startWork(live, { kind: 'mailbox', gen: null });
2714
2905
  }
2715
2906
  /** The mailbox's turn (the scheduler's 'mailbox' work). */
2716
2907
  async function runMailboxTurn(live) {
2717
- // Read while this batch waited (inside the 2 s window, or while the brain
2718
- // was busy with the turn that waited for it): not news any more.
2719
- let unread = live.mailbox.splice(0, live.mailbox.length).filter((item) => !alreadyRead(item));
2908
+ // Read while it waited (inside the debounce, or while the brain was busy with the turn that waited for it):
2909
+ // not news any more.
2910
+ settleRead(live);
2911
+ let batch = null;
2912
+ try { batch = coordination.mailbox.pending(live.record.id, { limit: settings.mailboxItems }); }
2913
+ catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); return null; }
2914
+ let unread = batch.items;
2915
+ let more = batch.more;
2720
2916
  if (!unread.length) { scheduleDispose(live); return null; }
2721
2917
  // A decided route whose card carried the owner's computer approval is carried out in a turn of
2722
2918
  // its own: nothing else in the mailbox rides on that approval. The rest waits for the next turn.
2723
2919
  const marked = live.computerRouteGrant?.routeId || null;
2724
2920
  const own = marked ? unread.filter((item) => item?.kind === 'route_decided' && String(item.route?.routeId || '') === marked) : [];
2725
2921
  if (own.length && own.length < unread.length) {
2726
- live.mailbox.unshift(...unread.filter((item) => !own.includes(item)));
2922
+ more += unread.length - own.length;
2727
2923
  unread = own;
2728
2924
  }
2729
2925
  // A route decided with no run attached whose run exists by now is not asked to be dispatched again.
@@ -2732,26 +2928,44 @@ export function createAssistantRuntime({
2732
2928
  const items = reconcileRouteItems(unread, sessionRuns);
2733
2929
  // A budget change since the brain last saw it rides first (a raise is what released a held mailbox).
2734
2930
  const budgetNote = budgetLine(live);
2735
- const text = budgetNote ? `${budgetNote}\n\n${formatMailbox(items)}` : formatMailbox(items);
2931
+ const body = formatMailbox(items, { more });
2932
+ const text = budgetNote ? `${budgetNote}\n\n${body}` : body;
2736
2933
  sendToSockets(live, { type: 'event', event: { type: 'synabun.mailbox', items } });
2737
2934
  appendTranscript(live.record.id, { at: iso(now()), packet: { type: 'event', event: { type: 'synabun.mailbox', items } } });
2738
2935
  live.mailboxTurn = true;
2739
2936
  // The user picked "here" on a card: that turn does the task, so it starts open.
2740
2937
  const decidedHere = items.some((item) => item.kind === 'route_decided' && item.route?.target?.kind === 'direct' && !(item.runIds || []).length);
2741
2938
  const firstRun = items.find((item) => item.run);
2742
- const taskId = firstRun?.run?.turns?.find((turn) => turn.n === firstRun.turn)?.taskId || firstRun?.run?.taskId || live.record.taskId || null;
2939
+ const taskId = firstRun?.taskId || firstRun?.run?.turns?.find((turn) => turn.n === firstRun.turn)?.taskId || firstRun?.run?.taskId || live.record.taskId || null;
2743
2940
  // The decided "here" routes this turn carries out (one of them may hold the owner's computer approval).
2744
2941
  const computerRoutes = items.filter((item) => item.kind === 'route_decided' && item.route?.target?.kind === 'direct' && !(item.runIds || []).length).map((item) => String(item.route?.routeId || '')).filter(Boolean);
2745
- const result = await runQuery(live, { text, system: true, taskId, gateOpen: decidedHere, computerRoutes });
2746
- // A human prompt reached the brain first: the items go after its turn.
2747
- if (result?.code === 'ASSISTANT_BUSY') { live.mailbox.unshift(...items); live.mailboxTurn = false; }
2942
+ let result = null;
2943
+ try { result = await runQuery(live, { text, system: true, taskId, gateOpen: decidedHere, computerRoutes }); }
2944
+ catch (error) {
2945
+ // A start that threw is a start that failed: its events stay open and the retry rules below apply (never a spin).
2946
+ log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`);
2947
+ result = { ok: false, code: 'TURN_FAILED', message: error?.message || String(error) };
2948
+ }
2949
+ if (result?.ok) {
2950
+ // The turn that carries them was started: only now are they acknowledged. A turn that was refused, failed
2951
+ // 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)); }
2953
+ catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); }
2954
+ live.mailboxAttempts = 0;
2955
+ return result;
2956
+ }
2957
+ live.mailboxTurn = false;
2958
+ // A human prompt reached the brain first (ASSISTANT_BUSY): the events go after its turn, whose end pumps. A
2959
+ // turn dropped because the session closed needs no retry. Anything else is tried again, then held.
2960
+ if (result?.code !== 'ASSISTANT_BUSY' && result?.code !== 'TURN_CANCELLED') holdMailbox(live, result);
2748
2961
  return result;
2749
2962
  }
2750
2963
  function onDispatchEvent(payload) {
2751
2964
  const run = payload?.run;
2752
2965
  if (!run?.assistantSessionId) return;
2753
2966
  const live = sessions.get(run.assistantSessionId);
2754
- if (!live) return;
2967
+ // 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; }
2755
2969
  // The conversation's thread record: its runs, their outcomes and follow-ups.
2756
2970
  try { userContext?.onDispatch(live.record, payload); } catch {}
2757
2971
  if (!live.record.dispatchRunIds?.includes(run.runId)) { live.record.dispatchRunIds = [...(live.record.dispatchRunIds || []), run.runId].slice(-100); touch(live); }
@@ -2762,27 +2976,15 @@ export function createAssistantRuntime({
2762
2976
  if (payload.reason === 'completed' || payload.reason === 'failed' || payload.reason === 'stopped' || payload.reason === 'interrupted') {
2763
2977
  sendToSockets(live, { type: 'event', event: { type: 'synabun.dispatch_result', run, result: run.lastResult || null } });
2764
2978
  }
2765
- if (!MAILBOX_REASONS.has(payload.reason)) return;
2766
- if (payload.reason === 'stopped' && !MAILBOX_STOP_REASONS.has(run.completionReason)) return;
2767
- // needs_input already carries the question; its turn_completed twin would
2768
- // hand the brain the same event twice.
2769
- if (payload.reason === 'turn_completed' && run.lastResult?.status === 'needs_input') return;
2770
- const kind = payload.reason === 'turn_completed' ? 'result' : payload.reason;
2771
- const carriesResult = kind === 'result' || kind === 'needs_input';
2772
- const item = {
2773
- kind, run, summary: run.lastResult?.summary ? clip(run.lastResult.summary, 400) : null, question: run.lastResult?.question || null,
2774
- files: run.lastResult?.files || [], follow_ups: run.lastResult?.follow_ups || [], request: payload.request || null, error: run.error || null,
2775
- text: payload.text || null,
2776
- turn: Number.isFinite(Number(payload.turn)) ? Number(payload.turn) : null,
2777
- // Jev's reading of the result: a "done" its own output does not show, and a status read without a ## Result block.
2778
- unverified: carriesResult ? (run.lastResult?.unverifiedClaim?.evidence || null) : null,
2779
- resultSource: carriesResult ? (run.lastResult?.source || null) : null,
2780
- // Image / video creation: the files this turn generated ({ kind, path, url, mime, bytes }).
2781
- media: carriesResult && Array.isArray(run.lastResult?.media) ? run.lastResult.media : [],
2782
- };
2783
- // Already read by the brain (agent_wait in the same turn that dispatched it): no second turn.
2784
- if (alreadyRead(item)) return;
2785
- enqueueMailbox(live, item);
2979
+ // Agents P2: the event is in the coordination log. The dispatcher appended it in the step that changed the run;
2980
+ // recording it here again stores nothing (same id), and is what a dispatcher without the service relies on.
2981
+ // 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);
2983
+ // Already read by the brain (agent_wait in the same turn that dispatched it): no second turn. Only this event is
2984
+ // looked at here; the whole mailbox is gone through once, when a turn is composed.
2985
+ 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 {}
2987
+ }
2786
2988
  }
2787
2989
  function onRunRemoved(payload) {
2788
2990
  const live = payload?.assistantSessionId ? sessions.get(payload.assistantSessionId) : null;
@@ -2796,19 +2998,42 @@ export function createAssistantRuntime({
2796
2998
  }
2797
2999
  // A result can be waiting in the mailbox while the user clears its run.
2798
3000
  // Do not let that stale result (or its memory reminder) start another turn.
2799
- live.mailbox = live.mailbox.filter((item) => !removed.has(String(item?.run?.runId || item?.runId || '')));
2800
- if (!live.mailbox.length && live.mailboxTimer) {
3001
+ try { coordination.mailbox.discard(live.record.id, (item) => removed.has(String(item?.run?.runId || item?.runId || ''))); } catch {}
3002
+ if (!mailboxCount(live) && live.mailboxTimer) {
2801
3003
  clearTimeout(live.mailboxTimer);
2802
3004
  live.mailboxTimer = null;
2803
3005
  }
2804
3006
  }
3007
+ /**
3008
+ * Everything open for a session that no longer exists is settled (nobody will ever read it). Never while the
3009
+ * sessions index could not be read: a session this start does not know yet may be there after the next one.
3010
+ */
3011
+ function dropMailbox(sessionId) {
3012
+ if (!indexReady) return;
3013
+ try { if (coordination.mailbox.count(sessionId)) coordination.mailbox.discard(sessionId, null); } catch {}
3014
+ }
3015
+ /**
3016
+ * After a restart: what a session's brain was not told before the server went down is still open in the store,
3017
+ * and is delivered now. A session that was removed gets nothing; one that is closed waits until it is opened again.
3018
+ */
3019
+ function resumeMailboxes() {
3020
+ if (shuttingDown) return;
3021
+ let open = [];
3022
+ try { open = coordination.mailbox.sessions(); } catch { open = []; }
3023
+ for (const { sessionId } of open) {
3024
+ const live = sessions.get(sessionId);
3025
+ if (!live) { dropMailbox(sessionId); continue; }
3026
+ if (live.record.status === 'ended') continue;
3027
+ scheduleMailbox(live, 0);
3028
+ }
3029
+ }
2805
3030
  function onPermissionBroadcast(message) {
2806
3031
  const live = message?.assistantSessionId ? sessions.get(message.assistantSessionId) : null;
2807
3032
  if (!live) return;
2808
3033
  if (message.type === 'assistant:permission-request') {
2809
3034
  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 } });
2810
3035
  } else if (message.type === 'assistant:permission-resolved') {
2811
- live.mailbox = live.mailbox.filter((item) => !(item.run?.runId === message.runId && item.request?.requestId === message.requestId));
3036
+ try { coordination.mailbox.discard(live.record.id, (item) => item.run?.runId === message.runId && item.request?.requestId === message.requestId); } catch {}
2812
3037
  sendToSockets(live, { type: 'event', event: { type: 'synabun.dispatch_control_resolved', runId: message.runId, request_id: message.requestId, resolvedBy: message.resolvedBy, behavior: message.behavior } });
2813
3038
  }
2814
3039
  }
@@ -2879,14 +3104,26 @@ export function createAssistantRuntime({
2879
3104
  * they cannot. The record is flagged before it is persisted: after a restart without a new
2880
3105
  * registration the session reads as read-only.
2881
3106
  */
2882
- async function resolveAutoAccount(brain) {
3107
+ function conversationAccounts(brain, live) {
3108
+ return (accountUsage?.list()?.[brain.provider] || []).map(row => {
3109
+ const key = providerBinding({ id: live?.record.id, brain: { ...brain, accountId: row.id } });
3110
+ const limit = live?.record.accountLimits?.[key];
3111
+ return limit && (!limit.resetsAt || limit.resetsAt > now())
3112
+ ? { ...row, usage: { ...row.usage, limited: true, resetsAt: limit.resetsAt ? iso(limit.resetsAt) : null } } : row;
3113
+ });
3114
+ }
3115
+ async function resolveAutoAccount(brain, live = null) {
2883
3116
  if (brain.accountId !== 'auto' || !['claude-code', 'codex'].includes(brain.provider)) return brain;
2884
3117
  await accountUsage?.refresh(brain.provider);
2885
- const rows = accountUsage?.list()?.[brain.provider] || [];
3118
+ const rows = conversationAccounts(brain, live);
2886
3119
  const key = brain.provider === 'codex' ? 'codexAccount' : 'claudeAccount';
2887
- const { row } = chooseUsageAccount(rows, 'auto', configStore?.workers?.()?.[key] || 'default');
3120
+ const { row, reason } = chooseUsageAccount(rows, 'auto', configStore?.workers?.()?.[key] || 'default');
2888
3121
  if (!row) throw Object.assign(new Error('Auto requires a signed-in subscription account.'), { code: 'ACCOUNT_NO_SUBSCRIPTION', status: 409 });
2889
- return { ...brain, accountId: row.id };
3122
+ if (reason === 'accounts_all_limited') {
3123
+ const reset = row.usage?.resetsAt;
3124
+ throw Object.assign(new Error(`All signed-in ${brain.provider === 'codex' ? 'Codex' : 'Claude'} subscriptions are limited. ${reset ? `Soonest reset: ${reset}.` : 'Reset time is unknown.'} This chat is preserved; retry after reset or choose another provider.`), { code: 'ACCOUNTS_ALL_LIMITED', status: 409, resetsAt: reset || null });
3125
+ }
3126
+ return { ...brain, accountId: row.id, accountPolicy: 'auto' };
2890
3127
  }
2891
3128
  async function createSession({ brain = {}, label = null, cwd = null, windowId = null, fallback = false, channel = null, draft = false } = {}, internal = {}) {
2892
3129
  if (brain?.mcpProfile !== undefined) throw Object.assign(new Error('Use tools: [group ids].'), { code: 'MCP_PROFILE_REMOVED', status: 400 });
@@ -2941,6 +3178,10 @@ export function createAssistantRuntime({
2941
3178
  function applyTestDensity(live, level) {
2942
3179
  live.record.testDensity = normalizeTestDensity(level, null);
2943
3180
  }
3181
+ /** agents-p4: null, '' or an unknown value clears the session's own level: it reads as the default (Solo). */
3182
+ function applyAgentDensity(live, level) {
3183
+ live.record.agentDensity = normalizeAgentDensity(level, null);
3184
+ }
2944
3185
  function applyComputerUse(live, enabled) {
2945
3186
  // A remote session's computer use is not a per-conversation choice: the owner's switch and
2946
3187
  // the level decide (remoteComputerUse). A PATCH, the socket and updateSession change nothing.
@@ -2949,7 +3190,18 @@ export function createAssistantRuntime({
2949
3190
  live.record.computerUse = value;
2950
3191
  try { desktop?.onSessionToggle?.(live.record.id, computerEffective(live.record)); } catch {}
2951
3192
  }
2952
- async function updateSession(id, patch = {}) {
3193
+ async function updateSession(id, patch = {}, internal = {}) {
3194
+ const live = sessions.get(id);
3195
+ if (!live) return null;
3196
+ const previous = live.switching;
3197
+ const pending = (async () => {
3198
+ if (previous) await previous.catch(() => {});
3199
+ return applySessionUpdate(id, patch, internal);
3200
+ })();
3201
+ live.switching = pending;
3202
+ try { return await pending; } finally { if (live.switching === pending) live.switching = null; }
3203
+ }
3204
+ async function applySessionUpdate(id, patch = {}, { fromTurn = false } = {}) {
2953
3205
  const live = sessions.get(id);
2954
3206
  if (!live) return null;
2955
3207
  // A rename (tab, float header, sidepanel ✎) is the session's one name: every list reads it
@@ -2963,6 +3215,7 @@ export function createAssistantRuntime({
2963
3215
  if (patch.routing && typeof patch.routing === 'object' && 'mode' in patch.routing) applyRouteMode(live, patch.routing.mode);
2964
3216
  if ('computerUse' in patch) applyComputerUse(live, patch.computerUse);
2965
3217
  if ('testDensity' in patch) applyTestDensity(live, patch.testDensity);
3218
+ if ('agentDensity' in patch) applyAgentDensity(live, patch.agentDensity); // agents-p4
2966
3219
  if (patch.brain && typeof patch.brain === 'object') {
2967
3220
  // A provider switch that names no model starts from the new provider's
2968
3221
  // default, never from the old provider's model id.
@@ -2975,15 +3228,22 @@ export function createAssistantRuntime({
2975
3228
  // An effort the panel cleared (its Auto row: `effort: null`) is the model's default. normalizeBrain
2976
3229
  // would fall back to the one before it, and Off (`none`, no thinking) or a level would stay on.
2977
3230
  if (Object.hasOwn(patch.brain, 'effort') && (patch.brain.effort === null || patch.brain.effort === '')) next = { ...next, effort: null };
2978
- next = await resolveAutoAccount(next);
3231
+ if (switching || patch.brain.accountId) next.accountPolicy = patch.brain.accountId === 'auto' || (!switching && patch.brain.accountPolicy === 'auto') ? 'auto' : 'manual';
3232
+ next = await resolveAutoAccount(next, live);
2979
3233
  const modelChanged = next.model !== live.record.brain.model || next.provider !== live.record.brain.provider;
2980
3234
  if (modelChanged) next = (await enabledBrain(next)).brain;
2981
3235
  // A remote session keeps what was asked for and runs what its level allows.
2982
3236
  if ('permissionMode' in patch.brain || 'planMode' in patch.brain) next = clampModeWrite(live, next);
2983
3237
  else next = clampedBrain(live, next);
2984
3238
  const providerChanged = patch.restartBrain === true || next.provider !== live.record.brain.provider || next.accountId !== live.record.brain.accountId || next.cwd !== live.record.brain.cwd || JSON.stringify(next.tools) !== JSON.stringify(live.record.brain.tools);
3239
+ const accountChanged = next.provider !== live.record.brain.provider || next.accountId !== live.record.brain.accountId;
3240
+ if (accountChanged && (live.running || live.brain?.isBusy?.() || (!fromTurn && live.turnPending > 0))) {
3241
+ throw Object.assign(new Error('Finish or stop the current turn before switching accounts.'), { code: 'ASSISTANT_BUSY', status: 409 });
3242
+ }
3243
+ // Dispose under the OLD account: identity, meter and late callbacks belong to it.
3244
+ if (providerChanged) await disposeBrain(live, 'switched');
2985
3245
  // A usage limit is the account's: another provider or account starts without the notice.
2986
- if (next.provider !== live.record.brain.provider || next.accountId !== live.record.brain.accountId) setLimit(live, null);
3246
+ if (next.provider !== live.record.brain.provider || next.accountId !== live.record.brain.accountId) setLimit(live, null, { remember: false });
2987
3247
  live.record.brain = next;
2988
3248
  // The panel's brain names its working folder `project` and never sends `cwd`. A project picked
2989
3249
  // there (the toolbar's Working project, the empty state's picker) moves the folder the way a
@@ -2993,10 +3253,14 @@ export function createAssistantRuntime({
2993
3253
  if (folder && folder !== next.cwd) live.record.brain = { ...next, cwd: folder };
2994
3254
  live.record.project = detectProject(live.record.brain.cwd) || live.record.project || 'global';
2995
3255
  if (providerChanged) {
2996
- await disposeBrain(live, 'switched');
3256
+ // Always seed again on a switch (including switching back). An old account's
3257
+ // session may predate turns or worker results now in this chat's journal.
3258
+ live.record.providerBinding = null;
3259
+ live.record.providerHandoff = null;
3260
+ live.record.memoryGeneration = (live.record.memoryGeneration || 1) + 1;
2997
3261
  live.record.providerSessionId = null;
2998
3262
  live.record.providerThreadId = null;
2999
- // Another conversation: its user-context digest is built (and frozen) anew.
3263
+ // A fresh provider session: rebuild its digest; the chat handoff stays authoritative.
3000
3264
  try { userContext?.conversationReplaced(live.record); } catch {}
3001
3265
  if (live.record.usageState) delete live.record.usageState[next.provider === 'claude-code' ? 'claude' : next.provider];
3002
3266
  if (live.record.usageState) delete live.record.usageState.codexThreadId;
@@ -3064,6 +3328,9 @@ export function createAssistantRuntime({
3064
3328
  await disposeBrain(live, 'closed');
3065
3329
  for (const ws of live.sockets) { try { ws.close(1000, 'session destroyed'); } catch {} }
3066
3330
  sessions.delete(id);
3331
+ if (live.mailboxTimer) { clearTimeout(live.mailboxTimer); live.mailboxTimer = null; }
3332
+ if (live.mailboxRetryTimer) { clearTimeout(live.mailboxRetryTimer); live.mailboxRetryTimer = null; }
3333
+ dropMailbox(id);
3067
3334
  const usageTimer = usageTimers.get(id);
3068
3335
  if (usageTimer) clearTimeout(usageTimer);
3069
3336
  usageTimers.delete(id);
@@ -3225,7 +3492,7 @@ export function createAssistantRuntime({
3225
3492
  const superseded = movedOn === true && (inner.decline === true || inner.behavior === 'deny');
3226
3493
  const sid = live.record.id;
3227
3494
  // Route cards are answered by the router and never reach the brain.
3228
- if (router?.owns?.(rid, sid)) {
3495
+ if (router?.owns?.(rid, sid) || router?.closedRoute?.(rid, sid)) {
3229
3496
  if (superseded && typeof router.cancel === 'function') {
3230
3497
  controlResolved(live, rid, origin);
3231
3498
  router.cancel(rid, 'superseded', { sessionId: sid });
@@ -3372,7 +3639,8 @@ export function createAssistantRuntime({
3372
3639
  if (live.disposeTimer) { clearTimeout(live.disposeTimer); live.disposeTimer = null; }
3373
3640
  if (live.draftTimer) { clearTimeout(live.draftTimer); live.draftTimer = null; }
3374
3641
  live.sockets.add(ws);
3375
- live.record.status = live.record.status === 'ended' ? 'idle' : live.record.status;
3642
+ // A closed session opened again: what its workers reported meanwhile waited in the store and goes now.
3643
+ if (live.record.status === 'ended') { live.record.status = 'idle'; if (mailboxCount(live)) scheduleMailbox(live, 0); }
3376
3644
  const engine = live.brain ? { type: 'engine', engine: live.brainProvider === 'claude-code' ? 'sdk' : live.brainProvider, brain: live.brainProvider, sdkVersion } : { type: 'engine', engine: 'assistant', brain: live.record.brain.provider, sdkVersion };
3377
3645
  try { ws.send(JSON.stringify(engine)); } catch {}
3378
3646
  try { ws.send(JSON.stringify({ type: 'assistant:session', session: view(live), reason: 'attached' })); } catch {}
@@ -3447,6 +3715,13 @@ export function createAssistantRuntime({
3447
3715
  broadcast('assistant:session-updated', live);
3448
3716
  sendToSockets(live, { type: 'assistant:session', session: view(live), reason: 'tests' });
3449
3717
  return;
3718
+ // agents-p4: the Agent density control (the owner's panel socket; an agent has no way to send this).
3719
+ case 'set_agent_density':
3720
+ applyAgentDensity(live, msg.level);
3721
+ touch(live);
3722
+ broadcast('assistant:session-updated', live);
3723
+ sendToSockets(live, { type: 'assistant:session', session: view(live), reason: 'agents' });
3724
+ return;
3450
3725
  case 'set_computer_use':
3451
3726
  applyComputerUse(live, msg.enabled);
3452
3727
  touch(live);
@@ -3500,6 +3775,10 @@ export function createAssistantRuntime({
3500
3775
  }
3501
3776
  case 'resume':
3502
3777
  if (msg.providerSessionId) {
3778
+ if (['claude-code', 'codex'].includes(live.record.brain.provider) && (live.record.providerBinding !== providerBinding(live.record) || ![live.record.providerSessionId, live.record.providerThreadId].includes(msg.providerSessionId))) {
3779
+ sendToSockets(live, { type: 'error', code: 'SESSION_ACCOUNT_MISMATCH', message: 'That provider session is not bound to this chat and account. Open its own conversation instead.' });
3780
+ return;
3781
+ }
3503
3782
  const moved = msg.providerSessionId !== live.record.providerSessionId;
3504
3783
  live.record.providerSessionId = msg.providerSessionId;
3505
3784
  // A provider conversation adopted (/resume <id>): the session holds a chat now.
@@ -3532,6 +3811,12 @@ export function createAssistantRuntime({
3532
3811
  return live ? testDensityOf(live.record) : null;
3533
3812
  }
3534
3813
 
3814
+ /** agents-p4: the dispatcher's and the team scheduler's reading of a session's Agent density (wired in server.js); null for an unknown session. */
3815
+ function agentDensityFor(id) {
3816
+ const live = sessions.get(id);
3817
+ return live ? agentDensityOf(live.record) : null;
3818
+ }
3819
+
3535
3820
  // ── router sinks (wired lazily in server.js; see assistant-router.js) ──────
3536
3821
  /** What the budget planner needs of a session: its brain, project, and whether it is still open. */
3537
3822
  function budgetSession(id) {
@@ -3549,7 +3834,16 @@ export function createAssistantRuntime({
3549
3834
  // remote: a decided route authorizes one dispatch only (assistant-router.js).
3550
3835
  // computer: what remoteComputerUse says for the running turn ("ask": a computer route card done here also asks for the Mac).
3551
3836
  const computer = policy ? computerDecision(live) : null;
3552
- return { brain: live.record.brain, routingMode, running: live.running, remote: !!policy, computer: computer ? { state: computer.state, reason: computer.reason } : null };
3837
+ // turn: what the brain's running turn is on (a re-routed task continues in place when it is the approved one).
3838
+ const turn = live.turnRun ? { model: live.turnRun.model ?? null, effort: live.turnRun.effort ?? null } : null;
3839
+ // closing: the session is closing or has ended (a continuation it refuses can never run: the router answers expired).
3840
+ const closing = !!live.closing || live.record.status === 'ended';
3841
+ // pendingWork: the brain's CLI runs background work it will report back on (a background Bash, an agent, a
3842
+ // wakeup). A thinking on/off switch restarts Claude Code and would end it, so an effort-only "here" pick that
3843
+ // needs one waits (the router's thinkingWaits; the bridge defers the switch as well).
3844
+ let pendingWork = false;
3845
+ try { pendingWork = live.brain?.hasPendingWork?.() === true; } catch { pendingWork = false; }
3846
+ return { brain: live.record.brain, routingMode, agentDensity: agentDensityFor(id), taskId: currentTask(id) || ensureTaskId(id), latestTaskId: live.record.taskId, running: live.running, remote: !!policy, computer: computer ? { state: computer.state, reason: computer.reason } : null, turn, closing, pendingWork };
3553
3847
  }
3554
3848
  /**
3555
3849
  * The panel's route chip counts pending routes from the session view, so a card
@@ -3584,6 +3878,11 @@ export function createAssistantRuntime({
3584
3878
  const live = sessions.get(id);
3585
3879
  if (!live) return;
3586
3880
  emitRouteEvent(live, phase, route);
3881
+ if (phase === 'continuation_delayed') {
3882
+ const packet = { type: 'event', event: { type: 'system', subtype: 'status', text: route.reason } };
3883
+ appendTranscript(id, { at: iso(now()), packet });
3884
+ sendToSockets(live, packet);
3885
+ }
3587
3886
  if (phase !== 'card' && phase !== 'pending' && phase !== 'auto') publishPendingRoutes(live);
3588
3887
  }
3589
3888
  function routerMailbox(id, item) { const live = sessions.get(id); if (live && item) enqueueMailbox(live, item); }
@@ -3602,10 +3901,29 @@ export function createAssistantRuntime({
3602
3901
  * arrives after a newer prompt, a Stop or the session closing is refused
3603
3902
  * (false): the router then approves nothing and the card expires.
3604
3903
  */
3605
- function routerContinue(id, { target = null, route = null } = {}) {
3904
+ function routerContinue(id, { target = null, route = null, retry = false, reroute = false } = {}) {
3606
3905
  const live = sessions.get(id);
3607
3906
  if (!live || !target) return false;
3608
- const gen = live.routeGens.get(String(route?.routeId || '')) ?? live.gen;
3907
+ // Idempotent by route: the router's watchdog delivers a continuation that has not started once more, and a
3908
+ // route asked again with its task_key delivers it again. One this session already ran is done (the router
3909
+ // hears it started, and nothing runs twice); one still queued (behind a running turn, a busy brain) or on its
3910
+ // way to the brain is left where it is. Only one that was dropped (a turn that failed to start, a newer
3911
+ // prompt) is queued again, below.
3912
+ const routeId = String(route?.routeId || '');
3913
+ if (routeId) {
3914
+ if (live.continuedRoutes?.has(routeId)) {
3915
+ try { router?.continuationStarted?.(routeId); } catch {}
3916
+ return true;
3917
+ }
3918
+ const queued = live.work.get('continuation');
3919
+ if (queued?.routeId === routeId && workCurrent(live, queued)) return true;
3920
+ const active = activeWork(live);
3921
+ if (active?.kind === 'continuation' && active.routeId === routeId) return true;
3922
+ }
3923
+ // A re-route (agent_route again for an approved task) is asked in the turn running now, whatever the
3924
+ // generation the route's card was raised in or it was first delivered in: it continues after this turn,
3925
+ // in this generation (and the watchdog's retries follow it there). A retry keeps its own generation.
3926
+ const gen = reroute ? live.gen : (live.routeGens.get(routeId) ?? live.gen);
3609
3927
  if (gen !== live.gen || live.record.status === 'ended' || live.closing) {
3610
3928
  log('assistant:work', `${id}: a late "do it here" pick (${route?.routeId || 'route'}) was dropped: a newer prompt or a Stop came after its turn`);
3611
3929
  return false;
@@ -3613,9 +3931,20 @@ export function createAssistantRuntime({
3613
3931
  const row = target.model ? findModel(catalog?.peek?.() || null, target.provider, target.model)?.row : null;
3614
3932
  const label = row?.label || target.model || 'the chosen model';
3615
3933
  const summary = route?.summary || '';
3616
- const text = `[SynaBun Router] The user chose to run ${summary ? `"${summary}"` : 'this task'} here on ${label}${target.effort ? ` (effort ${target.effort})` : ''}. Continue that task now on this model, from where the conversation left off.`;
3934
+ // An effort-only pick is a continuation on the brain's own model with the picked effort, for this task only.
3935
+ const effortText = !target.effort ? '' : String(target.effort).toLowerCase() === EFFORT_OFF ? ' (thinking off)' : ` (effort ${target.effort})`;
3936
+ const text = `[SynaBun Router] The user chose to run ${summary ? `"${summary}"` : 'this task'} here on ${label}${effortText}. Continue that task now on this model, from where the conversation left off.`;
3617
3937
  // `origin`: where the prompt this task came from was written, so the continuation answers there.
3618
- queueWork(live, { kind: 'continuation', gen, options: { text, turnModel: target.model || null, turnEffort: target.effort || null, gateOpen: true, origin: lastPromptOrigin(live) } });
3938
+ // A route with no card (approved at once) belongs to the generation it was first delivered in: a later delivery
3939
+ // after a newer prompt or a Stop is refused like a late pick. A re-route moves it to this generation.
3940
+ if (routeId && (reroute || !live.routeGens.has(routeId))) {
3941
+ live.routeGens.delete(routeId);
3942
+ live.routeGens.set(routeId, gen);
3943
+ while (live.routeGens.size > 50) live.routeGens.delete(live.routeGens.keys().next().value);
3944
+ }
3945
+ if (reroute) log('assistant:work', `${id}: ${routeId || 'a route'} was routed again in a later turn; its continuation is queued`);
3946
+ else if (retry) log('assistant:work', `${id}: the "do it here" continuation of ${routeId || 'a route'} had not started; queued again`);
3947
+ queueWork(live, { kind: 'continuation', gen, routeId: route?.routeId, options: { text, turnModel: target.model || null, turnEffort: target.effort || null, gateOpen: true, origin: lastPromptOrigin(live) } });
3619
3948
  return true;
3620
3949
  }
3621
3950
  function routerSinks() {
@@ -4037,22 +4366,30 @@ export function createAssistantRuntime({
4037
4366
  if (unsubscribeDispatcher) { try { unsubscribeDispatcher(); } catch {} unsubscribeDispatcher = null; }
4038
4367
  if (unsubscribePolicy) { try { unsubscribePolicy(); } catch {} unsubscribePolicy = null; }
4039
4368
  if (unsubscribeUsage) { try { unsubscribeUsage(); } catch {} unsubscribeUsage = null; }
4369
+ if (unsubscribeMailbox) { try { unsubscribeMailbox(); } catch {} unsubscribeMailbox = null; }
4370
+ if (mailboxBootTimer) { clearTimeout(mailboxBootTimer); mailboxBootTimer = null; }
4040
4371
  for (const timer of usageTimers.values()) clearTimeout(timer);
4041
4372
  usageTimers.clear();
4042
4373
  packetObservers.clear();
4043
4374
  shuttingDown = true;
4044
4375
  for (const live of sessions.values()) {
4045
4376
  if (live.mailboxTimer) clearTimeout(live.mailboxTimer);
4377
+ if (live.mailboxRetryTimer) clearTimeout(live.mailboxRetryTimer);
4046
4378
  if (live.disposeTimer) clearTimeout(live.disposeTimer);
4047
4379
  if (live.draftTimer) clearTimeout(live.draftTimer);
4048
4380
  if (live.workTimer) clearTimeout(live.workTimer);
4049
4381
  await disposeBrain(live, 'shutdown').catch(() => {});
4050
- live.record.status = 'idle';
4382
+ // A session the user closed stays closed across the restart (loadIndex keeps 'ended'): what its workers
4383
+ // report meanwhile waits in the store until it is opened again, and starts no brain at the next start.
4384
+ if (live.record.status !== 'ended') live.record.status = 'idle';
4051
4385
  }
4052
4386
  persist({ force: true });
4053
4387
  try { userContext?.shutdown(); } catch {}
4054
4388
  // Rows whose append failed get one more try before the process goes.
4055
4389
  metered('flush', () => usage?.flush?.());
4390
+ // A coordination service this runtime made for itself goes with it (a shared one is closed by its owner).
4391
+ // What a brain was not told stays open in the store and is delivered by the next start.
4392
+ if (ownsCoordination) coordination.close();
4056
4393
  }
4057
4394
 
4058
4395
  loadIndex();
@@ -4066,18 +4403,34 @@ export function createAssistantRuntime({
4066
4403
  else if (payload?.type === 'assistant:run-removed') onRunRemoved(payload);
4067
4404
  });
4068
4405
  }
4406
+ // Agents P2: the store wakes the mailbox of the session an event was addressed to (after its append committed).
4407
+ try {
4408
+ unsubscribeMailbox = coordination.mailbox.subscribe((sessionId, event) => {
4409
+ const live = sessions.get(sessionId);
4410
+ if (live) onMailboxEvent(live, event);
4411
+ });
4412
+ } catch (error) { log('assistant:mailbox-error', error?.message || String(error)); }
4413
+ // After a restart, once this server answers its workers: the mailboxes that were open are delivered again.
4414
+ if (coordination.durable) {
4415
+ Promise.resolve().then(() => dispatcher?.whenServerReady?.()).catch(() => {}).then(() => {
4416
+ if (shuttingDown) return;
4417
+ mailboxBootTimer = setTimeout(() => { mailboxBootTimer = null; resumeMailboxes(); }, settings.mailboxBootDelayMs);
4418
+ mailboxBootTimer.unref?.();
4419
+ });
4420
+ }
4069
4421
  const originalBroadcast = broadcastSync;
4070
4422
  // Permission broadcasts come from the dispatcher through broadcastSync; observe them here too.
4071
4423
  broadcastSync = (message) => { try { originalBroadcast(message); } catch {} if (message?.type === 'assistant:permission-request' || message?.type === 'assistant:permission-resolved') onPermissionBroadcast(message); };
4072
4424
 
4073
4425
  return {
4426
+ lastOwnerTurnAt: (sessionId) => sessions.get(sessionId)?.record.lastOwnerTurnAt ?? null,
4074
4427
  handleWebSocket, listSessions, getSession, createSession, updateSession, closeSession, destroySession, removeSession,
4075
4428
  resolveTerminal, accountInUse, ownsIsolatedServe, noteDispatch, subscribe, shutdown,
4076
4429
  // The sessions index written now, synchronously: the server's exit handler runs it on every way out,
4077
4430
  // since an exit through process.exit() never reaches shutdown()'s own write.
4078
4431
  flushIndex: () => persist({ force: true }),
4079
4432
  observeBroadcast: onPermissionBroadcast,
4080
- testDensityFor, routerSession, routerSend, routerEvent, routerMailbox, routerContinue, routerSinks, routerRouted, routerRouteFailed, routerComputerApproved, gateCheck, isPlanning, isPlanReadOnly,
4433
+ testDensityFor, agentDensityFor, routerSession, routerSend, routerEvent, routerMailbox, routerContinue, routerSinks, routerRouted, routerRouteFailed, routerComputerApproved, gateCheck, isPlanning, isPlanReadOnly,
4081
4434
  clarifySession, clarifyEvent, clarifyGate, clarifySinks,
4082
4435
  getComputerUse, getComputerTurn, supersedeComputerApproval, abortTurn, notifySession,
4083
4436
  brainSpend, brainSpendByProvider, budgetSession, onBudgetChanged, onBudgetSplit, sendBudget, currentTask, usageView,
@@ -4085,6 +4438,8 @@ export function createAssistantRuntime({
4085
4438
  observe, submit, stopTurn, answerControl, answerDispatchControl, pendingControls, isBusy, sessionPolicy, sessionChannel,
4086
4439
  // whatsapp_send_file's caller identity (POST /api/assistant/whatsapp/send-file).
4087
4440
  sessionForBrainCredential,
4088
- _internals: { sessions, ensureBrain, disposeBrain, runQuery, enqueueMailbox, deliverMailbox, settings, ensureGate, onBrainPacket, onTurnFinished, remoteHooks, packetObservers, userContext },
4441
+ // Agents P2: the coordination service the mailbox reads from.
4442
+ coordination,
4443
+ _internals: { sessions, ensureBrain, disposeBrain, runQuery, enqueueMailbox, deliverMailbox, resumeMailboxes, settings, ensureGate, onBrainPacket, onTurnFinished, remoteHooks, packetObservers, userContext },
4089
4444
  };
4090
4445
  }