synabun 2.3.1 → 2.4.0

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 (356) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +169 -0
  4. package/browser-extension/engine.js +477 -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 +244 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +165 -0
  19. package/browser-extension/popup.html +105 -0
  20. package/browser-extension/popup.js +347 -0
  21. package/browser-extension/protocol.js +226 -0
  22. package/browser-extension/service-worker.js +267 -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/mcp-server/dist/http.d.ts +2 -0
  28. package/mcp-server/dist/http.d.ts.map +1 -1
  29. package/mcp-server/dist/http.js +9 -1
  30. package/mcp-server/dist/http.js.map +1 -1
  31. package/mcp-server/dist/index.d.ts +11 -0
  32. package/mcp-server/dist/index.d.ts.map +1 -1
  33. package/mcp-server/dist/index.js +38 -3
  34. package/mcp-server/dist/index.js.map +1 -1
  35. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  36. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  38. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  39. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  40. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  41. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +94 -3
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +168 -23
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/team-context.d.ts +18 -0
  47. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  48. package/mcp-server/dist/services/team-context.js +29 -0
  49. package/mcp-server/dist/services/team-context.js.map +1 -0
  50. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  51. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  52. package/mcp-server/dist/services/tool-catalog.js +22 -6
  53. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  54. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  55. package/mcp-server/dist/services/tool-list.js +4 -0
  56. package/mcp-server/dist/services/tool-list.js.map +1 -1
  57. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  58. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.js +18 -1
  60. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  61. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  62. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/agent-definition.js +483 -0
  64. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  65. package/mcp-server/dist/tools/agents.d.ts +91 -9
  66. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  67. package/mcp-server/dist/tools/agents.js +161 -20
  68. package/mcp-server/dist/tools/agents.js.map +1 -1
  69. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  70. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  72. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  73. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  74. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.js +283 -2
  76. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  77. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  78. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.js +22 -5
  80. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  81. package/mcp-server/dist/tools/team.d.ts +32 -0
  82. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  83. package/mcp-server/dist/tools/team.js +87 -0
  84. package/mcp-server/dist/tools/team.js.map +1 -0
  85. package/mcp-server/package-lock.json +2 -2
  86. package/mcp-server/package.json +1 -1
  87. package/mcp-server/src/http.ts +9 -1
  88. package/mcp-server/src/index.ts +34 -4
  89. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  90. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  91. package/mcp-server/src/services/neural-interface.ts +190 -29
  92. package/mcp-server/src/services/team-context.ts +27 -0
  93. package/mcp-server/src/services/tool-catalog.ts +26 -8
  94. package/mcp-server/src/services/tool-list.ts +4 -0
  95. package/mcp-server/src/services/tool-runtime.ts +21 -2
  96. package/mcp-server/src/tools/agent-definition.ts +458 -0
  97. package/mcp-server/src/tools/agents.ts +175 -19
  98. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  99. package/mcp-server/src/tools/git-tools.ts +249 -3
  100. package/mcp-server/src/tools/morelogin.ts +20 -5
  101. package/mcp-server/src/tools/team.ts +97 -0
  102. package/neural-interface/i18n/en.json +1117 -47
  103. package/neural-interface/i18n/pt-BR.json +1117 -47
  104. package/neural-interface/lib/account-usage.js +1 -1
  105. package/neural-interface/lib/agents/density.js +101 -0
  106. package/neural-interface/lib/agents/forge-host.js +223 -0
  107. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  108. package/neural-interface/lib/agents/native-export.js +365 -0
  109. package/neural-interface/lib/agents/registry.js +840 -0
  110. package/neural-interface/lib/agents/resolve.js +544 -0
  111. package/neural-interface/lib/agents/schema.js +642 -0
  112. package/neural-interface/lib/agents/split.js +37 -0
  113. package/neural-interface/lib/agents-studio-api.js +591 -0
  114. package/neural-interface/lib/assistant-api.js +76 -7
  115. package/neural-interface/lib/assistant-catalog.js +2 -0
  116. package/neural-interface/lib/assistant-continuity.js +49 -0
  117. package/neural-interface/lib/assistant-dispatch.js +229 -102
  118. package/neural-interface/lib/assistant-persona.js +105 -8
  119. package/neural-interface/lib/assistant-route-gate.js +24 -9
  120. package/neural-interface/lib/assistant-router.js +384 -42
  121. package/neural-interface/lib/assistant-run-tail.js +151 -0
  122. package/neural-interface/lib/assistant-run-wait.js +183 -0
  123. package/neural-interface/lib/assistant-runtime.js +440 -93
  124. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  125. package/neural-interface/lib/assistant-usage.js +3 -2
  126. package/neural-interface/lib/automation-approval.js +2 -2
  127. package/neural-interface/lib/browser-close-evidence.js +80 -0
  128. package/neural-interface/lib/browser-default.js +210 -0
  129. package/neural-interface/lib/browser-extension-adapter.js +255 -0
  130. package/neural-interface/lib/browser-extension-bridge.js +418 -0
  131. package/neural-interface/lib/browser-extension-folder.js +116 -0
  132. package/neural-interface/lib/browser-extension-setup.js +140 -0
  133. package/neural-interface/lib/browser-profile-choices.js +3 -3
  134. package/neural-interface/lib/browser-tool-policy.js +1 -1
  135. package/neural-interface/lib/claude-account-links.js +301 -0
  136. package/neural-interface/lib/claude-accounts.js +45 -20
  137. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  138. package/neural-interface/lib/claude-model-catalog.js +6 -0
  139. package/neural-interface/lib/claude-panel-session.js +33 -0
  140. package/neural-interface/lib/codex-accounts.js +67 -24
  141. package/neural-interface/lib/coordination/README.md +384 -0
  142. package/neural-interface/lib/coordination/service.js +563 -0
  143. package/neural-interface/lib/coordination/store.js +1138 -0
  144. package/neural-interface/lib/db.js +22 -1
  145. package/neural-interface/lib/effort-levels.js +10 -1
  146. package/neural-interface/lib/memory-list-page.js +49 -0
  147. package/neural-interface/lib/memory-list-stamp.js +60 -0
  148. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  149. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  150. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  151. package/neural-interface/lib/morelogin.js +194 -8
  152. package/neural-interface/lib/native-loop-runtime.js +20 -0
  153. package/neural-interface/lib/opencode-build-preflight.js +16 -1
  154. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  155. package/neural-interface/lib/opencode-serve-records.js +14 -9
  156. package/neural-interface/lib/page-session.js +1 -1
  157. package/neural-interface/lib/peer-identity.js +60 -21
  158. package/neural-interface/lib/process-identity.js +68 -7
  159. package/neural-interface/lib/request-gate.js +3 -0
  160. package/neural-interface/lib/screenshot-location.js +33 -0
  161. package/neural-interface/lib/skills/creation.js +1 -1
  162. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  163. package/neural-interface/lib/studio-attention.js +56 -0
  164. package/neural-interface/lib/teams/README.md +382 -0
  165. package/neural-interface/lib/teams/api.js +287 -0
  166. package/neural-interface/lib/teams/brief.js +185 -0
  167. package/neural-interface/lib/teams/claims.js +315 -0
  168. package/neural-interface/lib/teams/git.js +293 -0
  169. package/neural-interface/lib/teams/index.js +122 -0
  170. package/neural-interface/lib/teams/integration.js +580 -0
  171. package/neural-interface/lib/teams/landing.js +184 -0
  172. package/neural-interface/lib/teams/recovery.js +256 -0
  173. package/neural-interface/lib/teams/scheduler.js +1474 -0
  174. package/neural-interface/lib/teams/schema.js +559 -0
  175. package/neural-interface/lib/teams/state.js +181 -0
  176. package/neural-interface/lib/teams/test-runner.js +86 -0
  177. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  178. package/neural-interface/lib/teams/worktrees.js +757 -0
  179. package/neural-interface/lib/tool-permission-choices.js +226 -0
  180. package/neural-interface/lib/whatsapp/cards.js +24 -10
  181. package/neural-interface/lib/worker-confinement.js +206 -6
  182. package/neural-interface/package-lock.json +2 -2
  183. package/neural-interface/package.json +1 -1
  184. package/neural-interface/public/extension-setup.html +107 -0
  185. package/neural-interface/public/index.html +52 -12
  186. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  187. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  188. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  189. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  190. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  191. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  192. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  193. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  194. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  195. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  196. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  197. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  198. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  199. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  200. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  201. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  202. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  203. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  204. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  205. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  206. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  207. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  208. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  209. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  210. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  211. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  212. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  213. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  214. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  215. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  216. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  217. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  218. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  219. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  220. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  221. package/neural-interface/public/shared/assistant/asst-render.js +36 -6
  222. package/neural-interface/public/shared/assistant/asst-route.js +78 -12
  223. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  224. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  225. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  226. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  229. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  230. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  231. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  232. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  233. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  234. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  235. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  236. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  237. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  238. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  239. package/neural-interface/public/shared/code-copy.js +120 -0
  240. package/neural-interface/public/shared/constants.js +7 -0
  241. package/neural-interface/public/shared/context-menu-model.js +1 -0
  242. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  243. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  244. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  245. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  246. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  247. package/neural-interface/public/shared/dom-morph.js +124 -0
  248. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  249. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  250. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  251. package/neural-interface/public/shared/html-shell.js +33 -4
  252. package/neural-interface/public/shared/i18n.js +14 -1
  253. package/neural-interface/public/shared/idle-queue.js +78 -0
  254. package/neural-interface/public/shared/iface-config.js +227 -0
  255. package/neural-interface/public/shared/lazy-module.js +108 -0
  256. package/neural-interface/public/shared/memory-list.js +117 -0
  257. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  258. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  259. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  260. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  261. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  269. package/neural-interface/public/shared/schedules-view.js +2 -2
  270. package/neural-interface/public/shared/session-project-items.js +11 -0
  271. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  272. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  273. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  274. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  275. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  276. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  277. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  278. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  279. package/neural-interface/public/shared/storage.js +6 -1
  280. package/neural-interface/public/shared/studio-attention.js +83 -0
  281. package/neural-interface/public/shared/styles.css +682 -50
  282. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  283. package/neural-interface/public/shared/transcript-rows.js +334 -0
  284. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  285. package/neural-interface/public/shared/ui-agents.js +97 -0
  286. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  287. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  288. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  289. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  290. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  291. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  292. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  293. package/neural-interface/public/shared/ui-games.js +1 -1
  294. package/neural-interface/public/shared/ui-loading.js +12 -1
  295. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  296. package/neural-interface/public/shared/ui-menubar.js +23 -0
  297. package/neural-interface/public/shared/ui-native-loop-router.js +1 -1
  298. package/neural-interface/public/shared/ui-navbar.js +15 -9
  299. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  300. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  301. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  302. package/neural-interface/public/shared/ui-sessions.js +3 -3
  303. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  304. package/neural-interface/public/shared/ui-settings.js +355 -400
  305. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  306. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  307. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  308. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  309. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  310. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  311. package/neural-interface/public/shared/ui-sync.js +5 -0
  312. package/neural-interface/public/shared/ui-terminal.js +13 -9
  313. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  314. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  315. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  316. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  317. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  318. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  319. package/neural-interface/public/shared/window-keys.js +71 -0
  320. package/neural-interface/public/variant/2d/main.js +2 -0
  321. package/neural-interface/public/variant/3d/app.js +620 -0
  322. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  323. package/neural-interface/public/variant/3d/main.js +21 -544
  324. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  325. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  326. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  327. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  328. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  329. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  330. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  331. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  332. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  333. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  334. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  335. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  336. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  337. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  338. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  339. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  340. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  341. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  342. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  343. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  346. package/neural-interface/scripts/boot-graph.mjs +270 -0
  347. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  348. package/neural-interface/server.js +1050 -140
  349. package/npm-shrinkwrap.json +2 -2
  350. package/package.json +3 -1
  351. package/skills/agent-forge/SKILL.md +182 -0
  352. package/skills/agent-forge/evals/evals.json +56 -0
  353. package/skills/agent-forge/references/definition-fields.md +61 -0
  354. package/skills/agent-forge/references/examples.md +105 -0
  355. package/skills/agent-forge/references/instructions.md +51 -0
  356. 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
@@ -925,6 +959,8 @@ export function createAssistantRuntime({
925
959
  }
926
960
  /** The session's Test density: its own value, else the default level (assistant-test-density.js). */
927
961
  function testDensityOf(record) { return normalizeTestDensity(record?.testDensity); }
962
+ /** agents-p4: the session's Agent density: its own value, else the default level, Solo (lib/agents/density.js). */
963
+ function agentDensityOf(record) { return normalizeAgentDensity(record?.agentDensity); }
928
964
  function computerSupported() { try { return !!desktop?.isSupported?.(); } catch { return false; } }
929
965
  /**
930
966
  * Effective computer toggle: explicit per-session value, else the service default (ON after setup).
@@ -1007,6 +1043,7 @@ export function createAssistantRuntime({
1007
1043
  if (!persisted) delete out.usageState;
1008
1044
  // The user-context state (frozen digest, delivery ledgers) is the server's own.
1009
1045
  if (!persisted) delete out.userContext;
1046
+ if (!persisted) { delete out.providerBinding; delete out.providerHandoff; delete out.accountLimits; }
1010
1047
  if (withLive && live) {
1011
1048
  out.running = live.running;
1012
1049
  out.attached = live.sockets.size;
@@ -1024,10 +1061,14 @@ export function createAssistantRuntime({
1024
1061
  out.computerRemote = computer ? { state: computer.state, reason: computer.reason, level: computer.level, approved: live.computerTurn?.approved === true } : null;
1025
1062
  out.testDensity = testDensityOf(record);
1026
1063
  out.testDensityExplicit = normalizeTestDensity(record.testDensity, null);
1064
+ // agents-p4: how many workers one task may get (the control next to Test density); null = not set, the default.
1065
+ out.agentDensity = agentDensityOf(record);
1066
+ out.agentDensityExplicit = normalizeAgentDensity(record.agentDensity, null);
1027
1067
  // `rename`: this server keeps a rename on the record (userRenamed), so a panel writes it here.
1028
1068
  // `adminSandbox`: the global setting is served here (PUT /api/assistant/admin-sandbox).
1029
1069
  // `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 };
1070
+ // `agentDensity` (agents-p4): this server keeps the session's Agent density and enforces it on teams.
1071
+ out.features = { routing: !!router, computer: computerSupported(), testDensity: true, agentDensity: true, rename: true, adminSandbox: !!adminSandbox, drafts: true, remove: true };
1031
1072
  out.draft = live.draft === true;
1032
1073
  if (adminSandbox) { try { out.adminSandbox = adminSandbox.enabled() === true; } catch { out.adminSandbox = false; } }
1033
1074
  out.budget = sessionMoney(record.id);
@@ -1074,9 +1115,18 @@ export function createAssistantRuntime({
1074
1115
  const live = sessions.get(sessionId);
1075
1116
  return live?.turnTaskId || live?.record.taskId || metered('task', () => usage?.currentTask?.(sessionId)?.id) || null;
1076
1117
  }
1118
+ // Task identity also works when metering is absent or unavailable; continue the existing task sequence.
1119
+ function nextTaskId(live) {
1120
+ const prior = Number(/^task-(\d+)$/.exec(live.record.taskId || '')?.[1]) || 0;
1121
+ live.record.taskSequence = Math.max(live.record.taskSequence || 0, prior) + 1;
1122
+ return `task-${live.record.taskSequence}`;
1123
+ }
1077
1124
  /** The session's current task, made when it has none yet. Never throws. */
1078
1125
  function ensureTaskId(sessionId) {
1079
- return metered('task', () => usage?.ensureTask?.(sessionId)?.id) || null;
1126
+ const live = sessions.get(sessionId);
1127
+ const taskId = metered('task', () => usage?.ensureTask?.(sessionId)?.id) || live?.record.taskId || (live ? nextTaskId(live) : null);
1128
+ if (live && !live.record.taskId) live.record.taskId = taskId;
1129
+ return taskId;
1080
1130
  }
1081
1131
  /**
1082
1132
  * What the gauge, the usage endpoint and agent_usage show. `session` is the headline: every
@@ -1151,8 +1201,17 @@ export function createAssistantRuntime({
1151
1201
  for (const ws of sockets) { if (ws.readyState === 1) { try { ws.send(raw); } catch {} } }
1152
1202
  }
1153
1203
  /** `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;
1204
+ function setLimit(live, next, { remember = true } = {}) {
1205
+ if (next === undefined) return false;
1206
+ const key = providerBinding(live.record);
1207
+ live.record.accountLimits ||= {};
1208
+ if (remember) {
1209
+ const previous = live.record.accountLimits[key];
1210
+ if (next?.status === 'rejected') live.record.accountLimits[key] = { ...next };
1211
+ else delete live.record.accountLimits[key];
1212
+ if (JSON.stringify(previous) !== JSON.stringify(live.record.accountLimits[key])) touch(live);
1213
+ }
1214
+ if (limitKey(next) === limitKey(live.limit)) return false;
1156
1215
  live.limit = next ? { ...next, provider: live.brainProvider || live.record.brain?.provider || null, at: iso(now()) } : null;
1157
1216
  sendLimit(live);
1158
1217
  return true;
@@ -1433,7 +1492,8 @@ export function createAssistantRuntime({
1433
1492
  // The CLI began a turn on its own (a background agent finished, a wakeup fired).
1434
1493
  if (packet.type === 'turn_started' && !live.running) {
1435
1494
  // A turn the CLI started itself is a new turn for the route gate too.
1436
- live.gate?.startTurn();
1495
+ const priorGate = live.gate?.snapshot();
1496
+ live.gate?.startTurn({ open: priorGate?.state === 'open' && priorGate.taskId === live.record.taskId, taskId: live.record.taskId, cli: true });
1437
1497
  live.running = true;
1438
1498
  beginComputerTurn(live);
1439
1499
  if (usage) {
@@ -1668,6 +1728,8 @@ export function createAssistantRuntime({
1668
1728
  }
1669
1729
  function onTurnFinished(live) {
1670
1730
  if (live.mailboxTurn) { live.mailboxTurn = false; }
1731
+ // The brain just worked: a mailbox held after a turn that could not be started is tried again.
1732
+ releaseMailboxHold(live);
1671
1733
  // Non-Claude brains have no Stop hook: nudge once per run when obligations remain.
1672
1734
  if (live.brainProvider !== 'claude-code' && live.obligations.size && !live.rememberedThisTurn) {
1673
1735
  for (const runId of [...live.obligations]) {
@@ -1800,11 +1862,11 @@ export function createAssistantRuntime({
1800
1862
  if (live.workTimer) { clearTimeout(live.workTimer); live.workTimer = null; }
1801
1863
  if (shuttingDown || live.closing || sessions.get(live.record.id) !== live || live.record.status === 'ended' || activeWork(live)) return;
1802
1864
  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;
1865
+ // The mailbox waits for its debounce, the plan card, and the retry of a turn that could not be started.
1866
+ if (!entry && !(settings.mailboxAuto && !live.mailboxTimer && !live.planCard && !live.mailboxRetryTimer && !live.mailboxHeld && mailboxCount(live))) return;
1805
1867
  if (sessionBusy(live)) {
1806
1868
  // 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);
1869
+ live.workTimer = setTimeout(() => { live.workTimer = null; pumpWork(live); }, settings.busyRecheckMs);
1808
1870
  live.workTimer.unref?.();
1809
1871
  return;
1810
1872
  }
@@ -1976,7 +2038,7 @@ export function createAssistantRuntime({
1976
2038
  function onBudgetSplit(sessionId, budget = null, { reason = null } = {}) {
1977
2039
  sendBudget(sessionId, budget, { reason });
1978
2040
  const live = sessions.get(String(sessionId || ''));
1979
- if (live && live.mailbox.length && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; live.budgetShareTriedAt = 0; scheduleMailbox(live, 0); }
2041
+ if (live && mailboxCount(live) && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; live.budgetShareTriedAt = 0; scheduleMailbox(live, 0); }
1980
2042
  }
1981
2043
  /**
1982
2044
  * Before a brain turn: when the brain's provider share is used up but the session has money left,
@@ -2014,7 +2076,7 @@ export function createAssistantRuntime({
2014
2076
  try { dispatcher?.checkSession?.(live.record.id); } catch {}
2015
2077
  sendCost(live);
2016
2078
  sendBudget(live.record.id, null, { reason: 'budget_changed' });
2017
- if (live.mailbox.length && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; scheduleMailbox(live, 0); }
2079
+ if (mailboxCount(live) && !brainBudgetBlock(live)) { live.budgetHoldNotified = false; scheduleMailbox(live, 0); }
2018
2080
  }
2019
2081
  }
2020
2082
  async function personaFor(live) {
@@ -2029,6 +2091,8 @@ export function createAssistantRuntime({
2029
2091
  try { setupState = desktop?.setupState?.() || null; } catch {}
2030
2092
  // This prompt states the level: a "[SynaBun Tests]" line follows only a later change.
2031
2093
  live.testDensityStamp = testDensityStamp(testDensityOf(live.record));
2094
+ // agents-p4: …and the Agent density: a "[SynaBun Agents]" line follows only a later change.
2095
+ live.agentDensityStamp = agentDensityStamp(agentDensityOf(live.record));
2032
2096
  // …and the budget: a "[SynaBun Budget]" line follows only a later change of the setting.
2033
2097
  const budgetSetting = budgetSettingNow();
2034
2098
  const money = sessionMoney(live.record.id);
@@ -2052,6 +2116,8 @@ export function createAssistantRuntime({
2052
2116
  computer: { available: computerSupported(), enabled: computerEffective(live.record), setupState, remote: computerDecision(live, { untrusted: false }) },
2053
2117
  taskClasses: TASK_CLASS_META,
2054
2118
  testDensity: testDensityOf(live.record),
2119
+ // agents-p4: the cap on workers per task, and the teams section that goes with it.
2120
+ agentDensity: agentDensityOf(live.record),
2055
2121
  // The session budget as the brain starts: the setting and, with a budget, the split so far.
2056
2122
  budget: budgetSetting ? { ...budgetSetting, view: money } : null,
2057
2123
  clarify: !!clarifier,
@@ -2074,10 +2140,24 @@ export function createAssistantRuntime({
2074
2140
  const remote = remotePolicyFor(live);
2075
2141
  if (remote) live.record.brain = clampedBrain(live, live.record.brain);
2076
2142
  const brain = live.record.brain;
2077
- const sink = { send: (packet) => onBrainPacket(live, packet) };
2143
+ // A bare legacy/mismatched id has no proven account owner. Seed from our journal.
2144
+ const binding = providerBinding(live.record);
2145
+ if (live.record.providerBinding !== binding) {
2146
+ live.record.providerSessionId = null;
2147
+ live.record.providerThreadId = null;
2148
+ live.record.providerHandoff = null;
2149
+ }
2150
+ live.record.providerBinding = binding;
2151
+ if (!live.record.providerSessionId && !live.record.providerThreadId) {
2152
+ const runs = dispatcher?.list?.({ assistantSessionId: live.record.id, limit: 500 }) || [];
2153
+ live.record.providerHandoff = buildAssistantHandoff(live.record, readTranscript(live.record.id, 10000), runs);
2154
+ }
2078
2155
  const basePersona = await personaFor(live);
2079
2156
  if (stale()) return null;
2080
2157
  if (live.brain) return live.brain;
2158
+ const epoch = live.brainEpoch = (live.brainEpoch || 0) + 1;
2159
+ const current = () => live.brainEpoch === epoch;
2160
+ const sink = { send: (packet) => { if (current()) onBrainPacket(live, packet); } };
2081
2161
  // What SynaBun has learned about the user rides after the persona, in the same system-level
2082
2162
  // slot (Claude systemPromptAppend, Codex developerInstructions, OpenCode agent prompt), frozen
2083
2163
  // per provider conversation so the prompt cache holds.
@@ -2086,7 +2166,7 @@ export function createAssistantRuntime({
2086
2166
  try { userSuffix = userContext.personaSuffix(live.record) || userSuffix; }
2087
2167
  catch (error) { log('assistant:user-context', error?.message || String(error)); }
2088
2168
  }
2089
- const persona = userSuffix.text ? `${basePersona}\n\n${userSuffix.text}` : basePersona;
2169
+ const persona = [basePersona, userSuffix.text, live.record.providerHandoff].filter(Boolean).join('\n\n');
2090
2170
  live.personaText = persona;
2091
2171
  // Computer use: one unforgeable grant per brain (the MCP `computer` group is
2092
2172
  // advertised only to callers presenting it). Revoked when the brain goes.
@@ -2128,11 +2208,11 @@ export function createAssistantRuntime({
2128
2208
  const extended = /\[extended\]$/.test(String(live.record.brain?.model || info.id || ''));
2129
2209
  return codexUsageCostUsd(usage, price, { contextWindow: extended ? info.contextWindow || null : null });
2130
2210
  },
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),
2211
+ onCodexThread: (threadId) => { if (!current()) return; if (threadId) live.record.providerThreadId = threadId; if (live.turnTaskId) pollCodex(live, { force: true }); },
2212
+ onCodexUsage: () => { if (current() && live.turnTaskId) pollCodex(live); },
2213
+ onOpenCodeEvent: (type, event) => { if (current()) openCodeEvent(live, type, event); },
2134
2214
  // 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); },
2215
+ onOpenCodeRoot: (sessionId) => { if (!current()) return; live.record.providerSessionId = sessionId; metered('meter-state', () => live.brainMeter?.setRoot?.(sessionId)); saveMeter(live); },
2136
2216
  desktopGrant: live.desktopGrant || null,
2137
2217
  brainCredential: live.brainCredential || null,
2138
2218
  // A remote session's level (lib/remote-policy.js): the Claude brain allows
@@ -2208,6 +2288,7 @@ export function createAssistantRuntime({
2208
2288
  if (identity.providerSessionId) live.record.providerSessionId = identity.providerSessionId;
2209
2289
  if (identity.providerThreadId) live.record.providerThreadId = identity.providerThreadId;
2210
2290
  } catch {}
2291
+ live.brainEpoch = (live.brainEpoch || 0) + 1;
2211
2292
  live.brain = null;
2212
2293
  // Its credential dies with it: a file send presenting it is refused from here on, and so is its pin.
2213
2294
  live.brainCredential = null;
@@ -2223,6 +2304,8 @@ export function createAssistantRuntime({
2223
2304
  live.turnTasks.length = 0;
2224
2305
  live.turnTaskId = null;
2225
2306
  live.running = false;
2307
+ // The next brain starts on the session's own model and effort.
2308
+ live.turnRun = null;
2226
2309
  closePlanCard(live, 'brain_disposed');
2227
2310
  live.planTurn = false;
2228
2311
  live.brainUserContext = null;
@@ -2391,6 +2474,19 @@ export function createAssistantRuntime({
2391
2474
  budgetBlock = brainBudgetBlock(live);
2392
2475
  }
2393
2476
  if (budgetBlock) return refuse(live, budgetBlock.code, budgetBlock.message, { request });
2477
+ if (live.switching) await live.switching;
2478
+ if (cancelled()) return dropTurn(live, request);
2479
+ if (live.record.brain.accountPolicy === 'auto') {
2480
+ await accountUsage?.refresh(live.record.brain.provider);
2481
+ if (cancelled()) return dropTurn(live, request);
2482
+ const rows = conversationAccounts(live.record.brain, live);
2483
+ const active = rows.find(row => row.id === live.record.brain.accountId);
2484
+ if (!active || active.signedIn !== true || active.mode !== 'subscription' || active.usage?.limited) {
2485
+ try { await updateSession(live.record.id, { brain: { accountId: 'auto' } }, { fromTurn: true }); }
2486
+ catch (error) { return refuse(live, error.code || 'ACCOUNT_UNAVAILABLE', error.message, { request }); }
2487
+ if (cancelled()) return dropTurn(live, request);
2488
+ }
2489
+ }
2394
2490
  // A Claude brain whose account cannot run (signed out, its key unreadable, removed) is refused with
2395
2491
  // why, before a process starts under it: the CLI would only answer "not logged in" mid-turn.
2396
2492
  if (!live.brain && ['claude-code', 'codex'].includes(live.record.brain?.provider)) {
@@ -2437,6 +2533,7 @@ export function createAssistantRuntime({
2437
2533
  // A Codex / OpenCode turn's recall result, for the user-context block below.
2438
2534
  let turnRecalled = null;
2439
2535
  if (!system) {
2536
+ if (origin === 'ui' && !untrusted) { live.record.lastOwnerTurnAt = now(); persist(); }
2440
2537
  live.lastPrompt = prompt;
2441
2538
  live.lastPromptOrigin = origin ? String(origin) : null;
2442
2539
  // A prompt from elsewhere (WhatsApp, the API) is news to the panel: it goes live too.
@@ -2488,6 +2585,15 @@ export function createAssistantRuntime({
2488
2585
  live.testDensityStamp = tests;
2489
2586
  }
2490
2587
  } catch {}
2588
+ // agents-p4: Agent density changed since the brain last saw it: one "[SynaBun Agents]" line, in the same place.
2589
+ try {
2590
+ const agents = agentDensityStamp(agentDensityOf(live.record));
2591
+ if (live.agentDensityStamp === undefined) live.agentDensityStamp = agents;
2592
+ else if (live.agentDensityStamp !== agents) {
2593
+ finalText = finalText.endsWith(prompt) ? `${finalText.slice(0, finalText.length - prompt.length)}${agents}\n\n${prompt}` : `${agents}\n\n${finalText}`;
2594
+ live.agentDensityStamp = agents;
2595
+ }
2596
+ } catch {}
2491
2597
  // The budget changed since the brain last saw it: one "[SynaBun Budget]" line, in the same place.
2492
2598
  const budgetNote = budgetLine(live);
2493
2599
  if (budgetNote) finalText = finalText.endsWith(prompt) ? `${finalText.slice(0, finalText.length - prompt.length)}${budgetNote}\n\n${prompt}` : `${budgetNote}\n\n${finalText}`;
@@ -2500,9 +2606,10 @@ export function createAssistantRuntime({
2500
2606
  finalText = finalText.endsWith(prompt) ? `${finalText.slice(0, finalText.length - prompt.length)}${clarified.note}\n\n${prompt}` : `${clarified.note}\n\n${finalText}`;
2501
2607
  }
2502
2608
  // 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
2609
+ taskId = clarified?.note
2504
2610
  ? (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);
2611
+ : 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);
2612
+ router?.expireOtherTasks?.(live.record.id, taskId);
2506
2613
  // An image the brain's model cannot see: run this turn on a vision model
2507
2614
  // of the same provider (the conversation stays in the same session).
2508
2615
  if (Array.isArray(images) && images.length && !turnModel) {
@@ -2535,7 +2642,7 @@ export function createAssistantRuntime({
2535
2642
  appendTranscript(live.record.id, { at: iso(now()), packet: continued });
2536
2643
  sendToSockets(live, continued);
2537
2644
  }
2538
- if (usage) {
2645
+ {
2539
2646
  taskId ||= live.record.taskId || ensureTaskId(live.record.id);
2540
2647
  // record.taskId is the latest human task: a system turn that carries its own names only its turn.
2541
2648
  if (!system || !live.record.taskId) live.record.taskId = taskId;
@@ -2569,7 +2676,20 @@ export function createAssistantRuntime({
2569
2676
  // Every turn names its model: the brain was built from an older snapshot of
2570
2677
  // the record, and routed/continuation turns override it for one turn only.
2571
2678
  const effectiveModel = turnModel || live.record.brain.model || null;
2572
- const effectiveEffort = brainEffort(live.record.brain.provider, effectiveModel, turnEffort || live.record.brain.effort || null);
2679
+ const askedEffort = turnEffort || live.record.brain.effort || null;
2680
+ const effectiveEffort = brainEffort(live.record.brain.provider, effectiveModel, askedEffort);
2681
+ // Off (`none`) asked of a Claude model that cannot turn its thinking off runs at the lowest level
2682
+ // (effort-levels.js thinkingAlwaysOn): said once per model in this session, so nothing claims "thinking off".
2683
+ if (String(askedEffort || '').toLowerCase() === EFFORT_OFF && effectiveEffort && effectiveEffort !== EFFORT_OFF && effectiveEffort !== 'off' && live.record.brain.provider === 'claude-code') {
2684
+ const said = live.effortOffNoted || (live.effortOffNoted = new Set());
2685
+ const key = String(effectiveModel || 'default');
2686
+ if (!said.has(key)) {
2687
+ said.add(key);
2688
+ 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.` } };
2689
+ appendTranscript(live.record.id, { at: iso(now()), packet });
2690
+ sendToSockets(live, packet);
2691
+ }
2692
+ }
2573
2693
  // User context (assistant-user-context.js): a human turn's trace and learning start here.
2574
2694
  // A Codex / OpenCode turn gets its per-turn block now (its recall result is known); a Claude
2575
2695
  // turn gets it in the in-process UserPromptSubmit hook, which finds the handle in turnMeta.
@@ -2617,11 +2737,22 @@ export function createAssistantRuntime({
2617
2737
  // Every turn starts unrouted; a continuation or a route_decided "here" turn starts open.
2618
2738
  // Plan mode never routes: the brain explores read-only (the plan policy) and
2619
2739
  // the approved plan is routed on the next turn.
2620
- ensureGate(live)?.startTurn({ open: gateOpen || live.record.brain?.planMode === true, carry: gateCarry });
2740
+ ensureGate(live)?.startTurn({ open: gateOpen || live.record.brain?.planMode === true, carry: gateCarry, taskId });
2741
+ // What this turn runs on, as the router compares a re-routed task with it (routerSession `turn`). The
2742
+ // brain process keeps it: a turn the CLI starts by itself afterwards (a task notification) runs on it too.
2743
+ const previousRun = live.turnRun;
2744
+ live.turnRun = { model: effectiveModel, effort: askedEffort };
2621
2745
  try {
2622
2746
  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 });
2747
+ if (system && work?.kind === 'continuation' && work.routeId) {
2748
+ const continued = live.continuedRoutes || (live.continuedRoutes = new Set());
2749
+ continued.add(String(work.routeId));
2750
+ while (continued.size > 100) continued.delete(continued.values().next().value);
2751
+ try { router?.continuationStarted?.(work.routeId); } catch (error) { log('assistant:route-continuation', error?.message || String(error)); }
2752
+ }
2623
2753
  } catch (error) {
2624
2754
  live.running = false;
2755
+ live.turnRun = previousRun;
2625
2756
  endComputerTurn(live, 'turn_failed');
2626
2757
  // The prompt never reached the brain: its task leaves the FIFO, a turn still in flight keeps its own.
2627
2758
  const queued = live.turnTasks.lastIndexOf(taskId);
@@ -2656,18 +2787,65 @@ export function createAssistantRuntime({
2656
2787
  return true;
2657
2788
  }
2658
2789
 
2659
- // ── mailbox ────────────────────────────────────────────────────────────────
2790
+ // ── mailbox (Agents P2: the coordination store) ────────────────────────────
2791
+ // What a session's brain has not been told yet is the open events addressed to it in the coordination store
2792
+ // (lib/coordination/service.js), not a list in memory: nothing is dropped for being many, a restart loses
2793
+ // nothing, and an event is acknowledged only once the turn that carries it was started.
2794
+ // critical (a question, a permission, a failure, a stall, an interrupted run, the budget spent): its turn starts
2795
+ // at once when the session is free;
2796
+ // everything else waits `mailboxDebounceMs` (150 ms at most) so results that arrive together go in one turn;
2797
+ // while the brain is busy everything waits in the store, low-priority progress folded, and goes when it is free.
2798
+ function mailboxCount(live, options) {
2799
+ try { return coordination.mailbox.count(live.record.id, options); } catch { return 0; }
2800
+ }
2801
+ /** A look at what a session has open (the `live.mailbox` view): nothing is handed out or acknowledged. */
2802
+ function mailboxPeek(sessionId) {
2803
+ try { return coordination.mailbox.pending(sessionId, { limit: 1000, peek: true }).items; } catch { return []; }
2804
+ }
2805
+ /** 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
2806
  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);
2807
+ try { coordination.mailbox.post(live.record.id, item); }
2808
+ catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); }
2809
+ // The store's wake-up (onMailboxEvent) schedules the delivery.
2664
2810
  }
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;
2811
+ /** An event was addressed to this session (the store's wake-up, after its append committed). */
2812
+ function onMailboxEvent(live, event) {
2813
+ // News is a reason to try a held mailbox again.
2814
+ releaseMailboxHold(live, { pump: false });
2815
+ scheduleMailbox(live, event?.priority === 'critical' ? 0 : settings.mailboxDebounceMs);
2816
+ }
2817
+ /**
2818
+ * `delay` 0: now, as soon as the session is free (a critical event, a budget that was raised). Otherwise events
2819
+ * that arrive together go in one turn: the scheduler delivers them once this short window closes.
2820
+ */
2821
+ function scheduleMailbox(live, delay = settings.mailboxDebounceMs) {
2822
+ if (!(delay > 0)) {
2823
+ if (live.mailboxTimer) { clearTimeout(live.mailboxTimer); live.mailboxTimer = null; }
2824
+ releaseMailboxHold(live, { pump: false });
2825
+ pumpSoon(live);
2826
+ return;
2827
+ }
2828
+ if (live.mailboxTimer || !mailboxCount(live)) return;
2668
2829
  live.mailboxTimer = setTimeout(() => { live.mailboxTimer = null; pumpWork(live); }, delay);
2669
2830
  live.mailboxTimer.unref?.();
2670
2831
  }
2832
+ /** A mailbox turn that could not be started waits (mailboxRetryDelaysMs), then holds; this lets it go again. */
2833
+ function releaseMailboxHold(live, { pump = true } = {}) {
2834
+ const held = live.mailboxHeld || !!live.mailboxRetryTimer;
2835
+ if (live.mailboxRetryTimer) { clearTimeout(live.mailboxRetryTimer); live.mailboxRetryTimer = null; }
2836
+ live.mailboxHeld = false;
2837
+ live.mailboxAttempts = 0;
2838
+ if (held && pump) pumpSoon(live);
2839
+ }
2840
+ function holdMailbox(live, result) {
2841
+ live.mailboxAttempts = (Number(live.mailboxAttempts) || 0) + 1;
2842
+ const delay = settings.mailboxRetryDelaysMs[live.mailboxAttempts - 1];
2843
+ 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`}`);
2844
+ if (delay === undefined) { live.mailboxHeld = true; return; }
2845
+ if (live.mailboxRetryTimer) clearTimeout(live.mailboxRetryTimer);
2846
+ live.mailboxRetryTimer = setTimeout(() => { live.mailboxRetryTimer = null; pumpWork(live); }, delay);
2847
+ live.mailboxRetryTimer.unref?.();
2848
+ }
2671
2849
  /**
2672
2850
  * A result / needs_input item for a turn the brain already read with
2673
2851
  * agent_wait, agent_read or agent_status (the dispatcher's delivery mark).
@@ -2682,6 +2860,10 @@ export function createAssistantRuntime({
2682
2860
  try { mark = dispatcher?.deliveryState?.(item.run.runId) || null; } catch { mark = null; }
2683
2861
  return !!mark && Number(mark.turn) >= turn;
2684
2862
  }
2863
+ /** Events the brain read by itself meanwhile are settled without a turn. → how many. */
2864
+ function settleRead(live) {
2865
+ try { return coordination.mailbox.discard(live.record.id, (item) => alreadyRead(item)); } catch { return 0; }
2866
+ }
2685
2867
  /**
2686
2868
  * Out of money: the events wait (a raise or No limit re-schedules them), said once. The brain's
2687
2869
  * provider share used up while the session has money left: the budget is divided again, then the
@@ -2695,35 +2877,41 @@ export function createAssistantRuntime({
2695
2877
  coverBrainTurn(live).then((covered) => {
2696
2878
  live.budgetCovering = false;
2697
2879
  live.budgetShareTriedAt = covered ? 0 : now();
2698
- if (live.mailbox.length) scheduleMailbox(live, 0);
2880
+ if (mailboxCount(live)) scheduleMailbox(live, 0);
2699
2881
  }).catch(() => { live.budgetCovering = false; live.budgetShareTriedAt = now(); });
2700
2882
  return false;
2701
2883
  }
2702
2884
  if (live.budgetCovering) return false;
2703
2885
  if (!live.budgetHoldNotified) {
2704
2886
  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.` });
2887
+ const waiting = mailboxCount(live);
2888
+ sendToSockets(live, { type: 'error', code: budgetBlock.code, message: `${budgetBlock.message} ${waiting} agent event${waiting === 1 ? '' : 's'} will reach the brain after that.` });
2706
2889
  }
2707
2890
  return false;
2708
2891
  }
2709
- /** The mailbox now, if the scheduler would start it (no batch window: it is asked for). */
2892
+ /** The mailbox now, if the scheduler would start it (no debounce: it is asked for). */
2710
2893
  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);
2894
+ if (shuttingDown || live.closing || !mailboxCount(live) || sessions.get(live.record.id) !== live || live.record.status === 'ended') return Promise.resolve(null);
2712
2895
  if (sessionBusy(live) || live.planCard || nextWork(live) || !mailboxAllowed(live)) { pumpSoon(live); return Promise.resolve(null); }
2713
2896
  return startWork(live, { kind: 'mailbox', gen: null });
2714
2897
  }
2715
2898
  /** The mailbox's turn (the scheduler's 'mailbox' work). */
2716
2899
  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));
2900
+ // Read while it waited (inside the debounce, or while the brain was busy with the turn that waited for it):
2901
+ // not news any more.
2902
+ settleRead(live);
2903
+ let batch = null;
2904
+ try { batch = coordination.mailbox.pending(live.record.id, { limit: settings.mailboxItems }); }
2905
+ catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); return null; }
2906
+ let unread = batch.items;
2907
+ let more = batch.more;
2720
2908
  if (!unread.length) { scheduleDispose(live); return null; }
2721
2909
  // A decided route whose card carried the owner's computer approval is carried out in a turn of
2722
2910
  // its own: nothing else in the mailbox rides on that approval. The rest waits for the next turn.
2723
2911
  const marked = live.computerRouteGrant?.routeId || null;
2724
2912
  const own = marked ? unread.filter((item) => item?.kind === 'route_decided' && String(item.route?.routeId || '') === marked) : [];
2725
2913
  if (own.length && own.length < unread.length) {
2726
- live.mailbox.unshift(...unread.filter((item) => !own.includes(item)));
2914
+ more += unread.length - own.length;
2727
2915
  unread = own;
2728
2916
  }
2729
2917
  // A route decided with no run attached whose run exists by now is not asked to be dispatched again.
@@ -2732,26 +2920,44 @@ export function createAssistantRuntime({
2732
2920
  const items = reconcileRouteItems(unread, sessionRuns);
2733
2921
  // A budget change since the brain last saw it rides first (a raise is what released a held mailbox).
2734
2922
  const budgetNote = budgetLine(live);
2735
- const text = budgetNote ? `${budgetNote}\n\n${formatMailbox(items)}` : formatMailbox(items);
2923
+ const body = formatMailbox(items, { more });
2924
+ const text = budgetNote ? `${budgetNote}\n\n${body}` : body;
2736
2925
  sendToSockets(live, { type: 'event', event: { type: 'synabun.mailbox', items } });
2737
2926
  appendTranscript(live.record.id, { at: iso(now()), packet: { type: 'event', event: { type: 'synabun.mailbox', items } } });
2738
2927
  live.mailboxTurn = true;
2739
2928
  // The user picked "here" on a card: that turn does the task, so it starts open.
2740
2929
  const decidedHere = items.some((item) => item.kind === 'route_decided' && item.route?.target?.kind === 'direct' && !(item.runIds || []).length);
2741
2930
  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;
2931
+ const taskId = firstRun?.taskId || firstRun?.run?.turns?.find((turn) => turn.n === firstRun.turn)?.taskId || firstRun?.run?.taskId || live.record.taskId || null;
2743
2932
  // The decided "here" routes this turn carries out (one of them may hold the owner's computer approval).
2744
2933
  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; }
2934
+ let result = null;
2935
+ try { result = await runQuery(live, { text, system: true, taskId, gateOpen: decidedHere, computerRoutes }); }
2936
+ catch (error) {
2937
+ // A start that threw is a start that failed: its events stay open and the retry rules below apply (never a spin).
2938
+ log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`);
2939
+ result = { ok: false, code: 'TURN_FAILED', message: error?.message || String(error) };
2940
+ }
2941
+ if (result?.ok) {
2942
+ // The turn that carries them was started: only now are they acknowledged. A turn that was refused, failed
2943
+ // or found the brain busy leaves every one of them open, also across a restart.
2944
+ try { coordination.mailbox.ack(live.record.id, items.map((item) => item.eventId).filter(Boolean)); }
2945
+ catch (error) { log('assistant:mailbox-error', `${live.record.id}: ${error?.message || error}`); }
2946
+ live.mailboxAttempts = 0;
2947
+ return result;
2948
+ }
2949
+ live.mailboxTurn = false;
2950
+ // A human prompt reached the brain first (ASSISTANT_BUSY): the events go after its turn, whose end pumps. A
2951
+ // turn dropped because the session closed needs no retry. Anything else is tried again, then held.
2952
+ if (result?.code !== 'ASSISTANT_BUSY' && result?.code !== 'TURN_CANCELLED') holdMailbox(live, result);
2748
2953
  return result;
2749
2954
  }
2750
2955
  function onDispatchEvent(payload) {
2751
2956
  const run = payload?.run;
2752
2957
  if (!run?.assistantSessionId) return;
2753
2958
  const live = sessions.get(run.assistantSessionId);
2754
- if (!live) return;
2959
+ // A session that is gone hears nothing: what was addressed to it is settled, so it does not wait in the store for good.
2960
+ if (!live) { dropMailbox(run.assistantSessionId); return; }
2755
2961
  // The conversation's thread record: its runs, their outcomes and follow-ups.
2756
2962
  try { userContext?.onDispatch(live.record, payload); } catch {}
2757
2963
  if (!live.record.dispatchRunIds?.includes(run.runId)) { live.record.dispatchRunIds = [...(live.record.dispatchRunIds || []), run.runId].slice(-100); touch(live); }
@@ -2762,27 +2968,15 @@ export function createAssistantRuntime({
2762
2968
  if (payload.reason === 'completed' || payload.reason === 'failed' || payload.reason === 'stopped' || payload.reason === 'interrupted') {
2763
2969
  sendToSockets(live, { type: 'event', event: { type: 'synabun.dispatch_result', run, result: run.lastResult || null } });
2764
2970
  }
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);
2971
+ // Agents P2: the event is in the coordination log. The dispatcher appended it in the step that changed the run;
2972
+ // recording it here again stores nothing (same id), and is what a dispatcher without the service relies on.
2973
+ // Which reasons reach the brain, and how urgently, is the service's rule. The store's wake-up schedules the turn.
2974
+ const recorded = coordination.recordDispatch(payload);
2975
+ // Already read by the brain (agent_wait in the same turn that dispatched it): no second turn. Only this event is
2976
+ // looked at here; the whole mailbox is gone through once, when a turn is composed.
2977
+ if (recorded?.delivered && alreadyRead({ kind: payload.reason === 'turn_completed' ? 'result' : payload.reason, turn: payload.turn, run })) {
2978
+ try { coordination.mailbox.ack(live.record.id, [recorded.id]); } catch {}
2979
+ }
2786
2980
  }
2787
2981
  function onRunRemoved(payload) {
2788
2982
  const live = payload?.assistantSessionId ? sessions.get(payload.assistantSessionId) : null;
@@ -2796,19 +2990,42 @@ export function createAssistantRuntime({
2796
2990
  }
2797
2991
  // A result can be waiting in the mailbox while the user clears its run.
2798
2992
  // 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) {
2993
+ try { coordination.mailbox.discard(live.record.id, (item) => removed.has(String(item?.run?.runId || item?.runId || ''))); } catch {}
2994
+ if (!mailboxCount(live) && live.mailboxTimer) {
2801
2995
  clearTimeout(live.mailboxTimer);
2802
2996
  live.mailboxTimer = null;
2803
2997
  }
2804
2998
  }
2999
+ /**
3000
+ * Everything open for a session that no longer exists is settled (nobody will ever read it). Never while the
3001
+ * sessions index could not be read: a session this start does not know yet may be there after the next one.
3002
+ */
3003
+ function dropMailbox(sessionId) {
3004
+ if (!indexReady) return;
3005
+ try { if (coordination.mailbox.count(sessionId)) coordination.mailbox.discard(sessionId, null); } catch {}
3006
+ }
3007
+ /**
3008
+ * After a restart: what a session's brain was not told before the server went down is still open in the store,
3009
+ * and is delivered now. A session that was removed gets nothing; one that is closed waits until it is opened again.
3010
+ */
3011
+ function resumeMailboxes() {
3012
+ if (shuttingDown) return;
3013
+ let open = [];
3014
+ try { open = coordination.mailbox.sessions(); } catch { open = []; }
3015
+ for (const { sessionId } of open) {
3016
+ const live = sessions.get(sessionId);
3017
+ if (!live) { dropMailbox(sessionId); continue; }
3018
+ if (live.record.status === 'ended') continue;
3019
+ scheduleMailbox(live, 0);
3020
+ }
3021
+ }
2805
3022
  function onPermissionBroadcast(message) {
2806
3023
  const live = message?.assistantSessionId ? sessions.get(message.assistantSessionId) : null;
2807
3024
  if (!live) return;
2808
3025
  if (message.type === 'assistant:permission-request') {
2809
3026
  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
3027
  } else if (message.type === 'assistant:permission-resolved') {
2811
- live.mailbox = live.mailbox.filter((item) => !(item.run?.runId === message.runId && item.request?.requestId === message.requestId));
3028
+ try { coordination.mailbox.discard(live.record.id, (item) => item.run?.runId === message.runId && item.request?.requestId === message.requestId); } catch {}
2812
3029
  sendToSockets(live, { type: 'event', event: { type: 'synabun.dispatch_control_resolved', runId: message.runId, request_id: message.requestId, resolvedBy: message.resolvedBy, behavior: message.behavior } });
2813
3030
  }
2814
3031
  }
@@ -2879,14 +3096,26 @@ export function createAssistantRuntime({
2879
3096
  * they cannot. The record is flagged before it is persisted: after a restart without a new
2880
3097
  * registration the session reads as read-only.
2881
3098
  */
2882
- async function resolveAutoAccount(brain) {
3099
+ function conversationAccounts(brain, live) {
3100
+ return (accountUsage?.list()?.[brain.provider] || []).map(row => {
3101
+ const key = providerBinding({ id: live?.record.id, brain: { ...brain, accountId: row.id } });
3102
+ const limit = live?.record.accountLimits?.[key];
3103
+ return limit && (!limit.resetsAt || limit.resetsAt > now())
3104
+ ? { ...row, usage: { ...row.usage, limited: true, resetsAt: limit.resetsAt ? iso(limit.resetsAt) : null } } : row;
3105
+ });
3106
+ }
3107
+ async function resolveAutoAccount(brain, live = null) {
2883
3108
  if (brain.accountId !== 'auto' || !['claude-code', 'codex'].includes(brain.provider)) return brain;
2884
3109
  await accountUsage?.refresh(brain.provider);
2885
- const rows = accountUsage?.list()?.[brain.provider] || [];
3110
+ const rows = conversationAccounts(brain, live);
2886
3111
  const key = brain.provider === 'codex' ? 'codexAccount' : 'claudeAccount';
2887
- const { row } = chooseUsageAccount(rows, 'auto', configStore?.workers?.()?.[key] || 'default');
3112
+ const { row, reason } = chooseUsageAccount(rows, 'auto', configStore?.workers?.()?.[key] || 'default');
2888
3113
  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 };
3114
+ if (reason === 'accounts_all_limited') {
3115
+ const reset = row.usage?.resetsAt;
3116
+ 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 });
3117
+ }
3118
+ return { ...brain, accountId: row.id, accountPolicy: 'auto' };
2890
3119
  }
2891
3120
  async function createSession({ brain = {}, label = null, cwd = null, windowId = null, fallback = false, channel = null, draft = false } = {}, internal = {}) {
2892
3121
  if (brain?.mcpProfile !== undefined) throw Object.assign(new Error('Use tools: [group ids].'), { code: 'MCP_PROFILE_REMOVED', status: 400 });
@@ -2941,6 +3170,10 @@ export function createAssistantRuntime({
2941
3170
  function applyTestDensity(live, level) {
2942
3171
  live.record.testDensity = normalizeTestDensity(level, null);
2943
3172
  }
3173
+ /** agents-p4: null, '' or an unknown value clears the session's own level: it reads as the default (Solo). */
3174
+ function applyAgentDensity(live, level) {
3175
+ live.record.agentDensity = normalizeAgentDensity(level, null);
3176
+ }
2944
3177
  function applyComputerUse(live, enabled) {
2945
3178
  // A remote session's computer use is not a per-conversation choice: the owner's switch and
2946
3179
  // the level decide (remoteComputerUse). A PATCH, the socket and updateSession change nothing.
@@ -2949,7 +3182,18 @@ export function createAssistantRuntime({
2949
3182
  live.record.computerUse = value;
2950
3183
  try { desktop?.onSessionToggle?.(live.record.id, computerEffective(live.record)); } catch {}
2951
3184
  }
2952
- async function updateSession(id, patch = {}) {
3185
+ async function updateSession(id, patch = {}, internal = {}) {
3186
+ const live = sessions.get(id);
3187
+ if (!live) return null;
3188
+ const previous = live.switching;
3189
+ const pending = (async () => {
3190
+ if (previous) await previous.catch(() => {});
3191
+ return applySessionUpdate(id, patch, internal);
3192
+ })();
3193
+ live.switching = pending;
3194
+ try { return await pending; } finally { if (live.switching === pending) live.switching = null; }
3195
+ }
3196
+ async function applySessionUpdate(id, patch = {}, { fromTurn = false } = {}) {
2953
3197
  const live = sessions.get(id);
2954
3198
  if (!live) return null;
2955
3199
  // A rename (tab, float header, sidepanel ✎) is the session's one name: every list reads it
@@ -2963,6 +3207,7 @@ export function createAssistantRuntime({
2963
3207
  if (patch.routing && typeof patch.routing === 'object' && 'mode' in patch.routing) applyRouteMode(live, patch.routing.mode);
2964
3208
  if ('computerUse' in patch) applyComputerUse(live, patch.computerUse);
2965
3209
  if ('testDensity' in patch) applyTestDensity(live, patch.testDensity);
3210
+ if ('agentDensity' in patch) applyAgentDensity(live, patch.agentDensity); // agents-p4
2966
3211
  if (patch.brain && typeof patch.brain === 'object') {
2967
3212
  // A provider switch that names no model starts from the new provider's
2968
3213
  // default, never from the old provider's model id.
@@ -2975,15 +3220,22 @@ export function createAssistantRuntime({
2975
3220
  // An effort the panel cleared (its Auto row: `effort: null`) is the model's default. normalizeBrain
2976
3221
  // would fall back to the one before it, and Off (`none`, no thinking) or a level would stay on.
2977
3222
  if (Object.hasOwn(patch.brain, 'effort') && (patch.brain.effort === null || patch.brain.effort === '')) next = { ...next, effort: null };
2978
- next = await resolveAutoAccount(next);
3223
+ if (switching || patch.brain.accountId) next.accountPolicy = patch.brain.accountId === 'auto' || (!switching && patch.brain.accountPolicy === 'auto') ? 'auto' : 'manual';
3224
+ next = await resolveAutoAccount(next, live);
2979
3225
  const modelChanged = next.model !== live.record.brain.model || next.provider !== live.record.brain.provider;
2980
3226
  if (modelChanged) next = (await enabledBrain(next)).brain;
2981
3227
  // A remote session keeps what was asked for and runs what its level allows.
2982
3228
  if ('permissionMode' in patch.brain || 'planMode' in patch.brain) next = clampModeWrite(live, next);
2983
3229
  else next = clampedBrain(live, next);
2984
3230
  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);
3231
+ const accountChanged = next.provider !== live.record.brain.provider || next.accountId !== live.record.brain.accountId;
3232
+ if (accountChanged && (live.running || live.brain?.isBusy?.() || (!fromTurn && live.turnPending > 0))) {
3233
+ throw Object.assign(new Error('Finish or stop the current turn before switching accounts.'), { code: 'ASSISTANT_BUSY', status: 409 });
3234
+ }
3235
+ // Dispose under the OLD account: identity, meter and late callbacks belong to it.
3236
+ if (providerChanged) await disposeBrain(live, 'switched');
2985
3237
  // 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);
3238
+ if (next.provider !== live.record.brain.provider || next.accountId !== live.record.brain.accountId) setLimit(live, null, { remember: false });
2987
3239
  live.record.brain = next;
2988
3240
  // The panel's brain names its working folder `project` and never sends `cwd`. A project picked
2989
3241
  // there (the toolbar's Working project, the empty state's picker) moves the folder the way a
@@ -2993,10 +3245,14 @@ export function createAssistantRuntime({
2993
3245
  if (folder && folder !== next.cwd) live.record.brain = { ...next, cwd: folder };
2994
3246
  live.record.project = detectProject(live.record.brain.cwd) || live.record.project || 'global';
2995
3247
  if (providerChanged) {
2996
- await disposeBrain(live, 'switched');
3248
+ // Always seed again on a switch (including switching back). An old account's
3249
+ // session may predate turns or worker results now in this chat's journal.
3250
+ live.record.providerBinding = null;
3251
+ live.record.providerHandoff = null;
3252
+ live.record.memoryGeneration = (live.record.memoryGeneration || 1) + 1;
2997
3253
  live.record.providerSessionId = null;
2998
3254
  live.record.providerThreadId = null;
2999
- // Another conversation: its user-context digest is built (and frozen) anew.
3255
+ // A fresh provider session: rebuild its digest; the chat handoff stays authoritative.
3000
3256
  try { userContext?.conversationReplaced(live.record); } catch {}
3001
3257
  if (live.record.usageState) delete live.record.usageState[next.provider === 'claude-code' ? 'claude' : next.provider];
3002
3258
  if (live.record.usageState) delete live.record.usageState.codexThreadId;
@@ -3064,6 +3320,9 @@ export function createAssistantRuntime({
3064
3320
  await disposeBrain(live, 'closed');
3065
3321
  for (const ws of live.sockets) { try { ws.close(1000, 'session destroyed'); } catch {} }
3066
3322
  sessions.delete(id);
3323
+ if (live.mailboxTimer) { clearTimeout(live.mailboxTimer); live.mailboxTimer = null; }
3324
+ if (live.mailboxRetryTimer) { clearTimeout(live.mailboxRetryTimer); live.mailboxRetryTimer = null; }
3325
+ dropMailbox(id);
3067
3326
  const usageTimer = usageTimers.get(id);
3068
3327
  if (usageTimer) clearTimeout(usageTimer);
3069
3328
  usageTimers.delete(id);
@@ -3225,7 +3484,7 @@ export function createAssistantRuntime({
3225
3484
  const superseded = movedOn === true && (inner.decline === true || inner.behavior === 'deny');
3226
3485
  const sid = live.record.id;
3227
3486
  // Route cards are answered by the router and never reach the brain.
3228
- if (router?.owns?.(rid, sid)) {
3487
+ if (router?.owns?.(rid, sid) || router?.closedRoute?.(rid, sid)) {
3229
3488
  if (superseded && typeof router.cancel === 'function') {
3230
3489
  controlResolved(live, rid, origin);
3231
3490
  router.cancel(rid, 'superseded', { sessionId: sid });
@@ -3372,7 +3631,8 @@ export function createAssistantRuntime({
3372
3631
  if (live.disposeTimer) { clearTimeout(live.disposeTimer); live.disposeTimer = null; }
3373
3632
  if (live.draftTimer) { clearTimeout(live.draftTimer); live.draftTimer = null; }
3374
3633
  live.sockets.add(ws);
3375
- live.record.status = live.record.status === 'ended' ? 'idle' : live.record.status;
3634
+ // A closed session opened again: what its workers reported meanwhile waited in the store and goes now.
3635
+ if (live.record.status === 'ended') { live.record.status = 'idle'; if (mailboxCount(live)) scheduleMailbox(live, 0); }
3376
3636
  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
3637
  try { ws.send(JSON.stringify(engine)); } catch {}
3378
3638
  try { ws.send(JSON.stringify({ type: 'assistant:session', session: view(live), reason: 'attached' })); } catch {}
@@ -3447,6 +3707,13 @@ export function createAssistantRuntime({
3447
3707
  broadcast('assistant:session-updated', live);
3448
3708
  sendToSockets(live, { type: 'assistant:session', session: view(live), reason: 'tests' });
3449
3709
  return;
3710
+ // agents-p4: the Agent density control (the owner's panel socket; an agent has no way to send this).
3711
+ case 'set_agent_density':
3712
+ applyAgentDensity(live, msg.level);
3713
+ touch(live);
3714
+ broadcast('assistant:session-updated', live);
3715
+ sendToSockets(live, { type: 'assistant:session', session: view(live), reason: 'agents' });
3716
+ return;
3450
3717
  case 'set_computer_use':
3451
3718
  applyComputerUse(live, msg.enabled);
3452
3719
  touch(live);
@@ -3500,6 +3767,10 @@ export function createAssistantRuntime({
3500
3767
  }
3501
3768
  case 'resume':
3502
3769
  if (msg.providerSessionId) {
3770
+ if (['claude-code', 'codex'].includes(live.record.brain.provider) && (live.record.providerBinding !== providerBinding(live.record) || ![live.record.providerSessionId, live.record.providerThreadId].includes(msg.providerSessionId))) {
3771
+ 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.' });
3772
+ return;
3773
+ }
3503
3774
  const moved = msg.providerSessionId !== live.record.providerSessionId;
3504
3775
  live.record.providerSessionId = msg.providerSessionId;
3505
3776
  // A provider conversation adopted (/resume <id>): the session holds a chat now.
@@ -3532,6 +3803,12 @@ export function createAssistantRuntime({
3532
3803
  return live ? testDensityOf(live.record) : null;
3533
3804
  }
3534
3805
 
3806
+ /** 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. */
3807
+ function agentDensityFor(id) {
3808
+ const live = sessions.get(id);
3809
+ return live ? agentDensityOf(live.record) : null;
3810
+ }
3811
+
3535
3812
  // ── router sinks (wired lazily in server.js; see assistant-router.js) ──────
3536
3813
  /** What the budget planner needs of a session: its brain, project, and whether it is still open. */
3537
3814
  function budgetSession(id) {
@@ -3549,7 +3826,16 @@ export function createAssistantRuntime({
3549
3826
  // remote: a decided route authorizes one dispatch only (assistant-router.js).
3550
3827
  // computer: what remoteComputerUse says for the running turn ("ask": a computer route card done here also asks for the Mac).
3551
3828
  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 };
3829
+ // turn: what the brain's running turn is on (a re-routed task continues in place when it is the approved one).
3830
+ const turn = live.turnRun ? { model: live.turnRun.model ?? null, effort: live.turnRun.effort ?? null } : null;
3831
+ // closing: the session is closing or has ended (a continuation it refuses can never run: the router answers expired).
3832
+ const closing = !!live.closing || live.record.status === 'ended';
3833
+ // pendingWork: the brain's CLI runs background work it will report back on (a background Bash, an agent, a
3834
+ // wakeup). A thinking on/off switch restarts Claude Code and would end it, so an effort-only "here" pick that
3835
+ // needs one waits (the router's thinkingWaits; the bridge defers the switch as well).
3836
+ let pendingWork = false;
3837
+ try { pendingWork = live.brain?.hasPendingWork?.() === true; } catch { pendingWork = false; }
3838
+ 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
3839
  }
3554
3840
  /**
3555
3841
  * The panel's route chip counts pending routes from the session view, so a card
@@ -3584,6 +3870,11 @@ export function createAssistantRuntime({
3584
3870
  const live = sessions.get(id);
3585
3871
  if (!live) return;
3586
3872
  emitRouteEvent(live, phase, route);
3873
+ if (phase === 'continuation_delayed') {
3874
+ const packet = { type: 'event', event: { type: 'system', subtype: 'status', text: route.reason } };
3875
+ appendTranscript(id, { at: iso(now()), packet });
3876
+ sendToSockets(live, packet);
3877
+ }
3587
3878
  if (phase !== 'card' && phase !== 'pending' && phase !== 'auto') publishPendingRoutes(live);
3588
3879
  }
3589
3880
  function routerMailbox(id, item) { const live = sessions.get(id); if (live && item) enqueueMailbox(live, item); }
@@ -3602,10 +3893,29 @@ export function createAssistantRuntime({
3602
3893
  * arrives after a newer prompt, a Stop or the session closing is refused
3603
3894
  * (false): the router then approves nothing and the card expires.
3604
3895
  */
3605
- function routerContinue(id, { target = null, route = null } = {}) {
3896
+ function routerContinue(id, { target = null, route = null, retry = false, reroute = false } = {}) {
3606
3897
  const live = sessions.get(id);
3607
3898
  if (!live || !target) return false;
3608
- const gen = live.routeGens.get(String(route?.routeId || '')) ?? live.gen;
3899
+ // Idempotent by route: the router's watchdog delivers a continuation that has not started once more, and a
3900
+ // route asked again with its task_key delivers it again. One this session already ran is done (the router
3901
+ // hears it started, and nothing runs twice); one still queued (behind a running turn, a busy brain) or on its
3902
+ // way to the brain is left where it is. Only one that was dropped (a turn that failed to start, a newer
3903
+ // prompt) is queued again, below.
3904
+ const routeId = String(route?.routeId || '');
3905
+ if (routeId) {
3906
+ if (live.continuedRoutes?.has(routeId)) {
3907
+ try { router?.continuationStarted?.(routeId); } catch {}
3908
+ return true;
3909
+ }
3910
+ const queued = live.work.get('continuation');
3911
+ if (queued?.routeId === routeId && workCurrent(live, queued)) return true;
3912
+ const active = activeWork(live);
3913
+ if (active?.kind === 'continuation' && active.routeId === routeId) return true;
3914
+ }
3915
+ // A re-route (agent_route again for an approved task) is asked in the turn running now, whatever the
3916
+ // generation the route's card was raised in or it was first delivered in: it continues after this turn,
3917
+ // in this generation (and the watchdog's retries follow it there). A retry keeps its own generation.
3918
+ const gen = reroute ? live.gen : (live.routeGens.get(routeId) ?? live.gen);
3609
3919
  if (gen !== live.gen || live.record.status === 'ended' || live.closing) {
3610
3920
  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
3921
  return false;
@@ -3613,9 +3923,20 @@ export function createAssistantRuntime({
3613
3923
  const row = target.model ? findModel(catalog?.peek?.() || null, target.provider, target.model)?.row : null;
3614
3924
  const label = row?.label || target.model || 'the chosen model';
3615
3925
  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.`;
3926
+ // An effort-only pick is a continuation on the brain's own model with the picked effort, for this task only.
3927
+ const effortText = !target.effort ? '' : String(target.effort).toLowerCase() === EFFORT_OFF ? ' (thinking off)' : ` (effort ${target.effort})`;
3928
+ 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
3929
  // `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) } });
3930
+ // A route with no card (approved at once) belongs to the generation it was first delivered in: a later delivery
3931
+ // after a newer prompt or a Stop is refused like a late pick. A re-route moves it to this generation.
3932
+ if (routeId && (reroute || !live.routeGens.has(routeId))) {
3933
+ live.routeGens.delete(routeId);
3934
+ live.routeGens.set(routeId, gen);
3935
+ while (live.routeGens.size > 50) live.routeGens.delete(live.routeGens.keys().next().value);
3936
+ }
3937
+ if (reroute) log('assistant:work', `${id}: ${routeId || 'a route'} was routed again in a later turn; its continuation is queued`);
3938
+ else if (retry) log('assistant:work', `${id}: the "do it here" continuation of ${routeId || 'a route'} had not started; queued again`);
3939
+ queueWork(live, { kind: 'continuation', gen, routeId: route?.routeId, options: { text, turnModel: target.model || null, turnEffort: target.effort || null, gateOpen: true, origin: lastPromptOrigin(live) } });
3619
3940
  return true;
3620
3941
  }
3621
3942
  function routerSinks() {
@@ -4037,22 +4358,30 @@ export function createAssistantRuntime({
4037
4358
  if (unsubscribeDispatcher) { try { unsubscribeDispatcher(); } catch {} unsubscribeDispatcher = null; }
4038
4359
  if (unsubscribePolicy) { try { unsubscribePolicy(); } catch {} unsubscribePolicy = null; }
4039
4360
  if (unsubscribeUsage) { try { unsubscribeUsage(); } catch {} unsubscribeUsage = null; }
4361
+ if (unsubscribeMailbox) { try { unsubscribeMailbox(); } catch {} unsubscribeMailbox = null; }
4362
+ if (mailboxBootTimer) { clearTimeout(mailboxBootTimer); mailboxBootTimer = null; }
4040
4363
  for (const timer of usageTimers.values()) clearTimeout(timer);
4041
4364
  usageTimers.clear();
4042
4365
  packetObservers.clear();
4043
4366
  shuttingDown = true;
4044
4367
  for (const live of sessions.values()) {
4045
4368
  if (live.mailboxTimer) clearTimeout(live.mailboxTimer);
4369
+ if (live.mailboxRetryTimer) clearTimeout(live.mailboxRetryTimer);
4046
4370
  if (live.disposeTimer) clearTimeout(live.disposeTimer);
4047
4371
  if (live.draftTimer) clearTimeout(live.draftTimer);
4048
4372
  if (live.workTimer) clearTimeout(live.workTimer);
4049
4373
  await disposeBrain(live, 'shutdown').catch(() => {});
4050
- live.record.status = 'idle';
4374
+ // A session the user closed stays closed across the restart (loadIndex keeps 'ended'): what its workers
4375
+ // report meanwhile waits in the store until it is opened again, and starts no brain at the next start.
4376
+ if (live.record.status !== 'ended') live.record.status = 'idle';
4051
4377
  }
4052
4378
  persist({ force: true });
4053
4379
  try { userContext?.shutdown(); } catch {}
4054
4380
  // Rows whose append failed get one more try before the process goes.
4055
4381
  metered('flush', () => usage?.flush?.());
4382
+ // A coordination service this runtime made for itself goes with it (a shared one is closed by its owner).
4383
+ // What a brain was not told stays open in the store and is delivered by the next start.
4384
+ if (ownsCoordination) coordination.close();
4056
4385
  }
4057
4386
 
4058
4387
  loadIndex();
@@ -4066,18 +4395,34 @@ export function createAssistantRuntime({
4066
4395
  else if (payload?.type === 'assistant:run-removed') onRunRemoved(payload);
4067
4396
  });
4068
4397
  }
4398
+ // Agents P2: the store wakes the mailbox of the session an event was addressed to (after its append committed).
4399
+ try {
4400
+ unsubscribeMailbox = coordination.mailbox.subscribe((sessionId, event) => {
4401
+ const live = sessions.get(sessionId);
4402
+ if (live) onMailboxEvent(live, event);
4403
+ });
4404
+ } catch (error) { log('assistant:mailbox-error', error?.message || String(error)); }
4405
+ // After a restart, once this server answers its workers: the mailboxes that were open are delivered again.
4406
+ if (coordination.durable) {
4407
+ Promise.resolve().then(() => dispatcher?.whenServerReady?.()).catch(() => {}).then(() => {
4408
+ if (shuttingDown) return;
4409
+ mailboxBootTimer = setTimeout(() => { mailboxBootTimer = null; resumeMailboxes(); }, settings.mailboxBootDelayMs);
4410
+ mailboxBootTimer.unref?.();
4411
+ });
4412
+ }
4069
4413
  const originalBroadcast = broadcastSync;
4070
4414
  // Permission broadcasts come from the dispatcher through broadcastSync; observe them here too.
4071
4415
  broadcastSync = (message) => { try { originalBroadcast(message); } catch {} if (message?.type === 'assistant:permission-request' || message?.type === 'assistant:permission-resolved') onPermissionBroadcast(message); };
4072
4416
 
4073
4417
  return {
4418
+ lastOwnerTurnAt: (sessionId) => sessions.get(sessionId)?.record.lastOwnerTurnAt ?? null,
4074
4419
  handleWebSocket, listSessions, getSession, createSession, updateSession, closeSession, destroySession, removeSession,
4075
4420
  resolveTerminal, accountInUse, ownsIsolatedServe, noteDispatch, subscribe, shutdown,
4076
4421
  // The sessions index written now, synchronously: the server's exit handler runs it on every way out,
4077
4422
  // since an exit through process.exit() never reaches shutdown()'s own write.
4078
4423
  flushIndex: () => persist({ force: true }),
4079
4424
  observeBroadcast: onPermissionBroadcast,
4080
- testDensityFor, routerSession, routerSend, routerEvent, routerMailbox, routerContinue, routerSinks, routerRouted, routerRouteFailed, routerComputerApproved, gateCheck, isPlanning, isPlanReadOnly,
4425
+ testDensityFor, agentDensityFor, routerSession, routerSend, routerEvent, routerMailbox, routerContinue, routerSinks, routerRouted, routerRouteFailed, routerComputerApproved, gateCheck, isPlanning, isPlanReadOnly,
4081
4426
  clarifySession, clarifyEvent, clarifyGate, clarifySinks,
4082
4427
  getComputerUse, getComputerTurn, supersedeComputerApproval, abortTurn, notifySession,
4083
4428
  brainSpend, brainSpendByProvider, budgetSession, onBudgetChanged, onBudgetSplit, sendBudget, currentTask, usageView,
@@ -4085,6 +4430,8 @@ export function createAssistantRuntime({
4085
4430
  observe, submit, stopTurn, answerControl, answerDispatchControl, pendingControls, isBusy, sessionPolicy, sessionChannel,
4086
4431
  // whatsapp_send_file's caller identity (POST /api/assistant/whatsapp/send-file).
4087
4432
  sessionForBrainCredential,
4088
- _internals: { sessions, ensureBrain, disposeBrain, runQuery, enqueueMailbox, deliverMailbox, settings, ensureGate, onBrainPacket, onTurnFinished, remoteHooks, packetObservers, userContext },
4433
+ // Agents P2: the coordination service the mailbox reads from.
4434
+ coordination,
4435
+ _internals: { sessions, ensureBrain, disposeBrain, runQuery, enqueueMailbox, deliverMailbox, resumeMailboxes, settings, ensureGate, onBrainPacket, onTurnFinished, remoteHooks, packetObservers, userContext },
4089
4436
  };
4090
4437
  }