synabun 2.4.1 → 2.4.3

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 (345) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +46 -6
  4. package/lib/data-home-files.js +4 -2
  5. package/lib/first-launch-protection.js +8 -2
  6. package/lib/release-npm-ci.mjs +23 -1
  7. package/lib/update-snapshot.js +11 -4
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +25 -2
  10. package/mcp-server/dist/http.js.map +1 -1
  11. package/mcp-server/dist/index.d.ts.map +1 -1
  12. package/mcp-server/dist/index.js +62 -17
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  15. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  16. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  18. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  19. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  20. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  21. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  22. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  23. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  24. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  25. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  26. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  27. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  28. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  29. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  30. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  31. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  32. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  33. package/mcp-server/dist/services/memory-schema.js +190 -13
  34. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  35. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  36. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  37. package/mcp-server/dist/services/memory-sessions.js +56 -20
  38. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  39. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-verification.js +8 -5
  41. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +19 -2
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  47. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  48. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  49. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  50. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  51. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  52. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  53. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  54. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  55. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  56. package/mcp-server/dist/services/sqlite-write.js +94 -0
  57. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  58. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  59. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  60. package/mcp-server/dist/services/sqlite.js +249 -8
  61. package/mcp-server/dist/services/sqlite.js.map +1 -1
  62. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  63. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  64. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  65. package/mcp-server/dist/services/typesafe-config.js +32 -10
  66. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  67. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  68. package/mcp-server/dist/services/typesafe.js +9 -7
  69. package/mcp-server/dist/services/typesafe.js.map +1 -1
  70. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  71. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  72. package/mcp-server/dist/services/vector-cache.js +161 -8
  73. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  74. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  75. package/mcp-server/dist/tools/agents.d.ts +11 -7
  76. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/agents.js +27 -9
  78. package/mcp-server/dist/tools/agents.js.map +1 -1
  79. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  80. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  82. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  83. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  84. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/browser-extension-setup.js +29 -0
  86. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  87. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/browser-interact.js +6 -1
  89. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  90. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  91. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  92. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  93. package/mcp-server/package-lock.json +5 -5
  94. package/mcp-server/package.json +1 -1
  95. package/mcp-server/src/http.ts +20 -2
  96. package/mcp-server/src/index.ts +59 -17
  97. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  98. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  99. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  100. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  101. package/mcp-server/src/services/memory-schema.ts +194 -12
  102. package/mcp-server/src/services/memory-sessions.ts +54 -21
  103. package/mcp-server/src/services/memory-verification.ts +7 -4
  104. package/mcp-server/src/services/neural-interface.ts +22 -2
  105. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  106. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  107. package/mcp-server/src/services/sqlite-write.ts +60 -0
  108. package/mcp-server/src/services/sqlite.ts +246 -8
  109. package/mcp-server/src/services/typesafe-config.ts +25 -6
  110. package/mcp-server/src/services/typesafe.ts +9 -7
  111. package/mcp-server/src/services/vector-cache.ts +154 -9
  112. package/mcp-server/src/tools/agents.ts +26 -9
  113. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  114. package/mcp-server/src/tools/browser-extension-setup.ts +36 -0
  115. package/mcp-server/src/tools/browser-interact.ts +5 -1
  116. package/neural-interface/i18n/en.json +313 -2
  117. package/neural-interface/i18n/pt-BR.json +321 -10
  118. package/neural-interface/lib/agents/split.js +32 -4
  119. package/neural-interface/lib/assistant-api.js +52 -8
  120. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  121. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  122. package/neural-interface/lib/assistant-catalog.js +2 -2
  123. package/neural-interface/lib/assistant-config.js +0 -7
  124. package/neural-interface/lib/assistant-dispatch.js +281 -95
  125. package/neural-interface/lib/assistant-envelope.js +40 -0
  126. package/neural-interface/lib/assistant-persona.js +16 -4
  127. package/neural-interface/lib/assistant-pricing.js +65 -14
  128. package/neural-interface/lib/assistant-router.js +131 -47
  129. package/neural-interface/lib/assistant-run-wait.js +45 -28
  130. package/neural-interface/lib/assistant-runtime.js +133 -42
  131. package/neural-interface/lib/backup-contents.js +158 -0
  132. package/neural-interface/lib/backup-crypto-io.js +330 -0
  133. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  134. package/neural-interface/lib/backup-crypto.js +525 -0
  135. package/neural-interface/lib/backup-download.js +268 -0
  136. package/neural-interface/lib/backup-encryption.js +318 -0
  137. package/neural-interface/lib/backup-groups.js +287 -0
  138. package/neural-interface/lib/backup-restore-session.js +176 -0
  139. package/neural-interface/lib/backup-restore-stage.js +60 -0
  140. package/neural-interface/lib/backup-service.js +788 -233
  141. package/neural-interface/lib/backup-zip-reader.js +30 -18
  142. package/neural-interface/lib/backup-zip-writer.js +34 -10
  143. package/neural-interface/lib/browser-extension-adapter.js +89 -15
  144. package/neural-interface/lib/browser-extension-archive.js +149 -0
  145. package/neural-interface/lib/browser-extension-bridge.js +24 -10
  146. package/neural-interface/lib/browser-extension-folder.js +596 -76
  147. package/neural-interface/lib/browser-extension-package.js +200 -0
  148. package/neural-interface/lib/browser-extension-pin.js +84 -0
  149. package/neural-interface/lib/browser-extension-pin.json +33 -0
  150. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +91 -6
  151. package/neural-interface/lib/browser-extension-setup.js +105 -18
  152. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  153. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  154. package/neural-interface/lib/cli-install.js +23 -3
  155. package/neural-interface/lib/cli-update-planner.js +171 -9
  156. package/neural-interface/lib/client-diagnostics.js +42 -0
  157. package/neural-interface/lib/confined-fs.js +7 -2
  158. package/neural-interface/lib/coordination/README.md +8 -2
  159. package/neural-interface/lib/coordination/contract.js +161 -0
  160. package/neural-interface/lib/coordination/database.js +999 -0
  161. package/neural-interface/lib/coordination/operations.js +436 -0
  162. package/neural-interface/lib/coordination/service.js +68 -537
  163. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  164. package/neural-interface/lib/coordination/store.js +219 -1111
  165. package/neural-interface/lib/db.js +70 -32
  166. package/neural-interface/lib/health-count.js +37 -0
  167. package/neural-interface/lib/loop-stall.js +139 -0
  168. package/neural-interface/lib/maritaca/client.js +2 -2
  169. package/neural-interface/lib/maritaca/models.js +12 -17
  170. package/neural-interface/lib/maritaca/opencode.js +4 -2
  171. package/neural-interface/lib/memory-api.js +9 -1
  172. package/neural-interface/lib/memory-session-capture.js +42 -10
  173. package/neural-interface/lib/memory-store-gate.js +313 -0
  174. package/neural-interface/lib/memory-store-migrate.js +65 -0
  175. package/neural-interface/lib/memory-timers.js +7 -7
  176. package/neural-interface/lib/native-loop-providers.js +23 -17
  177. package/neural-interface/lib/native-loop-runtime.js +48 -9
  178. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  179. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  180. package/neural-interface/lib/opencode-provider-view.js +14 -3
  181. package/neural-interface/lib/opencode-shell-read.js +107 -0
  182. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  183. package/neural-interface/lib/opencode-turn-release.js +173 -0
  184. package/neural-interface/lib/opencode-v2-client.js +4 -1
  185. package/neural-interface/lib/opencode-v2-ws-requests.js +65 -1
  186. package/neural-interface/lib/opencode2-client.js +343 -7
  187. package/neural-interface/lib/opencode2-translate.js +161 -4
  188. package/neural-interface/lib/recall-impact.js +122 -0
  189. package/neural-interface/lib/scratch-evidence.js +420 -0
  190. package/neural-interface/lib/scratch-process-guard.js +139 -0
  191. package/neural-interface/lib/scratch-references.js +279 -0
  192. package/neural-interface/lib/scratch-retention-core.js +385 -0
  193. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  194. package/neural-interface/lib/scratch-retention.js +151 -0
  195. package/neural-interface/lib/session-cache-builder.js +31 -43
  196. package/neural-interface/lib/session-cache-worker.js +157 -0
  197. package/neural-interface/lib/session-indexer.js +28 -21
  198. package/neural-interface/lib/session-search-index.js +85 -0
  199. package/neural-interface/lib/skills/creation.js +1 -1
  200. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  201. package/neural-interface/lib/style-guide/store.js +43 -3
  202. package/neural-interface/lib/system-restore.js +50 -0
  203. package/neural-interface/lib/teams/api.js +15 -6
  204. package/neural-interface/lib/teams/claims.js +67 -31
  205. package/neural-interface/lib/teams/index.js +7 -7
  206. package/neural-interface/lib/teams/integration.js +40 -40
  207. package/neural-interface/lib/teams/landing.js +6 -6
  208. package/neural-interface/lib/teams/recovery.js +24 -23
  209. package/neural-interface/lib/teams/scheduler.js +194 -95
  210. package/neural-interface/lib/teams/state.js +14 -14
  211. package/neural-interface/lib/teams/worktrees.js +27 -27
  212. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  213. package/neural-interface/lib/whatsapp/bridge.js +54 -7
  214. package/neural-interface/lib/worker-confinement.js +47 -2
  215. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  216. package/neural-interface/lib/worker-resume.js +5 -0
  217. package/neural-interface/lib/worker-stop.js +86 -0
  218. package/neural-interface/package-lock.json +5 -5
  219. package/neural-interface/package.json +1 -1
  220. package/neural-interface/public/extension-setup.html +5 -2
  221. package/neural-interface/public/index.html +233 -24
  222. package/neural-interface/public/onboarding.html +259 -34
  223. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  224. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  225. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  226. package/neural-interface/public/shared/agy/agy-panel.js +67 -20
  227. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  228. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  229. package/neural-interface/public/shared/api.js +1 -1
  230. package/neural-interface/public/shared/assistant/asst-api.js +28 -3
  231. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  232. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  233. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  234. package/neural-interface/public/shared/assistant/asst-panel.js +87 -3
  235. package/neural-interface/public/shared/assistant/asst-rack-styles.js +27 -0
  236. package/neural-interface/public/shared/assistant/asst-render.js +243 -44
  237. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  238. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  239. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  240. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  241. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  242. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  243. package/neural-interface/public/shared/assistant/asst-styles.js +11 -23
  244. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  245. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  246. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  247. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  248. package/neural-interface/public/shared/cdx/cdx-tabs.js +54 -9
  249. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  250. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  251. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  252. package/neural-interface/public/shared/effort-i18n.js +118 -0
  253. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  254. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  255. package/neural-interface/public/shared/html-shell.js +4 -52
  256. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  257. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  258. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  259. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  260. package/neural-interface/public/shared/mtc/mtc-panel.js +25 -3
  261. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -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-manager.js +1 -0
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +152 -8
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +53 -4
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +52 -6
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +22 -2
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +67 -93
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  278. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  279. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  280. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  281. package/neural-interface/public/shared/output-format.js +294 -0
  282. package/neural-interface/public/shared/provider-icons.js +6 -0
  283. package/neural-interface/public/shared/schedules-view.js +2 -1
  284. package/neural-interface/public/shared/server-presence.js +77 -0
  285. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  286. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  287. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  288. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  289. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  290. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  291. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  292. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  293. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  294. package/neural-interface/public/shared/studio-attention.js +6 -0
  295. package/neural-interface/public/shared/styles.css +341 -437
  296. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  297. package/neural-interface/public/shared/transcript-rows.js +28 -3
  298. package/neural-interface/public/shared/tray-auto-close.js +49 -6
  299. package/neural-interface/public/shared/ui-agents.js +1 -2
  300. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  301. package/neural-interface/public/shared/ui-claude-panel.js +62 -65
  302. package/neural-interface/public/shared/ui-loading.js +124 -17
  303. package/neural-interface/public/shared/ui-native-loop-router.js +52 -0
  304. package/neural-interface/public/shared/ui-navbar.js +2 -1
  305. package/neural-interface/public/shared/ui-output.js +533 -0
  306. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  307. package/neural-interface/public/shared/ui-scroll-follow.js +101 -6
  308. package/neural-interface/public/shared/ui-sessions.js +2 -2
  309. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  310. package/neural-interface/public/shared/ui-settings.js +224 -65
  311. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  312. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  313. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  314. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  315. package/neural-interface/public/shared/worker-end.js +9 -4
  316. package/neural-interface/public/variant/2d/main.js +5 -0
  317. package/neural-interface/public/variant/3d/app.js +10 -0
  318. package/neural-interface/public/variant/3d/main.js +5 -1
  319. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  320. package/neural-interface/server.js +725 -173
  321. package/npm-shrinkwrap.json +5 -5
  322. package/package.json +1 -2
  323. package/scripts/restore-data-home-from-backup.mjs +175 -8
  324. package/setup.js +18 -4
  325. package/browser-extension/content.js +0 -189
  326. package/browser-extension/engine.js +0 -508
  327. package/browser-extension/icons/icon-128.png +0 -0
  328. package/browser-extension/icons/icon-16.png +0 -0
  329. package/browser-extension/icons/icon-32.png +0 -0
  330. package/browser-extension/icons/icon-48.png +0 -0
  331. package/browser-extension/icons/status-off-16.png +0 -0
  332. package/browser-extension/icons/status-off-32.png +0 -0
  333. package/browser-extension/icons/status-off-48.png +0 -0
  334. package/browser-extension/icons/status-on-16.png +0 -0
  335. package/browser-extension/icons/status-on-32.png +0 -0
  336. package/browser-extension/icons/status-on-48.png +0 -0
  337. package/browser-extension/manifest.json +0 -56
  338. package/browser-extension/popup-strings.js +0 -250
  339. package/browser-extension/popup-view.js +0 -151
  340. package/browser-extension/popup.css +0 -166
  341. package/browser-extension/popup.html +0 -108
  342. package/browser-extension/popup.js +0 -359
  343. package/browser-extension/service-worker.js +0 -275
  344. package/browser-extension/setup-content.js +0 -36
  345. package/browser-extension/tokens.css +0 -326
@@ -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';
@@ -54,6 +55,7 @@ import { claudeTokensCostUsd } from './assistant-pricing.js';
54
55
  import { RemotePolicyError, clampDispatchSpec, getSessionPolicy, readRegisteredProjects } from './remote-policy.js';
55
56
  import { validateWorkerReply } from './worker-question.js';
56
57
  import { limitFromText } from '../public/shared/assistant/asst-limit.js';
58
+ import { abandonedPrograms, describeAbandoned } from '../public/shared/shell-stop-view.js';
57
59
  // agents-p1: a dispatch's agent_ref (lib/agents/resolve.js).
58
60
  import { agentCorrections, agentIntake, agentPinOf, agentRefOf, routedAgent, carryAgentRun, getAgentResolver, stampAgentRun } from './agents/resolve.js';
59
61
  // Agents P2 (durable agent messaging): run events, typed waits, the follow-up outbox and the transcript on disk.
@@ -413,6 +415,9 @@ export function createAssistantDispatcher({
413
415
  observeSkillEvent = () => {},
414
416
  completeSkillUsage = () => {},
415
417
  log = () => {},
418
+ // How long the resumes of one start wait for the browser extension, which reconnects by itself after a restart.
419
+ resumeBrowserWaitMs = 90_000,
420
+ resumeBrowserPollMs = 1_000,
416
421
  PACKAGE_ROOT = process.cwd(),
417
422
  findCodexAccount = () => null,
418
423
  getCodexAccount = () => null,
@@ -528,7 +533,7 @@ export function createAssistantDispatcher({
528
533
  const tails = createRunTailStore({ dir: resolve(dataDir, 'run-tails'), log: (tag, detail) => log(null, tag, detail) });
529
534
  // What image / video creation runs generated, and design runs' screenshots: <dataDir>/media/<runId>/<n>-<name>.
530
535
  const mediaRoot = resolve(dataDir, 'media');
531
- // A guarded worker's own scratch folder (lib/worker-confinement.js): <dataDir>/scratch/<runId>, removed when empty.
536
+ // Scratch retention also owns empty folders: an empty directory can still be a process's cwd.
532
537
  const scratchRoot = resolve(dataDir, 'scratch');
533
538
  /** A known task class, else null. */
534
539
  const knownClass = (value) => (Object.prototype.hasOwnProperty.call(TASK_CLASS_META, String(value || '')) ? String(value) : null);
@@ -558,9 +563,9 @@ export function createAssistantDispatcher({
558
563
  // in memory. Now each is a row of the outbox: it survives a restart, keeps its place, is marked sent in the step
559
564
  // that hands it to the run's provider, and the queue refuses more than its bound.
560
565
  /** Queue a follow-up for a run → { id, position }. Throws FOLLOW_UP_QUEUE_FULL (409) at the bound. */
561
- function queueFollowUp(entry, item) {
566
+ async function queueFollowUp(entry, item) {
562
567
  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 });
568
+ 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
569
  } catch (error) {
565
570
  if (error?.code === 'OUTBOX_FULL') {
566
571
  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 +574,29 @@ export function createAssistantDispatcher({
569
574
  }
570
575
  }
571
576
  /** 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; }
577
+ async function nextFollowUp(runId) {
578
+ try { return await coordination.followUps.next(runId); } catch { return null; }
574
579
  }
575
580
  function followUpCount(runId) {
576
- try { return coordination.followUps.count(runId); } catch { return 0; }
581
+ try { return coordination.followUps.cachedCount(runId); } catch { return 0; }
577
582
  }
578
583
  /** 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 []; }
584
+ async function cancelFollowUps(runId) {
585
+ try { return await coordination.followUps.cancel(runId); } catch { return []; }
581
586
  }
582
587
  /** After a restart: follow-ups queued for runs that are gone or ended reach nobody. Their run's notes say so. */
583
- function settleOrphanFollowUps() {
588
+ async function settleOrphanFollowUps() {
584
589
  let runIds = [];
585
- try { runIds = coordination.followUps.runs(); } catch { runIds = []; }
590
+ try { runIds = await coordination.followUps.runs(); } catch { runIds = []; }
586
591
  for (const runId of runIds) {
587
592
  const entry = entries.get(runId);
588
593
  if (entry && !TERMINAL_STATES.has(entry.state)) continue;
589
- const dropped = cancelFollowUps(runId);
594
+ const dropped = await cancelFollowUps(runId);
590
595
  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
596
  }
592
597
  }
593
598
  const resumeInProgress = new Set(); // runIds resumeRun works on (they hold their slot; the others waiting do not)
599
+ let resumeBrowserDeadline = 0; // one deadline per start: every run waits for the same extension
594
600
  // The server is going down (suspendForShutdown ran): a resume under way stops where it is, for the next start.
595
601
  let closing = false;
596
602
 
@@ -825,17 +831,25 @@ export function createAssistantDispatcher({
825
831
  }
826
832
 
827
833
  function touch(entry) { entry.version = (Number(entry.version) || 0) + 1; entry.updatedAt = iso(now()); }
828
- function emit(entry, reason, extra = {}) {
834
+ async function emit(entry, reason, extra = {}, transition = null) {
829
835
  touch(entry);
830
- persist({ force: TERMINAL_STATES.has(entry.state) });
831
- const payload = { type: 'assistant:dispatch', reason, run: view(entry), ...extra };
836
+ if (!transition) persist({ force: TERMINAL_STATES.has(entry.state) });
837
+ const payload = { type: 'assistant:dispatch', reason, run: view(transition ? { ...entry, ...transition } : entry), ...extra };
832
838
  // Agents P2: the event goes into the durable log in the step that changed the run, under an id that names it
833
839
  // (recording it again stores nothing), before anyone is told. It never throws: the run goes on either way.
834
- coordination.recordDispatch(payload);
840
+ await coordination.recordDispatch(payload);
841
+ if (transition) {
842
+ Object.assign(entry, transition);
843
+ persist({ force: true });
844
+ }
835
845
  if (['turn_completed', 'idle', 'failed', 'stopped', 'completed'].includes(reason)) { try { completeSkillUsage(entry); } catch {} }
836
846
  try { broadcastSync(payload); } catch {}
837
- for (const listener of listeners) { try { listener(payload); } catch {} }
847
+ const notified = [];
848
+ for (const listener of listeners) { try { notified.push(Promise.resolve(listener(payload)).catch(() => {})); } catch {} }
838
849
  notifyWaiters(entry.runId, reason);
850
+ // A turn can depend on its listeners (e.g. restoring claims). An ended worker can release its slot
851
+ // as soon as its event is recorded and announced, even if a listener is waiting for shutdown.
852
+ if (!TERMINAL_STATES.has(reason)) await Promise.all(notified);
839
853
  }
840
854
 
841
855
  // ── browser route (a run's browser moved while it works) ───────────────────
@@ -896,9 +910,9 @@ export function createAssistantDispatcher({
896
910
  * Agents P2: events a brain read through agent_wait until:"event" are settled in its session's mailbox by their
897
911
  * ids (never a second turn for them). The log keeps them: the same cursor returns them again. → how many.
898
912
  */
899
- function markEventsDelivered(assistantSessionId, eventIds) {
913
+ async function markEventsDelivered(assistantSessionId, eventIds) {
900
914
  if (!assistantSessionId || !Array.isArray(eventIds) || !eventIds.length) return 0;
901
- try { return coordination.mailbox.ack(String(assistantSessionId), eventIds).acked; } catch { return 0; }
915
+ try { return (await coordination.mailbox.ack(String(assistantSessionId), eventIds)).acked; } catch { return 0; }
902
916
  }
903
917
 
904
918
  // ── waiters (Agents P2: lib/assistant-run-wait.js) ─────────────────────────
@@ -2430,15 +2444,24 @@ export function createAssistantDispatcher({
2430
2444
  const waitForFollowUp = () => new Promise((resolveWait) => {
2431
2445
  const finish = (value) => { if (liveState.idleTimer) { clearTimeout(liveState.idleTimer); liveState.idleTimer = null; } liveState.waitResolve = null; resolveWait(value); };
2432
2446
  // The outbox first (Agents P2): what was queued while the turn worked, or while a restart had the run away.
2433
- const queued = nextFollowUp(entry.runId);
2434
- if (queued) { finish(queued); return; }
2435
- if (liveState.abortReason) { finish({ kind: 'abort' }); return; }
2436
- // sendTurn signals { kind: 'follow-up' } once its text is in the outbox: the oldest queued one is taken from there.
2437
- liveState.waitResolve = (value) => {
2438
- if (value?.kind !== 'follow-up') { finish(value); return; }
2439
- const next = nextFollowUp(entry.runId);
2440
- if (next) finish(next);
2447
+ // Install the wake-up before reading. A commit arriving during that read
2448
+ // triggers another look, without two takes racing for the same oldest row.
2449
+ let reading = false, again = false;
2450
+ const look = async () => {
2451
+ if (reading) { again = true; return; }
2452
+ reading = true;
2453
+ do {
2454
+ again = false;
2455
+ const next = await nextFollowUp(entry.runId);
2456
+ if (liveState.waitResolve !== wake) return;
2457
+ if (next) { finish(next); return; }
2458
+ } while (again);
2459
+ reading = false;
2441
2460
  };
2461
+ const wake = value => value?.kind === 'follow-up' ? look() : finish(value);
2462
+ liveState.waitResolve = wake;
2463
+ if (liveState.abortReason) { finish({ kind: 'abort' }); return; }
2464
+ look();
2442
2465
  liveState.idleTimer = setTimeout(() => finish({ kind: 'timeout' }), entry.idleTimeoutMs);
2443
2466
  liveState.idleTimer.unref?.();
2444
2467
  });
@@ -2462,7 +2485,7 @@ export function createAssistantDispatcher({
2462
2485
  // The work clock runs from here to the turn's end (its result-retry turn included).
2463
2486
  startWork(entry, liveState);
2464
2487
  ctx.setTurnState('running');
2465
- emit(entry, 'turn_started', { turn: turnNumber });
2488
+ await emit(entry, 'turn_started', { turn: turnNumber });
2466
2489
  persist({ force: true });
2467
2490
  // What this turn runs (commands, tool results, edited files): the evidence behind a "done".
2468
2491
  liveState.evidence = createTurnEvidence();
@@ -2470,7 +2493,7 @@ export function createAssistantDispatcher({
2470
2493
  liveState.turnMeteredUsd = 0;
2471
2494
  // A queued follow-up is sent exactly here, as its prompt goes to the provider: a restart from now on continues
2472
2495
  // this turn (resumeInfo.inFlight) and never sends the text a second time.
2473
- if (outboxId) { try { coordination.followUps.markSent([outboxId]); } catch (error) { log(entry.runId, 'assistant:follow-up-error', error?.message || String(error)); } }
2496
+ if (outboxId) { try { await coordination.followUps.markSent([outboxId]); } catch (error) { log(entry.runId, 'assistant:follow-up-error', error?.message || String(error)); } }
2474
2497
  let raw = await inner.runTurn(prompt, { ...meta, turn: turnNumber, outputSchema: entry.outputSchema || undefined });
2475
2498
  if (entry.provider === 'codex') settleCodexTurn(entry, liveState, raw);
2476
2499
  else if (entry.provider === 'antigravity') settleAntigravityTurn(entry, liveState, raw);
@@ -2588,7 +2611,7 @@ export function createAssistantDispatcher({
2588
2611
  // The worker remembers before its ## Result block: this turn's events carry that memory.
2589
2612
  syncMemory(entry);
2590
2613
  if (parsed.status === 'needs_input') emit(entry, 'needs_input', { turn: turnNumber, question: parsed.question });
2591
- emit(entry, 'turn_completed', { turn: turnNumber });
2614
+ await emit(entry, 'turn_completed', { turn: turnNumber });
2592
2615
  announceUnpriced(entry);
2593
2616
  checkSession(entry.assistantSessionId, { source: entry });
2594
2617
  return parsed;
@@ -2610,6 +2633,10 @@ export function createAssistantDispatcher({
2610
2633
  : { origin: 'dispatch' });
2611
2634
  } catch (error) {
2612
2635
  pauseWork(entry, liveState);
2636
+ // The CLI says nothing was saved under this session: the run starts its task again instead of failing.
2637
+ if (resume && entry.provider === 'claude-code' && !entry.resumeInfo?.noConversation && !liveState.abortReason && !liveState.suspending && isMissingConversationError(error)) {
2638
+ return restartWithoutConversation(entry, liveState);
2639
+ }
2613
2640
  return handleTurnError(error, liveState, entry, ctx);
2614
2641
  }
2615
2642
  }
@@ -2630,7 +2657,15 @@ export function createAssistantDispatcher({
2630
2657
  const next = await waitForFollowUp();
2631
2658
  if (liveState.suspending) return { providerSessionId: null };
2632
2659
  if (next.kind === 'abort') { entry.completionReason = entry.completionReason || liveState.abortReason || 'aborted'; return { providerSessionId: inner.identity?.()?.providerSessionId }; }
2633
- if (next.kind === 'complete') { entry.completionReason = next.reason || 'complete'; liveState.completed = true; return { providerSessionId: inner.identity?.()?.providerSessionId }; }
2660
+ if (next.kind === 'complete') {
2661
+ entry.completionReason = next.reason || 'complete';
2662
+ if (next.stopProvenance) {
2663
+ entry.stopProvenance = next.stopProvenance;
2664
+ ctx.noteTabClose?.(next.stopProvenance);
2665
+ }
2666
+ liveState.completed = true;
2667
+ return { providerSessionId: inner.identity?.()?.providerSessionId };
2668
+ }
2634
2669
  if (next.kind === 'timeout') { entry.completionReason = 'idle_timeout'; return { providerSessionId: inner.identity?.()?.providerSessionId }; }
2635
2670
  if (liveState.turnCounter >= entry.maxTurns) {
2636
2671
  entry.completionReason = 'max_turns';
@@ -3434,7 +3469,10 @@ export function createAssistantDispatcher({
3434
3469
  closing = true;
3435
3470
  const kept = [];
3436
3471
  for (const entry of entries.values()) {
3437
- if (!SUSPENDABLE_STATES.has(entry.state)) continue;
3472
+ // Idempotent in its answer too: on a signal the Assistant's handler (shutdown()) gets here before the graceful
3473
+ // shutdown does, and a run left out of `keep` would be stopped by the runtime instead of suspended.
3474
+ if (entry.state === 'suspended' && live.get(entry.runId)?.suspending && !finalizations.has(entry.runId)) { kept.push(entry.runId); continue; }
3475
+ if (!SUSPENDABLE_STATES.has(entry.state) || finalizations.has(entry.runId)) continue;
3438
3476
  const liveState = live.get(entry.runId) || null;
3439
3477
  // Only a run whose worker is up, or whose resume is starting it (its session is known): one still starting for
3440
3478
  // the first time has no session to resume yet.
@@ -3478,6 +3516,32 @@ export function createAssistantDispatcher({
3478
3516
  if (kept.length) persist({ force: true });
3479
3517
  return kept;
3480
3518
  }
3519
+ /**
3520
+ * A resumed Claude Code worker whose session id has no saved conversation (it was cut off before the CLI wrote one):
3521
+ * suspended again and resumed with no session, so it runs its original task from the beginning. Once per run.
3522
+ */
3523
+ async function restartWithoutConversation(entry, liveState) {
3524
+ liveState.suspending = true;
3525
+ liveState.turnOpen = false;
3526
+ stopUsagePolling(liveState);
3527
+ const info = resumeInfoOf(entry);
3528
+ delete info.inFlight;
3529
+ info.noConversation = true;
3530
+ // The attempt that found nothing never ran: it does not count against the run's resumes.
3531
+ entry.resumes = Math.max(0, (Number(entry.resumes) || 0) - 1);
3532
+ entry.state = 'resuming';
3533
+ entry.turnState = 'resuming';
3534
+ entry.notes.push('no conversation was saved before the restart: the run starts its original task again');
3535
+ persist({ force: true });
3536
+ const held = await safeRuntime()?.suspend?.(entry.runId, 'no_saved_conversation');
3537
+ if (held) {
3538
+ setTimeout(() => {
3539
+ if (entry.state !== 'resuming' || closing) return;
3540
+ resumeRun(entry).catch((error) => notResumed(entry, error?.message || String(error)));
3541
+ }, 0);
3542
+ }
3543
+ return { providerSessionId: null };
3544
+ }
3481
3545
  /** Book pending provider usage and save the meter baseline before the process ends. */
3482
3546
  function suspendUsage(entry, liveState) {
3483
3547
  if (entry.provider === 'codex') pollCodex(entry, liveState, { discover: true });
@@ -3561,12 +3625,22 @@ export function createAssistantDispatcher({
3561
3625
  const ids = bootResumes.splice(0)
3562
3626
  .map((runId) => entries.get(runId)).filter((entry) => entry?.state === 'resuming')
3563
3627
  .sort((a, b) => String(a.createdAt || '').localeCompare(String(b.createdAt || '')))
3628
+ // A run that may wait for the browser extension goes after those that need nothing to come back.
3629
+ .sort((a, b) => Number(!!a.usesBrowser) - Number(!!b.usesBrowser))
3564
3630
  .map((entry) => entry.runId);
3565
3631
  // Held for this dispatcher from here on: the runtime's own hold no longer ends them.
3566
3632
  for (const runId of ids) { try { runtime?.keepSuspended?.(runId); } catch { /* ended meanwhile */ } }
3567
3633
  for (const runId of bootInterrupts.splice(0)) {
3568
3634
  const entry = entries.get(runId);
3569
3635
  if (!entry) continue;
3636
+ // Stopped on purpose while the last server went down (after this dispatcher stopped listening): that stop stands.
3637
+ const stoppedRecord = runtime?.get?.(runId);
3638
+ if (stoppedRecord?.status === 'stopped' && stoppedRecord.stopProvenance) {
3639
+ Object.assign(entry, { state: 'stopped', completionReason: stoppedRecord.stoppedReason, stopProvenance: stoppedRecord.stopProvenance });
3640
+ delete entry.resumeRefused;
3641
+ emit(entry, 'stopped');
3642
+ continue;
3643
+ }
3570
3644
  // A CLI a crash left behind goes with the run.
3571
3645
  await endOldProcess(entry);
3572
3646
  try { await runtime?.endSuspended?.(runId, 'server_restart', { error: entry.resumeRefused ? `not resumed: ${entry.resumeRefused}` : null }); } catch { /* not held */ }
@@ -3582,7 +3656,7 @@ export function createAssistantDispatcher({
3582
3656
  const block = railBlock(spec, entry.assistantSessionId, { except: runId });
3583
3657
  if (block) { entry.notes.push(`resume queued: ${block}`); held.push(runId); persist(); continue; }
3584
3658
  // What it threw (a folder that cannot be made, a full disk) ends it, with why: nothing else would.
3585
- try { await resumeRun(entry); } catch (error) { log(runId, 'assistant:resume-error', error?.message || String(error)); notResumed(entry, error?.message || String(error)); }
3659
+ try { await resumeRun(entry); } catch (error) { log(runId, 'assistant:resume-error', error?.message || String(error)); await notResumed(entry, error?.message || String(error)); }
3586
3660
  }
3587
3661
  if (held.length) { queue.unshift(...held); processQueue().catch(() => {}); }
3588
3662
  }
@@ -3603,26 +3677,30 @@ export function createAssistantDispatcher({
3603
3677
  async function continueRun(entry) {
3604
3678
  if (closing) return null;
3605
3679
  const runtime = safeRuntime();
3606
- if (!runtime?.resume) return notResumed(entry, 'the native loop runtime is not available');
3680
+ if (!runtime?.resume) return await notResumed(entry, 'the native loop runtime is not available');
3681
+ // Its record ended while the last server went down (a deliberate stop after this dispatcher stopped listening):
3682
+ // that end stands, with who asked for it.
3683
+ const endedRecord = runtime.get?.(entry.runId);
3684
+ if (endedRecord && TERMINAL_STATES.has(endedRecord.status)) { await finalize(entry, endedRecord); return null; }
3607
3685
  refreshLimits();
3608
3686
  const refusal = resumeRefusal(entry, { now: now(), workLeftMs: workLeftMs(entry), isDirectory, accountUnusable: providerAccountUnusable });
3609
- if (refusal) return notResumed(entry, refusal);
3610
- try { await fitBudget(entry, { routed: true }); } catch (error) { return notResumed(entry, `the budget does not allow it (${error?.message || error})`); }
3687
+ if (refusal) return await notResumed(entry, refusal);
3688
+ try { await fitBudget(entry, { routed: true }); } catch (error) { return await notResumed(entry, `the budget does not allow it (${error?.message || error})`); }
3611
3689
  if (entry.state !== 'resuming' || closing) return null; // stopped meanwhile, or the server is going down again
3612
3690
  // Its own ceiling (budget_usd), with what its cut-off turn was booked at the suspension (fitBudget checks the
3613
3691
  // session and the share only): a run out of money is not resumed, as a turn that ends out of money does not idle.
3614
3692
  const spentOut = budgetBlock(entry);
3615
3693
  if (spentOut && spentOut.code !== 'BUDGET_SHARE_EXHAUSTED') {
3616
3694
  entry.completionReason = spentOut.reason;
3617
- return notResumed(entry, `the budget does not allow it (${spentOut.message})`);
3695
+ return await notResumed(entry, `the budget does not allow it (${spentOut.message})`);
3618
3696
  }
3619
- if (!runtime.isSuspended?.(entry.runId)) return notResumed(entry, 'its runtime record is gone');
3697
+ if (!runtime.isSuspended?.(entry.runId)) return await notResumed(entry, 'its runtime record is gone');
3620
3698
  // A crash ended no process: the CLI the run had may still be there, finishing the cut-off tool call. It is ended
3621
3699
  // first; one that cannot be checked keeps the run from resuming (two processes on one session would both write its
3622
3700
  // transcript).
3623
3701
  const orphan = await endOldProcess(entry);
3624
3702
  if (orphan.state === 'unknown' || orphan.state === 'still_running') {
3625
- 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'}`);
3703
+ 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'}`);
3626
3704
  }
3627
3705
  if (entry.state !== 'resuming' || closing) return null;
3628
3706
  const costBaseUsd = entry.provider === 'claude-code' ? rebaseClaudeUsage(entry) : 0;
@@ -3632,8 +3710,9 @@ export function createAssistantDispatcher({
3632
3710
  let browserTabId = null;
3633
3711
  if (entry.usesBrowser && typeof acquireLoopBrowserAndTab === 'function') {
3634
3712
  pinEntryBrowserProfile(entry);
3635
- const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId: entry.requestedBrowserSessionId, terminalSessionId: entry.runId, logTag: 'assistant:browser' }).catch((error) => ({ error: error?.message || String(error) }));
3636
- if (acq?.error) return notResumed(entry, `no browser tab: ${acq.error}`);
3713
+ const acq = await acquireResumeBrowser(entry);
3714
+ if (acq?.cancelled) return null;
3715
+ if (acq?.error) return await notResumed(entry, `no browser tab: ${acq.error}`);
3637
3716
  browserSessionId = acq.browserSessionId || null;
3638
3717
  browserTabId = acq.browserTabId || null;
3639
3718
  }
@@ -3646,7 +3725,9 @@ export function createAssistantDispatcher({
3646
3725
  if (entry.scratchDir) { try { mkdirSync(entry.scratchDir, { recursive: true }); } catch { /* the guard says so when it needs it */ } }
3647
3726
  const inFlight = entry.resumeInfo?.inFlight || null;
3648
3727
  const turned = lastTurnNumber(entry);
3649
- const mode = inFlight ? 'mid_turn' : turned > 0 ? 'idle' : 'fresh';
3728
+ // Nothing was saved under its session (restartWithoutConversation): its task runs from the beginning, in a new one.
3729
+ const noConversation = !!entry.resumeInfo?.noConversation;
3730
+ const mode = noConversation ? 'fresh' : inFlight ? 'mid_turn' : turned > 0 ? 'idle' : 'fresh';
3650
3731
  const liveState = newLiveState(entry);
3651
3732
  liveState.turnCounter = turned;
3652
3733
  liveState.resume = { mode, taskId: inFlight?.taskId || null };
@@ -3658,7 +3739,7 @@ export function createAssistantDispatcher({
3658
3739
  const state = runState(entry, {
3659
3740
  browserSessionId, browserTabId, desktopGrant,
3660
3741
  startedAt: entry.startedAt || iso(now()),
3661
- extra: { resumeSessionId: entry.providerSessionId, resumeThreadId: entry.providerThreadId, costBaseUsd, resumingWorker: true, antigravityHome: entry.resumeInfo?.antigravityHome || null },
3742
+ extra: { resumeSessionId: noConversation ? null : entry.providerSessionId, resumeThreadId: entry.providerThreadId, costBaseUsd, resumingWorker: true, antigravityHome: entry.resumeInfo?.antigravityHome || null },
3662
3743
  });
3663
3744
  // The CLI's spend stop (--max-budget-usd) counts from the total the resumed CLI restores (costBaseUsd): what the run
3664
3745
  // may still spend (its ceiling less what it spent, never more than the session has left) goes on top of that. A
@@ -3694,7 +3775,7 @@ export function createAssistantDispatcher({
3694
3775
  // The runtime ended its record (resume_failed): its run-stopped event ended the run here too.
3695
3776
  const why = error?.message || String(error);
3696
3777
  if (browserSessionId) await releaseSharedBrowserTab(browserSessionId, entry.runId).catch(() => {});
3697
- if (!TERMINAL_STATES.has(entry.state)) return notResumed(entry, why);
3778
+ if (!TERMINAL_STATES.has(entry.state)) return await notResumed(entry, why);
3698
3779
  entry.notes.push(`not resumed: ${why}`);
3699
3780
  persist();
3700
3781
  return null;
@@ -3709,6 +3790,23 @@ export function createAssistantDispatcher({
3709
3790
  reconcileKeepAwake();
3710
3791
  return view(entry);
3711
3792
  }
3793
+ /**
3794
+ * A browser tab for a resuming run. The extension reconnects by itself a moment after the server is back, so "not
3795
+ * connected" is waited out up to this start's deadline; any other answer is final. → the acquisition, { error }, or
3796
+ * { cancelled } when the run was stopped or the server began to go down during the wait.
3797
+ */
3798
+ async function acquireResumeBrowser(entry) {
3799
+ if (!resumeBrowserDeadline) resumeBrowserDeadline = now() + resumeBrowserWaitMs;
3800
+ for (;;) {
3801
+ const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId: entry.requestedBrowserSessionId, terminalSessionId: entry.runId, logTag: 'assistant:browser' }).catch((error) => ({ error: error?.message || String(error) }));
3802
+ if (!/EXTENSION_NOT_CONNECTED/.test(String(acq?.error || ''))) return acq;
3803
+ if (entry.state !== 'resuming' || closing) return { cancelled: true };
3804
+ const left = resumeBrowserDeadline - now();
3805
+ if (left <= 0) return { error: `the browser extension did not reconnect within ${Math.round(resumeBrowserWaitMs / 1000)} seconds of the restart` };
3806
+ await new Promise((done) => { const timer = setTimeout(done, Math.min(left, resumeBrowserPollMs)); timer.unref?.(); });
3807
+ if (entry.state !== 'resuming' || closing) return { cancelled: true };
3808
+ }
3809
+ }
3712
3810
  /**
3713
3811
  * The CLI a run had before a crash may still be there, finishing its cut-off tool call (a crash ends no process): it
3714
3812
  * is ended once its command line shows it is this run's (lib/worker-resume.js endOrphanProcess), before a resume and
@@ -3727,12 +3825,12 @@ export function createAssistantDispatcher({
3727
3825
  return { ...orphan, pid };
3728
3826
  }
3729
3827
  /** A run that could not be resumed after a restart ends as interrupted, with why (its notes, its error, its event). */
3730
- function notResumed(entry, why) {
3828
+ async function notResumed(entry, why) {
3731
3829
  if (TERMINAL_STATES.has(entry.state)) return null;
3732
3830
  const index = queue.indexOf(entry.runId);
3733
3831
  if (index !== -1) queue.splice(index, 1);
3734
3832
  // Follow-ups accepted for it while it was away (agent_send) reach nobody: its end says so, with the first of them.
3735
- const waiting = cancelFollowUps(entry.runId);
3833
+ const waiting = await cancelFollowUps(entry.runId);
3736
3834
  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)}")` : '';
3737
3835
  // Nothing of it may go on: a CLI a crash left behind is ended too.
3738
3836
  endOldProcess(entry).then(() => persist()).catch(() => {});
@@ -3744,7 +3842,7 @@ export function createAssistantDispatcher({
3744
3842
  try { ended = !!safeRuntime()?.isSuspended?.(entry.runId); } catch { ended = false; }
3745
3843
  // The runtime's run-stopped event finalizes the run here (onRuntimeMessage); without a record it is done here.
3746
3844
  if (ended) safeRuntime().endSuspended(entry.runId, 'server_restart', { error }).catch(() => {});
3747
- if (!TERMINAL_STATES.has(entry.state)) finalize(entry, { status: 'interrupted', stoppedReason: 'server_restart', error });
3845
+ if (!TERMINAL_STATES.has(entry.state)) await finalize(entry, { status: 'interrupted', stoppedReason: 'server_restart', error });
3748
3846
  return null;
3749
3847
  }
3750
3848
 
@@ -3759,7 +3857,7 @@ export function createAssistantDispatcher({
3759
3857
  const message = String(text || '').trim();
3760
3858
  if (!message) throw new DispatchError('MESSAGE_REQUIRED', 'text is required');
3761
3859
  if (message.length > 20_000) throw new DispatchError('MESSAGE_TOO_LONG', 'text must be at most 20000 characters');
3762
- 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 });
3860
+ 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 });
3763
3861
  if (entry.state === 'queued') throw new DispatchError('RUN_NOT_STARTED', `Run ${runId} is still queued`, { status: 409 });
3764
3862
  // Away for a server restart (suspended, or being resumed): the follow-up waits for the run and goes to it after
3765
3863
  // its resume, like a follow-up queued behind a turn. Should the run not resume, it ends and says why.
@@ -3785,23 +3883,24 @@ export function createAssistantDispatcher({
3785
3883
  const item = { kind: 'follow-up', text: message, origin, at: iso(now()), taskId: taskNow(entry.assistantSessionId) || entry.taskId || null };
3786
3884
  // Every follow-up goes through the outbox (Agents P2), also one an idle run takes at once: the queue is one, in
3787
3885
  // order, and what it holds outlives a restart.
3788
- const idle = !away && !!liveState.waitResolve;
3886
+ const idle = !away && !!liveState.waitResolve && !followUpCount(runId);
3789
3887
  if (!idle && !allowQueue) {
3790
3888
  throw new DispatchError('TURN_ACTIVE', away
3791
3889
  ? `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`
3792
3890
  : `Run ${runId} is busy; retry when idle or pass queue:true`, { status: 409 });
3793
3891
  }
3794
- const queued = queueFollowUp(entry, item);
3795
- if (origin === 'user') emit(entry, 'user_intervened', { text: clip(message, 200) });
3796
- if (idle) {
3797
- liveState.waitResolve({ kind: 'follow-up' });
3798
- return { ok: true, queued: false, turn: liveState.turnCounter + 1, followUpId: queued.id, run: view(entry) };
3799
- }
3800
- emit(entry, 'follow_up_queued', { queued: queued.position });
3801
- return {
3802
- ok: true, queued: true, position: queued.position, followUpId: queued.id, run: view(entry),
3803
- ...(away ? { note: 'The run resumes after the server restart; this follow-up goes to it then.' } : {}),
3804
- };
3892
+ return queueFollowUp(entry, item).then(queued => {
3893
+ if (origin === 'user') emit(entry, 'user_intervened', { text: clip(message, 200) });
3894
+ liveState?.waitResolve?.({ kind: 'follow-up' });
3895
+ if (idle) {
3896
+ return { ok: true, queued: false, turn: liveState.turnCounter + 1, followUpId: queued.id, run: view(entry) };
3897
+ }
3898
+ emit(entry, 'follow_up_queued', { queued: queued.position });
3899
+ return {
3900
+ ok: true, queued: true, position: queued.position, followUpId: queued.id, run: view(entry),
3901
+ ...(away ? { note: 'The run resumes after the server restart; this follow-up goes to it then.' } : {}),
3902
+ };
3903
+ });
3805
3904
  }
3806
3905
  /**
3807
3906
  * Before a follow-up: when the run's provider share is used up, the session's unspent budget is
@@ -3815,12 +3914,12 @@ export function createAssistantDispatcher({
3815
3914
  if (blocked?.code !== 'BUDGET_SHARE_EXHAUSTED') return !blocked;
3816
3915
  return coverShare(entry);
3817
3916
  }
3818
- function complete(runId, { reason = 'complete' } = {}) {
3917
+ function complete(runId, { reason = 'complete', stopProvenance = null } = {}) {
3819
3918
  const entry = requireEntry(runId);
3820
3919
  const liveState = live.get(runId);
3821
3920
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, run: view(entry) };
3822
- if (liveState?.waitResolve) { liveState.waitResolve({ kind: 'complete', reason }); return { ok: true, run: view(entry) }; }
3823
- return stop(runId, reason);
3921
+ if (liveState?.waitResolve) { liveState.waitResolve({ kind: 'complete', reason, stopProvenance }); return { ok: true, run: view(entry) }; }
3922
+ return stop(runId, reason, stopProvenance);
3824
3923
  }
3825
3924
  /**
3826
3925
  * The user closed the sidepanel tab of a worker that reported its task done
@@ -3831,21 +3930,24 @@ export function createAssistantDispatcher({
3831
3930
  * the tab then stops it as its X always did. A run that already ended is
3832
3931
  * left as it is.
3833
3932
  */
3834
- function completeClosedTab(runId) {
3933
+ function completeClosedTab(runId, stopProvenance = null) {
3835
3934
  const entry = requireEntry(runId);
3836
3935
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, completed: false, alreadyTerminal: true, run: view(entry) };
3837
3936
  if (!finishedIdle(entry, { outcomes: ['done'] }) || !live.get(runId)?.waitResolve) {
3838
3937
  const outcome = entry.lastResult?.status || null;
3839
3938
  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 });
3840
3939
  }
3841
- return { ...complete(runId, { reason: 'tab_closed' }), completed: true };
3940
+ return { ...complete(runId, { reason: 'tab_closed', stopProvenance: stopProvenance ? stampStopProvenance('tab_closed', stopProvenance, iso(now())) : null }), completed: true };
3842
3941
  }
3843
- async function stop(runId, reason = 'assistant') {
3942
+ async function stop(runId, reason = 'unknown', stopProvenance = null) {
3844
3943
  const entry = requireEntry(runId);
3944
+ if (!TERMINAL_STATES.has(entry.state) && finalizations.has(runId)) await finalizations.get(runId);
3945
+ const provenance = stampStopProvenance(reason, stopProvenance, iso(now()));
3845
3946
  if (WAITING_STATES.has(entry.state)) {
3846
3947
  const held = entry.state === 'awaiting_route';
3847
3948
  const index = queue.indexOf(runId);
3848
3949
  if (index !== -1) queue.splice(index, 1);
3950
+ entry.stopProvenance = provenance;
3849
3951
  entry.state = 'stopped'; entry.completionReason = reason; entry.finishedAt = iso(now()); entry.turnState = 'terminal';
3850
3952
  delete entry.rawSpec;
3851
3953
  delete entry.heldAgent;
@@ -3854,38 +3956,87 @@ export function createAssistantDispatcher({
3854
3956
  return { ok: true, run: view(entry) };
3855
3957
  }
3856
3958
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, run: view(entry), alreadyTerminal: true };
3857
- entry.completionReason = entry.completionReason || reason;
3858
3959
  // A run waiting for its resume after a restart leaves the queue and drops the follow-ups that waited for it; its
3859
3960
  // runtime record (suspended) ends as stopped.
3860
3961
  if (entry.state === 'resuming' || entry.state === 'suspended') {
3962
+ // Its old process, a page reacting to the restart or an unidentified caller never ends it (lib/worker-stop.js).
3963
+ if (!mayEndSuspendedRun(provenance)) {
3964
+ log(runId, 'assistant:stop-refused', 'a suspended run stays suspended: this caller may not end it', { reason, stopProvenance: provenance });
3965
+ 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 });
3966
+ }
3861
3967
  const index = queue.indexOf(runId);
3862
3968
  if (index !== -1) queue.splice(index, 1);
3863
- cancelFollowUps(runId);
3969
+ await cancelFollowUps(runId);
3864
3970
  // A CLI a crash left behind (this start has not ended it yet) goes with the run.
3865
3971
  if (entry.state === 'resuming') await endOldProcess(entry);
3866
3972
  }
3867
3973
  const runtime = safeRuntime();
3868
- const stopped = runtime ? await runtime.stop(runId, reason) : false;
3869
- if (!stopped) finalize(entry, { status: 'stopped', stoppedReason: reason });
3974
+ // The runtime marks the run stopped before its adapter's abort answers, and a finalize started by that mark
3975
+ // waits for this stop to settle (finalizeRun): what the abort gave up on (abandonedCommands) is then on the run.
3976
+ let stopSettled = () => {};
3977
+ runtimeStops.set(runId, new Promise((resolveStop) => { stopSettled = resolveStop; }));
3978
+ let stopped = false;
3979
+ try { stopped = runtime ? await runtime.stop(runId, reason, { stopProvenance: provenance }) : false; }
3980
+ finally { runtimeStops.delete(runId); stopSettled(); }
3981
+ if (!stopped) {
3982
+ // Another stop can win while it is disposing the adapter. Keep its action and caller.
3983
+ const winner = runtime?.get?.(runId);
3984
+ await finalize(entry, TERMINAL_STATES.has(winner?.status) ? winner : { status: 'stopped', stoppedReason: reason, stopProvenance: provenance });
3985
+ } else if (!TERMINAL_STATES.has(entry.state)) {
3986
+ // During a shutdown this dispatcher no longer hears the runtime: the stop is recorded here.
3987
+ await finalize(entry, runtime.get?.(runId) || { status: 'stopped', stoppedReason: reason, stopProvenance: provenance });
3988
+ }
3870
3989
  return { ok: true, run: view(entry) };
3871
3990
  }
3872
- async function killAll({ assistantSessionId = null, workflowId = null, reason = 'kill_all' } = {}) {
3991
+ async function killAll({ assistantSessionId = null, workflowId = null, reason = 'kill_all', stopProvenance = null } = {}) {
3873
3992
  const targets = [...entries.values()].filter((entry) => ACTIVE_STATES.has(entry.state)
3874
3993
  && (!assistantSessionId || entry.assistantSessionId === assistantSessionId)
3875
3994
  && (!workflowId || entry.workflowId === workflowId));
3876
3995
  const stopped = [];
3877
- for (const entry of targets) { try { await stop(entry.runId, reason); stopped.push(entry.runId); } catch {} }
3996
+ for (const entry of targets) { try { await stop(entry.runId, reason, stopProvenance); stopped.push(entry.runId); } catch {} }
3878
3997
  return { ok: true, stopped };
3879
3998
  }
3880
3999
 
3881
4000
  // ── runtime feed → registry ────────────────────────────────────────────────
4001
+ // Native runtime notifications do not await subscribers. Keep terminal events
4002
+ // admitted through their outbox cancellation before closing the shared store.
4003
+ const finalizations = new Map();
4004
+ // runId → a promise settled when this dispatcher's runtime.stop of the run returned (stop).
4005
+ const runtimeStops = new Map();
3882
4006
  function finalize(entry, runtimeRun) {
4007
+ if (finalizations.has(entry.runId)) return finalizations.get(entry.runId);
4008
+ if (TERMINAL_STATES.has(entry.state)) return Promise.resolve();
4009
+ // Reserve the run before cleanup: settling a pending permission can synchronously notify us again.
4010
+ const work = Promise.resolve().then(() => finalizeRun(entry, runtimeRun));
4011
+ finalizations.set(entry.runId, work);
4012
+ const settled = () => finalizations.delete(entry.runId);
4013
+ work.then(settled, settled);
4014
+ return work;
4015
+ }
4016
+ async function drainFinalizations() {
4017
+ if (!finalizations.size) return;
4018
+ let timer;
4019
+ try {
4020
+ await Promise.race([
4021
+ Promise.all(finalizations.values()),
4022
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Timed out draining terminal run events')), 8000); }),
4023
+ ]);
4024
+ } finally { clearTimeout(timer); }
4025
+ }
4026
+ async function finalizeRun(entry, runtimeRun) {
3883
4027
  if (TERMINAL_STATES.has(entry.state)) return;
4028
+ // A stop of ours still under way (stop): its abort's answer is on the run once it settled (bounded by the
4029
+ // adapter's own wait for OpenCode).
4030
+ const stopping = runtimeStops.get(entry.runId);
4031
+ if (stopping) {
4032
+ await stopping;
4033
+ if (TERMINAL_STATES.has(entry.state)) return;
4034
+ const latest = safeRuntime()?.get?.(entry.runId);
4035
+ if (Array.isArray(latest?.abandonedCommands) && latest.abandonedCommands.length) runtimeRun = { ...(runtimeRun || {}), abandonedCommands: latest.abandonedCommands };
4036
+ }
3884
4037
  const liveState = live.get(entry.runId);
3885
4038
  // Follow-ups still queued for it (behind a turn, or for its resume after a restart) go with it: its notes say so.
3886
- const unsent = cancelFollowUps(entry.runId);
3887
- 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;
3888
- if (undelivered) entry.notes.push(undelivered);
4039
+ const cancelled = cancelFollowUps(entry.runId);
3889
4040
  // What its transcript showed last stays readable (agent_read format "tail") after the worker is gone.
3890
4041
  if (liveState) tails.flush(entry.runId, liveState.ring);
3891
4042
  pauseWork(entry, liveState);
@@ -3895,10 +4046,18 @@ export function createAssistantDispatcher({
3895
4046
  if (status === 'stopped' && liveState?.completed && /^state_(removed|inactive)$/.test(String(runtimeRun?.stoppedReason || ''))) status = 'completed';
3896
4047
  // A Claude Code worker the shutdown could not suspend (suspendForShutdown) ends interrupted, with why.
3897
4048
  if (status === 'stopped' && entry.refusedAtShutdown) status = 'interrupted';
3898
- entry.state = TERMINAL_STATES.has(status) ? status : 'completed';
3899
- entry.turnState = 'terminal';
3900
- entry.finishedAt = iso(now());
4049
+ const terminal = { state: TERMINAL_STATES.has(status) ? status : 'completed', turnState: 'terminal', finishedAt: iso(now()) };
4050
+ // agent_wait reads this entry directly, and a registry flush can happen at any await.
4051
+ // Stage a successful completion until its log write returns. Failures can be visible while their cause is judged.
4052
+ const completion = terminal.state === 'completed' ? terminal : null;
4053
+ if (!completion) Object.assign(entry, terminal);
3901
4054
  entry.completionReason = entry.completionReason || runtimeRun?.stoppedReason || (status === 'completed' ? 'complete' : status);
4055
+ if (runtimeRun?.stopProvenance) entry.stopProvenance = runtimeRun.stopProvenance;
4056
+ else if (!entry.stopProvenance) {
4057
+ // A limit that ended it from inside its turn loop (idle timeout, max turns) has no stop call to carry this.
4058
+ const system = systemStopProvenance(entry.completionReason);
4059
+ if (system) entry.stopProvenance = stampStopProvenance(entry.completionReason, system, terminal.finishedAt);
4060
+ }
3902
4061
  if (runtimeRun?.error) entry.error = runtimeRun.error;
3903
4062
  try { finishUsage(entry, liveState || null); } catch (error) { log(entry.runId, 'assistant:meter-error', error?.message || String(error)); }
3904
4063
  if (liveState) {
@@ -3909,19 +4068,26 @@ export function createAssistantDispatcher({
3909
4068
  }
3910
4069
  entry.pending = [];
3911
4070
  releaseDesktop(entry);
3912
- // The run's scratch folder goes when it left nothing there (what it wrote is the user's to look at).
3913
- if (entry.scratchDir) { try { rmdirSync(entry.scratchDir); } catch { /* not empty, or already gone */ } }
3914
4071
  // A run that ended gives back what it did not spend: the session's split is made again (debounced).
3915
4072
  if (entry.assistantSessionId) { try { budget.onRunEnded(entry.assistantSessionId); } catch { /* the split stays as it is */ } }
4073
+ const unsent = await cancelled;
4074
+ 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;
4075
+ if (undelivered) entry.notes.push(undelivered);
4076
+ // A command its stop could not end (OpenCode, lib/native-loop-runtime.js _abortAdapter) may still be running: the
4077
+ // result says so, by program name only (a command line can hold a token), and the brain hears it with the stop.
4078
+ const abandoned = Array.isArray(runtimeRun?.abandonedCommands) && runtimeRun.abandonedCommands.length ? abandonedPrograms(runtimeRun.abandonedCommands) : [];
4079
+ const abandonedNote = abandoned.length ? describeAbandoned(abandoned.map((command) => ({ command }))) : null;
4080
+ if (abandonedNote) { entry.abandonedCommands = abandoned; entry.notes.push(abandonedNote); }
4081
+ const endText = [abandonedNote, undelivered].filter(Boolean).join('\n');
3916
4082
  if (entry.state === 'failed' && !budgetStopReason(entry.completionReason) && judge?.workerOutcome && !isEvalRun(entry)) {
3917
4083
  // State, queue and desktop move on now; the 'failed' event waits for its cause.
3918
- emitFailed(entry, liveState?.evidence || null);
4084
+ const failed = emitFailed(entry, liveState?.evidence || null);
3919
4085
  processQueue().catch(() => {});
3920
- return;
4086
+ return failed;
3921
4087
  }
3922
- if (entry.state === 'failed' || entry.lastResult?.status === 'blocked') { noteLimit(entry); entry.escalation = computeEscalation(entry); }
4088
+ if (entry.state === 'failed' || entry.lastResult?.status === 'blocked') { noteLimit(entry); entry.escalation = computeEscalation(entry, terminal.state); }
3923
4089
  // The end event says which follow-ups never reached the worker (a stop the brain hears of carries it to its mailbox).
3924
- emit(entry, entry.state, undelivered ? { text: undelivered } : {});
4090
+ await emit(entry, terminal.state, endText ? { text: endText } : {}, completion);
3925
4091
  // A memory already stored for the run (by the worker or the brain) is the run's memory.
3926
4092
  // An evaluation run (lib/skills/evals.js) is a measurement, not work to remember: it stores no memory.
3927
4093
  if (memory?.rememberDispatch && !isEvalRun(entry) && !syncMemory(entry, { announce: true }) && (entry.state === 'completed' || (entry.state === 'stopped' && entry.lastResult))) {
@@ -3988,7 +4154,7 @@ export function createAssistantDispatcher({
3988
4154
  if (calls.size > 200) calls.delete(calls.keys().next().value);
3989
4155
  return { ...payload, event: call };
3990
4156
  }
3991
- function onRuntimeMessage(message) {
4157
+ async function onRuntimeMessage(message) {
3992
4158
  const runId = message?.run?.runId;
3993
4159
  if (!runId || !entries.has(runId)) return;
3994
4160
  const entry = entries.get(runId);
@@ -4009,11 +4175,11 @@ export function createAssistantDispatcher({
4009
4175
  // Antigravity streams each message in small chunks: one transcript line per message, grown as it streams.
4010
4176
  if (entry.provider === 'antigravity' && message.event?.eventType === 'agent_message_chunk') { growMessageLine(liveState, message.event.event); return; }
4011
4177
  const summary = summarizeProviderEvent(entry.provider === 'antigravity' ? withAcpCall(liveState, message.event || {}) : message.event || {});
4012
- // A guard decision (lib/worker-confinement.js) is also a note of the run: what was refused or warned about,
4013
- // with its reason, so the brain and the panel see it without the transcript. The first twenty.
4178
+ // A guard decision (lib/worker-confinement.js) is also a note of the run: what was refused, warned about or
4179
+ // noted after it ran, with its reason, so the brain and the panel see it without the transcript. The first twenty.
4014
4180
  if ((message.event?.eventType || message.event?.event?.type) === 'synabun.confinement') {
4015
4181
  const count = (liveState.guardEvents = (liveState.guardEvents || 0) + 1);
4016
- if (count <= 20) entry.notes.push(`guard ${message.event.event?.action || 'refused'}: ${clip(summary, 300)}`);
4182
+ if (count <= 20) entry.notes.push(summary.startsWith('guard ') ? clip(summary, 300) : `guard ${message.event.event?.action || 'refused'}: ${clip(summary, 300)}`);
4017
4183
  else if (count === 21) entry.notes.push('guard: more decisions follow in the transcript');
4018
4184
  }
4019
4185
  if (summary) pushRingLine(liveState, `${iso(now()).slice(11, 19)} ${summary}`);
@@ -4034,7 +4200,11 @@ export function createAssistantDispatcher({
4034
4200
  const newIdentity = (run.providerSessionId && run.providerSessionId !== entry.providerSessionId)
4035
4201
  || (run.providerThreadId && run.providerThreadId !== entry.providerThreadId)
4036
4202
  || (run.antigravityHome && run.antigravityHome !== entry.antigravityHome);
4037
- if (run.providerSessionId) entry.providerSessionId = run.providerSessionId;
4203
+ if (run.providerSessionId) {
4204
+ // The restart without a saved conversation has its new session: a later restart resumes that one.
4205
+ if (entry.resumeInfo?.noConversation && run.providerSessionId !== entry.providerSessionId) delete entry.resumeInfo.noConversation;
4206
+ entry.providerSessionId = run.providerSessionId;
4207
+ }
4038
4208
  if (run.providerThreadId) entry.providerThreadId = run.providerThreadId;
4039
4209
  if (run.antigravityHome) entry.antigravityHome = run.antigravityHome;
4040
4210
  if (newIdentity) persist({ force: true });
@@ -4045,7 +4215,7 @@ export function createAssistantDispatcher({
4045
4215
  return;
4046
4216
  }
4047
4217
  if (['sidepanel:run-completed', 'sidepanel:run-failed', 'sidepanel:run-stopped'].includes(message.type) || TERMINAL_STATES.has(run.status)) {
4048
- finalize(entry, run);
4218
+ await finalize(entry, run);
4049
4219
  }
4050
4220
  }
4051
4221
  function attachRuntime() {
@@ -4065,7 +4235,7 @@ export function createAssistantDispatcher({
4065
4235
  const spec = { provider: entry.provider, accountId: entry.accountId, workflowId: entry.workflowId, usesComputer: !!entry.usesComputer };
4066
4236
  if (railBlock(spec, entry.assistantSessionId, resuming ? { except: runId } : {})) continue;
4067
4237
  queue.splice(queue.indexOf(runId), 1);
4068
- if (resuming) { try { await resumeRun(entry); } catch (error) { notResumed(entry, error?.message || String(error)); } continue; }
4238
+ if (resuming) { try { await resumeRun(entry); } catch (error) { await notResumed(entry, error?.message || String(error)); } continue; }
4069
4239
  try { await start(entry); emit(entry, 'queue_started'); } catch (error) { entry.notes.push(`queue start failed: ${error?.message || error}`); }
4070
4240
  }
4071
4241
  }
@@ -4112,6 +4282,13 @@ export function createAssistantDispatcher({
4112
4282
  function teamRuns(teamId, workflowId) {
4113
4283
  return [...entries.values()].filter(entry => entry.teamId === teamId || entry.team?.teamId === teamId || entry.workflowId === workflowId).map(entry => view(entry));
4114
4284
  }
4285
+ // Approved work can still be queued when its route is replaced. Held runs belong to the pending card.
4286
+ function activeRouteRuns(sessionId, routeId) {
4287
+ return [...entries.values()]
4288
+ .filter(entry => entry.assistantSessionId === sessionId && entry.route?.routeId === routeId
4289
+ && ACTIVE_STATES.has(entry.state) && entry.state !== 'awaiting_route')
4290
+ .map(({ runId, title, state }) => ({ runId, title, state }));
4291
+ }
4115
4292
  function totals({ assistantSessionId = null, workflowId = null } = {}) {
4116
4293
  const rows = [...entries.values()].filter((entry) => (!assistantSessionId || entry.assistantSessionId === assistantSessionId) && (!workflowId || entry.workflowId === workflowId));
4117
4294
  // tokens: the five classes plus total, from the runs' ledger views (a run without one counts its legacy input / output).
@@ -4252,6 +4429,7 @@ export function createAssistantDispatcher({
4252
4429
  // what is left). A run waiting for its resume stays as it is, for the next start.
4253
4430
  suspendForShutdown(reason);
4254
4431
  for (const entry of entries.values()) {
4432
+ if (finalizations.has(entry.runId)) continue;
4255
4433
  if (entry.state === 'suspended') { signalWorkerProcess(entry); continue; }
4256
4434
  if (entry.state === 'resuming') continue;
4257
4435
  if (ACTIVE_STATES.has(entry.state)) {
@@ -4268,7 +4446,7 @@ export function createAssistantDispatcher({
4268
4446
  // Agents P2: the transcript tails are written; a service this dispatcher made for itself goes with it (the one
4269
4447
  // server.js shares is closed there, after the runtime).
4270
4448
  tails.flushAll();
4271
- if (!sharedCoordination) coordination.close();
4449
+ try { await drainFinalizations(); } finally { if (!sharedCoordination) await coordination.close(); }
4272
4450
  }
4273
4451
 
4274
4452
  loadRegistry();
@@ -4286,13 +4464,21 @@ export function createAssistantDispatcher({
4286
4464
  }
4287
4465
 
4288
4466
  return {
4289
- dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4290
- respondPermission, subscribe, shutdown, limits, suspendForShutdown,
4467
+ dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, activeRouteRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4468
+ respondPermission, subscribe, shutdown, limits, suspendForShutdown, drainFinalizations,
4291
4469
  sessionBudget, checkSession, refreshLimits, providerSpend, coverFollowUp, budget,
4292
4470
  resolveRoute, declineRoute, heldRouteRefusal, escalate,
4293
4471
  markDelivered, deliveryState, markEventsDelivered, noteBrowserRoute, noteBrowserProfile,
4294
4472
  remove, removeFinished,
4295
4473
  mediaFile,
4474
+ scratchReleased(runId, isTask, finishedMs) {
4475
+ if (!coordination.durable) return false;
4476
+ const entry = entries.get(runId);
4477
+ if (!entry) return !isTask;
4478
+ return isTask && removable(entry) && (entry.turnState == null || entry.turnState === 'terminal') && Date.parse(entry.finishedAt) <= finishedMs
4479
+ && !entry.team && !entry.teamId && !entry.pending?.length && !finalizations.has(runId)
4480
+ && coordination.followUps.cachedCount(runId) === 0;
4481
+ },
4296
4482
  accountInUse: (provider, accountId) => activeEntries((e) => e.provider === provider && e.accountId === accountId).length > 0,
4297
4483
  // agents-p4: the session's Agent density as the server reads it (the default when it is not set or cannot be read).
4298
4484
  agentDensity: (assistantSessionId) => { try { return normalizeAgentDensity(agentDensity(assistantSessionId || null)); } catch { return normalizeAgentDensity(null); } },