synabun 2.4.0 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +73 -11
  4. package/browser-extension/engine.js +196 -15
  5. package/browser-extension/manifest.json +4 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +102 -11
  12. package/browser-extension/service-worker.js +20 -4
  13. package/browser-extension/tokens.css +1 -1
  14. package/docs/browser-extension-bridge.md +25 -5
  15. package/lib/data-home-files.js +47 -0
  16. package/lib/data-home-migration.js +34 -58
  17. package/lib/first-launch-protection.js +8 -2
  18. package/lib/update-snapshot.js +11 -4
  19. package/mcp-server/dist/http.d.ts.map +1 -1
  20. package/mcp-server/dist/http.js +25 -2
  21. package/mcp-server/dist/http.js.map +1 -1
  22. package/mcp-server/dist/index.d.ts.map +1 -1
  23. package/mcp-server/dist/index.js +62 -17
  24. package/mcp-server/dist/index.js.map +1 -1
  25. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  26. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  27. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  28. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  29. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  30. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  31. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  32. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  33. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  34. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  35. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  36. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  37. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  38. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  39. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  41. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  42. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  43. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  44. package/mcp-server/dist/services/memory-schema.js +190 -13
  45. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  46. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  47. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  48. package/mcp-server/dist/services/memory-sessions.js +56 -20
  49. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  50. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  51. package/mcp-server/dist/services/memory-verification.js +8 -5
  52. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  53. package/mcp-server/dist/services/neural-interface.d.ts +6 -0
  54. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  55. package/mcp-server/dist/services/neural-interface.js +19 -2
  56. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  57. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  58. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  59. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  60. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  61. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  62. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  63. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  64. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  65. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  66. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  67. package/mcp-server/dist/services/sqlite-write.js +94 -0
  68. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  69. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  70. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  71. package/mcp-server/dist/services/sqlite.js +249 -8
  72. package/mcp-server/dist/services/sqlite.js.map +1 -1
  73. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  74. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  75. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  76. package/mcp-server/dist/services/typesafe-config.js +32 -10
  77. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  78. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  79. package/mcp-server/dist/services/typesafe.js +9 -7
  80. package/mcp-server/dist/services/typesafe.js.map +1 -1
  81. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  82. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  83. package/mcp-server/dist/services/vector-cache.js +161 -8
  84. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  85. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  86. package/mcp-server/dist/tools/agents.d.ts +13 -8
  87. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/agents.js +35 -15
  89. package/mcp-server/dist/tools/agents.js.map +1 -1
  90. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  91. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  92. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  93. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  94. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  95. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  96. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  97. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  98. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  99. package/mcp-server/dist/tools/browser-interact.js +6 -1
  100. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  101. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  102. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  103. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  104. package/mcp-server/package-lock.json +2 -2
  105. package/mcp-server/package.json +1 -1
  106. package/mcp-server/src/http.ts +20 -2
  107. package/mcp-server/src/index.ts +59 -17
  108. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  109. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  110. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  111. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  112. package/mcp-server/src/services/memory-schema.ts +194 -12
  113. package/mcp-server/src/services/memory-sessions.ts +54 -21
  114. package/mcp-server/src/services/memory-verification.ts +7 -4
  115. package/mcp-server/src/services/neural-interface.ts +23 -2
  116. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  117. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  118. package/mcp-server/src/services/sqlite-write.ts +60 -0
  119. package/mcp-server/src/services/sqlite.ts +246 -8
  120. package/mcp-server/src/services/typesafe-config.ts +25 -6
  121. package/mcp-server/src/services/typesafe.ts +9 -7
  122. package/mcp-server/src/services/vector-cache.ts +154 -9
  123. package/mcp-server/src/tools/agents.ts +33 -14
  124. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  125. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  126. package/mcp-server/src/tools/browser-interact.ts +5 -1
  127. package/neural-interface/i18n/en.json +266 -2
  128. package/neural-interface/i18n/pt-BR.json +267 -3
  129. package/neural-interface/lib/agents/builtins.json +207 -0
  130. package/neural-interface/lib/agents/registry.js +60 -15
  131. package/neural-interface/lib/agents/resolve.js +69 -10
  132. package/neural-interface/lib/agents/split.js +32 -4
  133. package/neural-interface/lib/assistant-api.js +19 -8
  134. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  135. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  136. package/neural-interface/lib/assistant-catalog.js +2 -2
  137. package/neural-interface/lib/assistant-config.js +0 -7
  138. package/neural-interface/lib/assistant-dispatch.js +384 -119
  139. package/neural-interface/lib/assistant-persona.js +17 -5
  140. package/neural-interface/lib/assistant-pricing.js +65 -14
  141. package/neural-interface/lib/assistant-router.js +181 -54
  142. package/neural-interface/lib/assistant-run-wait.js +45 -28
  143. package/neural-interface/lib/assistant-runtime.js +48 -34
  144. package/neural-interface/lib/backup-contents.js +158 -0
  145. package/neural-interface/lib/backup-crypto-io.js +330 -0
  146. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  147. package/neural-interface/lib/backup-crypto.js +525 -0
  148. package/neural-interface/lib/backup-download.js +268 -0
  149. package/neural-interface/lib/backup-encryption.js +318 -0
  150. package/neural-interface/lib/backup-groups.js +287 -0
  151. package/neural-interface/lib/backup-restore-session.js +176 -0
  152. package/neural-interface/lib/backup-restore-stage.js +60 -0
  153. package/neural-interface/lib/backup-service.js +836 -322
  154. package/neural-interface/lib/backup-zip-reader.js +30 -18
  155. package/neural-interface/lib/backup-zip-writer.js +34 -10
  156. package/neural-interface/lib/browser-extension-adapter.js +109 -24
  157. package/neural-interface/lib/browser-extension-bridge.js +42 -8
  158. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  159. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  160. package/neural-interface/lib/cli-update-planner.js +105 -6
  161. package/neural-interface/lib/client-diagnostics.js +42 -0
  162. package/neural-interface/lib/confined-fs.js +7 -2
  163. package/neural-interface/lib/coordination/README.md +8 -2
  164. package/neural-interface/lib/coordination/contract.js +161 -0
  165. package/neural-interface/lib/coordination/database.js +999 -0
  166. package/neural-interface/lib/coordination/operations.js +436 -0
  167. package/neural-interface/lib/coordination/service.js +68 -537
  168. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  169. package/neural-interface/lib/coordination/store.js +219 -1111
  170. package/neural-interface/lib/db.js +70 -32
  171. package/neural-interface/lib/health-count.js +37 -0
  172. package/neural-interface/lib/loop-stall.js +139 -0
  173. package/neural-interface/lib/maritaca/client.js +2 -2
  174. package/neural-interface/lib/maritaca/models.js +12 -17
  175. package/neural-interface/lib/maritaca/opencode.js +4 -2
  176. package/neural-interface/lib/memory-api.js +9 -1
  177. package/neural-interface/lib/memory-session-capture.js +42 -10
  178. package/neural-interface/lib/memory-store-gate.js +313 -0
  179. package/neural-interface/lib/memory-store-migrate.js +65 -0
  180. package/neural-interface/lib/memory-timers.js +7 -7
  181. package/neural-interface/lib/native-loop-providers.js +13 -16
  182. package/neural-interface/lib/native-loop-runtime.js +34 -14
  183. package/neural-interface/lib/opencode-build-preflight.js +30 -8
  184. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  185. package/neural-interface/lib/opencode-provider-view.js +14 -3
  186. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  187. package/neural-interface/lib/opencode2-client.js +2 -1
  188. package/neural-interface/lib/peer-identity.js +13 -8
  189. package/neural-interface/lib/recall-impact.js +122 -0
  190. package/neural-interface/lib/scratch-evidence.js +420 -0
  191. package/neural-interface/lib/scratch-process-guard.js +139 -0
  192. package/neural-interface/lib/scratch-references.js +279 -0
  193. package/neural-interface/lib/scratch-retention-core.js +385 -0
  194. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  195. package/neural-interface/lib/scratch-retention.js +151 -0
  196. package/neural-interface/lib/session-cache-builder.js +70 -44
  197. package/neural-interface/lib/session-cache-worker.js +157 -0
  198. package/neural-interface/lib/session-indexer.js +28 -21
  199. package/neural-interface/lib/session-search-index.js +85 -0
  200. package/neural-interface/lib/skills/creation.js +1 -1
  201. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  202. package/neural-interface/lib/style-guide/store.js +43 -3
  203. package/neural-interface/lib/system-restore.js +50 -0
  204. package/neural-interface/lib/teams/api.js +15 -6
  205. package/neural-interface/lib/teams/claims.js +67 -31
  206. package/neural-interface/lib/teams/index.js +7 -7
  207. package/neural-interface/lib/teams/integration.js +40 -40
  208. package/neural-interface/lib/teams/landing.js +6 -6
  209. package/neural-interface/lib/teams/recovery.js +24 -23
  210. package/neural-interface/lib/teams/scheduler.js +196 -97
  211. package/neural-interface/lib/teams/schema.js +1 -1
  212. package/neural-interface/lib/teams/state.js +14 -14
  213. package/neural-interface/lib/teams/worktrees.js +27 -27
  214. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  215. package/neural-interface/lib/worker-confinement.js +47 -2
  216. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  217. package/neural-interface/lib/worker-resume.js +5 -0
  218. package/neural-interface/lib/worker-stop.js +86 -0
  219. package/neural-interface/package-lock.json +2 -2
  220. package/neural-interface/package.json +1 -1
  221. package/neural-interface/public/index.html +260 -0
  222. package/neural-interface/public/offline.html +4 -3
  223. package/neural-interface/public/onboarding.html +259 -34
  224. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  225. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  226. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  227. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  228. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  229. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  230. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  231. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  232. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  233. package/neural-interface/public/shared/api.js +3 -2
  234. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  235. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  236. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  237. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  238. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  239. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  240. package/neural-interface/public/shared/assistant/asst-render.js +106 -38
  241. package/neural-interface/public/shared/assistant/asst-route.js +102 -21
  242. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  243. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  244. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  245. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  246. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  247. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  248. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  249. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  250. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  251. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  252. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  253. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  254. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  255. package/neural-interface/public/shared/effort-i18n.js +118 -0
  256. package/neural-interface/public/shared/html-shell.js +4 -51
  257. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  258. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  259. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  260. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  261. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  262. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  272. package/neural-interface/public/shared/output-format.js +294 -0
  273. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  274. package/neural-interface/public/shared/page-session.js +1 -1
  275. package/neural-interface/public/shared/provider-icons.js +6 -0
  276. package/neural-interface/public/shared/schedules-view.js +2 -1
  277. package/neural-interface/public/shared/server-presence.js +77 -0
  278. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  279. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  280. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  281. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  282. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  284. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  285. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  286. package/neural-interface/public/shared/start-bridge.js +2 -2
  287. package/neural-interface/public/shared/studio-attention.js +6 -0
  288. package/neural-interface/public/shared/styles.css +354 -438
  289. package/neural-interface/public/shared/transcript-rows.js +28 -3
  290. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  291. package/neural-interface/public/shared/ui-agents.js +1 -2
  292. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  293. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  294. package/neural-interface/public/shared/ui-loading.js +185 -25
  295. package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
  296. package/neural-interface/public/shared/ui-navbar.js +2 -1
  297. package/neural-interface/public/shared/ui-output.js +533 -0
  298. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  299. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  300. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  301. package/neural-interface/public/shared/ui-sessions.js +2 -2
  302. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  303. package/neural-interface/public/shared/ui-settings.js +234 -67
  304. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  305. package/neural-interface/public/shared/ui-sync.js +1 -0
  306. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  307. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  308. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  309. package/neural-interface/public/shared/worker-end.js +9 -4
  310. package/neural-interface/public/sw.js +4 -3
  311. package/neural-interface/public/variant/2d/main.js +5 -0
  312. package/neural-interface/public/variant/3d/app.js +10 -0
  313. package/neural-interface/public/variant/3d/main.js +17 -4
  314. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  315. package/neural-interface/server.js +507 -160
  316. package/npm-shrinkwrap.json +2 -2
  317. package/package.json +2 -1
  318. package/scripts/restore-data-home-from-backup.mjs +175 -8
  319. package/setup.js +18 -4
@@ -25,12 +25,13 @@ import { browserToolsConflict, dispatchTools, launchTools, toolsView } from './a
25
25
  import { storedToolList, toolListRecord } from './tool-lists.js';
26
26
  import { randomBytes } from 'node:crypto';
27
27
  import { chooseUsageAccount } from './account-usage.js';
28
- import { existsSync, mkdirSync, readFileSync, renameSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
28
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
29
29
  import { dirname, isAbsolute, resolve } from 'node:path';
30
30
  import {
31
31
  RESULT_STATUSES, buildTaskPrompt, buildFollowUpPrompt, buildResultRetryPrompt, buildResumePrompt, parseResultContract,
32
32
  } from './assistant-task-prompt.js';
33
- import { MAX_RESUMES, clockTime, endOrphanProcess, endProcessTree, findClaudeTranscript, isInside, readCostState, resumeRefusal } from './worker-resume.js';
33
+ import { MAX_RESUMES, clockTime, endOrphanProcess, endProcessTree, findClaudeTranscript, isInside, isMissingConversationError, readCostState, resumeRefusal } from './worker-resume.js';
34
+ import { mayEndSuspendedRun, stampStopProvenance, systemStopProvenance } from './worker-stop.js';
34
35
  import { normalizeCapability, normalizePermissionPolicy } from './native-loop-providers.js';
35
36
  import { WORKER_GUARD_DEFAULT, describeConfinementEvent, normalizeWorkerGuardMode } from './worker-confinement.js';
36
37
  import { draftConfinementSupport } from './skills/draft-confinement.js';
@@ -55,7 +56,7 @@ import { RemotePolicyError, clampDispatchSpec, getSessionPolicy, readRegisteredP
55
56
  import { validateWorkerReply } from './worker-question.js';
56
57
  import { limitFromText } from '../public/shared/assistant/asst-limit.js';
57
58
  // agents-p1: a dispatch's agent_ref (lib/agents/resolve.js).
58
- import { agentCorrections, agentIntake, carryAgentRun, getAgentResolver, stampAgentRun } from './agents/resolve.js';
59
+ import { agentCorrections, agentIntake, agentPinOf, agentRefOf, routedAgent, carryAgentRun, getAgentResolver, stampAgentRun } from './agents/resolve.js';
59
60
  // Agents P2 (durable agent messaging): run events, typed waits, the follow-up outbox and the transcript on disk.
60
61
  import { createCoordinationService, sharedCoordinationService } from './coordination/service.js';
61
62
  import { createRunWaits } from './assistant-run-wait.js';
@@ -413,6 +414,9 @@ export function createAssistantDispatcher({
413
414
  observeSkillEvent = () => {},
414
415
  completeSkillUsage = () => {},
415
416
  log = () => {},
417
+ // How long the resumes of one start wait for the browser extension, which reconnects by itself after a restart.
418
+ resumeBrowserWaitMs = 90_000,
419
+ resumeBrowserPollMs = 1_000,
416
420
  PACKAGE_ROOT = process.cwd(),
417
421
  findCodexAccount = () => null,
418
422
  getCodexAccount = () => null,
@@ -528,7 +532,7 @@ export function createAssistantDispatcher({
528
532
  const tails = createRunTailStore({ dir: resolve(dataDir, 'run-tails'), log: (tag, detail) => log(null, tag, detail) });
529
533
  // What image / video creation runs generated, and design runs' screenshots: <dataDir>/media/<runId>/<n>-<name>.
530
534
  const mediaRoot = resolve(dataDir, 'media');
531
- // A guarded worker's own scratch folder (lib/worker-confinement.js): <dataDir>/scratch/<runId>, removed when empty.
535
+ // Scratch retention also owns empty folders: an empty directory can still be a process's cwd.
532
536
  const scratchRoot = resolve(dataDir, 'scratch');
533
537
  /** A known task class, else null. */
534
538
  const knownClass = (value) => (Object.prototype.hasOwnProperty.call(TASK_CLASS_META, String(value || '')) ? String(value) : null);
@@ -558,9 +562,9 @@ export function createAssistantDispatcher({
558
562
  // in memory. Now each is a row of the outbox: it survives a restart, keeps its place, is marked sent in the step
559
563
  // that hands it to the run's provider, and the queue refuses more than its bound.
560
564
  /** Queue a follow-up for a run → { id, position }. Throws FOLLOW_UP_QUEUE_FULL (409) at the bound. */
561
- function queueFollowUp(entry, item) {
565
+ async function queueFollowUp(entry, item) {
562
566
  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 });
567
+ return await coordination.followUps.enqueue({ runId: entry.runId, text: item.text, sessionId: entry.assistantSessionId || null, origin: item.origin, taskId: item.taskId, at: item.at });
564
568
  } catch (error) {
565
569
  if (error?.code === 'OUTBOX_FULL') {
566
570
  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 });
@@ -569,28 +573,29 @@ export function createAssistantDispatcher({
569
573
  }
570
574
  }
571
575
  /** 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; }
576
+ async function nextFollowUp(runId) {
577
+ try { return await coordination.followUps.next(runId); } catch { return null; }
574
578
  }
575
579
  function followUpCount(runId) {
576
- try { return coordination.followUps.count(runId); } catch { return 0; }
580
+ try { return coordination.followUps.cachedCount(runId); } catch { return 0; }
577
581
  }
578
582
  /** 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 []; }
583
+ async function cancelFollowUps(runId) {
584
+ try { return await coordination.followUps.cancel(runId); } catch { return []; }
581
585
  }
582
586
  /** After a restart: follow-ups queued for runs that are gone or ended reach nobody. Their run's notes say so. */
583
- function settleOrphanFollowUps() {
587
+ async function settleOrphanFollowUps() {
584
588
  let runIds = [];
585
- try { runIds = coordination.followUps.runs(); } catch { runIds = []; }
589
+ try { runIds = await coordination.followUps.runs(); } catch { runIds = []; }
586
590
  for (const runId of runIds) {
587
591
  const entry = entries.get(runId);
588
592
  if (entry && !TERMINAL_STATES.has(entry.state)) continue;
589
- const dropped = cancelFollowUps(runId);
593
+ const dropped = await cancelFollowUps(runId);
590
594
  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
595
  }
592
596
  }
593
597
  const resumeInProgress = new Set(); // runIds resumeRun works on (they hold their slot; the others waiting do not)
598
+ let resumeBrowserDeadline = 0; // one deadline per start: every run waits for the same extension
594
599
  // The server is going down (suspendForShutdown ran): a resume under way stops where it is, for the next start.
595
600
  let closing = false;
596
601
 
@@ -622,6 +627,7 @@ export function createAssistantDispatcher({
622
627
  entry.tools = []; entry.toolsRequested = [];
623
628
  entry.toolListError = { code: error.code, message: error.message, original: row.tools ?? row.mcpProfile };
624
629
  delete entry.mcpProfile; delete entry.rawSpec;
630
+ delete entry.heldAgent;
625
631
  entry.state = 'failed'; entry.completionReason = 'tools_invalid';
626
632
  }
627
633
  // A failure cause being judged when the server went down is never coming.
@@ -739,7 +745,7 @@ export function createAssistantDispatcher({
739
745
  // The brief goes to the worker's prompt; views name it only. The meters' state stays inside, and so does what a
740
746
  // resume after a restart needs (resumeInfo: the CLI's pid, the turn in progress); `resumes` counts them.
741
747
  // 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;
748
+ const { heldAgent: _heldAgent, rawSpec: _rawSpec, brief: _brief, usageState: _usageState, resumeInfo: _resumeInfo, crashed: _crashed, refusedAtShutdown: _refusedAtShutdown, aliveAt: _aliveAt, teamBrief: _teamBrief, ...rest } = entry;
743
749
  return {
744
750
  ...rest,
745
751
  tools: toolsView({ ...entry, tools: runtimeRun?.tools ?? entry.tools }),
@@ -824,17 +830,25 @@ export function createAssistantDispatcher({
824
830
  }
825
831
 
826
832
  function touch(entry) { entry.version = (Number(entry.version) || 0) + 1; entry.updatedAt = iso(now()); }
827
- function emit(entry, reason, extra = {}) {
833
+ async function emit(entry, reason, extra = {}, transition = null) {
828
834
  touch(entry);
829
- persist({ force: TERMINAL_STATES.has(entry.state) });
830
- const payload = { type: 'assistant:dispatch', reason, run: view(entry), ...extra };
835
+ if (!transition) persist({ force: TERMINAL_STATES.has(entry.state) });
836
+ const payload = { type: 'assistant:dispatch', reason, run: view(transition ? { ...entry, ...transition } : entry), ...extra };
831
837
  // Agents P2: the event goes into the durable log in the step that changed the run, under an id that names it
832
838
  // (recording it again stores nothing), before anyone is told. It never throws: the run goes on either way.
833
- coordination.recordDispatch(payload);
839
+ await coordination.recordDispatch(payload);
840
+ if (transition) {
841
+ Object.assign(entry, transition);
842
+ persist({ force: true });
843
+ }
834
844
  if (['turn_completed', 'idle', 'failed', 'stopped', 'completed'].includes(reason)) { try { completeSkillUsage(entry); } catch {} }
835
845
  try { broadcastSync(payload); } catch {}
836
- for (const listener of listeners) { try { listener(payload); } catch {} }
846
+ const notified = [];
847
+ for (const listener of listeners) { try { notified.push(Promise.resolve(listener(payload)).catch(() => {})); } catch {} }
837
848
  notifyWaiters(entry.runId, reason);
849
+ // A turn can depend on its listeners (e.g. restoring claims). An ended worker can release its slot
850
+ // as soon as its event is recorded and announced, even if a listener is waiting for shutdown.
851
+ if (!TERMINAL_STATES.has(reason)) await Promise.all(notified);
838
852
  }
839
853
 
840
854
  // ── browser route (a run's browser moved while it works) ───────────────────
@@ -895,9 +909,9 @@ export function createAssistantDispatcher({
895
909
  * Agents P2: events a brain read through agent_wait until:"event" are settled in its session's mailbox by their
896
910
  * ids (never a second turn for them). The log keeps them: the same cursor returns them again. → how many.
897
911
  */
898
- function markEventsDelivered(assistantSessionId, eventIds) {
912
+ async function markEventsDelivered(assistantSessionId, eventIds) {
899
913
  if (!assistantSessionId || !Array.isArray(eventIds) || !eventIds.length) return 0;
900
- try { return coordination.mailbox.ack(String(assistantSessionId), eventIds).acked; } catch { return 0; }
914
+ try { return (await coordination.mailbox.ack(String(assistantSessionId), eventIds)).acked; } catch { return 0; }
901
915
  }
902
916
 
903
917
  // ── waiters (Agents P2: lib/assistant-run-wait.js) ─────────────────────────
@@ -921,7 +935,7 @@ export function createAssistantDispatcher({
921
935
  }
922
936
 
923
937
  /** `taskClass`: the run's class (its route's, else the spec's); image / video creation needs a model that makes the medium. */
924
- function normalizeSpec(spec = {}, { catalogValue = null, taskClass = null } = {}) {
938
+ function normalizeSpec(spec = {}, { catalogValue = null, taskClass = null, builtin = false } = {}) {
925
939
  const provider = String(spec.provider || '').trim().toLowerCase();
926
940
  if (!NATIVE_PROVIDERS.has(provider)) throw new DispatchError('INVALID_PROVIDER', `provider must be one of ${[...NATIVE_PROVIDERS].join(', ')}`);
927
941
  const task = String(spec.task || '').trim();
@@ -1032,6 +1046,15 @@ export function createAssistantDispatcher({
1032
1046
  }
1033
1047
  // Image / video creation (the router already routed it to a maker; this is the backstop).
1034
1048
  const medium = requiredOutput(taskClass);
1049
+ if (builtin && taskClass === 'computer') {
1050
+ if (!usesComputer) throw new DispatchError('COMPUTER_UNAVAILABLE', 'The bundled desktop operator needs a desktop grant.', { status: 409 });
1051
+ if (designFit(catalogValue, { kind: 'dispatch', provider, model }) !== 'ok') {
1052
+ throw new DispatchError('COMPUTER_NEEDS_VISION', 'The desktop operator needs an available model confirmed to see images.', { status: 409 });
1053
+ }
1054
+ }
1055
+ if (builtin && medium && !catalogValue) {
1056
+ throw new DispatchError('MODEL_CANNOT_GENERATE', `The model catalog is unavailable to confirm ${medium} generation.`, { status: 409 });
1057
+ }
1035
1058
  if (medium && catalogValue) {
1036
1059
  const row = model ? findModel(catalogValue, provider, model)?.row || null : defaultModelRow(catalogValue, provider);
1037
1060
  if (!rowMakes(row, medium)) {
@@ -1504,6 +1527,35 @@ export function createAssistantDispatcher({
1504
1527
  return true;
1505
1528
  }
1506
1529
 
1530
+ function applyRouteAgent(original, input, route, ctx, pinned = null) {
1531
+ // Scope follows the actual worker folder, including team worktrees. Re-read approval
1532
+ // at dispatch: the route may have been proposed before the project or revision was known.
1533
+ const selected = routedAgent(agents, route.taskClass, input.cwd || input.project || PACKAGE_ROOT, route.agentRequest, pinned);
1534
+ if (!selected.resolved) return { input, note: selected.note };
1535
+ const { provider, model, effort, accountId, codexAccountId, claudeAccountId } = input;
1536
+ const spec = selected.resolver.prepare({
1537
+ ...original, provider, model, effort, accountId, codexAccountId, claudeAccountId,
1538
+ taskClass: route.taskClass,
1539
+ }, selected.resolved, { ...ctx, routed: true, classDefault: route.agentRequest ? null : route.taskClass });
1540
+ // An explicit profile was already resolved before routing. A profile inherited from
1541
+ // the role still needs the dispatcher's normal identity check.
1542
+ if (input.moreloginEnvId) {
1543
+ delete spec.moreloginProfile;
1544
+ delete spec.morelogin_profile;
1545
+ Object.assign(spec, { moreloginEnvId: input.moreloginEnvId, moreloginEnvName: input.moreloginEnvName });
1546
+ }
1547
+ return { input: spec, resolved: selected.resolved };
1548
+ }
1549
+
1550
+ function appliedRoute(route, input, note) {
1551
+ const pin = agentPinOf(input);
1552
+ const { agentRef, agentRevision, agentRequest, agentCorrection, ...rest } = route;
1553
+ const requested = agentRefOf(input) || (pin && !pin.classDefault ? pin.requested : agentRequest);
1554
+ return { ...rest, ...(requested ? { agentRequest: requested } : {}),
1555
+ ...(pin ? { agentRef: pin.ref, agentRevision: pin.revision } : {}),
1556
+ corrections: [...(route.corrections || []).filter(c => c.reason !== 'class_agent_unavailable'), ...(note ? [note] : [])] };
1557
+ }
1558
+
1507
1559
  // agents-p4: `team` (lib/teams/brief.js teamBrief) and `runId` are the team scheduler's own (lib/teams/scheduler.js):
1508
1560
  // the slice a run works and the id its claims were taken under. No request body reaches these options.
1509
1561
  async function dispatch(rawSpec = {}, { assistantSessionId = null, origin = 'assistant', brief: carried = null, notes: callerNotes = null, agentOf = null, team = null, runId: givenRunId = null } = {}) {
@@ -1521,7 +1573,9 @@ export function createAssistantDispatcher({
1521
1573
  // agents-p1: the agent the dispatch names (agent_ref) is applied before anything else reads the spec: what the
1522
1574
  // dispatch says itself wins, the definition fills the rest and never widens it (lib/agents/resolve.js). The very
1523
1575
  // same object comes back for a dispatch that names none.
1524
- rawSpec = agentIntake(agents, rawSpec, { assistantSessionId: sessionId, origin, desktop, resolveExternalTools });
1576
+ const original = rawSpec;
1577
+ const agentContext = { assistantSessionId: sessionId, origin, desktop, resolveExternalTools };
1578
+ rawSpec = agentIntake(agents, rawSpec, agentContext);
1525
1579
  // "true" (a string) is computer use too: normalizeSpec reads it so, and so must the gate.
1526
1580
  rawSpec = { ...rawSpec, usesComputer: rawSpec.usesComputer === true || rawSpec.usesComputer === 'true' };
1527
1581
  // The MoreLogin profile it names for the worker's browser tab, as MoreLogin lists it (refused here when it cannot
@@ -1548,14 +1602,6 @@ export function createAssistantDispatcher({
1548
1602
  // Skills owns the runtime selection and its provider-specific workspace. Never bind Assistant routes.
1549
1603
  if (router && !isSkillsRun(rawSpec) && origin !== 'ui' && sessionId) {
1550
1604
  routed = await router.resolveDispatch({ sessionId, spec: rawSpec, origin, team });
1551
- // A hold names an open card, but an answer that was already in flight (it waited on the same
1552
- // catalog read) can decide that card before this continuation runs. Approved for this
1553
- // session: the dispatch is resolved again with that route_id, so the run starts on it as any
1554
- // dispatch with an approved route does (its validation, the remote clamps and claim, the
1555
- // rails). Declined, cancelled or expired: the attachment below fails and it is refused.
1556
- for (let i = 0; i < 2 && routed?.action === 'hold' && routeApprovedFor(routed.routeId, sessionId); i += 1) {
1557
- routed = { ...(await router.resolveDispatch({ sessionId, spec: { ...rawSpec, routeId: routed.routeId }, origin, team })), approvedMeanwhile: true };
1558
- }
1559
1605
  }
1560
1606
  // A remote session's approved route, claimed by resolveDispatch, is used up only by the run it
1561
1607
  // starts: a dispatch refused before its run exists gives the route back, so retrying the route_id
@@ -1564,7 +1610,26 @@ export function createAssistantDispatcher({
1564
1610
  try {
1565
1611
  // An approved route may have moved it to another provider: clamp for that one
1566
1612
  // (a route approved for design brings design's defaults).
1567
- let input = routed?.spec ? clampRemote(withClassDefaults(routed.spec, knownClass(routed.route?.taskClass)), sessionId, remoteNotes) : rawSpec;
1613
+ let input, agentNote, heldAgent;
1614
+ for (let attempt = 0; ; attempt++) {
1615
+ input = routed?.spec || rawSpec;
1616
+ const route = routed?.route;
1617
+ if (knownClass(route?.taskClass) && !agentPinOf(rawSpec) && !agentRefOf(original) && !agentOf) {
1618
+ const selected = applyRouteAgent(original, input, route, agentContext);
1619
+ input = selected.input.moreloginProfile ? await withBrowserProfile(selected.input) : selected.input;
1620
+ agentNote = selected.note;
1621
+ if (routed.action === 'hold') heldAgent = { input: original, resolved: selected.resolved };
1622
+ }
1623
+ // An in-flight approval may finish during routing or a role's asynchronous profile lookup.
1624
+ // Rebind both the model and the role on the approved route before attaching a waiting run.
1625
+ if (routed?.action !== 'hold' || attempt >= 2 || !routeApprovedFor(routed.routeId, sessionId)) break;
1626
+ routed = { ...(await router.resolveDispatch({ sessionId, spec: { ...rawSpec, routeId: routed.routeId }, origin, team })), approvedMeanwhile: true };
1627
+ }
1628
+ const dispatchRoute = routed?.route;
1629
+ const routeClass = knownClass(dispatchRoute?.taskClass);
1630
+ if (routed?.spec || dispatchRoute) input = clampRemote(withClassDefaults(input, routeClass), sessionId, remoteNotes);
1631
+ if (agentNote) remoteNotes.push(agentNote.text);
1632
+ if (dispatchRoute) routed.route = appliedRoute(dispatchRoute, input, agentNote);
1568
1633
  // UI / callers without an Assistant session bypass the router, but may
1569
1634
  // still ask for Auto. A routed concrete account is never picked again here.
1570
1635
  if (!routed?.route && accountUsage && ['codex', 'claude-code'].includes(input.provider)) {
@@ -1582,8 +1647,12 @@ export function createAssistantDispatcher({
1582
1647
  // A route approved for other work cannot carry image / video creation or design, nor the other way round:
1583
1648
  // the class decides the model's capability check, the worker's media block or rules and what is collected.
1584
1649
  const declaredClass = knownClass(rawSpec.taskClass);
1585
- const routeClass = knownClass(routed?.route?.taskClass);
1586
- if (declaredClass && routeClass && runContract(declaredClass) !== runContract(routeClass)) {
1650
+ const pin = agentPinOf(input) || agentOf?.agentPin;
1651
+ const builtin = pin?.source === 'builtin' || !!pin?.classDefault;
1652
+ const classMismatch = builtin && dispatchRoute
1653
+ ? (declaredClass || knownClass(input.taskClass)) !== routeClass
1654
+ : declaredClass && routeClass && runContract(declaredClass) !== runContract(routeClass);
1655
+ if (classMismatch) {
1587
1656
  throw new DispatchError('ROUTE_CLASS_MISMATCH', `Route ${routed.route.routeId || ''} was approved for ${routeClass} work, but this dispatch says task_class "${declaredClass}". Call agent_route with task_class "${declaredClass}" and dispatch with its route_id.`, { status: 409, routeId: routed.route.routeId || null, routeClass, taskClass: declaredClass });
1588
1657
  }
1589
1658
  // The route's spec (a route_id alone can make it a design dispatch, with design's defaults):
@@ -1591,11 +1660,13 @@ export function createAssistantDispatcher({
1591
1660
  if (routed?.spec) refuseBrowserConflict(input);
1592
1661
  // agents-p4: a team's slices start on a route that is approved already; none waits on a card of its own.
1593
1662
  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 });
1594
- if (routed?.action === 'hold') return holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief, remoteNotes });
1663
+ if (routed?.action === 'hold') {
1664
+ return holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief, remoteNotes, agentNote, heldAgent });
1665
+ }
1595
1666
  // The run's class: its route's (the brain may omit task_class with a route_id), else the spec's.
1596
1667
  // Its capability backstop runs in normalizeSpec on the final target, however that was chosen.
1597
1668
  const taskClass = routeClass || knownClass(input.taskClass);
1598
- const spec = normalizeSpec(input, { catalogValue, taskClass });
1669
+ const spec = normalizeSpec(input, { catalogValue, taskClass, builtin });
1599
1670
  const queuedCount = [...entries.values()].filter((e) => e.state === 'queued' && e.assistantSessionId === sessionId).length;
1600
1671
  if (givenRunId && entries.has(String(givenRunId))) throw new DispatchError('RUN_EXISTS', `Run ${givenRunId} exists already.`, { status: 409 }); // agents-p4
1601
1672
  runId = givenRunId ? String(givenRunId) : randomId();
@@ -1622,7 +1693,7 @@ export function createAssistantDispatcher({
1622
1693
  try { budgetCorrections = await fitBudget(entry, { routed: !!routed?.route }); } catch (error) { entries.delete(runId); throw error; }
1623
1694
  entry.taskId = routed?.route?.taskId || taskAtDispatch(sessionId);
1624
1695
  const launched = await launchOrQueue(entry, spec, { queuedCount, strict: true });
1625
- const corrections = [...budgetCorrections, ...agentCorrections(input)]; // agents-p1: what the agent's definition was held to
1696
+ const corrections = [...budgetCorrections, ...(agentNote ? [agentNote] : []), ...agentCorrections(input)]; // agents-p1: what the agent's definition was held to
1626
1697
  const withCorrections = corrections.length ? { ...launched, corrections } : launched;
1627
1698
  // The route's own "decided" event (it had no run attached) still tells the brain to dispatch.
1628
1699
  return routed?.approvedMeanwhile
@@ -1705,7 +1776,7 @@ export function createAssistantDispatcher({
1705
1776
  }
1706
1777
 
1707
1778
  /** Accept a dispatch the router is holding for the user's model choice. */
1708
- function holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief = null, remoteNotes = [] }) {
1779
+ function holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief = null, remoteNotes = [], agentNote = null, heldAgent = null }) {
1709
1780
  const task = String(input.task || '').trim();
1710
1781
  if (!task) throw new DispatchError('TASK_REQUIRED', 'task is required');
1711
1782
  if (task.length > 20_000) throw new DispatchError('TASK_TOO_LONG', 'task must be at most 20000 characters');
@@ -1725,6 +1796,7 @@ export function createAssistantDispatcher({
1725
1796
  workflowId: input.workflowId ? String(input.workflowId) : null, parentRunId: input.parentRunId ? String(input.parentRunId) : null,
1726
1797
  usesBrowser: !!input.usesBrowser, usesComputer: input.usesComputer === true, capability: normalizeCapability(input.capability || 'full'),
1727
1798
  idempotencyKey, rawSpec: { ...input }, route: routed.route,
1799
+ ...(heldAgent ? { heldAgent } : {}),
1728
1800
  notes: ['awaiting the user\'s model choice on the route card', ...remoteNotes],
1729
1801
  };
1730
1802
  stampAgentRun(entry, input); // agents-p1
@@ -1751,10 +1823,30 @@ export function createAssistantDispatcher({
1751
1823
  emit(entry, 'route_pending', { routeId: routed.routeId });
1752
1824
  return {
1753
1825
  ok: true, queued: true, awaitingRoute: true, routeId: routed.routeId, run: view(entry),
1826
+ ...(agentNote ? { corrections: [agentNote] } : {}),
1754
1827
  next: 'This run is waiting for the user to pick its model on the route card. Do not dispatch it again. It starts automatically after the pick; the decision arrives as a [SynaBun Mailbox] route_decided event. If the user picks "here" instead, this run never starts and that event asks you to do the task yourself.',
1755
1828
  };
1756
1829
  }
1757
1830
 
1831
+ function workerForRoutePick(entry, target, agentRequest) {
1832
+ const runtime = { provider: target.provider, model: target.model || null, effort: target.effort ?? null,
1833
+ accountId: target.accountId || null, codexAccountId: null, claudeAccountId: null };
1834
+ if (!entry.heldAgent) return { input: { ...entry.rawSpec, ...runtime } };
1835
+ // Keep the role pinned while the card is open. The final provider can deliver a different
1836
+ // set of external servers, and the owner can select a proposal with a different agent.
1837
+ const original = entry.heldAgent.input;
1838
+ const sameRole = agentRequest === entry.route?.agentRequest;
1839
+ const route = { ...entry.route, agentRequest };
1840
+ const input = { ...original, ...runtime };
1841
+ if (entry.rawSpec?.moreloginEnvId && (sameRole || original.moreloginProfile || original.morelogin_profile || original.moreloginEnvId || original.morelogin_env_id)) {
1842
+ input.moreloginEnvId = entry.rawSpec.moreloginEnvId;
1843
+ input.moreloginEnvName = entry.rawSpec.moreloginEnvName;
1844
+ }
1845
+ const selected = applyRouteAgent(original, input, route, { assistantSessionId: entry.assistantSessionId,
1846
+ origin: entry.origin, desktop, resolveExternalTools }, sameRole ? entry.heldAgent.resolved : null);
1847
+ return { input: withClassDefaults(selected.input, entry.taskClass), route, note: selected.note };
1848
+ }
1849
+
1758
1850
  /**
1759
1851
  * Why the held run `runId` could not start on `target`, else null: the router's checkHeld, asked
1760
1852
  * before it approves a route card's pick, so a pick resolveRoute would refuse is not approved,
@@ -1762,7 +1854,7 @@ export function createAssistantDispatcher({
1762
1854
  * catalog as it stands: MODEL_CANNOT_SEE, MODEL_UNAVAILABLE) and, for every run, browser
1763
1855
  * settings on that provider (BROWSER_SETTINGS_CONFLICT). Other refusals still come in resolveRoute.
1764
1856
  */
1765
- function heldRouteRefusal(runId, target) {
1857
+ function heldRouteRefusal(runId, target, { agentRequest } = {}) {
1766
1858
  const entry = entries.get(String(runId || ''));
1767
1859
  if (!entry || entry.state !== 'awaiting_route' || !target?.provider) return null;
1768
1860
  const provider = String(target.provider).trim().toLowerCase();
@@ -1771,25 +1863,45 @@ export function createAssistantDispatcher({
1771
1863
  try { catalogValue = catalog?.peek?.() || null; } catch { catalogValue = null; }
1772
1864
  const refusal = designRefusal(catalogValue, provider, model, entry.taskClass || null);
1773
1865
  if (refusal) return refusal;
1866
+ if (entry.heldAgent) {
1867
+ try {
1868
+ const pick = workerForRoutePick(entry, target, agentRequest);
1869
+ const input = clampRemote(pick.input, entry.assistantSessionId);
1870
+ const pin = agentPinOf(input);
1871
+ normalizeSpec(input, { catalogValue, taskClass: entry.taskClass, builtin: pin?.source === 'builtin' || !!pin?.classDefault });
1872
+ return null;
1873
+ } catch (error) { return error; }
1874
+ }
1774
1875
  const conflict = browserSettingsConflict({ ...(entry.rawSpec || {}), provider, model }, provider);
1775
1876
  return conflict ? new DispatchError('BROWSER_SETTINGS_CONFLICT', conflict, { status: 400 }) : null;
1776
1877
  }
1777
1878
 
1778
1879
  /** The user picked a target for a held run: validate, then start or queue it. */
1779
- async function resolveRoute(runId, { target, routeId = null, decidedBy = 'user', remembered = false, optionId = null } = {}) {
1880
+ async function resolveRoute(runId, { target, routeId = null, decidedBy = 'user', remembered = false, optionId = null, agentRequest } = {}) {
1780
1881
  const entry = entries.get(runId);
1781
1882
  if (!entry || entry.state !== 'awaiting_route' || !target?.provider) return { ok: false, code: 'NOT_HELD' };
1782
1883
  const catalogValue = await catalogSnapshot();
1783
- let input = { ...(entry.rawSpec || {}), provider: target.provider, model: target.model || null, effort: target.effort ?? null, accountId: target.accountId || null, codexAccountId: null, claudeAccountId: null };
1784
1884
  let spec;
1785
- // The picked provider may need another clamp (Codex under strict worker approvals), or the level fell meanwhile.
1786
1885
  const remoteNotes = [];
1787
- try { input = clampRemote(input, entry.assistantSessionId, remoteNotes); spec = normalizeSpec(input, { catalogValue, taskClass: entry.taskClass || null }); }
1886
+ try {
1887
+ const pick = workerForRoutePick(entry, target, agentRequest);
1888
+ let input = pick.input.moreloginProfile || pick.input.morelogin_profile ? await withBrowserProfile(pick.input) : pick.input;
1889
+ input = clampRemote(input, entry.assistantSessionId, remoteNotes);
1890
+ const pin = entry.heldAgent ? agentPinOf(input) : entry.agentPin;
1891
+ spec = normalizeSpec(input, { catalogValue, taskClass: entry.taskClass || null, builtin: pin?.source === 'builtin' || !!pin?.classDefault });
1892
+ if (pick.route) {
1893
+ if (entry.agentRef && !pin) Object.assign(entry, { agentRef: null, agentRevision: null, agentPin: null });
1894
+ stampAgentRun(entry, input);
1895
+ entry.route = appliedRoute(pick.route, input, pick.note);
1896
+ if (pick.note) remoteNotes.push(pick.note.text);
1897
+ }
1898
+ }
1788
1899
  catch (error) {
1789
1900
  entry.state = 'failed'; entry.completionReason = 'route_invalid'; entry.finishedAt = iso(now()); entry.turnState = 'terminal';
1790
1901
  entry.error = error?.message || String(error);
1791
1902
  entry.notes.push(`route target rejected: ${entry.error}`);
1792
1903
  delete entry.rawSpec;
1904
+ delete entry.heldAgent;
1793
1905
  emit(entry, 'failed');
1794
1906
  return { ok: false, error };
1795
1907
  }
@@ -1800,6 +1912,7 @@ export function createAssistantDispatcher({
1800
1912
  target: describeTarget(target, { catalog: catalogValue }), decidedAt: iso(now()),
1801
1913
  };
1802
1914
  delete entry.rawSpec;
1915
+ delete entry.heldAgent;
1803
1916
  entry.state = 'queued';
1804
1917
  emit(entry, 'route_decided', { routeId });
1805
1918
  try { return await launchOrQueue(entry, spec); }
@@ -1815,6 +1928,7 @@ export function createAssistantDispatcher({
1815
1928
  entry.route = { ...(entry.route || {}), status, decidedBy: reason === 'route_expired' ? 'timeout' : 'user', decidedAt: iso(now()) };
1816
1929
  if (reason === 'route_here') entry.notes.push('the user chose to do this task here, in the conversation: this worker was not started');
1817
1930
  delete entry.rawSpec;
1931
+ delete entry.heldAgent;
1818
1932
  emit(entry, 'stopped');
1819
1933
  return true;
1820
1934
  }
@@ -2329,15 +2443,24 @@ export function createAssistantDispatcher({
2329
2443
  const waitForFollowUp = () => new Promise((resolveWait) => {
2330
2444
  const finish = (value) => { if (liveState.idleTimer) { clearTimeout(liveState.idleTimer); liveState.idleTimer = null; } liveState.waitResolve = null; resolveWait(value); };
2331
2445
  // 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; }
2334
- if (liveState.abortReason) { finish({ kind: 'abort' }); return; }
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);
2446
+ // Install the wake-up before reading. A commit arriving during that read
2447
+ // triggers another look, without two takes racing for the same oldest row.
2448
+ let reading = false, again = false;
2449
+ const look = async () => {
2450
+ if (reading) { again = true; return; }
2451
+ reading = true;
2452
+ do {
2453
+ again = false;
2454
+ const next = await nextFollowUp(entry.runId);
2455
+ if (liveState.waitResolve !== wake) return;
2456
+ if (next) { finish(next); return; }
2457
+ } while (again);
2458
+ reading = false;
2340
2459
  };
2460
+ const wake = value => value?.kind === 'follow-up' ? look() : finish(value);
2461
+ liveState.waitResolve = wake;
2462
+ if (liveState.abortReason) { finish({ kind: 'abort' }); return; }
2463
+ look();
2341
2464
  liveState.idleTimer = setTimeout(() => finish({ kind: 'timeout' }), entry.idleTimeoutMs);
2342
2465
  liveState.idleTimer.unref?.();
2343
2466
  });
@@ -2361,7 +2484,7 @@ export function createAssistantDispatcher({
2361
2484
  // The work clock runs from here to the turn's end (its result-retry turn included).
2362
2485
  startWork(entry, liveState);
2363
2486
  ctx.setTurnState('running');
2364
- emit(entry, 'turn_started', { turn: turnNumber });
2487
+ await emit(entry, 'turn_started', { turn: turnNumber });
2365
2488
  persist({ force: true });
2366
2489
  // What this turn runs (commands, tool results, edited files): the evidence behind a "done".
2367
2490
  liveState.evidence = createTurnEvidence();
@@ -2369,7 +2492,7 @@ export function createAssistantDispatcher({
2369
2492
  liveState.turnMeteredUsd = 0;
2370
2493
  // A queued follow-up is sent exactly here, as its prompt goes to the provider: a restart from now on continues
2371
2494
  // 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)); } }
2495
+ if (outboxId) { try { await coordination.followUps.markSent([outboxId]); } catch (error) { log(entry.runId, 'assistant:follow-up-error', error?.message || String(error)); } }
2373
2496
  let raw = await inner.runTurn(prompt, { ...meta, turn: turnNumber, outputSchema: entry.outputSchema || undefined });
2374
2497
  if (entry.provider === 'codex') settleCodexTurn(entry, liveState, raw);
2375
2498
  else if (entry.provider === 'antigravity') settleAntigravityTurn(entry, liveState, raw);
@@ -2487,7 +2610,7 @@ export function createAssistantDispatcher({
2487
2610
  // The worker remembers before its ## Result block: this turn's events carry that memory.
2488
2611
  syncMemory(entry);
2489
2612
  if (parsed.status === 'needs_input') emit(entry, 'needs_input', { turn: turnNumber, question: parsed.question });
2490
- emit(entry, 'turn_completed', { turn: turnNumber });
2613
+ await emit(entry, 'turn_completed', { turn: turnNumber });
2491
2614
  announceUnpriced(entry);
2492
2615
  checkSession(entry.assistantSessionId, { source: entry });
2493
2616
  return parsed;
@@ -2509,6 +2632,10 @@ export function createAssistantDispatcher({
2509
2632
  : { origin: 'dispatch' });
2510
2633
  } catch (error) {
2511
2634
  pauseWork(entry, liveState);
2635
+ // The CLI says nothing was saved under this session: the run starts its task again instead of failing.
2636
+ if (resume && entry.provider === 'claude-code' && !entry.resumeInfo?.noConversation && !liveState.abortReason && !liveState.suspending && isMissingConversationError(error)) {
2637
+ return restartWithoutConversation(entry, liveState);
2638
+ }
2512
2639
  return handleTurnError(error, liveState, entry, ctx);
2513
2640
  }
2514
2641
  }
@@ -2529,7 +2656,15 @@ export function createAssistantDispatcher({
2529
2656
  const next = await waitForFollowUp();
2530
2657
  if (liveState.suspending) return { providerSessionId: null };
2531
2658
  if (next.kind === 'abort') { entry.completionReason = entry.completionReason || liveState.abortReason || 'aborted'; return { providerSessionId: inner.identity?.()?.providerSessionId }; }
2532
- if (next.kind === 'complete') { entry.completionReason = next.reason || 'complete'; liveState.completed = true; return { providerSessionId: inner.identity?.()?.providerSessionId }; }
2659
+ if (next.kind === 'complete') {
2660
+ entry.completionReason = next.reason || 'complete';
2661
+ if (next.stopProvenance) {
2662
+ entry.stopProvenance = next.stopProvenance;
2663
+ ctx.noteTabClose?.(next.stopProvenance);
2664
+ }
2665
+ liveState.completed = true;
2666
+ return { providerSessionId: inner.identity?.()?.providerSessionId };
2667
+ }
2533
2668
  if (next.kind === 'timeout') { entry.completionReason = 'idle_timeout'; return { providerSessionId: inner.identity?.()?.providerSessionId }; }
2534
2669
  if (liveState.turnCounter >= entry.maxTurns) {
2535
2670
  entry.completionReason = 'max_turns';
@@ -3333,7 +3468,10 @@ export function createAssistantDispatcher({
3333
3468
  closing = true;
3334
3469
  const kept = [];
3335
3470
  for (const entry of entries.values()) {
3336
- if (!SUSPENDABLE_STATES.has(entry.state)) continue;
3471
+ // Idempotent in its answer too: on a signal the Assistant's handler (shutdown()) gets here before the graceful
3472
+ // shutdown does, and a run left out of `keep` would be stopped by the runtime instead of suspended.
3473
+ if (entry.state === 'suspended' && live.get(entry.runId)?.suspending && !finalizations.has(entry.runId)) { kept.push(entry.runId); continue; }
3474
+ if (!SUSPENDABLE_STATES.has(entry.state) || finalizations.has(entry.runId)) continue;
3337
3475
  const liveState = live.get(entry.runId) || null;
3338
3476
  // Only a run whose worker is up, or whose resume is starting it (its session is known): one still starting for
3339
3477
  // the first time has no session to resume yet.
@@ -3377,6 +3515,32 @@ export function createAssistantDispatcher({
3377
3515
  if (kept.length) persist({ force: true });
3378
3516
  return kept;
3379
3517
  }
3518
+ /**
3519
+ * A resumed Claude Code worker whose session id has no saved conversation (it was cut off before the CLI wrote one):
3520
+ * suspended again and resumed with no session, so it runs its original task from the beginning. Once per run.
3521
+ */
3522
+ async function restartWithoutConversation(entry, liveState) {
3523
+ liveState.suspending = true;
3524
+ liveState.turnOpen = false;
3525
+ stopUsagePolling(liveState);
3526
+ const info = resumeInfoOf(entry);
3527
+ delete info.inFlight;
3528
+ info.noConversation = true;
3529
+ // The attempt that found nothing never ran: it does not count against the run's resumes.
3530
+ entry.resumes = Math.max(0, (Number(entry.resumes) || 0) - 1);
3531
+ entry.state = 'resuming';
3532
+ entry.turnState = 'resuming';
3533
+ entry.notes.push('no conversation was saved before the restart: the run starts its original task again');
3534
+ persist({ force: true });
3535
+ const held = await safeRuntime()?.suspend?.(entry.runId, 'no_saved_conversation');
3536
+ if (held) {
3537
+ setTimeout(() => {
3538
+ if (entry.state !== 'resuming' || closing) return;
3539
+ resumeRun(entry).catch((error) => notResumed(entry, error?.message || String(error)));
3540
+ }, 0);
3541
+ }
3542
+ return { providerSessionId: null };
3543
+ }
3380
3544
  /** Book pending provider usage and save the meter baseline before the process ends. */
3381
3545
  function suspendUsage(entry, liveState) {
3382
3546
  if (entry.provider === 'codex') pollCodex(entry, liveState, { discover: true });
@@ -3460,12 +3624,22 @@ export function createAssistantDispatcher({
3460
3624
  const ids = bootResumes.splice(0)
3461
3625
  .map((runId) => entries.get(runId)).filter((entry) => entry?.state === 'resuming')
3462
3626
  .sort((a, b) => String(a.createdAt || '').localeCompare(String(b.createdAt || '')))
3627
+ // A run that may wait for the browser extension goes after those that need nothing to come back.
3628
+ .sort((a, b) => Number(!!a.usesBrowser) - Number(!!b.usesBrowser))
3463
3629
  .map((entry) => entry.runId);
3464
3630
  // Held for this dispatcher from here on: the runtime's own hold no longer ends them.
3465
3631
  for (const runId of ids) { try { runtime?.keepSuspended?.(runId); } catch { /* ended meanwhile */ } }
3466
3632
  for (const runId of bootInterrupts.splice(0)) {
3467
3633
  const entry = entries.get(runId);
3468
3634
  if (!entry) continue;
3635
+ // Stopped on purpose while the last server went down (after this dispatcher stopped listening): that stop stands.
3636
+ const stoppedRecord = runtime?.get?.(runId);
3637
+ if (stoppedRecord?.status === 'stopped' && stoppedRecord.stopProvenance) {
3638
+ Object.assign(entry, { state: 'stopped', completionReason: stoppedRecord.stoppedReason, stopProvenance: stoppedRecord.stopProvenance });
3639
+ delete entry.resumeRefused;
3640
+ emit(entry, 'stopped');
3641
+ continue;
3642
+ }
3469
3643
  // A CLI a crash left behind goes with the run.
3470
3644
  await endOldProcess(entry);
3471
3645
  try { await runtime?.endSuspended?.(runId, 'server_restart', { error: entry.resumeRefused ? `not resumed: ${entry.resumeRefused}` : null }); } catch { /* not held */ }
@@ -3481,7 +3655,7 @@ export function createAssistantDispatcher({
3481
3655
  const block = railBlock(spec, entry.assistantSessionId, { except: runId });
3482
3656
  if (block) { entry.notes.push(`resume queued: ${block}`); held.push(runId); persist(); continue; }
3483
3657
  // What it threw (a folder that cannot be made, a full disk) ends it, with why: nothing else would.
3484
- try { await resumeRun(entry); } catch (error) { log(runId, 'assistant:resume-error', error?.message || String(error)); notResumed(entry, error?.message || String(error)); }
3658
+ try { await resumeRun(entry); } catch (error) { log(runId, 'assistant:resume-error', error?.message || String(error)); await notResumed(entry, error?.message || String(error)); }
3485
3659
  }
3486
3660
  if (held.length) { queue.unshift(...held); processQueue().catch(() => {}); }
3487
3661
  }
@@ -3502,26 +3676,30 @@ export function createAssistantDispatcher({
3502
3676
  async function continueRun(entry) {
3503
3677
  if (closing) return null;
3504
3678
  const runtime = safeRuntime();
3505
- if (!runtime?.resume) return notResumed(entry, 'the native loop runtime is not available');
3679
+ if (!runtime?.resume) return await notResumed(entry, 'the native loop runtime is not available');
3680
+ // Its record ended while the last server went down (a deliberate stop after this dispatcher stopped listening):
3681
+ // that end stands, with who asked for it.
3682
+ const endedRecord = runtime.get?.(entry.runId);
3683
+ if (endedRecord && TERMINAL_STATES.has(endedRecord.status)) { await finalize(entry, endedRecord); return null; }
3506
3684
  refreshLimits();
3507
3685
  const refusal = resumeRefusal(entry, { now: now(), workLeftMs: workLeftMs(entry), isDirectory, accountUnusable: providerAccountUnusable });
3508
- if (refusal) return notResumed(entry, refusal);
3509
- try { await fitBudget(entry, { routed: true }); } catch (error) { return notResumed(entry, `the budget does not allow it (${error?.message || error})`); }
3686
+ if (refusal) return await notResumed(entry, refusal);
3687
+ try { await fitBudget(entry, { routed: true }); } catch (error) { return await notResumed(entry, `the budget does not allow it (${error?.message || error})`); }
3510
3688
  if (entry.state !== 'resuming' || closing) return null; // stopped meanwhile, or the server is going down again
3511
3689
  // Its own ceiling (budget_usd), with what its cut-off turn was booked at the suspension (fitBudget checks the
3512
3690
  // session and the share only): a run out of money is not resumed, as a turn that ends out of money does not idle.
3513
3691
  const spentOut = budgetBlock(entry);
3514
3692
  if (spentOut && spentOut.code !== 'BUDGET_SHARE_EXHAUSTED') {
3515
3693
  entry.completionReason = spentOut.reason;
3516
- return notResumed(entry, `the budget does not allow it (${spentOut.message})`);
3694
+ return await notResumed(entry, `the budget does not allow it (${spentOut.message})`);
3517
3695
  }
3518
- if (!runtime.isSuspended?.(entry.runId)) return notResumed(entry, 'its runtime record is gone');
3696
+ if (!runtime.isSuspended?.(entry.runId)) return await notResumed(entry, 'its runtime record is gone');
3519
3697
  // A crash ended no process: the CLI the run had may still be there, finishing the cut-off tool call. It is ended
3520
3698
  // first; one that cannot be checked keeps the run from resuming (two processes on one session would both write its
3521
3699
  // transcript).
3522
3700
  const orphan = await endOldProcess(entry);
3523
3701
  if (orphan.state === 'unknown' || orphan.state === 'still_running') {
3524
- return notResumed(entry, `its old ${providerName(entry.provider)} process (pid ${orphan.pid}) ${orphan.state === 'unknown' ? 'may still be running and could not be checked' : 'did not stop'}`);
3702
+ return await notResumed(entry, `its old ${providerName(entry.provider)} process (pid ${orphan.pid}) ${orphan.state === 'unknown' ? 'may still be running and could not be checked' : 'did not stop'}`);
3525
3703
  }
3526
3704
  if (entry.state !== 'resuming' || closing) return null;
3527
3705
  const costBaseUsd = entry.provider === 'claude-code' ? rebaseClaudeUsage(entry) : 0;
@@ -3531,8 +3709,9 @@ export function createAssistantDispatcher({
3531
3709
  let browserTabId = null;
3532
3710
  if (entry.usesBrowser && typeof acquireLoopBrowserAndTab === 'function') {
3533
3711
  pinEntryBrowserProfile(entry);
3534
- const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId: entry.requestedBrowserSessionId, terminalSessionId: entry.runId, logTag: 'assistant:browser' }).catch((error) => ({ error: error?.message || String(error) }));
3535
- if (acq?.error) return notResumed(entry, `no browser tab: ${acq.error}`);
3712
+ const acq = await acquireResumeBrowser(entry);
3713
+ if (acq?.cancelled) return null;
3714
+ if (acq?.error) return await notResumed(entry, `no browser tab: ${acq.error}`);
3536
3715
  browserSessionId = acq.browserSessionId || null;
3537
3716
  browserTabId = acq.browserTabId || null;
3538
3717
  }
@@ -3545,7 +3724,9 @@ export function createAssistantDispatcher({
3545
3724
  if (entry.scratchDir) { try { mkdirSync(entry.scratchDir, { recursive: true }); } catch { /* the guard says so when it needs it */ } }
3546
3725
  const inFlight = entry.resumeInfo?.inFlight || null;
3547
3726
  const turned = lastTurnNumber(entry);
3548
- const mode = inFlight ? 'mid_turn' : turned > 0 ? 'idle' : 'fresh';
3727
+ // Nothing was saved under its session (restartWithoutConversation): its task runs from the beginning, in a new one.
3728
+ const noConversation = !!entry.resumeInfo?.noConversation;
3729
+ const mode = noConversation ? 'fresh' : inFlight ? 'mid_turn' : turned > 0 ? 'idle' : 'fresh';
3549
3730
  const liveState = newLiveState(entry);
3550
3731
  liveState.turnCounter = turned;
3551
3732
  liveState.resume = { mode, taskId: inFlight?.taskId || null };
@@ -3557,7 +3738,7 @@ export function createAssistantDispatcher({
3557
3738
  const state = runState(entry, {
3558
3739
  browserSessionId, browserTabId, desktopGrant,
3559
3740
  startedAt: entry.startedAt || iso(now()),
3560
- extra: { resumeSessionId: entry.providerSessionId, resumeThreadId: entry.providerThreadId, costBaseUsd, resumingWorker: true, antigravityHome: entry.resumeInfo?.antigravityHome || null },
3741
+ extra: { resumeSessionId: noConversation ? null : entry.providerSessionId, resumeThreadId: entry.providerThreadId, costBaseUsd, resumingWorker: true, antigravityHome: entry.resumeInfo?.antigravityHome || null },
3561
3742
  });
3562
3743
  // The CLI's spend stop (--max-budget-usd) counts from the total the resumed CLI restores (costBaseUsd): what the run
3563
3744
  // may still spend (its ceiling less what it spent, never more than the session has left) goes on top of that. A
@@ -3593,7 +3774,7 @@ export function createAssistantDispatcher({
3593
3774
  // The runtime ended its record (resume_failed): its run-stopped event ended the run here too.
3594
3775
  const why = error?.message || String(error);
3595
3776
  if (browserSessionId) await releaseSharedBrowserTab(browserSessionId, entry.runId).catch(() => {});
3596
- if (!TERMINAL_STATES.has(entry.state)) return notResumed(entry, why);
3777
+ if (!TERMINAL_STATES.has(entry.state)) return await notResumed(entry, why);
3597
3778
  entry.notes.push(`not resumed: ${why}`);
3598
3779
  persist();
3599
3780
  return null;
@@ -3608,6 +3789,23 @@ export function createAssistantDispatcher({
3608
3789
  reconcileKeepAwake();
3609
3790
  return view(entry);
3610
3791
  }
3792
+ /**
3793
+ * A browser tab for a resuming run. The extension reconnects by itself a moment after the server is back, so "not
3794
+ * connected" is waited out up to this start's deadline; any other answer is final. → the acquisition, { error }, or
3795
+ * { cancelled } when the run was stopped or the server began to go down during the wait.
3796
+ */
3797
+ async function acquireResumeBrowser(entry) {
3798
+ if (!resumeBrowserDeadline) resumeBrowserDeadline = now() + resumeBrowserWaitMs;
3799
+ for (;;) {
3800
+ const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId: entry.requestedBrowserSessionId, terminalSessionId: entry.runId, logTag: 'assistant:browser' }).catch((error) => ({ error: error?.message || String(error) }));
3801
+ if (!/EXTENSION_NOT_CONNECTED/.test(String(acq?.error || ''))) return acq;
3802
+ if (entry.state !== 'resuming' || closing) return { cancelled: true };
3803
+ const left = resumeBrowserDeadline - now();
3804
+ if (left <= 0) return { error: `the browser extension did not reconnect within ${Math.round(resumeBrowserWaitMs / 1000)} seconds of the restart` };
3805
+ await new Promise((done) => { const timer = setTimeout(done, Math.min(left, resumeBrowserPollMs)); timer.unref?.(); });
3806
+ if (entry.state !== 'resuming' || closing) return { cancelled: true };
3807
+ }
3808
+ }
3611
3809
  /**
3612
3810
  * The CLI a run had before a crash may still be there, finishing its cut-off tool call (a crash ends no process): it
3613
3811
  * is ended once its command line shows it is this run's (lib/worker-resume.js endOrphanProcess), before a resume and
@@ -3626,12 +3824,12 @@ export function createAssistantDispatcher({
3626
3824
  return { ...orphan, pid };
3627
3825
  }
3628
3826
  /** A run that could not be resumed after a restart ends as interrupted, with why (its notes, its error, its event). */
3629
- function notResumed(entry, why) {
3827
+ async function notResumed(entry, why) {
3630
3828
  if (TERMINAL_STATES.has(entry.state)) return null;
3631
3829
  const index = queue.indexOf(entry.runId);
3632
3830
  if (index !== -1) queue.splice(index, 1);
3633
3831
  // Follow-ups accepted for it while it was away (agent_send) reach nobody: its end says so, with the first of them.
3634
- const waiting = cancelFollowUps(entry.runId);
3832
+ const waiting = await cancelFollowUps(entry.runId);
3635
3833
  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)}")` : '';
3636
3834
  // Nothing of it may go on: a CLI a crash left behind is ended too.
3637
3835
  endOldProcess(entry).then(() => persist()).catch(() => {});
@@ -3643,7 +3841,7 @@ export function createAssistantDispatcher({
3643
3841
  try { ended = !!safeRuntime()?.isSuspended?.(entry.runId); } catch { ended = false; }
3644
3842
  // The runtime's run-stopped event finalizes the run here (onRuntimeMessage); without a record it is done here.
3645
3843
  if (ended) safeRuntime().endSuspended(entry.runId, 'server_restart', { error }).catch(() => {});
3646
- if (!TERMINAL_STATES.has(entry.state)) finalize(entry, { status: 'interrupted', stoppedReason: 'server_restart', error });
3844
+ if (!TERMINAL_STATES.has(entry.state)) await finalize(entry, { status: 'interrupted', stoppedReason: 'server_restart', error });
3647
3845
  return null;
3648
3846
  }
3649
3847
 
@@ -3658,7 +3856,7 @@ export function createAssistantDispatcher({
3658
3856
  const message = String(text || '').trim();
3659
3857
  if (!message) throw new DispatchError('MESSAGE_REQUIRED', 'text is required');
3660
3858
  if (message.length > 20_000) throw new DispatchError('MESSAGE_TOO_LONG', 'text must be at most 20000 characters');
3661
- if (TERMINAL_STATES.has(entry.state)) throw new DispatchError('RUN_NOT_ACTIVE', `Run ${runId} is ${entry.state}; dispatch a new run with the previous result as context.`, { status: 409, resumable: false });
3859
+ if (TERMINAL_STATES.has(entry.state) || finalizations.has(runId)) throw new DispatchError('RUN_NOT_ACTIVE', `Run ${runId} is ${TERMINAL_STATES.has(entry.state) ? entry.state : 'finishing'}; dispatch a new run with the previous result as context.`, { status: 409, resumable: false });
3662
3860
  if (entry.state === 'queued') throw new DispatchError('RUN_NOT_STARTED', `Run ${runId} is still queued`, { status: 409 });
3663
3861
  // Away for a server restart (suspended, or being resumed): the follow-up waits for the run and goes to it after
3664
3862
  // its resume, like a follow-up queued behind a turn. Should the run not resume, it ends and says why.
@@ -3684,23 +3882,24 @@ export function createAssistantDispatcher({
3684
3882
  const item = { kind: 'follow-up', text: message, origin, at: iso(now()), taskId: taskNow(entry.assistantSessionId) || entry.taskId || null };
3685
3883
  // Every follow-up goes through the outbox (Agents P2), also one an idle run takes at once: the queue is one, in
3686
3884
  // order, and what it holds outlives a restart.
3687
- const idle = !away && !!liveState.waitResolve;
3885
+ const idle = !away && !!liveState.waitResolve && !followUpCount(runId);
3688
3886
  if (!idle && !allowQueue) {
3689
3887
  throw new DispatchError('TURN_ACTIVE', away
3690
3888
  ? `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
3889
  : `Run ${runId} is busy; retry when idle or pass queue:true`, { status: 409 });
3692
3890
  }
3693
- const queued = queueFollowUp(entry, item);
3694
- if (origin === 'user') emit(entry, 'user_intervened', { text: clip(message, 200) });
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) };
3698
- }
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
- };
3891
+ return queueFollowUp(entry, item).then(queued => {
3892
+ if (origin === 'user') emit(entry, 'user_intervened', { text: clip(message, 200) });
3893
+ liveState?.waitResolve?.({ kind: 'follow-up' });
3894
+ if (idle) {
3895
+ return { ok: true, queued: false, turn: liveState.turnCounter + 1, followUpId: queued.id, run: view(entry) };
3896
+ }
3897
+ emit(entry, 'follow_up_queued', { queued: queued.position });
3898
+ return {
3899
+ ok: true, queued: true, position: queued.position, followUpId: queued.id, run: view(entry),
3900
+ ...(away ? { note: 'The run resumes after the server restart; this follow-up goes to it then.' } : {}),
3901
+ };
3902
+ });
3704
3903
  }
3705
3904
  /**
3706
3905
  * Before a follow-up: when the run's provider share is used up, the session's unspent budget is
@@ -3714,12 +3913,12 @@ export function createAssistantDispatcher({
3714
3913
  if (blocked?.code !== 'BUDGET_SHARE_EXHAUSTED') return !blocked;
3715
3914
  return coverShare(entry);
3716
3915
  }
3717
- function complete(runId, { reason = 'complete' } = {}) {
3916
+ function complete(runId, { reason = 'complete', stopProvenance = null } = {}) {
3718
3917
  const entry = requireEntry(runId);
3719
3918
  const liveState = live.get(runId);
3720
3919
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, run: view(entry) };
3721
- if (liveState?.waitResolve) { liveState.waitResolve({ kind: 'complete', reason }); return { ok: true, run: view(entry) }; }
3722
- return stop(runId, reason);
3920
+ if (liveState?.waitResolve) { liveState.waitResolve({ kind: 'complete', reason, stopProvenance }); return { ok: true, run: view(entry) }; }
3921
+ return stop(runId, reason, stopProvenance);
3723
3922
  }
3724
3923
  /**
3725
3924
  * The user closed the sidepanel tab of a worker that reported its task done
@@ -3730,60 +3929,96 @@ export function createAssistantDispatcher({
3730
3929
  * the tab then stops it as its X always did. A run that already ended is
3731
3930
  * left as it is.
3732
3931
  */
3733
- function completeClosedTab(runId) {
3932
+ function completeClosedTab(runId, stopProvenance = null) {
3734
3933
  const entry = requireEntry(runId);
3735
3934
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, completed: false, alreadyTerminal: true, run: view(entry) };
3736
3935
  if (!finishedIdle(entry, { outcomes: ['done'] }) || !live.get(runId)?.waitResolve) {
3737
3936
  const outcome = entry.lastResult?.status || null;
3738
3937
  throw new DispatchError('RUN_NOT_FINISHED', `Run ${runId} is ${entry.state}${outcome ? ` (last result: ${outcome})` : ''}: closing its tab completes only a worker that reported its task done and waits for a follow-up.`, { status: 409, state: entry.state, outcome });
3739
3938
  }
3740
- return { ...complete(runId, { reason: 'tab_closed' }), completed: true };
3939
+ return { ...complete(runId, { reason: 'tab_closed', stopProvenance: stopProvenance ? stampStopProvenance('tab_closed', stopProvenance, iso(now())) : null }), completed: true };
3741
3940
  }
3742
- async function stop(runId, reason = 'assistant') {
3941
+ async function stop(runId, reason = 'unknown', stopProvenance = null) {
3743
3942
  const entry = requireEntry(runId);
3943
+ if (!TERMINAL_STATES.has(entry.state) && finalizations.has(runId)) await finalizations.get(runId);
3944
+ const provenance = stampStopProvenance(reason, stopProvenance, iso(now()));
3744
3945
  if (WAITING_STATES.has(entry.state)) {
3745
3946
  const held = entry.state === 'awaiting_route';
3746
3947
  const index = queue.indexOf(runId);
3747
3948
  if (index !== -1) queue.splice(index, 1);
3949
+ entry.stopProvenance = provenance;
3748
3950
  entry.state = 'stopped'; entry.completionReason = reason; entry.finishedAt = iso(now()); entry.turnState = 'terminal';
3749
3951
  delete entry.rawSpec;
3952
+ delete entry.heldAgent;
3750
3953
  if (held) { try { router?.cancelForRun?.(runId, 'run_stopped'); } catch {} }
3751
3954
  emit(entry, 'stopped');
3752
3955
  return { ok: true, run: view(entry) };
3753
3956
  }
3754
3957
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, run: view(entry), alreadyTerminal: true };
3755
- entry.completionReason = entry.completionReason || reason;
3756
3958
  // A run waiting for its resume after a restart leaves the queue and drops the follow-ups that waited for it; its
3757
3959
  // runtime record (suspended) ends as stopped.
3758
3960
  if (entry.state === 'resuming' || entry.state === 'suspended') {
3961
+ // Its old process, a page reacting to the restart or an unidentified caller never ends it (lib/worker-stop.js).
3962
+ if (!mayEndSuspendedRun(provenance)) {
3963
+ log(runId, 'assistant:stop-refused', 'a suspended run stays suspended: this caller may not end it', { reason, stopProvenance: provenance });
3964
+ throw new DispatchError('RUN_SUSPENDED', `Run ${runId} is ${entry.state === 'suspended' ? 'suspended for a server restart' : 'being resumed after a server restart'} and continues by itself; only a deliberate stop ends it.`, { status: 409, state: entry.state });
3965
+ }
3759
3966
  const index = queue.indexOf(runId);
3760
3967
  if (index !== -1) queue.splice(index, 1);
3761
- cancelFollowUps(runId);
3968
+ await cancelFollowUps(runId);
3762
3969
  // A CLI a crash left behind (this start has not ended it yet) goes with the run.
3763
3970
  if (entry.state === 'resuming') await endOldProcess(entry);
3764
3971
  }
3765
3972
  const runtime = safeRuntime();
3766
- const stopped = runtime ? await runtime.stop(runId, reason) : false;
3767
- if (!stopped) finalize(entry, { status: 'stopped', stoppedReason: reason });
3973
+ const stopped = runtime ? await runtime.stop(runId, reason, { stopProvenance: provenance }) : false;
3974
+ if (!stopped) {
3975
+ // Another stop can win while it is disposing the adapter. Keep its action and caller.
3976
+ const winner = runtime?.get?.(runId);
3977
+ await finalize(entry, TERMINAL_STATES.has(winner?.status) ? winner : { status: 'stopped', stoppedReason: reason, stopProvenance: provenance });
3978
+ } else if (!TERMINAL_STATES.has(entry.state)) {
3979
+ // During a shutdown this dispatcher no longer hears the runtime: the stop is recorded here.
3980
+ await finalize(entry, runtime.get?.(runId) || { status: 'stopped', stoppedReason: reason, stopProvenance: provenance });
3981
+ }
3768
3982
  return { ok: true, run: view(entry) };
3769
3983
  }
3770
- async function killAll({ assistantSessionId = null, workflowId = null, reason = 'kill_all' } = {}) {
3984
+ async function killAll({ assistantSessionId = null, workflowId = null, reason = 'kill_all', stopProvenance = null } = {}) {
3771
3985
  const targets = [...entries.values()].filter((entry) => ACTIVE_STATES.has(entry.state)
3772
3986
  && (!assistantSessionId || entry.assistantSessionId === assistantSessionId)
3773
3987
  && (!workflowId || entry.workflowId === workflowId));
3774
3988
  const stopped = [];
3775
- for (const entry of targets) { try { await stop(entry.runId, reason); stopped.push(entry.runId); } catch {} }
3989
+ for (const entry of targets) { try { await stop(entry.runId, reason, stopProvenance); stopped.push(entry.runId); } catch {} }
3776
3990
  return { ok: true, stopped };
3777
3991
  }
3778
3992
 
3779
3993
  // ── runtime feed → registry ────────────────────────────────────────────────
3994
+ // Native runtime notifications do not await subscribers. Keep terminal events
3995
+ // admitted through their outbox cancellation before closing the shared store.
3996
+ const finalizations = new Map();
3780
3997
  function finalize(entry, runtimeRun) {
3998
+ if (finalizations.has(entry.runId)) return finalizations.get(entry.runId);
3999
+ if (TERMINAL_STATES.has(entry.state)) return Promise.resolve();
4000
+ // Reserve the run before cleanup: settling a pending permission can synchronously notify us again.
4001
+ const work = Promise.resolve().then(() => finalizeRun(entry, runtimeRun));
4002
+ finalizations.set(entry.runId, work);
4003
+ const settled = () => finalizations.delete(entry.runId);
4004
+ work.then(settled, settled);
4005
+ return work;
4006
+ }
4007
+ async function drainFinalizations() {
4008
+ if (!finalizations.size) return;
4009
+ let timer;
4010
+ try {
4011
+ await Promise.race([
4012
+ Promise.all(finalizations.values()),
4013
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Timed out draining terminal run events')), 8000); }),
4014
+ ]);
4015
+ } finally { clearTimeout(timer); }
4016
+ }
4017
+ async function finalizeRun(entry, runtimeRun) {
3781
4018
  if (TERMINAL_STATES.has(entry.state)) return;
3782
4019
  const liveState = live.get(entry.runId);
3783
4020
  // 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);
4021
+ const cancelled = cancelFollowUps(entry.runId);
3787
4022
  // What its transcript showed last stays readable (agent_read format "tail") after the worker is gone.
3788
4023
  if (liveState) tails.flush(entry.runId, liveState.ring);
3789
4024
  pauseWork(entry, liveState);
@@ -3793,10 +4028,18 @@ export function createAssistantDispatcher({
3793
4028
  if (status === 'stopped' && liveState?.completed && /^state_(removed|inactive)$/.test(String(runtimeRun?.stoppedReason || ''))) status = 'completed';
3794
4029
  // A Claude Code worker the shutdown could not suspend (suspendForShutdown) ends interrupted, with why.
3795
4030
  if (status === 'stopped' && entry.refusedAtShutdown) status = 'interrupted';
3796
- entry.state = TERMINAL_STATES.has(status) ? status : 'completed';
3797
- entry.turnState = 'terminal';
3798
- entry.finishedAt = iso(now());
4031
+ const terminal = { state: TERMINAL_STATES.has(status) ? status : 'completed', turnState: 'terminal', finishedAt: iso(now()) };
4032
+ // agent_wait reads this entry directly, and a registry flush can happen at any await.
4033
+ // Stage a successful completion until its log write returns. Failures can be visible while their cause is judged.
4034
+ const completion = terminal.state === 'completed' ? terminal : null;
4035
+ if (!completion) Object.assign(entry, terminal);
3799
4036
  entry.completionReason = entry.completionReason || runtimeRun?.stoppedReason || (status === 'completed' ? 'complete' : status);
4037
+ if (runtimeRun?.stopProvenance) entry.stopProvenance = runtimeRun.stopProvenance;
4038
+ else if (!entry.stopProvenance) {
4039
+ // A limit that ended it from inside its turn loop (idle timeout, max turns) has no stop call to carry this.
4040
+ const system = systemStopProvenance(entry.completionReason);
4041
+ if (system) entry.stopProvenance = stampStopProvenance(entry.completionReason, system, terminal.finishedAt);
4042
+ }
3800
4043
  if (runtimeRun?.error) entry.error = runtimeRun.error;
3801
4044
  try { finishUsage(entry, liveState || null); } catch (error) { log(entry.runId, 'assistant:meter-error', error?.message || String(error)); }
3802
4045
  if (liveState) {
@@ -3807,19 +4050,20 @@ export function createAssistantDispatcher({
3807
4050
  }
3808
4051
  entry.pending = [];
3809
4052
  releaseDesktop(entry);
3810
- // The run's scratch folder goes when it left nothing there (what it wrote is the user's to look at).
3811
- if (entry.scratchDir) { try { rmdirSync(entry.scratchDir); } catch { /* not empty, or already gone */ } }
3812
4053
  // A run that ended gives back what it did not spend: the session's split is made again (debounced).
3813
4054
  if (entry.assistantSessionId) { try { budget.onRunEnded(entry.assistantSessionId); } catch { /* the split stays as it is */ } }
4055
+ const unsent = await cancelled;
4056
+ 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;
4057
+ if (undelivered) entry.notes.push(undelivered);
3814
4058
  if (entry.state === 'failed' && !budgetStopReason(entry.completionReason) && judge?.workerOutcome && !isEvalRun(entry)) {
3815
4059
  // State, queue and desktop move on now; the 'failed' event waits for its cause.
3816
- emitFailed(entry, liveState?.evidence || null);
4060
+ const failed = emitFailed(entry, liveState?.evidence || null);
3817
4061
  processQueue().catch(() => {});
3818
- return;
4062
+ return failed;
3819
4063
  }
3820
- if (entry.state === 'failed' || entry.lastResult?.status === 'blocked') { noteLimit(entry); entry.escalation = computeEscalation(entry); }
4064
+ if (entry.state === 'failed' || entry.lastResult?.status === 'blocked') { noteLimit(entry); entry.escalation = computeEscalation(entry, terminal.state); }
3821
4065
  // 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 } : {});
4066
+ await emit(entry, terminal.state, undelivered ? { text: undelivered } : {}, completion);
3823
4067
  // A memory already stored for the run (by the worker or the brain) is the run's memory.
3824
4068
  // An evaluation run (lib/skills/evals.js) is a measurement, not work to remember: it stores no memory.
3825
4069
  if (memory?.rememberDispatch && !isEvalRun(entry) && !syncMemory(entry, { announce: true }) && (entry.state === 'completed' || (entry.state === 'stopped' && entry.lastResult))) {
@@ -3886,7 +4130,7 @@ export function createAssistantDispatcher({
3886
4130
  if (calls.size > 200) calls.delete(calls.keys().next().value);
3887
4131
  return { ...payload, event: call };
3888
4132
  }
3889
- function onRuntimeMessage(message) {
4133
+ async function onRuntimeMessage(message) {
3890
4134
  const runId = message?.run?.runId;
3891
4135
  if (!runId || !entries.has(runId)) return;
3892
4136
  const entry = entries.get(runId);
@@ -3907,11 +4151,11 @@ export function createAssistantDispatcher({
3907
4151
  // Antigravity streams each message in small chunks: one transcript line per message, grown as it streams.
3908
4152
  if (entry.provider === 'antigravity' && message.event?.eventType === 'agent_message_chunk') { growMessageLine(liveState, message.event.event); return; }
3909
4153
  const summary = summarizeProviderEvent(entry.provider === 'antigravity' ? withAcpCall(liveState, message.event || {}) : message.event || {});
3910
- // A guard decision (lib/worker-confinement.js) is also a note of the run: what was refused or warned about,
3911
- // with its reason, so the brain and the panel see it without the transcript. The first twenty.
4154
+ // A guard decision (lib/worker-confinement.js) is also a note of the run: what was refused, warned about or
4155
+ // noted after it ran, with its reason, so the brain and the panel see it without the transcript. The first twenty.
3912
4156
  if ((message.event?.eventType || message.event?.event?.type) === 'synabun.confinement') {
3913
4157
  const count = (liveState.guardEvents = (liveState.guardEvents || 0) + 1);
3914
- if (count <= 20) entry.notes.push(`guard ${message.event.event?.action || 'refused'}: ${clip(summary, 300)}`);
4158
+ if (count <= 20) entry.notes.push(summary.startsWith('guard ') ? clip(summary, 300) : `guard ${message.event.event?.action || 'refused'}: ${clip(summary, 300)}`);
3915
4159
  else if (count === 21) entry.notes.push('guard: more decisions follow in the transcript');
3916
4160
  }
3917
4161
  if (summary) pushRingLine(liveState, `${iso(now()).slice(11, 19)} ${summary}`);
@@ -3932,7 +4176,11 @@ export function createAssistantDispatcher({
3932
4176
  const newIdentity = (run.providerSessionId && run.providerSessionId !== entry.providerSessionId)
3933
4177
  || (run.providerThreadId && run.providerThreadId !== entry.providerThreadId)
3934
4178
  || (run.antigravityHome && run.antigravityHome !== entry.antigravityHome);
3935
- if (run.providerSessionId) entry.providerSessionId = run.providerSessionId;
4179
+ if (run.providerSessionId) {
4180
+ // The restart without a saved conversation has its new session: a later restart resumes that one.
4181
+ if (entry.resumeInfo?.noConversation && run.providerSessionId !== entry.providerSessionId) delete entry.resumeInfo.noConversation;
4182
+ entry.providerSessionId = run.providerSessionId;
4183
+ }
3936
4184
  if (run.providerThreadId) entry.providerThreadId = run.providerThreadId;
3937
4185
  if (run.antigravityHome) entry.antigravityHome = run.antigravityHome;
3938
4186
  if (newIdentity) persist({ force: true });
@@ -3943,7 +4191,7 @@ export function createAssistantDispatcher({
3943
4191
  return;
3944
4192
  }
3945
4193
  if (['sidepanel:run-completed', 'sidepanel:run-failed', 'sidepanel:run-stopped'].includes(message.type) || TERMINAL_STATES.has(run.status)) {
3946
- finalize(entry, run);
4194
+ await finalize(entry, run);
3947
4195
  }
3948
4196
  }
3949
4197
  function attachRuntime() {
@@ -3963,7 +4211,7 @@ export function createAssistantDispatcher({
3963
4211
  const spec = { provider: entry.provider, accountId: entry.accountId, workflowId: entry.workflowId, usesComputer: !!entry.usesComputer };
3964
4212
  if (railBlock(spec, entry.assistantSessionId, resuming ? { except: runId } : {})) continue;
3965
4213
  queue.splice(queue.indexOf(runId), 1);
3966
- if (resuming) { try { await resumeRun(entry); } catch (error) { notResumed(entry, error?.message || String(error)); } continue; }
4214
+ if (resuming) { try { await resumeRun(entry); } catch (error) { await notResumed(entry, error?.message || String(error)); } continue; }
3967
4215
  try { await start(entry); emit(entry, 'queue_started'); } catch (error) { entry.notes.push(`queue start failed: ${error?.message || error}`); }
3968
4216
  }
3969
4217
  }
@@ -4010,6 +4258,13 @@ export function createAssistantDispatcher({
4010
4258
  function teamRuns(teamId, workflowId) {
4011
4259
  return [...entries.values()].filter(entry => entry.teamId === teamId || entry.team?.teamId === teamId || entry.workflowId === workflowId).map(entry => view(entry));
4012
4260
  }
4261
+ // Approved work can still be queued when its route is replaced. Held runs belong to the pending card.
4262
+ function activeRouteRuns(sessionId, routeId) {
4263
+ return [...entries.values()]
4264
+ .filter(entry => entry.assistantSessionId === sessionId && entry.route?.routeId === routeId
4265
+ && ACTIVE_STATES.has(entry.state) && entry.state !== 'awaiting_route')
4266
+ .map(({ runId, title, state }) => ({ runId, title, state }));
4267
+ }
4013
4268
  function totals({ assistantSessionId = null, workflowId = null } = {}) {
4014
4269
  const rows = [...entries.values()].filter((entry) => (!assistantSessionId || entry.assistantSessionId === assistantSessionId) && (!workflowId || entry.workflowId === workflowId));
4015
4270
  // tokens: the five classes plus total, from the runs' ledger views (a run without one counts its legacy input / output).
@@ -4150,12 +4405,14 @@ export function createAssistantDispatcher({
4150
4405
  // what is left). A run waiting for its resume stays as it is, for the next start.
4151
4406
  suspendForShutdown(reason);
4152
4407
  for (const entry of entries.values()) {
4408
+ if (finalizations.has(entry.runId)) continue;
4153
4409
  if (entry.state === 'suspended') { signalWorkerProcess(entry); continue; }
4154
4410
  if (entry.state === 'resuming') continue;
4155
4411
  if (ACTIVE_STATES.has(entry.state)) {
4156
4412
  pauseWork(entry);
4157
4413
  entry.state = 'interrupted'; entry.completionReason = reason; entry.finishedAt = iso(now()); entry.turnState = 'terminal'; entry.pending = [];
4158
4414
  delete entry.rawSpec;
4415
+ delete entry.heldAgent;
4159
4416
  // What the run's meter can still read is booked now; nothing provisional outlives the process.
4160
4417
  try { finishUsage(entry, live.get(entry.runId) || null); } catch {}
4161
4418
  releaseDesktop(entry);
@@ -4165,7 +4422,7 @@ export function createAssistantDispatcher({
4165
4422
  // Agents P2: the transcript tails are written; a service this dispatcher made for itself goes with it (the one
4166
4423
  // server.js shares is closed there, after the runtime).
4167
4424
  tails.flushAll();
4168
- if (!sharedCoordination) coordination.close();
4425
+ try { await drainFinalizations(); } finally { if (!sharedCoordination) await coordination.close(); }
4169
4426
  }
4170
4427
 
4171
4428
  loadRegistry();
@@ -4183,13 +4440,21 @@ export function createAssistantDispatcher({
4183
4440
  }
4184
4441
 
4185
4442
  return {
4186
- dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4187
- respondPermission, subscribe, shutdown, limits, suspendForShutdown,
4443
+ dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, activeRouteRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4444
+ respondPermission, subscribe, shutdown, limits, suspendForShutdown, drainFinalizations,
4188
4445
  sessionBudget, checkSession, refreshLimits, providerSpend, coverFollowUp, budget,
4189
4446
  resolveRoute, declineRoute, heldRouteRefusal, escalate,
4190
4447
  markDelivered, deliveryState, markEventsDelivered, noteBrowserRoute, noteBrowserProfile,
4191
4448
  remove, removeFinished,
4192
4449
  mediaFile,
4450
+ scratchReleased(runId, isTask, finishedMs) {
4451
+ if (!coordination.durable) return false;
4452
+ const entry = entries.get(runId);
4453
+ if (!entry) return !isTask;
4454
+ return isTask && removable(entry) && (entry.turnState == null || entry.turnState === 'terminal') && Date.parse(entry.finishedAt) <= finishedMs
4455
+ && !entry.team && !entry.teamId && !entry.pending?.length && !finalizations.has(runId)
4456
+ && coordination.followUps.cachedCount(runId) === 0;
4457
+ },
4193
4458
  accountInUse: (provider, accountId) => activeEntries((e) => e.provider === provider && e.accountId === accountId).length > 0,
4194
4459
  // agents-p4: the session's Agent density as the server reads it (the default when it is not set or cannot be read).
4195
4460
  agentDensity: (assistantSessionId) => { try { return normalizeAgentDensity(agentDensity(assistantSessionId || null)); } catch { return normalizeAgentDensity(null); } },