@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
@@ -61,6 +61,17 @@ function renderSettleInput(settle) {
61
61
  const lines = [`[结果 ${head}]`];
62
62
  if (settle.output)
63
63
  lines.push(`完整输出:${settle.output}`);
64
+ if (settle.worktree) {
65
+ if (settle.worktree.cleaned) {
66
+ lines.push(`Worktree:无改动,已自动回收(headSha=${settle.worktree.headSha.slice(0, 12)})`);
67
+ }
68
+ else {
69
+ const files = settle.worktree.changedFiles.length > 0 ? settle.worktree.changedFiles.slice(0, 20).join(", ") : "无";
70
+ const more = settle.worktree.changedFiles.length > 20 ? ` (+${settle.worktree.changedFiles.length - 20})` : "";
71
+ const dirty = settle.worktree.dirty ? ",含未提交改动" : "";
72
+ lines.push(`Worktree:${settle.worktree.path}(branch=${settle.worktree.branch ?? "detached"},headSha=${settle.worktree.headSha}${dirty},changedFiles=${files}${more})`);
73
+ }
74
+ }
64
75
  if (settle.changed)
65
76
  lines.push(`改动(git status):${settle.changed}`);
66
77
  lines.push(`<untrusted_agent_output>\n${settle.tail ?? "(无输出)"}\n</untrusted_agent_output>`);
@@ -126,7 +137,6 @@ function renderState(fields, seq, pending) {
126
137
  : "in_flight: 无");
127
138
  return lines.join("\n");
128
139
  }
129
- const STEP_RULES = "回合结束即本步结束:等用户用 task_ask,等某个时刻用 task_wait,完成用 task_close;在途的委派和作业结算或卡住时会自动叫醒你,不要等待或轮询。用最后一段回复写下这一步做了什么、证据和下一步。需要告知用户的内容用 task_report,其余默认静默。";
130
140
  /**
131
141
  * The turn input for one task step (spec 064, D15).
132
142
  *
@@ -138,11 +148,12 @@ const STEP_RULES = "回合结束即本步结束:等用户用 task_ask,等某
138
148
  export async function buildTaskStepBrief(input) {
139
149
  const { document, records } = input;
140
150
  const taskId = document.id;
141
- const sha = contractSha(document.body);
151
+ const tag = contractOpenTag(taskId, contractSha(document.body));
152
+ const contract = { tag, text: `${tag}\n${document.body.trim()}\n</task_contract>`, path: document.path };
142
153
  const now = input.now ?? Date.now();
143
154
  const blocks = [`[TASK_STEP:${taskId} #${input.seq}]`];
144
155
  if (input.full) {
145
- blocks.push(`${contractOpenTag(taskId, sha)}\n${document.body.trim()}\n</task_contract>`);
156
+ blocks.push(contract.text);
146
157
  blocks.push(`Task working files: ${join(input.deskDir, "work", taskId)}. Use this desk-local directory for intermediate files and command logs; do not reuse a shared absolute logs directory.`);
147
158
  const isFirstStep = !records.some((record) => record.kind === "step");
148
159
  if (isFirstStep && document.fields.origin) {
@@ -171,7 +182,10 @@ export async function buildTaskStepBrief(input) {
171
182
  }
172
183
  blocks.push(`<task_state>\n${renderState(document.fields, input.seq, input.pending)}\n</task_state>`);
173
184
  if (input.full) {
174
- blocks.push(`契约文件:${document.path}\n首次执行前读取 ${join(PLAYBOOKS_DIR, "task-lead.md")};已在当前上下文中读过则复用。\n${STEP_RULES}`);
185
+ blocks.push(`契约文件:${document.path}\n首次执行前读取 ${join(PLAYBOOKS_DIR, "task-lead.md")};已在当前上下文中读过则复用。`);
186
+ }
187
+ else {
188
+ blocks.push(`契约文件:${document.path}。如果上下文中没有完整契约,先读文件确认 Goal 和 DoD。`);
175
189
  }
176
- return { text: blocks.join("\n\n"), contractSha: sha };
190
+ return { text: blocks.join("\n\n"), contract };
177
191
  }
@@ -3,8 +3,10 @@ import { type TaskBudget } from "./frontmatter.js";
3
3
  /** What `/tasks` needs to say about a delivery channel (structurally `channel/channel-id.ts`'s `ChannelDescription`). */
4
4
  interface TaskChannelDescription {
5
5
  label: string;
6
- /** Still bound to this desk; false means the task is frozen (spec 058, D8). */
6
+ /** Still bound to this desk; false means outbound deliveries are held until rebound or adopted. */
7
7
  boundHere: boolean;
8
+ /** Whether the channel's transport is active in this process; false freezes execution (spec 061, INV-8). */
9
+ reachable?: boolean;
8
10
  }
9
11
  export interface HandleTasksCommandOptions {
10
12
  args: string;
@@ -30,6 +32,9 @@ type TasksCommand = {
30
32
  action: "archive";
31
33
  } | {
32
34
  action: "doctor";
35
+ } | {
36
+ action: "adopt";
37
+ id: string;
33
38
  } | {
34
39
  action: "pause";
35
40
  id: string;
@@ -18,6 +18,7 @@ import { normalizeTaskId, readActiveTasks } from "./contract.js";
18
18
  import { readTaskDeliveries } from "./delivery.js";
19
19
  import { taskStateLabel } from "./frontmatter.js";
20
20
  import { readTaskLog, renderTaskLogLineForUser, taskArchiveLogPath, taskLogIsArchived, taskLogIssues, taskLogPath, } from "./loop-log.js";
21
+ import { formatRetainedWorktreeLines } from "./receipts.js";
21
22
  import { archivedTaskPath, readStoredTask, taskPath } from "./store.js";
22
23
  /** `/tasks show <id>` contract excerpt; the full file is always readable at its own path. */
23
24
  const TASK_SHOW_CONTRACT_CHARS = 500;
@@ -59,7 +60,7 @@ export function parseTasksCommand(args) {
59
60
  throw new Error(`用法:/tasks ${action}`);
60
61
  return { action };
61
62
  }
62
- if (action === "show" || action === "pause" || action === "log" || action === "cancel") {
63
+ if (action === "show" || action === "adopt" || action === "pause" || action === "log" || action === "cancel") {
63
64
  const id = parts[1];
64
65
  if (!id || parts.length > 2)
65
66
  throw new Error(`用法:/tasks ${action} <id>`);
@@ -95,8 +96,10 @@ function deliveryNote(channel, options) {
95
96
  if (!channel)
96
97
  return "已冻结:未指定汇报频道";
97
98
  const described = options.describeChannel(channel);
99
+ if (described.reachable === false)
100
+ return `已冻结:汇报频道当前不可达(${described.label};可用 \`/tasks adopt\` 接管到当前频道)`;
98
101
  if (!described.boundHere)
99
- return `已冻结:汇报频道未绑定到本工位(${described.label})`;
102
+ return `汇报暂存:原汇报频道未绑定到本工位(${described.label};切回后自动送达,或用 \`/tasks adopt\` 接管到当前频道)`;
100
103
  return channel === options.currentChannelId ? undefined : `汇报到${described.label}`;
101
104
  }
102
105
  /** The state in the user's words, with how long it has been so and what is happening right now. */
@@ -197,8 +200,9 @@ async function showTask(options, idInput) {
197
200
  const channel = document.fields.channel;
198
201
  if (!document.fields.outcome) {
199
202
  const note = deliveryNote(channel, options);
203
+ const noteSuffix = note?.startsWith("已冻结") || note?.startsWith("汇报暂存") ? `(${note})` : "";
200
204
  head.push(channel
201
- ? `- 汇报频道(channel):${options.describeChannel(channel).label}${note?.startsWith("已冻结") ? `(${note})` : ""}`
205
+ ? `- 汇报频道(channel):${options.describeChannel(channel).label}${noteSuffix}`
202
206
  : `- 汇报频道:未指定(${note})`);
203
207
  }
204
208
  if (document.fields.paused) {
@@ -292,6 +296,18 @@ async function showTaskLog(deskDir, idInput) {
292
296
  lines.push("", `更早的记录在 \`${path}\``);
293
297
  return capReply(lines.join("\n"), { nextStepHint: `完整记录在 \`${path}\`` }).text;
294
298
  }
299
+ async function adoptTask(options, idInput) {
300
+ const id = normalizeTaskId(idInput);
301
+ if (!options.control.adopt) {
302
+ return "当前环境不支持接管任务汇报频道。";
303
+ }
304
+ const outcome = await options.control.adopt(options.desk, id, options.currentChannelId);
305
+ if (outcome.kind === "not_found")
306
+ return notFound(id);
307
+ if (outcome.kind === "unchanged")
308
+ return `任务 \`${id}\` 的汇报频道已经是当前频道。`;
309
+ return `已将任务 \`${id}\` 的汇报频道切换到当前频道,后台调度将继续推进。`;
310
+ }
295
311
  async function pauseTask(options, idInput) {
296
312
  const id = normalizeTaskId(idInput);
297
313
  const outcome = await options.control.pause(options.desk, id, {
@@ -332,7 +348,8 @@ async function cancelTask(options, idInput) {
332
348
  const stopped = outcome.cancelled.length > 0
333
349
  ? `,并取消了在途工作 ${outcome.cancelled.map((ref) => `\`${ref}\``).join("、")}`
334
350
  : "";
335
- return `已取消任务 \`${id}\`${stopped}。任务记录已归档,可用 \`/tasks log ${id}\` 查看。`;
351
+ const retained = formatRetainedWorktreeLines(outcome.retainedWorktrees);
352
+ return capReply([`已取消任务 \`${id}\`${stopped}。任务记录已归档,可用 \`/tasks log ${id}\` 查看。`, ...retained].join("\n"), { nextStepHint: `用 \`/tasks log ${id}\` 查看记录` }).text;
336
353
  }
337
354
  async function messageTask(options, idInput, text) {
338
355
  const id = normalizeTaskId(idInput);
@@ -355,7 +372,7 @@ async function messageTask(options, idInput, text) {
355
372
  case "held_paused":
356
373
  return `任务 \`${id}\` 已暂停:消息已记下,恢复(\`/tasks resume ${id}\`)后下一步会看到。`;
357
374
  case "held_frozen":
358
- return `任务 \`${id}\` 的汇报频道未绑定到本工位,任务已冻结:消息已记下,频道绑定回来后下一步会看到。`;
375
+ return `任务 \`${id}\` 的汇报频道当前不可达,任务已冻结:消息已记下,渠道恢复或用 \`/tasks adopt ${id}\` 接管后下一步会看到。`;
359
376
  }
360
377
  }
361
378
  function issue(problem, nextStep) {
@@ -382,8 +399,14 @@ async function doctor(options) {
382
399
  if (!entry.fields.channel) {
383
400
  problems.push(issue(`\`${entry.id}\` 没有汇报频道(channel),已冻结`, `在 \`${taskPath(options.deskDir, entry.id)}\` 的文件头加一行 \`channel: <频道 ID>\``));
384
401
  }
385
- else if (!options.describeChannel(entry.fields.channel).boundHere) {
386
- problems.push(issue(`\`${entry.id}\` 的汇报频道没有绑定到本工位,已冻结`, "在那个频道里把它绑定回本工位,或把文件头的 `channel:` 改成本工位已绑定的频道"));
402
+ else {
403
+ const described = options.describeChannel(entry.fields.channel);
404
+ if (described.reachable === false) {
405
+ problems.push(issue(`\`${entry.id}\` 的汇报频道当前不可达,已冻结`, `开启对应渠道配置,或在本工位当前频道执行 \`/tasks adopt ${entry.id}\``));
406
+ }
407
+ else if (!described.boundHere) {
408
+ problems.push(issue(`\`${entry.id}\` 的汇报频道当前未绑定到本工位,汇报与提问暂存待送达`, `在那个频道里切回本工位,或在本工位当前频道执行 \`/tasks adopt ${entry.id}\``));
409
+ }
387
410
  }
388
411
  const waiting = entry.fields.waiting;
389
412
  const since = waiting?.kind === "work" ? parseLocalTime(waiting.since) : undefined;
@@ -449,6 +472,8 @@ async function dispatchTasksCommand(options, command) {
449
472
  return await showTaskLog(options.deskDir, command.id);
450
473
  case "archive":
451
474
  return await listArchive(options.deskDir);
475
+ case "adopt":
476
+ return await adoptTask(options, command.id);
452
477
  case "pause":
453
478
  return await pauseTask(options, command.id);
454
479
  case "resume":
@@ -71,9 +71,18 @@ export type TaskControlOutcome = {
71
71
  } | {
72
72
  kind: "stopping";
73
73
  };
74
+ /** A runtime-managed Git worktree that cannot safely be removed on task close. */
75
+ export interface RetainedWorktreeInfo {
76
+ runId: string;
77
+ path: string;
78
+ branch: string | null;
79
+ headSha: string;
80
+ reason: "dirty" | "unmerged" | "busy" | "unavailable";
81
+ }
74
82
  export type TaskCancelOutcome = {
75
83
  kind: "cancelled";
76
84
  cancelled: string[];
85
+ retainedWorktrees?: RetainedWorktreeInfo[];
77
86
  } | {
78
87
  kind: "not_found";
79
88
  };
@@ -95,6 +104,8 @@ export interface TaskControl {
95
104
  reason: string;
96
105
  }): Promise<TaskControlOutcome>;
97
106
  resume(desk: string, id: string, grants: Partial<TaskBudget>): Promise<TaskControlOutcome>;
107
+ /** Reassigns an active task's delivery `channel` to `channel` (e.g. unfreezing a task after a DM rebound). */
108
+ adopt?(desk: string, id: string, channel: string): Promise<TaskControlOutcome>;
98
109
  /** Stops the step, cancels the task's delegations and jobs, closes and archives. */
99
110
  cancel(desk: string, id: string, input: {
100
111
  by: "user";
@@ -14,6 +14,8 @@ export interface TaskDelivery {
14
14
  }
15
15
  export type TaskSender = (channel: string, text: string) => Promise<boolean>;
16
16
  export declare function readTaskDeliveries(deskDir: string): Promise<TaskDelivery[]>;
17
+ /** Retarget pending delivery records of `taskId` when `/tasks adopt` moves the task to a new channel. */
18
+ export declare function redirectTaskDeliveries(deskDir: string, taskId: string, channel: string): Promise<void>;
17
19
  /** Persist before any network operation; the same id joins the report and its receipt. */
18
20
  export declare function queueTaskReport(deskDir: string, taskId: string, seq: number, channel: string, text: string): Promise<TaskDelivery>;
19
21
  /** Caller holds the task lock; a stable close id makes retrying preparation idempotent. */
@@ -21,23 +21,111 @@ const pathFor = (deskDir, id) => {
21
21
  throw new Error("Invalid task delivery id; have the deployer inspect the delivery queue.");
22
22
  return join(directory(deskDir), `${id}.json`);
23
23
  };
24
- export async function readTaskDeliveries(deskDir) {
24
+ /** Faults are retained in place. A known owner fences only that task; an unknowable owner
25
+ * fences delivery globally because its FIFO predecessor relation cannot be established. */
26
+ async function scanDeliveries(deskDir) {
25
27
  let names;
26
28
  try {
27
29
  names = await readdir(directory(deskDir));
28
30
  }
29
31
  catch (error) {
30
32
  if (error.code === "ENOENT")
31
- return [];
33
+ return { messages: [], faults: [] };
32
34
  throw error;
33
35
  }
34
36
  const messages = [];
37
+ const faults = [];
35
38
  for (const name of names.filter((name) => name.endsWith(".json"))) {
36
- const message = await readDelivery(deskDir, name.slice(0, -5));
37
- if (message)
38
- messages.push(message);
39
+ try {
40
+ const message = await readDelivery(deskDir, name.slice(0, -5));
41
+ if (message)
42
+ messages.push(message);
43
+ }
44
+ catch (error) {
45
+ const taskId = undefined;
46
+ const path = join(directory(deskDir), name);
47
+ faults.push({ path, taskId, error });
48
+ }
49
+ }
50
+ // The report journal independently records ownership. It can still identify a file whose
51
+ // JSON is truncated or unreadable; never infer ownership from unparseable text fragments.
52
+ if (faults.length) {
53
+ const taskNames = new Set((await readdir(join(deskDir, "tasks"))).filter((name) => name.endsWith(".md")));
54
+ try {
55
+ for (const file of await readdir(join(deskDir, "tasks", "archive")))
56
+ if (file.endsWith(".md"))
57
+ taskNames.add(file);
58
+ }
59
+ catch (error) {
60
+ if (error.code !== "ENOENT")
61
+ throw error;
62
+ }
63
+ for (const file of taskNames) {
64
+ const taskId = file.slice(0, -3);
65
+ if (!validTaskId(taskId))
66
+ continue;
67
+ try {
68
+ const records = await readTaskLog(deskDir, taskId, { strict: true });
69
+ for (const fault of faults) {
70
+ if (!fault.taskId &&
71
+ records.some((record) => (record.kind === "report" || record.kind === "close") &&
72
+ fault.path ===
73
+ join(directory(deskDir), `${record.kind === "close" ? "close-" : ""}${record.id}.json`)))
74
+ fault.taskId = taskId;
75
+ }
76
+ }
77
+ catch (error) {
78
+ log.logWarn("tasks.delivery.owner_failed", "Delivery ownership lookup failed", {
79
+ reason: errorMessage(error),
80
+ fields: { taskId },
81
+ });
82
+ }
83
+ }
84
+ }
85
+ for (const { path, taskId, error } of faults)
86
+ log.logWarn("tasks.delivery.read_failed", "Task delivery read failed", {
87
+ reason: errorMessage(error),
88
+ fields: {
89
+ path,
90
+ taskId,
91
+ code: error.code,
92
+ classification: error instanceof InvalidDeliveryError ? "corrupt" : "io",
93
+ },
94
+ });
95
+ return { messages: messages.sort((a, b) => a.taskId.localeCompare(b.taskId) || a.order - b.order), faults };
96
+ }
97
+ export async function readTaskDeliveries(deskDir) {
98
+ const { messages, faults } = await scanDeliveries(deskDir);
99
+ if (faults.length)
100
+ throw new AggregateError(faults.map((fault) => fault.error), "Task delivery queue contains unreadable records; have the deployer inspect the logged paths.");
101
+ return messages;
102
+ }
103
+ /** Retarget pending delivery records of `taskId` when `/tasks adopt` moves the task to a new channel. */
104
+ export async function redirectTaskDeliveries(deskDir, taskId, channel) {
105
+ const { messages } = await scanDeliveries(deskDir);
106
+ for (const item of messages) {
107
+ if (item.taskId !== taskId || item.channel === channel)
108
+ continue;
109
+ await withFileLock(join(deskDir, ".locks", `delivery-${item.id}.lock`), async () => {
110
+ const current = await readDelivery(deskDir, item.id);
111
+ if (!current || current.sentAt)
112
+ return;
113
+ await save(deskDir, { ...current, channel, nextAttemptAt: 0 });
114
+ }, { timeoutMs: 10_000 });
115
+ }
116
+ }
117
+ class InvalidDeliveryError extends Error {
118
+ constructor(path, cause) {
119
+ super(`Invalid task delivery: ${path}; have the deployer inspect it before retrying.`, { cause });
120
+ }
121
+ }
122
+ function validTaskId(value) {
123
+ try {
124
+ return normalizeTaskId(value) === value;
125
+ }
126
+ catch {
127
+ return false;
39
128
  }
40
- return messages.sort((a, b) => a.taskId.localeCompare(b.taskId) || a.order - b.order);
41
129
  }
42
130
  async function readDelivery(deskDir, id) {
43
131
  const path = pathFor(deskDir, id);
@@ -50,21 +138,31 @@ async function readDelivery(deskDir, id) {
50
138
  return undefined;
51
139
  throw error;
52
140
  }
53
- const value = JSON.parse(raw);
141
+ let value;
142
+ try {
143
+ value = JSON.parse(raw);
144
+ }
145
+ catch (error) {
146
+ throw new InvalidDeliveryError(path, error);
147
+ }
54
148
  if (!isPlainObject(value) ||
55
149
  value.id !== id ||
56
150
  typeof value.taskId !== "string" ||
57
- normalizeTaskId(value.taskId) !== value.taskId ||
151
+ !validTaskId(value.taskId) ||
58
152
  typeof value.channel !== "string" ||
59
153
  (value.kind !== "report" && value.kind !== "receipt") ||
60
154
  typeof value.text !== "string" ||
61
155
  typeof value.createdAt !== "string" ||
62
- !Number.isInteger(value.order) ||
63
- !Number.isFinite(value.attempts) ||
156
+ !Number.isSafeInteger(value.order) ||
157
+ value.order < 0 ||
158
+ !Number.isSafeInteger(value.attempts) ||
159
+ value.attempts < 0 ||
64
160
  !Number.isFinite(value.nextAttemptAt) ||
65
- (value.kind === "report" && !Number.isInteger(value.seq)) ||
66
- (value.sentAt !== undefined && typeof value.sentAt !== "string")) {
67
- throw new Error(`Invalid task delivery: ${path}; have the deployer inspect it before retrying.`);
161
+ value.nextAttemptAt < 0 ||
162
+ !Number.isFinite(Date.parse(value.createdAt)) ||
163
+ (value.kind === "report" && (!Number.isSafeInteger(value.seq) || value.seq < 1)) ||
164
+ (value.sentAt !== undefined && (typeof value.sentAt !== "string" || !Number.isFinite(Date.parse(value.sentAt))))) {
165
+ throw new InvalidDeliveryError(path);
68
166
  }
69
167
  return value;
70
168
  }
@@ -91,8 +189,9 @@ export async function queueTaskReport(deskDir, taskId, seq, channel, text) {
91
189
  throw new RecoverableToolError(`Task "${taskId}" is no longer accepting reports. End this step and inspect task_list before starting further work.`);
92
190
  }
93
191
  const records = await readTaskLog(deskDir, taskId, { strict: true });
94
- const queued = (await readTaskDeliveries(deskDir)).filter((record) => record.taskId === taskId && record.kind === "report");
95
- message.order = Math.max(seq * 4 + records.filter((record) => record.kind === "report" && record.seq === seq).length, ...queued.map((record) => record.order + 1));
192
+ const queued = (await scanDeliveries(deskDir)).messages.filter((record) => record.taskId === taskId && record.kind === "report");
193
+ const reports = records.filter((record) => record.kind === "report");
194
+ message.order = Math.max(...reports.map((record) => record.seq * 4 + reports.length), seq * 4 + records.filter((record) => record.kind === "report" && record.seq === seq).length, ...queued.map((record) => record.order + 1));
96
195
  await save(deskDir, message);
97
196
  await recordReport(deskDir, message);
98
197
  });
@@ -207,14 +306,35 @@ export async function deliverTaskMessage(deskDir, id, send, now = Date.now()) {
207
306
  export async function drainTaskDeliveries(deskDir, send, allowed, now = Date.now()) {
208
307
  const blocked = new Set();
209
308
  let next;
210
- for (const message of await readTaskDeliveries(deskDir)) {
211
- if (blocked.has(message.taskId) || !allowed(message.channel))
309
+ const { messages, faults } = await scanDeliveries(deskDir);
310
+ if (faults.length)
311
+ next = now + RETRY_MIN_MS;
312
+ if (faults.some((fault) => !fault.taskId))
313
+ return next;
314
+ for (const fault of faults)
315
+ blocked.add(fault.taskId);
316
+ for (const message of messages) {
317
+ if (blocked.has(message.taskId))
318
+ continue;
319
+ if (!allowed(message.channel)) {
320
+ blocked.add(message.taskId);
212
321
  continue;
213
- if (!(await deliverTaskMessage(deskDir, message.id, send, now))) {
322
+ }
323
+ try {
324
+ if (!(await deliverTaskMessage(deskDir, message.id, send, now))) {
325
+ blocked.add(message.taskId);
326
+ const current = await readDelivery(deskDir, message.id);
327
+ const at = Math.max(now + 1_000, current?.nextAttemptAt ?? now + RETRY_MIN_MS);
328
+ next = Math.min(next ?? at, at);
329
+ }
330
+ }
331
+ catch (error) {
214
332
  blocked.add(message.taskId);
215
- const current = await readDelivery(deskDir, message.id);
216
- const at = Math.max(now + 1_000, current?.nextAttemptAt ?? now + RETRY_MIN_MS);
217
- next = Math.min(next ?? at, at);
333
+ next = Math.min(next ?? now + RETRY_MIN_MS, now + RETRY_MIN_MS);
334
+ log.logWarn("tasks.delivery.drain_failed", "Task delivery drain failed", {
335
+ reason: errorMessage(error),
336
+ fields: { taskId: message.taskId, deliveryId: message.id, path: pathFor(deskDir, message.id) },
337
+ });
218
338
  }
219
339
  }
220
340
  return next;
@@ -87,6 +87,16 @@ export interface TaskSettleRecord {
87
87
  tail?: string;
88
88
  /** A run's working directory afterwards (`git status --porcelain`), as the completion wake shows it. */
89
89
  changed?: string;
90
+ /** Structured summary when a bound write delegation executed in a runtime-managed Git worktree. */
91
+ worktree?: {
92
+ path: string;
93
+ baseHead?: string;
94
+ branch: string | null;
95
+ headSha: string;
96
+ changedFiles: string[];
97
+ dirty?: boolean;
98
+ cleaned?: boolean;
99
+ };
90
100
  exitCode?: number;
91
101
  durationMs?: number;
92
102
  /**
@@ -172,6 +182,8 @@ export declare function taskLogPath(deskDir: string, id: string): string;
172
182
  export declare function taskArchiveLogPath(deskDir: string, id: string): string;
173
183
  /** True when the loop log for `id` lives only in the archive (the task is closed). */
174
184
  export declare function taskLogIsArchived(deskDir: string, id: string): boolean;
185
+ /** Close and evict a single task's cached appender once its log has moved to `tasks/archive/`. */
186
+ export declare function closeTaskLogAppender(deskDir: string, id: string): Promise<void>;
175
187
  /** Test seam: drop cached appenders so a temp-dir fixture does not leak into the next case. */
176
188
  export declare function resetTaskLogAppenders(): Promise<void>;
177
189
  type OmitTs<T> = T extends unknown ? Omit<T, "ts"> : never;
@@ -66,6 +66,15 @@ function appenderFor(path, deskDir, id) {
66
66
  appenders.set(path, appender);
67
67
  return appender;
68
68
  }
69
+ /** Close and evict a single task's cached appender once its log has moved to `tasks/archive/`. */
70
+ export async function closeTaskLogAppender(deskDir, id) {
71
+ const path = taskLogPath(deskDir, id);
72
+ const appender = appenders.get(path);
73
+ if (!appender)
74
+ return;
75
+ appenders.delete(path);
76
+ await appender.close();
77
+ }
69
78
  /** Test seam: drop cached appenders so a temp-dir fixture does not leak into the next case. */
70
79
  export async function resetTaskLogAppenders() {
71
80
  const open = [...appenders.values()];
@@ -240,7 +249,7 @@ export function renderTaskLogLine(record) {
240
249
  case "dispatch":
241
250
  return `- ${at} 派发 ${record.ref}${record.item ? ` → ${record.item}` : ""}${record.agent ? ` (${record.agent}${record.purpose === "verify" ? ", verify" : ""})` : ""}`;
242
251
  case "settle":
243
- return `- ${at} 结算 ${record.ref}: ${record.status}${record.verdict ? ` VERDICT ${record.verdict.toUpperCase()}` : ""}${record.exitCode !== undefined ? ` exit ${record.exitCode}` : ""}${record.output ? ` · ${record.output}` : ""}`;
252
+ return `- ${at} 结算 ${record.ref}: ${record.status}${record.verdict ? ` VERDICT ${record.verdict.toUpperCase()}` : ""}${record.exitCode !== undefined ? ` exit ${record.exitCode}` : ""}${record.worktree && !record.worktree.cleaned ? ` · worktree ${record.worktree.branch ?? record.worktree.headSha.slice(0, 8)} (${record.worktree.changedFiles.length} files)` : ""}${record.output ? ` · ${record.output}` : ""}`;
244
253
  case "stall":
245
254
  return `- ${at} 卡顿 ${record.ref}: 已 ${record.silentMinutes} 分钟没有输出`;
246
255
  case "message":
@@ -1,3 +1,4 @@
1
+ import type { RetainedWorktreeInfo } from "./control.js";
1
2
  import type { TaskFrontmatter } from "./frontmatter.js";
2
3
  import type { GuardBreach } from "./state.js";
3
4
  /**
@@ -5,15 +6,18 @@ import type { GuardBreach } from "./state.js";
5
6
  * User copy under spec 053: Chinese, the four markers, no tool names or internal tags, and every
6
7
  * next step is something the user can type.
7
8
  */
9
+ /** A `task_report` message, tagged with its task id when the leader did not already name it. */
10
+ export declare function reportReceipt(id: string, text: string): string;
8
11
  /** A `task_ask` question, delivered once the step ends. */
9
12
  export declare function askReceipt(id: string, question: string): string;
10
13
  /** The runtime paused the task: budget, idle, timeout or errors. A budget stop says how to give it more. */
11
14
  export declare function pausedReceipt(id: string, title: string, reason: string, breach?: GuardBreach): string;
15
+ export declare function formatRetainedWorktreeLines(retained?: readonly RetainedWorktreeInfo[]): string[];
12
16
  export declare function completedReceipt(id: string, title: string, document: {
13
17
  fields: TaskFrontmatter;
14
18
  body: string;
15
- }, closedAt: string): string;
19
+ }, closedAt: string, retainedWorktrees?: readonly RetainedWorktreeInfo[]): string;
16
20
  /** The leader cancelled its own task. */
17
- export declare function cancelledByLeaderReceipt(id: string, title: string, note: string): string;
21
+ export declare function cancelledByLeaderReceipt(id: string, title: string, note: string, retainedWorktrees?: readonly RetainedWorktreeInfo[]): string;
18
22
  /** The user cancelled from another channel of the desk; the report channel should not be left wondering. */
19
- export declare function cancelledByUserReceipt(id: string, title: string): string;
23
+ export declare function cancelledByUserReceipt(id: string, title: string, retainedWorktrees?: readonly RetainedWorktreeInfo[]): string;
@@ -9,6 +9,12 @@ import { parseTaskItems } from "./contract.js";
9
9
  * User copy under spec 053: Chinese, the four markers, no tool names or internal tags, and every
10
10
  * next step is something the user can type.
11
11
  */
12
+ /** A `task_report` message, tagged with its task id when the leader did not already name it. */
13
+ export function reportReceipt(id, text) {
14
+ if (text.includes(id))
15
+ return text;
16
+ return `**任务 \`${id}\` 汇报**\n${text}`;
17
+ }
12
18
  /** A `task_ask` question, delivered once the step ends. */
13
19
  export function askReceipt(id, question) {
14
20
  return `⚠️ 任务 \`${id}\` 需要你的决定:${question}\n直接回复我,或用 \`/tasks msg ${id} <内容>\` 回答。`;
@@ -21,7 +27,25 @@ export function pausedReceipt(id, title, reason, breach) {
21
27
  `查看:\`/tasks show ${id}\`;${resume}:\`/tasks resume ${id}${grant}\`\n` +
22
28
  `不再需要:\`/tasks cancel ${id}\``);
23
29
  }
24
- export function completedReceipt(id, title, document, closedAt) {
30
+ export function formatRetainedWorktreeLines(retained) {
31
+ if (!retained || retained.length === 0)
32
+ return [];
33
+ const lines = retained.slice(0, 3).map((item) => {
34
+ const ref = item.branch ? `分支 \`${item.branch}\`` : `提交 \`${item.headSha.slice(0, 12)}\``;
35
+ const why = {
36
+ dirty: "含未提交改动",
37
+ unmerged: "含未合并提交",
38
+ busy: "仍有委派正在使用",
39
+ unavailable: "暂时无法确认状态",
40
+ }[item.reason];
41
+ return `- ⚠️ 保留工作树:\`${item.path}\`(委派 \`${item.runId}\`,${ref},${why})`;
42
+ });
43
+ if (retained.length > 3) {
44
+ lines.push(`- ⚠️ 另有 ${retained.length - 3} 个工作树已保留在本地仓库`);
45
+ }
46
+ return lines;
47
+ }
48
+ export function completedReceipt(id, title, document, closedAt, retainedWorktrees) {
25
49
  const usage = document.fields.usage;
26
50
  const since = usage ? parseLocalTime(usage.startedAt) : undefined;
27
51
  const end = parseLocalTime(closedAt);
@@ -36,13 +60,18 @@ export function completedReceipt(id, title, document, closedAt) {
36
60
  ...(items
37
61
  ? [`- 工作项:${items.done}/${items.total}${dropped.length > 0 ? `;已放弃:${dropped.join("、")}` : ""}`]
38
62
  : []),
63
+ ...formatRetainedWorktreeLines(retainedWorktrees),
39
64
  ].join("\n"), { nextStepHint: `用 \`/tasks show ${id}\` 查看详情` }).text;
40
65
  }
41
66
  /** The leader cancelled its own task. */
42
- export function cancelledByLeaderReceipt(id, title, note) {
43
- return `🛑 任务 \`${id}\`(${title})已取消:${truncate(note.replace(/\s+/g, " "), 160)}`;
67
+ export function cancelledByLeaderReceipt(id, title, note, retainedWorktrees) {
68
+ const retained = formatRetainedWorktreeLines(retainedWorktrees);
69
+ return capReply([`🛑 任务 \`${id}\`(${title})已取消:${truncate(note.replace(/\s+/g, " "), 160)}`, ...retained].join("\n"), { nextStepHint: `用 \`/tasks log ${id}\` 查看记录` }).text;
44
70
  }
45
71
  /** The user cancelled from another channel of the desk; the report channel should not be left wondering. */
46
- export function cancelledByUserReceipt(id, title) {
47
- return `🛑 任务 \`${id}\`(${title})已被取消。`;
72
+ export function cancelledByUserReceipt(id, title, retainedWorktrees) {
73
+ const retained = formatRetainedWorktreeLines(retainedWorktrees);
74
+ return capReply([`🛑 任务 \`${id}\`(${title})已被取消。`, ...retained].join("\n"), {
75
+ nextStepHint: `用 \`/tasks log ${id}\` 查看记录`,
76
+ }).text;
48
77
  }
@@ -10,6 +10,9 @@ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.j
10
10
  * Callers that legitimately need longer must pass an explicit `timeout`.
11
11
  */
12
12
  export declare const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
13
+ export declare const BASH_MAX_OUTPUT_BYTES: number;
14
+ export declare const BASH_MAX_OUTPUT_LINES = 1000;
15
+ export declare function formatFullOutputHint(path: string): string;
13
16
  declare const bashSchema: Type.TObject<{
14
17
  command: Type.TString;
15
18
  timeout: Type.TOptional<Type.TInteger>;