synabun 2.4.1 → 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 (295) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +56 -14
  4. package/browser-extension/engine.js +158 -8
  5. package/browser-extension/manifest.json +3 -1
  6. package/browser-extension/protocol.js +91 -6
  7. package/browser-extension/service-worker.js +13 -5
  8. package/browser-extension/tokens.css +1 -1
  9. package/docs/browser-extension-bridge.md +24 -4
  10. package/lib/data-home-files.js +4 -2
  11. package/lib/first-launch-protection.js +8 -2
  12. package/lib/update-snapshot.js +11 -4
  13. package/mcp-server/dist/http.d.ts.map +1 -1
  14. package/mcp-server/dist/http.js +25 -2
  15. package/mcp-server/dist/http.js.map +1 -1
  16. package/mcp-server/dist/index.d.ts.map +1 -1
  17. package/mcp-server/dist/index.js +62 -17
  18. package/mcp-server/dist/index.js.map +1 -1
  19. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  20. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  21. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  22. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  23. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  24. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  25. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  26. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  27. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  28. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  29. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  30. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  31. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  32. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  33. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  34. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  35. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  36. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  37. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  38. package/mcp-server/dist/services/memory-schema.js +190 -13
  39. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  40. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  41. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  42. package/mcp-server/dist/services/memory-sessions.js +56 -20
  43. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  44. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  45. package/mcp-server/dist/services/memory-verification.js +8 -5
  46. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  47. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  48. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  49. package/mcp-server/dist/services/neural-interface.js +19 -2
  50. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  51. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  52. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  53. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  54. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  55. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  56. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  57. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  58. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  59. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  60. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  61. package/mcp-server/dist/services/sqlite-write.js +94 -0
  62. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  63. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  64. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  65. package/mcp-server/dist/services/sqlite.js +249 -8
  66. package/mcp-server/dist/services/sqlite.js.map +1 -1
  67. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  68. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  69. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  70. package/mcp-server/dist/services/typesafe-config.js +32 -10
  71. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  72. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  73. package/mcp-server/dist/services/typesafe.js +9 -7
  74. package/mcp-server/dist/services/typesafe.js.map +1 -1
  75. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  76. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  77. package/mcp-server/dist/services/vector-cache.js +161 -8
  78. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  79. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  80. package/mcp-server/dist/tools/agents.d.ts +11 -7
  81. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  82. package/mcp-server/dist/tools/agents.js +27 -9
  83. package/mcp-server/dist/tools/agents.js.map +1 -1
  84. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  85. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  86. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  87. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  88. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  89. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  90. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  91. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  92. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  93. package/mcp-server/dist/tools/browser-interact.js +6 -1
  94. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  95. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  96. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  97. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  98. package/mcp-server/package-lock.json +2 -2
  99. package/mcp-server/package.json +1 -1
  100. package/mcp-server/src/http.ts +20 -2
  101. package/mcp-server/src/index.ts +59 -17
  102. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  103. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  104. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  105. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  106. package/mcp-server/src/services/memory-schema.ts +194 -12
  107. package/mcp-server/src/services/memory-sessions.ts +54 -21
  108. package/mcp-server/src/services/memory-verification.ts +7 -4
  109. package/mcp-server/src/services/neural-interface.ts +22 -2
  110. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  111. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  112. package/mcp-server/src/services/sqlite-write.ts +60 -0
  113. package/mcp-server/src/services/sqlite.ts +246 -8
  114. package/mcp-server/src/services/typesafe-config.ts +25 -6
  115. package/mcp-server/src/services/typesafe.ts +9 -7
  116. package/mcp-server/src/services/vector-cache.ts +154 -9
  117. package/mcp-server/src/tools/agents.ts +26 -9
  118. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  119. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  120. package/mcp-server/src/tools/browser-interact.ts +5 -1
  121. package/neural-interface/i18n/en.json +263 -1
  122. package/neural-interface/i18n/pt-BR.json +264 -2
  123. package/neural-interface/lib/agents/split.js +32 -4
  124. package/neural-interface/lib/assistant-api.js +19 -8
  125. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  126. package/neural-interface/lib/assistant-catalog.js +2 -2
  127. package/neural-interface/lib/assistant-config.js +0 -7
  128. package/neural-interface/lib/assistant-dispatch.js +257 -95
  129. package/neural-interface/lib/assistant-persona.js +16 -4
  130. package/neural-interface/lib/assistant-pricing.js +65 -14
  131. package/neural-interface/lib/assistant-router.js +131 -47
  132. package/neural-interface/lib/assistant-run-wait.js +45 -28
  133. package/neural-interface/lib/assistant-runtime.js +39 -33
  134. package/neural-interface/lib/backup-contents.js +158 -0
  135. package/neural-interface/lib/backup-crypto-io.js +330 -0
  136. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  137. package/neural-interface/lib/backup-crypto.js +525 -0
  138. package/neural-interface/lib/backup-download.js +268 -0
  139. package/neural-interface/lib/backup-encryption.js +318 -0
  140. package/neural-interface/lib/backup-groups.js +287 -0
  141. package/neural-interface/lib/backup-restore-session.js +176 -0
  142. package/neural-interface/lib/backup-restore-stage.js +60 -0
  143. package/neural-interface/lib/backup-service.js +788 -233
  144. package/neural-interface/lib/backup-zip-reader.js +30 -18
  145. package/neural-interface/lib/backup-zip-writer.js +34 -10
  146. package/neural-interface/lib/browser-extension-adapter.js +89 -13
  147. package/neural-interface/lib/browser-extension-bridge.js +18 -7
  148. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  149. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  150. package/neural-interface/lib/cli-update-planner.js +105 -6
  151. package/neural-interface/lib/client-diagnostics.js +42 -0
  152. package/neural-interface/lib/confined-fs.js +7 -2
  153. package/neural-interface/lib/coordination/README.md +8 -2
  154. package/neural-interface/lib/coordination/contract.js +161 -0
  155. package/neural-interface/lib/coordination/database.js +999 -0
  156. package/neural-interface/lib/coordination/operations.js +436 -0
  157. package/neural-interface/lib/coordination/service.js +68 -537
  158. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  159. package/neural-interface/lib/coordination/store.js +219 -1111
  160. package/neural-interface/lib/db.js +70 -32
  161. package/neural-interface/lib/health-count.js +37 -0
  162. package/neural-interface/lib/loop-stall.js +139 -0
  163. package/neural-interface/lib/maritaca/client.js +2 -2
  164. package/neural-interface/lib/maritaca/models.js +12 -17
  165. package/neural-interface/lib/maritaca/opencode.js +4 -2
  166. package/neural-interface/lib/memory-api.js +9 -1
  167. package/neural-interface/lib/memory-session-capture.js +42 -10
  168. package/neural-interface/lib/memory-store-gate.js +313 -0
  169. package/neural-interface/lib/memory-store-migrate.js +65 -0
  170. package/neural-interface/lib/memory-timers.js +7 -7
  171. package/neural-interface/lib/native-loop-providers.js +13 -16
  172. package/neural-interface/lib/native-loop-runtime.js +28 -7
  173. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  174. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  175. package/neural-interface/lib/opencode-provider-view.js +14 -3
  176. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  177. package/neural-interface/lib/opencode2-client.js +2 -1
  178. package/neural-interface/lib/recall-impact.js +122 -0
  179. package/neural-interface/lib/scratch-evidence.js +420 -0
  180. package/neural-interface/lib/scratch-process-guard.js +139 -0
  181. package/neural-interface/lib/scratch-references.js +279 -0
  182. package/neural-interface/lib/scratch-retention-core.js +385 -0
  183. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  184. package/neural-interface/lib/scratch-retention.js +151 -0
  185. package/neural-interface/lib/session-cache-builder.js +31 -43
  186. package/neural-interface/lib/session-cache-worker.js +157 -0
  187. package/neural-interface/lib/session-indexer.js +28 -21
  188. package/neural-interface/lib/session-search-index.js +85 -0
  189. package/neural-interface/lib/skills/creation.js +1 -1
  190. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  191. package/neural-interface/lib/style-guide/store.js +43 -3
  192. package/neural-interface/lib/system-restore.js +50 -0
  193. package/neural-interface/lib/teams/api.js +15 -6
  194. package/neural-interface/lib/teams/claims.js +67 -31
  195. package/neural-interface/lib/teams/index.js +7 -7
  196. package/neural-interface/lib/teams/integration.js +40 -40
  197. package/neural-interface/lib/teams/landing.js +6 -6
  198. package/neural-interface/lib/teams/recovery.js +24 -23
  199. package/neural-interface/lib/teams/scheduler.js +194 -95
  200. package/neural-interface/lib/teams/state.js +14 -14
  201. package/neural-interface/lib/teams/worktrees.js +27 -27
  202. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  203. package/neural-interface/lib/worker-confinement.js +47 -2
  204. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  205. package/neural-interface/lib/worker-resume.js +5 -0
  206. package/neural-interface/lib/worker-stop.js +86 -0
  207. package/neural-interface/package-lock.json +2 -2
  208. package/neural-interface/package.json +1 -1
  209. package/neural-interface/public/index.html +233 -24
  210. package/neural-interface/public/onboarding.html +259 -34
  211. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  212. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  213. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  214. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  215. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  216. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  217. package/neural-interface/public/shared/api.js +1 -1
  218. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  219. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  220. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  221. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  222. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  223. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  224. package/neural-interface/public/shared/assistant/asst-render.js +105 -38
  225. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  226. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  229. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  230. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  231. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  232. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  233. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  234. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  235. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  236. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  237. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  238. package/neural-interface/public/shared/effort-i18n.js +118 -0
  239. package/neural-interface/public/shared/html-shell.js +4 -52
  240. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  241. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  242. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  243. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  244. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  245. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  246. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  247. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  248. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  249. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  250. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  251. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  252. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  253. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  254. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  255. package/neural-interface/public/shared/output-format.js +294 -0
  256. package/neural-interface/public/shared/provider-icons.js +6 -0
  257. package/neural-interface/public/shared/schedules-view.js +2 -1
  258. package/neural-interface/public/shared/server-presence.js +77 -0
  259. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  260. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  261. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  262. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  263. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  264. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  265. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  266. package/neural-interface/public/shared/studio-attention.js +6 -0
  267. package/neural-interface/public/shared/styles.css +341 -437
  268. package/neural-interface/public/shared/transcript-rows.js +28 -3
  269. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  270. package/neural-interface/public/shared/ui-agents.js +1 -2
  271. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  272. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  273. package/neural-interface/public/shared/ui-loading.js +124 -17
  274. package/neural-interface/public/shared/ui-native-loop-router.js +10 -0
  275. package/neural-interface/public/shared/ui-navbar.js +2 -1
  276. package/neural-interface/public/shared/ui-output.js +533 -0
  277. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  278. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  279. package/neural-interface/public/shared/ui-sessions.js +2 -2
  280. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  281. package/neural-interface/public/shared/ui-settings.js +224 -65
  282. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  283. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  284. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  285. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  286. package/neural-interface/public/shared/worker-end.js +9 -4
  287. package/neural-interface/public/variant/2d/main.js +5 -0
  288. package/neural-interface/public/variant/3d/app.js +10 -0
  289. package/neural-interface/public/variant/3d/main.js +5 -1
  290. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  291. package/neural-interface/server.js +477 -139
  292. package/npm-shrinkwrap.json +2 -2
  293. package/package.json +1 -1
  294. package/scripts/restore-data-home-from-backup.mjs +175 -8
  295. 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';
@@ -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
 
@@ -825,17 +830,25 @@ export function createAssistantDispatcher({
825
830
  }
826
831
 
827
832
  function touch(entry) { entry.version = (Number(entry.version) || 0) + 1; entry.updatedAt = iso(now()); }
828
- function emit(entry, reason, extra = {}) {
833
+ async function emit(entry, reason, extra = {}, transition = null) {
829
834
  touch(entry);
830
- persist({ force: TERMINAL_STATES.has(entry.state) });
831
- 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 };
832
837
  // Agents P2: the event goes into the durable log in the step that changed the run, under an id that names it
833
838
  // (recording it again stores nothing), before anyone is told. It never throws: the run goes on either way.
834
- coordination.recordDispatch(payload);
839
+ await coordination.recordDispatch(payload);
840
+ if (transition) {
841
+ Object.assign(entry, transition);
842
+ persist({ force: true });
843
+ }
835
844
  if (['turn_completed', 'idle', 'failed', 'stopped', 'completed'].includes(reason)) { try { completeSkillUsage(entry); } catch {} }
836
845
  try { broadcastSync(payload); } catch {}
837
- 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 {} }
838
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);
839
852
  }
840
853
 
841
854
  // ── browser route (a run's browser moved while it works) ───────────────────
@@ -896,9 +909,9 @@ export function createAssistantDispatcher({
896
909
  * Agents P2: events a brain read through agent_wait until:"event" are settled in its session's mailbox by their
897
910
  * ids (never a second turn for them). The log keeps them: the same cursor returns them again. → how many.
898
911
  */
899
- function markEventsDelivered(assistantSessionId, eventIds) {
912
+ async function markEventsDelivered(assistantSessionId, eventIds) {
900
913
  if (!assistantSessionId || !Array.isArray(eventIds) || !eventIds.length) return 0;
901
- 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; }
902
915
  }
903
916
 
904
917
  // ── waiters (Agents P2: lib/assistant-run-wait.js) ─────────────────────────
@@ -2430,15 +2443,24 @@ export function createAssistantDispatcher({
2430
2443
  const waitForFollowUp = () => new Promise((resolveWait) => {
2431
2444
  const finish = (value) => { if (liveState.idleTimer) { clearTimeout(liveState.idleTimer); liveState.idleTimer = null; } liveState.waitResolve = null; resolveWait(value); };
2432
2445
  // 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);
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;
2441
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();
2442
2464
  liveState.idleTimer = setTimeout(() => finish({ kind: 'timeout' }), entry.idleTimeoutMs);
2443
2465
  liveState.idleTimer.unref?.();
2444
2466
  });
@@ -2462,7 +2484,7 @@ export function createAssistantDispatcher({
2462
2484
  // The work clock runs from here to the turn's end (its result-retry turn included).
2463
2485
  startWork(entry, liveState);
2464
2486
  ctx.setTurnState('running');
2465
- emit(entry, 'turn_started', { turn: turnNumber });
2487
+ await emit(entry, 'turn_started', { turn: turnNumber });
2466
2488
  persist({ force: true });
2467
2489
  // What this turn runs (commands, tool results, edited files): the evidence behind a "done".
2468
2490
  liveState.evidence = createTurnEvidence();
@@ -2470,7 +2492,7 @@ export function createAssistantDispatcher({
2470
2492
  liveState.turnMeteredUsd = 0;
2471
2493
  // A queued follow-up is sent exactly here, as its prompt goes to the provider: a restart from now on continues
2472
2494
  // 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)); } }
2495
+ if (outboxId) { try { await coordination.followUps.markSent([outboxId]); } catch (error) { log(entry.runId, 'assistant:follow-up-error', error?.message || String(error)); } }
2474
2496
  let raw = await inner.runTurn(prompt, { ...meta, turn: turnNumber, outputSchema: entry.outputSchema || undefined });
2475
2497
  if (entry.provider === 'codex') settleCodexTurn(entry, liveState, raw);
2476
2498
  else if (entry.provider === 'antigravity') settleAntigravityTurn(entry, liveState, raw);
@@ -2588,7 +2610,7 @@ export function createAssistantDispatcher({
2588
2610
  // The worker remembers before its ## Result block: this turn's events carry that memory.
2589
2611
  syncMemory(entry);
2590
2612
  if (parsed.status === 'needs_input') emit(entry, 'needs_input', { turn: turnNumber, question: parsed.question });
2591
- emit(entry, 'turn_completed', { turn: turnNumber });
2613
+ await emit(entry, 'turn_completed', { turn: turnNumber });
2592
2614
  announceUnpriced(entry);
2593
2615
  checkSession(entry.assistantSessionId, { source: entry });
2594
2616
  return parsed;
@@ -2610,6 +2632,10 @@ export function createAssistantDispatcher({
2610
2632
  : { origin: 'dispatch' });
2611
2633
  } catch (error) {
2612
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
+ }
2613
2639
  return handleTurnError(error, liveState, entry, ctx);
2614
2640
  }
2615
2641
  }
@@ -2630,7 +2656,15 @@ export function createAssistantDispatcher({
2630
2656
  const next = await waitForFollowUp();
2631
2657
  if (liveState.suspending) return { providerSessionId: null };
2632
2658
  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 }; }
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
+ }
2634
2668
  if (next.kind === 'timeout') { entry.completionReason = 'idle_timeout'; return { providerSessionId: inner.identity?.()?.providerSessionId }; }
2635
2669
  if (liveState.turnCounter >= entry.maxTurns) {
2636
2670
  entry.completionReason = 'max_turns';
@@ -3434,7 +3468,10 @@ export function createAssistantDispatcher({
3434
3468
  closing = true;
3435
3469
  const kept = [];
3436
3470
  for (const entry of entries.values()) {
3437
- 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;
3438
3475
  const liveState = live.get(entry.runId) || null;
3439
3476
  // Only a run whose worker is up, or whose resume is starting it (its session is known): one still starting for
3440
3477
  // the first time has no session to resume yet.
@@ -3478,6 +3515,32 @@ export function createAssistantDispatcher({
3478
3515
  if (kept.length) persist({ force: true });
3479
3516
  return kept;
3480
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
+ }
3481
3544
  /** Book pending provider usage and save the meter baseline before the process ends. */
3482
3545
  function suspendUsage(entry, liveState) {
3483
3546
  if (entry.provider === 'codex') pollCodex(entry, liveState, { discover: true });
@@ -3561,12 +3624,22 @@ export function createAssistantDispatcher({
3561
3624
  const ids = bootResumes.splice(0)
3562
3625
  .map((runId) => entries.get(runId)).filter((entry) => entry?.state === 'resuming')
3563
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))
3564
3629
  .map((entry) => entry.runId);
3565
3630
  // Held for this dispatcher from here on: the runtime's own hold no longer ends them.
3566
3631
  for (const runId of ids) { try { runtime?.keepSuspended?.(runId); } catch { /* ended meanwhile */ } }
3567
3632
  for (const runId of bootInterrupts.splice(0)) {
3568
3633
  const entry = entries.get(runId);
3569
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
+ }
3570
3643
  // A CLI a crash left behind goes with the run.
3571
3644
  await endOldProcess(entry);
3572
3645
  try { await runtime?.endSuspended?.(runId, 'server_restart', { error: entry.resumeRefused ? `not resumed: ${entry.resumeRefused}` : null }); } catch { /* not held */ }
@@ -3582,7 +3655,7 @@ export function createAssistantDispatcher({
3582
3655
  const block = railBlock(spec, entry.assistantSessionId, { except: runId });
3583
3656
  if (block) { entry.notes.push(`resume queued: ${block}`); held.push(runId); persist(); continue; }
3584
3657
  // 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)); }
3658
+ try { await resumeRun(entry); } catch (error) { log(runId, 'assistant:resume-error', error?.message || String(error)); await notResumed(entry, error?.message || String(error)); }
3586
3659
  }
3587
3660
  if (held.length) { queue.unshift(...held); processQueue().catch(() => {}); }
3588
3661
  }
@@ -3603,26 +3676,30 @@ export function createAssistantDispatcher({
3603
3676
  async function continueRun(entry) {
3604
3677
  if (closing) return null;
3605
3678
  const runtime = safeRuntime();
3606
- 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; }
3607
3684
  refreshLimits();
3608
3685
  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})`); }
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})`); }
3611
3688
  if (entry.state !== 'resuming' || closing) return null; // stopped meanwhile, or the server is going down again
3612
3689
  // Its own ceiling (budget_usd), with what its cut-off turn was booked at the suspension (fitBudget checks the
3613
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.
3614
3691
  const spentOut = budgetBlock(entry);
3615
3692
  if (spentOut && spentOut.code !== 'BUDGET_SHARE_EXHAUSTED') {
3616
3693
  entry.completionReason = spentOut.reason;
3617
- return notResumed(entry, `the budget does not allow it (${spentOut.message})`);
3694
+ return await notResumed(entry, `the budget does not allow it (${spentOut.message})`);
3618
3695
  }
3619
- 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');
3620
3697
  // A crash ended no process: the CLI the run had may still be there, finishing the cut-off tool call. It is ended
3621
3698
  // first; one that cannot be checked keeps the run from resuming (two processes on one session would both write its
3622
3699
  // transcript).
3623
3700
  const orphan = await endOldProcess(entry);
3624
3701
  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'}`);
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'}`);
3626
3703
  }
3627
3704
  if (entry.state !== 'resuming' || closing) return null;
3628
3705
  const costBaseUsd = entry.provider === 'claude-code' ? rebaseClaudeUsage(entry) : 0;
@@ -3632,8 +3709,9 @@ export function createAssistantDispatcher({
3632
3709
  let browserTabId = null;
3633
3710
  if (entry.usesBrowser && typeof acquireLoopBrowserAndTab === 'function') {
3634
3711
  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}`);
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}`);
3637
3715
  browserSessionId = acq.browserSessionId || null;
3638
3716
  browserTabId = acq.browserTabId || null;
3639
3717
  }
@@ -3646,7 +3724,9 @@ export function createAssistantDispatcher({
3646
3724
  if (entry.scratchDir) { try { mkdirSync(entry.scratchDir, { recursive: true }); } catch { /* the guard says so when it needs it */ } }
3647
3725
  const inFlight = entry.resumeInfo?.inFlight || null;
3648
3726
  const turned = lastTurnNumber(entry);
3649
- 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';
3650
3730
  const liveState = newLiveState(entry);
3651
3731
  liveState.turnCounter = turned;
3652
3732
  liveState.resume = { mode, taskId: inFlight?.taskId || null };
@@ -3658,7 +3738,7 @@ export function createAssistantDispatcher({
3658
3738
  const state = runState(entry, {
3659
3739
  browserSessionId, browserTabId, desktopGrant,
3660
3740
  startedAt: entry.startedAt || iso(now()),
3661
- 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 },
3662
3742
  });
3663
3743
  // The CLI's spend stop (--max-budget-usd) counts from the total the resumed CLI restores (costBaseUsd): what the run
3664
3744
  // may still spend (its ceiling less what it spent, never more than the session has left) goes on top of that. A
@@ -3694,7 +3774,7 @@ export function createAssistantDispatcher({
3694
3774
  // The runtime ended its record (resume_failed): its run-stopped event ended the run here too.
3695
3775
  const why = error?.message || String(error);
3696
3776
  if (browserSessionId) await releaseSharedBrowserTab(browserSessionId, entry.runId).catch(() => {});
3697
- if (!TERMINAL_STATES.has(entry.state)) return notResumed(entry, why);
3777
+ if (!TERMINAL_STATES.has(entry.state)) return await notResumed(entry, why);
3698
3778
  entry.notes.push(`not resumed: ${why}`);
3699
3779
  persist();
3700
3780
  return null;
@@ -3709,6 +3789,23 @@ export function createAssistantDispatcher({
3709
3789
  reconcileKeepAwake();
3710
3790
  return view(entry);
3711
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
+ }
3712
3809
  /**
3713
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
3714
3811
  * is ended once its command line shows it is this run's (lib/worker-resume.js endOrphanProcess), before a resume and
@@ -3727,12 +3824,12 @@ export function createAssistantDispatcher({
3727
3824
  return { ...orphan, pid };
3728
3825
  }
3729
3826
  /** 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) {
3827
+ async function notResumed(entry, why) {
3731
3828
  if (TERMINAL_STATES.has(entry.state)) return null;
3732
3829
  const index = queue.indexOf(entry.runId);
3733
3830
  if (index !== -1) queue.splice(index, 1);
3734
3831
  // 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);
3832
+ const waiting = await cancelFollowUps(entry.runId);
3736
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)}")` : '';
3737
3834
  // Nothing of it may go on: a CLI a crash left behind is ended too.
3738
3835
  endOldProcess(entry).then(() => persist()).catch(() => {});
@@ -3744,7 +3841,7 @@ export function createAssistantDispatcher({
3744
3841
  try { ended = !!safeRuntime()?.isSuspended?.(entry.runId); } catch { ended = false; }
3745
3842
  // The runtime's run-stopped event finalizes the run here (onRuntimeMessage); without a record it is done here.
3746
3843
  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 });
3844
+ if (!TERMINAL_STATES.has(entry.state)) await finalize(entry, { status: 'interrupted', stoppedReason: 'server_restart', error });
3748
3845
  return null;
3749
3846
  }
3750
3847
 
@@ -3759,7 +3856,7 @@ export function createAssistantDispatcher({
3759
3856
  const message = String(text || '').trim();
3760
3857
  if (!message) throw new DispatchError('MESSAGE_REQUIRED', 'text is required');
3761
3858
  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 });
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 });
3763
3860
  if (entry.state === 'queued') throw new DispatchError('RUN_NOT_STARTED', `Run ${runId} is still queued`, { status: 409 });
3764
3861
  // Away for a server restart (suspended, or being resumed): the follow-up waits for the run and goes to it after
3765
3862
  // its resume, like a follow-up queued behind a turn. Should the run not resume, it ends and says why.
@@ -3785,23 +3882,24 @@ export function createAssistantDispatcher({
3785
3882
  const item = { kind: 'follow-up', text: message, origin, at: iso(now()), taskId: taskNow(entry.assistantSessionId) || entry.taskId || null };
3786
3883
  // Every follow-up goes through the outbox (Agents P2), also one an idle run takes at once: the queue is one, in
3787
3884
  // order, and what it holds outlives a restart.
3788
- const idle = !away && !!liveState.waitResolve;
3885
+ const idle = !away && !!liveState.waitResolve && !followUpCount(runId);
3789
3886
  if (!idle && !allowQueue) {
3790
3887
  throw new DispatchError('TURN_ACTIVE', away
3791
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`
3792
3889
  : `Run ${runId} is busy; retry when idle or pass queue:true`, { status: 409 });
3793
3890
  }
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
- };
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
+ });
3805
3903
  }
3806
3904
  /**
3807
3905
  * Before a follow-up: when the run's provider share is used up, the session's unspent budget is
@@ -3815,12 +3913,12 @@ export function createAssistantDispatcher({
3815
3913
  if (blocked?.code !== 'BUDGET_SHARE_EXHAUSTED') return !blocked;
3816
3914
  return coverShare(entry);
3817
3915
  }
3818
- function complete(runId, { reason = 'complete' } = {}) {
3916
+ function complete(runId, { reason = 'complete', stopProvenance = null } = {}) {
3819
3917
  const entry = requireEntry(runId);
3820
3918
  const liveState = live.get(runId);
3821
3919
  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);
3920
+ if (liveState?.waitResolve) { liveState.waitResolve({ kind: 'complete', reason, stopProvenance }); return { ok: true, run: view(entry) }; }
3921
+ return stop(runId, reason, stopProvenance);
3824
3922
  }
3825
3923
  /**
3826
3924
  * The user closed the sidepanel tab of a worker that reported its task done
@@ -3831,21 +3929,24 @@ export function createAssistantDispatcher({
3831
3929
  * the tab then stops it as its X always did. A run that already ended is
3832
3930
  * left as it is.
3833
3931
  */
3834
- function completeClosedTab(runId) {
3932
+ function completeClosedTab(runId, stopProvenance = null) {
3835
3933
  const entry = requireEntry(runId);
3836
3934
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, completed: false, alreadyTerminal: true, run: view(entry) };
3837
3935
  if (!finishedIdle(entry, { outcomes: ['done'] }) || !live.get(runId)?.waitResolve) {
3838
3936
  const outcome = entry.lastResult?.status || null;
3839
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 });
3840
3938
  }
3841
- 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 };
3842
3940
  }
3843
- async function stop(runId, reason = 'assistant') {
3941
+ async function stop(runId, reason = 'unknown', stopProvenance = null) {
3844
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()));
3845
3945
  if (WAITING_STATES.has(entry.state)) {
3846
3946
  const held = entry.state === 'awaiting_route';
3847
3947
  const index = queue.indexOf(runId);
3848
3948
  if (index !== -1) queue.splice(index, 1);
3949
+ entry.stopProvenance = provenance;
3849
3950
  entry.state = 'stopped'; entry.completionReason = reason; entry.finishedAt = iso(now()); entry.turnState = 'terminal';
3850
3951
  delete entry.rawSpec;
3851
3952
  delete entry.heldAgent;
@@ -3854,38 +3955,70 @@ export function createAssistantDispatcher({
3854
3955
  return { ok: true, run: view(entry) };
3855
3956
  }
3856
3957
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, run: view(entry), alreadyTerminal: true };
3857
- entry.completionReason = entry.completionReason || reason;
3858
3958
  // A run waiting for its resume after a restart leaves the queue and drops the follow-ups that waited for it; its
3859
3959
  // runtime record (suspended) ends as stopped.
3860
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
+ }
3861
3966
  const index = queue.indexOf(runId);
3862
3967
  if (index !== -1) queue.splice(index, 1);
3863
- cancelFollowUps(runId);
3968
+ await cancelFollowUps(runId);
3864
3969
  // A CLI a crash left behind (this start has not ended it yet) goes with the run.
3865
3970
  if (entry.state === 'resuming') await endOldProcess(entry);
3866
3971
  }
3867
3972
  const runtime = safeRuntime();
3868
- const stopped = runtime ? await runtime.stop(runId, reason) : false;
3869
- 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
+ }
3870
3982
  return { ok: true, run: view(entry) };
3871
3983
  }
3872
- async function killAll({ assistantSessionId = null, workflowId = null, reason = 'kill_all' } = {}) {
3984
+ async function killAll({ assistantSessionId = null, workflowId = null, reason = 'kill_all', stopProvenance = null } = {}) {
3873
3985
  const targets = [...entries.values()].filter((entry) => ACTIVE_STATES.has(entry.state)
3874
3986
  && (!assistantSessionId || entry.assistantSessionId === assistantSessionId)
3875
3987
  && (!workflowId || entry.workflowId === workflowId));
3876
3988
  const stopped = [];
3877
- 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 {} }
3878
3990
  return { ok: true, stopped };
3879
3991
  }
3880
3992
 
3881
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();
3882
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) {
3883
4018
  if (TERMINAL_STATES.has(entry.state)) return;
3884
4019
  const liveState = live.get(entry.runId);
3885
4020
  // 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);
4021
+ const cancelled = cancelFollowUps(entry.runId);
3889
4022
  // What its transcript showed last stays readable (agent_read format "tail") after the worker is gone.
3890
4023
  if (liveState) tails.flush(entry.runId, liveState.ring);
3891
4024
  pauseWork(entry, liveState);
@@ -3895,10 +4028,18 @@ export function createAssistantDispatcher({
3895
4028
  if (status === 'stopped' && liveState?.completed && /^state_(removed|inactive)$/.test(String(runtimeRun?.stoppedReason || ''))) status = 'completed';
3896
4029
  // A Claude Code worker the shutdown could not suspend (suspendForShutdown) ends interrupted, with why.
3897
4030
  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());
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);
3901
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
+ }
3902
4043
  if (runtimeRun?.error) entry.error = runtimeRun.error;
3903
4044
  try { finishUsage(entry, liveState || null); } catch (error) { log(entry.runId, 'assistant:meter-error', error?.message || String(error)); }
3904
4045
  if (liveState) {
@@ -3909,19 +4050,20 @@ export function createAssistantDispatcher({
3909
4050
  }
3910
4051
  entry.pending = [];
3911
4052
  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
4053
  // A run that ended gives back what it did not spend: the session's split is made again (debounced).
3915
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);
3916
4058
  if (entry.state === 'failed' && !budgetStopReason(entry.completionReason) && judge?.workerOutcome && !isEvalRun(entry)) {
3917
4059
  // State, queue and desktop move on now; the 'failed' event waits for its cause.
3918
- emitFailed(entry, liveState?.evidence || null);
4060
+ const failed = emitFailed(entry, liveState?.evidence || null);
3919
4061
  processQueue().catch(() => {});
3920
- return;
4062
+ return failed;
3921
4063
  }
3922
- 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); }
3923
4065
  // 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 } : {});
4066
+ await emit(entry, terminal.state, undelivered ? { text: undelivered } : {}, completion);
3925
4067
  // A memory already stored for the run (by the worker or the brain) is the run's memory.
3926
4068
  // An evaluation run (lib/skills/evals.js) is a measurement, not work to remember: it stores no memory.
3927
4069
  if (memory?.rememberDispatch && !isEvalRun(entry) && !syncMemory(entry, { announce: true }) && (entry.state === 'completed' || (entry.state === 'stopped' && entry.lastResult))) {
@@ -3988,7 +4130,7 @@ export function createAssistantDispatcher({
3988
4130
  if (calls.size > 200) calls.delete(calls.keys().next().value);
3989
4131
  return { ...payload, event: call };
3990
4132
  }
3991
- function onRuntimeMessage(message) {
4133
+ async function onRuntimeMessage(message) {
3992
4134
  const runId = message?.run?.runId;
3993
4135
  if (!runId || !entries.has(runId)) return;
3994
4136
  const entry = entries.get(runId);
@@ -4009,11 +4151,11 @@ export function createAssistantDispatcher({
4009
4151
  // Antigravity streams each message in small chunks: one transcript line per message, grown as it streams.
4010
4152
  if (entry.provider === 'antigravity' && message.event?.eventType === 'agent_message_chunk') { growMessageLine(liveState, message.event.event); return; }
4011
4153
  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.
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.
4014
4156
  if ((message.event?.eventType || message.event?.event?.type) === 'synabun.confinement') {
4015
4157
  const count = (liveState.guardEvents = (liveState.guardEvents || 0) + 1);
4016
- 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)}`);
4017
4159
  else if (count === 21) entry.notes.push('guard: more decisions follow in the transcript');
4018
4160
  }
4019
4161
  if (summary) pushRingLine(liveState, `${iso(now()).slice(11, 19)} ${summary}`);
@@ -4034,7 +4176,11 @@ export function createAssistantDispatcher({
4034
4176
  const newIdentity = (run.providerSessionId && run.providerSessionId !== entry.providerSessionId)
4035
4177
  || (run.providerThreadId && run.providerThreadId !== entry.providerThreadId)
4036
4178
  || (run.antigravityHome && run.antigravityHome !== entry.antigravityHome);
4037
- 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
+ }
4038
4184
  if (run.providerThreadId) entry.providerThreadId = run.providerThreadId;
4039
4185
  if (run.antigravityHome) entry.antigravityHome = run.antigravityHome;
4040
4186
  if (newIdentity) persist({ force: true });
@@ -4045,7 +4191,7 @@ export function createAssistantDispatcher({
4045
4191
  return;
4046
4192
  }
4047
4193
  if (['sidepanel:run-completed', 'sidepanel:run-failed', 'sidepanel:run-stopped'].includes(message.type) || TERMINAL_STATES.has(run.status)) {
4048
- finalize(entry, run);
4194
+ await finalize(entry, run);
4049
4195
  }
4050
4196
  }
4051
4197
  function attachRuntime() {
@@ -4065,7 +4211,7 @@ export function createAssistantDispatcher({
4065
4211
  const spec = { provider: entry.provider, accountId: entry.accountId, workflowId: entry.workflowId, usesComputer: !!entry.usesComputer };
4066
4212
  if (railBlock(spec, entry.assistantSessionId, resuming ? { except: runId } : {})) continue;
4067
4213
  queue.splice(queue.indexOf(runId), 1);
4068
- 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; }
4069
4215
  try { await start(entry); emit(entry, 'queue_started'); } catch (error) { entry.notes.push(`queue start failed: ${error?.message || error}`); }
4070
4216
  }
4071
4217
  }
@@ -4112,6 +4258,13 @@ export function createAssistantDispatcher({
4112
4258
  function teamRuns(teamId, workflowId) {
4113
4259
  return [...entries.values()].filter(entry => entry.teamId === teamId || entry.team?.teamId === teamId || entry.workflowId === workflowId).map(entry => view(entry));
4114
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
+ }
4115
4268
  function totals({ assistantSessionId = null, workflowId = null } = {}) {
4116
4269
  const rows = [...entries.values()].filter((entry) => (!assistantSessionId || entry.assistantSessionId === assistantSessionId) && (!workflowId || entry.workflowId === workflowId));
4117
4270
  // tokens: the five classes plus total, from the runs' ledger views (a run without one counts its legacy input / output).
@@ -4252,6 +4405,7 @@ export function createAssistantDispatcher({
4252
4405
  // what is left). A run waiting for its resume stays as it is, for the next start.
4253
4406
  suspendForShutdown(reason);
4254
4407
  for (const entry of entries.values()) {
4408
+ if (finalizations.has(entry.runId)) continue;
4255
4409
  if (entry.state === 'suspended') { signalWorkerProcess(entry); continue; }
4256
4410
  if (entry.state === 'resuming') continue;
4257
4411
  if (ACTIVE_STATES.has(entry.state)) {
@@ -4268,7 +4422,7 @@ export function createAssistantDispatcher({
4268
4422
  // Agents P2: the transcript tails are written; a service this dispatcher made for itself goes with it (the one
4269
4423
  // server.js shares is closed there, after the runtime).
4270
4424
  tails.flushAll();
4271
- if (!sharedCoordination) coordination.close();
4425
+ try { await drainFinalizations(); } finally { if (!sharedCoordination) await coordination.close(); }
4272
4426
  }
4273
4427
 
4274
4428
  loadRegistry();
@@ -4286,13 +4440,21 @@ export function createAssistantDispatcher({
4286
4440
  }
4287
4441
 
4288
4442
  return {
4289
- dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4290
- 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,
4291
4445
  sessionBudget, checkSession, refreshLimits, providerSpend, coverFollowUp, budget,
4292
4446
  resolveRoute, declineRoute, heldRouteRefusal, escalate,
4293
4447
  markDelivered, deliveryState, markEventsDelivered, noteBrowserRoute, noteBrowserProfile,
4294
4448
  remove, removeFinished,
4295
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
+ },
4296
4458
  accountInUse: (provider, accountId) => activeEntries((e) => e.provider === provider && e.accountId === accountId).length > 0,
4297
4459
  // agents-p4: the session's Agent density as the server reads it (the default when it is not set or cannot be read).
4298
4460
  agentDensity: (assistantSessionId) => { try { return normalizeAgentDensity(agentDensity(assistantSessionId || null)); } catch { return normalizeAgentDensity(null); } },