@oyasmi/pipiclaw 0.9.5 → 0.9.6-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (345) hide show
  1. package/README.en.md +300 -142
  2. package/README.md +295 -140
  3. package/dist/agent/builtin-commands.d.ts +1 -1
  4. package/dist/agent/builtin-commands.js +1 -1
  5. package/dist/agent/channel-runner.d.ts +4 -3
  6. package/dist/agent/channel-runner.js +17 -28
  7. package/dist/agent/maintenance-context.js +2 -2
  8. package/dist/agent/prompt/builder.d.ts +1 -1
  9. package/dist/agent/prompt/builder.js +1 -1
  10. package/dist/agent/prompt/extension.d.ts +1 -1
  11. package/dist/agent/prompt/extension.js +1 -1
  12. package/dist/agent/prompt/manifest.d.ts +6 -1
  13. package/dist/agent/prompt/manifest.js +12 -5
  14. package/dist/agent/prompt/resources.d.ts +0 -3
  15. package/dist/agent/prompt/resources.js +0 -6
  16. package/dist/agent/prompt/sections.d.ts +2 -2
  17. package/dist/agent/prompt/sections.js +36 -26
  18. package/dist/agent/prompt/types.d.ts +3 -2
  19. package/dist/agent/runner-factory.js +1 -1
  20. package/dist/agent/session/command-extension.js +3 -1
  21. package/dist/agent/session/compaction-summary.js +3 -6
  22. package/dist/agent/session/compaction.d.ts +2 -0
  23. package/dist/agent/session/compaction.js +22 -14
  24. package/dist/agent/session/event-guards.d.ts +2 -1
  25. package/dist/agent/session/event-guards.js +6 -0
  26. package/dist/agent/session/model-selection.d.ts +2 -1
  27. package/dist/agent/session/model-selection.js +5 -5
  28. package/dist/agent/session/session-events.js +31 -4
  29. package/dist/agent/session/session-host.d.ts +5 -3
  30. package/dist/agent/session/session-host.js +20 -16
  31. package/dist/agent/status-render.js +3 -0
  32. package/dist/agent/stop-watchdog.js +5 -1
  33. package/dist/agent/turn/task-digest.d.ts +2 -5
  34. package/dist/agent/turn/task-digest.js +25 -45
  35. package/dist/agent/turn/turn-context.js +4 -6
  36. package/dist/agent/turn/turn-error.d.ts +1 -1
  37. package/dist/agent/turn/turn-error.js +9 -0
  38. package/dist/agent/turn/turn-pipeline.d.ts +10 -5
  39. package/dist/agent/turn/turn-pipeline.js +36 -7
  40. package/dist/agent/turn/turn-prompt.d.ts +2 -0
  41. package/dist/agent/turn/turn-prompt.js +2 -1
  42. package/dist/agent/turn/turn-recovery.js +4 -1
  43. package/dist/agent/turn/turn-state.d.ts +2 -0
  44. package/dist/agent/turn/turn-state.js +2 -1
  45. package/dist/agent/types.d.ts +23 -3
  46. package/dist/agent/types.js +2 -0
  47. package/dist/app/auth-command.d.ts +25 -0
  48. package/dist/app/auth-command.js +200 -67
  49. package/dist/app/home.d.ts +7 -8
  50. package/dist/app/home.js +143 -56
  51. package/dist/channel/attachments.d.ts +4 -0
  52. package/dist/channel/attachments.js +4 -0
  53. package/dist/channel/channel-context.d.ts +6 -0
  54. package/dist/channel/config.d.ts +3 -0
  55. package/dist/channel/config.js +11 -5
  56. package/dist/channel/store.d.ts +1 -1
  57. package/dist/commands/catalog.js +42 -10
  58. package/dist/commands/router.js +5 -1
  59. package/dist/desk/commands.d.ts +44 -5
  60. package/dist/desk/commands.js +162 -28
  61. package/dist/desk/paths.d.ts +6 -0
  62. package/dist/desk/paths.js +21 -1
  63. package/dist/desk/registry.d.ts +17 -2
  64. package/dist/desk/registry.js +122 -12
  65. package/dist/desk/types.d.ts +83 -1
  66. package/dist/dingtalk/bot.d.ts +1 -1
  67. package/dist/dingtalk/bot.js +4 -3
  68. package/dist/dingtalk/config.js +10 -10
  69. package/dist/dingtalk/delivery.js +15 -8
  70. package/dist/dingtalk/inbound-media.d.ts +36 -14
  71. package/dist/dingtalk/inbound-media.js +71 -12
  72. package/dist/dingtalk/inbound.d.ts +9 -2
  73. package/dist/dingtalk/inbound.js +17 -2
  74. package/dist/dingtalk/media.d.ts +4 -10
  75. package/dist/dingtalk/media.js +58 -32
  76. package/dist/events/commands.d.ts +2 -0
  77. package/dist/events/commands.js +13 -8
  78. package/dist/events/history.d.ts +9 -0
  79. package/dist/events/history.js +66 -0
  80. package/dist/events/parse.js +7 -3
  81. package/dist/events/types.d.ts +3 -0
  82. package/dist/events/watcher.d.ts +4 -8
  83. package/dist/events/watcher.js +53 -58
  84. package/dist/jobs/kill.d.ts +23 -0
  85. package/dist/jobs/kill.js +65 -0
  86. package/dist/jobs/manager.d.ts +19 -18
  87. package/dist/jobs/manager.js +36 -103
  88. package/dist/main.js +15 -3
  89. package/dist/memory/boundary-work.d.ts +2 -1
  90. package/dist/memory/boundary-work.js +1 -1
  91. package/dist/memory/lifecycle.d.ts +2 -1
  92. package/dist/memory/lifecycle.js +2 -2
  93. package/dist/memory/reflect-job.d.ts +2 -1
  94. package/dist/memory/reflect-job.js +1 -1
  95. package/dist/memory/reflect.d.ts +2 -1
  96. package/dist/memory/reflect.js +25 -4
  97. package/dist/memory/scheduler.d.ts +2 -1
  98. package/dist/memory/scheduler.js +1 -1
  99. package/dist/memory/session-corpus.d.ts +1 -1
  100. package/dist/memory/session-corpus.js +76 -1
  101. package/dist/memory/session-search.d.ts +2 -1
  102. package/dist/memory/session-search.js +14 -12
  103. package/dist/memory/sidecar-worker.d.ts +2 -1
  104. package/dist/memory/sidecar-worker.js +2 -4
  105. package/dist/memory/store.d.ts +2 -0
  106. package/dist/memory/store.js +19 -9
  107. package/dist/models/credential-work.d.ts +7 -0
  108. package/dist/models/credential-work.js +36 -0
  109. package/dist/models/login-ui.js +4 -4
  110. package/dist/models/provider-login.js +7 -6
  111. package/dist/models/requests.d.ts +8 -0
  112. package/dist/models/requests.js +69 -0
  113. package/dist/models/runtime.d.ts +3 -1
  114. package/dist/models/runtime.js +9 -2
  115. package/dist/playbooks/agent-delegation.md +20 -45
  116. package/dist/playbooks/background-jobs.md +1 -1
  117. package/dist/playbooks/catalog.js +1 -1
  118. package/dist/playbooks/delegation-inline.md +25 -0
  119. package/dist/playbooks/delegation-recovery.md +28 -0
  120. package/dist/playbooks/event-scheduling.md +18 -37
  121. package/dist/playbooks/event-sensors.md +26 -0
  122. package/dist/playbooks/event-task-template.md +22 -0
  123. package/dist/playbooks/learning-and-skills.md +26 -0
  124. package/dist/playbooks/memory-operations.md +36 -0
  125. package/dist/playbooks/outbound-media.md +2 -2
  126. package/dist/playbooks/runtime-files.md +29 -0
  127. package/dist/playbooks/runtime-operations.md +25 -0
  128. package/dist/playbooks/runtime-orientation.md +18 -53
  129. package/dist/playbooks/task-lead.md +22 -68
  130. package/dist/playbooks/task-manage.md +38 -0
  131. package/dist/playbooks/task-recovery.md +24 -0
  132. package/dist/playbooks/task-verify.md +22 -0
  133. package/dist/runtime/bootstrap.d.ts +10 -0
  134. package/dist/runtime/bootstrap.js +93 -29
  135. package/dist/runtime/daemon-lock.js +3 -3
  136. package/dist/runtime/desk-runtime.d.ts +40 -7
  137. package/dist/runtime/desk-runtime.js +330 -44
  138. package/dist/runtime/durable-dispatch.d.ts +14 -2
  139. package/dist/runtime/durable-dispatch.js +207 -65
  140. package/dist/runtime/ingress-busy.js +17 -8
  141. package/dist/runtime/ingress-commands.js +24 -4
  142. package/dist/runtime/ingress-deps.d.ts +4 -1
  143. package/dist/runtime/ingress.js +6 -1
  144. package/dist/runtime/request-execution.js +7 -6
  145. package/dist/runtime/shutdown.d.ts +4 -1
  146. package/dist/runtime/shutdown.js +88 -35
  147. package/dist/runtime/task-close.d.ts +1 -1
  148. package/dist/runtime/task-close.js +6 -3
  149. package/dist/runtime/task-control.d.ts +2 -3
  150. package/dist/runtime/task-control.js +38 -11
  151. package/dist/runtime/task-input.js +1 -1
  152. package/dist/runtime/task-lane-types.d.ts +12 -2
  153. package/dist/runtime/task-lane-types.js +9 -0
  154. package/dist/runtime/task-lane.d.ts +2 -0
  155. package/dist/runtime/task-lane.js +38 -20
  156. package/dist/runtime/task-step.d.ts +3 -3
  157. package/dist/runtime/task-step.js +34 -16
  158. package/dist/runtime/transports.js +6 -5
  159. package/dist/runtime/turn-run.js +103 -66
  160. package/dist/security/command-guard.d.ts +1 -1
  161. package/dist/security/command-guard.js +259 -314
  162. package/dist/security/path-guard.js +48 -7
  163. package/dist/security/shell-parse.d.ts +10 -0
  164. package/dist/security/shell-parse.js +224 -0
  165. package/dist/security/types.d.ts +2 -0
  166. package/dist/subagents/commands.d.ts +1 -1
  167. package/dist/subagents/commands.js +14 -5
  168. package/dist/subagents/completion-wake.js +6 -0
  169. package/dist/subagents/detached-discovery.d.ts +1 -1
  170. package/dist/subagents/discovery.d.ts +18 -199
  171. package/dist/subagents/discovery.js +35 -289
  172. package/dist/subagents/dispatch.d.ts +1 -2
  173. package/dist/subagents/dispatch.js +50 -29
  174. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  175. package/dist/subagents/external/antigravity-cli.js +517 -0
  176. package/dist/subagents/external/claude-code.js +8 -17
  177. package/dist/subagents/external/codex-cli.js +8 -18
  178. package/dist/subagents/external/cursor-cli.js +34 -31
  179. package/dist/subagents/external/dispatch.d.ts +21 -7
  180. package/dist/subagents/external/dispatch.js +146 -12
  181. package/dist/subagents/external/exec.js +3 -0
  182. package/dist/subagents/external/harness.d.ts +57 -33
  183. package/dist/subagents/external/harness.js +69 -40
  184. package/dist/subagents/external/reconciliation.js +1 -0
  185. package/dist/subagents/external/registry.js +4 -1
  186. package/dist/subagents/external/role-warnings.d.ts +4 -13
  187. package/dist/subagents/external/role-warnings.js +4 -28
  188. package/dist/subagents/external/run.d.ts +1 -2
  189. package/dist/subagents/external/run.js +16 -26
  190. package/dist/subagents/external/settlement.d.ts +2 -0
  191. package/dist/subagents/external/settlement.js +13 -3
  192. package/dist/subagents/format.d.ts +1 -1
  193. package/dist/subagents/format.js +1 -1
  194. package/dist/subagents/internal/outcome.d.ts +1 -2
  195. package/dist/subagents/internal/outcome.js +19 -12
  196. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  197. package/dist/subagents/internal/provider-retry.js +2 -4
  198. package/dist/subagents/internal/run.d.ts +2 -3
  199. package/dist/subagents/internal/run.js +27 -4
  200. package/dist/subagents/internal/state.d.ts +2 -5
  201. package/dist/subagents/internal/state.js +1 -2
  202. package/dist/subagents/internal/worker.d.ts +1 -2
  203. package/dist/subagents/internal/worker.js +20 -10
  204. package/dist/subagents/resolve.d.ts +56 -0
  205. package/dist/subagents/resolve.js +202 -0
  206. package/dist/subagents/result.d.ts +6 -4
  207. package/dist/subagents/result.js +39 -6
  208. package/dist/subagents/run-record.d.ts +54 -2
  209. package/dist/subagents/run-record.js +7 -0
  210. package/dist/subagents/runs.d.ts +6 -31
  211. package/dist/subagents/runs.js +26 -31
  212. package/dist/subagents/task-envelope.d.ts +1 -2
  213. package/dist/subagents/task-envelope.js +13 -4
  214. package/dist/subagents/task-settlement.js +1 -0
  215. package/dist/subagents/types.d.ts +105 -6
  216. package/dist/subagents/types.js +16 -1
  217. package/dist/subagents/workspace-lease.d.ts +41 -24
  218. package/dist/subagents/workspace-lease.js +159 -24
  219. package/dist/subagents/worktree.d.ts +52 -0
  220. package/dist/subagents/worktree.js +363 -0
  221. package/dist/tasks/archive.js +4 -0
  222. package/dist/tasks/brief.d.ts +5 -1
  223. package/dist/tasks/brief.js +19 -5
  224. package/dist/tasks/commands.d.ts +6 -1
  225. package/dist/tasks/commands.js +32 -7
  226. package/dist/tasks/control.d.ts +11 -0
  227. package/dist/tasks/delivery.d.ts +2 -0
  228. package/dist/tasks/delivery.js +141 -21
  229. package/dist/tasks/loop-log.d.ts +12 -0
  230. package/dist/tasks/loop-log.js +10 -1
  231. package/dist/tasks/receipts.d.ts +7 -3
  232. package/dist/tasks/receipts.js +34 -5
  233. package/dist/tools/bash.d.ts +3 -0
  234. package/dist/tools/bash.js +29 -15
  235. package/dist/tools/contract/presentation.js +7 -5
  236. package/dist/tools/edit-diff.d.ts +11 -0
  237. package/dist/tools/edit-diff.js +148 -0
  238. package/dist/tools/edit-match.d.ts +18 -0
  239. package/dist/tools/edit-match.js +242 -0
  240. package/dist/tools/edit.d.ts +10 -2
  241. package/dist/tools/edit.js +91 -361
  242. package/dist/tools/event-manage.d.ts +2 -1
  243. package/dist/tools/event-manage.js +46 -39
  244. package/dist/tools/file-observations.d.ts +9 -0
  245. package/dist/tools/file-observations.js +50 -0
  246. package/dist/tools/glob-match.d.ts +3 -1
  247. package/dist/tools/glob-match.js +40 -17
  248. package/dist/tools/glob.d.ts +1 -0
  249. package/dist/tools/glob.js +39 -19
  250. package/dist/tools/grep-command.d.ts +13 -0
  251. package/dist/tools/grep-command.js +77 -0
  252. package/dist/tools/grep.js +96 -201
  253. package/dist/tools/index.d.ts +6 -2
  254. package/dist/tools/index.js +9 -4
  255. package/dist/tools/job.js +12 -11
  256. package/dist/tools/read.d.ts +2 -0
  257. package/dist/tools/read.js +10 -2
  258. package/dist/tools/registry.d.ts +16 -11
  259. package/dist/tools/registry.js +32 -12
  260. package/dist/tools/send-media.js +9 -5
  261. package/dist/tools/session-search.d.ts +2 -1
  262. package/dist/tools/session-search.js +15 -5
  263. package/dist/tools/skill.js +13 -12
  264. package/dist/tools/subagent-manage.d.ts +1 -1
  265. package/dist/tools/subagent-manage.js +25 -152
  266. package/dist/tools/subagent.d.ts +24 -2
  267. package/dist/tools/subagent.js +24 -18
  268. package/dist/tools/task-manage/control-tools.js +1 -1
  269. package/dist/tools/task-manage/factory.d.ts +2 -2
  270. package/dist/tools/task-manage/factory.js +40 -4
  271. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  272. package/dist/tools/task-manage/lifecycle.js +56 -13
  273. package/dist/tools/task-manage/schema.d.ts +4 -1
  274. package/dist/tools/task-manage/schema.js +4 -1
  275. package/dist/tools/task-manage/shared.d.ts +1 -1
  276. package/dist/tools/task-manage/types.d.ts +5 -1
  277. package/dist/tools/write-content.d.ts +7 -1
  278. package/dist/tools/write-content.js +18 -6
  279. package/dist/tools/write.d.ts +3 -0
  280. package/dist/tools/write.js +6 -2
  281. package/dist/tui/cli.d.ts +6 -6
  282. package/dist/tui/cli.js +120 -28
  283. package/dist/tui/client.d.ts +7 -0
  284. package/dist/tui/client.js +67 -16
  285. package/dist/tui/frontend.d.ts +2 -0
  286. package/dist/tui/pitui-frontend.d.ts +4 -0
  287. package/dist/tui/pitui-frontend.js +27 -0
  288. package/dist/tui/render.d.ts +1 -0
  289. package/dist/tui/render.js +5 -0
  290. package/dist/tui/session.js +6 -0
  291. package/dist/usage/ledger.d.ts +1 -1
  292. package/dist/usage/render.js +1 -1
  293. package/dist/web/client.d.ts +1 -0
  294. package/dist/web/client.js +11 -0
  295. package/dist/web/fetch.js +6 -3
  296. package/dist/webapi/auth.d.ts +0 -3
  297. package/dist/webapi/auth.js +3 -7
  298. package/dist/webapi/config.js +17 -14
  299. package/dist/webapi/key-command.js +41 -41
  300. package/dist/webapi/response-state.d.ts +7 -1
  301. package/dist/webapi/response-state.js +166 -3
  302. package/dist/webapi/routes/websocket.js +24 -1
  303. package/dist/webapi/server.d.ts +3 -1
  304. package/dist/webapi/server.js +32 -1
  305. package/dist/webapi/service.js +8 -0
  306. package/dist/webapi/transport.d.ts +2 -0
  307. package/dist/webapi/transport.js +11 -1
  308. package/examples/sub-agents/README.md +43 -75
  309. package/examples/sub-agents/agy-main.md +21 -0
  310. package/examples/sub-agents/claude-high.md +21 -0
  311. package/examples/sub-agents/claude-main.md +21 -0
  312. package/examples/sub-agents/codex-flash.md +21 -0
  313. package/examples/sub-agents/codex-high.md +21 -0
  314. package/examples/sub-agents/codex-main.md +21 -0
  315. package/examples/sub-agents/codex-review.md +20 -0
  316. package/examples/sub-agents/cursor-high.md +20 -0
  317. package/examples/sub-agents/cursor-main.md +20 -0
  318. package/examples/sub-agents/glm-flash.md +21 -0
  319. package/examples/sub-agents/glm-high.md +21 -0
  320. package/examples/sub-agents/pi-scout.md +20 -0
  321. package/package.json +11 -12
  322. package/dist/agent/session/request-tools.d.ts +0 -3
  323. package/dist/agent/session/request-tools.js +0 -20
  324. package/dist/models/api-keys.d.ts +0 -11
  325. package/dist/models/api-keys.js +0 -22
  326. package/dist/playbooks/memory-and-learning.md +0 -55
  327. package/examples/sub-agents/agents/claude-high.md +0 -23
  328. package/examples/sub-agents/agents/claude-main.md +0 -23
  329. package/examples/sub-agents/agents/codex-flash.md +0 -23
  330. package/examples/sub-agents/agents/codex-high.md +0 -23
  331. package/examples/sub-agents/agents/codex-main.md +0 -23
  332. package/examples/sub-agents/agents/codex-review.md +0 -23
  333. package/examples/sub-agents/agents/cursor-high.md +0 -22
  334. package/examples/sub-agents/agents/cursor-main.md +0 -22
  335. package/examples/sub-agents/agents/glm-flash.md +0 -23
  336. package/examples/sub-agents/agents/glm-high.md +0 -23
  337. package/examples/sub-agents/agents/scout.md +0 -30
  338. package/examples/sub-agents/roles/builder-hard.md +0 -34
  339. package/examples/sub-agents/roles/builder.md +0 -34
  340. package/examples/sub-agents/roles/explorer.md +0 -39
  341. package/examples/sub-agents/roles/git-committer.md +0 -43
  342. package/examples/sub-agents/roles/planner.md +0 -33
  343. package/examples/sub-agents/roles/reviewer.md +0 -33
  344. package/examples/sub-agents/roles/verifier.md +0 -35
  345. package/examples/sub-agents/roles/worker.md +0 -34
@@ -6,6 +6,7 @@ const SHUTDOWN_WAIT_MS = 15000;
6
6
  const SHUTDOWN_FLUSH_WAIT_MS = 45000;
7
7
  const SHUTDOWN_ABORT_WAIT_MS = 5000;
8
8
  const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
9
+ const SHUTDOWN_TOTAL_MS = 90_000;
9
10
  function waitForTasks(tasks, timeoutMs) {
10
11
  if (tasks.length === 0) {
11
12
  return Promise.resolve(true);
@@ -27,6 +28,31 @@ export function createShutdown(deps) {
27
28
  return shutdownPromise;
28
29
  }
29
30
  shutdownPromise = (async () => {
31
+ const deadline = Date.now() + SHUTDOWN_TOTAL_MS;
32
+ let closed = false;
33
+ let quiescent = true;
34
+ const wait = (tasks, budget) => waitForTasks(tasks, Math.max(0, Math.min(budget, deadline - Date.now())));
35
+ const phase = async (name, work, budget) => {
36
+ const settled = await wait([
37
+ Promise.resolve()
38
+ .then(work)
39
+ .catch((error) => {
40
+ quiescent = false;
41
+ if (!closed)
42
+ log.logWarn("runtime.shutdown.phase_failed", "Shutdown phase failed", {
43
+ reason: errorMessage(error),
44
+ fields: { phase: name },
45
+ });
46
+ }),
47
+ ], budget);
48
+ if (!settled) {
49
+ quiescent = false;
50
+ log.logWarn("runtime.shutdown.phase_timeout", "Shutdown phase failed", {
51
+ reason: "deadline exceeded",
52
+ fields: { phase: name },
53
+ });
54
+ }
55
+ };
30
56
  deps.markShuttingDown();
31
57
  log.logInfoEvent("runtime.shutdown.started", "Shutting down", { fields: { reason } });
32
58
  taskLane.stop();
@@ -37,14 +63,14 @@ export function createShutdown(deps) {
37
63
  jobs.stop();
38
64
  // Admission closes first; the transports keep delivering, so a turn that finishes inside
39
65
  // the grace window below still reaches its channel (its card, its Web API response).
40
- await transports.stopAcceptingAll();
66
+ await phase("stop-accepting", () => transports.stopAcceptingAll(), SHUTDOWN_ABORT_WAIT_MS);
41
67
  ingress.stop();
42
68
  const runningTasks = Array.from(activeTasks);
43
69
  if (runningTasks.length > 0) {
44
70
  log.logInfoEvent("runtime.shutdown.waiting", "Waiting for active turns to finish", {
45
71
  fields: { activeTurns: runningTasks.length },
46
72
  });
47
- const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
73
+ const completed = await wait(runningTasks, SHUTDOWN_WAIT_MS);
48
74
  if (!completed) {
49
75
  log.logWarn("runtime.shutdown.grace_exceeded", "Shutdown grace period exceeded; aborting active turns", {
50
76
  fields: { waitMs: SHUTDOWN_WAIT_MS },
@@ -58,21 +84,23 @@ export function createShutdown(deps) {
58
84
  channelId: channelId,
59
85
  });
60
86
  aborts.push(runner.abort().catch((err) => {
61
- log.logWarn("runtime.shutdown.abort_failed", "Turn abort during shutdown failed", {
62
- channelId: channelId,
63
- reason: errorMessage(err),
64
- });
87
+ if (!closed)
88
+ log.logWarn("runtime.shutdown.abort_failed", "Turn abort during shutdown failed", {
89
+ channelId: channelId,
90
+ reason: errorMessage(err),
91
+ });
65
92
  }));
66
93
  }
67
- await Promise.allSettled(aborts);
94
+ // abort() can itself hang before reaching the SDK. It shares the same
95
+ // abort window with the turns; it never extends the shutdown deadline.
96
+ await wait([...aborts, ...activeTasks], SHUTDOWN_ABORT_WAIT_MS);
68
97
  const remainingTasks = Array.from(activeTasks);
69
98
  if (remainingTasks.length > 0) {
70
- const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
71
- if (!abortedCompleted) {
72
- log.logWarn("runtime.shutdown.forced", "Shutdown forced with turns still active", {
73
- fields: { activeTurns: remainingTasks.length },
74
- });
75
- }
99
+ quiescent = false;
100
+ log.logWarn("runtime.shutdown.forced", "Shutdown turn drain failed", {
101
+ reason: "deadline exceeded",
102
+ fields: { activeTurns: remainingTasks.length },
103
+ });
76
104
  }
77
105
  }
78
106
  }
@@ -81,21 +109,26 @@ export function createShutdown(deps) {
81
109
  // left to unwind on its own as the process exits.
82
110
  const disposals = [];
83
111
  for (const [channelId, runner] of channelRunners) {
84
- if (runner.isBusy())
112
+ if (runner.isBusy()) {
113
+ runner.retireForRecovery();
85
114
  continue;
115
+ }
86
116
  disposals.push(runner.dispose().catch((err) => {
87
- log.logWarn("runtime.shutdown.dispose_failed", "Runner dispose during shutdown failed", {
88
- channelId: channelId,
89
- reason: errorMessage(err),
90
- });
117
+ quiescent = false;
118
+ if (!closed)
119
+ log.logWarn("runtime.shutdown.dispose_failed", "Runner dispose during shutdown failed", {
120
+ channelId: channelId,
121
+ reason: errorMessage(err),
122
+ });
91
123
  }));
92
124
  }
93
125
  if (disposals.length > 0) {
94
126
  log.logInfoEvent("runtime.shutdown.disposing", "Disposing idle channel runners", {
95
127
  fields: { count: disposals.length },
96
128
  });
97
- const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
129
+ const disposed = await wait(disposals, SHUTDOWN_FLUSH_WAIT_MS);
98
130
  if (!disposed) {
131
+ quiescent = false;
99
132
  log.logWarn("runtime.shutdown.dispose_timeout", "Runner disposal during shutdown timed out", {
100
133
  fields: { waitMs: SHUTDOWN_FLUSH_WAIT_MS },
101
134
  });
@@ -103,23 +136,43 @@ export function createShutdown(deps) {
103
136
  }
104
137
  channelRunners.clear();
105
138
  // Only now do connections close: what is still unfinished ends as interrupted.
106
- await transports.stopAll();
107
- const storageFlushes = [
108
- store.close(),
109
- // Cancels the debounce timer and lands the last activity times.
110
- channelIndex.close(),
111
- getUsageLedger().flush?.() ?? Promise.resolve(),
112
- flushSecurityLogs(),
113
- ...(deskRuntime.flush ? [deskRuntime.flush()] : []),
114
- ];
115
- const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
116
- if (!storageFlushed) {
117
- log.logWarn("runtime.shutdown.flush_timeout", "Log flush during shutdown timed out", {
118
- fields: { waitMs: SHUTDOWN_LOG_FLUSH_WAIT_MS },
119
- });
139
+ await phase("stop-transports", () => transports.stopAll(), SHUTDOWN_ABORT_WAIT_MS);
140
+ await phase("credentials", deps.flushCredentials, SHUTDOWN_FLUSH_WAIT_MS);
141
+ await phase("storage", async () => {
142
+ await Promise.all([
143
+ deps.getDurableDispatch()?.flush?.() ?? Promise.resolve(),
144
+ store.close(),
145
+ channelIndex.close(),
146
+ getUsageLedger().flush?.() ?? Promise.resolve(),
147
+ flushSecurityLogs(),
148
+ ...(deskRuntime.flush ? [deskRuntime.flush()] : []),
149
+ ]);
150
+ }, SHUTDOWN_LOG_FLUSH_WAIT_MS);
151
+ await phase("logging", () => log.flushLogging(), SHUTDOWN_LOG_FLUSH_WAIT_MS);
152
+ // A deadline cannot cancel an arbitrary storage promise. Do not hand this home to
153
+ // a new writer while such work (or an active turn) can still mutate it. Process exit
154
+ // makes the retained PID lock reclaimable; an embedded caller must exit before reopen.
155
+ // A task drive can finish by starting its runner's asynchronous disposal. That
156
+ // cleanup joins activeTasks synchronously and must also fence lock hand-off.
157
+ quiescent &&= activeTasks.size === 0;
158
+ closed = true;
159
+ if (quiescent) {
160
+ const released = await wait([
161
+ deps.releaseDaemonLock().catch((error) => {
162
+ log.logWarn("runtime.shutdown.unlock_failed", "Daemon lock release failed", {
163
+ reason: errorMessage(error),
164
+ });
165
+ }),
166
+ ], Math.max(0, deadline - Date.now()));
167
+ if (!released)
168
+ log.logWarn("runtime.shutdown.unlock_timeout", "Daemon lock release failed", {
169
+ reason: "deadline exceeded",
170
+ });
120
171
  }
121
- await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
122
- await deps.releaseDaemonLock();
172
+ else
173
+ log.logWarn("runtime.shutdown.lock_retained", "Shutdown quiescence failed", {
174
+ reason: "unfinished work may still write; daemon lock retained until process exit",
175
+ });
123
176
  })();
124
177
  return shutdownPromise;
125
178
  };
@@ -1,4 +1,4 @@
1
1
  import type { TaskStepIntent } from "../tasks/control.js";
2
- import type { LaneContext, LiveTask } from "./task-lane-types.js";
2
+ import { type LaneContext, type LiveTask } from "./task-lane-types.js";
3
3
  /** Commit the leader's durable close without another model turn. Delivery failures retain that intent. */
4
4
  export declare function finishTaskClose(ctx: LaneContext, live: LiveTask, title: string, intent: TaskStepIntent, cancelWork: (desk: string, id: string) => Promise<string[]>, dispose: (live: LiveTask) => Promise<void>): Promise<number | undefined>;
@@ -7,6 +7,7 @@ import { drainTaskDeliveries } from "../tasks/delivery.js";
7
7
  import { appendTaskLog, readTaskLog } from "../tasks/loop-log.js";
8
8
  import { cancelledByLeaderReceipt, completedReceipt } from "../tasks/receipts.js";
9
9
  import { closeTask, pauseTask } from "../tasks/store.js";
10
+ import { canDeliverToChannel } from "./task-lane-types.js";
10
11
  import { listPendingWork } from "./task-pending.js";
11
12
  /** Commit the leader's durable close without another model turn. Delivery failures retain that intent. */
12
13
  export async function finishTaskClose(ctx, live, title, intent, cancelWork, dispose) {
@@ -17,7 +18,7 @@ export async function finishTaskClose(ctx, live, title, intent, cancelWork, disp
17
18
  };
18
19
  const flush = async (desk, deskDir) => {
19
20
  try {
20
- noteHorizon(await drainTaskDeliveries(deskDir, (channel, text) => ctx.options.deliver(desk, channel, text), (channel) => ctx.options.isBoundTo(channel, desk) && ctx.options.isReachable(channel), ctx.now()));
21
+ noteHorizon(await drainTaskDeliveries(deskDir, (channel, text) => ctx.options.deliver(desk, channel, text), (channel) => canDeliverToChannel(ctx, desk, channel), ctx.now()));
21
22
  }
22
23
  catch (error) {
23
24
  log.logWarn("tasks.delivery.drain_failed", "Task delivery drain failed", {
@@ -56,14 +57,16 @@ export async function finishTaskClose(ctx, live, title, intent, cancelWork, disp
56
57
  }
57
58
  if (close.outcome === "cancel")
58
59
  await cancelWork(live.desk, live.taskId);
60
+ const runMgr = ctx.options.getRuns(live.desk);
61
+ const retainedWorktrees = await Promise.resolve(runMgr.reclaimTaskWorktrees?.(live.taskId) ?? []).catch(() => []);
59
62
  const closed = await closeTask(live.deskDir, live.taskId, {
60
63
  outcome: close.outcome,
61
64
  by: "leader",
62
65
  note: close.note,
63
66
  reportId: close.reportId,
64
67
  receipt: (document, closedAt) => close.outcome === "complete"
65
- ? completedReceipt(live.taskId, title, document, closedAt)
66
- : cancelledByLeaderReceipt(live.taskId, title, close.note),
68
+ ? completedReceipt(live.taskId, title, document, closedAt, retainedWorktrees)
69
+ : cancelledByLeaderReceipt(live.taskId, title, close.note, retainedWorktrees),
67
70
  });
68
71
  if (!closed) {
69
72
  await dispose(live);
@@ -1,8 +1,6 @@
1
1
  import type { TaskCancelOutcome, TaskControl, TaskControlOutcome, TaskLiveSnapshot, TaskMessageOutcome } from "../tasks/control.js";
2
- import type { TaskBudget, TaskFrontmatter } from "../tasks/frontmatter.js";
2
+ import type { TaskBudget } from "../tasks/frontmatter.js";
3
3
  import { type LaneContext } from "./task-lane-types.js";
4
- /** Whether a task's report channel can currently be reached (INV-7). */
5
- export declare function isFrozen(ctx: LaneContext, desk: string, fields: TaskFrontmatter): boolean;
6
4
  /**
7
5
  * The chat-facing control surface of the lane (spec 064, D24): every write is made inside the
8
6
  * task's own mutation lock (the store's transitions take it), appended to the log before the lane is
@@ -24,6 +22,7 @@ export declare class LaneControl implements TaskControl {
24
22
  reason: string;
25
23
  }): Promise<TaskControlOutcome>;
26
24
  resume(desk: string, id: string, grants: Partial<TaskBudget>): Promise<TaskControlOutcome>;
25
+ adopt(desk: string, id: string, channel: string): Promise<TaskControlOutcome>;
27
26
  cancel(desk: string, id: string, input: {
28
27
  by: "user";
29
28
  note: string;
@@ -4,22 +4,17 @@ import { withTimeout } from "../shared/with-timeout.js";
4
4
  import { isTaskArchiving } from "../tasks/archive.js";
5
5
  import { pendingTaskClose } from "../tasks/completion.js";
6
6
  import { extractTaskTitle, readActiveTasks } from "../tasks/contract.js";
7
- import { drainTaskDeliveries } from "../tasks/delivery.js";
7
+ import { drainTaskDeliveries, redirectTaskDeliveries } from "../tasks/delivery.js";
8
8
  import { taskInputTag } from "../tasks/input-receipts.js";
9
9
  import { appendTaskLog, readTaskLog } from "../tasks/loop-log.js";
10
10
  import { withTaskMutation } from "../tasks/mutation-lock.js";
11
11
  import { cancelledByUserReceipt } from "../tasks/receipts.js";
12
- import { closeTask as closeStoredTask, pauseTask as pauseStoredTask, readStoredTask, resumeTask as resumeStoredTask, tasksDir, } from "../tasks/store.js";
12
+ import { closeTask as closeStoredTask, pauseTask as pauseStoredTask, readStoredTask, resumeTask as resumeStoredTask, tasksDir, updateStoredTask, } from "../tasks/store.js";
13
13
  import { describeToolCall } from "../tools/contract/presentation.js";
14
14
  import { submitTaskInput } from "./task-input.js";
15
- import { taskKey } from "./task-lane-types.js";
15
+ import { canDeliverToChannel, isFrozen, taskKey } from "./task-lane-types.js";
16
16
  import { listPendingWork } from "./task-pending.js";
17
17
  import { abortStep } from "./task-step.js";
18
- /** Whether a task's report channel can currently be reached (INV-7). */
19
- export function isFrozen(ctx, desk, fields) {
20
- const channel = fields.channel;
21
- return !channel || !ctx.options.isBoundTo(channel, desk) || !ctx.options.isReachable(channel);
22
- }
23
18
  /**
24
19
  * The chat-facing control surface of the lane (spec 064, D24): every write is made inside the
25
20
  * task's own mutation lock (the store's transitions take it), appended to the log before the lane is
@@ -157,6 +152,32 @@ export class LaneControl {
157
152
  this.ctx.notify();
158
153
  return { kind: "ok" };
159
154
  }
155
+ async adopt(desk, id, channel) {
156
+ const { ctx } = this;
157
+ const deskDir = ctx.options.getDeskDir(desk);
158
+ if (!deskDir)
159
+ return { kind: "not_found" };
160
+ const existing = await readStoredTask(deskDir, id);
161
+ if (!existing || existing.fields.outcome)
162
+ return { kind: "not_found" };
163
+ if (existing.fields.channel === channel)
164
+ return { kind: "unchanged" };
165
+ const updated = await updateStoredTask(deskDir, id, (doc) => {
166
+ doc.fields = { ...doc.fields, channel };
167
+ });
168
+ if (!updated)
169
+ return { kind: "not_found" };
170
+ const live = ctx.live.get(taskKey(desk, id));
171
+ if (live) {
172
+ live.channelId = channel;
173
+ if (!live.driving)
174
+ await ctx.release(live);
175
+ }
176
+ await redirectTaskDeliveries(deskDir, id, channel).catch(() => undefined);
177
+ await drainTaskDeliveries(deskDir, (targetChannel, text) => ctx.options.deliver(desk, targetChannel, text), (targetChannel) => canDeliverToChannel(ctx, desk, targetChannel), ctx.now()).catch(() => undefined);
178
+ ctx.notify();
179
+ return { kind: "ok" };
180
+ }
160
181
  async cancel(desk, id, input) {
161
182
  const { ctx } = this;
162
183
  const deskDir = ctx.options.getDeskDir(desk);
@@ -175,13 +196,15 @@ export class LaneControl {
175
196
  }
176
197
  }
177
198
  const cancelled = await this.cancelBoundWork(desk, id);
199
+ const runMgr = ctx.options.getRuns(desk);
200
+ const retainedWorktrees = await Promise.resolve(runMgr.reclaimTaskWorktrees?.(id) ?? []).catch(() => []);
178
201
  const reportChannel = document.fields.channel;
179
202
  await closeStoredTask(deskDir, id, {
180
203
  outcome: "cancel",
181
204
  by: input.by,
182
205
  note: input.note,
183
206
  receipt: reportChannel && reportChannel !== input.channel
184
- ? () => cancelledByUserReceipt(id, extractTaskTitle(document.body, id))
207
+ ? () => cancelledByUserReceipt(id, extractTaskTitle(document.body, id), retainedWorktrees)
185
208
  : undefined,
186
209
  });
187
210
  if (live)
@@ -190,12 +213,16 @@ export class LaneControl {
190
213
  // A cancel typed in another channel of the desk leaves the report channel told (D29); one typed
191
214
  // there is answered by the command's own reply.
192
215
  if (reportChannel && reportChannel !== input.channel) {
193
- await drainTaskDeliveries(deskDir, (channel, text) => ctx.options.deliver(desk, channel, text), (channel) => ctx.options.isBoundTo(channel, desk) && ctx.options.isReachable(channel), ctx.now()).catch((error) => log.logWarn("tasks.delivery.drain_failed", "Task delivery drain failed", {
216
+ await drainTaskDeliveries(deskDir, (channel, text) => ctx.options.deliver(desk, channel, text), (channel) => canDeliverToChannel(ctx, desk, channel), ctx.now()).catch((error) => log.logWarn("tasks.delivery.drain_failed", "Task delivery drain failed", {
194
217
  reason: errorMessage(error),
195
218
  fields: { desk, taskId: id },
196
219
  }));
197
220
  }
198
- return { kind: "cancelled", cancelled };
221
+ return {
222
+ kind: "cancelled",
223
+ cancelled,
224
+ ...(retainedWorktrees.length > 0 ? { retainedWorktrees } : {}),
225
+ };
199
226
  }
200
227
  /** Cancel every delegation and job bound to the task; the refs that were still running. */
201
228
  async cancelBoundWork(desk, taskId) {
@@ -15,7 +15,7 @@ function eligible(ctx, live, step) {
15
15
  !live.quarantined &&
16
16
  !ctx.isStopped() &&
17
17
  ctx.options.isEnabled?.() !== false &&
18
- ctx.options.isBoundTo(live.channelId, live.desk) &&
18
+ !!live.channelId &&
19
19
  ctx.options.isReachable(live.channelId) &&
20
20
  !live.intent.ask &&
21
21
  !live.intent.waitUntil &&
@@ -3,6 +3,7 @@ import type { ChannelStore } from "../channel/store.js";
3
3
  import type { DeskJobManager } from "../jobs/manager.js";
4
4
  import type { SubAgentRunManager } from "../subagents/runs.js";
5
5
  import type { TaskSessionContext, TaskStepIntent } from "../tasks/control.js";
6
+ import type { TaskFrontmatter } from "../tasks/frontmatter.js";
6
7
  /** Executing tasks per desk and per daemon (spec 064, D12). Code constants, not settings. */
7
8
  export declare const MAX_EXECUTING_TASKS_PER_DESK = 3;
8
9
  export declare const MAX_EXECUTING_TASKS = 5;
@@ -40,11 +41,15 @@ export interface TaskLaneOptions {
40
41
  }>;
41
42
  /** The directory of a desk the runtime knows, or `undefined`. */
42
43
  getDeskDir: (desk: string) => string | undefined;
44
+ /** The current working directory of `desk`, so a retained runner notices `/desk cwd` or `desk.json` updates. */
45
+ getDeskCwd?: (desk: string, channelId: string) => string | undefined;
43
46
  /**
44
- * Whether a report channel is bound to a desk right now. A task whose `channel` is missing or not
45
- * bound to its own desk is frozen: the lane does not touch it (INV-7).
47
+ * Whether a report channel is bound to a desk right now. Gates outbound channel deliveries (INV-5),
48
+ * while background step execution continues in the task's own session.
46
49
  */
47
50
  isBoundTo: (channelId: string, desk: string) => boolean;
51
+ /** Called when an active desk scan sees no non-paused open tasks, allowing unbound desks to go dormant. */
52
+ onDeskIdle?: (desk: string) => void;
48
53
  /** Whether the channel's transport is switched on in this process (spec 061, INV-8). */
49
54
  isReachable: (channelId: string) => boolean;
50
55
  /** Build the runner for one task (the `task` profile). The lane owns it from here and disposes it. */
@@ -88,6 +93,7 @@ export interface LiveTask {
88
93
  startedAt: number;
89
94
  submittedInputIds: Set<string>;
90
95
  submitting?: Promise<void>;
96
+ quarantining?: Promise<void>;
91
97
  injecting?: boolean;
92
98
  inputDirty?: boolean;
93
99
  ending?: boolean;
@@ -121,3 +127,7 @@ export interface LaneContext {
121
127
  isStopped(): boolean;
122
128
  }
123
129
  export declare function taskKey(desk: string, taskId: string): string;
130
+ /** Whether a task's execution must be held back (missing channel or disabled transport; spec 061 INV-8). */
131
+ export declare function isFrozen(ctx: LaneContext, _desk: string, fields: TaskFrontmatter): boolean;
132
+ /** Whether outbound task deliveries (reports, receipts, questions) may be sent to `channel` right now (INV-5). */
133
+ export declare function canDeliverToChannel(ctx: LaneContext, desk: string, channel: string | undefined): boolean;
@@ -12,3 +12,12 @@ export const ERROR_BACKOFF_MS = [60_000, 5 * 60_000];
12
12
  export function taskKey(desk, taskId) {
13
13
  return `${desk}\0${taskId}`;
14
14
  }
15
+ /** Whether a task's execution must be held back (missing channel or disabled transport; spec 061 INV-8). */
16
+ export function isFrozen(ctx, _desk, fields) {
17
+ const channel = fields.channel;
18
+ return !channel || !ctx.options.isReachable(channel);
19
+ }
20
+ /** Whether outbound task deliveries (reports, receipts, questions) may be sent to `channel` right now (INV-5). */
21
+ export function canDeliverToChannel(ctx, desk, channel) {
22
+ return !!channel && ctx.options.isBoundTo(channel, desk) && ctx.options.isReachable(channel);
23
+ }
@@ -44,6 +44,7 @@ export declare class TaskLane implements TaskControl {
44
44
  /** One scan now, outside the timer: the entry point tests and the runtime's own wiring use. */
45
45
  runOnce(): Promise<void>;
46
46
  isRunning(desk: string, id: string): boolean;
47
+ runningTaskInDesk(desk: string): string | undefined;
47
48
  created(): void;
48
49
  snapshot(desk: string, id?: string): Promise<TaskLiveSnapshot[]>;
49
50
  message(desk: string, id: string, input: {
@@ -56,6 +57,7 @@ export declare class TaskLane implements TaskControl {
56
57
  reason: string;
57
58
  }): Promise<TaskControlOutcome>;
58
59
  resume(desk: string, id: string, grants: Partial<TaskBudget>): Promise<TaskControlOutcome>;
60
+ adopt(desk: string, id: string, channel: string): Promise<TaskControlOutcome>;
59
61
  cancel(desk: string, id: string, input: {
60
62
  by: "user";
61
63
  note: string;
@@ -12,9 +12,9 @@ import { askReceipt, pausedReceipt } from "../tasks/receipts.js";
12
12
  import { checkGuards, evaluateWaiting } from "../tasks/state.js";
13
13
  import { pauseTask, readStoredTask, reconcileTaskState, requeueWaiting } from "../tasks/store.js";
14
14
  import { finishTaskClose } from "./task-close.js";
15
- import { isFrozen, LaneControl } from "./task-control.js";
15
+ import { LaneControl } from "./task-control.js";
16
16
  import { TaskInputDelivery } from "./task-input.js";
17
- import { ERROR_BACKOFF_MS, MAX_EXECUTING_TASKS, MAX_EXECUTING_TASKS_PER_DESK, MAX_SLEEP_MS, NOTIFY_DEBOUNCE_MS, STEP_TIME_LIMIT_MS, taskKey, } from "./task-lane-types.js";
17
+ import { canDeliverToChannel, ERROR_BACKOFF_MS, isFrozen, MAX_EXECUTING_TASKS, MAX_EXECUTING_TASKS_PER_DESK, MAX_SLEEP_MS, NOTIFY_DEBOUNCE_MS, STEP_TIME_LIMIT_MS, taskKey, } from "./task-lane-types.js";
18
18
  import { listPendingWork } from "./task-pending.js";
19
19
  import { abortStep, executeStep } from "./task-step.js";
20
20
  function isExecuting(seen, live) {
@@ -56,7 +56,7 @@ export class TaskLane {
56
56
  this.questionRetry = new Map();
57
57
  const timing = {
58
58
  stepTimeLimitMs: options.timing?.stepTimeLimitMs ?? STEP_TIME_LIMIT_MS,
59
- stopGraceMs: options.timing?.stopGraceMs ?? 3_000,
59
+ stopGraceMs: options.timing?.stopGraceMs ?? 15_000,
60
60
  maxSleepMs: options.timing?.maxSleepMs ?? MAX_SLEEP_MS,
61
61
  notifyDebounceMs: options.timing?.notifyDebounceMs ?? NOTIFY_DEBOUNCE_MS,
62
62
  errorBackoffMs: options.timing?.errorBackoffMs ?? ERROR_BACKOFF_MS,
@@ -137,6 +137,12 @@ export class TaskLane {
137
137
  isRunning(desk, id) {
138
138
  return this.ctx.live.get(taskKey(desk, id))?.driving ?? false;
139
139
  }
140
+ runningTaskInDesk(desk) {
141
+ for (const live of this.ctx.live.values())
142
+ if (live.desk === desk && live.driving)
143
+ return live.taskId;
144
+ return undefined;
145
+ }
140
146
  created() {
141
147
  this.control.created();
142
148
  }
@@ -152,6 +158,9 @@ export class TaskLane {
152
158
  resume(desk, id, grants) {
153
159
  return this.control.resume(desk, id, grants);
154
160
  }
161
+ adopt(desk, id, channel) {
162
+ return this.control.adopt(desk, id, channel);
163
+ }
155
164
  cancel(desk, id, input) {
156
165
  return this.control.cancel(desk, id, input);
157
166
  }
@@ -204,12 +213,17 @@ export class TaskLane {
204
213
  let entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
205
214
  let pending = await listPendingWork(this.options, desk, now);
206
215
  // D10: whatever state the previous process left becomes true to the facts before anything is decided.
216
+ let reconciled = false;
207
217
  for (const entry of entries) {
208
- if (!isFrozen(this.ctx, desk, entry.fields))
209
- await this.reconcile(desk, deskDir, entry, pending.get(entry.id)?.length ?? 0);
218
+ if (!isFrozen(this.ctx, desk, entry.fields)) {
219
+ if (await this.reconcile(desk, deskDir, entry, pending.get(entry.id)?.length ?? 0))
220
+ reconciled = true;
221
+ }
222
+ }
223
+ if (reconciled) {
224
+ entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
225
+ pending = await listPendingWork(this.options, desk, now);
210
226
  }
211
- entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
212
- pending = await listPendingWork(this.options, desk, now);
213
227
  const seen = [];
214
228
  for (const entry of entries) {
215
229
  const key = taskKey(desk, entry.id);
@@ -228,15 +242,7 @@ export class TaskLane {
228
242
  const channel = entry.fields.channel;
229
243
  log.logInfoEvent("tasks.task.frozen", "Task frozen: report channel not usable", {
230
244
  channelId: channel,
231
- fields: {
232
- taskId: entry.id,
233
- desk,
234
- reason: !channel
235
- ? "channel_missing"
236
- : this.options.isBoundTo(channel, desk)
237
- ? "channel_unreachable"
238
- : "channel_not_bound",
239
- },
245
+ fields: { taskId: entry.id, desk, reason: !channel ? "channel_missing" : "channel_unreachable" },
240
246
  });
241
247
  }
242
248
  else if (!frozen && this.frozenLogged.delete(key)) {
@@ -314,6 +320,8 @@ export class TaskLane {
314
320
  }
315
321
  }
316
322
  candidates.set(scan.desk, ready);
323
+ if (!scan.seen.some((item) => item.entry.fields.state !== "paused"))
324
+ this.options.onDeskIdle?.(scan.desk);
317
325
  }
318
326
  if (!enabled)
319
327
  return;
@@ -574,10 +582,12 @@ export class TaskLane {
574
582
  return;
575
583
  }
576
584
  const doc = await readStoredTask(deskDir, id);
585
+ const targetChannel = doc?.fields.channel ?? channel;
577
586
  if (!doc ||
578
587
  doc.fields.state !== "waiting" ||
579
588
  doc.fields.waiting?.kind !== "user" ||
580
- isFrozen(this.ctx, desk, doc.fields))
589
+ isFrozen(this.ctx, desk, doc.fields) ||
590
+ !canDeliverToChannel(this.ctx, desk, targetChannel))
581
591
  return;
582
592
  const question = doc.fields.waiting.question;
583
593
  const records = await readTaskLog(deskDir, id);
@@ -586,7 +596,7 @@ export class TaskLane {
586
596
  return;
587
597
  this.questionRetry.set(key, this.ctx.now() + 60_000);
588
598
  try {
589
- if (await this.options.deliver(desk, doc.fields.channel ?? channel, askReceipt(id, question))) {
599
+ if (await this.options.deliver(desk, targetChannel, askReceipt(id, question))) {
590
600
  await withTaskMutation(deskDir, id, async () => {
591
601
  const current = await readStoredTask(deskDir, id);
592
602
  if (current?.fields.state === "waiting" &&
@@ -661,7 +671,7 @@ export class TaskLane {
661
671
  }
662
672
  async flushDeliveries(desk, deskDir) {
663
673
  try {
664
- this.noteHorizon(await drainTaskDeliveries(deskDir, (channel, text) => this.options.deliver(desk, channel, text), (channel) => this.options.isBoundTo(channel, desk) && this.options.isReachable(channel), this.ctx.now()));
674
+ this.noteHorizon(await drainTaskDeliveries(deskDir, (channel, text) => this.options.deliver(desk, channel, text), (channel) => canDeliverToChannel(this.ctx, desk, channel), this.ctx.now()));
665
675
  }
666
676
  catch (error) {
667
677
  log.logWarn("tasks.delivery.drain_failed", "Task delivery drain failed", {
@@ -681,12 +691,20 @@ export class TaskLane {
681
691
  async dispose(live) {
682
692
  if (this.ctx.live.get(live.key) === live)
683
693
  this.ctx.live.delete(live.key);
694
+ live.quarantined = undefined;
684
695
  const runner = live.runner;
685
696
  live.runner = undefined;
686
697
  if (!runner)
687
698
  return;
688
699
  try {
689
- await runner.dispose();
700
+ const disposal = runner.dispose();
701
+ this.options.activeTasks.add(disposal);
702
+ try {
703
+ await disposal;
704
+ }
705
+ finally {
706
+ this.options.activeTasks.delete(disposal);
707
+ }
690
708
  }
691
709
  catch (error) {
692
710
  log.logWarn("tasks.runner.dispose_failed", "Task runner dispose failed", {
@@ -3,9 +3,9 @@ import type { TaskStepIntent } from "../tasks/control.js";
3
3
  import { type TaskStepResult } from "../tasks/loop-log.js";
4
4
  import type { StepDerivation } from "../tasks/state.js";
5
5
  import { type EndedStep } from "../tasks/store.js";
6
- import type { LaneContext, LiveTask, StepAbort } from "./task-lane-types.js";
7
- /** The task's runner, built on first use and kept until the task leaves execution (D13). */
8
- export declare function ensureRunner(ctx: LaneContext, live: LiveTask): AgentRunner;
6
+ import { type LaneContext, type LiveTask, type StepAbort } from "./task-lane-types.js";
7
+ /** The task's runner, built on first use and kept until the task leaves execution (D13) or the desk's cwd changes. */
8
+ export declare function ensureRunner(ctx: LaneContext, live: LiveTask): Promise<AgentRunner>;
9
9
  /** Stop the running step: the turn is asked to end, and the abort cuts a tool that would not. */
10
10
  export declare function abortStep(ctx: LaneContext, live: LiveTask, reason: StepAbort): void;
11
11
  /** What a finished step tells the drive loop. */