synabun 2.3.1 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +189 -0
  4. package/browser-extension/engine.js +508 -0
  5. package/browser-extension/icons/icon-128.png +0 -0
  6. package/browser-extension/icons/icon-16.png +0 -0
  7. package/browser-extension/icons/icon-32.png +0 -0
  8. package/browser-extension/icons/icon-48.png +0 -0
  9. package/browser-extension/icons/status-off-16.png +0 -0
  10. package/browser-extension/icons/status-off-32.png +0 -0
  11. package/browser-extension/icons/status-off-48.png +0 -0
  12. package/browser-extension/icons/status-on-16.png +0 -0
  13. package/browser-extension/icons/status-on-32.png +0 -0
  14. package/browser-extension/icons/status-on-48.png +0 -0
  15. package/browser-extension/manifest.json +56 -0
  16. package/browser-extension/popup-strings.js +250 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +166 -0
  19. package/browser-extension/popup.html +108 -0
  20. package/browser-extension/popup.js +359 -0
  21. package/browser-extension/protocol.js +232 -0
  22. package/browser-extension/service-worker.js +275 -0
  23. package/browser-extension/setup-content.js +36 -0
  24. package/browser-extension/tokens.css +326 -0
  25. package/docs/browser-extension-bridge.md +84 -0
  26. package/docs/whatsapp.md +1 -1
  27. package/lib/data-home-files.js +45 -0
  28. package/lib/data-home-migration.js +34 -58
  29. package/mcp-server/dist/http.d.ts +2 -0
  30. package/mcp-server/dist/http.d.ts.map +1 -1
  31. package/mcp-server/dist/http.js +9 -1
  32. package/mcp-server/dist/http.js.map +1 -1
  33. package/mcp-server/dist/index.d.ts +11 -0
  34. package/mcp-server/dist/index.d.ts.map +1 -1
  35. package/mcp-server/dist/index.js +38 -3
  36. package/mcp-server/dist/index.js.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  38. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  39. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  40. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  41. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  42. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  43. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.d.ts +95 -3
  45. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  46. package/mcp-server/dist/services/neural-interface.js +168 -23
  47. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  48. package/mcp-server/dist/services/team-context.d.ts +18 -0
  49. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  50. package/mcp-server/dist/services/team-context.js +29 -0
  51. package/mcp-server/dist/services/team-context.js.map +1 -0
  52. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  53. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  54. package/mcp-server/dist/services/tool-catalog.js +22 -6
  55. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  56. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  57. package/mcp-server/dist/services/tool-list.js +4 -0
  58. package/mcp-server/dist/services/tool-list.js.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  60. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  61. package/mcp-server/dist/services/tool-runtime.js +18 -1
  62. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  63. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  64. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  65. package/mcp-server/dist/tools/agent-definition.js +483 -0
  66. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  67. package/mcp-server/dist/tools/agents.d.ts +92 -9
  68. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  69. package/mcp-server/dist/tools/agents.js +163 -20
  70. package/mcp-server/dist/tools/agents.js.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  72. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  73. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  74. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  76. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/git-tools.js +283 -2
  78. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  80. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/morelogin.js +22 -5
  82. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  83. package/mcp-server/dist/tools/team.d.ts +32 -0
  84. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/team.js +87 -0
  86. package/mcp-server/dist/tools/team.js.map +1 -0
  87. package/mcp-server/package-lock.json +2 -2
  88. package/mcp-server/package.json +1 -1
  89. package/mcp-server/src/http.ts +9 -1
  90. package/mcp-server/src/index.ts +34 -4
  91. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  92. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  93. package/mcp-server/src/services/neural-interface.ts +191 -29
  94. package/mcp-server/src/services/team-context.ts +27 -0
  95. package/mcp-server/src/services/tool-catalog.ts +26 -8
  96. package/mcp-server/src/services/tool-list.ts +4 -0
  97. package/mcp-server/src/services/tool-runtime.ts +21 -2
  98. package/mcp-server/src/tools/agent-definition.ts +458 -0
  99. package/mcp-server/src/tools/agents.ts +177 -19
  100. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  101. package/mcp-server/src/tools/git-tools.ts +249 -3
  102. package/mcp-server/src/tools/morelogin.ts +20 -5
  103. package/mcp-server/src/tools/team.ts +97 -0
  104. package/neural-interface/i18n/en.json +1119 -47
  105. package/neural-interface/i18n/pt-BR.json +1119 -47
  106. package/neural-interface/lib/account-usage.js +1 -1
  107. package/neural-interface/lib/agents/builtins.json +207 -0
  108. package/neural-interface/lib/agents/density.js +101 -0
  109. package/neural-interface/lib/agents/forge-host.js +223 -0
  110. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  111. package/neural-interface/lib/agents/native-export.js +365 -0
  112. package/neural-interface/lib/agents/registry.js +885 -0
  113. package/neural-interface/lib/agents/resolve.js +603 -0
  114. package/neural-interface/lib/agents/schema.js +642 -0
  115. package/neural-interface/lib/agents/split.js +37 -0
  116. package/neural-interface/lib/agents-studio-api.js +591 -0
  117. package/neural-interface/lib/assistant-api.js +76 -7
  118. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  119. package/neural-interface/lib/assistant-catalog.js +2 -0
  120. package/neural-interface/lib/assistant-continuity.js +49 -0
  121. package/neural-interface/lib/assistant-dispatch.js +351 -121
  122. package/neural-interface/lib/assistant-persona.js +105 -8
  123. package/neural-interface/lib/assistant-route-gate.js +24 -9
  124. package/neural-interface/lib/assistant-router.js +432 -47
  125. package/neural-interface/lib/assistant-run-tail.js +151 -0
  126. package/neural-interface/lib/assistant-run-wait.js +183 -0
  127. package/neural-interface/lib/assistant-runtime.js +449 -94
  128. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  129. package/neural-interface/lib/assistant-usage.js +3 -2
  130. package/neural-interface/lib/automation-approval.js +2 -2
  131. package/neural-interface/lib/backup-service.js +64 -105
  132. package/neural-interface/lib/browser-close-evidence.js +80 -0
  133. package/neural-interface/lib/browser-default.js +210 -0
  134. package/neural-interface/lib/browser-extension-adapter.js +264 -0
  135. package/neural-interface/lib/browser-extension-bridge.js +441 -0
  136. package/neural-interface/lib/browser-extension-folder.js +116 -0
  137. package/neural-interface/lib/browser-extension-setup.js +140 -0
  138. package/neural-interface/lib/browser-profile-choices.js +3 -3
  139. package/neural-interface/lib/browser-tool-policy.js +1 -1
  140. package/neural-interface/lib/claude-account-links.js +301 -0
  141. package/neural-interface/lib/claude-accounts.js +45 -20
  142. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  143. package/neural-interface/lib/claude-model-catalog.js +6 -0
  144. package/neural-interface/lib/claude-panel-session.js +33 -0
  145. package/neural-interface/lib/codex-accounts.js +67 -24
  146. package/neural-interface/lib/coordination/README.md +384 -0
  147. package/neural-interface/lib/coordination/service.js +563 -0
  148. package/neural-interface/lib/coordination/store.js +1138 -0
  149. package/neural-interface/lib/db.js +22 -1
  150. package/neural-interface/lib/effort-levels.js +10 -1
  151. package/neural-interface/lib/memory-list-page.js +49 -0
  152. package/neural-interface/lib/memory-list-stamp.js +60 -0
  153. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  154. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  155. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  156. package/neural-interface/lib/morelogin.js +194 -8
  157. package/neural-interface/lib/native-loop-runtime.js +26 -7
  158. package/neural-interface/lib/opencode-build-preflight.js +28 -8
  159. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  160. package/neural-interface/lib/opencode-serve-records.js +14 -9
  161. package/neural-interface/lib/page-session.js +1 -1
  162. package/neural-interface/lib/peer-identity.js +73 -29
  163. package/neural-interface/lib/process-identity.js +68 -7
  164. package/neural-interface/lib/request-gate.js +3 -0
  165. package/neural-interface/lib/screenshot-location.js +33 -0
  166. package/neural-interface/lib/session-cache-builder.js +41 -3
  167. package/neural-interface/lib/skills/creation.js +1 -1
  168. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  169. package/neural-interface/lib/studio-attention.js +56 -0
  170. package/neural-interface/lib/teams/README.md +382 -0
  171. package/neural-interface/lib/teams/api.js +287 -0
  172. package/neural-interface/lib/teams/brief.js +185 -0
  173. package/neural-interface/lib/teams/claims.js +315 -0
  174. package/neural-interface/lib/teams/git.js +293 -0
  175. package/neural-interface/lib/teams/index.js +122 -0
  176. package/neural-interface/lib/teams/integration.js +580 -0
  177. package/neural-interface/lib/teams/landing.js +184 -0
  178. package/neural-interface/lib/teams/recovery.js +256 -0
  179. package/neural-interface/lib/teams/scheduler.js +1474 -0
  180. package/neural-interface/lib/teams/schema.js +559 -0
  181. package/neural-interface/lib/teams/state.js +181 -0
  182. package/neural-interface/lib/teams/test-runner.js +86 -0
  183. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  184. package/neural-interface/lib/teams/worktrees.js +757 -0
  185. package/neural-interface/lib/tool-permission-choices.js +226 -0
  186. package/neural-interface/lib/whatsapp/cards.js +24 -10
  187. package/neural-interface/lib/worker-confinement.js +206 -6
  188. package/neural-interface/package-lock.json +2 -2
  189. package/neural-interface/package.json +1 -1
  190. package/neural-interface/public/extension-setup.html +107 -0
  191. package/neural-interface/public/index.html +103 -12
  192. package/neural-interface/public/offline.html +4 -3
  193. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  194. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  195. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  196. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  197. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  198. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  199. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  200. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  201. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  202. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  203. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  204. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  205. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  206. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  207. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  208. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  209. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  210. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  211. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  212. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  213. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  214. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  215. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  216. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  217. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  218. package/neural-interface/public/shared/api.js +2 -1
  219. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  220. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  221. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  222. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  223. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  224. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  225. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  226. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  227. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  228. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  229. package/neural-interface/public/shared/assistant/asst-render.js +37 -6
  230. package/neural-interface/public/shared/assistant/asst-route.js +80 -12
  231. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  232. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  233. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  234. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  235. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  236. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  237. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  238. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  239. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  240. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  241. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  242. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  243. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  244. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  245. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  246. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  247. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  248. package/neural-interface/public/shared/code-copy.js +120 -0
  249. package/neural-interface/public/shared/constants.js +7 -0
  250. package/neural-interface/public/shared/context-menu-model.js +1 -0
  251. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  252. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  253. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  254. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  255. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  256. package/neural-interface/public/shared/dom-morph.js +124 -0
  257. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  258. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  259. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  260. package/neural-interface/public/shared/html-shell.js +34 -4
  261. package/neural-interface/public/shared/i18n.js +14 -1
  262. package/neural-interface/public/shared/idle-queue.js +78 -0
  263. package/neural-interface/public/shared/iface-config.js +227 -0
  264. package/neural-interface/public/shared/lazy-module.js +108 -0
  265. package/neural-interface/public/shared/memory-list.js +117 -0
  266. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  267. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  268. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  269. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  278. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  279. package/neural-interface/public/shared/page-session.js +1 -1
  280. package/neural-interface/public/shared/schedules-view.js +2 -2
  281. package/neural-interface/public/shared/session-project-items.js +11 -0
  282. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  283. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  284. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  285. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  286. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  287. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  288. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  289. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  290. package/neural-interface/public/shared/start-bridge.js +2 -2
  291. package/neural-interface/public/shared/storage.js +6 -1
  292. package/neural-interface/public/shared/studio-attention.js +83 -0
  293. package/neural-interface/public/shared/styles.css +694 -50
  294. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  295. package/neural-interface/public/shared/transcript-rows.js +334 -0
  296. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  297. package/neural-interface/public/shared/ui-agents.js +97 -0
  298. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  299. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  300. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  301. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  302. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  303. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  304. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  305. package/neural-interface/public/shared/ui-games.js +1 -1
  306. package/neural-interface/public/shared/ui-loading.js +83 -19
  307. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  308. package/neural-interface/public/shared/ui-menubar.js +23 -0
  309. package/neural-interface/public/shared/ui-native-loop-router.js +50 -21
  310. package/neural-interface/public/shared/ui-navbar.js +15 -9
  311. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  312. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  313. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  314. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  315. package/neural-interface/public/shared/ui-sessions.js +3 -3
  316. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  317. package/neural-interface/public/shared/ui-settings.js +363 -400
  318. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  319. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  320. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  321. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  322. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  323. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  324. package/neural-interface/public/shared/ui-sync.js +6 -0
  325. package/neural-interface/public/shared/ui-terminal.js +13 -9
  326. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  327. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  328. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  329. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  330. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  331. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  332. package/neural-interface/public/shared/window-keys.js +71 -0
  333. package/neural-interface/public/sw.js +4 -3
  334. package/neural-interface/public/variant/2d/main.js +2 -0
  335. package/neural-interface/public/variant/3d/app.js +620 -0
  336. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  337. package/neural-interface/public/variant/3d/main.js +30 -544
  338. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  339. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  340. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  341. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  342. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  343. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  346. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  347. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  348. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  349. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  350. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  351. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  352. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  353. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  354. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  355. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  356. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  357. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  358. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  359. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  360. package/neural-interface/scripts/boot-graph.mjs +270 -0
  361. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  362. package/neural-interface/server.js +1083 -164
  363. package/npm-shrinkwrap.json +2 -2
  364. package/package.json +4 -1
  365. package/skills/agent-forge/SKILL.md +182 -0
  366. package/skills/agent-forge/evals/evals.json +56 -0
  367. package/skills/agent-forge/references/definition-fields.md +61 -0
  368. package/skills/agent-forge/references/examples.md +105 -0
  369. package/skills/agent-forge/references/instructions.md +51 -0
  370. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -29,8 +29,12 @@
29
29
  // It validates targets against the catalog, remembers per-class preferences,
30
30
  // holds un-routed dispatches until the user picks (dispatcher `awaiting_route`)
31
31
  // and suggests one-tier escalations when a run fails or reports blocked.
32
- // All I/O is injected (catalog, config store, sinks into the runtime/dispatcher).
32
+ // Catalog, config and runtime I/O are injected. The split planner checks git before worktree approval.
33
33
 
34
+ import { routeTaskIdentity } from '../public/shared/assistant/route-identity.js';
35
+ import { agentPinOf, agentRefOf, routedAgent } from './agents/resolve.js';
36
+ import { planRouteSplit } from './agents/split.js';
37
+ import { normalizeAgentDensity } from './agents/density.js';
34
38
  import { randomBytes } from 'node:crypto';
35
39
  import { CATALOG_PROVIDERS, TIERS, defaultIsHidden, defaultModelRow, findModel, hiddenModelId, priceText, providerAllHidden, providerEmpty, rowIsHidden, rowMakes } from './assistant-catalog.js';
36
40
  import { effectiveRouting, normalizeRouteMode } from './assistant-config.js';
@@ -92,6 +96,11 @@ export function runContract(taskClass) { return requiredOutput(taskClass) || cla
92
96
  const TIER_RANK = { small: 0, medium: 1, large: 2 };
93
97
  const MAX_ESCALATION_DEPTH = 2;
94
98
  const DECIDED_TTL_MS = 60 * 60_000;
99
+ // A queued "do it here" continuation not started after this is delivered once more; still not started after the
100
+ // same again, the brain and the panel are told (maybeContinuation's watchdog).
101
+ export const CONTINUATION_WATCH_MS = 30_000;
102
+ const CONTINUATION_WATCH_S = CONTINUATION_WATCH_MS / 1000;
103
+ const CONTINUATIONS_KEPT = 200;
95
104
 
96
105
  function clip(value, max = 200) {
97
106
  const text = String(value ?? '').replace(/\s+/g, ' ').trim();
@@ -207,8 +216,9 @@ export function normalizeRouteRequest(body = {}, { brain = {} } = {}) {
207
216
  let coercedProvider = null;
208
217
  for (const raw of Array.isArray(body.proposals) ? body.proposals.slice(0, 3) : []) {
209
218
  if (!raw || typeof raw !== 'object') continue;
219
+ const requested = agentRefOf(raw);
210
220
  let kind = raw.kind === 'direct' ? 'direct' : 'dispatch';
211
- let provider = CATALOG_PROVIDERS.includes(raw.provider) ? raw.provider : null;
221
+ let provider = CATALOG_PROVIDERS.includes(raw.provider) ? raw.provider : requested === 'none' ? brain.provider : null;
212
222
  let model = raw.model ? String(raw.model).trim().slice(0, 200) : null;
213
223
  if (kind === 'direct') {
214
224
  if (provider && provider !== brain.provider) {
@@ -224,6 +234,7 @@ export function normalizeRouteRequest(body = {}, { brain = {} } = {}) {
224
234
  }
225
235
  proposals.push({
226
236
  kind, provider, model,
237
+ ...(requested ? { agentRequest: requested } : {}),
227
238
  effort: raw.effort ? String(raw.effort).trim().slice(0, 40) : null,
228
239
  ...(raw.accountId || raw.account_id ? { accountId: String(raw.accountId || raw.account_id).slice(0, 64) } : {}),
229
240
  reason: raw.reason ? clip(raw.reason, 240) : null,
@@ -274,12 +285,17 @@ export function describeTarget(target, { catalog = null, brain = {}, brainInfo =
274
285
  /**
275
286
  * `target` with its effort checked against its model (effort-levels.js): an
276
287
  * unsupported level becomes the nearest one the model runs, and the change is
277
- * pushed onto `corrections` as { field: 'effort', from, to, reason: 'effort_unsupported' }.
288
+ * pushed onto `corrections` as { field: 'effort', from, to, reason: 'effort_unsupported' }. Off (`none`) on a
289
+ * Claude model whose thinking cannot be turned off runs at the lowest level, reason 'thinking_always_on', with a
290
+ * text that says so: no route claims "thinking off" while the request carries adaptive thinking.
278
291
  */
279
292
  export function effortChecked(target, catalog, corrections = null) {
280
293
  if (!target?.effort) return target;
281
294
  const { effort, corrected } = normalizeEffort({ provider: target.provider, model: target.model || null, effort: target.effort, catalog });
282
- if (corrected) corrections?.push({ field: 'effort', from: corrected.from, to: corrected.to, reason: 'effort_unsupported' });
295
+ if (corrected?.reason === 'thinking_always_on') {
296
+ corrections?.push({ field: 'effort', from: corrected.from, to: corrected.to, reason: 'thinking_always_on',
297
+ text: `effort none (thinking off) runs as ${corrected.to}: ${target.model || 'this model'} cannot turn its thinking off` });
298
+ } else if (corrected) corrections?.push({ field: 'effort', from: corrected.from, to: corrected.to, reason: 'effort_unsupported' });
283
299
  return effort === target.effort ? target : { ...target, effort };
284
300
  }
285
301
 
@@ -894,7 +910,7 @@ export function routeSides({ options = [], request = {}, defaultOptionId = null
894
910
  const label = request.taskClassLabel || TASK_CLASS_META[request.taskClass]?.label || 'This task';
895
911
  const side = (kind) => {
896
912
  if (firstOf(kind)) return { available: true, reason: null, code: null };
897
- if (kind === 'direct' && request.dispatchOnly) return { available: false, code: 'worker_only', reason: `${label} always runs on a worker.` };
913
+ if (kind === 'direct' && request.dispatchOnly) return { available: false, code: 'worker_only', reason: request.plannedSplit ? 'This task uses the approved worker plan.' : `${label} always runs on a worker.` };
898
914
  if (kind === 'direct' && options.some((o) => o.kind === 'dispatch' && o.accountKind === 'direct')) {
899
915
  return { available: false, code: 'account_worker', reason: "This conversation's account cannot take it, so it runs on a worker." };
900
916
  }
@@ -1057,9 +1073,11 @@ export function escalationFor({ run, catalog = null, routing = {}, depth = 0 })
1057
1073
  export function createAssistantRouter({
1058
1074
  catalog,
1059
1075
  configStore = null,
1076
+ agents = null,
1060
1077
  getSession = () => null,
1061
1078
  sinks = {},
1062
1079
  now = Date.now,
1080
+ continuationTimers = { setTimeout, clearTimeout },
1063
1081
  randomId = () => randomBytes(6).toString('hex'),
1064
1082
  log = () => {},
1065
1083
  clarifier = null,
@@ -1073,10 +1091,37 @@ export function createAssistantRouter({
1073
1091
  // routeId → decided route (reusable by agent_dispatch route_id; a remote session's is
1074
1092
  // used up by the first dispatch that starts a run: `consumed`).
1075
1093
  const decided = new Map();
1094
+ const continuations = new Map();
1076
1095
  const stamps = new Map(); // sessionId → last stamp shown to the brain
1077
1096
  const lastClosed = new Map(); // routeId → { routeId, settled } of recently closed cards
1078
1097
  const call = (name, ...args) => { try { return sinks[name]?.(...args); } catch (error) { log('router:sink-error', `${name}: ${error?.message || error}`); return undefined; } };
1079
1098
 
1099
+ // Resolve each distinct proposed role once. A different model (saved preference, budget or
1100
+ // custom card choice) can still run the proposed role. Direct choices never use a worker.
1101
+ function workerRoles(request, cwd, pin = null) {
1102
+ const roles = new Map();
1103
+ return request.proposals.map(proposal => {
1104
+ const ref = proposal.agentRequest;
1105
+ if (pin) return { agentRef: pin.ref, agentRevision: pin.revision, agentRequest: pin.ref };
1106
+ if (!roles.has(ref)) {
1107
+ const role = agents ? routedAgent(agents, request.taskClass, cwd, ref) : {};
1108
+ roles.set(ref, role.meta || (role.note ? { agentCorrection: role.note } : {}));
1109
+ }
1110
+ return roles.get(ref);
1111
+ });
1112
+ }
1113
+ function workerRole(request, target, optionId) {
1114
+ if (target?.kind !== 'dispatch' || !request.roles) return {};
1115
+ const suggestion = /^s([1-3])$/.exec(optionId || '');
1116
+ const index = suggestion ? Number(suggestion[1]) - 1 : 0;
1117
+ return request.roles[index] || request.roles[0] || {};
1118
+ }
1119
+ function agentFields(record) {
1120
+ if (!record) return {};
1121
+ const { agentRef, agentRevision, agentRequest, agentCorrection } = record;
1122
+ return { ...(agentRef ? { agentRef, agentRevision } : {}), ...(agentRequest ? { agentRequest } : {}),
1123
+ ...(agentCorrection ? { agentCorrection } : {}) };
1124
+ }
1080
1125
  function routing() { try { return configStore?.routing?.() || effectiveRouting({}); } catch { return effectiveRouting({}); } }
1081
1126
  function modeFor(sessionId) {
1082
1127
  const session = getSession(sessionId);
@@ -1144,7 +1189,7 @@ export function createAssistantRouter({
1144
1189
  };
1145
1190
  call('routeEvent', sessionId, 'declined', routeView(route, { catalog: cat, brain, brainInfo }));
1146
1191
  return {
1147
- ok: true, status: 'declined', reason: 'budget_exhausted', dry, routeId, mode, source: 'budget', target: null,
1192
+ ok: true, status: 'declined', reason: 'budget_exhausted', reasonCode: 'budget_exhausted', dry, routeId, mode, source: 'budget', target: null,
1148
1193
  remembered: false, continuation: false, corrections: evaluation.corrections || [], runIds: [], expiresAt: null,
1149
1194
  budget: compactBudget(sessionId), next: budgetDeclinedText(sessionId, dry),
1150
1195
  };
@@ -1196,13 +1241,17 @@ export function createAssistantRouter({
1196
1241
  }
1197
1242
  function pruneDecided() {
1198
1243
  const cutoff = now();
1199
- for (const [id, route] of decided) if (route.expiresAt < cutoff) decided.delete(id);
1244
+ // A later mailbox turn can revisit an older task. Keep its identity for the live session,
1245
+ // including closed tombstones; TTL only evicts legacy routes or sessions that are gone.
1246
+ for (const [id, route] of decided) if (route.expiresAt < cutoff && (!route.taskId || !getSession(route.sessionId))) decided.delete(id);
1200
1247
  }
1201
1248
 
1202
1249
  function routeView(source, { catalog: cat = null, brain = {}, brainInfo = null } = {}) {
1203
1250
  const target = source.target ? describeTarget(source.target, { catalog: cat, brain, brainInfo }) : null;
1204
1251
  return {
1252
+ ...agentFields(source),
1205
1253
  routeId: source.routeId, runIds: [...(source.runIds || [])], taskClass: source.taskClass, taskClassLabel: TASK_CLASS_META[source.taskClass]?.label || source.taskClass,
1254
+ plannedSplit: source.plannedSplit || null, sessionId: source.sessionId || null, taskId: source.taskId || null, taskKey: source.taskKey || '',
1206
1255
  summary: source.summary || '', confidence: source.confidence ?? null, reason: source.reason || null,
1207
1256
  target, alternatives: (source.alternatives || []).slice(0, 4), decidedBy: source.decidedBy || null, remembered: !!source.remembered,
1208
1257
  optionId: source.optionId || null, corrections: source.corrections || [], mode: source.mode || null, status: source.status || null,
@@ -1217,7 +1266,7 @@ export function createAssistantRouter({
1217
1266
 
1218
1267
  function nextText(status, target, { routeId, label } = {}) {
1219
1268
  if (status === 'pending') return 'The user has not picked a model yet. End your turn now with one short line saying you are waiting for their choice. Their decision arrives as a [SynaBun Mailbox] route_decided event; do not start the task before it.';
1220
- if (status === 'declined') return 'The user declined this route. Do not start the task; ask what they would like instead.';
1269
+ if (status === 'declined') return label === 'dismissed' ? 'The route card was dismissed. Do not start the task; route again when ready.' : label === 'cancelled' ? 'The user cancelled this route. Do not start the task; ask what they would like instead.' : 'This route was declined by the routing system. Do not start the task; check the route reason.';
1221
1270
  // The user wrote something else instead of choosing (cancel 'superseded'): their message is next, so nothing is asked here.
1222
1271
  if (status === 'moved_on') return 'The user did not pick a model: they sent a new message instead, which you get next. Nothing was approved, so do not start this task. End your turn now, with no text unless you have a result to report.';
1223
1272
  if (status === 'expired' || status === 'cancelled') return 'This route is no longer valid. Do not start the task; ask the user how to proceed.';
@@ -1225,21 +1274,182 @@ export function createAssistantRouter({
1225
1274
  if (target.kind === 'dispatch') {
1226
1275
  return `Dispatch now with agent_dispatch route_id="${routeId}" (provider ${target.provider}${target.model ? `, model ${target.model}` : ', provider default model'}${target.effort ? `, effort ${target.effort}` : ''}). Do not ask the user again about the model.`;
1227
1276
  }
1228
- if (target.continuation) return `The user chose to run this here on ${label || target.model}. End your turn now with one short line; SynaBun continues this task on that model immediately after.`;
1277
+ if (target.continuation) return `The user chose to run this here on ${label || target.model}${target.effort ? ` (${effortWord(target.effort)})` : ''}. End your turn now with one short line; SynaBun has queued a continuation on that model and effort; if it has not started within ${CONTINUATION_WATCH_S} seconds it is delivered once more, and you are told if that one does not start either.`;
1229
1278
  return 'Proceed here yourself now.';
1230
1279
  }
1231
1280
 
1232
- /** A "do it here" pick on another model or effort: the runtime continues the task on it. */
1233
- function continuesHere(target, brain) {
1281
+ /**
1282
+ * An effort as `model` runs it, for comparing two of them: corrected to a level the model supports
1283
+ * (effort-levels.js normalizeEffort), lower case; none / no setting -> the row's `defaultEffort`
1284
+ * when the catalog names one, else null (the model's default).
1285
+ */
1286
+ function runEffort(provider, model, effort) {
1287
+ const cat = catalog.peek?.() || null;
1288
+ const kept = normalizeEffort({ provider, model, effort, catalog: cat }).effort;
1289
+ if (kept) return String(kept).toLowerCase();
1290
+ let row = null;
1291
+ try { row = model ? findModel(cat, provider, model)?.row || null : defaultModelRow(cat, provider); } catch { row = null; }
1292
+ return row?.defaultEffort ? String(row.defaultEffort).toLowerCase() : null;
1293
+ }
1294
+ /**
1295
+ * Does a direct `target` ask for another effort than `turn` runs on? A target with no effort (null, Auto /
1296
+ * default, or a model that takes no effort) is the session's own: no. An effort that clamps to the turn's is
1297
+ * the same; Off (`none`) and a level always differ.
1298
+ */
1299
+ function effortDiffers(target, turn = {}) {
1300
+ if (!target?.effort) return false;
1301
+ const provider = target.provider || turn.provider || null;
1302
+ const model = target.model || turn.model || null;
1303
+ if (!normalizeEffort({ provider, model, effort: target.effort, catalog: catalog.peek?.() || null }).effort) return false;
1304
+ return runEffort(provider, model, target.effort) !== runEffort(provider, model, turn.effort ?? null);
1305
+ }
1306
+ /**
1307
+ * A "do it here" pick hands off to a continuation turn when it switches the model (or provider) away from
1308
+ * `brain`, or asks for another effort than the brain's running turn is on (`turn`, turnBrain: a continuation's
1309
+ * effort, which a turn the CLI starts by itself afterwards keeps). The continuation runs that one task on the
1310
+ * pick; the session's own effort is not changed, so the turns after it are back on it.
1311
+ */
1312
+ function continuesHere(target, brain, turn = brain) {
1234
1313
  if (!target || target.kind !== 'direct') return false;
1235
- if (String(target.model || '') === String(brain.model || '') && !target.effort) return false;
1236
- if (String(target.model || '') === String(brain.model || '') && String(target.effort || '') === String(brain.effort || '')) return false;
1314
+ if (String(target.provider || brain.provider) !== String(brain.provider)
1315
+ || String(target.model || brain.model || '') !== String(brain.model || '')) return true;
1316
+ return effortDiffers(target, turn);
1317
+ }
1318
+ /**
1319
+ * Off (`none`) to or from a level is a start-up option of Claude Code: the switch restarts the CLI, which ends
1320
+ * the background work it runs (a background Bash, an agent, a wakeup), so the bridge defers it while there is
1321
+ * any (claude-agent-bridge.js _thinkingDeferred), and a continuation then would not run on the pick. An
1322
+ * effort-only pick that needs that switch while the session reports background work (routerSession
1323
+ * `pendingWork`) carries on in place, as the turn runs; the correction says so, and that the task, routed again
1324
+ * once the work has reported (its task-notification turn), continues on the pick. -> the correction, or null.
1325
+ */
1326
+ function thinkingWaits(sessionId, target, brain, turn) {
1327
+ if (!target || target.kind !== 'direct') return null;
1328
+ const provider = String(target.provider || brain.provider || '');
1329
+ if (provider !== 'claude-code' || provider !== String(brain.provider || '')) return null;
1330
+ if (String(target.model || brain.model || '') !== String(brain.model || '')) return null;
1331
+ if (!effortDiffers(target, turn) || getSession(sessionId)?.pendingWork !== true) return null;
1332
+ const model = target.model || brain.model || null;
1333
+ const want = runEffort(provider, model, target.effort);
1334
+ const have = runEffort(provider, model, turn.effort ?? null);
1335
+ if ((want === EFFORT_OFF) === (have === EFFORT_OFF)) return null;
1336
+ const off = want === EFFORT_OFF;
1337
+ const asIs = have === EFFORT_OFF ? 'thinking off' : `thinking on${have ? `, ${have}` : ''}`;
1338
+ return {
1339
+ field: 'effort', from: target.effort, to: turn.effort ?? null, reason: 'thinking_waits',
1340
+ text: `${off ? 'thinking off' : `thinking on (${want})`} waits: Claude Code is running background work, and switching thinking ${off ? 'off' : 'on'} restarts it, which would end that work. This carries on here as it runs now (${asIs}); once the background work has reported, route this task again with the same task_key and it continues on ${effortWord(target.effort)}`,
1341
+ };
1342
+ }
1343
+ /** What the brain's running turn is on, from a session snapshot (turnBrain, for a session id). */
1344
+ function turnOf(session, brain = {}) {
1345
+ const turn = session?.turn;
1346
+ return turn && typeof turn === 'object' ? { ...brain, model: turn.model ?? brain.model ?? null, effort: turn.effort ?? null } : brain;
1347
+ }
1348
+ /**
1349
+ * Whether a direct pick queues a continuation now: continuesHere against the running turn (a re-route compares
1350
+ * the model with the turn too), unless its thinking switch waits for background work (thinkingWaits).
1351
+ */
1352
+ function continuesNow(sessionId, target, brain, { reroute = false } = {}) {
1353
+ const turn = turnBrain(sessionId, brain);
1354
+ const base = reroute ? turn : brain;
1355
+ if (!continuesHere(target, base, turn)) return false;
1356
+ return !thinkingWaits(sessionId, target, base, turn);
1357
+ }
1358
+ // The continuation watchdog. A "do it here" pick queues a continuation in the runtime (continueDirect),
1359
+ // which calls continuationStarted(routeId) once the turn reached the brain. Not started after
1360
+ // CONTINUATION_WATCH_MS: it is delivered once more (the runtime takes a delivery of a continuation it
1361
+ // still holds, queued or on its way, or one that already ran, as done: never a second turn), and only
1362
+ // if that one has not started either, CONTINUATION_WATCH_MS later, the brain and the panel are told.
1363
+ // A retry the runtime refuses (the turn is gone, the session is closing) is told at once. Every timer
1364
+ // ends with the start, the session's end or Stop, a newer task, a newer continuation and shutdown.
1365
+ function stopContinuationWatch(entry) {
1366
+ if (entry?.timer != null) continuationTimers.clearTimeout(entry.timer);
1367
+ if (entry) entry.timer = null;
1368
+ }
1369
+ function closeContinuation(entry) { stopContinuationWatch(entry); entry.closed = true; }
1370
+ function continuationStarted(routeId) {
1371
+ const entry = continuations.get(String(routeId || ''));
1372
+ if (!entry) return;
1373
+ stopContinuationWatch(entry);
1374
+ entry.started = true;
1375
+ }
1376
+ /** The runtime took the continuation (queued it, or holds / ran it already): exactly `true`. */
1377
+ // `reroute`: agent_route asked for the task again in the turn running now, so it is delivered in that turn's
1378
+ // generation; the watchdog's retry keeps the generation the continuation was delivered in.
1379
+ const deliverContinuation = (entry, retry, reroute = false) => call('continueDirect', entry.sessionId,
1380
+ retry || reroute ? { ...entry.payload, ...(retry ? { retry: true } : {}), ...(reroute ? { reroute: true } : {}) } : entry.payload) === true;
1381
+ function reportContinuation(entry, reasonCode, text) {
1382
+ entry.reported = true;
1383
+ call('mailbox', entry.sessionId, { kind: 'route_continuation_delayed', route: entry.source, reasonCode, retried: entry.retries > 0, text });
1384
+ call('routeEvent', entry.sessionId, 'continuation_delayed', { ...entry.source, reasonCode, retried: entry.retries > 0, reason: text });
1385
+ }
1386
+ function armContinuationWatch(entry, fire) {
1387
+ stopContinuationWatch(entry);
1388
+ entry.timer = continuationTimers.setTimeout(() => {
1389
+ entry.timer = null;
1390
+ if (entry.started || entry.closed) return;
1391
+ fire();
1392
+ }, CONTINUATION_WATCH_MS);
1393
+ entry.timer?.unref?.();
1394
+ }
1395
+ function watchContinuation(entry) {
1396
+ entry.reported = false;
1397
+ armContinuationWatch(entry, () => {
1398
+ entry.retries += 1;
1399
+ const delivered = deliverContinuation(entry, true);
1400
+ // (The runtime may answer that it already ran, and say so through continuationStarted meanwhile.)
1401
+ if (entry.started || entry.closed) return;
1402
+ if (!delivered) {
1403
+ reportContinuation(entry, 'continuation_undeliverable', `The approved continuation did not start within ${CONTINUATION_WATCH_S} seconds, and SynaBun's retry could not deliver it (its turn is gone, or the session is stopping). Nothing ran. Route again with the same task_key to retry.`);
1404
+ return;
1405
+ }
1406
+ armContinuationWatch(entry, () => reportContinuation(entry, 'continuation_timeout',
1407
+ `The approved continuation has not started after ${CONTINUATION_WATCH_S * 2} seconds, although SynaBun retried its delivery once at ${CONTINUATION_WATCH_S} seconds. It may still be queued behind a running turn; check the task, and route again with the same task_key to retry.`));
1408
+ });
1409
+ }
1410
+ /**
1411
+ * → whether a continuation is queued for this route (continueDirect), so the answer can say continuation:true.
1412
+ * `reroute`: the task's route was approved in an earlier turn and is asked again in the turn running now (a task
1413
+ * notification, a mailbox turn, the user's next words). It is compared with what that turn runs on (turnBrain), not
1414
+ * with the session's brain: a turn already on the approved model carries the task on in place (false). A
1415
+ * continuation still queued and watched is that one (true); one that already ran is consumed (false). Otherwise it
1416
+ * is delivered again, in the generation of the turn running now (the runtime's `reroute`).
1417
+ */
1418
+ function maybeContinuation(sessionId, target, brain, source, { reroute = false } = {}) {
1419
+ if (reroute ? (!target || target.kind !== 'direct') : !continuesNow(sessionId, target, brain)) return false;
1420
+ const routeId = String(source.routeId || '');
1421
+ const previous = continuations.get(routeId);
1422
+ if (previous?.started) return false;
1423
+ // Delivered and still watched: the watchdog retries it; nothing is queued twice.
1424
+ if (previous && !previous.reported && !previous.closed) return true;
1425
+ if (reroute && !continuesNow(sessionId, target, brain, { reroute: true })) return false;
1426
+ // A newer continuation of the session replaces the one the runtime holds (one continuation slot): the older stops being watched.
1427
+ for (const [id, other] of continuations) if (id !== routeId && other.sessionId === sessionId && !other.started && !other.closed) closeContinuation(other);
1428
+ const entry = previous || { routeId, sessionId, taskId: source.taskId ?? getSession(sessionId)?.taskId ?? null, payload: { target, route: source, text: source.summary || '' }, source, started: false, closed: false, reported: false, retries: 0, timer: null };
1429
+ entry.closed = false;
1430
+ continuations.delete(routeId);
1431
+ continuations.set(routeId, entry);
1432
+ while (continuations.size > CONTINUATIONS_KEPT) { const [oldest, old] = continuations.entries().next().value; stopContinuationWatch(old); continuations.delete(oldest); }
1433
+ if (!deliverContinuation(entry, !!previous, reroute)) {
1434
+ closeContinuation(entry);
1435
+ throw routeError('ROUTE_CONTINUATION_FAILED', 'The continuation could not be queued. Route again with the same task_key to retry.', 409);
1436
+ }
1437
+ // (A runtime that already ran it says so at once: consumed.)
1438
+ if (entry.started) return false;
1439
+ watchContinuation(entry);
1237
1440
  return true;
1238
1441
  }
1239
- /** → whether the runtime took the continuation (continueDirect): false for a pick whose turn is gone. */
1240
- function maybeContinuation(sessionId, target, brain, source) {
1241
- if (!continuesHere(target, brain)) return false;
1242
- return call('continueDirect', sessionId, { target, route: source, text: source.summary || '' }) !== false;
1442
+ /**
1443
+ * What the brain's running turn is on: the runtime's `turn` ({ model, effort }: a continuation's model and
1444
+ * effort, which a turn the CLI starts by itself afterwards keeps), else the brain's own. A re-route compares
1445
+ * with this, so a turn already on the approved model and effort carries the task on in place; every pick's
1446
+ * effort is compared with it (continuesHere).
1447
+ */
1448
+ function turnBrain(sessionId, brain = {}) { return turnOf(getSession(sessionId), brain); }
1449
+ /** The session is closing or has ended (routerSession `closing`): a continuation it refuses can never run. */
1450
+ function sessionClosing(sessionId) {
1451
+ const session = getSession(sessionId);
1452
+ return !session || session.closing === true;
1243
1453
  }
1244
1454
 
1245
1455
  function resultFor(status, { routeId, mode, source = null, target = null, card = null, runIds = [], corrections = [], cat = null, brain = {}, brainInfo = null, remembered = false, continuation = false, sessionId = null, switched = null, droppedRuns = [] } = {}) {
@@ -1261,12 +1471,26 @@ export function createAssistantRouter({
1261
1471
  : binding ? `The user's saved route for this task class applies (${binding.to}), not your pick (${binding.from}). `
1262
1472
  : skipped ? `The saved route for this task class (${skipped.from}) is on a disabled model, so your pick stands. `
1263
1473
  : maker ? `Your pick (${maker.from}) cannot make what this task creates, so it runs on ${maker.to}. ` : '';
1474
+ // An effort-only pick whose thinking switch waits for background work (thinkingWaits): said first.
1475
+ const waits = (corrections || []).find((c) => c?.reason === 'thinking_waits');
1476
+ const waitLead = waits && !continuation ? `${waits.text}. ` : '';
1264
1477
  const shares = sessionId && budgeted() ? compactBudget(sessionId) : null;
1478
+ const record = decided.get(routeId) || card;
1479
+ const plannedSplit = record?.plannedSplit || null;
1480
+ const flow = plannedSplit?.flow;
1481
+ const splitNext = status === 'approved' && target?.kind === 'dispatch' && plannedSplit
1482
+ ? flow === 'team'
1483
+ ? `Call agent_team action "plan" with task_class="${record.taskClass}" and these ${plannedSplit.workers} slice titles (${["research", "review"].includes(record.taskClass) ? "read-only: owned_paths []" : "disjoint owned_paths"}), then action "start" with route_id="${routeId}". One approval covers every slice; never route a slice. Wait on its workflow_id, then ${["research", "review"].includes(record.taskClass) ? "synthesize the results; worktrees are cleaned up automatically, no integration or landing" : "verify the integration result"}.`
1484
+ : `Call agent_dispatch with route_id="${routeId}" for one worker. Explain: ${plannedSplit.reason}`
1485
+ : null;
1265
1486
  return {
1266
- ok: true, status, routeId, mode, source, target: described, remembered, continuation,
1267
- corrections, runIds, expiresAt: card?.expiresAt ? new Date(card.expiresAt).toISOString() : null,
1487
+ ...agentFields(record),
1488
+ ok: true, status, routeId, mode, source: source || record?.decidedBy || (status === 'expired' ? 'timeout' : status === 'cancelled' ? 'system' : null), reasonCode: record?.reasonCode || (status === 'expired' ? 'expired' : status === 'cancelled' ? 'cancelled' : null), target: described, remembered, continuation,
1489
+ taskClass: record?.taskClass || null, sessionId: sessionId || record?.sessionId || null, taskId: record?.taskId || null, taskKey: record?.taskKey || '',
1490
+ agentDensity: plannedSplit?.density || normalizeAgentDensity(getSession(sessionId || record?.sessionId)?.agentDensity), expectedWorkers: plannedSplit?.workers || 1, plannedSplit, workflowId: record?.workflowId || null,
1491
+ corrections: record?.agentCorrection ? [...corrections, record.agentCorrection] : corrections, runIds, expiresAt: card?.expiresAt ? new Date(card.expiresAt).toISOString() : null,
1268
1492
  ...(shares ? { budget: shares } : {}),
1269
- next: `${lead}${status === 'approved' ? kindLead : ''}${nextText(status, described, { routeId, label: described?.label })}`,
1493
+ next: `${waitLead}${lead}${status === 'approved' ? kindLead : ''}${splitNext || nextText(record?.reasonCode === 'moved_on' ? 'moved_on' : status, described, { routeId, label: status === 'declined' ? record?.reasonCode : described?.label })}`,
1270
1494
  };
1271
1495
  }
1272
1496
 
@@ -1291,7 +1515,7 @@ export function createAssistantRouter({
1291
1515
  };
1292
1516
  call('routeEvent', sessionId, 'declined', routeView(route, { catalog: cat, brain, brainInfo }));
1293
1517
  return {
1294
- ok: true, status: 'declined', reason: 'no_capable_model', requires: request.needsOutput, ...(needs ? { needs } : {}), routeId, mode, source: 'rule', target: null,
1518
+ ok: true, status: 'declined', reason: 'no_capable_model', reasonCode: 'no_capable_model', requires: request.needsOutput, ...(needs ? { needs } : {}), routeId, mode, source: 'rule', target: null,
1295
1519
  remembered: false, continuation: false, corrections: [], runIds: [], expiresAt: null, next: noMakerText(request),
1296
1520
  };
1297
1521
  }
@@ -1310,7 +1534,7 @@ export function createAssistantRouter({
1310
1534
  if (request.taskClass !== 'computer') return null;
1311
1535
  const option = options.find((o) => o.id === defaultOptionId);
1312
1536
  if (!option || option.disabled || option.kind !== 'direct' || option.provider !== brain.provider) return null;
1313
- if (continuesHere({ kind: 'direct', provider: option.provider, model: option.model, effort: option.effort }, brain)) return null;
1537
+ if (continuesHere({ kind: 'direct', provider: option.provider, model: option.model, effort: option.effort }, brain, turnOf(session, brain))) return null;
1314
1538
  return { optionId: option.id };
1315
1539
  }
1316
1540
 
@@ -1324,6 +1548,7 @@ export function createAssistantRouter({
1324
1548
  const first = request.proposals[0];
1325
1549
  const fallback = origin === 'dispatch' && option.badge !== 'remembered' && option.provider === first?.provider ? first.accountId : null;
1326
1550
  Object.assign(option, accountTarget(option, brain, cat, { check: false, fallback }));
1551
+ Object.assign(option, workerRole(request, option, option.id));
1327
1552
  if (option.accountError) { option.disabled = true; option.disabledReason = option.accountError.message; }
1328
1553
  // A "here" whose account cannot take it (this conversation's is out of usage) runs on a worker
1329
1554
  // on another account: the card names it as a worker and says why, never "Do it here".
@@ -1339,7 +1564,9 @@ export function createAssistantRouter({
1339
1564
  const expiresAt = now() + r.cardTimeoutMinutes * 60_000;
1340
1565
  const pref = r.preferences?.[request.taskClass];
1341
1566
  const card = {
1567
+ ...agentFields(options.find(o => o.id === (defaults.dispatch || defaultOptionId))),
1342
1568
  routeId, requestId, sessionId, origin, status: 'pending', mode, workflowId,
1569
+ plannedSplit: request.plannedSplit || null, taskId: request.taskId, taskKey: request.taskKey || '',
1343
1570
  taskClass: request.taskClass, summary: request.summary, confidence: request.confidence, needsVision: request.needsVision,
1344
1571
  needsOutput: request.needsOutput || null, dispatchOnly: request.dispatchOnly === true, visionOnly: request.visionOnly === true,
1345
1572
  reasons: evaluation.reasons, request, options, defaultOptionId, sides, defaults, runIds: new Set(runIds), waiters: new Set(),
@@ -1354,6 +1581,7 @@ export function createAssistantRouter({
1354
1581
  request: {
1355
1582
  subtype: 'route', kind: 'route', provider: 'synabun', routeId, origin, runIds: [...card.runIds], workflowId, sessionId, mode,
1356
1583
  reasons: evaluation.reasons, taskClass: request.taskClass, taskClassLabel: request.taskClassLabel, summary: request.summary,
1584
+ plannedSplit: request.plannedSplit || null, taskId: request.taskId || null, taskKey: request.taskKey || '',
1357
1585
  confidence: request.confidence, needsVision: request.needsVision,
1358
1586
  // Image / video creation: the medium the model must generate, and no "here" (always a worker).
1359
1587
  requires: request.needsOutput || null, dispatchOnly: request.dispatchOnly === true,
@@ -1401,7 +1629,7 @@ export function createAssistantRouter({
1401
1629
  byRequest.delete(card.requestId);
1402
1630
  cards.delete(card.routeId);
1403
1631
  // Why it closed, for a producer that attaches a run a moment too late (bounded).
1404
- lastClosed.set(card.routeId, { routeId: card.routeId, settled: card.settled || null });
1632
+ lastClosed.set(card.routeId, { routeId: card.routeId, requestId: card.requestId, sessionId: card.sessionId, taskId: card.taskId, taskKey: card.taskKey, mode: card.mode, decidedBy: card.decidedBy, reasonCode: card.reasonCode, settled: card.settled || null });
1405
1633
  while (lastClosed.size > 50) lastClosed.delete(lastClosed.keys().next().value);
1406
1634
  }
1407
1635
 
@@ -1412,15 +1640,18 @@ export function createAssistantRouter({
1412
1640
  const card = cards.get(routeId);
1413
1641
  if (!card || card.status !== 'pending') return;
1414
1642
  card.status = reason === 'expired' || reason === 'superseded' ? 'expired' : 'cancelled';
1643
+ card.decidedBy = reason === 'expired' ? 'timeout' : 'system';
1644
+ card.reasonCode = movedOn ? 'moved_on' : reason;
1415
1645
  const status = card.status;
1416
1646
  for (const runId of card.runIds) call('declineHeld', runId, reason === 'expired' ? 'route_expired' : `route_${reason}`);
1417
1647
  call('cancelCard', card.sessionId, card.requestId, reason);
1418
- const view = routeView({ ...card, status, decidedBy: reason === 'expired' ? 'timeout' : null }, { catalog: catalog.peek?.(), brain: card.brain });
1648
+ const view = routeView({ ...card, status, decidedBy: card.decidedBy }, { catalog: catalog.peek?.(), brain: card.brain });
1419
1649
  call('routeEvent', card.sessionId, status === 'expired' ? 'expired' : 'cancelled', view);
1420
1650
  if ((card.mailboxOnDecision || card.runIds.size) && reason !== 'session_closed' && reason !== 'aborted' && reason !== 'superseded') {
1421
1651
  call('mailbox', card.sessionId, { kind: 'route_expired', route: view, runIds: [...card.runIds], text: `Route card for "${card.summary || card.taskClass}" ${status === 'expired' ? 'expired without an answer' : `was cancelled (${reason})`}.` });
1422
1652
  }
1423
1653
  settle(card, { status, routeId, ...(movedOn ? { movedOn: true } : {}) });
1654
+ if (card.taskId) decided.set(routeId, { ...view, sessionId: card.sessionId, expiresAt: now() + DECIDED_TTL_MS });
1424
1655
  closeCard(card);
1425
1656
  }
1426
1657
 
@@ -1443,13 +1674,17 @@ export function createAssistantRouter({
1443
1674
  */
1444
1675
  async function propose(args = {}) {
1445
1676
  const origin = args.origin || 'agent_route';
1677
+ const taskId = getSession(args.sessionId)?.taskId || null;
1446
1678
  try {
1447
1679
  const result = await proposeRoute(args);
1448
1680
  // The class rides along: a "chat" route must not unlock the gate.
1449
- if (origin === 'agent_route') call('routed', args.sessionId, result, { taskClass: normalizeRouteRequest(args.body || {}).taskClass });
1681
+ if (origin === 'agent_route') call('routed', args.sessionId, result, { taskClass: result.taskClass || normalizeRouteRequest(args.body || {}).taskClass });
1450
1682
  return result;
1451
1683
  } catch (error) {
1452
- if (origin === 'agent_route') call('routeFailed', args.sessionId, error);
1684
+ if (origin === 'agent_route' && (!taskId || getSession(args.sessionId)?.taskId === taskId)) {
1685
+ if (/^ROUTE_(SPLIT_|PROJECT_|TASK_)/.test(error?.code || '')) call('routed', args.sessionId, { status: 'plan_required', taskId, next: error.message }, { taskClass: normalizeRouteRequest(args.body || {}).taskClass });
1686
+ else call('routeFailed', args.sessionId, error);
1687
+ }
1453
1688
  throw error;
1454
1689
  }
1455
1690
  }
@@ -1462,18 +1697,85 @@ export function createAssistantRouter({
1462
1697
  next: `The user has not answered your questions yet (brief ${waiting.briefId}${what}). End your turn now with one short line and route this after the answers arrive (a [SynaBun Mailbox] clarify_answered event, or the user's next message). If this task does not depend on them, call agent_route again with independent:true.`,
1463
1698
  };
1464
1699
  }
1700
+ function taskIdentity(sessionId, session, body = {}) {
1701
+ const taskKey = body.task_key ?? body.taskKey ?? '';
1702
+ if (typeof taskKey !== 'string' || taskKey.length > 100 || /[\x00-\x1f]/.test(taskKey)) throw routeError('ROUTE_TASK_KEY_INVALID', 'task_key must be at most 100 characters of text.', 400);
1703
+ return { sessionId, taskId: session.taskId || null, taskKey: taskKey.trim() };
1704
+ }
1705
+ function assertCurrentTask(sessionId, taskId) {
1706
+ if (taskId && getSession(sessionId)?.taskId !== taskId) throw routeError('ROUTE_TASK_CHANGED', 'This request has moved on to another task; route the current task.', 409);
1707
+ }
1708
+ /**
1709
+ * The task already has a route (same task id and task_key). `deliver` (agent_route only; a dispatch looking
1710
+ * the route up asks the runtime for nothing): an approved "do it here" route goes through maybeContinuation
1711
+ * as a re-route, so an answer that says continuation:true always has one queued and watched. A turn already
1712
+ * on the approved model (the continuation itself, or a turn the CLI started after it) carries the task on in
1713
+ * place, and a continuation that already ran is consumed: continuation:false, and the gate opens. A refusal
1714
+ * from a session that is closing answers expired (nothing can run there); any other refusal is
1715
+ * ROUTE_CONTINUATION_FAILED, which says to route again.
1716
+ */
1717
+ function existingTaskResult(request, sessionId, context, { deliver = false } = {}) {
1718
+ const key = routeTaskIdentity(request);
1719
+ if (!key) return null;
1720
+ const card = [...cards.values()].find(c => routeTaskIdentity(c) === key);
1721
+ const prior = card || [...decided.values()].find(c => routeTaskIdentity(c) === key);
1722
+ if (!prior) return null;
1723
+ assertCurrentTask(sessionId, request.taskId);
1724
+ let continuation = false;
1725
+ // A thinking switch that waited is decided again now (the background work may have reported since).
1726
+ let corrections = (prior.corrections || []).filter((c) => c?.reason !== 'thinking_waits');
1727
+ if (prior.status === 'approved' && prior.target) {
1728
+ if (!deliver) continuation = continuesNow(sessionId, prior.target, context.brain, { reroute: true });
1729
+ else {
1730
+ try { continuation = maybeContinuation(sessionId, prior.target, context.brain, prior, { reroute: true }); } catch (error) {
1731
+ if (error?.code !== 'ROUTE_CONTINUATION_FAILED' || !sessionClosing(sessionId)) throw error;
1732
+ // The session is closing or gone: nothing runs, so nothing is promised.
1733
+ log('router:reroute-refused', `${prior.routeId}: the continuation of a re-routed task could not be queued (the session is closing)`);
1734
+ return { ...resultFor('expired', { routeId: prior.routeId, mode: prior.mode, cat: context.cat, brain: context.brain, brainInfo: context.brainInfo, sessionId }), reason: 'superseded' };
1735
+ }
1736
+ }
1737
+ }
1738
+ if (prior.status === 'approved' && prior.target && !continuation) {
1739
+ const waits = thinkingWaits(sessionId, prior.target, turnBrain(sessionId, context.brain), turnBrain(sessionId, context.brain));
1740
+ if (waits) corrections = [...corrections, waits];
1741
+ }
1742
+ return resultFor(prior.status, { routeId: prior.routeId, mode: prior.mode, card, source: prior.decidedBy,
1743
+ target: prior.target, corrections, remembered: prior.remembered,
1744
+ continuation, sessionId, ...context });
1745
+ }
1746
+ // New human requests retire the previous request's pending cards, across every subtask.
1747
+ function expireOtherTasks(sessionId, taskId) {
1748
+ for (const card of [...cards.values()]) if (card.sessionId === sessionId && card.taskId && card.taskId !== taskId) expire(card.routeId, 'superseded', { movedOn: true });
1749
+ // An earlier task's continuation is not watched any more (the runtime dropped it with its generation).
1750
+ for (const entry of continuations.values()) if (entry.sessionId === sessionId && !entry.started && entry.taskId && entry.taskId !== taskId) closeContinuation(entry);
1751
+ }
1465
1752
  async function proposeRoute({ sessionId, body = {}, origin = 'agent_route', waitMs = null, signal = null } = {}) {
1466
1753
  pruneDecided();
1467
1754
  const session = requireSession(sessionId);
1468
1755
  const waiting = origin === 'agent_route' ? clarifier?.blocking?.(sessionId, { independent: body.independent === true }) : null;
1469
1756
  if (waiting) return clarifyingResult(sessionId, waiting);
1470
1757
  const brain = session.brain || {};
1758
+ expireOtherTasks(sessionId, session.latestTaskId || session.taskId);
1471
1759
  const cat = await catalogValue();
1472
1760
  const brainInfo = brainInfoFor(brain);
1473
1761
  const request = normalizeRouteRequest(body, { brain });
1762
+ Object.assign(request, taskIdentity(sessionId, session, body));
1763
+ // The same task routed again (a later turn: a task notification, a mailbox event, the user's next words).
1764
+ const existing = existingTaskResult(request, sessionId, { cat, brain, brainInfo }, { deliver: origin === 'agent_route' });
1765
+ if (existing) return existing;
1766
+ request.plannedSplit = await planRouteSplit(body, session, request.taskClass);
1767
+ request.projectPath = request.plannedSplit?.projectPath || null;
1768
+ request.roles = workerRoles(request, body.cwd || body.project);
1769
+ if (request.plannedSplit) {
1770
+ request.dispatchOnly = true;
1771
+ request.proposals = request.proposals.map(p => ({ ...p, kind: 'dispatch' }));
1772
+ }
1474
1773
  const mode = modeFor(sessionId);
1475
1774
  const r = routing();
1476
1775
  const evaluation = await evaluateWithBudget(sessionId, { mode, routing: r, request, brain, brainInfo, catalog: cat });
1776
+ const raced = existingTaskResult(request, sessionId, { cat, brain, brainInfo }, { deliver: origin === 'agent_route' });
1777
+ if (raced) return raced;
1778
+ assertCurrentTask(sessionId, request.taskId);
1477
1779
  if (evaluation.unavailable === 'budget_exhausted') return budgetDeclinedResult({ sessionId, request, mode, cat, brain, brainInfo, evaluation });
1478
1780
  if (evaluation.unavailable) return unavailableResult({ sessionId, request, mode, cat, brain, brainInfo });
1479
1781
  if (!evaluation.ask) {
@@ -1481,21 +1783,26 @@ export function createAssistantRouter({
1481
1783
  let target = evaluation.auto;
1482
1784
  const checked = accountTarget(target, brain, cat, { check: false, select: request.taskClass !== 'chat' });
1483
1785
  if (checked.accountError) {
1484
- const failed = { routeId, sessionId, taskClass: request.taskClass, summary: request.summary, target: checked, status: 'declined', reason: checked.accountError.message, reasonCode: checked.accountError.code, mode };
1786
+ const failed = { routeId, sessionId, taskClass: request.taskClass, summary: request.summary, target: checked, status: 'declined', decidedBy: 'account', reason: checked.accountError.message, reasonCode: checked.accountError.code, mode };
1485
1787
  call('routeEvent', sessionId, 'declined', routeView(failed, { catalog: cat, brain, brainInfo }));
1486
- return { ok: false, status: 'declined', routeId, mode, code: checked.accountError.code, target: describeTarget(checked, { catalog: cat, brain }), next: checked.accountError.message };
1788
+ return { ok: false, status: 'declined', routeId, mode, source: 'account', reasonCode: checked.accountError.code, code: checked.accountError.code, target: describeTarget(checked, { catalog: cat, brain }), next: checked.accountError.message };
1487
1789
  }
1488
1790
  target = checked;
1489
1791
  const decidedBy = evaluation.source === 'remembered' ? 'remembered' : evaluation.source === 'budget' ? 'budget' : 'brain';
1792
+ // Off to or from a level that waits for Claude Code's background work: in place, and the answer says so.
1793
+ const waits = origin === 'agent_route' && request.taskClass !== 'chat' ? thinkingWaits(sessionId, target, brain, turnBrain(sessionId, brain)) : null;
1490
1794
  const route = {
1795
+ taskId: request.taskId, taskKey: request.taskKey || '', plannedSplit: request.plannedSplit || null, workflowId: null,
1491
1796
  routeId, status: 'approved', sessionId, taskClass: request.taskClass, summary: request.summary, confidence: request.confidence,
1492
- target, decidedBy, remembered: evaluation.source === 'remembered', corrections: accountCorrections(target, evaluation.corrections), mode,
1797
+ ...workerRole(request, target),
1798
+ target, decidedBy, remembered: evaluation.source === 'remembered', corrections: [...accountCorrections(target, evaluation.corrections), ...(waits ? [waits] : [])], mode,
1493
1799
  reason: request.proposals[0]?.reason || null, runIds: [], expiresAt: now() + DECIDED_TTL_MS,
1494
1800
  };
1495
1801
  decided.set(routeId, route);
1496
1802
  noteBudgetTask(sessionId, request, target);
1497
1803
  if (request.taskClass !== 'chat') call('routeEvent', sessionId, 'auto', routeView(route, { catalog: cat, brain, brainInfo }));
1498
- const continuation = origin === 'agent_route' ? maybeContinuation(sessionId, target, brain, route) : false;
1804
+ // A chat route is the brain's own turn: it never continues (its effort is the session's).
1805
+ const continuation = origin === 'agent_route' && request.taskClass !== 'chat' ? maybeContinuation(sessionId, target, brain, route) : false;
1499
1806
  return resultFor('approved', { routeId, mode, source: evaluation.source, target, corrections: route.corrections, cat, brain, brainInfo, remembered: route.remembered, continuation, sessionId });
1500
1807
  }
1501
1808
  // The session as it is now (the catalog was awaited since): its computer-use answer decides what the card says.
@@ -1540,6 +1847,8 @@ export function createAssistantRouter({
1540
1847
  * the answer came in on; a card of another session is refused (ROUTE_NOT_FOUND).
1541
1848
  */
1542
1849
  async function answer(idOrRequestId, response = {}, { origin = 'ui', sessionId = null, authority = null } = {}) {
1850
+ const closed = closedRoute(idOrRequestId, sessionId);
1851
+ if (closed) return { ...resultFor(closed.settled.status, { routeId: closed.routeId, mode: closed.mode, card: closed, sessionId: closed.sessionId }), ...(closed.settled.movedOn ? { reason: 'superseded' } : {}) };
1543
1852
  const card = openCard(idOrRequestId, { sessionId });
1544
1853
  const routeId = card.routeId;
1545
1854
  const cat = await catalogValue();
@@ -1548,22 +1857,27 @@ export function createAssistantRouter({
1548
1857
  // decided: an answer in progress never undoes a cancellation or decides a card twice.
1549
1858
  if (cards.get(routeId) !== card || card.status !== 'pending') openCard(routeId, { sessionId });
1550
1859
  const session = getSession(card.sessionId) || { brain: card.brain };
1860
+ if (card.taskId && session.taskId !== card.taskId) { expire(routeId, 'superseded', { movedOn: true }); throw routeError('ROUTE_TASK_CHANGED', 'This card belongs to an earlier task.', 409); }
1551
1861
  const brain = session.brain || card.brain || {};
1552
1862
  const brainInfo = brainInfoFor(brain);
1553
1863
  const parsed = targetFromAnswer({ card, response, catalog: cat, brain });
1554
1864
  if (parsed.declined) {
1555
1865
  card.status = 'declined';
1866
+ card.decidedBy = 'user';
1867
+ card.reasonCode = response.reason === 'dismissed' ? 'dismissed' : 'cancelled';
1556
1868
  for (const runId of card.runIds) call('declineHeld', runId, 'route_declined');
1557
1869
  const view = routeView({ ...card, status: 'declined', decidedBy: 'user' }, { catalog: cat, brain, brainInfo });
1558
1870
  call('routeEvent', card.sessionId, 'declined', view);
1559
1871
  const result = resultFor('declined', { routeId, mode: card.mode, card, cat, brain, brainInfo, runIds: [...card.runIds] });
1560
- if (card.mailboxOnDecision && !card.waiters.size) call('mailbox', card.sessionId, { kind: 'route_declined', route: view, runIds: [...card.runIds], text: `The user declined the route for "${card.summary || card.taskClass}".` });
1872
+ if (card.mailboxOnDecision && !card.waiters.size) call('mailbox', card.sessionId, { kind: 'route_declined', route: view, runIds: [...card.runIds], text: result.next });
1873
+ if (card.taskId) decided.set(routeId, { ...view, sessionId: card.sessionId, expiresAt: now() + DECIDED_TTL_MS });
1561
1874
  settle(card, { status: 'declined', result });
1562
1875
  closeCard(card);
1563
1876
  return result;
1564
1877
  }
1565
1878
  const { optionId, remember } = parsed;
1566
1879
  const target = checkedTarget(parsed.target, brain, cat, null, null, card.mode === 'always-ask');
1880
+ const pickedRole = workerRole(card.request, target, optionId);
1567
1881
  const corrections = accountCorrections(target, parsed.corrections || []);
1568
1882
  // The session budget must be able to pay for the pick: a provider with no share left divides the
1569
1883
  // unspent budget again first; still none, and the card stays open with the reason.
@@ -1584,7 +1898,7 @@ export function createAssistantRouter({
1584
1898
  // or reported started: the card stays open with the reason. A "here" pick starts none.
1585
1899
  if (!keptHere) {
1586
1900
  for (const runId of card.runIds) {
1587
- const refusal = call('checkHeld', runId, target);
1901
+ const refusal = call('checkHeld', runId, target, pickedRole);
1588
1902
  if (refusal) throw routeError(refusal.code || 'ROUTE_INVALID', refusal.message || 'The held run cannot start on that model.', Number(refusal.status) || 400);
1589
1903
  }
1590
1904
  }
@@ -1592,11 +1906,21 @@ export function createAssistantRouter({
1592
1906
  // handed over first. The runtime refuses a pick that turn no longer owns (a
1593
1907
  // newer prompt, a Stop or the session closing came after it): then nothing is
1594
1908
  // approved or remembered, and the card expires on every host.
1595
- const continuation = (keptHere || !card.runIds.size) && continuesHere(target, brain);
1909
+ // An effort-only pick continues too: another effort than the brain's running turn is on (continuesNow), unless
1910
+ // its thinking switch waits for Claude Code's background work, which the answer then says (thinkingWaits).
1911
+ const here = keptHere || !card.runIds.size;
1912
+ const continuation = here && continuesNow(card.sessionId, target, brain);
1913
+ const waits = here && !continuation ? thinkingWaits(card.sessionId, target, brain, turnBrain(card.sessionId, brain)) : null;
1914
+ if (waits) corrections.push(waits);
1596
1915
  // The decision is claimed here, before the first side effect (the runtime's continuation, the
1597
1916
  // held runs, the mailbox): nothing a sink does can close or decide this card again meanwhile.
1598
1917
  card.status = 'approved';
1599
- if (continuation && !maybeContinuation(card.sessionId, target, brain, { routeId, summary: card.summary, taskClass: card.taskClass, target, decidedBy: 'user', optionId })) {
1918
+ let queued = !continuation;
1919
+ if (continuation) {
1920
+ try { queued = maybeContinuation(card.sessionId, target, brain, { routeId, summary: card.summary, taskClass: card.taskClass, target, decidedBy: 'user', optionId }); }
1921
+ catch { queued = false; }
1922
+ }
1923
+ if (!queued) {
1600
1924
  card.status = 'pending';
1601
1925
  expire(routeId, 'superseded');
1602
1926
  log('router:superseded', `${routeId}: a "do it here" pick after its turn was replaced; nothing approved`);
@@ -1613,7 +1937,9 @@ export function createAssistantRouter({
1613
1937
  const heldRuns = keptHere ? [] : [...card.runIds];
1614
1938
  const droppedRuns = keptHere ? [...card.runIds] : [];
1615
1939
  const route = {
1940
+ taskId: card.taskId, taskKey: card.taskKey || '', plannedSplit: card.plannedSplit || null, workflowId: null,
1616
1941
  routeId, status: 'approved', sessionId: card.sessionId, taskClass: card.taskClass, summary: card.summary, confidence: card.confidence,
1942
+ ...pickedRole,
1617
1943
  target, decidedBy: 'user', remembered, optionId, corrections, mode: card.mode, runIds: heldRuns,
1618
1944
  reason: card.options.find((o) => o.id === optionId)?.reason || null, alternatives: card.alternatives, expiresAt: now() + DECIDED_TTL_MS,
1619
1945
  };
@@ -1622,7 +1948,7 @@ export function createAssistantRouter({
1622
1948
  // A remote session: the held run this card was for is its one dispatch.
1623
1949
  if (heldRuns.length && session.remote === true) route.consumed = true;
1624
1950
  for (const runId of droppedRuns) call('declineHeld', runId, 'route_here');
1625
- for (const runId of heldRuns) call('startHeld', runId, target, { routeId, decidedBy: 'user', remembered, optionId });
1951
+ for (const runId of heldRuns) call('startHeld', runId, target, { routeId, decidedBy: 'user', remembered, optionId, agentRequest: route.agentRequest });
1626
1952
  const view = routeView(route, { catalog: cat, brain, brainInfo });
1627
1953
  call('routeEvent', card.sessionId, 'decided', view);
1628
1954
  const inTurnWaiter = card.waiters.size > 0;
@@ -1663,7 +1989,7 @@ export function createAssistantRouter({
1663
1989
  * dispatcher refuses first gives it back: releaseRoute), a card holds one run,
1664
1990
  * and a workflow does not fan out under one card. The desktop keeps both.
1665
1991
  */
1666
- async function resolveDispatch({ sessionId, spec = {}, origin = 'assistant' } = {}) {
1992
+ async function resolveDispatch({ sessionId, spec = {}, origin = 'assistant', team = null } = {}) {
1667
1993
  pruneDecided();
1668
1994
  if (origin === 'ui' || !sessionId) return { action: 'start', spec, route: null };
1669
1995
  const session = getSession(sessionId);
@@ -1677,13 +2003,17 @@ export function createAssistantRouter({
1677
2003
  const remote = session.remote === true;
1678
2004
  if (routeId) {
1679
2005
  const approved = decided.get(routeId);
2006
+ const bound = approved || cards.get(routeId);
2007
+ if (bound?.sessionId === sessionId && !team) assertCurrentTask(sessionId, bound.taskId);
2008
+ if (bound?.taskId && ['expired', 'cancelled'].includes(bound.status)) throw routeClosedError(lastClosed.get(routeId) || bound);
2009
+ if (bound?.taskId && (bound.status !== 'approved' && bound.status !== 'pending' || bound.consumed)) throw routeError('ROUTE_NOT_APPROVED', 'This task route is closed or already used.', 409);
1680
2010
  // The user picked "here" on this route's card: it runs in this conversation, never on a worker
1681
2011
  // (a brain's own direct route, or a saved one in Never ask, keeps its old dispatch behaviour).
1682
2012
  if (approved && approved.sessionId === sessionId && approved.target?.kind === 'direct' && approved.decidedBy === 'user') {
1683
2013
  const where = approved.target.model ? ` on ${approved.target.model}` : '';
1684
2014
  throw routeError('ROUTE_IS_DIRECT', `Route ${routeId} was decided by the user to run here, in this conversation${where}, not on a worker. Do the task yourself now; do not dispatch it. If it should go to a worker after all, ask the user, then call agent_route again.`, 409, { routeId, target: approved.target });
1685
2015
  }
1686
- if (approved && approved.sessionId === sessionId && approved.target && !approved.consumed) {
2016
+ if (approved && approved.sessionId === sessionId && approved.target && (approved.plannedSplit || !approved.consumed)) {
1687
2017
  // A remote session's route is claimed here, so a second dispatch cannot take it meanwhile.
1688
2018
  // `claimed` tells the dispatcher to give it back (releaseRoute) if it refuses the launch
1689
2019
  // before a run exists: only the run it starts uses the route up.
@@ -1708,22 +2038,31 @@ export function createAssistantRouter({
1708
2038
  }
1709
2039
  if (moved.correction) { runTarget = moved.target; budgetCorrection = moved.correction; }
1710
2040
  }
1711
- if (remote) approved.consumed = true;
2041
+ const claim = approved.plannedSplit ? claimSplit(approved, spec, team) : null;
2042
+ if (remote && !approved.plannedSplit) approved.consumed = true;
1712
2043
  const applied = { ...spec, provider: runTarget.provider, model: runTarget.model || null, effort: runTarget.effort ?? null, accountId: runTarget.accountId || null, codexAccountId: null, claudeAccountId: null };
1713
2044
  const meta = routeMeta(approved, cat, brain, brainInfo);
1714
2045
  const route = budgetCorrection ? { ...meta, target: describeTarget(runTarget, { catalog: cat, brain, brainInfo }), corrections: [...(meta.corrections || []), budgetCorrection] } : meta;
1715
- return { action: 'start', spec: applied, route: { ...route, requested: { provider: spec.provider || null, model: spec.model || null, effort: spec.effort || null } }, ...(remote ? { claimed: true } : {}) };
2046
+ return { action: 'start', spec: applied, route: { ...route, requested: { provider: spec.provider || null, model: spec.model || null, effort: spec.effort || null } }, ...(claim ? { claimed: true, claim } : remote ? { claimed: true } : {}) };
1716
2047
  }
1717
2048
  const pending = cards.get(routeId);
2049
+ if (pending?.plannedSplit && pending.sessionId === sessionId) throw routeError('ROUTE_NOT_APPROVED', 'Wait for the whole task approval; do not dispatch or route individual workers.', 409, { routeId });
1718
2050
  if (pending && pending.sessionId === sessionId && pending.status === 'pending' && !(remote && pending.runIds.size)) {
1719
2051
  return { action: 'hold', routeId, spec, route: pendingMeta(pending) };
1720
2052
  }
1721
2053
  }
2054
+ if (team || spec.workerIndex != null) throw routeError('ROUTE_NOT_APPROVED', 'This split requires its approved route_id; do not route individual workers.', 409);
1722
2055
  const request = normalizeRouteRequest({
1723
2056
  task_class: spec.taskClass || 'code', confidence: spec.confidence ?? null, summary: spec.title || clip(spec.task, 200),
1724
2057
  needs_vision: !!spec.usesComputer,
1725
2058
  proposals: [{ kind: 'dispatch', provider: spec.provider || brain.provider, model: spec.model || null, effort: spec.effort || null, accountId: spec.accountId || spec.codexAccountId || spec.claudeAccountId || null }],
1726
2059
  }, { brain });
2060
+ Object.assign(request, taskIdentity(sessionId, session, spec));
2061
+ expireOtherTasks(sessionId, session.latestTaskId || request.taskId);
2062
+ const prior = existingTaskResult(request, sessionId, { cat, brain, brainInfo });
2063
+ if (prior && prior.routeId !== routeId) return resolveDispatch({ sessionId, spec: { ...spec, routeId: prior.routeId }, origin, team });
2064
+ request.proposals[0].agentRequest = agentRefOf(spec);
2065
+ request.roles = workerRoles(request, spec.cwd || spec.project, agentPinOf(spec));
1727
2066
  if (!spec.provider) request.proposals[0].provider = brain.provider || 'claude-code';
1728
2067
  const evaluation = await evaluateWithBudget(sessionId, { mode, routing: r, request, brain, brainInfo, catalog: cat });
1729
2068
  if (evaluation.unavailable === 'budget_exhausted') {
@@ -1731,17 +2070,26 @@ export function createAssistantRouter({
1731
2070
  }
1732
2071
  if (evaluation.unavailable) throw routeError('NO_CAPABLE_MODEL', noMakerText(request), 409, { requires: request.needsOutput, ...(request.needsOutput ? {} : { needs: 'vision' }), taskClass: request.taskClass });
1733
2072
  if (!evaluation.ask) {
2073
+ assertCurrentTask(sessionId, request.taskId);
2074
+ const raced = existingTaskResult(request, sessionId, { cat, brain, brainInfo });
2075
+ if (raced) return resolveDispatch({ sessionId, spec: { ...spec, routeId: raced.routeId }, origin, team });
1734
2076
  const t = checkedTarget(evaluation.auto, brain, cat);
1735
2077
  noteBudgetTask(sessionId, request, t);
1736
- const applied = { ...spec, provider: t.provider, model: t.model || null, effort: t.effort || spec.effort || null, ...(t.accountId ? { accountId: t.accountId, codexAccountId: null, claudeAccountId: null } : {}) };
2078
+ const applied = { ...spec, provider: t.provider, model: t.model || null, effort: t.effort ?? null, accountId: t.accountId || null, codexAccountId: null, claudeAccountId: null };
1737
2079
  const route = {
2080
+ ...workerRole(request, { ...t, kind: 'dispatch' }),
1738
2081
  routeId: `route-${randomId()}`, status: 'auto', decidedBy: evaluation.source === 'remembered' ? 'remembered' : evaluation.source === 'budget' ? 'budget' : 'brain', mode,
1739
2082
  taskClass: request.taskClass, confidence: request.confidence, target: t, corrections: accountCorrections(t, evaluation.corrections),
1740
2083
  remembered: evaluation.source === 'remembered',
1741
2084
  };
2085
+ Object.assign(route, taskIdentity(sessionId, session, spec), { summary: request.summary, expiresAt: now() + DECIDED_TTL_MS });
2086
+ if (route.taskId) decided.set(route.routeId, { ...route, status: 'approved', consumed: remote });
1742
2087
  return { action: 'start', spec: applied, route: { ...routeMeta(route, cat, brain, brainInfo), requested: { provider: spec.provider || null, model: spec.model || null, effort: spec.effort || null } } };
1743
2088
  }
1744
- let card = spec.workflowId && !remote ? [...cards.values()].find((c) => c.sessionId === sessionId && c.status === 'pending' && c.workflowId && c.workflowId === spec.workflowId) : null;
2089
+ assertCurrentTask(sessionId, request.taskId);
2090
+ const raced = existingTaskResult(request, sessionId, { cat, brain, brainInfo });
2091
+ if (raced && raced.routeId !== routeId) return resolveDispatch({ sessionId, spec: { ...spec, routeId: raced.routeId }, origin, team });
2092
+ let card = request.taskId ? [...cards.values()].find(c => routeTaskIdentity(c) === routeTaskIdentity(request)) : spec.workflowId && !remote ? [...cards.values()].find((c) => c.sessionId === sessionId && c.status === 'pending' && c.taskId === request.taskId && c.workflowId && c.workflowId === spec.workflowId) : null;
1745
2093
  if (!card) {
1746
2094
  card = createCard({ sessionId, request, evaluation, brain, brainInfo, cat, mode, origin: 'dispatch', workflowId: spec.workflowId || null });
1747
2095
  call('sendCard', sessionId, card.packet);
@@ -1754,7 +2102,9 @@ export function createAssistantRouter({
1754
2102
 
1755
2103
  function routeMeta(route, cat, brain, brainInfo) {
1756
2104
  return {
2105
+ ...agentFields(route),
1757
2106
  routeId: route.routeId, status: route.status === 'approved' ? 'approved' : route.status, decidedBy: route.decidedBy || null, mode: route.mode || null,
2107
+ plannedSplit: route.plannedSplit || null, taskId: route.taskId || null, taskKey: route.taskKey || '', sessionId: route.sessionId || null,
1758
2108
  taskClass: route.taskClass || null, taskClassLabel: TASK_CLASS_META[route.taskClass]?.label || null, confidence: route.confidence ?? null,
1759
2109
  target: route.target ? describeTarget(route.target, { catalog: cat, brain, brainInfo }) : null,
1760
2110
  corrections: route.corrections || [], remembered: !!route.remembered, decidedAt: new Date(now()).toISOString(),
@@ -1762,7 +2112,8 @@ export function createAssistantRouter({
1762
2112
  }
1763
2113
  function pendingMeta(card) {
1764
2114
  return {
1765
- routeId: card.routeId, status: 'pending', decidedBy: null, mode: card.mode, taskClass: card.taskClass,
2115
+ ...agentFields(card),
2116
+ routeId: card.routeId, taskId: card.taskId || null, taskKey: card.taskKey || '', sessionId: card.sessionId || null, status: 'pending', decidedBy: null, mode: card.mode, taskClass: card.taskClass,
1766
2117
  taskClassLabel: TASK_CLASS_META[card.taskClass]?.label || null, confidence: card.confidence ?? null,
1767
2118
  target: null, corrections: [], remembered: false, decidedAt: null,
1768
2119
  };
@@ -1774,8 +2125,33 @@ export function createAssistantRouter({
1774
2125
  * the route_id gets the route again, so it runs or is refused for the same reason, and never
1775
2126
  * falls through to a fresh route of another class.
1776
2127
  */
1777
- function releaseRoute(routeId) {
2128
+ function claimSplit(route, spec, team) {
2129
+ const split = route.plannedSplit;
2130
+ const mismatch = (text) => { throw routeError('ROUTE_SPLIT_MISMATCH', text, 409, { routeId: route.routeId }); };
2131
+ if (spec.taskClass && spec.taskClass !== route.taskClass) mismatch('Dispatch task_class must match the approved split.');
2132
+ let slot = 1;
2133
+ if (split.flow === 'team') {
2134
+ if (!team?.teamId || !team?.sliceId || spec.workflowId !== `team:${team.teamId}`) mismatch('This route requires agent_team plan → start, not individual dispatches.');
2135
+ if (route.workflowId && route.workflowId !== spec.workflowId) mismatch('This route already belongs to another team.');
2136
+ slot = team.sliceId;
2137
+ } else if (team) mismatch('This task was approved for one worker, not a team.');
2138
+ route.claims ||= new Map();
2139
+ if (route.claims.has(slot) && !team) mismatch('This worker already started. Use agent_send for follow-ups; do not route or dispatch it again.');
2140
+ if (!route.claims.has(slot) && route.claims.size >= split.workers) mismatch('All approved worker slots are assigned.');
2141
+ if (!team && [...route.claims.values()].some(c => c.task === spec.task)) mismatch('Every parallel worker needs a distinct task.');
2142
+ const token = randomBytes(12).toString('hex');
2143
+ const previous = route.claims.get(slot);
2144
+ route.claims.set(slot, { token, task: spec.task });
2145
+ if (team) route.workflowId = spec.workflowId;
2146
+ return { slot, token, previous };
2147
+ }
2148
+
2149
+ function releaseRoute(routeId, claim = null) {
1778
2150
  const route = decided.get(String(routeId || ''));
2151
+ if (claim && route?.claims?.get(claim.slot)?.token === claim.token) {
2152
+ if (claim.previous) route.claims.set(claim.slot, claim.previous); else route.claims.delete(claim.slot);
2153
+ return true;
2154
+ }
1779
2155
  if (!route?.consumed) return false;
1780
2156
  route.consumed = false;
1781
2157
  return true;
@@ -1812,6 +2188,8 @@ export function createAssistantRouter({
1812
2188
  return true;
1813
2189
  }
1814
2190
  function cancelForSession(sessionId, reason = 'session_closed', { origins = null } = {}) {
2191
+ // The session closing, its brain going or a Stop: the runtime dropped its continuation; nothing watches it.
2192
+ for (const entry of continuations.values()) if (entry.sessionId === sessionId && !entry.started) closeContinuation(entry);
1815
2193
  for (const card of [...cards.values()]) {
1816
2194
  if (card.sessionId !== sessionId) continue;
1817
2195
  if (origins && !origins.includes(card.origin)) continue;
@@ -1825,11 +2203,16 @@ export function createAssistantRouter({
1825
2203
  if (!routeId) return false;
1826
2204
  return sessionId === null || sessionId === undefined || cards.get(routeId)?.sessionId === String(sessionId);
1827
2205
  }
2206
+ function closedRoute(idOrRequestId, sessionId = null) {
2207
+ const id = String(idOrRequestId);
2208
+ return [...lastClosed.values()].find(c => c.taskId && (c.routeId === id || c.requestId === id)
2209
+ && (sessionId == null || c.sessionId === String(sessionId)) && ['expired', 'cancelled'].includes(c.settled?.status)) || null;
2210
+ }
1828
2211
  function status(routeId) {
1829
2212
  const card = cards.get(routeId);
1830
- if (card) return { routeId, status: card.status, sessionId: card.sessionId, runIds: [...card.runIds], taskClass: card.taskClass, expiresAt: new Date(card.expiresAt).toISOString(), request: card.packet.request };
2213
+ if (card) return { ...agentFields(card), routeId, status: card.status, sessionId: card.sessionId, taskId: card.taskId || null, taskKey: card.taskKey || '', runIds: [...card.runIds], taskClass: card.taskClass, expiresAt: new Date(card.expiresAt).toISOString(), request: card.packet.request };
1831
2214
  const route = decided.get(routeId);
1832
- if (route) return { routeId, status: route.status, sessionId: route.sessionId, runIds: route.runIds || [], taskClass: route.taskClass, target: route.target, decidedBy: route.decidedBy };
2215
+ if (route) return { ...agentFields(route), routeId, status: route.status, sessionId: route.sessionId, taskId: route.taskId || null, taskKey: route.taskKey || '', runIds: route.runIds || [], taskClass: route.taskClass, target: route.target, decidedBy: route.decidedBy, plannedSplit: route.plannedSplit || null, workflowId: route.workflowId || null };
1833
2216
  return null;
1834
2217
  }
1835
2218
 
@@ -1848,16 +2231,18 @@ export function createAssistantRouter({
1848
2231
  }
1849
2232
 
1850
2233
  function shutdown() {
2234
+ for (const entry of continuations.values()) closeContinuation(entry);
2235
+ continuations.clear();
1851
2236
  for (const card of [...cards.values()]) { if (card.timer) clearTimeout(card.timer); settle(card, { status: 'cancelled' }); }
1852
2237
  cards.clear();
1853
2238
  byRequest.clear();
1854
2239
  }
1855
2240
 
1856
2241
  return {
1857
- propose, answer, resolveDispatch, releaseRoute, holdRuns, cancel, cancelForRun, cancelForSession, pendingCards, owns, status, modeFor, stamp, shutdown,
2242
+ continuationStarted, propose, answer, expireOtherTasks, resolveDispatch, releaseRoute, holdRuns, cancel, cancelForRun, cancelForSession, pendingCards, owns, closedRoute, status, modeFor, stamp, shutdown,
1858
2243
  routeClosedError: (routeId) => routeClosedError(lastClosed.get(String(routeId || '')) || { routeId: String(routeId || '') }),
1859
2244
  routing, escalationFor: ({ run, depth = 0 }) => escalationFor({ run, catalog: catalog.peek?.() || null, routing: routing(), depth }),
1860
- _internals: { cards, decided, byRequest },
2245
+ _internals: { cards, decided, byRequest, continuations },
1861
2246
  };
1862
2247
  }
1863
2248