synabun 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +169 -0
  4. package/browser-extension/engine.js +477 -0
  5. package/browser-extension/icons/icon-128.png +0 -0
  6. package/browser-extension/icons/icon-16.png +0 -0
  7. package/browser-extension/icons/icon-32.png +0 -0
  8. package/browser-extension/icons/icon-48.png +0 -0
  9. package/browser-extension/icons/status-off-16.png +0 -0
  10. package/browser-extension/icons/status-off-32.png +0 -0
  11. package/browser-extension/icons/status-off-48.png +0 -0
  12. package/browser-extension/icons/status-on-16.png +0 -0
  13. package/browser-extension/icons/status-on-32.png +0 -0
  14. package/browser-extension/icons/status-on-48.png +0 -0
  15. package/browser-extension/manifest.json +56 -0
  16. package/browser-extension/popup-strings.js +244 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +165 -0
  19. package/browser-extension/popup.html +105 -0
  20. package/browser-extension/popup.js +347 -0
  21. package/browser-extension/protocol.js +226 -0
  22. package/browser-extension/service-worker.js +267 -0
  23. package/browser-extension/setup-content.js +36 -0
  24. package/browser-extension/tokens.css +326 -0
  25. package/docs/browser-extension-bridge.md +84 -0
  26. package/docs/whatsapp.md +1 -1
  27. package/mcp-server/dist/http.d.ts +2 -0
  28. package/mcp-server/dist/http.d.ts.map +1 -1
  29. package/mcp-server/dist/http.js +9 -1
  30. package/mcp-server/dist/http.js.map +1 -1
  31. package/mcp-server/dist/index.d.ts +11 -0
  32. package/mcp-server/dist/index.d.ts.map +1 -1
  33. package/mcp-server/dist/index.js +38 -3
  34. package/mcp-server/dist/index.js.map +1 -1
  35. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  36. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  38. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  39. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  40. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  41. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +94 -3
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +168 -23
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/team-context.d.ts +18 -0
  47. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  48. package/mcp-server/dist/services/team-context.js +29 -0
  49. package/mcp-server/dist/services/team-context.js.map +1 -0
  50. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  51. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  52. package/mcp-server/dist/services/tool-catalog.js +22 -6
  53. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  54. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  55. package/mcp-server/dist/services/tool-list.js +4 -0
  56. package/mcp-server/dist/services/tool-list.js.map +1 -1
  57. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  58. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.js +18 -1
  60. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  61. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  62. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/agent-definition.js +483 -0
  64. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  65. package/mcp-server/dist/tools/agents.d.ts +91 -9
  66. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  67. package/mcp-server/dist/tools/agents.js +161 -20
  68. package/mcp-server/dist/tools/agents.js.map +1 -1
  69. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  70. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  72. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  73. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  74. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.js +283 -2
  76. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  77. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  78. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.js +22 -5
  80. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  81. package/mcp-server/dist/tools/team.d.ts +32 -0
  82. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  83. package/mcp-server/dist/tools/team.js +87 -0
  84. package/mcp-server/dist/tools/team.js.map +1 -0
  85. package/mcp-server/package-lock.json +2 -2
  86. package/mcp-server/package.json +1 -1
  87. package/mcp-server/src/http.ts +9 -1
  88. package/mcp-server/src/index.ts +34 -4
  89. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  90. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  91. package/mcp-server/src/services/neural-interface.ts +190 -29
  92. package/mcp-server/src/services/team-context.ts +27 -0
  93. package/mcp-server/src/services/tool-catalog.ts +26 -8
  94. package/mcp-server/src/services/tool-list.ts +4 -0
  95. package/mcp-server/src/services/tool-runtime.ts +21 -2
  96. package/mcp-server/src/tools/agent-definition.ts +458 -0
  97. package/mcp-server/src/tools/agents.ts +175 -19
  98. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  99. package/mcp-server/src/tools/git-tools.ts +249 -3
  100. package/mcp-server/src/tools/morelogin.ts +20 -5
  101. package/mcp-server/src/tools/team.ts +97 -0
  102. package/neural-interface/i18n/en.json +1174 -47
  103. package/neural-interface/i18n/pt-BR.json +1174 -47
  104. package/neural-interface/lib/account-usage.js +1 -1
  105. package/neural-interface/lib/agents/density.js +101 -0
  106. package/neural-interface/lib/agents/forge-host.js +223 -0
  107. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  108. package/neural-interface/lib/agents/native-export.js +365 -0
  109. package/neural-interface/lib/agents/registry.js +840 -0
  110. package/neural-interface/lib/agents/resolve.js +544 -0
  111. package/neural-interface/lib/agents/schema.js +642 -0
  112. package/neural-interface/lib/agents/split.js +37 -0
  113. package/neural-interface/lib/agents-studio-api.js +591 -0
  114. package/neural-interface/lib/assistant-api.js +76 -7
  115. package/neural-interface/lib/assistant-catalog.js +2 -0
  116. package/neural-interface/lib/assistant-continuity.js +49 -0
  117. package/neural-interface/lib/assistant-dispatch.js +229 -102
  118. package/neural-interface/lib/assistant-persona.js +105 -8
  119. package/neural-interface/lib/assistant-route-gate.js +24 -9
  120. package/neural-interface/lib/assistant-router.js +384 -42
  121. package/neural-interface/lib/assistant-run-tail.js +151 -0
  122. package/neural-interface/lib/assistant-run-wait.js +183 -0
  123. package/neural-interface/lib/assistant-runtime.js +440 -93
  124. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  125. package/neural-interface/lib/assistant-usage.js +3 -2
  126. package/neural-interface/lib/automation-approval.js +2 -2
  127. package/neural-interface/lib/browser-close-evidence.js +80 -0
  128. package/neural-interface/lib/browser-default.js +210 -0
  129. package/neural-interface/lib/browser-extension-adapter.js +255 -0
  130. package/neural-interface/lib/browser-extension-bridge.js +418 -0
  131. package/neural-interface/lib/browser-extension-folder.js +116 -0
  132. package/neural-interface/lib/browser-extension-setup.js +140 -0
  133. package/neural-interface/lib/browser-profile-choices.js +3 -3
  134. package/neural-interface/lib/browser-profiles.js +1 -1
  135. package/neural-interface/lib/browser-tool-policy.js +1 -1
  136. package/neural-interface/lib/claude-account-links.js +301 -0
  137. package/neural-interface/lib/claude-accounts.js +45 -20
  138. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  139. package/neural-interface/lib/claude-model-catalog.js +6 -0
  140. package/neural-interface/lib/claude-panel-session.js +33 -0
  141. package/neural-interface/lib/cli-install-api.js +23 -0
  142. package/neural-interface/lib/codex-accounts.js +67 -24
  143. package/neural-interface/lib/coordination/README.md +384 -0
  144. package/neural-interface/lib/coordination/service.js +563 -0
  145. package/neural-interface/lib/coordination/store.js +1138 -0
  146. package/neural-interface/lib/db.js +22 -1
  147. package/neural-interface/lib/editor-completion-opencode.js +4 -3
  148. package/neural-interface/lib/effort-levels.js +10 -1
  149. package/neural-interface/lib/maritaca/opencode-proxy.js +7 -2
  150. package/neural-interface/lib/maritaca/opencode.js +35 -0
  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 +219 -7
  157. package/neural-interface/lib/native-loop-runtime.js +24 -1
  158. package/neural-interface/lib/opencode-build-preflight.js +116 -0
  159. package/neural-interface/lib/opencode-launch-error.js +13 -0
  160. package/neural-interface/lib/opencode-native-boundary.js +800 -84
  161. package/neural-interface/lib/opencode-serve-probe.js +426 -0
  162. package/neural-interface/lib/opencode-serve-records.js +14 -9
  163. package/neural-interface/lib/opencode-serve-scan.js +108 -0
  164. package/neural-interface/lib/page-session.js +1 -1
  165. package/neural-interface/lib/peer-identity.js +60 -21
  166. package/neural-interface/lib/process-identity.js +235 -7
  167. package/neural-interface/lib/request-gate.js +3 -0
  168. package/neural-interface/lib/screenshot-location.js +33 -0
  169. package/neural-interface/lib/skills/creation.js +1 -1
  170. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  171. package/neural-interface/lib/studio-attention.js +56 -0
  172. package/neural-interface/lib/teams/README.md +382 -0
  173. package/neural-interface/lib/teams/api.js +287 -0
  174. package/neural-interface/lib/teams/brief.js +185 -0
  175. package/neural-interface/lib/teams/claims.js +315 -0
  176. package/neural-interface/lib/teams/git.js +293 -0
  177. package/neural-interface/lib/teams/index.js +122 -0
  178. package/neural-interface/lib/teams/integration.js +580 -0
  179. package/neural-interface/lib/teams/landing.js +184 -0
  180. package/neural-interface/lib/teams/recovery.js +256 -0
  181. package/neural-interface/lib/teams/scheduler.js +1474 -0
  182. package/neural-interface/lib/teams/schema.js +559 -0
  183. package/neural-interface/lib/teams/state.js +181 -0
  184. package/neural-interface/lib/teams/test-runner.js +86 -0
  185. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  186. package/neural-interface/lib/teams/worktrees.js +757 -0
  187. package/neural-interface/lib/tool-permission-choices.js +226 -0
  188. package/neural-interface/lib/whatsapp/cards.js +24 -10
  189. package/neural-interface/lib/worker-confinement.js +206 -6
  190. package/neural-interface/lib/worker-mcp-channel.js +38 -1
  191. package/neural-interface/package-lock.json +4 -2
  192. package/neural-interface/package.json +3 -1
  193. package/neural-interface/public/extension-setup.html +107 -0
  194. package/neural-interface/public/index.html +52 -12
  195. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  196. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  197. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  198. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  199. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  200. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  201. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  202. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  203. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  204. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  205. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  206. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  207. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  208. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  209. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  210. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  211. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  212. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  213. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  214. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  215. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  216. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  217. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  218. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  219. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  220. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  221. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  222. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  223. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  224. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  225. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  226. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  227. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  228. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  229. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  230. package/neural-interface/public/shared/assistant/asst-render.js +36 -6
  231. package/neural-interface/public/shared/assistant/asst-route.js +78 -12
  232. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  233. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  234. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  235. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  236. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  237. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  238. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  239. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  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 +33 -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/opencode-verify-view.js +175 -0
  279. package/neural-interface/public/shared/schedules-view.js +2 -2
  280. package/neural-interface/public/shared/session-project-items.js +11 -0
  281. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  282. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  284. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  285. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  286. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  287. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  288. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  289. package/neural-interface/public/shared/storage.js +6 -1
  290. package/neural-interface/public/shared/studio-attention.js +83 -0
  291. package/neural-interface/public/shared/styles.css +713 -61
  292. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  293. package/neural-interface/public/shared/transcript-rows.js +334 -0
  294. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  295. package/neural-interface/public/shared/ui-agents.js +97 -0
  296. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  297. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  298. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  299. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  300. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  301. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  302. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  303. package/neural-interface/public/shared/ui-games.js +1 -1
  304. package/neural-interface/public/shared/ui-loading.js +12 -1
  305. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  306. package/neural-interface/public/shared/ui-menubar.js +23 -0
  307. package/neural-interface/public/shared/ui-native-loop-router.js +1 -1
  308. package/neural-interface/public/shared/ui-navbar.js +15 -9
  309. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  310. package/neural-interface/public/shared/ui-opencode-verify.js +120 -0
  311. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  312. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  313. package/neural-interface/public/shared/ui-sessions.js +3 -3
  314. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  315. package/neural-interface/public/shared/ui-settings.js +372 -402
  316. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  317. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  318. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  319. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  320. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  321. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  322. package/neural-interface/public/shared/ui-sync.js +5 -0
  323. package/neural-interface/public/shared/ui-terminal.js +13 -9
  324. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  325. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  326. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  327. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  328. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  329. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  330. package/neural-interface/public/shared/window-keys.js +71 -0
  331. package/neural-interface/public/variant/2d/main.js +2 -0
  332. package/neural-interface/public/variant/3d/app.js +620 -0
  333. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  334. package/neural-interface/public/variant/3d/main.js +21 -544
  335. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  336. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  337. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  338. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  339. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  340. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  341. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  342. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  343. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  346. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  347. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  348. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  349. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  350. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  351. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  352. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  353. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  354. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  355. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  356. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  357. package/neural-interface/scripts/boot-graph.mjs +270 -0
  358. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  359. package/neural-interface/server.js +1164 -157
  360. package/npm-shrinkwrap.json +2 -2
  361. package/package.json +3 -1
  362. package/skills/agent-forge/SKILL.md +182 -0
  363. package/skills/agent-forge/evals/evals.json +56 -0
  364. package/skills/agent-forge/references/definition-fields.md +61 -0
  365. package/skills/agent-forge/references/examples.md +105 -0
  366. package/skills/agent-forge/references/instructions.md +51 -0
  367. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -42,8 +42,10 @@ import { MAX_MEDIA_BYTES, MAX_RUN_MEDIA_BYTES, copyRunMedia, mediaType, mediaUrl
42
42
  import { loadPlaybook } from './assistant-playbooks.js';
43
43
  import { loadStyleGuideForRun } from './style-guide/store.js';
44
44
  import { claimCheckWaived, normalizeTestDensity, testingApplies } from './assistant-test-density.js';
45
+ import { normalizeAgentDensity } from './agents/density.js'; // agents-p4
45
46
  import { normalizeEffort } from './effort-levels.js';
46
47
  import { acpCommandOf, createTurnEvidence, recordProviderEvent, evidenceSnapshot, claimEvidenceLine } from './assistant-evidence.js';
48
+ import { runAwaitsAnswer } from '../public/shared/sidepanel-session-status.js';
47
49
  import { BUDGET_MAX_USD, codexUsageCostUsd, floorCents } from './assistant-budget.js';
48
50
  import { MIN_SPEND_USD, PROVIDER_LABELS, UNPRICED_PROVIDER_REASON, isFreePrice, isUnpricedProvider } from './assistant-budget-split.js';
49
51
  import { createBudgetPlanner } from './assistant-budget-planner.js';
@@ -52,6 +54,12 @@ import { claudeTokensCostUsd } from './assistant-pricing.js';
52
54
  import { RemotePolicyError, clampDispatchSpec, getSessionPolicy, readRegisteredProjects } from './remote-policy.js';
53
55
  import { validateWorkerReply } from './worker-question.js';
54
56
  import { limitFromText } from '../public/shared/assistant/asst-limit.js';
57
+ // agents-p1: a dispatch's agent_ref (lib/agents/resolve.js).
58
+ import { agentCorrections, agentIntake, carryAgentRun, getAgentResolver, stampAgentRun } from './agents/resolve.js';
59
+ // Agents P2 (durable agent messaging): run events, typed waits, the follow-up outbox and the transcript on disk.
60
+ import { createCoordinationService, sharedCoordinationService } from './coordination/service.js';
61
+ import { createRunWaits } from './assistant-run-wait.js';
62
+ import { createRunTailStore, pageText } from './assistant-run-tail.js';
55
63
 
56
64
  // Antigravity (Google's `agy`, over ACP: lib/native-loop-providers.js createAntigravityNativeLoopAdapter) is a worker
57
65
  // provider only: never a brain, no accounts, its usage reported in tokens and never priced.
@@ -454,6 +462,10 @@ export function createAssistantDispatcher({
454
462
  // Clarification (assistant-clarify.js): { forDispatch(sessionId, { briefId, independent }) }.
455
463
  // A brain's dispatch waits while its questions are open and carries the user's brief.
456
464
  clarifier = null,
465
+ // agents-p1: the agent resolver (lib/agents/resolve.js createAgentResolver, or what returns one). A dispatch's
466
+ // agent_ref is resolved through it at intake. Default: the one server.js set for the process (none: such a
467
+ // dispatch is refused, AGENTS_UNAVAILABLE; a dispatch without agent_ref never asks).
468
+ agents = getAgentResolver,
457
469
  // Live limit overrides (assistant-config.json `limits`, re-read on every check), the brain's own
458
470
  // spend per assistant session (the runtime: its total, and by the provider it ran on) and list
459
471
  // prices for Codex usage (assistant-budget.js createModelPricing).
@@ -480,9 +492,16 @@ export function createAssistantDispatcher({
480
492
  // The session's Test density (assistant-test-density.js): (assistantSessionId) => level | null.
481
493
  // Read when a prompt is composed; null or an unknown value is the default level.
482
494
  testDensity = () => null,
495
+ // agents-p4: the session's Agent density (lib/agents/density.js): (assistantSessionId) => level | null. How many
496
+ // workers one task may get; the team scheduler (lib/teams/scheduler.js) asks the dispatcher for it and enforces it.
497
+ agentDensity = () => null,
483
498
  // After a restart, resolves once this server answers its workers (a resumed CLI connects to SynaBun's MCP as it
484
499
  // starts): runs are resumed only then. null: at once.
485
500
  serverReady = null,
501
+ // The coordination service (lib/coordination/service.js): the durable log run events go to, the follow-up outbox
502
+ // and typed waits. Given none, the dispatcher takes the one server.js shares (shareCoordinationService), else it
503
+ // keeps its own in memory (a test: nothing survives the process).
504
+ coordination: givenCoordination = null,
486
505
  } = {}) {
487
506
  if (typeof getRuntime !== 'function') throw new Error('createAssistantDispatcher requires getRuntime()');
488
507
  if (!dataDir) throw new Error('createAssistantDispatcher requires dataDir');
@@ -502,6 +521,11 @@ export function createAssistantDispatcher({
502
521
  return limits;
503
522
  }
504
523
  const registryPath = resolve(dataDir, 'assistant-dispatches.json');
524
+ // ── Agents P2: durable messaging ───────────────────────────────────────────
525
+ const sharedCoordination = givenCoordination || sharedCoordinationService();
526
+ const coordination = sharedCoordination || createCoordinationService({ log: (tag, detail) => log(null, tag, detail) });
527
+ // A run's transcript tail and the whole text of its last turn, kept on disk: <dataDir>/run-tails/<runId>.*.json.
528
+ const tails = createRunTailStore({ dir: resolve(dataDir, 'run-tails'), log: (tag, detail) => log(null, tag, detail) });
505
529
  // What image / video creation runs generated, and design runs' screenshots: <dataDir>/media/<runId>/<n>-<name>.
506
530
  const mediaRoot = resolve(dataDir, 'media');
507
531
  // A guarded worker's own scratch folder (lib/worker-confinement.js): <dataDir>/scratch/<runId>, removed when empty.
@@ -529,7 +553,43 @@ export function createAssistantDispatcher({
529
553
  // Assistant listens (both filled by loadRegistry). Follow-ups sent to a run while it is away wait here for it.
530
554
  const bootResumes = [];
531
555
  const bootInterrupts = [];
532
- const awaitingResume = new Map(); // runId → follow-up items (sendTurn) for a suspended or resuming run
556
+ // ── Agents P2: follow-ups wait in the coordination store's outbox ──────────
557
+ // Text sent to a run while it works, or while a restart has it away (suspended / resuming), used to sit in arrays
558
+ // in memory. Now each is a row of the outbox: it survives a restart, keeps its place, is marked sent in the step
559
+ // that hands it to the run's provider, and the queue refuses more than its bound.
560
+ /** Queue a follow-up for a run → { id, position }. Throws FOLLOW_UP_QUEUE_FULL (409) at the bound. */
561
+ function queueFollowUp(entry, item) {
562
+ try {
563
+ return coordination.followUps.enqueue({ runId: entry.runId, text: item.text, sessionId: entry.assistantSessionId || null, origin: item.origin, taskId: item.taskId, at: item.at });
564
+ } catch (error) {
565
+ if (error?.code === 'OUTBOX_FULL') {
566
+ throw new DispatchError('FOLLOW_UP_QUEUE_FULL', `Run ${entry.runId} already has ${error.queued} follow-up${error.queued === 1 ? '' : 's'} waiting (at most ${error.limit}). Wait until it took some (agent_wait), or send one message that says it all.`, { status: 409, queued: error.queued, limit: error.limit });
567
+ }
568
+ throw new DispatchError('FOLLOW_UP_NOT_QUEUED', `The follow-up for run ${entry.runId} could not be queued: ${error?.message || error}`, { status: 500 });
569
+ }
570
+ }
571
+ /** The run's oldest follow-up not handed to its provider yet ({ id, kind: 'follow-up', text, origin, taskId, at }), or null. */
572
+ function nextFollowUp(runId) {
573
+ try { return coordination.followUps.next(runId); } catch { return null; }
574
+ }
575
+ function followUpCount(runId) {
576
+ try { return coordination.followUps.count(runId); } catch { return 0; }
577
+ }
578
+ /** The run will take no more follow-ups (it ended, was stopped, did not resume): they leave the queue → the items. */
579
+ function cancelFollowUps(runId) {
580
+ try { return coordination.followUps.cancel(runId); } catch { return []; }
581
+ }
582
+ /** After a restart: follow-ups queued for runs that are gone or ended reach nobody. Their run's notes say so. */
583
+ function settleOrphanFollowUps() {
584
+ let runIds = [];
585
+ try { runIds = coordination.followUps.runs(); } catch { runIds = []; }
586
+ for (const runId of runIds) {
587
+ const entry = entries.get(runId);
588
+ if (entry && !TERMINAL_STATES.has(entry.state)) continue;
589
+ const dropped = cancelFollowUps(runId);
590
+ if (entry && dropped.length) entry.notes = [...(Array.isArray(entry.notes) ? entry.notes : []), `${dropped.length} queued follow-up${dropped.length === 1 ? '' : 's'} not delivered: the run ended first (the first: "${clip(dropped[0].text, 160)}")`];
591
+ }
592
+ }
533
593
  const resumeInProgress = new Set(); // runIds resumeRun works on (they hold their slot; the others waiting do not)
534
594
  // The server is going down (suspendForShutdown ran): a resume under way stops where it is, for the next start.
535
595
  let closing = false;
@@ -625,7 +685,7 @@ export function createAssistantDispatcher({
625
685
  const terminal = rows.filter((row) => !ACTIVE_STATES.has(row.state));
626
686
  const retained = [...active, ...terminal.slice(0, Math.max(0, limits.retention - active.length))];
627
687
  const retainedIds = new Set(retained.map((row) => row.runId));
628
- for (const row of terminal) if (!retainedIds.has(row.runId)) { entries.delete(row.runId); live.delete(row.runId); meters.delete(row.runId); }
688
+ for (const row of terminal) if (!retainedIds.has(row.runId)) { entries.delete(row.runId); live.delete(row.runId); meters.delete(row.runId); tails.remove(row.runId); }
629
689
  try { writeJsonAtomic(registryPath, retained); } catch (error) { log(null, 'assistant:registry-error', error?.message || String(error)); }
630
690
  };
631
691
  if (force) { if (persistTimer) { clearTimeout(persistTimer); persistTimer = null; } write(); return; }
@@ -678,7 +738,8 @@ export function createAssistantDispatcher({
678
738
  const elapsedMs = startedAt ? Math.max(0, end - new Date(startedAt).getTime()) : 0;
679
739
  // The brief goes to the worker's prompt; views name it only. The meters' state stays inside, and so does what a
680
740
  // resume after a restart needs (resumeInfo: the CLI's pid, the turn in progress); `resumes` counts them.
681
- const { rawSpec: _rawSpec, brief: _brief, usageState: _usageState, resumeInfo: _resumeInfo, crashed: _crashed, refusedAtShutdown: _refusedAtShutdown, aliveAt: _aliveAt, ...rest } = entry;
741
+ // agents-p4: a team slice's brief (the TEAM block's content) goes to the worker's prompt; views carry `team` only.
742
+ const { rawSpec: _rawSpec, brief: _brief, usageState: _usageState, resumeInfo: _resumeInfo, crashed: _crashed, refusedAtShutdown: _refusedAtShutdown, aliveAt: _aliveAt, teamBrief: _teamBrief, ...rest } = entry;
682
743
  return {
683
744
  ...rest,
684
745
  tools: toolsView({ ...entry, tools: runtimeRun?.tools ?? entry.tools }),
@@ -767,6 +828,9 @@ export function createAssistantDispatcher({
767
828
  touch(entry);
768
829
  persist({ force: TERMINAL_STATES.has(entry.state) });
769
830
  const payload = { type: 'assistant:dispatch', reason, run: view(entry), ...extra };
831
+ // Agents P2: the event goes into the durable log in the step that changed the run, under an id that names it
832
+ // (recording it again stores nothing), before anyone is told. It never throws: the run goes on either way.
833
+ coordination.recordDispatch(payload);
770
834
  if (['turn_completed', 'idle', 'failed', 'stopped', 'completed'].includes(reason)) { try { completeSkillUsage(entry); } catch {} }
771
835
  try { broadcastSync(payload); } catch {}
772
836
  for (const listener of listeners) { try { listener(payload); } catch {} }
@@ -827,27 +891,27 @@ export function createAssistantDispatcher({
827
891
  const mark = entries.get(runId)?.delivered;
828
892
  return mark && typeof mark === 'object' ? { ...mark } : null;
829
893
  }
830
-
831
- // ── waiters ────────────────────────────────────────────────────────────────
832
- const waiters = new Set(); // { check(): boolean, resolve() }
833
- function notifyWaiters() {
834
- for (const waiter of [...waiters]) {
835
- try { if (waiter.check()) { waiters.delete(waiter); waiter.resolve(); } } catch {}
836
- }
837
- }
838
- function satisfies(entry, until, sinceVersion) {
839
- if (!entry) return true;
840
- // A failed run whose cause is still being judged is not final yet: its
841
- // 'failed' event (with the cause and the matching escalation) follows
842
- // within the surface timeout.
843
- const terminal = TERMINAL_STATES.has(entry.state) && !entry.judging;
844
- if (until === 'terminal') return terminal;
845
- if (until === 'event') return terminal || entry.state === 'awaiting_permission' || entry.state === 'awaiting_route' || (Number(entry.version) || 0) !== sinceVersion;
846
- // 'idle' (default): the run is not busy — idle, awaiting a decision (a
847
- // permission or the user's model choice), or finished.
848
- return entry.state === 'idle' || entry.state === 'awaiting_permission' || entry.state === 'awaiting_route' || terminal;
894
+ /**
895
+ * Agents P2: events a brain read through agent_wait until:"event" are settled in its session's mailbox by their
896
+ * ids (never a second turn for them). The log keeps them: the same cursor returns them again. → how many.
897
+ */
898
+ function markEventsDelivered(assistantSessionId, eventIds) {
899
+ if (!assistantSessionId || !Array.isArray(eventIds) || !eventIds.length) return 0;
900
+ try { return coordination.mailbox.ack(String(assistantSessionId), eventIds).acked; } catch { return 0; }
849
901
  }
850
902
 
903
+ // ── waiters (Agents P2: lib/assistant-run-wait.js) ─────────────────────────
904
+ // until 'idle' / 'terminal' read the runs' state; until 'event' waits on typed events of the coordination log
905
+ // after a cursor. A workflow's runs are looked up at every check, so one added later is waited for too.
906
+ const runWaits = createRunWaits({
907
+ entries, view, coordination, now,
908
+ // A failed run whose cause is still being judged is not final yet: its 'failed' event follows.
909
+ isTerminal: (entry) => TERMINAL_STATES.has(entry.state) && !entry.judging,
910
+ waitCapMs: () => limits.waitCapMs,
911
+ fail: (code, message, extra) => new DispatchError(code, message, extra),
912
+ });
913
+ function notifyWaiters() { runWaits.notify(); }
914
+
851
915
  // ── validation ─────────────────────────────────────────────────────────────
852
916
  function suggestModels(catalogValue, provider, model) {
853
917
  const rows = catalogValue?.models?.[provider] || [];
@@ -1440,7 +1504,9 @@ export function createAssistantDispatcher({
1440
1504
  return true;
1441
1505
  }
1442
1506
 
1443
- async function dispatch(rawSpec = {}, { assistantSessionId = null, origin = 'assistant', brief: carried = null, notes: callerNotes = null } = {}) {
1507
+ // agents-p4: `team` (lib/teams/brief.js teamBrief) and `runId` are the team scheduler's own (lib/teams/scheduler.js):
1508
+ // the slice a run works and the id its claims were taken under. No request body reaches these options.
1509
+ async function dispatch(rawSpec = {}, { assistantSessionId = null, origin = 'assistant', brief: carried = null, notes: callerNotes = null, agentOf = null, team = null, runId: givenRunId = null } = {}) {
1444
1510
  const sessionId = assistantSessionId ? String(assistantSessionId) : null;
1445
1511
  const idempotencyKey = rawSpec.idempotencyKey || rawSpec.idempotency_key ? String(rawSpec.idempotencyKey || rawSpec.idempotency_key).slice(0, 200) : null;
1446
1512
  if (idempotencyKey && sessionId) {
@@ -1452,6 +1518,10 @@ export function createAssistantDispatcher({
1452
1518
  }
1453
1519
  refreshLimits();
1454
1520
  refuseSessionOver(sessionId);
1521
+ // agents-p1: the agent the dispatch names (agent_ref) is applied before anything else reads the spec: what the
1522
+ // dispatch says itself wins, the definition fills the rest and never widens it (lib/agents/resolve.js). The very
1523
+ // same object comes back for a dispatch that names none.
1524
+ rawSpec = agentIntake(agents, rawSpec, { assistantSessionId: sessionId, origin, desktop, resolveExternalTools });
1455
1525
  // "true" (a string) is computer use too: normalizeSpec reads it so, and so must the gate.
1456
1526
  rawSpec = { ...rawSpec, usesComputer: rawSpec.usesComputer === true || rawSpec.usesComputer === 'true' };
1457
1527
  // The MoreLogin profile it names for the worker's browser tab, as MoreLogin lists it (refused here when it cannot
@@ -1477,14 +1547,14 @@ export function createAssistantDispatcher({
1477
1547
  let routed = null;
1478
1548
  // Skills owns the runtime selection and its provider-specific workspace. Never bind Assistant routes.
1479
1549
  if (router && !isSkillsRun(rawSpec) && origin !== 'ui' && sessionId) {
1480
- routed = await router.resolveDispatch({ sessionId, spec: rawSpec, origin });
1550
+ routed = await router.resolveDispatch({ sessionId, spec: rawSpec, origin, team });
1481
1551
  // A hold names an open card, but an answer that was already in flight (it waited on the same
1482
1552
  // catalog read) can decide that card before this continuation runs. Approved for this
1483
1553
  // session: the dispatch is resolved again with that route_id, so the run starts on it as any
1484
1554
  // dispatch with an approved route does (its validation, the remote clamps and claim, the
1485
1555
  // rails). Declined, cancelled or expired: the attachment below fails and it is refused.
1486
1556
  for (let i = 0; i < 2 && routed?.action === 'hold' && routeApprovedFor(routed.routeId, sessionId); i += 1) {
1487
- routed = { ...(await router.resolveDispatch({ sessionId, spec: { ...rawSpec, routeId: routed.routeId }, origin })), approvedMeanwhile: true };
1557
+ routed = { ...(await router.resolveDispatch({ sessionId, spec: { ...rawSpec, routeId: routed.routeId }, origin, team })), approvedMeanwhile: true };
1488
1558
  }
1489
1559
  }
1490
1560
  // A remote session's approved route, claimed by resolveDispatch, is used up only by the run it
@@ -1519,14 +1589,29 @@ export function createAssistantDispatcher({
1519
1589
  // The route's spec (a route_id alone can make it a design dispatch, with design's defaults):
1520
1590
  // its browser settings must agree too (the route already exists).
1521
1591
  if (routed?.spec) refuseBrowserConflict(input);
1592
+ // agents-p4: a team's slices start on a route that is approved already; none waits on a card of its own.
1593
+ if (team && routed?.action === 'hold') throw new DispatchError('TEAM_ROUTE_REQUIRED', 'A team slice starts on an approved route: route the team\'s task with agent_route first and start the team with that route_id.', { status: 409, routeId: routed.routeId || null });
1522
1594
  if (routed?.action === 'hold') return holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief, remoteNotes });
1523
1595
  // The run's class: its route's (the brain may omit task_class with a route_id), else the spec's.
1524
1596
  // Its capability backstop runs in normalizeSpec on the final target, however that was chosen.
1525
1597
  const taskClass = routeClass || knownClass(input.taskClass);
1526
1598
  const spec = normalizeSpec(input, { catalogValue, taskClass });
1527
1599
  const queuedCount = [...entries.values()].filter((e) => e.state === 'queued' && e.assistantSessionId === sessionId).length;
1528
- runId = randomId();
1600
+ if (givenRunId && entries.has(String(givenRunId))) throw new DispatchError('RUN_EXISTS', `Run ${givenRunId} exists already.`, { status: 409 }); // agents-p4
1601
+ runId = givenRunId ? String(givenRunId) : randomId();
1529
1602
  const entry = { ...baseEntry(runId, sessionId, origin), ...specFields(spec), notes: [...(spec.notes || []), ...remoteNotes] };
1603
+ stampAgentRun(entry, input); // agents-p1: agentRef, agentRevision, agentPin (nothing for a dispatch without an agent)
1604
+ // agents-p4: a team slice's run names its team and slice from its first event on (the durable log files it under
1605
+ // the team), and keeps the slice's brief for its prompt. Its worker is confined by its worktree (worker-confinement.js).
1606
+ if (team && team.teamId && team.sliceId) {
1607
+ entry.teamId = String(team.teamId);
1608
+ entry.team = { teamId: String(team.teamId), sliceId: String(team.sliceId) };
1609
+ entry.teamBrief = team;
1610
+ entry.notes.push(`team ${team.teamId}, slice ${team.sliceId}: ${team.readOnly ? 'read-only worktree; cleaned when the worker ends, changes kept and reported' : 'confined to its worktree and its own files; SynaBun commits and joins its work'}`);
1611
+ }
1612
+ // A run dispatched again as another run (escalate, which names its parent in `agentOf`) is its parent's agent
1613
+ // from the moment its record exists: its first events in the durable log (queued, started) say so too.
1614
+ if (agentOf) carryAgentRun(agentOf, entry);
1530
1615
  if (taskClass) entry.taskClass = taskClass;
1531
1616
  if (brief) { entry.brief = brief; entry.notes.push(`carries the user's brief ${brief.briefId || ''}`.trim()); }
1532
1617
  if (routed?.route) entry.route = routed.route;
@@ -1535,16 +1620,17 @@ export function createAssistantDispatcher({
1535
1620
  if (spec.idempotencyKey && sessionId) idempotency.set(`${sessionId}:${spec.idempotencyKey}`, { runId, at: now() });
1536
1621
  let budgetCorrections = [];
1537
1622
  try { budgetCorrections = await fitBudget(entry, { routed: !!routed?.route }); } catch (error) { entries.delete(runId); throw error; }
1538
- entry.taskId = taskAtDispatch(sessionId);
1623
+ entry.taskId = routed?.route?.taskId || taskAtDispatch(sessionId);
1539
1624
  const launched = await launchOrQueue(entry, spec, { queuedCount, strict: true });
1540
- const withCorrections = budgetCorrections.length ? { ...launched, corrections: budgetCorrections } : launched;
1625
+ const corrections = [...budgetCorrections, ...agentCorrections(input)]; // agents-p1: what the agent's definition was held to
1626
+ const withCorrections = corrections.length ? { ...launched, corrections } : launched;
1541
1627
  // The route's own "decided" event (it had no run attached) still tells the brain to dispatch.
1542
1628
  return routed?.approvedMeanwhile
1543
1629
  ? { ...withCorrections, next: 'The user picked this route while the dispatch was on its way, so this run started on it. Do not dispatch it again when the route_decided event for this route arrives.' }
1544
1630
  : withCorrections;
1545
1631
  } catch (error) {
1546
1632
  // A run that exists (it failed or stopped at start) used the route; a refusal before one did not.
1547
- if (routed?.claimed && !(runId && entries.has(runId))) router.releaseRoute?.(routed.route?.routeId);
1633
+ if (routed?.claimed && !(runId && entries.has(runId))) router.releaseRoute?.(routed.route?.routeId, routed.claim);
1548
1634
  throw error;
1549
1635
  }
1550
1636
  }
@@ -1641,6 +1727,7 @@ export function createAssistantDispatcher({
1641
1727
  idempotencyKey, rawSpec: { ...input }, route: routed.route,
1642
1728
  notes: ['awaiting the user\'s model choice on the route card', ...remoteNotes],
1643
1729
  };
1730
+ stampAgentRun(entry, input); // agents-p1
1644
1731
  const heldClass = knownClass(routed.route?.taskClass) || knownClass(input.taskClass);
1645
1732
  if (heldClass) entry.taskClass = heldClass;
1646
1733
  const selection = dispatchTools({ ...input, taskClass: heldClass });
@@ -1651,7 +1738,7 @@ export function createAssistantDispatcher({
1651
1738
  entry.usesBrowser = input.usesBrowser === true || selection.groups.some(isBrowserGroup);
1652
1739
  if (brief) entry.brief = brief;
1653
1740
  // A held run belongs to the task that asked for it, whenever the user picks its model.
1654
- entry.taskId = taskAtDispatch(sessionId);
1741
+ entry.taskId = routed?.route?.taskId || taskAtDispatch(sessionId);
1655
1742
  // The run waits on its route card, so the card must still be open: one that closed meanwhile
1656
1743
  // (the user wrote something else, a Stop) would leave a run nothing ever starts or declines.
1657
1744
  // Attached before the run exists: a refusal leaves no entry and no idempotency key behind.
@@ -1754,9 +1841,9 @@ export function createAssistantDispatcher({
1754
1841
  usesBrowser: entry.usesBrowser, usesComputer: entry.usesComputer, maxMinutes: entry.maxMinutes, budgetUsd: entry.budgetUsd,
1755
1842
  ...(entry.moreloginEnvId ? { moreloginEnvId: entry.moreloginEnvId, moreloginEnvName: entry.moreloginEnvName || null } : {}),
1756
1843
  outputSchema: entry.outputSchema, taskClass: entry.taskClass || null,
1757
- }, { assistantSessionId: entry.assistantSessionId, origin: 'ui', brief: entry.brief || null });
1844
+ }, { assistantSessionId: entry.assistantSessionId, origin: 'ui', brief: entry.brief || null, agentOf: entry });
1758
1845
  const child = entries.get(result?.run?.runId);
1759
- if (child) { child.escalationDepth = (Number(entry.escalationDepth) || 0) + 1; child.escalatedFrom = runId; }
1846
+ if (child) { child.escalationDepth = (Number(entry.escalationDepth) || 0) + 1; child.escalatedFrom = runId; carryAgentRun(entry, child); /* agents-p1 */ }
1760
1847
  entry.notes.push(`${retry ? 'retried on' : 'escalated to'} ${to.provider}/${to.model || 'default'} as ${result?.run?.runId || '?'}`);
1761
1848
  if (entry.limit && typeof entry.limit === 'object') entry.limit = { ...entry.limit, retriedAt: iso(now()) };
1762
1849
  emit(entry, 'escalated', { childRunId: result?.run?.runId || null });
@@ -1997,7 +2084,7 @@ export function createAssistantDispatcher({
1997
2084
  /** What a run's worker keeps in memory while it lives (never saved): its turn loop, transcript tail, waits. */
1998
2085
  function newLiveState(entry) {
1999
2086
  return {
2000
- entry, ctx: null, ring: [], ringChars: 0, followUps: [], waitResolve: null, idleTimer: null,
2087
+ entry, ctx: null, ring: [], ringChars: 0, waitResolve: null, idleTimer: null,
2001
2088
  pendingResolvers: new Map(), dead: false, lastEventAt: now(), stalledFlagged: false, turnCounter: 0, abortReason: null,
2002
2089
  evidence: null, // the current turn's commands / tool results / edited files (assistant-evidence.js)
2003
2090
  completed: false, // its turn loop ended on a completion (agent_complete, a closed finished tab, a removal)
@@ -2055,6 +2142,8 @@ export function createAssistantDispatcher({
2055
2142
  title: entry.title, tags: entry.tags, workflowId: entry.workflowId, parentRunId: entry.parentRunId,
2056
2143
  // The user's brief after a clarification (assistant-task-prompt.js briefBlock).
2057
2144
  brief: entry.brief || null,
2145
+ // agents-p4: a team slice's TEAM block (assistant-task-prompt.js teamBlock); null for every other run.
2146
+ team: entry.teamBrief || null,
2058
2147
  // Image / video creation: the prompt's media block and what the adapter collects ('image' | 'video');
2059
2148
  // design collects its screenshots and images the same way ('image').
2060
2149
  taskClass: entry.taskClass || null, collectMedia: collectedMedia(entry.taskClass),
@@ -2239,13 +2328,20 @@ export function createAssistantDispatcher({
2239
2328
  startUsageMetering(entry, liveState);
2240
2329
  const waitForFollowUp = () => new Promise((resolveWait) => {
2241
2330
  const finish = (value) => { if (liveState.idleTimer) { clearTimeout(liveState.idleTimer); liveState.idleTimer = null; } liveState.waitResolve = null; resolveWait(value); };
2242
- if (liveState.followUps.length) { finish(liveState.followUps.shift()); return; }
2331
+ // The outbox first (Agents P2): what was queued while the turn worked, or while a restart had the run away.
2332
+ const queued = nextFollowUp(entry.runId);
2333
+ if (queued) { finish(queued); return; }
2243
2334
  if (liveState.abortReason) { finish({ kind: 'abort' }); return; }
2244
- liveState.waitResolve = finish;
2335
+ // sendTurn signals { kind: 'follow-up' } once its text is in the outbox: the oldest queued one is taken from there.
2336
+ liveState.waitResolve = (value) => {
2337
+ if (value?.kind !== 'follow-up') { finish(value); return; }
2338
+ const next = nextFollowUp(entry.runId);
2339
+ if (next) finish(next);
2340
+ };
2245
2341
  liveState.idleTimer = setTimeout(() => finish({ kind: 'timeout' }), entry.idleTimeoutMs);
2246
2342
  liveState.idleTimer.unref?.();
2247
2343
  });
2248
- const runInnerTurn = async (prompt, meta, { origin = 'assistant', label = null, followUp = null, taskId = entry.taskId || null } = {}) => {
2344
+ const runInnerTurn = async (prompt, meta, { origin = 'assistant', label = null, followUp = null, taskId = entry.taskId || null, outboxId = null } = {}) => {
2249
2345
  liveState.turnCounter += 1;
2250
2346
  const turnNumber = liveState.turnCounter;
2251
2347
  const startedAt = iso(now());
@@ -2271,6 +2367,9 @@ export function createAssistantDispatcher({
2271
2367
  liveState.evidence = createTurnEvidence();
2272
2368
  // Money booked while this turn runs (OpenCode steps, Codex rollout records).
2273
2369
  liveState.turnMeteredUsd = 0;
2370
+ // A queued follow-up is sent exactly here, as its prompt goes to the provider: a restart from now on continues
2371
+ // this turn (resumeInfo.inFlight) and never sends the text a second time.
2372
+ if (outboxId) { try { coordination.followUps.markSent([outboxId]); } catch (error) { log(entry.runId, 'assistant:follow-up-error', error?.message || String(error)); } }
2274
2373
  let raw = await inner.runTurn(prompt, { ...meta, turn: turnNumber, outputSchema: entry.outputSchema || undefined });
2275
2374
  if (entry.provider === 'codex') settleCodexTurn(entry, liveState, raw);
2276
2375
  else if (entry.provider === 'antigravity') settleAntigravityTurn(entry, liveState, raw);
@@ -2365,6 +2464,8 @@ export function createAssistantDispatcher({
2365
2464
  // (the OpenCode panel's pill): a warm worker whose turn ended asking waits on the user, it does not rest.
2366
2465
  ctx.setOutcome?.(parsed.status || null);
2367
2466
  entry.lastText = text.slice(0, 20_000);
2467
+ // The whole text goes to disk (lib/assistant-run-tail.js): agent_read format "text" pages through it with `offset`.
2468
+ tails.saveText(entry.runId, { turn: turnNumber, text });
2368
2469
  // The turn has ended: its result is in. Idle time from here on is not work.
2369
2470
  pauseWork(entry, liveState);
2370
2471
  // Blocked or contract-less turns offer a one-tier escalation (the run
@@ -2443,15 +2544,18 @@ export function createAssistantDispatcher({
2443
2544
  entry.notes.push(`follow-up dropped: ${blocked.message}${blocked.code === 'BUDGET_SHARE_EXHAUSTED' ? '; no unspent budget could be moved to it' : ''}`);
2444
2545
  return budgetStop(entry, blocked);
2445
2546
  }
2446
- // No work time left: a turn started now would only be cut off.
2547
+ // No work time left: a turn started now would only be cut off. The run ends as the cap's timer ends it
2548
+ // (stopped, time_cap), so its brain hears it in its mailbox; the follow-up stays in the outbox until
2549
+ // finalize cancels it, and the stop event names it.
2447
2550
  if (workLeftMs(entry) <= 0) {
2448
2551
  entry.completionReason = 'time_cap';
2449
2552
  entry.notes.push(`follow-up dropped: its ${entry.maxMinutes} minutes of work time are used up`);
2553
+ stop(entry.runId, 'time_cap').catch(() => {});
2450
2554
  return { providerSessionId: inner.identity?.()?.providerSessionId };
2451
2555
  }
2452
2556
  try {
2453
2557
  const followPrompt = buildFollowUpPrompt(next.text, state, { turn: liveState.turnCounter + 1, maxTurns: entry.maxTurns, origin: next.origin, testDensity: changedTestDensity(entry) });
2454
- await runInnerTurn(followPrompt, meta, { origin: next.origin, label: clip(next.text, 80), followUp: next.text, taskId: next.taskId || entry.taskId || null });
2558
+ await runInnerTurn(followPrompt, meta, { origin: next.origin, label: clip(next.text, 80), followUp: next.text, taskId: next.taskId || entry.taskId || null, outboxId: next.id || null });
2455
2559
  } catch (error) {
2456
2560
  pauseWork(entry, liveState);
2457
2561
  return handleTurnError(error, liveState, entry, ctx);
@@ -3445,10 +3549,9 @@ export function createAssistantDispatcher({
3445
3549
  const liveState = newLiveState(entry);
3446
3550
  liveState.turnCounter = turned;
3447
3551
  liveState.resume = { mode, taskId: inFlight?.taskId || null };
3448
- // Follow-ups sent while it was away wait for it like any queued follow-up.
3449
- const waiting = awaitingResume.get(entry.runId) || [];
3450
- awaitingResume.delete(entry.runId);
3451
- liveState.followUps.push(...waiting);
3552
+ // Follow-ups sent while it was away wait in the outbox: its turn loop takes them like any queued follow-up.
3553
+ // The transcript tail kept on disk goes on where it was.
3554
+ for (const line of tails.readTail(entry.runId)) pushRingLine(liveState, line);
3452
3555
  live.set(entry.runId, liveState);
3453
3556
  const desktopGrant = mintDesktopGrant(entry);
3454
3557
  const state = runState(entry, {
@@ -3528,8 +3631,7 @@ export function createAssistantDispatcher({
3528
3631
  const index = queue.indexOf(entry.runId);
3529
3632
  if (index !== -1) queue.splice(index, 1);
3530
3633
  // Follow-ups accepted for it while it was away (agent_send) reach nobody: its end says so, with the first of them.
3531
- const waiting = awaitingResume.get(entry.runId) || [];
3532
- awaitingResume.delete(entry.runId);
3634
+ const waiting = cancelFollowUps(entry.runId);
3533
3635
  const undelivered = waiting.length ? `; ${waiting.length} follow-up${waiting.length === 1 ? '' : 's'} sent while it was away ${waiting.length === 1 ? 'was' : 'were'} not delivered (${waiting.length === 1 ? '' : 'the first: '}"${clip(waiting[0].text, 160)}")` : '';
3534
3636
  // Nothing of it may go on: a CLI a crash left behind is ended too.
3535
3637
  endOldProcess(entry).then(() => persist()).catch(() => {});
@@ -3580,20 +3682,25 @@ export function createAssistantDispatcher({
3580
3682
  }
3581
3683
  // A follow-up works for the task in progress when it is sent, which may be a later one than the run's.
3582
3684
  const item = { kind: 'follow-up', text: message, origin, at: iso(now()), taskId: taskNow(entry.assistantSessionId) || entry.taskId || null };
3685
+ // Every follow-up goes through the outbox (Agents P2), also one an idle run takes at once: the queue is one, in
3686
+ // order, and what it holds outlives a restart.
3687
+ const idle = !away && !!liveState.waitResolve;
3688
+ if (!idle && !allowQueue) {
3689
+ throw new DispatchError('TURN_ACTIVE', away
3690
+ ? `Run ${runId} is ${entry.state === 'suspended' ? 'suspended while the server restarts' : 'being resumed after a server restart'}; retry when it is idle or pass queue:true`
3691
+ : `Run ${runId} is busy; retry when idle or pass queue:true`, { status: 409 });
3692
+ }
3693
+ const queued = queueFollowUp(entry, item);
3583
3694
  if (origin === 'user') emit(entry, 'user_intervened', { text: clip(message, 200) });
3584
- if (away) {
3585
- if (!allowQueue) throw new DispatchError('TURN_ACTIVE', `Run ${runId} is ${entry.state === 'suspended' ? 'suspended while the server restarts' : 'being resumed after a server restart'}; retry when it is idle or pass queue:true`, { status: 409 });
3586
- const waiting = awaitingResume.get(runId) || [];
3587
- waiting.push(item);
3588
- awaitingResume.set(runId, waiting);
3589
- emit(entry, 'follow_up_queued', { queued: waiting.length });
3590
- return { ok: true, queued: true, position: waiting.length, run: view(entry), note: 'The run resumes after the server restart; this follow-up goes to it then.' };
3695
+ if (idle) {
3696
+ liveState.waitResolve({ kind: 'follow-up' });
3697
+ return { ok: true, queued: false, turn: liveState.turnCounter + 1, followUpId: queued.id, run: view(entry) };
3591
3698
  }
3592
- if (liveState.waitResolve) { liveState.waitResolve(item); return { ok: true, queued: false, turn: liveState.turnCounter + 1, run: view(entry) }; }
3593
- if (!allowQueue) throw new DispatchError('TURN_ACTIVE', `Run ${runId} is busy; retry when idle or pass queue:true`, { status: 409 });
3594
- liveState.followUps.push(item);
3595
- emit(entry, 'follow_up_queued', { queued: liveState.followUps.length });
3596
- return { ok: true, queued: true, position: liveState.followUps.length, run: view(entry) };
3699
+ emit(entry, 'follow_up_queued', { queued: queued.position });
3700
+ return {
3701
+ ok: true, queued: true, position: queued.position, followUpId: queued.id, run: view(entry),
3702
+ ...(away ? { note: 'The run resumes after the server restart; this follow-up goes to it then.' } : {}),
3703
+ };
3597
3704
  }
3598
3705
  /**
3599
3706
  * Before a follow-up: when the run's provider share is used up, the session's unspent budget is
@@ -3651,7 +3758,7 @@ export function createAssistantDispatcher({
3651
3758
  if (entry.state === 'resuming' || entry.state === 'suspended') {
3652
3759
  const index = queue.indexOf(runId);
3653
3760
  if (index !== -1) queue.splice(index, 1);
3654
- awaitingResume.delete(runId);
3761
+ cancelFollowUps(runId);
3655
3762
  // A CLI a crash left behind (this start has not ended it yet) goes with the run.
3656
3763
  if (entry.state === 'resuming') await endOldProcess(entry);
3657
3764
  }
@@ -3673,8 +3780,12 @@ export function createAssistantDispatcher({
3673
3780
  function finalize(entry, runtimeRun) {
3674
3781
  if (TERMINAL_STATES.has(entry.state)) return;
3675
3782
  const liveState = live.get(entry.runId);
3676
- // Follow-ups that waited for its resume after a restart go with it.
3677
- awaitingResume.delete(entry.runId);
3783
+ // Follow-ups still queued for it (behind a turn, or for its resume after a restart) go with it: its notes say so.
3784
+ const unsent = cancelFollowUps(entry.runId);
3785
+ const undelivered = unsent.length ? `${unsent.length} queued follow-up${unsent.length === 1 ? '' : 's'} not delivered: the run ended first (the first: "${clip(unsent[0].text, 160)}")` : null;
3786
+ if (undelivered) entry.notes.push(undelivered);
3787
+ // What its transcript showed last stays readable (agent_read format "tail") after the worker is gone.
3788
+ if (liveState) tails.flush(entry.runId, liveState.ring);
3678
3789
  pauseWork(entry, liveState);
3679
3790
  let status = runtimeRun?.status || 'completed';
3680
3791
  // A completed worker whose loop file was swept meanwhile (a stale-file cleanup) reaches the
@@ -3707,7 +3818,8 @@ export function createAssistantDispatcher({
3707
3818
  return;
3708
3819
  }
3709
3820
  if (entry.state === 'failed' || entry.lastResult?.status === 'blocked') { noteLimit(entry); entry.escalation = computeEscalation(entry); }
3710
- emit(entry, entry.state);
3821
+ // The end event says which follow-ups never reached the worker (a stop the brain hears of carries it to its mailbox).
3822
+ emit(entry, entry.state, undelivered ? { text: undelivered } : {});
3711
3823
  // A memory already stored for the run (by the worker or the brain) is the run's memory.
3712
3824
  // An evaluation run (lib/skills/evals.js) is a measurement, not work to remember: it stores no memory.
3713
3825
  if (memory?.rememberDispatch && !isEvalRun(entry) && !syncMemory(entry, { announce: true }) && (entry.state === 'completed' || (entry.state === 'stopped' && entry.lastResult))) {
@@ -3730,6 +3842,8 @@ export function createAssistantDispatcher({
3730
3842
  const removed = liveState.ring.shift();
3731
3843
  liveState.ringChars -= removed?.length || 0;
3732
3844
  }
3845
+ // Kept on disk too (at most once a second), so the tail is still there after the run or a restart.
3846
+ tails.touch(liveState.entry.runId, () => liveState.ring);
3733
3847
  }
3734
3848
  /**
3735
3849
  * An Antigravity message chunk (ACP agent_message_chunk): the text joins the message's line when that line is
@@ -3747,6 +3861,7 @@ export function createAssistantDispatcher({
3747
3861
  liveState.ring[liveState.ring.length - 1] = line;
3748
3862
  liveState.ringChars += line.length - open.line.length;
3749
3863
  open.line = line;
3864
+ tails.touch(liveState.entry.runId, () => liveState.ring);
3750
3865
  }
3751
3866
  return;
3752
3867
  }
@@ -3882,6 +3997,19 @@ export function createAssistantDispatcher({
3882
3997
  .slice(0, Math.max(1, Math.min(500, Number(limit) || 100)))
3883
3998
  .map((entry) => view(entry));
3884
3999
  }
4000
+ // Check live entries directly: a long queue must not hide an older worker behind the roster's page limit.
4001
+ function hasRunAwaitingOwner() {
4002
+ for (const entry of entries.values()) {
4003
+ if (entry.removedAt || !ACTIVE_STATES.has(entry.state) || entry.state === 'suspended') continue;
4004
+ if (entry.state === 'awaiting_route' || entry.route?.status === 'pending' || entry.state === 'awaiting_permission') return true;
4005
+ if (runAwaitsAnswer({ status: runStatusFromState(entry.state), turnState: entry.turnState, pending: entry.pending, lastResult: entry.lastResult })) return true;
4006
+ }
4007
+ return false;
4008
+ }
4009
+ // Unbounded inventory, including removed runs, for conservative team cleanup checks.
4010
+ function teamRuns(teamId, workflowId) {
4011
+ return [...entries.values()].filter(entry => entry.teamId === teamId || entry.team?.teamId === teamId || entry.workflowId === workflowId).map(entry => view(entry));
4012
+ }
3885
4013
  function totals({ assistantSessionId = null, workflowId = null } = {}) {
3886
4014
  const rows = [...entries.values()].filter((entry) => (!assistantSessionId || entry.assistantSessionId === assistantSessionId) && (!workflowId || entry.workflowId === workflowId));
3887
4015
  // tokens: the five classes plus total, from the runs' ledger views (a run without one counts its legacy input / output).
@@ -3910,60 +4038,45 @@ export function createAssistantDispatcher({
3910
4038
  out.queue = queue.map((runId, index) => ({ runId, position: index + 1, title: entries.get(runId)?.title || null, provider: entries.get(runId)?.provider || null }));
3911
4039
  return out;
3912
4040
  }
3913
- function transcript(runId, { format = 'result', tail = 40, maxChars = 4000 } = {}) {
4041
+ /**
4042
+ * agent_read. `offset` (Agents P2, additive) pages through the text of format "text" / "tail": without it the
4043
+ * answer is the END of the text, at most `maxChars`, and says where that page starts (`offset`) and how long the
4044
+ * whole is (`totalChars`); with it the page starts there and `nextOffset` is where the following one starts.
4045
+ */
4046
+ function transcript(runId, { format = 'result', tail = 40, maxChars = 4000, offset = null } = {}) {
3914
4047
  const entry = requireEntry(runId);
3915
4048
  const liveState = live.get(runId);
3916
4049
  const cap = Math.max(200, Math.min(20_000, Number(maxChars) || 4000));
3917
4050
  const base = { runId, state: entry.state, turnState: entry.turnState, outcome: entry.lastResult?.status || null, turns: (entry.turns || []).length };
3918
4051
  if (format === 'result') return { ...base, result: entry.lastResult, turnsSummary: (entry.turns || []).map((turn) => ({ n: turn.n, origin: turn.origin, status: turn.result?.status || null, summary: clip(turn.result?.summary, 200), costUsd: turn.costUsd })) };
3919
4052
  if (format === 'text') {
3920
- const text = String(entry.lastText || '');
3921
- return { ...base, text: text.length > cap ? text.slice(-cap) : text, truncated: text.length > cap };
4053
+ // The whole text of the last turn is on disk; the registry keeps its first 20,000 characters only.
4054
+ const kept = tails.readText(runId);
4055
+ const lastTurn = (entry.turns || []).at(-1)?.n ?? null;
4056
+ const text = kept && (kept.turn === null || lastTurn === null || kept.turn === lastTurn) ? kept.text : String(entry.lastText || '');
4057
+ return { ...base, ...pageText(text, { offset, maxChars: cap }) };
3922
4058
  }
3923
4059
  if (format === 'files') return { ...base, files: entry.lastResult?.files || [] };
3924
4060
  // A skill-evaluation run's tool calls and its start catalog (kept while the run lives).
3925
4061
  if (format === 'tools') return { ...base, calls: liveState?.evalCalls ? [...liveState.evalCalls] : [], init: liveState?.evalInit || null, unavailable: !liveState ? 'tool calls are only kept for live runs' : null };
3926
4062
  if (format === 'events' || format === 'tail') {
3927
- const lines = liveState ? liveState.ring.slice(-Math.max(1, Math.min(500, Number(tail) || 40))) : [];
3928
- const joined = lines.join('\n');
3929
- return { ...base, tail: lines, text: joined.length > cap ? joined.slice(-cap) : joined, truncated: joined.length > cap, unavailable: !liveState ? 'transcript buffer is only kept for live runs' : null };
4063
+ // A live run's ring, else what was kept of it on disk (the run ended, or the server restarted since).
4064
+ const all = liveState ? liveState.ring : tails.readTail(runId);
4065
+ const lines = all.slice(-Math.max(1, Math.min(500, Number(tail) || 40)));
4066
+ return {
4067
+ ...base, tail: lines, ...pageText(lines.join('\n'), { offset, maxChars: cap }),
4068
+ unavailable: !liveState && !all.length ? 'no transcript was kept for this run' : null,
4069
+ };
3930
4070
  }
3931
4071
  throw new DispatchError('INVALID_FORMAT', `Unknown transcript format ${format}`);
3932
4072
  }
3933
4073
  function pendingPermissions(runId) { return [...(requireEntry(runId).pending || [])]; }
3934
4074
 
3935
- async function wait({ runId = null, runIds = null, workflowId = null, assistantSessionId = null, until = 'idle', mode = 'all', timeoutMs = 30_000 } = {}) {
3936
- let ids = Array.isArray(runIds) ? [...runIds] : runId ? [runId] : [];
3937
- if (workflowId) ids = [...new Set([...ids, ...[...entries.values()].filter((e) => e.workflowId === workflowId && (!assistantSessionId || e.assistantSessionId === assistantSessionId)).map((e) => e.runId)])];
3938
- ids = ids.slice(0, 20);
3939
- if (!ids.length) throw new DispatchError('RUN_IDS_REQUIRED', 'runId, runIds or workflowId is required');
3940
- for (const id of ids) requireEntry(id);
3941
- const started = now();
3942
- const budget = Math.max(1000, Math.min(limits.waitCapMs, Number(timeoutMs) || 30_000));
3943
- const baseline = new Map(ids.map((id) => [id, Number(entries.get(id)?.version) || 0]));
3944
- const check = () => {
3945
- const satisfied = ids.filter((id) => satisfies(entries.get(id), until, baseline.get(id)));
3946
- return mode === 'any' ? satisfied.length > 0 : satisfied.length === ids.length;
3947
- };
3948
- if (!check()) {
3949
- await new Promise((resolveWait) => {
3950
- const waiter = { check, resolve: () => { clearTimeout(timer); resolveWait(); } };
3951
- const timer = setTimeout(() => { waiters.delete(waiter); resolveWait(); }, budget);
3952
- timer.unref?.();
3953
- waiters.add(waiter);
3954
- });
3955
- }
3956
- const done = ids.filter((id) => satisfies(entries.get(id), until, baseline.get(id)));
3957
- const pendingIds = ids.filter((id) => !done.includes(id));
3958
- const timedOut = !check();
3959
- return {
3960
- ok: true, timedOut, waitedMs: now() - started, until, mode,
3961
- done: done.map((id) => view(entries.get(id))),
3962
- pending: pendingIds.map((id) => view(entries.get(id))),
3963
- needsInput: ids.map((id) => entries.get(id)).filter((e) => e?.lastResult?.status === 'needs_input' && e.state === 'idle').map((e) => ({ runId: e.runId, question: e.lastResult.question })),
3964
- permissions: ids.flatMap((id) => (entries.get(id)?.pending || []).map((request) => ({ runId: id, ...request }))),
3965
- };
3966
- }
4075
+ /**
4076
+ * agent_wait (lib/assistant-run-wait.js). Additive since Agents P2: `afterSeq` and `kinds` for until 'event',
4077
+ * `unseenFor` (the asking brain's session), and `events` / `cursor` in the answer.
4078
+ */
4079
+ function wait(options = {}) { return runWaits.wait(options); }
3967
4080
 
3968
4081
  // ── removal (the user clears finished runs from the agents tray) ──────────
3969
4082
  /**
@@ -3976,7 +4089,7 @@ export function createAssistantDispatcher({
3976
4089
  function finishedIdle(entry, { outcomes = ['done', 'blocked'] } = {}) {
3977
4090
  return entry.state === 'idle' && !entry.judging
3978
4091
  && outcomes.includes(entry.lastResult?.status)
3979
- && !(live.get(entry.runId)?.followUps?.length);
4092
+ && !followUpCount(entry.runId);
3980
4093
  }
3981
4094
  async function finishIdleForRemoval(entry) {
3982
4095
  if (!finishedIdle(entry)) return;
@@ -4049,12 +4162,20 @@ export function createAssistantDispatcher({
4049
4162
  }
4050
4163
  }
4051
4164
  persist({ force: true });
4165
+ // Agents P2: the transcript tails are written; a service this dispatcher made for itself goes with it (the one
4166
+ // server.js shares is closed there, after the runtime).
4167
+ tails.flushAll();
4168
+ if (!sharedCoordination) coordination.close();
4052
4169
  }
4053
4170
 
4054
4171
  loadRegistry();
4172
+ settleOrphanFollowUps();
4055
4173
  attachRuntime();
4056
4174
  stalledTimer = setInterval(() => { attachRuntime(); checkStalled(); beat(); }, 60_000);
4057
4175
  stalledTimer.unref?.();
4176
+ // Transcript files of runs the registry dropped go, a while after the start (never on its path).
4177
+ const tailSweep = setTimeout(() => { try { tails.sweep(entries.keys()); } catch { /* the next start tries again */ } }, 30_000);
4178
+ tailSweep.unref?.();
4058
4179
  // After a restart: the cut-off runs are resumed, or said to have ended, once the Assistant listens (server.js makes
4059
4180
  // its runtime, which subscribes, right after this dispatcher, in the same tick).
4060
4181
  if (bootResumes.length || bootInterrupts.length) {
@@ -4062,14 +4183,20 @@ export function createAssistantDispatcher({
4062
4183
  }
4063
4184
 
4064
4185
  return {
4065
- dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, list, totals, wait, transcript, pendingPermissions,
4186
+ dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4066
4187
  respondPermission, subscribe, shutdown, limits, suspendForShutdown,
4067
4188
  sessionBudget, checkSession, refreshLimits, providerSpend, coverFollowUp, budget,
4068
4189
  resolveRoute, declineRoute, heldRouteRefusal, escalate,
4069
- markDelivered, deliveryState, noteBrowserRoute, noteBrowserProfile,
4190
+ markDelivered, deliveryState, markEventsDelivered, noteBrowserRoute, noteBrowserProfile,
4070
4191
  remove, removeFinished,
4071
4192
  mediaFile,
4072
4193
  accountInUse: (provider, accountId) => activeEntries((e) => e.provider === provider && e.accountId === accountId).length > 0,
4073
- _internals: { entries, live, queue, processQueue, attachRuntime, registryPath },
4194
+ // agents-p4: the session's Agent density as the server reads it (the default when it is not set or cannot be read).
4195
+ agentDensity: (assistantSessionId) => { try { return normalizeAgentDensity(agentDensity(assistantSessionId || null)); } catch { return normalizeAgentDensity(null); } },
4196
+ // Agents P2: the coordination service this dispatcher records into (the Assistant runtime reads its mailbox from it),
4197
+ // and when this server answers its workers (the runtime delivers the mailboxes a restart left open only then).
4198
+ coordination,
4199
+ whenServerReady: () => Promise.resolve(typeof serverReady === 'function' ? serverReady() : null).catch(() => null),
4200
+ _internals: { entries, live, queue, processQueue, attachRuntime, registryPath, tails, runWaits },
4074
4201
  };
4075
4202
  }