@qodeca/xezar 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (481) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +810 -0
  3. package/dist/agent-config/account-identity.d.ts +44 -0
  4. package/dist/agent-config/account-identity.js +128 -0
  5. package/dist/agent-config/account-identity.js.map +1 -0
  6. package/dist/agent-config/catalog.d.ts +71 -0
  7. package/dist/agent-config/catalog.js +223 -0
  8. package/dist/agent-config/catalog.js.map +1 -0
  9. package/dist/agent-config/files.d.ts +46 -0
  10. package/dist/agent-config/files.js +119 -0
  11. package/dist/agent-config/files.js.map +1 -0
  12. package/dist/agent-config/model-settings/claude.d.ts +2 -0
  13. package/dist/agent-config/model-settings/claude.js +11 -0
  14. package/dist/agent-config/model-settings/claude.js.map +1 -0
  15. package/dist/agent-config/model-settings/codex.d.ts +2 -0
  16. package/dist/agent-config/model-settings/codex.js +16 -0
  17. package/dist/agent-config/model-settings/codex.js.map +1 -0
  18. package/dist/agent-config/model-settings/opencode.d.ts +2 -0
  19. package/dist/agent-config/model-settings/opencode.js +8 -0
  20. package/dist/agent-config/model-settings/opencode.js.map +1 -0
  21. package/dist/agent-config/model-settings/pi.d.ts +12 -0
  22. package/dist/agent-config/model-settings/pi.js +18 -0
  23. package/dist/agent-config/model-settings/pi.js.map +1 -0
  24. package/dist/agent-config/model-settings/shared.d.ts +9 -0
  25. package/dist/agent-config/model-settings/shared.js +93 -0
  26. package/dist/agent-config/model-settings/shared.js.map +1 -0
  27. package/dist/agent-config/model-settings/types.d.ts +9 -0
  28. package/dist/agent-config/model-settings/types.js +2 -0
  29. package/dist/agent-config/model-settings/types.js.map +1 -0
  30. package/dist/agent-config/models.d.ts +9 -0
  31. package/dist/agent-config/models.js +32 -0
  32. package/dist/agent-config/models.js.map +1 -0
  33. package/dist/agent-config/seed.d.ts +7 -0
  34. package/dist/agent-config/seed.js +90 -0
  35. package/dist/agent-config/seed.js.map +1 -0
  36. package/dist/agent-config/service.d.ts +44 -0
  37. package/dist/agent-config/service.js +71 -0
  38. package/dist/agent-config/service.js.map +1 -0
  39. package/dist/agent-config/validate.d.ts +21 -0
  40. package/dist/agent-config/validate.js +76 -0
  41. package/dist/agent-config/validate.js.map +1 -0
  42. package/dist/automations/coordinator.d.ts +26 -0
  43. package/dist/automations/coordinator.js +66 -0
  44. package/dist/automations/coordinator.js.map +1 -0
  45. package/dist/automations/github-poller.d.ts +74 -0
  46. package/dist/automations/github-poller.js +234 -0
  47. package/dist/automations/github-poller.js.map +1 -0
  48. package/dist/automations/scheduler.d.ts +42 -0
  49. package/dist/automations/scheduler.js +192 -0
  50. package/dist/automations/scheduler.js.map +1 -0
  51. package/dist/automations/store.d.ts +65 -0
  52. package/dist/automations/store.js +298 -0
  53. package/dist/automations/store.js.map +1 -0
  54. package/dist/automations/task-template.d.ts +18 -0
  55. package/dist/automations/task-template.js +95 -0
  56. package/dist/automations/task-template.js.map +1 -0
  57. package/dist/automations/types.d.ts +255 -0
  58. package/dist/automations/types.js +159 -0
  59. package/dist/automations/types.js.map +1 -0
  60. package/dist/config.d.ts +77 -0
  61. package/dist/config.js +242 -0
  62. package/dist/config.js.map +1 -0
  63. package/dist/contract/agent-config.d.ts +153 -0
  64. package/dist/contract/agent-profiles.d.ts +347 -0
  65. package/dist/contract/automations.d.ts +935 -0
  66. package/dist/contract/events.d.ts +104 -0
  67. package/dist/contract/github.d.ts +597 -0
  68. package/dist/contract/health.d.ts +102 -0
  69. package/dist/contract/index.d.ts +16 -0
  70. package/dist/contract/index.js +1953 -0
  71. package/dist/contract/projects.d.ts +210 -0
  72. package/dist/contract/repo.d.ts +234 -0
  73. package/dist/contract/runs.d.ts +1527 -0
  74. package/dist/contract/skills.d.ts +234 -0
  75. package/dist/contract/workflows.d.ts +218 -0
  76. package/dist/contract/workspace.d.ts +579 -0
  77. package/dist/core/agent-env.d.ts +31 -0
  78. package/dist/core/agent-env.js +371 -0
  79. package/dist/core/agent-env.js.map +1 -0
  80. package/dist/core/agent-model-policy.d.ts +10 -0
  81. package/dist/core/agent-model-policy.js +36 -0
  82. package/dist/core/agent-model-policy.js.map +1 -0
  83. package/dist/core/agent-profiles.d.ts +62 -0
  84. package/dist/core/agent-profiles.js +90 -0
  85. package/dist/core/agent-profiles.js.map +1 -0
  86. package/dist/core/agent-runner.d.ts +211 -0
  87. package/dist/core/agent-runner.js +68 -0
  88. package/dist/core/agent-runner.js.map +1 -0
  89. package/dist/core/ask.d.ts +115 -0
  90. package/dist/core/ask.js +256 -0
  91. package/dist/core/ask.js.map +1 -0
  92. package/dist/core/backend-detect.d.ts +16 -0
  93. package/dist/core/backend-detect.js +155 -0
  94. package/dist/core/backend-detect.js.map +1 -0
  95. package/dist/core/claude-cli-runner.d.ts +65 -0
  96. package/dist/core/claude-cli-runner.js +479 -0
  97. package/dist/core/claude-cli-runner.js.map +1 -0
  98. package/dist/core/claude-model-catalog.d.ts +24 -0
  99. package/dist/core/claude-model-catalog.js +208 -0
  100. package/dist/core/claude-model-catalog.js.map +1 -0
  101. package/dist/core/claude-ui-mapper.d.ts +79 -0
  102. package/dist/core/claude-ui-mapper.js +597 -0
  103. package/dist/core/claude-ui-mapper.js.map +1 -0
  104. package/dist/core/codex-app-server-runner.d.ts +41 -0
  105. package/dist/core/codex-app-server-runner.js +584 -0
  106. package/dist/core/codex-app-server-runner.js.map +1 -0
  107. package/dist/core/codex-app-server-transport.d.ts +35 -0
  108. package/dist/core/codex-app-server-transport.js +150 -0
  109. package/dist/core/codex-app-server-transport.js.map +1 -0
  110. package/dist/core/codex-model-catalog.d.ts +10 -0
  111. package/dist/core/codex-model-catalog.js +110 -0
  112. package/dist/core/codex-model-catalog.js.map +1 -0
  113. package/dist/core/codex-ui-mapper.d.ts +109 -0
  114. package/dist/core/codex-ui-mapper.js +764 -0
  115. package/dist/core/codex-ui-mapper.js.map +1 -0
  116. package/dist/core/model-identity.d.ts +125 -0
  117. package/dist/core/model-identity.js +132 -0
  118. package/dist/core/model-identity.js.map +1 -0
  119. package/dist/core/model-presets.d.ts +21 -0
  120. package/dist/core/model-presets.js +91 -0
  121. package/dist/core/model-presets.js.map +1 -0
  122. package/dist/core/ndjson.d.ts +6 -0
  123. package/dist/core/ndjson.js +23 -0
  124. package/dist/core/ndjson.js.map +1 -0
  125. package/dist/core/opencode-model-catalog.d.ts +32 -0
  126. package/dist/core/opencode-model-catalog.js +153 -0
  127. package/dist/core/opencode-model-catalog.js.map +1 -0
  128. package/dist/core/opencode-server-runner.d.ts +32 -0
  129. package/dist/core/opencode-server-runner.js +535 -0
  130. package/dist/core/opencode-server-runner.js.map +1 -0
  131. package/dist/core/opencode-ui-mapper.d.ts +111 -0
  132. package/dist/core/opencode-ui-mapper.js +668 -0
  133. package/dist/core/opencode-ui-mapper.js.map +1 -0
  134. package/dist/core/pi-runner.d.ts +24 -0
  135. package/dist/core/pi-runner.js +349 -0
  136. package/dist/core/pi-runner.js.map +1 -0
  137. package/dist/core/pi-ui-mapper.d.ts +34 -0
  138. package/dist/core/pi-ui-mapper.js +270 -0
  139. package/dist/core/pi-ui-mapper.js.map +1 -0
  140. package/dist/core/process-usage.d.ts +66 -0
  141. package/dist/core/process-usage.js +193 -0
  142. package/dist/core/process-usage.js.map +1 -0
  143. package/dist/core/provider-auth.d.ts +154 -0
  144. package/dist/core/provider-auth.js +509 -0
  145. package/dist/core/provider-auth.js.map +1 -0
  146. package/dist/core/provider-availability.d.ts +3 -0
  147. package/dist/core/provider-availability.js +14 -0
  148. package/dist/core/provider-availability.js.map +1 -0
  149. package/dist/core/runner-factory.d.ts +8 -0
  150. package/dist/core/runner-factory.js +25 -0
  151. package/dist/core/runner-factory.js.map +1 -0
  152. package/dist/core/runner-model-catalog.d.ts +28 -0
  153. package/dist/core/runner-model-catalog.js +62 -0
  154. package/dist/core/runner-model-catalog.js.map +1 -0
  155. package/dist/core/secret-redaction.d.ts +37 -0
  156. package/dist/core/secret-redaction.js +115 -0
  157. package/dist/core/secret-redaction.js.map +1 -0
  158. package/dist/core/shell-env.d.ts +28 -0
  159. package/dist/core/shell-env.js +56 -0
  160. package/dist/core/shell-env.js.map +1 -0
  161. package/dist/core/tool-display.d.ts +31 -0
  162. package/dist/core/tool-display.js +179 -0
  163. package/dist/core/tool-display.js.map +1 -0
  164. package/dist/core/ui-events.d.ts +332 -0
  165. package/dist/core/ui-events.js +22 -0
  166. package/dist/core/ui-events.js.map +1 -0
  167. package/dist/core/usage-limit.d.ts +42 -0
  168. package/dist/core/usage-limit.js +209 -0
  169. package/dist/core/usage-limit.js.map +1 -0
  170. package/dist/core/usage.d.ts +11 -0
  171. package/dist/core/usage.js +15 -0
  172. package/dist/core/usage.js.map +1 -0
  173. package/dist/core/v1-text-coalescer.d.ts +36 -0
  174. package/dist/core/v1-text-coalescer.js +72 -0
  175. package/dist/core/v1-text-coalescer.js.map +1 -0
  176. package/dist/git-diff-base.d.ts +85 -0
  177. package/dist/git-diff-base.js +180 -0
  178. package/dist/git-diff-base.js.map +1 -0
  179. package/dist/git-refs.d.ts +11 -0
  180. package/dist/git-refs.js +14 -0
  181. package/dist/git-refs.js.map +1 -0
  182. package/dist/git-worktree.d.ts +161 -0
  183. package/dist/git-worktree.js +508 -0
  184. package/dist/git-worktree.js.map +1 -0
  185. package/dist/handoff.d.ts +62 -0
  186. package/dist/handoff.js +154 -0
  187. package/dist/handoff.js.map +1 -0
  188. package/dist/index.d.ts +2 -0
  189. package/dist/index.js +684 -0
  190. package/dist/index.js.map +1 -0
  191. package/dist/install-as-command.d.ts +40 -0
  192. package/dist/install-as-command.js +52 -0
  193. package/dist/install-as-command.js.map +1 -0
  194. package/dist/pack-check.d.ts +17 -0
  195. package/dist/pack-check.js +27 -0
  196. package/dist/pack-check.js.map +1 -0
  197. package/dist/paths.d.ts +140 -0
  198. package/dist/paths.js +192 -0
  199. package/dist/paths.js.map +1 -0
  200. package/dist/planner.d.ts +27 -0
  201. package/dist/planner.js +268 -0
  202. package/dist/planner.js.map +1 -0
  203. package/dist/release/manifests.d.ts +78 -0
  204. package/dist/release/manifests.js +57 -0
  205. package/dist/release/manifests.js.map +1 -0
  206. package/dist/release/snapshot.d.ts +67 -0
  207. package/dist/release/snapshot.js +97 -0
  208. package/dist/release/snapshot.js.map +1 -0
  209. package/dist/release/stable.d.ts +33 -0
  210. package/dist/release/stable.js +50 -0
  211. package/dist/release/stable.js.map +1 -0
  212. package/dist/runs/agent-tmpdir.d.ts +41 -0
  213. package/dist/runs/agent-tmpdir.js +183 -0
  214. package/dist/runs/agent-tmpdir.js.map +1 -0
  215. package/dist/runs/arm-repo-handle.d.ts +17 -0
  216. package/dist/runs/arm-repo-handle.js +24 -0
  217. package/dist/runs/arm-repo-handle.js.map +1 -0
  218. package/dist/runs/auto-name.d.ts +75 -0
  219. package/dist/runs/auto-name.js +179 -0
  220. package/dist/runs/auto-name.js.map +1 -0
  221. package/dist/runs/event-history.d.ts +50 -0
  222. package/dist/runs/event-history.js +613 -0
  223. package/dist/runs/event-history.js.map +1 -0
  224. package/dist/runs/retention.d.ts +60 -0
  225. package/dist/runs/retention.js +86 -0
  226. package/dist/runs/retention.js.map +1 -0
  227. package/dist/runs/review-gate.d.ts +18 -0
  228. package/dist/runs/review-gate.js +21 -0
  229. package/dist/runs/review-gate.js.map +1 -0
  230. package/dist/runs/run-index.d.ts +19 -0
  231. package/dist/runs/run-index.js +43 -0
  232. package/dist/runs/run-index.js.map +1 -0
  233. package/dist/runs/store.d.ts +490 -0
  234. package/dist/runs/store.js +1283 -0
  235. package/dist/runs/store.js.map +1 -0
  236. package/dist/runs/task-markers.d.ts +28 -0
  237. package/dist/runs/task-markers.js +74 -0
  238. package/dist/runs/task-markers.js.map +1 -0
  239. package/dist/runs/task-refs.d.ts +25 -0
  240. package/dist/runs/task-refs.js +74 -0
  241. package/dist/runs/task-refs.js.map +1 -0
  242. package/dist/runs/ui-event-sink.d.ts +80 -0
  243. package/dist/runs/ui-event-sink.js +209 -0
  244. package/dist/runs/ui-event-sink.js.map +1 -0
  245. package/dist/server/app-type.d.ts +21 -0
  246. package/dist/server/app-type.js +2 -0
  247. package/dist/server/app-type.js.map +1 -0
  248. package/dist/server/capabilities.d.ts +70 -0
  249. package/dist/server/capabilities.js +152 -0
  250. package/dist/server/capabilities.js.map +1 -0
  251. package/dist/server/checkout.d.ts +128 -0
  252. package/dist/server/checkout.js +296 -0
  253. package/dist/server/checkout.js.map +1 -0
  254. package/dist/server/forge/github.d.ts +535 -0
  255. package/dist/server/forge/github.js +2544 -0
  256. package/dist/server/forge/github.js.map +1 -0
  257. package/dist/server/forge/index.d.ts +40 -0
  258. package/dist/server/forge/index.js +72 -0
  259. package/dist/server/forge/index.js.map +1 -0
  260. package/dist/server/forge/types.d.ts +267 -0
  261. package/dist/server/forge/types.js +2 -0
  262. package/dist/server/forge/types.js.map +1 -0
  263. package/dist/server/fs-browse.d.ts +105 -0
  264. package/dist/server/fs-browse.js +182 -0
  265. package/dist/server/fs-browse.js.map +1 -0
  266. package/dist/server/git-changes.d.ts +213 -0
  267. package/dist/server/git-changes.js +555 -0
  268. package/dist/server/git-changes.js.map +1 -0
  269. package/dist/server/git.d.ts +28 -0
  270. package/dist/server/git.js +112 -0
  271. package/dist/server/git.js.map +1 -0
  272. package/dist/server/github.d.ts +9 -0
  273. package/dist/server/github.js +8 -0
  274. package/dist/server/github.js.map +1 -0
  275. package/dist/server/launch-key.d.ts +7 -0
  276. package/dist/server/launch-key.js +33 -0
  277. package/dist/server/launch-key.js.map +1 -0
  278. package/dist/server/open-in-app.d.ts +66 -0
  279. package/dist/server/open-in-app.js +211 -0
  280. package/dist/server/open-in-app.js.map +1 -0
  281. package/dist/server/open-in-terminal.d.ts +70 -0
  282. package/dist/server/open-in-terminal.js +179 -0
  283. package/dist/server/open-in-terminal.js.map +1 -0
  284. package/dist/server/pr.d.ts +7 -0
  285. package/dist/server/pr.js +7 -0
  286. package/dist/server/pr.js.map +1 -0
  287. package/dist/server/project-context.d.ts +120 -0
  288. package/dist/server/project-context.js +192 -0
  289. package/dist/server/project-context.js.map +1 -0
  290. package/dist/server/provider-action-gate.d.ts +8 -0
  291. package/dist/server/provider-action-gate.js +56 -0
  292. package/dist/server/provider-action-gate.js.map +1 -0
  293. package/dist/server/provider-auth-runtime.d.ts +21 -0
  294. package/dist/server/provider-auth-runtime.js +66 -0
  295. package/dist/server/provider-auth-runtime.js.map +1 -0
  296. package/dist/server/server.d.ts +13578 -0
  297. package/dist/server/server.js +5284 -0
  298. package/dist/server/server.js.map +1 -0
  299. package/dist/server/static-ui.d.ts +49 -0
  300. package/dist/server/static-ui.js +92 -0
  301. package/dist/server/static-ui.js.map +1 -0
  302. package/dist/server/validators.d.ts +97 -0
  303. package/dist/server/validators.js +86 -0
  304. package/dist/server/validators.js.map +1 -0
  305. package/dist/server/ws.d.ts +83 -0
  306. package/dist/server/ws.js +216 -0
  307. package/dist/server/ws.js.map +1 -0
  308. package/dist/server/wsl.d.ts +25 -0
  309. package/dist/server/wsl.js +92 -0
  310. package/dist/server/wsl.js.map +1 -0
  311. package/dist/server-install/engine.d.ts +50 -0
  312. package/dist/server-install/engine.js +324 -0
  313. package/dist/server-install/engine.js.map +1 -0
  314. package/dist/server-install/platforms/macosx-ngrok.d.ts +6 -0
  315. package/dist/server-install/platforms/macosx-ngrok.js +348 -0
  316. package/dist/server-install/platforms/macosx-ngrok.js.map +1 -0
  317. package/dist/server-install/platforms/ubuntu-vps.d.ts +63 -0
  318. package/dist/server-install/platforms/ubuntu-vps.js +997 -0
  319. package/dist/server-install/platforms/ubuntu-vps.js.map +1 -0
  320. package/dist/server-install/state.d.ts +52 -0
  321. package/dist/server-install/state.js +182 -0
  322. package/dist/server-install/state.js.map +1 -0
  323. package/dist/server-install/steps.d.ts +109 -0
  324. package/dist/server-install/steps.js +334 -0
  325. package/dist/server-install/steps.js.map +1 -0
  326. package/dist/server-install/strategies.d.ts +4 -0
  327. package/dist/server-install/strategies.js +20 -0
  328. package/dist/server-install/strategies.js.map +1 -0
  329. package/dist/server-install/types.d.ts +287 -0
  330. package/dist/server-install/types.js +121 -0
  331. package/dist/server-install/types.js.map +1 -0
  332. package/dist/server-install/ui.d.ts +42 -0
  333. package/dist/server-install/ui.js +130 -0
  334. package/dist/server-install/ui.js.map +1 -0
  335. package/dist/skills-banner.d.ts +22 -0
  336. package/dist/skills-banner.js +41 -0
  337. package/dist/skills-banner.js.map +1 -0
  338. package/dist/skills-remote.d.ts +84 -0
  339. package/dist/skills-remote.js +468 -0
  340. package/dist/skills-remote.js.map +1 -0
  341. package/dist/skills-update.d.ts +88 -0
  342. package/dist/skills-update.js +392 -0
  343. package/dist/skills-update.js.map +1 -0
  344. package/dist/skills.d.ts +82 -0
  345. package/dist/skills.js +251 -0
  346. package/dist/skills.js.map +1 -0
  347. package/dist/todos.d.ts +48 -0
  348. package/dist/todos.js +201 -0
  349. package/dist/todos.js.map +1 -0
  350. package/dist/ui-state.d.ts +26 -0
  351. package/dist/ui-state.js +38 -0
  352. package/dist/ui-state.js.map +1 -0
  353. package/dist/update-check.d.ts +12 -0
  354. package/dist/update-check.js +41 -0
  355. package/dist/update-check.js.map +1 -0
  356. package/dist/workflows/load.d.ts +15 -0
  357. package/dist/workflows/load.js +56 -0
  358. package/dist/workflows/load.js.map +1 -0
  359. package/dist/workflows/run.d.ts +803 -0
  360. package/dist/workflows/run.js +3483 -0
  361. package/dist/workflows/run.js.map +1 -0
  362. package/dist/workflows/types.d.ts +145 -0
  363. package/dist/workflows/types.js +194 -0
  364. package/dist/workflows/types.js.map +1 -0
  365. package/dist/workspace/agent-accounts.d.ts +153 -0
  366. package/dist/workspace/agent-accounts.js +304 -0
  367. package/dist/workspace/agent-accounts.js.map +1 -0
  368. package/dist/workspace/agent-profiles.d.ts +78 -0
  369. package/dist/workspace/agent-profiles.js +115 -0
  370. package/dist/workspace/agent-profiles.js.map +1 -0
  371. package/dist/workspace/config.d.ts +169 -0
  372. package/dist/workspace/config.js +379 -0
  373. package/dist/workspace/config.js.map +1 -0
  374. package/dist/workspace/migrations.d.ts +45 -0
  375. package/dist/workspace/migrations.js +147 -0
  376. package/dist/workspace/migrations.js.map +1 -0
  377. package/dist/workspace/projects-cli.d.ts +25 -0
  378. package/dist/workspace/projects-cli.js +172 -0
  379. package/dist/workspace/projects-cli.js.map +1 -0
  380. package/dist/workspace/projects.d.ts +109 -0
  381. package/dist/workspace/projects.js +250 -0
  382. package/dist/workspace/projects.js.map +1 -0
  383. package/dist/workspace/semaphore.d.ts +179 -0
  384. package/dist/workspace/semaphore.js +195 -0
  385. package/dist/workspace/semaphore.js.map +1 -0
  386. package/dist/workspace/ui-state.d.ts +34 -0
  387. package/dist/workspace/ui-state.js +53 -0
  388. package/dist/workspace/ui-state.js.map +1 -0
  389. package/package.json +85 -0
  390. package/scripts/check-pack.mjs +46 -0
  391. package/scripts/inline-contract.mjs +112 -0
  392. package/scripts/install-as-command.mjs +120 -0
  393. package/scripts/mock-claude.mjs +524 -0
  394. package/scripts/mock-pi-rpc.mjs +83 -0
  395. package/scripts/sync-readme.mjs +20 -0
  396. package/scripts/test-process-usage.mjs +47 -0
  397. package/web/dist/assets/alert-dialog-CGskMvgc.js +1 -0
  398. package/web/dist/assets/arrow-down-G8adPhbu.js +1 -0
  399. package/web/dist/assets/arrow-left-BJsIW6A0.js +1 -0
  400. package/web/dist/assets/bundle-mjs-BT31bpU6.js +1 -0
  401. package/web/dist/assets/centered-state-B_V_Ai2h.js +43 -0
  402. package/web/dist/assets/chevron-right-CFzn-von.js +1 -0
  403. package/web/dist/assets/chunk-BO2N2NFS-DE6qKn3r.js +131 -0
  404. package/web/dist/assets/collapsible-B_8uYwHb.js +1 -0
  405. package/web/dist/assets/commit-list-C4Dv6vUL.js +1 -0
  406. package/web/dist/assets/compare-variants-SR2zZfZq.js +1 -0
  407. package/web/dist/assets/core-BCsw8oQw.js +12 -0
  408. package/web/dist/assets/css-BsVw1vtW.js +1 -0
  409. package/web/dist/assets/diff-CbozNUJq.js +3 -0
  410. package/web/dist/assets/diff-stat-btAmKFJr.js +1 -0
  411. package/web/dist/assets/diff-view-BpFTcG3R.js +6 -0
  412. package/web/dist/assets/diff-woXpYk--.js +1 -0
  413. package/web/dist/assets/dropdown-menu-Z80KMInL.js +1 -0
  414. package/web/dist/assets/editable-title-wS5NWwob.js +1 -0
  415. package/web/dist/assets/ellipsis-vertical-Bmi2u2TG.js +1 -0
  416. package/web/dist/assets/engine-javascript-FQvzRocB.js +141 -0
  417. package/web/dist/assets/file-DKoYWRsv.js +1 -0
  418. package/web/dist/assets/folder-u01HScRT.js +1 -0
  419. package/web/dist/assets/git-toolbar-DZlZjTGz.js +1 -0
  420. package/web/dist/assets/github-CFURo9kf.js +1 -0
  421. package/web/dist/assets/go-rLFTqkRN.js +1 -0
  422. package/web/dist/assets/highlighted-body-OFNGDK62-BL-MfFgl.js +1 -0
  423. package/web/dist/assets/highlighter-C8DK1_sG.js +3 -0
  424. package/web/dist/assets/html-BY76lXLH.js +1 -0
  425. package/web/dist/assets/image-preview-BR3iIIhf.js +1 -0
  426. package/web/dist/assets/index-BcI5hug3.css +2 -0
  427. package/web/dist/assets/index-DlC81_GI.js +7 -0
  428. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  429. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  430. package/web/dist/assets/javascript-BgS3c2Ky.js +1 -0
  431. package/web/dist/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  432. package/web/dist/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  433. package/web/dist/assets/json-qhed-kSA.js +1 -0
  434. package/web/dist/assets/jsonc-CYpm1nAK.js +1 -0
  435. package/web/dist/assets/jsx-Bz0zcwM4.js +1 -0
  436. package/web/dist/assets/lib-BQXq3kEf.js +1 -0
  437. package/web/dist/assets/lib-BxQXEXDF.js +1 -0
  438. package/web/dist/assets/markdown-5FuCZDA4.js +2 -0
  439. package/web/dist/assets/markdown-BYOwaDjH.js +1 -0
  440. package/web/dist/assets/mermaid-GHXKKRXX-C4jxqUUb.js +1 -0
  441. package/web/dist/assets/new-task-form-BydHBbef.js +1 -0
  442. package/web/dist/assets/pill-vNzaaYxj.js +1 -0
  443. package/web/dist/assets/project-router-BbCzrHKs.js +1 -0
  444. package/web/dist/assets/prompt-templates-B7Fs2b1S.js +15 -0
  445. package/web/dist/assets/python-gzcpVVnB.js +1 -0
  446. package/web/dist/assets/react-runtime-CCIEwYL0.js +9 -0
  447. package/web/dist/assets/refresh-cw-DGliez3E.js +1 -0
  448. package/web/dist/assets/repo-git-CJFDMauC.js +1 -0
  449. package/web/dist/assets/rolldown-runtime-QTnfLwEv.js +1 -0
  450. package/web/dist/assets/run-diff-Bq9vkSNK.js +3 -0
  451. package/web/dist/assets/run-header-Cd8mSKBG.js +1 -0
  452. package/web/dist/assets/rust-Cfkwpbl8.js +1 -0
  453. package/web/dist/assets/search-x-69n_672Y.js +1 -0
  454. package/web/dist/assets/shellscript-CLZ0U2zV.js +1 -0
  455. package/web/dist/assets/skill-empty-hint-DTu0LzaJ.js +1 -0
  456. package/web/dist/assets/skills-Cs-auniL.js +1 -0
  457. package/web/dist/assets/skills-D4P-Hgey.js +1 -0
  458. package/web/dist/assets/sparkles-B8agSxBZ.js +1 -0
  459. package/web/dist/assets/sql-BsFa4tDR.js +1 -0
  460. package/web/dist/assets/square-terminal-Cf4Og6ct.js +1 -0
  461. package/web/dist/assets/tab-link-Cp2-CJS8.js +1 -0
  462. package/web/dist/assets/task-changes-DYgNXOyY.js +1 -0
  463. package/web/dist/assets/task-commits-BRpZSz1G.js +1 -0
  464. package/web/dist/assets/task-files-pKOwSyLh.js +2 -0
  465. package/web/dist/assets/task-thread-Bfyqqy-t.js +9 -0
  466. package/web/dist/assets/textarea--cpYshee.js +1 -0
  467. package/web/dist/assets/thread-loading-GyH2Atwo.js +1 -0
  468. package/web/dist/assets/toml-CcmNWLt0.js +1 -0
  469. package/web/dist/assets/trash-2--ZtrzUx3.js +1 -0
  470. package/web/dist/assets/triangle-alert-D5tJwRD2.js +1 -0
  471. package/web/dist/assets/tsx-udAQXfEw.js +1 -0
  472. package/web/dist/assets/typescript-bsJCZSQ-.js +1 -0
  473. package/web/dist/assets/upload-SnwVxKOA.js +1 -0
  474. package/web/dist/assets/use-desktop-C31lOFUD.js +1 -0
  475. package/web/dist/assets/use-submit-shortcut-JY8M_MPL.js +1 -0
  476. package/web/dist/assets/utils-Bb8ohcr3.js +64 -0
  477. package/web/dist/assets/workflows-BmOehP-A.js +11 -0
  478. package/web/dist/assets/yaml-rwi0_p6S.js +1 -0
  479. package/web/dist/assets/zoomable-image-0G3IBXWC.js +1 -0
  480. package/web/dist/index.html +80 -0
  481. package/web/dist/xezar.svg +14 -0
@@ -0,0 +1,3483 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { spawn } from 'node:child_process';
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { parseAskMarkerResult, stripAskMarker, } from '../core/ask.js';
6
+ import { onUsage, registerRunProcess, unregisterRunProcess } from '../core/process-usage.js';
7
+ import { parseUsageLimit } from '../core/usage-limit.js';
8
+ import { createRunner } from '../core/runner-factory.js';
9
+ import { modelConflictsWithRunner } from '../core/model-presets.js';
10
+ import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
11
+ import { ModelIdentityError, formatModelIdentity, normalizeModelForBackend, } from '../core/model-identity.js';
12
+ import { HANDOFF_ONLY_INSTRUCTIONS, HANDOFF_INSTRUCTIONS, appendHandoffHeartbeat, followupsEnabled, handoffPath, seedHandoffFile, } from '../handoff.js';
13
+ import { todosPath } from '../todos.js';
14
+ // Contract VALUES, like `workspaceUiStateSchema` in workspace/migrations.ts: the attachment
15
+ // vocabulary the routes validate with is the same one the engine stores and re-reads by, so the
16
+ // wire and the disk can never disagree about what counts as an image (#950).
17
+ import { attachmentExtension, isImageAttachmentName, isImageMediaType, } from '../contract/index.js';
18
+ import { discoverSkills } from '../skills.js';
19
+ import { materializeSkillDir } from '../skills-remote.js';
20
+ import { seedAgentConfigLocalLayer } from '../agent-config/seed.js';
21
+ import { readAgentModelProvider } from '../agent-config/models.js';
22
+ import { loadConfig, resolveWorktreeRetention } from '../config.js';
23
+ import { autosaveCommit, createWorktree, resolveBaseRef, worktreeDiff, worktreeShortstat } from '../git-worktree.js';
24
+ import { getHeadCommit, getRepoInfo } from '../server/git.js';
25
+ import { loadWorkflows } from './load.js';
26
+ import { reclaimWorktrees, rematerializeReclaimedWorktree } from '../runs/retention.js';
27
+ import { AgentTempDirError, agentTmpEnv, removeAgentTmpDir, sweepAgentTmpDirs, } from '../runs/agent-tmpdir.js';
28
+ import { extractTaskRefs, refineTaskRefs, titleRefNumber } from '../runs/task-refs.js';
29
+ import { parseTaskMarkers, stripTaskMarkers } from '../runs/task-markers.js';
30
+ import { autoNamingActive, generateRunName, liveTitleUpdatesEnabled, postValidateTitle } from '../runs/auto-name.js';
31
+ import { reviewGateEnabled } from '../runs/review-gate.js';
32
+ import { resolveProfileEnvForRoot } from '../workspace/agent-profiles.js';
33
+ import { DEFAULT_AGENT_ACCOUNT_ID } from '../workspace/agent-accounts.js';
34
+ import { WorkspaceSemaphore } from '../workspace/semaphore.js';
35
+ import { UiEventSink } from '../runs/ui-event-sink.js';
36
+ import { chainStepNote, DEFAULT_ALLOWED_TOOLS, stepKind } from './types.js';
37
+ const CHECK_OUTPUT_CAP = 20_000;
38
+ async function configuredModelProvider(backend, repoRoot) {
39
+ return readAgentModelProvider(backend, repoRoot).catch(() => undefined);
40
+ }
41
+ /** An interactive session that hears nothing from the user closes itself. */
42
+ export const IDLE_TIMEOUT_MS = 15 * 60_000;
43
+ /**
44
+ * Task-completion marker from the agent contract (HANDOFF_INSTRUCTIONS): a
45
+ * turn whose text ends with `XEZ:DONE` means "goal achieved, nothing to ask" —
46
+ * the session is closed right away instead of parking at `waiting` (#347).
47
+ * Detection runs on the accumulated turn text so delta-streaming backends
48
+ * (codex, opencode) can't split the marker across text events.
49
+ */
50
+ const DONE_MARKER_RE = /XEZ:DONE\s*$/;
51
+ /**
52
+ * Still-working marker from the agent contract (spec
53
+ * 2026-07-18-subagent-monitoring-status, #490): a turn whose text ends with
54
+ * `XEZ:MONITORING` means "I ended this turn but I'm still working on my own
55
+ * downstream work (a sub-agent / a command I'm monitoring), not waiting on the
56
+ * user" — xezar parks it as `running`/`activity:'monitoring'` instead of
57
+ * `waiting`, so the cockpit shows a non-attention state. `XEZ:DONE` wins if both
58
+ * appear. Detected on accumulated turn text (like `XEZ:DONE`) so delta-streaming
59
+ * backends can't split the marker across text events.
60
+ */
61
+ const MONITORING_MARKER_RE = /XEZ:MONITORING\s*$/;
62
+ /**
63
+ * Preserve boundaries between complete assistant text blocks while a turn is
64
+ * accumulated for marker parsing. The runners join these same v1 blocks with
65
+ * newlines in `AgentRunResult`; matching that contract here prevents a
66
+ * trailing `XEZ:TITLE=` block from absorbing later commentary (#623).
67
+ */
68
+ export function appendTurnText(current, next) {
69
+ if (!current)
70
+ return next;
71
+ if (!next)
72
+ return current;
73
+ return `${current}\n${next}`;
74
+ }
75
+ /** Strip a trailing marker from one text event so transcripts stay free of
76
+ * protocol noise. Delta backends may split the marker across events — then
77
+ * it stays visible; detection above is unaffected. */
78
+ function stripDoneMarker(text) {
79
+ return text.replace(/\s*XEZ:DONE\s*$/, '');
80
+ }
81
+ /** Strip a trailing `XEZ:MONITORING` marker from one text event (see
82
+ * `stripDoneMarker`; same delta-backend caveat). */
83
+ function stripMonitoringMarker(text) {
84
+ return text.replace(/\s*XEZ:MONITORING\s*$/, '');
85
+ }
86
+ /** Emit the v2 `ask.requested` event for a parsed marker (the cockpit renders
87
+ * it as an ask card, #473). Returns the minted request id. */
88
+ function emitAskRequested(sink, ask) {
89
+ const requestId = randomUUID();
90
+ sink.handle({ type: 'ask.requested', requestId, questions: ask.questions });
91
+ return requestId;
92
+ }
93
+ /** A persisted, non-fatal explanation for protocol-shaped text that could not
94
+ * become an ask card. Never include the raw payload in this diagnostic. Carries
95
+ * `tone: 'danger'` (#936): the agent's question was lost outright, which is not
96
+ * a footnote — the cockpit renders an un-toned note as the dimmest line in the
97
+ * thread. Older events carry no `tone` and keep rendering dim. */
98
+ function askMarkerRejection(result) {
99
+ if (result.kind === 'invalid-json') {
100
+ return 'structured question ignored — XEZ:ASK payload is not valid JSON';
101
+ }
102
+ if (result.kind !== 'invalid-structure')
103
+ return undefined;
104
+ const issue = result.issues[0];
105
+ const location = issue?.path.length ? ` at ${issue.path.join('.')}` : '';
106
+ return `structured question ignored — XEZ:ASK payload failed validation${location}${issue ? `: ${issue.message}` : ''}`;
107
+ }
108
+ /** A persisted, auditable trace for a card that only rendered because the
109
+ * payload's missing closers were appended (#936) — a repair can only lose what
110
+ * the truncation already removed, so the recovery must stay visible rather than
111
+ * passing for a clean parse. Carries `tone: 'danger'` for the same reason the
112
+ * rejection does: it is the ONLY signal that the card may be missing a trailing
113
+ * option or a trailing `multiSelect` the cut took with it, and the raw payload
114
+ * is stripped along with the card, so a dim footnote could not be acted on. */
115
+ function askMarkerRecovery(result) {
116
+ return result.kind === 'valid' && result.repaired
117
+ ? 'structured question recovered from an unbalanced XEZ:ASK payload — check the options, and how many you may pick, match what was asked'
118
+ : undefined;
119
+ }
120
+ /** Resolve the ask marker for one finished turn. Both turn-end handlers
121
+ * (`runAgentStep` and `runContinuation`) route through this single function:
122
+ * they are hand-duplicated, and `AGENTS.md` warns that a lifecycle change
123
+ * applied to only one of them ships half a fix — the notes and their tones are
124
+ * exactly that kind of change. `enabled` is the caller's own precondition (the
125
+ * session is open, the turn is not a `XEZ:DONE`, and for an agent step, the run
126
+ * is interactive); when false there is no marker to look for. */
127
+ function resolveAskTurn(turnText, enabled) {
128
+ if (!enabled)
129
+ return { ask: null, notes: [] };
130
+ const result = parseAskMarkerResult(turnText);
131
+ const notes = [];
132
+ const rejection = askMarkerRejection(result);
133
+ if (rejection)
134
+ notes.push({ message: rejection, tone: 'danger' });
135
+ const recovery = askMarkerRecovery(result);
136
+ if (recovery)
137
+ notes.push({ message: recovery, tone: 'danger' });
138
+ return { ask: result.kind === 'valid' ? result.request : null, notes };
139
+ }
140
+ /** Periodic "xezar autosave" commit in the task worktree (spec 006). */
141
+ export const AUTOSAVE_INTERVAL_MS = 90_000;
142
+ /** The periodic autosave timer is opt-in (#471): off, a task branch carries only the
143
+ * agent's own commits plus the turn-end/pre-PR flushes — no mid-run "xezar autosave"
144
+ * noise interleaving PR history. The flushes (`autosaveCommit` at turn end and before
145
+ * a draft PR) are NOT gated: the branch must still end holding the finished state. */
146
+ export function periodicAutosaveEnabled(env = process.env) {
147
+ return env.XEZ_AUTOSAVE === '1';
148
+ }
149
+ /**
150
+ * Explicitly opt out of the repository-root lease for runs that execute in the
151
+ * current checkout. This covers explicit worktree opt-out, non-Git degradation,
152
+ * and continuations whose worktree cannot be restored (spec 006 hardening, #438).
153
+ * This is intentionally unsafe: concurrent agents may overwrite each other's
154
+ * files or Git state. Isolated worktree runs are unaffected.
155
+ */
156
+ export function repositoryRootLockDisabled(env = process.env) {
157
+ return env.XEZ_DISABLE_REPO_LOCK === '1';
158
+ }
159
+ const REPOSITORY_ROOT_LOCK_DISABLED_NOTE = 'repository-root lock disabled by XEZ_DISABLE_REPO_LOCK=1 (shared checkout is unsafe)';
160
+ /** Safety cap on autonomous auto-continues per run — stops a stuck agent from nudging forever. */
161
+ const MAX_AUTO_CONTINUES = 40;
162
+ const AUTONOMOUS_NUDGE = 'Continue working autonomously until the task is fully complete. Do not ask me for confirmation or clarification — make reasonable assumptions and proceed. When everything is done, end the session with your done signal.';
163
+ const MONITORING_WAKE_NUDGE = 'Re-check the downstream work you were monitoring. Continue toward the task goal; emit XEZ:MONITORING again only if it is still pending.';
164
+ /**
165
+ * Auto-resume after a provider usage limit (spec 2026-08-03-auto-resume-after-usage-limit).
166
+ *
167
+ * The wait is the provider's own reset instant plus this grace: resuming AT the boundary races the
168
+ * provider's clock (and its rounding), and one failed resume costs the whole window over again.
169
+ * Thirty seconds is cheap next to five hours and long enough to be past any sane skew.
170
+ */
171
+ export const AUTO_RESUME_GRACE_MS = 30_000;
172
+ /**
173
+ * Consecutive automatic resumes allowed without a human turn. A resume can only fire after a real
174
+ * reset instant, so this is not a throttle — it is the backstop for the pathological case (a
175
+ * provider that answers "limit reached, retry now" in a loop), and it is deliberately generous
176
+ * enough to sit through a couple of days of five-hour windows.
177
+ */
178
+ export const MAX_AUTO_RESUMES = 12;
179
+ /**
180
+ * How long a missed deadline stays worth acting on. The promise is "we pick this up when the
181
+ * window reopens" — kept across a restart or an overnight close, which is the case the feature
182
+ * exists for. A day later it is no longer that promise: the user has moved on, and a task
183
+ * springing back to life is a surprise rather than a service. Such a deadline is retired with a
184
+ * note instead of fired, so the only tasks a sweep can revive are ones someone is still waiting on.
185
+ */
186
+ export const AUTO_RESUME_MISSED_WINDOW_MS = 24 * 60 * 60_000;
187
+ /**
188
+ * How often the queue checks that it is not wedged.
189
+ *
190
+ * A hold is the only thing in the engine that can make an idle queue CORRECT, so it is also the
191
+ * only thing that can make a wedged one look correct. This tick is the way out: cheap (a few
192
+ * in-memory checks), unref'd, and it only ever acts when idling has no justification left.
193
+ */
194
+ export const QUEUE_WATCHDOG_MS = 60_000;
195
+ /** Shared empty holds for the common "nothing is held" pump — avoids allocating per sweep. */
196
+ const NO_HOLDS = { deadline: new Set(), inFlight: new Set() };
197
+ /**
198
+ * May this run start, given what its account is holding?
199
+ *
200
+ * The two kinds of hold bind different work, and getting that wrong has produced a bug in each
201
+ * direction (spec 2026-08-03-auto-resume-after-usage-limit):
202
+ *
203
+ * - a `deadline` hold means the window is KNOWN shut until an instant, so it blocks everything
204
+ * on that account — resumes included. Exempting them let four resumes fire at once and
205
+ * re-limit one after another, which is the stampede wearing a different hat.
206
+ * - an `inFlight` hold means a resume is testing the window right now and nothing is proven, so
207
+ * it blocks fresh work but not other resumes. Blocking those deadlocked a live workspace.
208
+ */
209
+ function accountHeldFor(run, holds, fallbackRunner) {
210
+ const key = runAccountKey(run, fallbackRunner);
211
+ if (holds.deadline.has(key))
212
+ return true;
213
+ return holds.inFlight.has(key) && !resumeInFlight(run);
214
+ }
215
+ /**
216
+ * Which agent ACCOUNT a run's work runs on — the thing a provider usage limit actually closes
217
+ * (spec 2026-08-03-auto-resume-after-usage-limit).
218
+ *
219
+ * Backend plus agent account, because those are the two axes a limit is scoped to: a Claude
220
+ * limit must never stall a Codex task, and a second Claude login is a second budget. A record
221
+ * that names no runner has not started yet and will take the configured default, which is what
222
+ * `fallbackRunner` carries; a run that HAS started always carries its resolved runner (execute
223
+ * persists it), and only started runs can be holding.
224
+ */
225
+ export function runAccountKey(run, fallbackRunner) {
226
+ return `${run.runner ?? fallbackRunner}:${run.agentProfile ?? 'default'}`;
227
+ }
228
+ /**
229
+ * Is this run an automatic resume that has not completed a turn yet?
230
+ *
231
+ * Such a run is the work the reopened window is FOR, so the hold must never apply to it — not
232
+ * its own, and not another resume's. Two resumes that hold each other is a deadlock the queue
233
+ * cannot recover from: both sit `queued` with a counter and no deadline, each waiting for the
234
+ * other to prove a window neither will ever get to test. That is the shape a live run produced
235
+ * — two scheduled tasks fired, both went `queued`, and nothing in the workspace moved again.
236
+ *
237
+ * The hold exists to stop NEW work walking into a closed window. A resume is not new work.
238
+ */
239
+ function resumeInFlight(run) {
240
+ return (run.autoResumeAttempts !== undefined && (run.status === 'queued' || run.status === 'running'));
241
+ }
242
+ const AUTO_RESUME_PROMPT = 'The provider usage limit that interrupted this task has reset. Read the handoff file (XEZ_HANDOFF_FILE) to recover context, then continue the task from where you left off.';
243
+ /**
244
+ * The wake instant as a human reads it — local, to the SECOND, with the zone named. The
245
+ * transcript line is what someone scanning a stalled task actually reads, and "18:41" is not
246
+ * enough to tell a wait that is nearly over from one that just started; the machine-readable ISO
247
+ * copy lives on `RunRecord.autoResumeAt`. Server-side formatting is honest here because xezar is
248
+ * local-first: the process and the browser reading it are the same machine.
249
+ */
250
+ function formatWakeInstant(at) {
251
+ return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'long' }).format(at);
252
+ }
253
+ /**
254
+ * The effective "extra" system prompt for a run (spec §protocol v2, R2 2.3):
255
+ * the per-run override (`POST /api/runs` `systemPrompt`) REPLACES the
256
+ * `config.json` default — they are the same knob at two scopes, so the more
257
+ * specific one wins outright; they never concatenate. Whichever wins is
258
+ * ADDITIVE to the skill body and the handoff contract, which always ride
259
+ * along (see `composeSystemPrompt`). Blank strings count as unset.
260
+ */
261
+ export function resolveExtraSystemPrompt(override, configDefault) {
262
+ return override?.trim() || configDefault?.trim() || undefined;
263
+ }
264
+ /**
265
+ * Joins the parts of one agent step's system prompt in fixed order — skill
266
+ * body (most task-specific), then the run's extra prompt (user guidance, can
267
+ * amend the skill), then the handoff contract (always last, never optional in
268
+ * practice). Blank parts drop out; survivors join with the same `\n\n---\n\n`
269
+ * divider the skill+handoff composition has always used.
270
+ */
271
+ export function composeSystemPrompt(...parts) {
272
+ return parts
273
+ .map((p) => p?.trim())
274
+ .filter((p) => Boolean(p))
275
+ .join('\n\n---\n\n');
276
+ }
277
+ /**
278
+ * The directories a spawned agent may reach outside its worktree: the run-state
279
+ * folder that holds its handoff file, plus its own temp directory when this run
280
+ * got one (#785). Handing an agent a `TMPDIR` its file tools are not allowed to
281
+ * write would trade one silent failure for another, so the two travel together;
282
+ * under `XEZ_AGENT_TMPDIR=0` there is no per-run directory and the list is
283
+ * exactly what it always was.
284
+ */
285
+ export function agentDirectories(runsDir, env) {
286
+ return env.TMPDIR ? [runsDir, env.TMPDIR] : [runsDir];
287
+ }
288
+ /**
289
+ * Materialized pasted attachment: the on-disk name/serving-URL pair the
290
+ * transcript already used, plus the absolute path that lets the agent
291
+ * operate on the file itself — save it, `cp` it, attach it to a GitHub
292
+ * issue/PR (#357). `path` is only ever an absolute path under
293
+ * `.ai/xezar/runs/<runId>-images/` (see `RunManager.persistAttachment`).
294
+ */
295
+ /** Inverse of `attachmentExtension` (#472) — a persisted attachment is re-encoded from disk at
296
+ * dequeue and needs its media type back. Only ever asked about IMAGE names (a file reaches the
297
+ * agent as a path, never as a block), so an unknown extension still answers `image/png`: that is
298
+ * the pre-existing fallback for the `.img` an SVG or a BMP paste lands as. */
299
+ export function mediaTypeFor(name) {
300
+ const ext = name.split('.').pop()?.toLowerCase();
301
+ return ext === 'jpg' ? 'image/jpeg'
302
+ : ext === 'webp' ? 'image/webp'
303
+ : ext === 'gif' ? 'image/gif'
304
+ : 'image/png';
305
+ }
306
+ /** Highest `<prefix>-<n>.<ext>` suffix already present in a run's image dir (#472).
307
+ * `screenshot-*` and `pasted-*` share one numbering space, so this scans both and
308
+ * returns 0 for a missing/empty directory. */
309
+ export function highestImageSeq(dir) {
310
+ try {
311
+ return readdirSync(dir).reduce((max, name) => {
312
+ const m = /^(?:screenshot|pasted)-(\d+)\./.exec(name);
313
+ return m ? Math.max(max, Number(m[1])) : max;
314
+ }, 0);
315
+ }
316
+ catch {
317
+ return 0;
318
+ }
319
+ }
320
+ /** One wire attachment (`{mediaType, data}`) as the engine wants it: an image the model can view,
321
+ * or a file it will only ever be given the path of. The single mapping the four attachment-
322
+ * carrying routes share, so none of them can invent a different one. */
323
+ export function toPastedContent(attachment) {
324
+ return isImageMediaType(attachment.mediaType)
325
+ ? { type: 'image', source: { type: 'base64', media_type: attachment.mediaType, data: attachment.data } }
326
+ : { type: 'file', mediaType: attachment.mediaType, data: attachment.data };
327
+ }
328
+ /** The image blocks of a mixed list — what may be delivered to a session. */
329
+ export function contentBlocksOf(content) {
330
+ return content.filter((b) => b.type !== 'file');
331
+ }
332
+ /**
333
+ * Plain-text note listing the absolute paths of pasted attachments, appended
334
+ * to the message that carries them (#357). The base64 image blocks stay in
335
+ * the message for the model to *view*; this note is what lets it *use* the
336
+ * files as files — and the only usable reference on backends (codex,
337
+ * opencode) whose `textOf()` drops image blocks before reaching the model.
338
+ */
339
+ export function pastedAttachmentsText(attachments) {
340
+ const list = attachments.map((a) => `- ${a.path}`).join('\n');
341
+ return (`The user attached ${attachments.length} pasted file${attachments.length > 1 ? 's' : ''}, ` +
342
+ `also saved on disk at:\n${list}\n` +
343
+ `When the task involves saving, uploading, attaching, or transforming the pasted content ` +
344
+ `(e.g. attaching to a GitHub issue/PR, copying into the repo), operate on these files — do ` +
345
+ `not attempt to reconstruct them from the conversation.`);
346
+ }
347
+ /** Same note as `pastedAttachmentsText`, wrapped as a trailing `ContentBlock`
348
+ * ready to append to a message's content array. */
349
+ export function pastedAttachmentsNote(attachments) {
350
+ return { type: 'text', text: pastedAttachmentsText(attachments) };
351
+ }
352
+ /** Variant letters + the fixed diversification hints (spec 010). A runs the
353
+ * task verbatim; B/C get one constant sentence each — zero configuration. */
354
+ export const VARIANT_LETTERS = ['A', 'B', 'C'];
355
+ const VARIANT_HINTS = {
356
+ A: undefined,
357
+ B: 'Approach hint: prefer the minimal, surgical change.',
358
+ C: 'Approach hint: prefer a thorough, structural approach.',
359
+ };
360
+ const RESTART_CONTINUATION_PROMPT = 'The xezar process restarted while you were working on this task. Read the handoff file (XEZ_HANDOFF_FILE) to recover context, then continue the task from where you left off.';
361
+ /**
362
+ * The mini workflow engine: executes a `WorkflowDef` against a repo, one step
363
+ * at a time, persisting every event to the RunStore (which the SSE endpoints
364
+ * relay live to the GUI). No GitHub choreography — agent steps and shell
365
+ * checks with bounded retry loops, plus live sessions: the last agent step
366
+ * stays open for follow-ups (`waiting`) until "finish", idle timeout, or
367
+ * cancel. Runs queue behind the workspace-wide `maxParallel` slots (the shared
368
+ * `WorkspaceSemaphore`, spec 2026-07-20 step 2.5) and each run executes in its
369
+ * own git worktree on a `xez/<id8>` branch (spec 006), autosave-committed at
370
+ * turn end and before a draft PR — plus every 90 s when opted in via
371
+ * XEZ_AUTOSAVE=1 (#471). Each autosave records its trigger in the commit
372
+ * subject, so the always-on flushes are not mistaken for the opt-in timer.
373
+ * The user's working tree is never touched.
374
+ */
375
+ export class RunManager {
376
+ store;
377
+ repoRoot;
378
+ active = new Map();
379
+ // Queue + `starting` set (spec 006, janitor's pump() pattern): `starting`
380
+ // covers the window between shifting a run off the queue and the run
381
+ // registering in `active`, so parallel-slot counting is never racy.
382
+ queue = [];
383
+ starting = new Set();
384
+ // Runs parked at `waiting` (open session, ball in the user's court). They
385
+ // don't consume a `maxParallel` slot (#347) — an idle claude process costs
386
+ // memory but no tokens, queued work progressing matters more, and the idle
387
+ // timeout already bounds how long a session can sit open. Invariant:
388
+ // `waiting ⊆ active` — always cleared together via dropActive().
389
+ waiting = new Set();
390
+ /** Durable monitoring subset. Only the configured number receives the waiting-slot exemption. */
391
+ monitoring = new Set();
392
+ pendingJobs = new Map();
393
+ /** Interrupted agent turns recovered after a process restart. Unlike an
394
+ * explicit user Continue, these are bulk scheduler work and must re-enter
395
+ * through `pump()` so both workspace and per-project caps are honored. */
396
+ pendingContinuations = new Map();
397
+ /** Per-run image counter behind `pasted-<n>` / `screenshot-<n>` (#472). Lives on
398
+ * the manager rather than the `ActiveRun` so a *queued* run — which has no
399
+ * `ActiveRun` at all — can persist attachments. Seeded lazily from disk. */
400
+ queuedImageSeq = new Map();
401
+ /** Messages that landed in the dequeue → session-open gap (#472), flushed as
402
+ * ordinary follow-up turns the moment the session opens. In-memory only. */
403
+ deferredMessages = new Map();
404
+ /** Armed usage-limit resumes, keyed by run id (spec
405
+ * 2026-08-03-auto-resume-after-usage-limit). The DEADLINE itself lives on the record
406
+ * (`autoResumeAt`) — this map holds only the process-local timer, so a restart rebuilds it
407
+ * from the record rather than losing the wait. Runs here are `failed` and therefore NOT in
408
+ * `active`, which is why the timer cannot live on an `ActiveRun` like the monitoring one. */
409
+ autoResumeTimers = new Map();
410
+ pumping = false;
411
+ /** A pump that arrived while one was in flight — replayed by `pump()`'s own
412
+ * loop so a slot freed mid-sweep is never a lost wakeup. */
413
+ pumpAgain = false;
414
+ /**
415
+ * Runs normally isolate in worktrees and may execute in parallel. When that
416
+ * isolation is unavailable (or explicitly disabled), access to `repoRoot` is
417
+ * serialized by default so two agents cannot edit/revert the same files
418
+ * (#438). `XEZ_DISABLE_REPO_LOCK=1` deliberately bypasses this safety lease.
419
+ */
420
+ repoRootTail = Promise.resolve();
421
+ /** `.ai/xezar` — where the per-task handoff files and todos.json live. */
422
+ dataDir;
423
+ /** Runs currently being paused by the memory guard — dedupes the ~2 s samples so one breach
424
+ * triggers one pause, not a burst. Cleared in dropActive when the run leaves the registry. */
425
+ memoryPausing = new Set();
426
+ /** Unsubscribe handle for the constructor's `onUsage` subscription — released
427
+ * by dispose() so a torn-down manager stops receiving sampler ticks. */
428
+ offUsage;
429
+ /** The stalled-queue watchdog (see `rescueStalledQueue`). */
430
+ queueWatchdog;
431
+ /** Set by the watchdog for exactly one sweep: ignore the usage-limit hold and make progress. */
432
+ forceNextPump = false;
433
+ /** Runs the watchdog started despite the hold. The spawn-time gate (`requeueWhileHeld`) would
434
+ * otherwise hand them straight back and the rescue would undo itself in a millisecond. */
435
+ forceStarted = new Set();
436
+ /** The workspace-wide parallel-cap semaphore + cached resource config
437
+ * (spec 2026-07-20, step 2.5). Boot constructs ONE and every manager shares
438
+ * it; the private fallback keeps single-manager callers and tests working. */
439
+ semaphore;
440
+ /** Unregister handle for this manager's semaphore membership — released by
441
+ * dispose() so a torn-down project stops counting against the cap. */
442
+ offSemaphore;
443
+ constructor(store, repoRoot, options = {}) {
444
+ this.store = store;
445
+ this.repoRoot = repoRoot;
446
+ this.dataDir = join(repoRoot, '.ai/xezar');
447
+ this.semaphore = options.semaphore ?? new WorkspaceSemaphore();
448
+ this.offSemaphore = this.semaphore.register({
449
+ busySlots: () => this.busySlots(),
450
+ pump: () => this.pump(),
451
+ oldestQueuedAt: () => this.oldestQueuedAt(),
452
+ accountHolds: () => this.accountHolds(),
453
+ });
454
+ // Memory guard (#memory-guard): the shared process-tree sampler already ticks ~every 2 s for
455
+ // the runs table; piggyback on it to enforce the per-task memory ceiling.
456
+ this.offUsage = onUsage((snapshot) => void this.enforceMemoryLimit(snapshot));
457
+ this.queueWatchdog = setInterval(() => void this.rescueStalledQueue(), QUEUE_WATCHDOG_MS);
458
+ this.queueWatchdog.unref?.();
459
+ }
460
+ /**
461
+ * Release everything this manager owns without touching run records
462
+ * (multi-project workspace, spec 2026-07-20: a removed project's context is
463
+ * torn down while the process lives on). Unsubscribes the shared usage
464
+ * sampler — before dispose() existed that subscription lived for the whole
465
+ * process — clears every per-run idle/autosave timer, releases any held
466
+ * repo-root locks, and empties the queued state so nothing fires later.
467
+ * Live sessions are NOT ended here: run lifecycle stays the caller's policy;
468
+ * dispose only guarantees the manager makes no further moves on its own.
469
+ */
470
+ dispose() {
471
+ this.offUsage();
472
+ this.offSemaphore();
473
+ clearInterval(this.queueWatchdog);
474
+ for (const [runId, state] of this.active) {
475
+ this.clearIdleTimer(state);
476
+ this.clearMonitoringWakeTimer(state, runId);
477
+ this.clearAutosaveTimer(state);
478
+ state.releaseRepoRoot?.();
479
+ state.releaseRepoRoot = undefined;
480
+ }
481
+ for (const timer of this.autoResumeTimers.values())
482
+ clearTimeout(timer);
483
+ this.autoResumeTimers.clear();
484
+ this.active.clear();
485
+ this.waiting.clear();
486
+ this.starting.clear();
487
+ this.queue.length = 0;
488
+ this.pendingJobs.clear();
489
+ this.pendingContinuations.clear();
490
+ this.memoryPausing.clear();
491
+ this.lastNamerKey.clear();
492
+ }
493
+ /**
494
+ * Pause any active run whose whole process tree exceeds the WORKSPACE
495
+ * `resources.memoryLimitMb`, freeing its slot so the queue advances
496
+ * (#memory-guard). "Pause" closes the session — freeing the tree's
497
+ * memory — and leaves the run resumable via Continue; a loud warning explains why. No-op when
498
+ * no limit is set or the sampler has no data (e.g. `ps`/PowerShell unavailable).
499
+ */
500
+ async enforceMemoryLimit(snapshot) {
501
+ // The sampler is module-global (one `ps` for the whole process), so with
502
+ // multiple projects a snapshot carries EVERY project's runs. Act only on
503
+ // rows this manager owns (multi-project spec, step 2.4).
504
+ const runIds = Object.keys(snapshot).filter((runId) => this.active.has(runId));
505
+ if (runIds.length === 0)
506
+ return;
507
+ // Workspace limit from the shared semaphore's in-memory cache (step 2.5:
508
+ // refreshed at boot and on PUT /api/workspace/config — never N per-tick
509
+ // file reads across N projects). Legacy per-repo `memoryLimitMb` keys are
510
+ // ignored post-migration.
511
+ const limitMb = this.semaphore.memoryLimitMb();
512
+ if (!limitMb || limitMb <= 0)
513
+ return;
514
+ const limitBytes = limitMb * 1024 * 1024;
515
+ for (const runId of runIds) {
516
+ const usage = snapshot[runId];
517
+ if (!usage || usage.rssBytes <= limitBytes)
518
+ continue;
519
+ if (this.memoryPausing.has(runId))
520
+ continue;
521
+ const state = this.active.get(runId);
522
+ if (!state?.session?.open || state.cancelled)
523
+ continue;
524
+ this.memoryPausing.add(runId);
525
+ const usedMb = Math.round(usage.rssBytes / (1024 * 1024));
526
+ this.store.appendEvent(runId, {
527
+ type: 'note',
528
+ message: `⚠ memory limit exceeded — this task's process tree is using ${usedMb} MiB (limit ${limitMb} MiB). Pausing it and letting the next queued task run; resume it with Continue.`,
529
+ });
530
+ this.store.appendEvent(runId, {
531
+ type: 'lifecycle',
532
+ message: `paused — memory limit exceeded (${usedMb} MiB > ${limitMb} MiB)`,
533
+ });
534
+ // Closing the session frees the tree and lets the normal exit path settle the run and
535
+ // pump the queue. Suppress autonomous auto-continue so the pause actually holds.
536
+ state.autonomous = false;
537
+ this.clearIdleTimer(state);
538
+ state.session.end();
539
+ }
540
+ }
541
+ /** Env the spawned claude gets so the agent can find its handoff file and
542
+ * the global inbox (spec 007; the inbox only when the run opted in).
543
+ *
544
+ * `XEZ_TODOS_FILE` is set to `''` rather than omitted when follow-ups are
545
+ * off: runners spawn with `{ ...process.env, ...spec.env }`, so omitting the
546
+ * key would let a value inherited from *this* process through — a nested
547
+ * xezar (an agent running `xez serve`/`xez run`/the test suite) would then
548
+ * write follow-ups into the parent's inbox despite the opt-out. Empty is the
549
+ * established "absent" spelling — consumers guard with `if (todosFile)`.
550
+ *
551
+ * `TMPDIR`/`TEMP`/`TMP` (#785) point at this run's own scratch directory
552
+ * instead of the machine-wide one every agent used to share. Created and
553
+ * write-probed here, on the last common path before a spawn, so an unusable
554
+ * temp directory throws `AgentTempDirError` at the caller rather than
555
+ * turning into empty command output inside a running agent. */
556
+ agentEnv(runId, generateFollowups = true) {
557
+ return {
558
+ XEZ_HANDOFF_FILE: handoffPath(this.dataDir, runId),
559
+ XEZ_TASK_ID: runId,
560
+ XEZ_TODOS_FILE: generateFollowups ? todosPath(this.dataDir) : '',
561
+ ...agentTmpEnv(this.dataDir, runId),
562
+ };
563
+ }
564
+ /**
565
+ * `agentEnv` plus the agent-account variable for the profile this STEP runs under (spec
566
+ * 2026-07-29-agent-profiles), and the id it resolved to so the caller can record it.
567
+ *
568
+ * Resolved per step, not per run, because a workflow can mix backends: an override naming a
569
+ * Claude account says nothing about which Codex account a codex step should use. Resolution
570
+ * order, most specific first:
571
+ *
572
+ * 1. the step's ALREADY-RECORDED `profileId` — a resume or Continue must reattach to the
573
+ * account that created the session, whatever the project has since been switched to;
574
+ * 2. the run's composer override, but only for steps on the run's own runner;
575
+ * 3. the project's stored selection, and failing that the discovered default.
576
+ *
577
+ * Read fresh every time. `~/.xezar/config.json` is shared by every xezar process on this
578
+ * machine, so a cached snapshot is a staleness bug, and one small JSON read is free next to
579
+ * spawning a CLI. Never throws: an unreadable home degrades to the default profile, which is
580
+ * exactly the behaviour that predates profiles.
581
+ */
582
+ async agentEnvForStep(runId, backend, options = {}) {
583
+ const run = this.store.getRun(runId);
584
+ const profileId = options.recordedProfileId
585
+ ?? (backend === (run?.runner ?? 'claude') ? run?.agentProfile : undefined);
586
+ const resolved = await resolveProfileEnvForRoot(this.repoRoot, backend, profileId);
587
+ return {
588
+ env: { ...this.agentEnv(runId, options.generateFollowups), ...resolved.env },
589
+ profileId: resolved.profile.id,
590
+ };
591
+ }
592
+ startRun(workflow, input, group) {
593
+ // Sanitize at the manager boundary so CLI runs, workflows, variants, and
594
+ // direct callers cannot bypass the HTTP policy.
595
+ const effectiveInput = agentModelsLocked(this.repoRoot)
596
+ ? { ...input, model: undefined }
597
+ : input;
598
+ const run = this.store.createRun({
599
+ title: makeRunTitle(input.task, workflow) + (group ? ` (${group.variant})` : ''),
600
+ workflow: workflow.name,
601
+ task: input.task,
602
+ model: effectiveInput.model,
603
+ runner: input.runner,
604
+ // The composer's per-task account (spec 2026-07-29-agent-profiles). Persisted at creation
605
+ // so a queued run picks it up at dequeue and every later resume reads the same answer.
606
+ agentProfile: input.agentProfile,
607
+ // The global inbox is the ceiling on the per-run flag (#471). Enforced here rather than
608
+ // at the HTTP route because `xezar run`, the inbox's own "▶ Run" and variants all reach
609
+ // startRun directly — a route-level gate would leave those writing todos.json.
610
+ generateFollowups: followupsEnabled() ? input.generateFollowups : false,
611
+ // Persist autonomy on the record (#489) so the terminal review gate
612
+ // (`settleSuccess`) and the group-pick winner-park can honor it — mid-run
613
+ // auto-nudge reads `input.autonomous` (`execute`), but the record is the
614
+ // only source those after-the-fact consumers have.
615
+ autonomous: input.autonomous === true,
616
+ // Persist the explicit opt-out so queued-run restart recovery and the
617
+ // session Git routes can distinguish it from a removed isolated worktree.
618
+ worktree: !group && input.worktree === false ? false : undefined,
619
+ groupId: group?.groupId,
620
+ variant: group?.variant,
621
+ steps: workflow.steps.map((s) => ({ id: s.id, name: s.name ?? s.id, kind: stepKind(s) })),
622
+ });
623
+ // Persist the full definition so a queued run survives a restart (#367) —
624
+ // ad-hoc "(planned)" chains exist nowhere else to re-resolve from.
625
+ this.store.updateRun(run.id, { workflowDef: workflow });
626
+ // Initial pasted attachments must be visible while the run is still queued (#612),
627
+ // and must survive a restart before a slot opens. Persist them before the job
628
+ // enters `pendingJobs`; `hydrateQueuedInput` reconstructs their content blocks
629
+ // from these URLs when a recovered run eventually starts — and for a file (#950)
630
+ // this write is the ONLY copy, since it never had a block to be rebuilt from.
631
+ if (input.images?.length) {
632
+ const persisted = this.persistPastedAttachments(run.id, input.images);
633
+ if (persisted.length) {
634
+ this.store.updateRun(run.id, { taskImages: persisted.map((saved) => saved.url) });
635
+ }
636
+ }
637
+ // Step-0 reference extraction (task auto-naming spec): the regex layer's
638
+ // numbers persist immediately; the namer may add the kind it verified later.
639
+ const skillHint = workflow.steps.find((s) => stepKind(s) === 'agent' && s.skill)?.skill?.trim();
640
+ const refs = refineTaskRefs(extractTaskRefs(input.task), skillHint);
641
+ if (refs.prNumber !== undefined || refs.issueNumber !== undefined) {
642
+ this.store.updateRun(run.id, {
643
+ ...(refs.prNumber !== undefined ? { prNumber: refs.prNumber } : {}),
644
+ ...(refs.issueNumber !== undefined ? { issueNumber: refs.issueNumber } : {}),
645
+ });
646
+ }
647
+ // Fire-and-forget LLM naming (task auto-naming spec): the heuristic title
648
+ // above shows instantly; the namer's short title replaces it when (and if)
649
+ // the model answers. Never awaited, never fails the run.
650
+ void this.autoNameRun(run.id, skillHint, input.task);
651
+ this.pendingJobs.set(run.id, { workflow, input: effectiveInput });
652
+ this.queue.push(run.id);
653
+ void this.pump();
654
+ return run;
655
+ }
656
+ /**
657
+ * Parallel variants (spec 010): N runs of the same workflow on the same
658
+ * task, sharing a groupId. Variant A gets the task verbatim; B and C get a
659
+ * fixed one-line approach hint appended to the *task input* (not the step
660
+ * template), so diversification works with any workflow. The normal queue
661
+ * applies — with maxParallel=2 a third variant simply waits.
662
+ */
663
+ startVariants(workflow, input, count) {
664
+ const groupId = randomUUID();
665
+ return VARIANT_LETTERS.slice(0, Math.min(Math.max(count, 1), VARIANT_LETTERS.length)).map((variant) => {
666
+ const hint = VARIANT_HINTS[variant];
667
+ const task = hint ? `${input.task}\n\n${hint}` : input.task;
668
+ return this.startRun(workflow, { ...input, task, worktree: undefined }, { groupId, variant });
669
+ });
670
+ }
671
+ /**
672
+ * Slots this manager holds against the workspace-wide cap. `waiting` runs
673
+ * don't hold a slot (#347): an idle claude process costs memory but no
674
+ * tokens, queued work progressing matters more, and the idle timeout already
675
+ * bounds how long a session can sit open. Because the exemption lives HERE —
676
+ * in the count, not in any acquire path — a message into a `waiting` run
677
+ * (sendMessage) resumes it immediately even when that momentarily exceeds
678
+ * `maxParallel`, including when other projects saturate the cap.
679
+ */
680
+ busySlots() {
681
+ const ordinaryWaiting = this.waiting.size - this.monitoring.size;
682
+ const exemptMonitoring = Math.min(this.monitoring.size, this.semaphore.maxMonitoringSessions());
683
+ return this.active.size + this.starting.size - ordinaryWaiting - exemptMonitoring;
684
+ }
685
+ /** Epoch ms of this manager's oldest queued run (the semaphore's fairness
686
+ * key when a freed slot is broadcast), or null when nothing is queued.
687
+ * `queue` is FIFO — `startRun` pushes and `recover()` re-queues by
688
+ * `createdAt` — so the head is the oldest. */
689
+ oldestQueuedAt() {
690
+ const head = this.queue[0];
691
+ if (!head)
692
+ return null;
693
+ const createdAt = this.store.getRun(head)?.createdAt;
694
+ const ms = createdAt ? Date.parse(createdAt) : Number.NaN;
695
+ return Number.isNaN(ms) ? null : ms;
696
+ }
697
+ /**
698
+ * A slot this manager held just came free. Pump the whole WORKSPACE, not
699
+ * just this manager: `maxParallel` is counted across every project, so the
700
+ * run that should take the slot is the workspace's oldest queued one — which
701
+ * usually sits in another project's queue. Pumping only `this` is what left
702
+ * a queued run in project B stuck at `queued` while project A's runs came
703
+ * and went. `release()` pumps this manager too, so it replaces the local
704
+ * `pump()` at every slot-freeing transition.
705
+ */
706
+ releaseSlot() {
707
+ void this.semaphore.release();
708
+ }
709
+ /**
710
+ * Start queued runs while parallel slots are free. A run starts only under
711
+ * BOTH ceilings: the WORKSPACE `resources.maxParallel` (default 2, counted
712
+ * across every manager — spec 2026-07-20, step 2.5) AND this project's own
713
+ * per-project `maxParallel` when the registry sets one (spec 2026-07-22,
714
+ * inherits the workspace cap when unset). Legacy per-repo `maxParallel` keys
715
+ * are ignored. A non-git directory degrades to 1 sequential run in the repo
716
+ * root (spec 006 degradation rule), which is always the tighter bound.
717
+ */
718
+ async pump() {
719
+ this.reconcileMonitoringWakeTimers();
720
+ this.reconcileAutoResumes();
721
+ // A pump requested while one is in flight can't just be dropped: the
722
+ // in-flight pass may already have read capacity (it awaits `getRepoInfo`
723
+ // before the first check), so a slot freed in that window would be lost
724
+ // until the next unrelated event. Re-run the sweep instead.
725
+ if (this.pumping) {
726
+ this.pumpAgain = true;
727
+ return;
728
+ }
729
+ this.pumping = true;
730
+ try {
731
+ do {
732
+ this.pumpAgain = false;
733
+ const repo = await getRepoInfo(this.repoRoot);
734
+ const maxParallel = this.semaphore.maxParallel();
735
+ // Per-project ceiling (spec 2026-07-22-per-project-concurrency): this
736
+ // project never runs more than its own configured `maxParallel`; absent
737
+ // an override it equals the workspace cap, so behavior is unchanged.
738
+ const projectMax = this.semaphore.projectMaxParallel(this.repoRoot);
739
+ // `waiting` runs don't hold a slot (#347) — see busySlots(). The check
740
+ // below is the only slot gate: resumes never pass through it. A run
741
+ // starts only under BOTH the workspace cap and this project's ceiling.
742
+ const capacity = () => this.semaphore.busy() < maxParallel &&
743
+ this.busySlots() < projectMax &&
744
+ (repo !== null || this.busySlots() < 1);
745
+ // The usage-limit hold (spec 2026-08-03-auto-resume-after-usage-limit).
746
+ //
747
+ // A limit closes an ACCOUNT, not a run — so starting the next queued task walks it into
748
+ // the same wall. Measured before this gate existed: eight tasks under `maxParallel: 2`
749
+ // all failed within 517 ms, each spawning a CLI (and, outside worktree-opt-out mode, a
750
+ // worktree and a branch) only to be marked `scheduled`. The cap was respected at every
751
+ // instant and was no brake at all, because a doomed run lives ~200 ms.
752
+ //
753
+ // So: while any run on an account is waiting out a limit, nothing new starts on THAT
754
+ // account. Other accounts (a second login, a different backend) keep running — the hold
755
+ // is keyed, not global. The set is derived from the durable records rather than tracked
756
+ // separately, which is what makes it survive a restart, expire on its own, and lift the
757
+ // instant a user cancels a resume.
758
+ // The watchdog's one-shot override — read and cleared here, so a forced sweep never
759
+ // leaks into the next ordinary one.
760
+ const forced = this.forceNextPump;
761
+ this.forceNextPump = false;
762
+ const holds = this.queue.length > 0 && !forced ? this.semaphore.accountHolds() : NO_HOLDS;
763
+ const anyHold = holds.deadline.size > 0 || holds.inFlight.size > 0;
764
+ // Only pay for the config read when something is actually held: a queued record may name
765
+ // no runner, and then the account it would use is the configured default.
766
+ const defaultRunner = anyHold ? (await loadConfig(this.repoRoot)).defaultRunner : undefined;
767
+ while (this.queue.length > 0 && capacity()) {
768
+ // FIFO among the runs that CAN start; a held one keeps its place in the queue rather
769
+ // than being dequeued and re-queued (which would churn its position and its record).
770
+ const next = !anyHold
771
+ ? 0
772
+ : this.queue.findIndex((id) => {
773
+ const queued = this.store.getRun(id);
774
+ return !queued || !accountHeldFor(queued, holds, defaultRunner ?? 'claude');
775
+ });
776
+ if (next === -1)
777
+ break; // everything queued is waiting on a held account
778
+ const runId = this.queue.splice(next, 1)[0];
779
+ if (!runId)
780
+ break;
781
+ // A forced sweep has to reach the spawn: the gate inside `execute` asks the same
782
+ // question and would send this run straight back to the queue.
783
+ if (forced)
784
+ this.forceStarted.add(runId);
785
+ const job = this.pendingJobs.get(runId);
786
+ const continuation = this.pendingContinuations.get(runId);
787
+ this.pendingJobs.delete(runId);
788
+ this.pendingContinuations.delete(runId);
789
+ if (!job && !continuation)
790
+ continue;
791
+ this.starting.add(runId);
792
+ if (continuation) {
793
+ const hydrated = this.hydrateQueuedContinuation(runId, continuation);
794
+ void this.runContinuation(runId, hydrated.stepId, hydrated.sessionId, hydrated.backend, hydrated.prompt, hydrated.images, hydrated.persistedImages, hydrated.persistedAttachments).catch((err) => {
795
+ const message = err instanceof Error ? err.message : String(err);
796
+ this.store.updateRun(runId, {
797
+ status: 'failed',
798
+ error: `continue crashed: ${message}`,
799
+ finishedAt: new Date().toISOString(),
800
+ });
801
+ this.starting.delete(runId);
802
+ this.dropActive(runId);
803
+ });
804
+ continue;
805
+ }
806
+ if (!job)
807
+ continue;
808
+ // Rebuild the prompt from the store at the last instant (#472), so an edit
809
+ // or a stacked message that landed while the run waited is honored. Entered
810
+ // in the same synchronous tick as the `pendingJobs.delete` above, so no
811
+ // handler can observe a half-dequeued run.
812
+ const input = this.hydrateQueuedInput(runId, job.input);
813
+ void this.execute(runId, job.workflow, input).catch((err) => {
814
+ const message = err instanceof Error ? err.message : String(err);
815
+ this.store.updateRun(runId, {
816
+ status: 'failed',
817
+ error: `engine crashed: ${message}`,
818
+ finishedAt: new Date().toISOString(),
819
+ });
820
+ const state = this.active.get(runId);
821
+ if (state) {
822
+ this.clearIdleTimer(state);
823
+ this.clearAutosaveTimer(state);
824
+ }
825
+ this.starting.delete(runId);
826
+ this.dropActive(runId);
827
+ });
828
+ }
829
+ } while (this.pumpAgain);
830
+ }
831
+ finally {
832
+ this.pumping = false;
833
+ }
834
+ }
835
+ /**
836
+ * Make one `queued` RECORD executable again — the engine half a queued run needs but does not
837
+ * persist (`pendingJobs` / `pendingContinuations` are process-local, the record is not).
838
+ *
839
+ * Two callers, one path: boot recovery re-adopts everything the previous process was holding,
840
+ * and the queue watchdog re-adopts anything the running process has somehow lost. A queued
841
+ * record with no work item behind it is invisible to `pump()` and would sit there for good,
842
+ * which is the worst failure this engine has — the task is neither running nor failed, just
843
+ * silently never going to happen.
844
+ *
845
+ * A continuation is reconstructed first: its executable details are gone, but the pending
846
+ * `continue-N` step and the session before it are durable, which is enough. Otherwise the
847
+ * workflow is revived from the record. A run that can be neither is failed loudly rather than
848
+ * left in the queue as a ghost.
849
+ */
850
+ async reviveQueuedRun(run, reason) {
851
+ const queuedContinuation = [...run.steps]
852
+ .reverse()
853
+ .find((step) => step.status === 'pending' && step.id.startsWith('continue-'));
854
+ const sessionStep = queuedContinuation
855
+ ? [...run.steps].reverse().find((step) => step.id !== queuedContinuation.id && step.sessionId)
856
+ : undefined;
857
+ if (queuedContinuation && sessionStep?.sessionId) {
858
+ const backend = run.runner ?? 'claude';
859
+ const sessionBackend = sessionStep.backend ?? backend;
860
+ this.pendingContinuations.set(run.id, {
861
+ stepId: queuedContinuation.id,
862
+ sessionId: sessionBackend === backend ? sessionStep.sessionId : undefined,
863
+ backend,
864
+ prompt: RESTART_CONTINUATION_PROMPT,
865
+ images: [],
866
+ });
867
+ this.queue.push(run.id);
868
+ this.store.appendEvent(run.id, {
869
+ type: 'lifecycle',
870
+ message: `${reason} — interrupted continuation re-queued`,
871
+ });
872
+ return;
873
+ }
874
+ const workflow = await this.reviveWorkflow(run);
875
+ if (!workflow) {
876
+ this.store.updateRun(run.id, {
877
+ status: 'failed',
878
+ error: 'interrupted — workflow definition not recoverable after a restart',
879
+ finishedAt: new Date().toISOString(),
880
+ });
881
+ this.store.appendEvent(run.id, {
882
+ type: 'lifecycle',
883
+ message: `${reason} — workflow definition not recoverable, task failed`,
884
+ });
885
+ return;
886
+ }
887
+ // Re-apply the inbox ceiling (#471). `execute()` gates again at spawn time, so the agent is
888
+ // safe either way — but a run queued while the inbox was on and recovered after it was
889
+ // switched off would otherwise keep echoing `generateFollowups: true` on a run that
890
+ // demonstrably produced none. Normalize the record, the way startRun does.
891
+ const generateFollowups = followupsEnabled() ? run.generateFollowups : false;
892
+ if (generateFollowups !== run.generateFollowups) {
893
+ this.store.updateRun(run.id, { generateFollowups });
894
+ }
895
+ this.pendingJobs.set(run.id, {
896
+ workflow,
897
+ // Folded through the same helper `pump()` uses (#472) so a restart carries the stack.
898
+ // Idempotent: hydration always composes from `run.task` + the stack, never from an
899
+ // already-folded `input.task`, so re-hydrating at dequeue yields the same string.
900
+ input: this.hydrateQueuedInput(run.id, {
901
+ task: run.task,
902
+ model: run.model,
903
+ runner: run.runner,
904
+ generateFollowups,
905
+ // Re-thread autonomy (#489): the rebuilt input feeds `execute`, whose mid-run auto-nudge
906
+ // reads `input.autonomous`. Without this a recovered autonomous run would run
907
+ // non-autonomously and later wrongly park at `review`.
908
+ autonomous: run.autonomous,
909
+ // Preserve an explicit worktree opt-out across a queued restart.
910
+ worktree: run.worktree,
911
+ }),
912
+ });
913
+ this.queue.push(run.id);
914
+ this.store.appendEvent(run.id, { type: 'lifecycle', message: `${reason} — task re-queued` });
915
+ }
916
+ /**
917
+ * Startup recovery (#367) — re-adopt runs that were live when the previous
918
+ * xezar process exited (requires the store opened with `keepLive`):
919
+ * - `queued` → back into the queue (FIFO by createdAt), from the persisted
920
+ * workflowDef (or the catalog by name for older records);
921
+ * - `waiting` → the turn was over and the ball was in the user's court —
922
+ * settle exactly like a closed session (review/done, Continue still works);
923
+ * - `running` → mark interrupted, then immediately resume the last agent
924
+ * session via the Continue path, pointing the agent at its handoff file.
925
+ * Call once, before the server starts taking requests.
926
+ */
927
+ async recover() {
928
+ const live = this.store
929
+ .listRuns()
930
+ .filter((r) => ['queued', 'waiting', 'running'].includes(r.status))
931
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
932
+ // A crash never reaches `dropActive`, so its temp directory (#785) outlived the run.
933
+ // Startup is the one moment we know which runs are still live, so sweep every other
934
+ // per-run directory here — bounded to `<dataDir>/tmp`, never a sibling.
935
+ sweepAgentTmpDirs(this.dataDir, live.map((r) => r.id));
936
+ for (const run of live) {
937
+ if (run.status === 'queued') {
938
+ await this.reviveQueuedRun(run, 'xezar restarted');
939
+ continue;
940
+ }
941
+ if (run.status === 'waiting') {
942
+ for (const step of run.steps) {
943
+ if (step.status === 'waiting' || step.status === 'running') {
944
+ this.store.updateStep(run.id, step.id, { status: 'done', finishedAt: new Date().toISOString() });
945
+ }
946
+ }
947
+ this.store.appendEvent(run.id, {
948
+ type: 'lifecycle',
949
+ message: 'xezar restarted — the open session was settled',
950
+ });
951
+ await this.settleSuccess(run.id);
952
+ continue;
953
+ }
954
+ // `running`: the process died mid-turn. Mark it interrupted (the state
955
+ // continueRun expects), then pick the work back up from the last session.
956
+ const finishedAt = new Date().toISOString();
957
+ for (const step of run.steps) {
958
+ if (step.status === 'running' || step.status === 'waiting') {
959
+ this.store.updateStep(run.id, step.id, { status: 'failed', finishedAt });
960
+ }
961
+ }
962
+ this.store.updateRun(run.id, {
963
+ status: 'failed',
964
+ error: 'interrupted — xezar process exited during the run',
965
+ finishedAt,
966
+ currentStepId: undefined,
967
+ });
968
+ const resumed = this.continueRun(run.id, {
969
+ text: RESTART_CONTINUATION_PROMPT,
970
+ }, true);
971
+ this.store.appendEvent(run.id, {
972
+ type: 'lifecycle',
973
+ message: resumed.ok
974
+ ? 'xezar restarted — resuming the interrupted task from its last session'
975
+ : `xezar restarted — could not resume the interrupted task (${resumed.error ?? 'unknown'})`,
976
+ });
977
+ }
978
+ // Re-arm usage-limit resumes (spec 2026-08-03-auto-resume-after-usage-limit): the wait is
979
+ // routinely longer than a xezar session, so the deadline is durable and the timer is rebuilt
980
+ // from it. `pump()` reconciles again on every sweep, so this is the fast path, not the only
981
+ // one — see `reconcileAutoResumes`.
982
+ this.reconcileAutoResumes();
983
+ void this.pump();
984
+ }
985
+ /** The persisted definition when it looks sane, else the catalog by name. */
986
+ async reviveWorkflow(run) {
987
+ // "Looks sane" is the STORE's job now: it parses `workflowDef` against the definition schema
988
+ // and `.catch`es a def that no longer fits to `undefined`, so anything present here already
989
+ // has the `steps` array the old inline `Array.isArray` check was asking for.
990
+ const def = run.workflowDef;
991
+ if (def)
992
+ return def;
993
+ const { workflows } = await loadWorkflows(this.repoRoot);
994
+ return workflows.find((w) => w.name === run.workflow) ?? null;
995
+ }
996
+ /** Remove a run from the live registries — keeps `waiting ⊆ active`. */
997
+ dropActive(runId) {
998
+ const state = this.active.get(runId);
999
+ state?.releaseRepoRoot?.();
1000
+ if (state)
1001
+ state.releaseRepoRoot = undefined;
1002
+ this.waiting.delete(runId);
1003
+ this.monitoring.delete(runId);
1004
+ if (state)
1005
+ this.clearMonitoringWakeTimer(state, runId);
1006
+ this.active.delete(runId);
1007
+ this.memoryPausing.delete(runId);
1008
+ this.lastNamerKey.delete(runId);
1009
+ this.forceStarted.delete(runId);
1010
+ // The run's slot is gone from busySlots() as of the deletes above — hand it
1011
+ // to the workspace's oldest queued run, in ANY project. Every terminal path
1012
+ // funnels through here, so this one call covers them all.
1013
+ // Same reasoning as retention below — every terminal path funnels through here, so the
1014
+ // usage-limit question ("did this run stop because the account is out of window, and when
1015
+ // does that window reopen?") is asked once, in one place, off the record the failing path
1016
+ // has already written. Nothing to do for any other outcome.
1017
+ //
1018
+ // BEFORE releasing the slot, and that order is the whole point: `releaseSlot` pumps every
1019
+ // manager, and a pump reads the hold off the records. Publishing the schedule afterwards
1020
+ // left a window — measured as exactly one extra task — where the queue saw a free slot and
1021
+ // an account that looked healthy, and started work that was already doomed.
1022
+ this.scheduleAutoResumeIfLimited(runId);
1023
+ this.releaseSlot();
1024
+ // A run leaving the active registry is a terminal transition (done/review/
1025
+ // failed/cancelled) — the one moment the finished-worktree count can grow.
1026
+ // Enforce count-based retention (#483) here so a single hook covers every
1027
+ // terminal path. Fire-and-forget: retention must never delay or throw into
1028
+ // the lifecycle.
1029
+ void this.enforceRetention();
1030
+ // The run's temp directory (#785) goes on the same terminal transition, and
1031
+ // unconditionally — it is scratch, not an artifact, so unlike a worktree
1032
+ // there is no keep-count to respect and nothing left to recover from it. A
1033
+ // Continue (or an auto-resume) re-creates it through `agentEnv`.
1034
+ removeAgentTmpDir(this.dataDir, runId);
1035
+ }
1036
+ // ---- usage-limit auto-resume (spec 2026-08-03-auto-resume-after-usage-limit) --------------
1037
+ /**
1038
+ * A run just failed: if the provider said "usage limit, back at T", promise to resume it at
1039
+ * `T + AUTO_RESUME_GRACE_MS` instead of leaving the task dead until someone notices.
1040
+ *
1041
+ * Every refusal below is silent-but-honest — the run stays `failed` with its Continue button,
1042
+ * which is exactly the pre-feature behavior — except the safety cap, which says so on the
1043
+ * transcript, because a run that stops resuming itself needs to explain why.
1044
+ */
1045
+ scheduleAutoResumeIfLimited(runId) {
1046
+ if (this.autoResumeTimers.has(runId))
1047
+ return; // already promised
1048
+ const run = this.store.getRun(runId);
1049
+ if (!run || run.status !== 'failed')
1050
+ return;
1051
+ // Archiving IS resigning from a task. Reviving one because a window happened to reopen would
1052
+ // be the feature working against the clearest signal the user can give it.
1053
+ if (run.archived)
1054
+ return;
1055
+ const limit = parseUsageLimit(run.error);
1056
+ if (!limit)
1057
+ return;
1058
+ if (!this.semaphore.autoResumeOnUsageLimit())
1059
+ return;
1060
+ // No session to resume = nothing this feature can do; `continueRun` would refuse anyway.
1061
+ if (!run.steps.some((step) => step.sessionId))
1062
+ return;
1063
+ const attempts = run.autoResumeAttempts ?? 0;
1064
+ if (attempts >= MAX_AUTO_RESUMES) {
1065
+ this.store.appendEvent(runId, {
1066
+ type: 'note',
1067
+ message: `automatic resume cap reached (${MAX_AUTO_RESUMES}) — continue this task manually`,
1068
+ });
1069
+ return;
1070
+ }
1071
+ const wakeAt = new Date(limit.resetAt.getTime() + AUTO_RESUME_GRACE_MS);
1072
+ this.armAutoResume(runId, wakeAt.getTime());
1073
+ this.store.appendEvent(runId, {
1074
+ type: 'lifecycle',
1075
+ message: `usage limit reached — resuming automatically at ${formatWakeInstant(wakeAt)}`,
1076
+ });
1077
+ }
1078
+ /** Publish the deadline on the record (the cockpit's only source) and arm the timer for it. */
1079
+ armAutoResume(runId, deadline) {
1080
+ this.store.updateRun(runId, { autoResumeAt: new Date(deadline).toISOString() });
1081
+ const timer = setTimeout(() => this.fireAutoResume(runId), Math.max(0, deadline - Date.now()));
1082
+ timer.unref?.();
1083
+ this.autoResumeTimers.set(runId, timer);
1084
+ }
1085
+ /**
1086
+ * The window has reopened. Re-check the record synchronously — hours may have passed, and the
1087
+ * user may have continued, deleted or cancelled the run in them — then hand the resume to the
1088
+ * ordinary queued-continuation path so it obeys both concurrency caps like any other work.
1089
+ */
1090
+ fireAutoResume(runId) {
1091
+ this.autoResumeTimers.delete(runId);
1092
+ const run = this.store.getRun(runId);
1093
+ if (!run || run.status !== 'failed' || !run.autoResumeAt)
1094
+ return;
1095
+ // Belt and braces against the one gap `reconcileAutoResumes` cannot close: the setting going
1096
+ // off in the window between the last pump and this tick.
1097
+ if (!this.semaphore.autoResumeOnUsageLimit()) {
1098
+ this.clearAutoResume(runId);
1099
+ return;
1100
+ }
1101
+ const attempts = (run.autoResumeAttempts ?? 0) + 1;
1102
+ // `continueRun` retires the pending resume (timer + record fields) on the way in — this is a
1103
+ // resume, not a user turn, so the counter is put back straight after.
1104
+ const resumed = this.continueRun(runId, { text: AUTO_RESUME_PROMPT }, true);
1105
+ if (!resumed.ok) {
1106
+ // Refusals happen before `continueRun` retires anything, so the deadline is still on the
1107
+ // record — and a deadline in the past is a promise the cockpit keeps displaying and the
1108
+ // engine will never keep. Retire it here instead, and say why.
1109
+ this.clearAutoResume(runId);
1110
+ this.store.appendEvent(runId, {
1111
+ type: 'note',
1112
+ message: `automatic resume could not start — ${resumed.error ?? 'unknown'}`,
1113
+ });
1114
+ return;
1115
+ }
1116
+ this.store.updateRun(runId, { autoResumeAttempts: attempts });
1117
+ this.store.appendEvent(runId, {
1118
+ type: 'lifecycle',
1119
+ message: `usage limit reset — resuming automatically (${attempts}/${MAX_AUTO_RESUMES})`,
1120
+ });
1121
+ // A deferred continuation only ENQUEUES itself; the queue moves when something pumps it, and
1122
+ // `recover()` — the other deferring caller — pumps once after its whole bulk sweep. A timer
1123
+ // firing on its own has no such follow-up, so without this the resumed run sits at `queued`
1124
+ // until some unrelated run happens to finish. This is the pump for it.
1125
+ void this.pump();
1126
+ }
1127
+ /**
1128
+ * Make the armed timers agree with the records and the current setting. Runs on every `pump()`
1129
+ * — which is where a settings change lands (a config PUT refreshes the shared semaphore, which
1130
+ * pumps every manager) — and once from `recover()`.
1131
+ *
1132
+ * It is a RECONCILE rather than a one-shot restore because the deadline is durable state and
1133
+ * the timer is not: a restart, a rebuilt project context, a manager disposed mid-wait, or a
1134
+ * refusal all leave a record promising a resume that no timer is holding. Rebuilding from the
1135
+ * record covers every one of those at once — the alternative is a hint counting down to a time
1136
+ * that has already passed, which is exactly the failure this method exists to make impossible.
1137
+ *
1138
+ * Cheap: an in-memory scan, and arming is skipped for every run already held.
1139
+ */
1140
+ reconcileAutoResumes() {
1141
+ if (!this.semaphore.autoResumeOnUsageLimit()) {
1142
+ // Sweep the RECORDS, not the timer map. A record promising a resume that no timer is
1143
+ // holding is the exact population this method exists for, and it is also the one the
1144
+ // setting can be switched off in front of: xezar restarted while it was off, the config
1145
+ // was hand-edited, or the project context was disposed mid-wait. Retiring only the armed
1146
+ // timers leaves such a record with a live `autoResumeAt`, which `accountHolds()` reads as
1147
+ // a deadline hold — so nothing new starts on that account, `rescueStalledQueue` treats the
1148
+ // phantom appointment as a legitimate reason to sit still, and the cockpit shows a
1149
+ // `scheduled` row for a resume that will never come. `clearAutoResume` covers the armed
1150
+ // ones too, so this one loop is the whole cancellation.
1151
+ const pending = new Set([
1152
+ ...this.autoResumeTimers.keys(),
1153
+ ...this.store.listRuns().filter((run) => run.autoResumeAt !== undefined).map((run) => run.id),
1154
+ ]);
1155
+ for (const runId of pending) {
1156
+ this.clearAutoResume(runId);
1157
+ this.store.appendEvent(runId, {
1158
+ type: 'note',
1159
+ message: 'automatic resume cancelled — auto-resume is switched off',
1160
+ });
1161
+ }
1162
+ return;
1163
+ }
1164
+ for (const run of this.store.listRuns()) {
1165
+ if (run.status !== 'failed' || !run.autoResumeAt)
1166
+ continue;
1167
+ if (this.autoResumeTimers.has(run.id))
1168
+ continue;
1169
+ const deadline = Date.parse(run.autoResumeAt);
1170
+ // A deadline that is unreadable, belongs to a run that has spent its cap, or belongs to a
1171
+ // task the user has archived is retired rather than re-armed: it can only mislead. One
1172
+ // that has just passed arms at zero — the window is open, which is the point.
1173
+ if (run.archived
1174
+ || !Number.isFinite(deadline)
1175
+ || (run.autoResumeAttempts ?? 0) >= MAX_AUTO_RESUMES) {
1176
+ this.store.updateRun(run.id, { autoResumeAt: undefined });
1177
+ continue;
1178
+ }
1179
+ // …and one missed by more than a day is retired loudly: reviving a task from another era
1180
+ // is a surprise, not a service, and this is what keeps a sweep from resurrecting every
1181
+ // limit-stopped task a user has long since walked away from.
1182
+ if (Date.now() - deadline > AUTO_RESUME_MISSED_WINDOW_MS) {
1183
+ this.store.updateRun(run.id, { autoResumeAt: undefined });
1184
+ this.store.appendEvent(run.id, {
1185
+ type: 'note',
1186
+ message: 'automatic resume expired — its window reopened over a day ago; continue this task manually',
1187
+ });
1188
+ continue;
1189
+ }
1190
+ this.armAutoResume(run.id, deadline);
1191
+ }
1192
+ }
1193
+ /**
1194
+ * Hand a run that has not spawned anything back to the queue, when the account it would run on
1195
+ * went into a usage-limit hold (spec 2026-08-03-auto-resume-after-usage-limit).
1196
+ *
1197
+ * The dequeue-time gate in `pump()` cannot be the only one: a run can sit between dequeue and
1198
+ * spawn for a long time — an in-place run waiting for the exclusive repo-root lease is the
1199
+ * measured case — and the account can close in that gap. This is the last honest moment to
1200
+ * refuse, because everything after it costs a real agent turn.
1201
+ *
1202
+ * "Untouched" is the contract: the run has created no session and no worktree, so it goes back
1203
+ * as plain `queued` with its `startedAt` cleared, and `pump()` will pick it up when the window
1204
+ * reopens. Returns true when the caller must abandon the run.
1205
+ */
1206
+ requeueWhileHeld(runId, workflow, input, runner, state) {
1207
+ const run = this.store.getRun(runId);
1208
+ if (!run || run.status === 'cancelled' || state?.cancelled)
1209
+ return false;
1210
+ // The watchdog sent this one through. Checked, never consumed: the spawn path asks this
1211
+ // question TWICE — here at the top of `execute`, and again after the exclusive repo-root
1212
+ // lease is granted — so a one-shot flag would clear at the first gate and let the second one
1213
+ // hand an in-place run straight back, re-wedging the queue the rescue had just freed.
1214
+ // `dropActive` retires the entry on every terminal path, so the set still cleans itself up.
1215
+ if (this.forceStarted.has(runId))
1216
+ return false;
1217
+ if (!accountHeldFor({ ...run, runner }, this.semaphore.accountHolds(), runner))
1218
+ return false;
1219
+ state?.releaseRepoRoot?.();
1220
+ if (state)
1221
+ state.releaseRepoRoot = undefined;
1222
+ this.pendingJobs.set(runId, { workflow, input });
1223
+ this.queue.push(runId);
1224
+ this.store.updateRun(runId, { status: 'queued', startedAt: undefined, currentStepId: undefined });
1225
+ this.store.appendEvent(runId, {
1226
+ type: 'note',
1227
+ message: 'held in the queue — this agent account is waiting out a usage limit',
1228
+ });
1229
+ this.dropActive(runId);
1230
+ return true;
1231
+ }
1232
+ /**
1233
+ * The failsafe: a queue must never be able to wedge.
1234
+ *
1235
+ * Everything else in this file makes an idle queue CORRECT under some condition — a slot cap, a
1236
+ * repo-root lease, and now a usage-limit hold. That is also what makes a wedged queue look
1237
+ * correct, and the hold has already produced one in the field: two resumes fired together, each
1238
+ * holding the account the other was waiting on, and the whole workspace stopped with every task
1239
+ * `queued`. That specific bug is fixed and tested, but "the queue stopped and nothing will ever
1240
+ * restart it" is too expensive a failure mode to leave resting on any single fix being right.
1241
+ *
1242
+ * The test is deliberately about JUSTIFICATION rather than about any particular bug: idling is
1243
+ * legitimate while work is running (here or in another project), or while a real appointment is
1244
+ * still ahead — a scheduled resume that will fire and pump on its own. Anything else is a
1245
+ * queue with work in it, nothing running anywhere, and no event coming to wake it. That gets one
1246
+ * forced sweep, which starts work under the ordinary caps and lets the account's real state
1247
+ * re-assert itself: if the window truly is shut, that task meets the limit and re-establishes an
1248
+ * honest hold, with a real deadline behind it this time.
1249
+ *
1250
+ * Public so a test can drive the wedge directly instead of waiting out the interval.
1251
+ */
1252
+ async rescueStalledQueue(now = Date.now()) {
1253
+ // First, the worst shape: a record that says `queued` while the engine holds no job, no
1254
+ // continuation and no queue entry for it. `pump()` cannot see such a run — it iterates the
1255
+ // queue, and this one is not in it — so nothing will ever start it. Re-adopt it through the
1256
+ // same path boot recovery uses.
1257
+ for (const run of this.store.listRuns()) {
1258
+ if (run.status !== 'queued')
1259
+ continue;
1260
+ if (this.active.has(run.id) || this.starting.has(run.id))
1261
+ continue;
1262
+ if (this.pendingJobs.has(run.id) || this.pendingContinuations.has(run.id))
1263
+ continue;
1264
+ if (this.queue.includes(run.id))
1265
+ continue;
1266
+ console.warn(`[xez] queue watchdog: re-adopting queued run ${run.id} the engine had lost`);
1267
+ await this.reviveQueuedRun(run, 'queue watchdog');
1268
+ }
1269
+ if (this.queue.length === 0)
1270
+ return;
1271
+ if (this.busySlots() > 0 || this.starting.size > 0)
1272
+ return;
1273
+ if (this.semaphore.busy() > 0)
1274
+ return;
1275
+ // A future deadline is a real reason to sit still: that timer will fire and pump.
1276
+ for (const run of this.store.listRuns()) {
1277
+ if (run.status !== 'failed' || !run.autoResumeAt)
1278
+ continue;
1279
+ const deadline = Date.parse(run.autoResumeAt);
1280
+ if (Number.isFinite(deadline) && deadline > now)
1281
+ return;
1282
+ }
1283
+ if (this.semaphore.accountHolds().inFlight.size === 0) {
1284
+ // Not the hold, then — some other wakeup went missing. An ordinary pump is the whole fix,
1285
+ // and it is idempotent, so this stays quiet.
1286
+ void this.pump();
1287
+ return;
1288
+ }
1289
+ console.warn('[xez] queue watchdog: work is queued, nothing is running, and the usage-limit hold has no'
1290
+ + ' deadline behind it — starting the next task anyway');
1291
+ this.forceNextPump = true;
1292
+ void this.pump();
1293
+ }
1294
+ /**
1295
+ * The accounts this project is currently holding: one key per run parked on a usage-limit
1296
+ * resume that has not come due yet (spec 2026-08-03-auto-resume-after-usage-limit).
1297
+ *
1298
+ * Published to the shared semaphore so the hold spans PROJECTS — one Claude account can be
1299
+ * driving tasks in three repos, and a limit closes it for all of them. Derived from the
1300
+ * records on every ask rather than tracked as state: a deadline that passes, a resume that
1301
+ * fires, a cancel, an archive and a delete all lift the hold with no bookkeeping.
1302
+ *
1303
+ * Deliberately excludes a deadline that has already passed — that run is about to resume, and
1304
+ * holding the queue for it would only stall the very work the window reopened for.
1305
+ */
1306
+ accountHolds(now = Date.now()) {
1307
+ const deadline = new Set();
1308
+ const inFlight = new Set();
1309
+ for (const run of this.store.listRuns()) {
1310
+ // A holding run always carries the runner it actually ran on, so the fallback is unused
1311
+ // here — it is spelled out rather than `!` so a future record shape degrades, not throws.
1312
+ const key = () => runAccountKey(run, run.runner ?? 'claude');
1313
+ if (run.status === 'failed' && run.autoResumeAt) {
1314
+ const at = Date.parse(run.autoResumeAt);
1315
+ if (Number.isFinite(at) && at > now)
1316
+ deadline.add(key());
1317
+ }
1318
+ else if (resumeInFlight(run)) {
1319
+ inFlight.add(key());
1320
+ }
1321
+ }
1322
+ return { deadline, inFlight };
1323
+ }
1324
+ /**
1325
+ * The PER-TASK off switch (`DELETE /api/v1/runs/:id/auto-resume`, and the archive route):
1326
+ * stop resuming THIS task, without touching the workspace setting or any other task.
1327
+ *
1328
+ * Idempotent — a run with nothing pending answers the same way, because "this task will not
1329
+ * resume itself" is equally true either way. Returns false only when the run does not exist,
1330
+ * which is the route's 404.
1331
+ */
1332
+ cancelAutoResume(runId) {
1333
+ const run = this.store.getRun(runId);
1334
+ if (!run)
1335
+ return false;
1336
+ const pending = run.autoResumeAt !== undefined || this.autoResumeTimers.has(runId);
1337
+ this.clearAutoResume(runId);
1338
+ if (pending) {
1339
+ this.store.appendEvent(runId, {
1340
+ type: 'note',
1341
+ message: 'automatic resume cancelled for this task',
1342
+ });
1343
+ // This run may have been the last thing holding its account's queue — nothing else will
1344
+ // notice, since the hold is derived and its release is not an event.
1345
+ void this.pump();
1346
+ }
1347
+ return true;
1348
+ }
1349
+ /** Retire a pending resume — timer, deadline and counter. The counter goes too because every
1350
+ * caller is a fresh epoch: a human Continue, or a resume that re-stamps its own count. */
1351
+ clearAutoResume(runId) {
1352
+ const timer = this.autoResumeTimers.get(runId);
1353
+ if (timer)
1354
+ clearTimeout(timer);
1355
+ this.autoResumeTimers.delete(runId);
1356
+ const run = this.store.getRun(runId);
1357
+ if (!run)
1358
+ return;
1359
+ if (run.autoResumeAt !== undefined || run.autoResumeAttempts !== undefined) {
1360
+ this.store.updateRun(runId, { autoResumeAt: undefined, autoResumeAttempts: undefined });
1361
+ }
1362
+ }
1363
+ /** Reclaim finished worktrees beyond the keep-limit (#483) — directory only,
1364
+ * `xez/<id8>` branch kept. Best-effort; a failure never affects run
1365
+ * lifecycle. `review`/live runs are excluded by the selector. */
1366
+ async enforceRetention() {
1367
+ try {
1368
+ const keep = await resolveWorktreeRetention(this.repoRoot);
1369
+ await reclaimWorktrees(this.repoRoot, this.store, keep);
1370
+ }
1371
+ catch {
1372
+ // retention is best-effort; swallow so terminal transitions never break.
1373
+ }
1374
+ }
1375
+ /** Last live-refresh namer inputs per run — unchanged inputs skip the call. */
1376
+ lastNamerKey = new Map();
1377
+ /**
1378
+ * Acquire the one-at-a-time lease for runs executing in `repoRoot`.
1379
+ *
1380
+ * A lease waiter is idle, so it parks in `waiting` and gives its
1381
+ * `maxParallel` slot back (the #347 rule): isolated worktrees keep using
1382
+ * every configured slot while root runs line up. The store status stays
1383
+ * `running` — only the queue's busy count changes, so the GUI never shows a
1384
+ * lease-blocked run as awaiting user input.
1385
+ *
1386
+ * The lease is held for the run's whole lifetime, including the idle
1387
+ * `waiting` parks between agent turns. A parked session is still live and
1388
+ * writes to the working tree the moment it resumes, so handing the tree to
1389
+ * another run there would reintroduce the concurrent-edit bug (#438) this
1390
+ * lease exists to prevent.
1391
+ *
1392
+ * Returns false when the run was cancelled while waiting: the lease was
1393
+ * never granted and the caller must not touch the working tree.
1394
+ */
1395
+ async acquireRepoRoot(runId, state) {
1396
+ // `cancel()` can land between the run going `running` and reaching here,
1397
+ // while `interrupt` is still the default no-op — never enter the chain.
1398
+ if (state.cancelled)
1399
+ return false;
1400
+ const previous = this.repoRootTail;
1401
+ let release = () => undefined;
1402
+ this.repoRootTail = new Promise((resolve) => {
1403
+ release = resolve;
1404
+ });
1405
+ // Until `previous` resolves this run does not own the tree yet, so a drop
1406
+ // during the wait must not hand the tree to the next waiter — chain our
1407
+ // release behind `previous` instead of resolving the tail early.
1408
+ state.releaseRepoRoot = () => {
1409
+ void previous.then(release);
1410
+ };
1411
+ let abort = () => undefined;
1412
+ const cancelled = new Promise((resolve) => {
1413
+ abort = resolve;
1414
+ });
1415
+ const parked = state.interrupt;
1416
+ state.interrupt = () => {
1417
+ parked();
1418
+ abort();
1419
+ };
1420
+ this.waiting.add(runId);
1421
+ this.releaseSlot();
1422
+ try {
1423
+ await Promise.race([previous, cancelled]);
1424
+ }
1425
+ finally {
1426
+ state.interrupt = parked;
1427
+ this.waiting.delete(runId);
1428
+ }
1429
+ if (state.cancelled)
1430
+ return false;
1431
+ state.releaseRepoRoot = release;
1432
+ return true;
1433
+ }
1434
+ cancel(runId) {
1435
+ // Still waiting in the queue: just drop it there.
1436
+ const queuedAt = this.queue.indexOf(runId);
1437
+ if (queuedAt >= 0) {
1438
+ this.queue.splice(queuedAt, 1);
1439
+ this.pendingJobs.delete(runId);
1440
+ this.pendingContinuations.delete(runId);
1441
+ this.store.updateRun(runId, { status: 'cancelled', finishedAt: new Date().toISOString() });
1442
+ this.store.appendEvent(runId, { type: 'lifecycle', message: 'cancelled while queued' });
1443
+ return true;
1444
+ }
1445
+ const state = this.active.get(runId);
1446
+ if (!state)
1447
+ return false;
1448
+ state.cancelled = true;
1449
+ this.clearIdleTimer(state);
1450
+ state.interrupt();
1451
+ return true;
1452
+ }
1453
+ isActive(runId) {
1454
+ return this.active.has(runId) || this.starting.has(runId) || this.queue.includes(runId);
1455
+ }
1456
+ /**
1457
+ * Fold a queued run's persisted prompt — `run.task` plus everything stacked
1458
+ * onto it (#472) — into the job input that is about to execute.
1459
+ *
1460
+ * Called from `pump()` immediately before `execute()`, which makes the RECORD
1461
+ * the single source of truth for a queued run's prompt. Before this, the
1462
+ * executing copy lived in `pendingJobs` (memory) while the record held a
1463
+ * second one, so an edit that PATCHed the record silently did nothing until a
1464
+ * restart. `recover()` rebuilds through the same helper, so both paths agree.
1465
+ *
1466
+ * **Read-only, and that is load-bearing.** It composes into the in-memory
1467
+ * `input` and never writes the folded string back to `RunRecord.task`; the
1468
+ * task and its stack stay separate on disk for the life of the run. Writing
1469
+ * back would re-append the whole stack on every recovery and compound without
1470
+ * bound — asserted directly by a test.
1471
+ */
1472
+ hydrateQueuedInput(runId, input) {
1473
+ const run = this.store.getRun(runId);
1474
+ if (!run)
1475
+ return input;
1476
+ const stack = run.queuedMessages ?? [];
1477
+ const task = [run.task, ...stack.map((m) => m.text)]
1478
+ .map((part) => part.trim())
1479
+ .filter((part) => part.length > 0)
1480
+ .join('\n\n');
1481
+ // Keep the original in-memory blocks for a live process (including the
1482
+ // best-effort case where persistence failed). Recovery has no such copy,
1483
+ // so rebuild it from the durable task-image URLs.
1484
+ const images = input.images?.length
1485
+ ? input.images
1486
+ : this.readPersistedAttachments(runId, run.taskImages ?? [], 'task').blocks;
1487
+ const stackedImages = this.readPersistedAttachments(runId, stack.flatMap((m) => m.images ?? []), 'queued').blocks;
1488
+ return {
1489
+ ...input,
1490
+ task,
1491
+ ...(images.length ? { images } : { images: undefined }),
1492
+ ...(stackedImages.length ? { stackedImages } : { stackedImages: undefined }),
1493
+ };
1494
+ }
1495
+ /** Apply edits and messages made while a restart continuation waits for
1496
+ * capacity. The durable record remains the source of truth, just as it is for
1497
+ * an ordinary queued workflow (#472), so a second restart reconstructs and
1498
+ * hydrates the same amendments instead of dropping them. */
1499
+ hydrateQueuedContinuation(runId, continuation) {
1500
+ const run = this.store.getRun(runId);
1501
+ if (!run) {
1502
+ return { ...continuation, persistedImages: [], persistedAttachments: [] };
1503
+ }
1504
+ const stack = run.queuedMessages ?? [];
1505
+ const amendedTask = [run.task, ...stack.map((message) => message.text)]
1506
+ .map((part) => part.trim())
1507
+ .filter((part) => part.length > 0)
1508
+ .join('\n\n');
1509
+ const prompt = amendedTask
1510
+ ? `${continuation.prompt}\n\nCurrent task and queued updates:\n\n${amendedTask}`
1511
+ : continuation.prompt;
1512
+ const persisted = this.readPersistedAttachments(runId, stack.flatMap((message) => message.images ?? []), 'queued');
1513
+ return {
1514
+ ...continuation,
1515
+ prompt,
1516
+ persistedImages: persisted.blocks,
1517
+ persistedAttachments: persisted.attachments,
1518
+ };
1519
+ }
1520
+ /**
1521
+ * Re-read persisted attachments at dequeue/restart (#472): an image comes back as a viewable
1522
+ * block AND a path, a file (#950) as a path only. The branch is on the NAME's extension, never
1523
+ * on which list the URL came from — images and files share one list, and re-encoding a `.pdf`
1524
+ * into a base64 image block is a message no backend can accept.
1525
+ *
1526
+ * A file is still `stat`-checked here rather than trusted: an attachment the user deleted must
1527
+ * drop out of the paths handed to the agent, exactly as a missing image does.
1528
+ */
1529
+ readPersistedAttachments(runId, urls, kind) {
1530
+ const blocks = [];
1531
+ const attachments = [];
1532
+ for (const url of urls) {
1533
+ const name = url.split('/').pop();
1534
+ if (!name || name.includes('..') || name.includes('/') || name.includes('\\'))
1535
+ continue;
1536
+ const path = join(this.dataDir, 'runs', `${runId}-images`, name);
1537
+ try {
1538
+ if (isImageAttachmentName(name)) {
1539
+ const data = readFileSync(path);
1540
+ blocks.push({
1541
+ type: 'image',
1542
+ source: { type: 'base64', media_type: mediaTypeFor(name), data: data.toString('base64') },
1543
+ });
1544
+ }
1545
+ else if (!existsSync(path)) {
1546
+ throw new Error('missing');
1547
+ }
1548
+ attachments.push({ name, url, path });
1549
+ }
1550
+ catch {
1551
+ // Degrade, never fail the boot (AGENTS.md): the user deleted `.ai/xezar/`
1552
+ // or the file is unreadable — start with the text and say which attachment went.
1553
+ this.store.appendEvent(runId, {
1554
+ type: 'note',
1555
+ message: `${kind} attachment ${name} could not be read — starting without it`,
1556
+ });
1557
+ }
1558
+ }
1559
+ return { blocks, attachments };
1560
+ }
1561
+ /**
1562
+ * Still waiting for a slot? Checked against the engine's own queue rather than
1563
+ * the record's `status` (#472): the record is written by `execute()` a tick
1564
+ * after `pump()` dequeues, so a status read can see `queued` for a run that has
1565
+ * already started. The pending maps are deleted synchronously at dequeue, so
1566
+ * they are the authoritative answer for "can this prompt still be amended".
1567
+ */
1568
+ isQueued(runId) {
1569
+ return this.pendingJobs.has(runId) || this.pendingContinuations.has(runId);
1570
+ }
1571
+ /** Split a pasted message into the persisted shape a stacked message holds. */
1572
+ toQueuedMessage(runId, content) {
1573
+ const text = content
1574
+ .filter((b) => b.type === 'text')
1575
+ .map((b) => b.text)
1576
+ .join('\n');
1577
+ const images = this.persistPastedAttachments(runId, content).map((saved) => saved.url);
1578
+ return {
1579
+ id: randomUUID(),
1580
+ text,
1581
+ ...(images.length ? { images } : {}),
1582
+ createdAt: new Date().toISOString(),
1583
+ };
1584
+ }
1585
+ /**
1586
+ * Append a prompt message onto a still-queued run (#472). Returns the stored
1587
+ * entry, or null when the run has already started — the caller then falls
1588
+ * through to `deferMessage`.
1589
+ */
1590
+ enqueueMessage(runId, content) {
1591
+ if (!this.isQueued(runId))
1592
+ return null;
1593
+ const run = this.store.getRun(runId);
1594
+ if (!run)
1595
+ return null;
1596
+ const message = this.toQueuedMessage(runId, content);
1597
+ this.store.updateRun(runId, { queuedMessages: [...(run.queuedMessages ?? []), message] });
1598
+ return message;
1599
+ }
1600
+ /** Edit a stacked message in place. Omitted fields retain their current value. */
1601
+ editQueuedMessage(runId, msgId, edit) {
1602
+ if (!this.isQueued(runId))
1603
+ return null;
1604
+ const run = this.store.getRun(runId);
1605
+ const stack = run?.queuedMessages;
1606
+ if (!stack)
1607
+ return null;
1608
+ const at = stack.findIndex((m) => m.id === msgId);
1609
+ if (at < 0)
1610
+ return null;
1611
+ const current = stack[at];
1612
+ const replacementImages = edit.images === undefined
1613
+ ? current.images
1614
+ : this.toQueuedMessage(runId, edit.images).images;
1615
+ const replacement = {
1616
+ id: msgId,
1617
+ text: edit.text ?? current.text,
1618
+ ...(replacementImages?.length ? { images: replacementImages } : {}),
1619
+ createdAt: current.createdAt,
1620
+ };
1621
+ const next = [...stack];
1622
+ next[at] = replacement;
1623
+ this.store.updateRun(runId, { queuedMessages: next });
1624
+ // Images the edit dropped are now orphans.
1625
+ this.dropOrphanImages(runId, stack[at].images ?? [], next);
1626
+ return replacement;
1627
+ }
1628
+ /** Remove a stacked message and its now-orphaned attachments. */
1629
+ removeQueuedMessage(runId, msgId) {
1630
+ if (!this.isQueued(runId))
1631
+ return false;
1632
+ const run = this.store.getRun(runId);
1633
+ const stack = run?.queuedMessages;
1634
+ if (!stack)
1635
+ return false;
1636
+ const target = stack.find((m) => m.id === msgId);
1637
+ if (!target)
1638
+ return false;
1639
+ const next = stack.filter((m) => m.id !== msgId);
1640
+ this.store.updateRun(runId, { queuedMessages: next });
1641
+ this.dropOrphanImages(runId, target.images ?? [], next);
1642
+ return true;
1643
+ }
1644
+ /**
1645
+ * Delete image files no longer referenced by anything (#472). Best effort — a
1646
+ * leftover file is harmless and goes with the run. Never touches a URL still
1647
+ * referenced by another stacked entry or by the initial prompt's `taskImages`.
1648
+ */
1649
+ dropOrphanImages(runId, candidates, stack) {
1650
+ if (!candidates.length)
1651
+ return;
1652
+ const run = this.store.getRun(runId);
1653
+ const referenced = new Set([
1654
+ ...(run?.taskImages ?? []),
1655
+ ...stack.flatMap((m) => m.images ?? []),
1656
+ ]);
1657
+ for (const url of candidates) {
1658
+ if (referenced.has(url))
1659
+ continue;
1660
+ const name = url.split('/').pop();
1661
+ // Defend the join against a crafted URL: only a bare file name may be deleted.
1662
+ if (!name || name.includes('..') || name.includes('/') || name.includes('\\'))
1663
+ continue;
1664
+ try {
1665
+ rmSync(join(this.dataDir, 'runs', `${runId}-images`, name), { force: true });
1666
+ }
1667
+ catch {
1668
+ /* best effort */
1669
+ }
1670
+ }
1671
+ }
1672
+ /**
1673
+ * Edit the initial prompt of a still-queued run (#472). Re-derives the
1674
+ * heuristic title and the PR/issue chips, but never re-runs the LLM namer —
1675
+ * it already fired at creation and a second model call per edit is unjustified.
1676
+ */
1677
+ editTask(runId, task) {
1678
+ if (!this.isQueued(runId))
1679
+ return false;
1680
+ const run = this.store.getRun(runId);
1681
+ if (!run)
1682
+ return false;
1683
+ const workflow = this.pendingJobs.get(runId)?.workflow;
1684
+ const skillHint = workflow?.steps.find((s) => stepKind(s) === 'agent' && s.skill)?.skill?.trim();
1685
+ const refs = refineTaskRefs(extractTaskRefs(task), skillHint);
1686
+ // Hand-edited titles always win (#389): `user` beats the heuristic, and a
1687
+ // `marker` title the agent declared beats it too.
1688
+ const keepTitle = run.titleOrigin === 'user' || run.titleOrigin === 'marker';
1689
+ this.store.updateRun(runId, {
1690
+ task,
1691
+ ...(keepTitle || !workflow ? {} : { title: makeRunTitle(task, workflow) }),
1692
+ ...(refs.prNumber !== undefined ? { prNumber: refs.prNumber } : {}),
1693
+ ...(refs.issueNumber !== undefined ? { issueNumber: refs.issueNumber } : {}),
1694
+ });
1695
+ return true;
1696
+ }
1697
+ /**
1698
+ * Buffer a message that arrived in the gap between dequeue and session-open
1699
+ * (#472). `pump()` has already folded the stack and `execute()` is spawning the
1700
+ * backend, so there is nothing left to amend and no session to deliver into —
1701
+ * without this rung the message would 409, a genuinely dropped message in the
1702
+ * feature built to stop dropping them. Flushed as an ordinary follow-up turn
1703
+ * the instant the session opens; dropped if the run never starts, which the
1704
+ * existing error path already surfaces.
1705
+ *
1706
+ * The buffer lives on the manager rather than the `ActiveRun` because the
1707
+ * `ActiveRun` does not exist yet for part of this window.
1708
+ */
1709
+ deferMessage(runId, content) {
1710
+ // The window spans two sub-states: `starting` (no `ActiveRun` yet) and the
1711
+ // longer stretch where the `ActiveRun` exists but the backend is still being
1712
+ // spawned. `execute()` deletes the run from `starting` as soon as it builds
1713
+ // the state — seconds before the session opens — so checking `starting`
1714
+ // alone would reopen exactly the drop this rung exists to close.
1715
+ const state = this.active.get(runId);
1716
+ const startingUp = this.starting.has(runId) || (state !== undefined && !state.sessionEverOpened && !state.cancelled);
1717
+ if (!startingUp)
1718
+ return false;
1719
+ const pending = this.deferredMessages.get(runId) ?? [];
1720
+ pending.push(content);
1721
+ this.deferredMessages.set(runId, pending);
1722
+ return true;
1723
+ }
1724
+ /** Deliver anything `deferMessage` buffered, once the session is live. */
1725
+ flushDeferred(runId) {
1726
+ const pending = this.deferredMessages.get(runId);
1727
+ if (!pending?.length)
1728
+ return;
1729
+ // Re-buffer whatever the session refused rather than dropping it. `sendMessage`
1730
+ // answers false when the session is not open yet — and silently losing a message
1731
+ // here would be precisely the failure `deferMessage` exists to prevent. Anything
1732
+ // left over is retried by the next session that opens on this run.
1733
+ const unsent = pending.filter((content) => !this.sendMessage(runId, content));
1734
+ if (unsent.length)
1735
+ this.deferredMessages.set(runId, unsent);
1736
+ else
1737
+ this.deferredMessages.delete(runId);
1738
+ }
1739
+ /**
1740
+ * Deliver a user message into the run's live claude session (mid-turn or
1741
+ * while `waiting`). Returns false when there is no open session — the GUI
1742
+ * then offers "Continue" instead.
1743
+ */
1744
+ sendMessage(runId, content) {
1745
+ const delivered = this.deliverMessage(runId, content, true);
1746
+ if (delivered) {
1747
+ const state = this.active.get(runId);
1748
+ if (state)
1749
+ state.monitoringWakeups = 0;
1750
+ this.store.updateRun(runId, { monitoringWakeCapReached: undefined });
1751
+ }
1752
+ return delivered;
1753
+ }
1754
+ /** Shared live-session delivery. Synthetic scheduler prompts reuse lifecycle
1755
+ * bookkeeping without masquerading as user-authored transcript messages. */
1756
+ deliverMessage(runId, content, userAuthored) {
1757
+ const state = this.active.get(runId);
1758
+ if (!state?.session?.open || state.cancelled)
1759
+ return false;
1760
+ const text = content
1761
+ .filter((b) => b.type === 'text')
1762
+ .map((b) => b.text)
1763
+ .join('\n');
1764
+ // Persist the attachments so the thread can render them (not just count them) — the same
1765
+ // on-disk store + `/images/` route the agent's own screenshots use. `pasted` prefix marks
1766
+ // these as user attachments (vs. agent tool screenshots) on disk (#357).
1767
+ const persisted = userAuthored ? this.persistPastedAttachments(runId, content) : [];
1768
+ const images = persisted.map((saved) => saved.url);
1769
+ if (userAuthored) {
1770
+ this.store.appendEvent(runId, {
1771
+ type: 'user-message',
1772
+ stepId: state.currentStepId,
1773
+ text,
1774
+ imageCount: content.filter((b) => b.type === 'image').length,
1775
+ images,
1776
+ });
1777
+ }
1778
+ // Tell the agent where the pasted files live on disk (#357): image blocks still ride along
1779
+ // so the model can *view* them, but a real path is what lets it *operate* on them (save,
1780
+ // `cp`, attach to a GitHub issue/PR) — and it's the only usable reference on backends (codex,
1781
+ // opencode) that drop image blocks entirely before reaching the model, and the ONLY reference
1782
+ // at all for a non-image attachment (#950), which is why `contentBlocksOf` drops file blocks
1783
+ // here rather than letting one reach a backend that has no idea what it is.
1784
+ const blocks = contentBlocksOf(content);
1785
+ const expanded = userAuthored ? expandRegistrySlashSkill(blocks, state.skills ?? []) : blocks;
1786
+ const deliverable = persisted.length ? [...expanded, pastedAttachmentsNote(persisted)] : expanded;
1787
+ const delivered = state.session.sendMessage(deliverable);
1788
+ if (delivered) {
1789
+ this.clearIdleTimer(state);
1790
+ this.clearMonitoringWakeTimer(state, runId);
1791
+ this.waiting.delete(runId); // resumed — the run counts against slots again
1792
+ this.monitoring.delete(runId);
1793
+ // Clear any `monitoring` activity — the agent is actively working again
1794
+ // (spec 2026-07-18-subagent-monitoring-status, #490).
1795
+ this.store.updateRun(runId, { status: 'running', activity: undefined });
1796
+ if (state.currentStepId) {
1797
+ this.store.updateStep(runId, state.currentStepId, { status: 'running' });
1798
+ }
1799
+ }
1800
+ return delivered;
1801
+ }
1802
+ /** Close the open session gracefully — the run then completes as `done`
1803
+ * (or rests at `review` when the worktree holds changes, spec 009).
1804
+ * On a run already resting at `review` (no session — the engine loop is
1805
+ * over), "Finish" is the third review exit: accept the changes without a
1806
+ * PR and flip straight to `done`. */
1807
+ finish(runId) {
1808
+ const state = this.active.get(runId);
1809
+ if (state?.session?.open) {
1810
+ this.clearIdleTimer(state);
1811
+ this.store.appendEvent(runId, { type: 'lifecycle', message: 'session closed by user' });
1812
+ state.session.end();
1813
+ return true;
1814
+ }
1815
+ const run = this.store.getRun(runId);
1816
+ if (run?.status === 'review' && !this.isActive(runId)) {
1817
+ this.store.updateRun(runId, { status: 'done' });
1818
+ this.store.appendEvent(runId, { type: 'lifecycle', message: 'review accepted — finished without a PR' });
1819
+ return true;
1820
+ }
1821
+ return false;
1822
+ }
1823
+ /**
1824
+ * "Continue" (spec 003): reopen a finished run's claude session in-process
1825
+ * (`claude --resume <sessionId>`) as a new synthetic step. The session then
1826
+ * behaves exactly like an interactive step: `waiting` after each turn,
1827
+ * messages via sendMessage, closed by finish/idle/cancel.
1828
+ */
1829
+ continueRun(runId, opts = {},
1830
+ /** Restart recovery may discover several interrupted tasks at once. Those
1831
+ * continuations are queued; an explicit user Continue remains immediate. */
1832
+ deferForCapacity = false) {
1833
+ if (agentModelsLocked(this.repoRoot) && opts.model?.trim()) {
1834
+ return { ok: false, error: AGENT_MODELS_LOCKED_ERROR };
1835
+ }
1836
+ if (this.active.has(runId))
1837
+ return { ok: false, error: 'run is still active' };
1838
+ const run = this.store.getRun(runId);
1839
+ if (!run)
1840
+ return { ok: false, error: 'not found' };
1841
+ // `review` is continuable too — that's the "Send back" path (spec 009).
1842
+ if (!['done', 'failed', 'cancelled', 'review'].includes(run.status)) {
1843
+ return { ok: false, error: `cannot continue a ${run.status} run` };
1844
+ }
1845
+ const sessionStep = [...run.steps].reverse().find((s) => s.sessionId);
1846
+ if (!sessionStep?.sessionId)
1847
+ return { ok: false, error: 'no agent session to resume' };
1848
+ const targetRunner = opts.runner ?? run.runner ?? 'claude';
1849
+ // Session ids are provider-owned opaque values. New records carry explicit
1850
+ // affinity; for legacy records, the run's current runner is the conservative
1851
+ // owner until a continuation emits a new, attributed session id (#562).
1852
+ const sessionBackend = sessionStep.backend ?? run.runner ?? 'claude';
1853
+ // A session id only resolves inside the config dir that created it (spec
1854
+ // 2026-07-29-agent-profiles), so switching ACCOUNT ends the session exactly like switching
1855
+ // backend does: `claude --resume <id>` under another login finds nothing and would silently
1856
+ // open a fresh conversation while the thread claimed it had resumed. A step that recorded no
1857
+ // account predates the feature and therefore ran under the discovered one.
1858
+ const sessionAccount = sessionStep.profileId ?? DEFAULT_AGENT_ACCOUNT_ID;
1859
+ const accountSwitched = opts.agentProfile !== undefined && opts.agentProfile !== sessionAccount;
1860
+ const resume = sessionBackend === targetRunner && !accountSwitched;
1861
+ // Follow-up runner/model/account override (#401, spec 2026-07-29-agent-profiles): the composer
1862
+ // lets the user pick which backend, model and login handle this continuation — the same flat
1863
+ // pill the /new composer offers. Omitted → the run's current backend/model/account is kept
1864
+ // (backward compat). A provided choice is persisted BEFORE scheduling, so it becomes the
1865
+ // run's current backend — `runContinuation` reads it off the record, later continuations
1866
+ // default to it, and the header reflects the active engine. An empty model ('') clears the
1867
+ // pin, letting the runner pick the model (auto).
1868
+ if (opts.runner !== undefined || opts.model !== undefined || opts.agentProfile !== undefined) {
1869
+ // Guard the pairing before persisting anything: the model override applies to the runner
1870
+ // this continuation will actually use (`opts.runner ?? record.runner ?? 'claude'` — the
1871
+ // same resolution `runContinuation` reads off the record). A model that is recognizably
1872
+ // another runner's preset would corrupt the run; free-form/custom ids pass untouched.
1873
+ if (opts.model && modelConflictsWithRunner(opts.model, targetRunner)) {
1874
+ return { ok: false, error: `model '${opts.model}' is not a ${targetRunner} model` };
1875
+ }
1876
+ // A runner switch that carries NO explicit model must not leave the previous backend's pin
1877
+ // on the record: the guard above only sees `opts.model`, so without this an inherited
1878
+ // `opus` would survive a switch to codex and `runContinuation` would hand it to the codex
1879
+ // runner. Clearing (not rejecting) is right — the pin belonged to the old backend and is
1880
+ // meaningless for the new one, which is exactly what the composer already displays (auto).
1881
+ // Only a recognizably foreign preset is cleared; a free-form/custom id is left alone.
1882
+ const inheritedPinIsForeign = opts.model === undefined &&
1883
+ run.model !== undefined &&
1884
+ modelConflictsWithRunner(run.model, targetRunner);
1885
+ // An account belongs to ONE agent, so a runner switch that names no account must not leave
1886
+ // the previous backend's login on the record. It is inert immediately (resolution applies
1887
+ // the run's account only to steps on the run's own runner) and wrong later, when a further
1888
+ // continuation switches back and inherits a login the user picked for a different task.
1889
+ const inheritedAccountIsForeign = opts.agentProfile === undefined &&
1890
+ run.agentProfile !== undefined &&
1891
+ targetRunner !== (run.runner ?? 'claude');
1892
+ this.store.updateRun(runId, {
1893
+ ...(opts.runner !== undefined ? { runner: opts.runner } : {}),
1894
+ ...(opts.model !== undefined
1895
+ ? { model: opts.model === '' ? undefined : opts.model }
1896
+ : inheritedPinIsForeign
1897
+ ? { model: undefined }
1898
+ : {}),
1899
+ // Persisted BEFORE scheduling, like the runner/model pair: `runContinuation` resolves the
1900
+ // account off the record, and every later continuation then defaults to it.
1901
+ ...(opts.agentProfile !== undefined
1902
+ ? { agentProfile: opts.agentProfile }
1903
+ : inheritedAccountIsForeign
1904
+ ? { agentProfile: undefined }
1905
+ : {}),
1906
+ });
1907
+ }
1908
+ // Everything that could refuse this continuation has now passed, so a pending usage-limit
1909
+ // resume is superseded either way: this IS that resume (it re-stamps its own counter), or a
1910
+ // human got there first — and then the counter starts over, because the cap only exists to
1911
+ // bound UNATTENDED resumes.
1912
+ this.clearAutoResume(runId);
1913
+ const continuations = run.steps.filter((s) => s.id.startsWith('continue-')).length;
1914
+ const stepId = `continue-${continuations + 1}`;
1915
+ this.store.addStep(runId, { id: stepId, name: 'Continue', kind: 'agent' });
1916
+ const prompt = opts.text?.trim() || 'Continue.';
1917
+ const images = opts.images ?? [];
1918
+ if (deferForCapacity) {
1919
+ this.pendingContinuations.set(runId, {
1920
+ stepId,
1921
+ sessionId: resume ? sessionStep.sessionId : undefined,
1922
+ backend: targetRunner,
1923
+ prompt,
1924
+ images,
1925
+ });
1926
+ this.queue.push(runId);
1927
+ this.store.updateRun(runId, {
1928
+ status: 'queued',
1929
+ error: undefined,
1930
+ finishedAt: undefined,
1931
+ currentStepId: undefined,
1932
+ });
1933
+ return { ok: true };
1934
+ }
1935
+ void this.runContinuation(runId, stepId, resume ? sessionStep.sessionId : undefined, targetRunner, prompt, images).catch((err) => {
1936
+ const message = err instanceof Error ? err.message : String(err);
1937
+ this.store.updateRun(runId, {
1938
+ status: 'failed',
1939
+ error: `continue crashed: ${message}`,
1940
+ finishedAt: new Date().toISOString(),
1941
+ });
1942
+ this.dropActive(runId);
1943
+ });
1944
+ return { ok: true };
1945
+ }
1946
+ async runContinuation(runId, stepId, sessionId, backend, prompt,
1947
+ /** Attachments pasted into the follow-up composer — delivered with the
1948
+ * reopened session's opening message, exactly like a live-session
1949
+ * message's attachments. */
1950
+ images = [],
1951
+ /** Queued-message screenshots were persisted when they were enqueued and
1952
+ * reconstructed at dequeue. Keep them separate from fresh `images` so
1953
+ * opening a recovered continuation does not persist duplicate files. */
1954
+ persistedImages = [], persistedAttachments = []) {
1955
+ // Continuation runs in the task's worktree when it still exists (spec
1956
+ // 006) — the resumed session sees exactly what the original run left.
1957
+ // Retention (#483) may have reclaimed this run's worktree directory while
1958
+ // keeping its branch and worktreePath. Re-materialize it on resume and clear
1959
+ // the stamp so the session regains its isolated tree and the run is eligible
1960
+ // for retention again — otherwise it keeps a dir on disk while staying
1961
+ // invisible to the enforcer forever. Best-effort; falls back to repoRoot.
1962
+ await rematerializeReclaimedWorktree(this.repoRoot, this.store, runId);
1963
+ const record = this.store.getRun(runId);
1964
+ // The env is a live ceiling: a run created while the inbox was on must not keep writing
1965
+ // follow-ups after it is switched off.
1966
+ const generateFollowups = followupsEnabled() && record?.generateFollowups !== false;
1967
+ const cwd = record?.worktreePath && existsSync(record.worktreePath)
1968
+ ? record.worktreePath
1969
+ : this.repoRoot;
1970
+ const state = { cancelled: false, interrupt: () => undefined, cwd };
1971
+ this.active.set(runId, state);
1972
+ this.starting.delete(runId);
1973
+ if (state.cwd === this.repoRoot) {
1974
+ if (repositoryRootLockDisabled()) {
1975
+ this.store.appendEvent(runId, {
1976
+ type: 'note',
1977
+ message: REPOSITORY_ROOT_LOCK_DISABLED_NOTE,
1978
+ });
1979
+ }
1980
+ else {
1981
+ this.store.appendEvent(runId, {
1982
+ type: 'note',
1983
+ message: 'waiting for exclusive access to the repository working tree',
1984
+ });
1985
+ if (!(await this.acquireRepoRoot(runId, state))) {
1986
+ this.store.updateRun(runId, {
1987
+ status: 'cancelled',
1988
+ finishedAt: new Date().toISOString(),
1989
+ currentStepId: undefined,
1990
+ });
1991
+ this.store.appendEvent(runId, { type: 'lifecycle', message: 'run cancelled' });
1992
+ this.dropActive(runId);
1993
+ return;
1994
+ }
1995
+ }
1996
+ }
1997
+ this.armAutosave(state);
1998
+ if (record)
1999
+ seedHandoffFile(this.dataDir, record); // idempotent — normally already there
2000
+ // Registry snapshot for `/skill` expansion. `execute` loads this for the workflow's own
2001
+ // sessions; a continuation builds its OWN ActiveRun, and without this the resumed session
2002
+ // expanded against an empty registry and leaked `/om-...` verbatim to the backend, which
2003
+ // answered "Unknown skill" (#811). Best-effort — discovery must never break Continue.
2004
+ state.skills = await discoverSkills(this.repoRoot).catch(() => []);
2005
+ this.store.updateRun(runId, {
2006
+ status: 'running',
2007
+ error: undefined,
2008
+ finishedAt: undefined,
2009
+ currentStepId: stepId,
2010
+ activity: undefined, // resuming a monitoring run — it's actively working again (#490)
2011
+ });
2012
+ this.store.updateStep(runId, stepId, {
2013
+ status: 'running',
2014
+ iterations: 1,
2015
+ startedAt: new Date().toISOString(),
2016
+ sessionId,
2017
+ backend,
2018
+ });
2019
+ this.store.appendEvent(runId, { type: 'step-start', stepId, name: 'Continue', kind: 'agent', iteration: 1 });
2020
+ // Attachments pasted into the follow-up composer, on the same terms as a live-session
2021
+ // message (#357): persisted to the run's own attachment store so the thread renders the
2022
+ // bubble's images rather than a bare count, and handed to the agent as absolute paths
2023
+ // appended to the prompt (so it can operate on them — and because codex/opencode drop image
2024
+ // blocks before they reach the model). An image ALSO rides along as a base64 block so the
2025
+ // model can view it; a file (#950) has nothing to view and travels as its path alone.
2026
+ const freshAttachments = this.persistPastedAttachments(runId, images);
2027
+ const openingImages = [...contentBlocksOf(images), ...persistedImages];
2028
+ const attachments = [...freshAttachments, ...persistedAttachments];
2029
+ this.store.appendEvent(runId, {
2030
+ type: 'user-message',
2031
+ stepId,
2032
+ text: prompt,
2033
+ imageCount: openingImages.filter((b) => b.type === 'image').length,
2034
+ ...(attachments.length ? { images: attachments.map((saved) => saved.url) } : {}),
2035
+ });
2036
+ let stepCost = 0;
2037
+ let turnText = '';
2038
+ let sessionError;
2039
+ const sink = this.makeUiSink(runId, stepId);
2040
+ const onEvent = (event) => {
2041
+ if (event.type === 'image') {
2042
+ const saved = this.persistAttachment(runId, event.mediaType, event.data);
2043
+ if (saved)
2044
+ this.store.appendEvent(runId, { type: 'image', stepId, ...saved });
2045
+ return;
2046
+ }
2047
+ if (event.type === 'text') {
2048
+ turnText = appendTurnText(turnText, event.text);
2049
+ const text = stripAskMarker(stripTaskMarkers(stripMonitoringMarker(stripDoneMarker(event.text))));
2050
+ if (text)
2051
+ this.store.appendEvent(runId, { type: 'text', text, stepId });
2052
+ return;
2053
+ }
2054
+ this.store.appendEvent(runId, { ...event, stepId });
2055
+ if (event.type === 'error') {
2056
+ sessionError ??= event.message;
2057
+ state.session?.interrupt();
2058
+ return;
2059
+ }
2060
+ if (sessionError)
2061
+ return;
2062
+ if (event.type === 'session') {
2063
+ this.store.updateStep(runId, stepId, { sessionId: event.sessionId, backend });
2064
+ }
2065
+ if (event.type === 'token-usage') {
2066
+ this.store.updateStep(runId, stepId, { tokensUsed: event.tokensUsed });
2067
+ }
2068
+ if (event.type === 'cost') {
2069
+ stepCost += event.usd;
2070
+ this.store.updateStep(runId, stepId, { costUsd: stepCost });
2071
+ }
2072
+ if (event.type === 'turn-end') {
2073
+ // Belt-and-braces: v2 `turn.completed` already flushed the delta
2074
+ // coalescers; the v1 turn boundary flushes again (idempotent) so no
2075
+ // buffered delta can outlive its turn.
2076
+ sink.flushAll();
2077
+ void this.recordTurnEnd(runId, turnText); // titleSummary + diffStat (#389)
2078
+ const sessionOpen = !state.cancelled && state.session?.open;
2079
+ const done = sessionOpen && DONE_MARKER_RE.test(turnText.trimEnd());
2080
+ // `XEZ:ASK` → the user is genuinely blocked; wins over `XEZ:MONITORING`
2081
+ // (a pending question is always attention), loses to `XEZ:DONE` (#473).
2082
+ const { ask, notes: askNotes } = resolveAskTurn(turnText, Boolean(sessionOpen) && !done);
2083
+ const monitoring = sessionOpen && !done && !ask && MONITORING_MARKER_RE.test(turnText.trimEnd());
2084
+ turnText = '';
2085
+ for (const note of askNotes)
2086
+ this.store.appendEvent(runId, { type: 'note', ...note, stepId });
2087
+ if (done) {
2088
+ // Goal achieved (agent contract, #347) — same as in runAgentStep.
2089
+ this.store.appendEvent(runId, { type: 'lifecycle', message: 'goal achieved — session closed' });
2090
+ appendHandoffHeartbeat(this.dataDir, runId, 'turn complete — goal achieved, session closed');
2091
+ state.session?.end();
2092
+ return;
2093
+ }
2094
+ if (sessionOpen) {
2095
+ // Autonomous (#autonomous): never hand the ball back to the user. Nudge the agent to
2096
+ // keep going (bounded by MAX_AUTO_CONTINUES) instead of parking at `waiting`.
2097
+ const autoContinued = state.autonomous &&
2098
+ (state.autoContinues ?? 0) < MAX_AUTO_CONTINUES &&
2099
+ !state.cancelled &&
2100
+ (() => {
2101
+ const sent = state.session?.sendMessage([{ type: 'text', text: AUTONOMOUS_NUDGE }]);
2102
+ if (!sent)
2103
+ return false;
2104
+ state.autoContinues = (state.autoContinues ?? 0) + 1;
2105
+ this.store.appendEvent(runId, {
2106
+ type: 'note',
2107
+ message: `autonomous — continuing without pausing (${state.autoContinues}/${MAX_AUTO_CONTINUES})`,
2108
+ });
2109
+ return true;
2110
+ })();
2111
+ if (!autoContinued) {
2112
+ // `XEZ:ASK` → park `waiting` (attention) AND surface the structured
2113
+ // question as an ask card (#473). `XEZ:MONITORING` → non-attention
2114
+ // `running`/`activity:'monitoring'` (#490). Both share the waiting
2115
+ // lifecycle (free the slot, keep the idle timer); the autonomous
2116
+ // nudge above still wins over either.
2117
+ if (ask)
2118
+ emitAskRequested(sink, ask);
2119
+ if (monitoring) {
2120
+ this.store.updateRun(runId, { status: 'running', activity: 'monitoring' });
2121
+ this.store.updateStep(runId, stepId, { status: 'running' });
2122
+ this.monitoring.add(runId);
2123
+ this.clearIdleTimer(state);
2124
+ this.armMonitoringWakeTimer(runId, state);
2125
+ }
2126
+ else {
2127
+ this.store.updateRun(runId, { status: 'waiting', activity: undefined });
2128
+ this.store.updateStep(runId, stepId, { status: 'waiting' });
2129
+ this.monitoring.delete(runId);
2130
+ this.clearMonitoringWakeTimer(state, runId);
2131
+ }
2132
+ this.waiting.add(runId);
2133
+ if (!monitoring)
2134
+ this.armIdleTimer(runId, state);
2135
+ this.releaseSlot();
2136
+ }
2137
+ }
2138
+ // A turn that completed is the ONLY evidence the provider's window actually reopened, so
2139
+ // it is what retires the consecutive-resume counter — which in turn releases the account
2140
+ // hold for every other task queued behind it (spec
2141
+ // 2026-08-03-auto-resume-after-usage-limit). `settleSuccess` does the same for a run that
2142
+ // finishes outright; this covers the far more common "parked for the user" ending.
2143
+ if (this.store.getRun(runId)?.autoResumeAttempts !== undefined) {
2144
+ this.store.updateRun(runId, { autoResumeAttempts: undefined });
2145
+ }
2146
+ appendHandoffHeartbeat(this.dataDir, runId, `turn complete — status=${monitoring ? 'monitoring' : sessionOpen ? 'waiting' : 'running'}`);
2147
+ }
2148
+ };
2149
+ // Backend + model come off the record: the run's current backend by default, or the
2150
+ // follow-up override that `continueRun` persisted before scheduling (#401).
2151
+ const continueBackend = backend;
2152
+ /** Settle this turn as a failure before anything is spawned — the shape both
2153
+ * pre-spawn gates below need (model identity, #405; temp directory, #785). */
2154
+ const failBeforeSpawn = (message) => {
2155
+ const failedAt = new Date().toISOString();
2156
+ sink.sessionEnded('error', message);
2157
+ this.store.updateStep(runId, stepId, {
2158
+ status: 'failed',
2159
+ error: message,
2160
+ finishedAt: failedAt,
2161
+ });
2162
+ this.store.updateRun(runId, {
2163
+ status: 'failed',
2164
+ error: `continue failed: ${message}`,
2165
+ finishedAt: failedAt,
2166
+ currentStepId: undefined,
2167
+ });
2168
+ this.store.appendEvent(runId, {
2169
+ type: 'lifecycle',
2170
+ message: `continue failed — ${message}`,
2171
+ });
2172
+ this.dropActive(runId);
2173
+ };
2174
+ // Apply the SAME canonical-identity gate the first spawn applies (#405, review M1).
2175
+ // A follow-up may switch both runner and model (#401), so without this the record keeps
2176
+ // asserting the identity the run STARTED with while a different model serves the turn —
2177
+ // the exact defect that PR existed to remove — and the raw record string reaches the CLI
2178
+ // in the un-normalised wire form the first step already converted away (`anthropic/opus`
2179
+ // instead of `opus`). Fail loud here too rather than let the backend pick a default.
2180
+ let continueModel;
2181
+ try {
2182
+ const normalized = normalizeModelForBackend(continueBackend, agentModelsLocked(this.repoRoot) ? undefined : record?.model, { configuredProvider: await configuredModelProvider(continueBackend, state.cwd) });
2183
+ continueModel = normalized?.backendModel;
2184
+ this.store.updateRun(runId, {
2185
+ modelIdentity: normalized ? formatModelIdentity(normalized.identity) : undefined,
2186
+ });
2187
+ }
2188
+ catch (err) {
2189
+ if (!(err instanceof ModelIdentityError))
2190
+ throw err;
2191
+ failBeforeSpawn(err.message);
2192
+ return;
2193
+ }
2194
+ // Resuming reattaches to a session that lives inside ONE account's config dir, so the
2195
+ // continuation must run under the account that created it — not whatever the project has
2196
+ // been switched to since. The owning step is the one carrying this session id.
2197
+ const owningStep = sessionId === undefined
2198
+ ? undefined
2199
+ : record?.steps.find((s) => s.sessionId === sessionId);
2200
+ const resumedProfileId = owningStep?.profileId;
2201
+ // The owning step also names the session's tools: resolve `allowedTools`/`bashAllowlist`
2202
+ // from the persisted `workflowDef` exactly as the first spawn did (`runAgentStep`).
2203
+ // Rebuilding with the bare DEFAULT_ALLOWED_TOOLS silently revoked every per-step grant
2204
+ // (MCP servers, subagents) on Continue, restart recovery and the usage-limit auto-resume
2205
+ // — and dropping `bashAllowlist` WIDENED Bash from an allowlist to unrestricted
2206
+ // (`AgentRunSpec.allowedTools`, #430). Record steps share ids with `workflowDef.steps`;
2207
+ // a synthetic `continue-N` owner and a fresh-session continuation (backend switch — no
2208
+ // owning session) both extend the run's tail, so they resolve from the definition's last
2209
+ // agent step. A legacy record without `workflowDef` (#367), or a session no step owns,
2210
+ // keeps today's defaults.
2211
+ const defSteps = record?.workflowDef?.steps;
2212
+ const toolsStep = defSteps === undefined || (sessionId !== undefined && owningStep === undefined)
2213
+ ? undefined
2214
+ : defSteps.find((s) => s.id === owningStep?.id)
2215
+ ?? [...defSteps].reverse().find((s) => stepKind(s) === 'agent');
2216
+ // The temp-directory preflight (#785) rides along with the account resolution: a resumed
2217
+ // turn hits the same broken `/tmp` a fresh one would, and an agent whose shell silently
2218
+ // returns nothing is worse than a turn that refuses to start and says why.
2219
+ let continueProfile;
2220
+ try {
2221
+ continueProfile = await this.agentEnvForStep(runId, continueBackend, {
2222
+ generateFollowups,
2223
+ recordedProfileId: resumedProfileId,
2224
+ });
2225
+ }
2226
+ catch (err) {
2227
+ if (!(err instanceof AgentTempDirError))
2228
+ throw err;
2229
+ failBeforeSpawn(err.message);
2230
+ return;
2231
+ }
2232
+ this.store.updateStep(runId, stepId, { profileId: continueProfile.profileId });
2233
+ const runner = createRunner(continueBackend);
2234
+ state.currentStepId = stepId;
2235
+ this.beginUsageInvocation(runId, state, stepId);
2236
+ // A continuation's opening message becomes the session's `userPrompt` and never passes
2237
+ // through `deliverMessage`, so it needs the SAME delivery-only `/skill` rewrite the
2238
+ // live path applies (#811). Delivery-only: the `user-message` event above already
2239
+ // persisted the user's original text, and the transcript must keep showing that.
2240
+ const openingPrompt = expandRegistrySlashSkillText(prompt, state.skills ?? []);
2241
+ const session = runner.startSession({
2242
+ // The Continue step is a fresh agent session on the same run — the
2243
+ // run's extra system prompt (already resolved at execute time and
2244
+ // echoed on the record) rides along with the handoff contract.
2245
+ systemPrompt: composeSystemPrompt(record?.systemPrompt, generateFollowups ? HANDOFF_INSTRUCTIONS : HANDOFF_ONLY_INSTRUCTIONS),
2246
+ userPrompt: attachments.length
2247
+ ? `${openingPrompt}\n\n${pastedAttachmentsText(attachments)}`
2248
+ : openingPrompt,
2249
+ ...(openingImages.length ? { images: openingImages } : {}),
2250
+ cwd: state.cwd,
2251
+ allowedTools: toolsStep?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
2252
+ bashAllowlist: toolsStep?.bashAllowlist,
2253
+ additionalDirectories: agentDirectories(join(this.dataDir, 'runs'), continueProfile.env),
2254
+ env: continueProfile.env,
2255
+ model: continueModel,
2256
+ sessionId,
2257
+ resume: sessionId !== undefined,
2258
+ timeoutMs: 0,
2259
+ }, onEvent, { onUiEvent: (event) => this.handleRunnerUiEvent(runId, state, sink, event) });
2260
+ state.session = session;
2261
+ state.sessionEverOpened = true;
2262
+ this.flushDeferred(runId);
2263
+ state.interrupt = () => session.interrupt();
2264
+ if (session.pid !== undefined)
2265
+ registerRunProcess(runId, session.pid);
2266
+ const finishedAt = () => new Date().toISOString();
2267
+ try {
2268
+ await session.result;
2269
+ if (sessionError)
2270
+ throw new Error(sessionError);
2271
+ sink.sessionEnded(state.cancelled ? 'cancelled' : 'end_turn');
2272
+ if (state.cancelled) {
2273
+ this.store.updateStep(runId, stepId, { status: 'cancelled', finishedAt: finishedAt() });
2274
+ this.store.updateRun(runId, { status: 'cancelled', finishedAt: finishedAt(), currentStepId: undefined });
2275
+ this.store.appendEvent(runId, { type: 'lifecycle', message: 'run cancelled' });
2276
+ appendHandoffHeartbeat(this.dataDir, runId, `step "${stepId}" complete — status=cancelled`);
2277
+ }
2278
+ else {
2279
+ this.store.updateStep(runId, stepId, { status: 'done', finishedAt: finishedAt() });
2280
+ this.store.appendEvent(runId, { type: 'step-end', stepId, status: 'done' });
2281
+ await this.settleSuccess(runId);
2282
+ appendHandoffHeartbeat(this.dataDir, runId, `step "${stepId}" complete — status=done`);
2283
+ }
2284
+ }
2285
+ catch (err) {
2286
+ const message = err instanceof Error ? err.message : String(err);
2287
+ sink.sessionEnded('error', message);
2288
+ this.store.updateStep(runId, stepId, { status: 'failed', error: message, finishedAt: finishedAt() });
2289
+ appendHandoffHeartbeat(this.dataDir, runId, `step "${stepId}" complete — status=failed`);
2290
+ this.store.updateRun(runId, {
2291
+ status: 'failed',
2292
+ error: `continue failed: ${message}`,
2293
+ finishedAt: finishedAt(),
2294
+ currentStepId: undefined,
2295
+ });
2296
+ this.store.appendEvent(runId, { type: 'lifecycle', message: `continue failed — ${message}` });
2297
+ }
2298
+ finally {
2299
+ this.recordUsagePeaks(runId);
2300
+ this.clearIdleTimer(state);
2301
+ this.clearAutosaveTimer(state);
2302
+ if (state.cwd !== this.repoRoot)
2303
+ await autosaveCommit(state.cwd, 'turn end');
2304
+ this.dropActive(runId);
2305
+ }
2306
+ }
2307
+ // ---- execution -----------------------------------------------------------
2308
+ async execute(runId, workflow, input) {
2309
+ const state = {
2310
+ cancelled: false,
2311
+ interrupt: () => undefined,
2312
+ cwd: this.repoRoot,
2313
+ autonomous: input.autonomous === true,
2314
+ autoContinues: 0,
2315
+ };
2316
+ this.active.set(runId, state);
2317
+ this.starting.delete(runId);
2318
+ const emit = (event) => this.store.appendEvent(runId, event);
2319
+ // Resolve the agent backend for this run: the task choice (GUI) wins over
2320
+ // the config default. Per-step `runner` can still override it below.
2321
+ const config = await loadConfig(this.repoRoot);
2322
+ const taskBackend = input.runner ?? config.defaultRunner;
2323
+ // The account may have gone into a usage-limit hold since this run was dequeued — the queue
2324
+ // gate cannot be the only one, because dequeue is not the moment of no return. Nothing has
2325
+ // happened yet here, so the run goes back to the queue untouched (spec
2326
+ // 2026-08-03-auto-resume-after-usage-limit).
2327
+ if (this.requeueWhileHeld(runId, workflow, input, taskBackend))
2328
+ return;
2329
+ // Extra system prompt (R2 2.3): POST override > config default; echoed on
2330
+ // the record so the UI/API can show what the run actually used.
2331
+ const extraSystemPrompt = resolveExtraSystemPrompt(input.systemPrompt, config.systemPrompt);
2332
+ // Canonical provider/model identity (#405) — the normalised `provider/model`
2333
+ // the task ran with, persisted for cost attribution / reproducible replay
2334
+ // beside the free-text `model`. Best-effort here (a per-step `runner`/`model`
2335
+ // can still override below); the authoritative fail-loud gate is at spawn.
2336
+ let modelIdentity;
2337
+ try {
2338
+ const normalized = normalizeModelForBackend(taskBackend, agentModelsLocked(this.repoRoot) ? undefined : input.model, { configuredProvider: await configuredModelProvider(taskBackend, this.repoRoot) });
2339
+ modelIdentity = normalized ? formatModelIdentity(normalized.identity) : undefined;
2340
+ }
2341
+ catch {
2342
+ // An unresolvable task-level model surfaces loudly at the step below; the
2343
+ // metadata echo stays absent rather than guessing.
2344
+ }
2345
+ this.store.updateRun(runId, {
2346
+ status: 'running',
2347
+ startedAt: new Date().toISOString(),
2348
+ runner: taskBackend,
2349
+ systemPrompt: extraSystemPrompt,
2350
+ modelIdentity,
2351
+ });
2352
+ emit({ type: 'lifecycle', message: `run started — workflow "${workflow.name}" (runner: ${taskBackend})` });
2353
+ // Worktree per task (spec 006): the agent works on its own branch in
2354
+ // `.ai/xezar/worktrees/<id>`, never in the user's working tree. A Git task
2355
+ // that requests isolation fails closed if the worktree cannot be
2356
+ // established; only explicit opt-out and non-Git modes run in place.
2357
+ const repo = await getRepoInfo(this.repoRoot);
2358
+ if (repo && input.worktree === false) {
2359
+ // Composer opt-out: run in the repo working tree, no branch/worktree. The
2360
+ // repository-root lease serializes these runs by default; the explicit
2361
+ // XEZ_DISABLE_REPO_LOCK=1 escape hatch allows unsafe overlap.
2362
+ // Pin the starting commit: the session's Changes and Commits views use it
2363
+ // as their stable lower bound while reading the current working copy.
2364
+ const startingCommit = await getHeadCommit(repo.root);
2365
+ if (startingCommit)
2366
+ this.store.updateRun(runId, { baseBranch: startingCommit });
2367
+ emit({ type: 'note', message: 'worktree off — running in the repo working tree' });
2368
+ }
2369
+ else if (repo) {
2370
+ emit({
2371
+ type: 'note',
2372
+ message: `worktree on — using an isolated task worktree (${input.worktree === true ? 'explicit request' : 'default'})`,
2373
+ });
2374
+ // Fork from the configured base branch (config.json `baseBranch`, e.g.
2375
+ // `develop`) — also the target of the eventual draft PR. Unresolvable
2376
+ // (typo, not fetched) → note + the currently checked-out branch.
2377
+ //
2378
+ // A task that already recorded a fork point keeps it: its worktree is
2379
+ // reused as-is, and re-resolving against a since-changed config would
2380
+ // silently re-anchor the `merge-base` every diff/shortstat is measured
2381
+ // from, shifting "what did this task change" under an existing task.
2382
+ const recorded = this.store.getRun(runId)?.baseBranch;
2383
+ let base = recorded ?? repo.branch;
2384
+ const configured = recorded ? undefined : config.baseBranch;
2385
+ if (configured) {
2386
+ const resolved = await resolveBaseRef(this.repoRoot, configured);
2387
+ if (resolved) {
2388
+ base = resolved;
2389
+ }
2390
+ else {
2391
+ emit({
2392
+ type: 'note',
2393
+ message: `configured base branch "${configured}" not found (locally or on origin) — using "${repo.branch}"`,
2394
+ });
2395
+ }
2396
+ }
2397
+ try {
2398
+ const wt = await createWorktree(this.repoRoot, runId, base);
2399
+ state.cwd = wt.path;
2400
+ this.store.updateRun(runId, {
2401
+ worktreePath: wt.path,
2402
+ branch: wt.branch,
2403
+ baseBranch: wt.baseBranch,
2404
+ });
2405
+ emit({ type: 'note', message: `worktree ready — branch ${wt.branch} (base ${wt.baseBranch})` });
2406
+ // Seed from this manager's project root: each multi-project context has
2407
+ // its own manager/repoRoot and must never copy another project's layer.
2408
+ const seededConfig = await seedAgentConfigLocalLayer(this.repoRoot, state.cwd).catch(() => []);
2409
+ if (seededConfig.length > 0) {
2410
+ emit({ type: 'note', message: `seeded personal agent config: ${seededConfig.join(', ')}` });
2411
+ }
2412
+ this.armAutosave(state);
2413
+ }
2414
+ catch (err) {
2415
+ const message = err instanceof Error ? err.message : String(err);
2416
+ const error = `worktree creation failed: ${message}`;
2417
+ emit({ type: 'note', message: `${error} — task stopped before workflow execution` });
2418
+ this.store.updateRun(runId, {
2419
+ status: 'failed',
2420
+ error,
2421
+ finishedAt: new Date().toISOString(),
2422
+ currentStepId: undefined,
2423
+ });
2424
+ emit({ type: 'lifecycle', message: `run failed — ${error}` });
2425
+ this.dropActive(runId);
2426
+ return;
2427
+ }
2428
+ }
2429
+ else {
2430
+ emit({ type: 'note', message: 'not a git repository — running in place, one task at a time' });
2431
+ }
2432
+ if (state.cwd === this.repoRoot) {
2433
+ if (repositoryRootLockDisabled()) {
2434
+ emit({
2435
+ type: 'note',
2436
+ message: REPOSITORY_ROOT_LOCK_DISABLED_NOTE,
2437
+ });
2438
+ }
2439
+ else {
2440
+ emit({
2441
+ type: 'note',
2442
+ message: 'waiting for exclusive access to the repository working tree',
2443
+ });
2444
+ // A cancel during the wait leaves the lease ungranted; the step loop
2445
+ // below breaks on `cancelled` before touching the tree and settles the
2446
+ // run through the usual path.
2447
+ await this.acquireRepoRoot(runId, state);
2448
+ }
2449
+ // THE window that matters for an in-place run. Waiting for the exclusive tree can take
2450
+ // minutes, and a run parked on that lease holds no slot (#347) — so the queue keeps
2451
+ // advancing behind it and the dequeue-time gate is long past. Measured with five in-place
2452
+ // tasks and `maxParallel: 2`: four of them started. Re-ask here, where the very next thing
2453
+ // is a spawn, and hand the run back to the queue if the account closed meanwhile. This
2454
+ // check also covers the explicit lock-bypass path, where the account may close while the
2455
+ // run is preparing its first step.
2456
+ if (this.requeueWhileHeld(runId, workflow, input, taskBackend, state))
2457
+ return;
2458
+ }
2459
+ // Handoff journal (spec 007) — seeded after the worktree exists so the
2460
+ // header can name the branch. Idempotent: an existing file stays as-is.
2461
+ const seeded = this.store.getRun(runId);
2462
+ if (seeded)
2463
+ seedHandoffFile(this.dataDir, seeded);
2464
+ const skills = await discoverSkills(this.repoRoot);
2465
+ // Every ActiveRun construction site must carry the registry — `runContinuation` builds
2466
+ // its own, and the one that skipped this leaked raw `/skill` text to the backend (#811).
2467
+ state.skills = skills;
2468
+ const retriesUsed = new Map();
2469
+ let checkFailure = null;
2470
+ let runError = null;
2471
+ // `startRun` already persisted the task's attachments so a queued bubble can render them
2472
+ // (#612). Reuse those files for the agent-facing path note instead of minting
2473
+ // duplicate pasted files when execution finally begins.
2474
+ //
2475
+ // The STACK's attachments (#472) are listed here too: they were persisted when they were
2476
+ // enqueued, and their paths are the only thing an agent ever gets for a non-image one — a
2477
+ // note that covered the initial prompt alone would hand it a task about a file it was never
2478
+ // told the path of (#950).
2479
+ const startRecord = this.store.getRun(runId);
2480
+ let startAttachments = [
2481
+ ...(startRecord?.taskImages ?? []),
2482
+ ...(startRecord?.queuedMessages ?? []).flatMap((m) => m.images ?? []),
2483
+ ]
2484
+ .map((url) => {
2485
+ const name = url.split('/').pop();
2486
+ if (!name || name.includes('..') || name.includes('/') || name.includes('\\'))
2487
+ return null;
2488
+ const path = join(this.dataDir, 'runs', `${runId}-images`, name);
2489
+ return existsSync(path) ? { name, url, path } : null;
2490
+ })
2491
+ .filter((saved) => saved !== null);
2492
+ // Task screenshots go with the FIRST agent step's opening message only —
2493
+ // later steps and retry loops run in fresh sessions without them. Stacked
2494
+ // attachments (#472) ride along too, but are NOT re-persisted above: they
2495
+ // already live on disk, and adding them to `taskImages` would both duplicate
2496
+ // the files and make the task bubble claim the stack's images as its own.
2497
+ // File blocks are dropped here — a session only ever sees viewable blocks (#950). An empty
2498
+ // result stays `undefined` rather than `[]`, so a task carrying only files hands the runner
2499
+ // seam exactly the shape a task carrying nothing always did.
2500
+ const startBlocks = contentBlocksOf([...(input.images ?? []), ...(input.stackedImages ?? [])]);
2501
+ let startImages = startBlocks.length ? startBlocks : undefined;
2502
+ const lastAgentIdx = findLastAgentStepIndex(workflow);
2503
+ let i = 0;
2504
+ while (i < workflow.steps.length) {
2505
+ if (state.cancelled)
2506
+ break;
2507
+ const step = workflow.steps[i];
2508
+ const kind = stepKind(step);
2509
+ const record = this.store.getRun(runId)?.steps.find((s) => s.id === step.id);
2510
+ const iteration = (record?.iterations ?? 0) + 1;
2511
+ this.store.updateRun(runId, { currentStepId: step.id });
2512
+ this.store.updateStep(runId, step.id, {
2513
+ status: 'running',
2514
+ iterations: iteration,
2515
+ startedAt: new Date().toISOString(),
2516
+ error: undefined,
2517
+ });
2518
+ emit({ type: 'step-start', stepId: step.id, name: step.name ?? step.id, kind, iteration });
2519
+ if (kind === 'agent') {
2520
+ // The last agent step of the workflow is interactive: after its turn
2521
+ // the session stays open for follow-ups until finish/idle/cancel.
2522
+ const interactive = i === lastAgentIdx && i === workflow.steps.length - 1;
2523
+ const failure = await this.runAgentStep(runId, state, step, input, skills, checkFailure, interactive, emit, startImages, taskBackend, extraSystemPrompt, chainStepNote(workflow.steps, i), startAttachments);
2524
+ startImages = undefined;
2525
+ startAttachments = [];
2526
+ checkFailure = null;
2527
+ if (state.cancelled)
2528
+ break;
2529
+ if (failure) {
2530
+ this.finishStep(runId, step.id, 'failed', failure, emit);
2531
+ runError = `step "${step.id}" failed: ${failure}`;
2532
+ break;
2533
+ }
2534
+ this.finishStep(runId, step.id, 'done', undefined, emit);
2535
+ i++;
2536
+ continue;
2537
+ }
2538
+ const { ok, output } = await this.runCheckStep(state, step, emit);
2539
+ if (state.cancelled)
2540
+ break;
2541
+ if (ok) {
2542
+ this.finishStep(runId, step.id, 'done', undefined, emit);
2543
+ i++;
2544
+ continue;
2545
+ }
2546
+ const used = retriesUsed.get(step.id) ?? 0;
2547
+ if (step.onFail && used < step.onFail.max) {
2548
+ retriesUsed.set(step.id, used + 1);
2549
+ checkFailure = output;
2550
+ this.finishStep(runId, step.id, 'failed', 'check failed — looping back', emit);
2551
+ const retryIdx = workflow.steps.findIndex((s) => s.id === step.onFail?.retry);
2552
+ emit({
2553
+ type: 'note',
2554
+ stepId: step.id,
2555
+ message: `check failed — retrying from "${step.onFail.retry}" (attempt ${used + 1}/${step.onFail.max})`,
2556
+ });
2557
+ // Steps we're about to re-run go back to pending so the GUI rail
2558
+ // reads top-to-bottom truthfully.
2559
+ for (const s of workflow.steps.slice(retryIdx, i + 1)) {
2560
+ this.store.updateStep(runId, s.id, { status: 'pending' });
2561
+ }
2562
+ i = retryIdx;
2563
+ continue;
2564
+ }
2565
+ this.finishStep(runId, step.id, 'failed', `\`${step.command}\` exited non-zero`, emit);
2566
+ runError = `check "${step.id}" failed${step.onFail ? ` after ${used + 1} attempts` : ''}`;
2567
+ break;
2568
+ }
2569
+ // Final autosave: the branch always ends holding the finished state.
2570
+ this.clearAutosaveTimer(state);
2571
+ if (state.cwd !== this.repoRoot)
2572
+ await autosaveCommit(state.cwd, 'run finalize');
2573
+ const finishedAt = new Date().toISOString();
2574
+ if (state.cancelled) {
2575
+ const run = this.store.getRun(runId);
2576
+ for (const s of run?.steps ?? []) {
2577
+ if (s.status === 'running' || s.status === 'waiting') {
2578
+ this.store.updateStep(runId, s.id, { status: 'cancelled' });
2579
+ }
2580
+ }
2581
+ this.store.updateRun(runId, { status: 'cancelled', finishedAt, currentStepId: undefined });
2582
+ emit({ type: 'lifecycle', message: 'run cancelled' });
2583
+ }
2584
+ else if (runError) {
2585
+ this.store.updateRun(runId, { status: 'failed', error: runError, finishedAt, currentStepId: undefined });
2586
+ emit({ type: 'lifecycle', message: `run failed — ${runError}` });
2587
+ }
2588
+ else {
2589
+ await this.settleSuccess(runId);
2590
+ }
2591
+ this.clearIdleTimer(state);
2592
+ this.dropActive(runId);
2593
+ }
2594
+ /** Returns an error message, or null on success. */
2595
+ async runAgentStep(runId, state, step, input, skills, checkFailure, interactive, emit, images, taskBackend, extraSystemPrompt,
2596
+ /** The chain-boundary note for this step (#410), or undefined when the
2597
+ * workflow has a single agent step and there is no boundary to explain. */
2598
+ chainNote,
2599
+ /** Pasted attachments already materialized to disk (#357) — their absolute
2600
+ * paths are appended to `userPrompt` so the agent can operate on the
2601
+ * real files, not just view the inline image blocks. */
2602
+ attachments = []) {
2603
+ let systemPrompt;
2604
+ if (step.skill) {
2605
+ const skill = skills.find((s) => s.name === step.skill);
2606
+ if (skill) {
2607
+ // The body alone often does not identify the selected skill. Keep its
2608
+ // name and catalog description in the normalized runner payload so a
2609
+ // numeric task such as "432" still gives the model enough context to
2610
+ // describe the work — and therefore derive a useful title (#432).
2611
+ systemPrompt = skillSystemPrompt(skill);
2612
+ // Directory team skills (SKILL.md + references/) get materialized
2613
+ // into <cwd>/.claude/skills/<name>/ — the run's worktree when there
2614
+ // is one — so claude sees the companion files on disk; the shared
2615
+ // info/exclude keeps them out of git (and out of autosave commits).
2616
+ if (skill.source === 'team' && skill.team?.dir) {
2617
+ const seeded = await materializeSkillDir(state.cwd, skill).catch(() => false);
2618
+ if (seeded) {
2619
+ emit({
2620
+ type: 'note',
2621
+ stepId: step.id,
2622
+ message: `team skill "${skill.name}" materialized to .claude/skills/${skill.name}/`,
2623
+ });
2624
+ }
2625
+ }
2626
+ }
2627
+ else {
2628
+ emit({
2629
+ type: 'note',
2630
+ stepId: step.id,
2631
+ message: `skill "${step.skill}" not found in .ai/xezar/skills, .ai/skills or the team skills repo — running with the plain prompt`,
2632
+ });
2633
+ }
2634
+ }
2635
+ let userPrompt = applyTemplate(step.prompt ?? '{{task}}', input.task);
2636
+ // A fresh run's OPENING prompt is delivered straight to `startSession`, never through
2637
+ // `deliverMessage`, so — like the continuation seam above (#811) — it needs the same
2638
+ // delivery-only `/skill` rewrite. Without it a task STARTED with `/om-...` as its first
2639
+ // message leaks the raw slash to the backend, which answers "Unknown command" even though
2640
+ // Xezar lists the skill (#278). `state.skills` was populated by `discoverSkills` earlier in
2641
+ // `execute`. Expand before the chain/check/attachment prefixes so the leading slash still
2642
+ // matches; a leading `/name` that is not a known skill passes through byte-for-byte.
2643
+ userPrompt = expandRegistrySlashSkillText(userPrompt, state.skills ?? []);
2644
+ if (chainNote)
2645
+ userPrompt = `${chainNote}\n\n---\n\n${userPrompt}`;
2646
+ if (checkFailure) {
2647
+ userPrompt += `\n\nA verification command failed after the previous attempt. Fix the cause. Failing output:\n\n${checkFailure}`;
2648
+ }
2649
+ if (images?.length) {
2650
+ emit({
2651
+ type: 'note',
2652
+ stepId: step.id,
2653
+ message: `${images.length} screenshot${images.length > 1 ? 's' : ''} attached to the task`,
2654
+ });
2655
+ }
2656
+ // Point the agent at the on-disk files (#357) — for an image the base64 block above already
2657
+ // let it *view* the file and this is what lets it *use* it (save, attach to an issue/PR, copy
2658
+ // into the repo); for a non-image attachment (#950) it is the only reference the agent gets
2659
+ // at all. Deliberately NOT nested in the branch above: gating the paths on an image block
2660
+ // existing is what would leave an agent holding a task about a `.pdf` it was never told the
2661
+ // location of.
2662
+ if (attachments.length)
2663
+ userPrompt += `\n\n${pastedAttachmentsText(attachments)}`;
2664
+ const sessionId = randomUUID();
2665
+ const backend = step.runner ?? taskBackend;
2666
+ this.store.updateStep(runId, step.id, { sessionId, backend });
2667
+ const stepRecord = this.store.getRun(runId)?.steps.find((s) => s.id === step.id);
2668
+ const startTokens = stepRecord?.tokensUsed ?? 0;
2669
+ let stepCost = stepRecord?.costUsd ?? 0;
2670
+ let turnText = '';
2671
+ let sessionError;
2672
+ const sink = this.makeUiSink(runId, step.id);
2673
+ const onEvent = (event) => {
2674
+ if (event.type === 'image') {
2675
+ const saved = this.persistAttachment(runId, event.mediaType, event.data);
2676
+ if (saved)
2677
+ emit({ type: 'image', stepId: step.id, ...saved });
2678
+ return;
2679
+ }
2680
+ if (event.type === 'text') {
2681
+ turnText = appendTurnText(turnText, event.text);
2682
+ const text = stripAskMarker(stripTaskMarkers(stripMonitoringMarker(stripDoneMarker(event.text))));
2683
+ if (text)
2684
+ emit({ type: 'text', text, stepId: step.id });
2685
+ return;
2686
+ }
2687
+ emit({ ...event, stepId: step.id });
2688
+ if (event.type === 'error') {
2689
+ sessionError ??= event.message;
2690
+ state.session?.interrupt();
2691
+ return;
2692
+ }
2693
+ if (sessionError)
2694
+ return;
2695
+ if (event.type === 'session') {
2696
+ // Codex/OpenCode mint their own session id — persist it so resume works.
2697
+ this.store.updateStep(runId, step.id, { sessionId: event.sessionId, backend });
2698
+ }
2699
+ if (event.type === 'token-usage') {
2700
+ this.store.updateStep(runId, step.id, { tokensUsed: startTokens + event.tokensUsed });
2701
+ }
2702
+ if (event.type === 'cost') {
2703
+ stepCost += event.usd;
2704
+ this.store.updateStep(runId, step.id, { costUsd: stepCost });
2705
+ }
2706
+ if (event.type === 'turn-end') {
2707
+ // v2 `turn.completed` already flushed the coalescers; the v1 turn
2708
+ // boundary flushes again (idempotent) as a backstop.
2709
+ sink.flushAll();
2710
+ void this.recordTurnEnd(runId, turnText); // titleSummary + diffStat (#389)
2711
+ const sessionOpen = !state.cancelled && state.session?.open;
2712
+ const done = interactive && sessionOpen && DONE_MARKER_RE.test(turnText.trimEnd());
2713
+ // `XEZ:ASK` → the user is blocked; wins over `XEZ:MONITORING`, loses to
2714
+ // `XEZ:DONE` (#473).
2715
+ const { ask, notes: askNotes } = resolveAskTurn(turnText, Boolean(interactive && sessionOpen) && !done);
2716
+ const monitoring = interactive &&
2717
+ sessionOpen &&
2718
+ !done &&
2719
+ !ask &&
2720
+ MONITORING_MARKER_RE.test(turnText.trimEnd());
2721
+ turnText = '';
2722
+ for (const note of askNotes)
2723
+ emit({ type: 'note', stepId: step.id, ...note });
2724
+ if (done) {
2725
+ // Goal achieved (agent contract, #347): close the session instead
2726
+ // of parking at `waiting` — the run completes and frees its slot.
2727
+ emit({ type: 'lifecycle', message: 'goal achieved — session closed' });
2728
+ appendHandoffHeartbeat(this.dataDir, runId, 'turn complete — goal achieved, session closed');
2729
+ state.session?.end();
2730
+ return;
2731
+ }
2732
+ const waiting = interactive && sessionOpen;
2733
+ if (waiting) {
2734
+ // Turn over, session open. Either the ball is in the user's court
2735
+ // (`waiting`) — optionally with a structured `XEZ:ASK` question the
2736
+ // cockpit renders as an ask card (#473) — or the agent declared it is
2737
+ // still working on its own downstream work with `XEZ:MONITORING`, which
2738
+ // parks as `running`/`activity:'monitoring'`, a non-attention state,
2739
+ // instead of raising "needs you" (#490). Lifecycle is identical: the
2740
+ // run frees its slot and keeps the idle timer.
2741
+ if (ask)
2742
+ emitAskRequested(sink, ask);
2743
+ if (monitoring) {
2744
+ this.store.updateRun(runId, { status: 'running', activity: 'monitoring' });
2745
+ this.store.updateStep(runId, step.id, { status: 'running' });
2746
+ this.monitoring.add(runId);
2747
+ this.clearIdleTimer(state);
2748
+ this.armMonitoringWakeTimer(runId, state);
2749
+ }
2750
+ else {
2751
+ this.store.updateRun(runId, { status: 'waiting', activity: undefined });
2752
+ this.store.updateStep(runId, step.id, { status: 'waiting' });
2753
+ this.monitoring.delete(runId);
2754
+ this.clearMonitoringWakeTimer(state, runId);
2755
+ }
2756
+ this.waiting.add(runId);
2757
+ if (!monitoring)
2758
+ this.armIdleTimer(runId, state);
2759
+ this.releaseSlot(); // the freed slot can start a queued run right away — in any project
2760
+ }
2761
+ // The window is proven open — see the twin in `runContinuation`.
2762
+ if (this.store.getRun(runId)?.autoResumeAttempts !== undefined) {
2763
+ this.store.updateRun(runId, { autoResumeAttempts: undefined });
2764
+ }
2765
+ // Xez's own heartbeat — the handoff stays current even when the
2766
+ // agent forgets to write (spec 007).
2767
+ appendHandoffHeartbeat(this.dataDir, runId, `turn complete — status=${monitoring ? 'monitoring' : waiting ? 'waiting' : 'running'}`);
2768
+ }
2769
+ };
2770
+ const stepBackend = step.runner ?? taskBackend;
2771
+ // Normalise the selected model to canonical `provider/model` and back to the
2772
+ // backend's own wire form via the ONE shared mapper (#405). Fail-loud: an
2773
+ // unresolvable model (e.g. a bare id on opencode) returns the step error
2774
+ // instead of letting the backend silently substitute its default.
2775
+ let backendModel;
2776
+ try {
2777
+ const normalized = normalizeModelForBackend(stepBackend, agentModelsLocked(this.repoRoot) ? undefined : step.model ?? input.model, { configuredProvider: await configuredModelProvider(stepBackend, state.cwd) });
2778
+ backendModel = normalized?.backendModel;
2779
+ // Persist the identity of what ACTUALLY runs (#405, review M1). The run-start echo
2780
+ // (line ~993) is best-effort from `taskBackend`/`input.model`; a per-step `runner`/`model`
2781
+ // override makes it assert a model that never ran. Re-write it here, from the resolved
2782
+ // step identity, so the record — the product of this PR — is always one that ran.
2783
+ this.store.updateRun(runId, {
2784
+ modelIdentity: normalized ? formatModelIdentity(normalized.identity) : undefined,
2785
+ });
2786
+ }
2787
+ catch (err) {
2788
+ if (err instanceof ModelIdentityError)
2789
+ return err.message;
2790
+ throw err;
2791
+ }
2792
+ // Which agent account this step spawns under, and — recorded on the step before the spawn —
2793
+ // which one its session belongs to. `sessionId` and `profileId` are a pair: a resume that
2794
+ // reads the wrong account's config dir finds no session and silently starts a fresh one.
2795
+ // Resolved together with the temp-directory preflight (#785): the step fails with a named,
2796
+ // actionable error instead of spawning a backend whose shell would return empty output.
2797
+ let stepProfile;
2798
+ try {
2799
+ stepProfile = await this.agentEnvForStep(runId, stepBackend, {
2800
+ generateFollowups: followupsEnabled() && input.generateFollowups !== false,
2801
+ });
2802
+ }
2803
+ catch (err) {
2804
+ if (err instanceof AgentTempDirError)
2805
+ return err.message;
2806
+ throw err;
2807
+ }
2808
+ this.store.updateStep(runId, step.id, { profileId: stepProfile.profileId });
2809
+ const runner = createRunner(stepBackend);
2810
+ let session;
2811
+ state.currentStepId = step.id;
2812
+ this.beginUsageInvocation(runId, state, step.id);
2813
+ try {
2814
+ session = runner.startSession({
2815
+ // Skill body, then the run's extra prompt (POST override or config
2816
+ // default), then the handoff/todos contract — every agent step.
2817
+ systemPrompt: composeSystemPrompt(systemPrompt, extraSystemPrompt, followupsEnabled() && input.generateFollowups !== false
2818
+ ? HANDOFF_INSTRUCTIONS
2819
+ : HANDOFF_ONLY_INSTRUCTIONS),
2820
+ userPrompt,
2821
+ images,
2822
+ cwd: state.cwd,
2823
+ allowedTools: step.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
2824
+ bashAllowlist: step.bashAllowlist,
2825
+ // The handoff file lives outside the worktree — grant access.
2826
+ additionalDirectories: agentDirectories(join(this.dataDir, 'runs'), stepProfile.env),
2827
+ env: stepProfile.env,
2828
+ model: backendModel,
2829
+ sessionId,
2830
+ // Interactive sessions have no wall clock — the idle timer rules.
2831
+ timeoutMs: interactive ? 0 : undefined,
2832
+ }, onEvent, {
2833
+ autoEndAfterFirstTurn: !interactive,
2834
+ onUiEvent: (event) => this.handleRunnerUiEvent(runId, state, sink, event),
2835
+ });
2836
+ }
2837
+ catch (err) {
2838
+ state.currentStepId = undefined;
2839
+ return err instanceof Error ? err.message : String(err);
2840
+ }
2841
+ state.session = session;
2842
+ state.sessionEverOpened = true;
2843
+ this.flushDeferred(runId);
2844
+ state.currentStepId = step.id;
2845
+ state.interrupt = () => session.interrupt();
2846
+ if (session.pid !== undefined)
2847
+ registerRunProcess(runId, session.pid);
2848
+ try {
2849
+ const result = await session.result;
2850
+ if (sessionError) {
2851
+ sink.sessionEnded('error', sessionError);
2852
+ return sessionError;
2853
+ }
2854
+ // v2 counterpart of v1's `done` (spec: the mappers leave session-close
2855
+ // events to the RunManager — only it knows how the session settled).
2856
+ sink.sessionEnded(state.cancelled ? 'cancelled' : 'end_turn');
2857
+ this.store.updateStep(runId, step.id, { tokensUsed: startTokens + result.tokensUsed });
2858
+ return null;
2859
+ }
2860
+ catch (err) {
2861
+ const message = err instanceof Error ? err.message : String(err);
2862
+ sink.sessionEnded('error', message); // alongside v1's fatal `error`
2863
+ return message;
2864
+ }
2865
+ finally {
2866
+ this.recordUsagePeaks(runId);
2867
+ this.clearIdleTimer(state);
2868
+ this.monitoring.delete(runId);
2869
+ this.waiting.delete(runId);
2870
+ this.clearMonitoringWakeTimer(state, runId);
2871
+ state.session = undefined;
2872
+ state.currentStepId = undefined;
2873
+ state.interrupt = () => undefined;
2874
+ }
2875
+ }
2876
+ /**
2877
+ * Protocol-v2 sink for one agent session (R2 step 2.1): the runner's
2878
+ * `onUiEvent` stream flows through here. Persisted snapshots ride the same
2879
+ * NDJSON file as v1 (the store stamps `seq`/`ts`, `appendEvent` fans them
2880
+ * out live too); coalesced `item.delta` flushes go out live-only via
2881
+ * `emitEphemeral` — raw deltas never hit disk (spec §performance
2882
+ * guardrails). One sink per session: cumulative usage dedup and the
2883
+ * item-shape cache are session-scoped, like the mapper state feeding them.
2884
+ */
2885
+ makeUiSink(runId, stepId) {
2886
+ return new UiEventSink({
2887
+ persist: (event) => this.store.appendEvent(runId, { ...event, stepId }),
2888
+ emitLive: (event) => this.store.emitEphemeral(runId, { ...event, stepId }),
2889
+ });
2890
+ }
2891
+ /** Native backend asks arrive before turn-end. Persist and park immediately
2892
+ * so the cockpit shows attention and the run releases its workspace slot. */
2893
+ handleRunnerUiEvent(runId, state, sink, event) {
2894
+ this.recordUsageUiEvent(runId, state, event);
2895
+ sink.handle(event);
2896
+ if (event.type !== 'ask.requested' || state.cancelled)
2897
+ return;
2898
+ this.clearIdleTimer(state);
2899
+ this.monitoring.delete(runId);
2900
+ this.clearMonitoringWakeTimer(state, runId);
2901
+ this.waiting.add(runId);
2902
+ this.store.updateRun(runId, { status: 'waiting', activity: undefined });
2903
+ if (state.currentStepId)
2904
+ this.store.updateStep(runId, state.currentStepId, { status: 'waiting' });
2905
+ this.releaseSlot();
2906
+ }
2907
+ /** Persist the invocation checkpoint before launching a runner. A throw or
2908
+ * process exit before `turn.started` therefore leaves a durable mismatch. */
2909
+ beginUsageInvocation(runId, state, stepId) {
2910
+ const step = this.store.getRun(runId)?.steps.find((candidate) => candidate.id === stepId);
2911
+ if (!step)
2912
+ return;
2913
+ const epoch = (step.usageInvocationEpoch ?? 0) + 1;
2914
+ this.persistUsageCheckpoint(runId, stepId, {
2915
+ usageInvocationEpoch: epoch,
2916
+ usageInvocationsStarted: (step.usageInvocationsStarted ?? 0) + 1,
2917
+ });
2918
+ state.usageInvocation = {
2919
+ stepId,
2920
+ epoch,
2921
+ observed: false,
2922
+ startedTurns: new Set(),
2923
+ recordedTurns: new Set(),
2924
+ };
2925
+ }
2926
+ /** Fold backend-neutral completed-turn usage into the current step exactly
2927
+ * once. Invocation/turn counters are written before the event reaches the
2928
+ * NDJSON sink so crashes cannot preserve a falsely complete subtotal. */
2929
+ recordUsageUiEvent(runId, state, event) {
2930
+ const invocation = state.usageInvocation;
2931
+ if (!invocation)
2932
+ return;
2933
+ const step = this.store.getRun(runId)?.steps.find((candidate) => candidate.id === invocation.stepId);
2934
+ if (!step)
2935
+ return;
2936
+ if (event.type === 'turn.started') {
2937
+ if (invocation.startedTurns.has(event.turnId))
2938
+ return;
2939
+ invocation.startedTurns.add(event.turnId);
2940
+ const firstObservedTurn = !invocation.observed;
2941
+ invocation.observed = true;
2942
+ this.persistUsageCheckpoint(runId, invocation.stepId, {
2943
+ usageTurnsStarted: (step.usageTurnsStarted ?? 0) + 1,
2944
+ ...(firstObservedTurn
2945
+ ? { usageInvocationsObserved: (step.usageInvocationsObserved ?? 0) + 1 }
2946
+ : {}),
2947
+ });
2948
+ return;
2949
+ }
2950
+ if (event.type !== 'turn.completed')
2951
+ return;
2952
+ if (!invocation.startedTurns.has(event.turnId) || invocation.recordedTurns.has(event.turnId))
2953
+ return;
2954
+ const input = event.usage?.input;
2955
+ const output = event.usage?.output;
2956
+ if (typeof input !== 'number' ||
2957
+ !Number.isFinite(input) ||
2958
+ input < 0 ||
2959
+ typeof output !== 'number' ||
2960
+ !Number.isFinite(output) ||
2961
+ output < 0) {
2962
+ return;
2963
+ }
2964
+ invocation.recordedTurns.add(event.turnId);
2965
+ this.persistUsageCheckpoint(runId, invocation.stepId, {
2966
+ inputTokens: (step.inputTokens ?? 0) + input,
2967
+ outputTokens: (step.outputTokens ?? 0) + output,
2968
+ usageTurnsRecorded: (step.usageTurnsRecorded ?? 0) + 1,
2969
+ });
2970
+ }
2971
+ /** Usage completeness is a crash boundary, unlike high-frequency token
2972
+ * snapshots: the checkpoint must reach `runs.json` before the runner starts
2973
+ * or the matching UI event is persisted and forwarded. */
2974
+ persistUsageCheckpoint(runId, stepId, patch) {
2975
+ this.store.updateStep(runId, stepId, patch);
2976
+ this.store.flush();
2977
+ }
2978
+ /**
2979
+ * Turn-end bookkeeping (#389), shared by `runAgentStep` and
2980
+ * `runContinuation` — called (fire-and-forget) from every `turn-end` event:
2981
+ *
2982
+ * - `titleSummary`: derived from the turn's text, set ONCE — only while the
2983
+ * record has none. A user's inline edit also lands in `titleSummary`
2984
+ * (see `PATCH /api/runs/:id`), so an edit is never overwritten either.
2985
+ * - `diffStat`: cheap `git diff --shortstat` vs the base, refreshed every
2986
+ * turn. Async and best-effort — a git failure becomes at most a `note`
2987
+ * event, NEVER a run failure. `updateRun` fans the record out over SSE,
2988
+ * so the list views pick both up with no extra wiring.
2989
+ *
2990
+ * Not `private` so the integration tests can drive a turn-end directly —
2991
+ * a real agent session is the only other way to reach this path.
2992
+ */
2993
+ /**
2994
+ * The namer's apply path (task auto-naming spec). Fire-and-forget: called
2995
+ * without await from `startRun` (creation) and `recordTurnEnd` (live
2996
+ * refresh). A user-owned title (`titleOrigin: 'user'`) is never overwritten;
2997
+ * namer-owned titles may be replaced by fresher namer results.
2998
+ */
2999
+ async autoNameRun(runId, skillName, task, live) {
3000
+ // XEZ_AUTONAME=0 kills all LLM naming; dry-run skips it too unless
3001
+ // XEZ_AUTONAME=1 forces the mock path — see autoNamingActive.
3002
+ if (!autoNamingActive())
3003
+ return;
3004
+ try {
3005
+ let skillDescription;
3006
+ if (skillName) {
3007
+ const skills = await discoverSkills(this.repoRoot).catch(() => []);
3008
+ skillDescription = skills.find((s) => s.name === skillName)?.description;
3009
+ }
3010
+ const result = await generateRunName(this.repoRoot, { task, skillName, skillDescription, ...live });
3011
+ if (!result)
3012
+ return;
3013
+ const run = this.store.getRun(runId);
3014
+ // Marker-owned state outranks the namer (spec 2026-07-18-task-ref-markers):
3015
+ // a declared title blocks the whole apply (this call raced the marker),
3016
+ // and a declared pr/issue kind blocks that kind field-by-field.
3017
+ if (!run || run.titleOrigin === 'user' || run.titleOrigin === 'marker')
3018
+ return;
3019
+ this.store.updateRun(runId, {
3020
+ titleSummary: result.titleSummary,
3021
+ titleOrigin: 'auto',
3022
+ ...(result.prNumber !== undefined && run.markerRefs?.pr === undefined
3023
+ ? { prNumber: result.prNumber }
3024
+ : {}),
3025
+ ...(result.issueNumber !== undefined && run.markerRefs?.issue === undefined
3026
+ ? { issueNumber: result.issueNumber }
3027
+ : {}),
3028
+ });
3029
+ }
3030
+ catch {
3031
+ // Naming is best-effort — nothing here may disturb the run.
3032
+ }
3033
+ }
3034
+ async recordTurnEnd(runId, turnText) {
3035
+ try {
3036
+ const run = this.store.getRun(runId);
3037
+ if (!run)
3038
+ return;
3039
+ this.applyTurnMarkers(runId, run, turnText);
3040
+ // Titles are the namer's job (task auto-naming spec) — turn text is
3041
+ // deliberately NEVER a title source; see maybeRefreshTitle below. The
3042
+ // one exception is an explicit XEZ:TITLE declaration (applied above).
3043
+ if (run.worktreePath && existsSync(run.worktreePath)) {
3044
+ // `taskBranch` + `runStartedAt` are what keep this number *this task's* (#751): a
3045
+ // review/QA run repoints the worktree onto the branch under review, and without the
3046
+ // branch to compare HEAD against and the moment it was checked out, the stat would
3047
+ // claim that whole branch's diff.
3048
+ const stat = await worktreeShortstat(run.worktreePath, run.baseBranch ?? 'HEAD', {
3049
+ taskBranch: run.branch,
3050
+ runStartedAt: run.startedAt,
3051
+ });
3052
+ if (stat)
3053
+ this.store.updateRun(runId, { diffStat: stat });
3054
+ else
3055
+ this.store.appendEvent(runId, { type: 'note', message: 'diff stat unavailable — git diff --shortstat failed in the worktree' });
3056
+ }
3057
+ await this.maybeRefreshTitle(runId, turnText);
3058
+ }
3059
+ catch {
3060
+ // Bookkeeping only — nothing here may disturb the run.
3061
+ }
3062
+ }
3063
+ /**
3064
+ * In-band declarations from the finished turn (spec
3065
+ * 2026-07-18-task-ref-markers): the main thread's own `XEZ:PR=` /
3066
+ * `XEZ:ISSUE=` / `XEZ:TITLE=` lines, parsed from the accumulated turn text
3067
+ * like `XEZ:DONE` — never from tool output. Declared numbers overwrite the
3068
+ * regex/namer display tier (the store re-resolves the referenced-PR chip);
3069
+ * a declared title takes `titleOrigin: 'marker'`, which beats the namer but
3070
+ * never a user rename, and silences the live refresh below.
3071
+ */
3072
+ applyTurnMarkers(runId, run, turnText) {
3073
+ const markers = parseTaskMarkers(turnText);
3074
+ if (markers.pr !== undefined || markers.issue !== undefined) {
3075
+ this.store.applyMarkerRefs(runId, { pr: markers.pr, issue: markers.issue });
3076
+ }
3077
+ if (markers.title && run.titleOrigin !== 'user') {
3078
+ const current = this.store.getRun(runId);
3079
+ const refNumber = current?.prNumber ?? current?.issueNumber;
3080
+ const validated = postValidateTitle(markers.title, refNumber);
3081
+ // Same junk guard as composeNameResult: a declaration that validates to
3082
+ // nothing (or to a bare number prefix) must not blank the title.
3083
+ if (validated && validated !== `${refNumber}:`) {
3084
+ this.store.updateRun(runId, { titleSummary: validated, titleOrigin: 'marker' });
3085
+ }
3086
+ }
3087
+ }
3088
+ /**
3089
+ * Live title refresh (task auto-naming spec, step 3): re-run the namer with
3090
+ * the turn's context. Skips: toggle off (`liveTitleUpdates` config over
3091
+ * `XEZ_TITLE_UPDATES` env, default ON), user-owned title, marker-owned title
3092
+ * (the agent declares via `XEZ:TITLE` — the token-saving fast path), dry-run
3093
+ * mocks (canned answers add nothing), empty turn text, unchanged namer inputs.
3094
+ */
3095
+ async maybeRefreshTitle(runId, turnText) {
3096
+ if (!autoNamingActive())
3097
+ return;
3098
+ if (!turnText.trim())
3099
+ return;
3100
+ const config = await loadConfig(this.repoRoot);
3101
+ if (!liveTitleUpdatesEnabled(config))
3102
+ return;
3103
+ const run = this.store.getRun(runId);
3104
+ if (!run || run.titleOrigin === 'user' || run.titleOrigin === 'marker')
3105
+ return;
3106
+ const statText = run.diffStat ? `${run.diffStat.files} files, +${run.diffStat.adds} -${run.diffStat.dels}` : undefined;
3107
+ const key = `${turnText.slice(0, 200)}|${statText ?? ''}`;
3108
+ if (this.lastNamerKey.get(runId) === key)
3109
+ return;
3110
+ this.lastNamerKey.set(runId, key);
3111
+ const workflow = await this.reviveWorkflow(run);
3112
+ const skillName = workflow?.steps.find((s) => stepKind(s) === 'agent' && s.skill)?.skill?.trim();
3113
+ void this.autoNameRun(runId, skillName, run.task, { turnText, diffStat: statText });
3114
+ }
3115
+ /**
3116
+ * End-of-session telemetry (#348): stop sampling the run's process tree and
3117
+ * fold the session's peaks into the run record. `max` with existing values —
3118
+ * a run can hold several sessions (multiple agent steps, Continue) and the
3119
+ * record keeps the highest water mark across all of them.
3120
+ */
3121
+ recordUsagePeaks(runId) {
3122
+ const peaks = unregisterRunProcess(runId);
3123
+ if (!peaks)
3124
+ return;
3125
+ const run = this.store.getRun(runId);
3126
+ this.store.updateRun(runId, {
3127
+ peakRssBytes: Math.max(run?.peakRssBytes ?? 0, peaks.peakRssBytes),
3128
+ peakProcCount: Math.max(run?.peakProcCount ?? 0, peaks.peakProcCount),
3129
+ });
3130
+ }
3131
+ /**
3132
+ * Diff-first review gate (spec 009), shared by `execute` and
3133
+ * `runContinuation`: a *successful* run whose worktree holds changes rests
3134
+ * at `review` instead of `done` — the user inspects the diff first, then
3135
+ * sends feedback back, opens a draft PR, or just finishes. Failed/cancelled
3136
+ * runs never enter review; no worktree or an empty diff means plain `done`.
3137
+ *
3138
+ * The gate is opt-in (#489): the review park happens only when it is enabled
3139
+ * (`reviewGateEnabled` — config toggle over the `XEZ_REVIEW_GATE` env, default
3140
+ * OFF) AND the run is not autonomous. Autonomous runs — and runs with the gate
3141
+ * off — settle straight to `done`, leaving the diff in the worktree untouched.
3142
+ */
3143
+ async settleSuccess(runId) {
3144
+ const run = this.store.getRun(runId);
3145
+ let review = false;
3146
+ if (run?.worktreePath && existsSync(run.worktreePath)) {
3147
+ const diff = await worktreeDiff(run.worktreePath, run.baseBranch ?? 'HEAD');
3148
+ const hasDiff = diff.trim().length > 0 && !diff.startsWith('(diff failed');
3149
+ const config = await loadConfig(this.repoRoot);
3150
+ review = hasDiff && reviewGateEnabled(config) && run.autonomous !== true;
3151
+ }
3152
+ this.store.updateRun(runId, {
3153
+ status: review ? 'review' : 'done',
3154
+ finishedAt: new Date().toISOString(),
3155
+ currentStepId: undefined,
3156
+ // A run that got all the way to a settled turn is not in a limit loop, so the resume
3157
+ // counter starts over — otherwise a task that legitimately met the limit once a week would
3158
+ // creep toward the cap forever and stop resuming for no reason anyone could see.
3159
+ autoResumeAttempts: undefined,
3160
+ });
3161
+ this.store.appendEvent(runId, {
3162
+ type: 'lifecycle',
3163
+ message: review
3164
+ ? 'changes ready for review — send feedback, open a draft PR, or finish'
3165
+ : 'run finished',
3166
+ });
3167
+ }
3168
+ /**
3169
+ * Persist every attachment a user message carries — images and files alike (#950) — into the
3170
+ * run's own attachment folder, in the order they were attached. The returned paths are what the
3171
+ * agent is told about; the caller decides which of them also ride along as viewable blocks.
3172
+ */
3173
+ persistPastedAttachments(runId, content) {
3174
+ return content
3175
+ .map((b) => b.type === 'image'
3176
+ ? this.persistAttachment(runId, b.source.media_type, b.source.data, 'pasted')
3177
+ : b.type === 'file'
3178
+ ? this.persistAttachment(runId, b.mediaType, b.data, 'pasted')
3179
+ : null)
3180
+ .filter((saved) => saved !== null);
3181
+ }
3182
+ /**
3183
+ * Agent screenshot (an image block inside a tool result) or a user attachment —
3184
+ * a pasted screenshot, or since #950 a PDF/TXT/MD file: the base64 data never
3185
+ * enters the NDJSON event log — it lands as a file under
3186
+ * `.ai/xezar/runs/<id>-images/` and the transcript event carries only the name +
3187
+ * serving URL. `namePrefix` distinguishes the two origins on disk
3188
+ * (`screenshot-<n>.<ext>` for agent tool screenshots, `pasted-<n>.<ext>` for user
3189
+ * attachments, #357) and the absolute `path` lets the agent operate on the file
3190
+ * directly (save/attach/upload) — for a non-image attachment that path is the ONLY
3191
+ * way it ever reaches the agent.
3192
+ * Best effort: on failure the attachment is dropped, the transcript still
3193
+ * shows the tool result's `[screenshot]` placeholder (or the image count).
3194
+ */
3195
+ persistAttachment(runId, mediaType, data, namePrefix = 'screenshot') {
3196
+ try {
3197
+ // One mapping, shared with the wire (`packages/contract`): an image keeps the extension it
3198
+ // always had, a file gets `pdf`/`txt`/`md`, and both share the `pasted-<n>` numbering space
3199
+ // below so a `pasted-3.md` can never collide with a `pasted-3.png`.
3200
+ const ext = attachmentExtension(mediaType);
3201
+ const dir = join(this.dataDir, 'runs', `${runId}-images`);
3202
+ mkdirSync(dir, { recursive: true });
3203
+ // Seed from the highest numeric suffix already on disk, NOT the file count:
3204
+ // `screenshot-*` and `pasted-*` share one numbering space, so counting would
3205
+ // re-issue a live number after any deletion. Only matters on the first write
3206
+ // of a process (restart case) — afterwards the map is authoritative.
3207
+ let seq = this.queuedImageSeq.get(runId);
3208
+ if (seq === undefined)
3209
+ seq = highestImageSeq(dir);
3210
+ // `persistAttachment` is fully synchronous, so two pastes cannot interleave between
3211
+ // the read of the counter and the write. The exclusive-create flag is the
3212
+ // belt-and-braces guard for a stale seed: it degrades to a renamed file rather
3213
+ // than a silent overwrite.
3214
+ for (let attempt = 0; attempt < 100; attempt += 1) {
3215
+ seq += 1;
3216
+ const name = `${namePrefix}-${seq}.${ext}`;
3217
+ const path = join(dir, name);
3218
+ try {
3219
+ writeFileSync(path, Buffer.from(data, 'base64'), { flag: 'wx' });
3220
+ }
3221
+ catch (err) {
3222
+ if (err.code === 'EEXIST')
3223
+ continue;
3224
+ throw err;
3225
+ }
3226
+ this.queuedImageSeq.set(runId, seq);
3227
+ // Versioned, because that is the only surface served now. The cockpit still upgrades
3228
+ // the unversioned URLs sitting in OLD transcripts when it renders them
3229
+ // (`resolveApiUrl`), but a URL minted today must be fetchable as written.
3230
+ return { name, url: `/api/v1/runs/${runId}/images/${name}`, path };
3231
+ }
3232
+ return null;
3233
+ }
3234
+ catch {
3235
+ return null;
3236
+ }
3237
+ }
3238
+ armIdleTimer(runId, state) {
3239
+ this.clearIdleTimer(state);
3240
+ state.idleTimer = setTimeout(() => {
3241
+ if (state.session?.open && !state.cancelled) {
3242
+ this.store.appendEvent(runId, {
3243
+ type: 'lifecycle',
3244
+ message: `session closed after ${Math.round(IDLE_TIMEOUT_MS / 60_000)}m of inactivity`,
3245
+ });
3246
+ state.session.end();
3247
+ }
3248
+ }, IDLE_TIMEOUT_MS);
3249
+ state.idleTimer.unref?.();
3250
+ }
3251
+ clearIdleTimer(state) {
3252
+ if (state.idleTimer) {
3253
+ clearTimeout(state.idleTimer);
3254
+ state.idleTimer = undefined;
3255
+ }
3256
+ }
3257
+ reconcileMonitoringWakeTimers() {
3258
+ for (const runId of this.monitoring) {
3259
+ const state = this.active.get(runId);
3260
+ if (state)
3261
+ this.armMonitoringWakeTimer(runId, state);
3262
+ }
3263
+ }
3264
+ armMonitoringWakeTimer(runId, state) {
3265
+ const minutes = this.semaphore.monitoringWakeIntervalMinutes();
3266
+ if (minutes === null) {
3267
+ this.clearMonitoringWakeTimer(state, runId);
3268
+ return;
3269
+ }
3270
+ if ((state.monitoringWakeups ?? 0) >= MAX_AUTO_CONTINUES) {
3271
+ this.clearMonitoringWakeTimer(state, runId);
3272
+ if (!this.store.getRun(runId)?.monitoringWakeCapReached) {
3273
+ this.store.updateRun(runId, { monitoringWakeCapReached: true });
3274
+ this.store.appendEvent(runId, {
3275
+ type: 'note',
3276
+ message: `automatic monitoring wake-up cap reached (${MAX_AUTO_CONTINUES}); session remains parked`,
3277
+ });
3278
+ }
3279
+ return;
3280
+ }
3281
+ if (state.monitoringWakeTimer && state.monitoringWakeIntervalMinutes === minutes)
3282
+ return;
3283
+ this.clearMonitoringWakeTimer(state, runId);
3284
+ state.monitoringWakeIntervalMinutes = minutes;
3285
+ this.store.updateRun(runId, { monitoringWakeCapReached: undefined });
3286
+ const deadline = Date.now() + minutes * 60_000;
3287
+ this.store.updateRun(runId, { monitoringWakeAt: new Date(deadline).toISOString() });
3288
+ state.monitoringWakeTimer = setTimeout(() => {
3289
+ state.monitoringWakeTimer = undefined;
3290
+ this.store.updateRun(runId, { monitoringWakeAt: undefined });
3291
+ if (!this.monitoring.has(runId) || !state.session?.open || state.cancelled)
3292
+ return;
3293
+ const wakeups = state.monitoringWakeups ?? 0;
3294
+ if (wakeups >= MAX_AUTO_CONTINUES) {
3295
+ this.store.updateRun(runId, { monitoringWakeCapReached: true });
3296
+ this.store.appendEvent(runId, {
3297
+ type: 'note',
3298
+ message: `automatic monitoring wake-up cap reached (${MAX_AUTO_CONTINUES}); session remains parked`,
3299
+ });
3300
+ return;
3301
+ }
3302
+ state.monitoringWakeups = wakeups + 1;
3303
+ this.store.appendEvent(runId, {
3304
+ type: 'note',
3305
+ message: `automatic monitoring wake-up (${state.monitoringWakeups}/${MAX_AUTO_CONTINUES})`,
3306
+ });
3307
+ this.deliverMessage(runId, [{ type: 'text', text: MONITORING_WAKE_NUDGE }], false);
3308
+ }, Math.max(0, deadline - Date.now()));
3309
+ state.monitoringWakeTimer.unref?.();
3310
+ }
3311
+ clearMonitoringWakeTimer(state, runId) {
3312
+ if (state.monitoringWakeTimer)
3313
+ clearTimeout(state.monitoringWakeTimer);
3314
+ state.monitoringWakeTimer = undefined;
3315
+ state.monitoringWakeIntervalMinutes = undefined;
3316
+ if (runId)
3317
+ this.store.updateRun(runId, { monitoringWakeAt: undefined });
3318
+ }
3319
+ /** Autosave-commit the worktree every 90 s while the run lives (spec 006).
3320
+ * Opt-in via XEZ_AUTOSAVE=1 (#471) — see periodicAutosaveEnabled. */
3321
+ armAutosave(state) {
3322
+ if (!periodicAutosaveEnabled())
3323
+ return;
3324
+ if (state.cwd === this.repoRoot || state.autosaveTimer)
3325
+ return;
3326
+ state.autosaveTimer = setInterval(() => {
3327
+ void autosaveCommit(state.cwd, 'periodic');
3328
+ }, AUTOSAVE_INTERVAL_MS);
3329
+ state.autosaveTimer.unref?.();
3330
+ }
3331
+ clearAutosaveTimer(state) {
3332
+ if (state.autosaveTimer) {
3333
+ clearInterval(state.autosaveTimer);
3334
+ state.autosaveTimer = undefined;
3335
+ }
3336
+ }
3337
+ runCheckStep(state, step, emit) {
3338
+ const command = step.command;
3339
+ emit({ type: 'note', stepId: step.id, message: `$ ${command}` });
3340
+ return new Promise((resolve) => {
3341
+ // Check steps run in the same cwd as the agent steps — the worktree.
3342
+ const child = spawn('bash', ['-lc', command], { cwd: state.cwd, env: process.env });
3343
+ state.interrupt = () => child.kill('SIGTERM');
3344
+ let output = '';
3345
+ const collect = (chunk) => {
3346
+ if (output.length < CHECK_OUTPUT_CAP) {
3347
+ output += chunk.toString('utf8');
3348
+ if (output.length >= CHECK_OUTPUT_CAP)
3349
+ output += '\n… (output truncated)';
3350
+ }
3351
+ };
3352
+ child.stdout.on('data', collect);
3353
+ child.stderr.on('data', collect);
3354
+ child.on('error', (err) => {
3355
+ state.interrupt = () => undefined;
3356
+ const message = `failed to spawn: ${err.message}`;
3357
+ emit({ type: 'check-output', stepId: step.id, command, text: message, exitCode: -1 });
3358
+ resolve({ ok: false, output: message });
3359
+ });
3360
+ child.on('close', (code) => {
3361
+ state.interrupt = () => undefined;
3362
+ const trimmed = output.trim() || '(no output)';
3363
+ emit({ type: 'check-output', stepId: step.id, command, text: trimmed, exitCode: code ?? -1 });
3364
+ resolve({ ok: code === 0, output: trimmed });
3365
+ });
3366
+ });
3367
+ }
3368
+ finishStep(runId, stepId, status, error, emit) {
3369
+ this.store.updateStep(runId, stepId, {
3370
+ status,
3371
+ error,
3372
+ finishedAt: new Date().toISOString(),
3373
+ });
3374
+ emit({ type: 'step-end', stepId, status, ...(error ? { error } : {}) });
3375
+ appendHandoffHeartbeat(this.dataDir, runId, `step "${stepId}" complete — status=${status}`);
3376
+ }
3377
+ }
3378
+ function findLastAgentStepIndex(workflow) {
3379
+ for (let i = workflow.steps.length - 1; i >= 0; i--) {
3380
+ const step = workflow.steps[i];
3381
+ if (step && stepKind(step) === 'agent')
3382
+ return i;
3383
+ }
3384
+ return -1;
3385
+ }
3386
+ function applyTemplate(template, task) {
3387
+ return template.replaceAll('{{task}}', task);
3388
+ }
3389
+ /**
3390
+ * Immediate title shown while a run is queued. The namer's `titleSummary`
3391
+ * replaces it once the model answers; this is the honest, permanent fallback
3392
+ * when no model is available (#432, spec 2026-07-17-task-auto-naming). When
3393
+ * the task references a PR/issue, the number leads: `469: /om-auto-review-pr`.
3394
+ */
3395
+ export function makeRunTitle(task, workflow) {
3396
+ const firstLine = task.trim().split('\n')[0] ?? '';
3397
+ const skill = workflow.steps.find((step) => stepKind(step) === 'agent' && step.skill)?.skill?.trim();
3398
+ const contextual = skill && !firstLine.startsWith(`/${skill}`)
3399
+ ? `/${skill}${firstLine ? ` ${firstLine}` : ''}`
3400
+ : firstLine;
3401
+ const refNumber = titleRefNumber(refineTaskRefs(extractTaskRefs(task), skill));
3402
+ // `469` or `/om-auto-review-pr 469` reads as `469: /om-auto-review-pr` — the
3403
+ // number leads so it survives the tasks table's narrow truncation.
3404
+ const skillArg = skill && contextual.startsWith(`/${skill}`) ? contextual.slice(skill.length + 1).trim() : null;
3405
+ const body = refNumber !== undefined && skill && (skillArg === '' || /^#?\d+$/.test(skillArg ?? ''))
3406
+ ? `/${skill}`
3407
+ : contextual;
3408
+ const prefixed = refNumber !== undefined && !body.trimStart().replace(/^#/, '').startsWith(String(refNumber))
3409
+ ? `${refNumber}: ${body}`
3410
+ : body;
3411
+ const chars = [...(prefixed || '(untitled task)')];
3412
+ return chars.length > 80 ? `${chars.slice(0, 79).join('').trimEnd()}…` : chars.join('');
3413
+ }
3414
+ /**
3415
+ * Skill identity is context, while the Markdown body remains instructions.
3416
+ *
3417
+ * For an on-disk skill we also hand the agent the ABSOLUTE directory of the
3418
+ * installed copy. A run executes in an isolated worktree that has no local
3419
+ * `.agents/skills` (gitignored, absent in a fresh checkout), so without this
3420
+ * the agent cannot read the skill's companion files (`references/*.md`) — or,
3421
+ * worse, reads a stale copy materialized from the team-repo cache. The path
3422
+ * resolves against the MAIN project root (`discoverSkills(repoRoot)`), i.e. the
3423
+ * current `npx skills`-installed copy, so a worktree agent and the main
3424
+ * checkout read the exact same, up-to-date files. Team skills are omitted here:
3425
+ * they are materialized into the worktree separately (see the call site).
3426
+ */
3427
+ export function skillSystemPrompt(skill) {
3428
+ const lines = [
3429
+ `Selected skill: /${skill.name}`,
3430
+ ...(skill.description ? [`Description: ${skill.description}`] : []),
3431
+ ];
3432
+ if (skill.source && skill.source !== 'team' && skill.path) {
3433
+ const dir = dirname(skill.path);
3434
+ lines.push('', `Skill files are installed on disk at: ${dir}`, `Read any file this skill references (for example references/*.md) from that absolute directory. ` +
3435
+ `It is the current installed copy — use it even though your working directory is a separate worktree that does not contain the skill.`);
3436
+ }
3437
+ lines.push('', 'Skill instructions:', skill.body.trim());
3438
+ return lines.join('\n');
3439
+ }
3440
+ /**
3441
+ * Expand a registry-backed slash skill in one prompt string before it reaches a
3442
+ * backend. Claude otherwise intercepts an unknown leading slash command, and
3443
+ * Codex/OpenCode have no native slash-skill lookup at all (#676).
3444
+ *
3445
+ * Only a match at character zero counts, and unknown commands pass through
3446
+ * byte-for-byte — a backend's OWN slash commands must keep working. The caller
3447
+ * persists the original user text before applying this delivery-only rewrite.
3448
+ *
3449
+ * Both delivery seams route through here: live-session messages via
3450
+ * `expandRegistrySlashSkill`, and a continuation's opening prompt, which becomes
3451
+ * the session's `userPrompt` and never passes through `deliverMessage` at all
3452
+ * (#811).
3453
+ */
3454
+ export function expandRegistrySlashSkillText(text, skills) {
3455
+ const match = /^\/([A-Za-z0-9][A-Za-z0-9._-]*)(?=\s|$)/.exec(text);
3456
+ if (!match)
3457
+ return text;
3458
+ const skill = skills.find((candidate) => candidate.name === match[1]);
3459
+ if (!skill)
3460
+ return text;
3461
+ const request = text.slice(match[0].length).trim();
3462
+ return request ? `${skillSystemPrompt(skill)}\n\nUser request:\n${request}` : skillSystemPrompt(skill);
3463
+ }
3464
+ /**
3465
+ * `expandRegistrySlashSkillText` over a live chat message: only the first text
3466
+ * block is eligible, and an unchanged block returns the caller's array
3467
+ * identity untouched.
3468
+ */
3469
+ export function expandRegistrySlashSkill(content, skills) {
3470
+ const textIndex = content.findIndex((block) => block.type === 'text');
3471
+ if (textIndex < 0)
3472
+ return content;
3473
+ const block = content[textIndex];
3474
+ if (!block || block.type !== 'text')
3475
+ return content;
3476
+ const text = expandRegistrySlashSkillText(block.text, skills);
3477
+ if (text === block.text)
3478
+ return content;
3479
+ const expanded = [...content];
3480
+ expanded[textIndex] = { type: 'text', text };
3481
+ return expanded;
3482
+ }
3483
+ //# sourceMappingURL=run.js.map