@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
@@ -10,9 +10,10 @@ import * as log from "../log.js";
10
10
  import { writeFileAtomically } from "../shared/atomic-file.js";
11
11
  import { createSerialQueue } from "../shared/serial-queue.js";
12
12
  import { errorMessage } from "../shared/text-utils.js";
13
- import { isRecord } from "../shared/type-guards.js";
13
+ import { isPlainObject } from "../shared/type-guards.js";
14
14
  const DEFAULT_LEASE_MS = 15 * 60_000;
15
15
  const DEFAULT_INTERVAL_MS = 30_000;
16
+ const DEFAULT_EXHAUSTED_RETENTION_MS = 7 * 24 * 60 * 60_000;
16
17
  /** Total delivery attempts (crash-lease redelivery and `markRetryable` failures combined) before
17
18
  * a dispatch id is given up on as a poison pill rather than retried forever. */
18
19
  const MAX_DELIVERIES = 8;
@@ -96,31 +97,52 @@ function dispatchId(event) {
96
97
  .update(JSON.stringify([event.channelId, event.producer, event.ts, event.text]))
97
98
  .digest("hex");
98
99
  }
99
- function parseRecord(raw) {
100
+ class CorruptDispatchError extends Error {
101
+ }
102
+ function parseRecord(raw, id) {
103
+ let value;
100
104
  try {
101
- const value = JSON.parse(raw);
102
- if (!isRecord(value) ||
103
- value.version !== 1 ||
104
- typeof value.id !== "string" ||
105
- typeof value.createdAt !== "string" ||
106
- (value.status !== "pending" &&
107
- value.status !== "queued" &&
108
- value.status !== "running" &&
109
- value.status !== "exhausted") ||
110
- !isRecord(value.event) ||
111
- value.event.source !== "wake" ||
112
- typeof value.event.channelId !== "string" ||
113
- typeof value.event.producer !== "string" ||
114
- typeof value.event.text !== "string" ||
115
- typeof value.deliveries !== "number" ||
116
- (value.nextAttemptAt !== undefined && typeof value.nextAttemptAt !== "string")) {
117
- return undefined;
118
- }
119
- return value;
105
+ value = JSON.parse(raw);
120
106
  }
121
- catch {
122
- return undefined;
107
+ catch (cause) {
108
+ throw new CorruptDispatchError("Invalid dispatch JSON; have the deployer inspect the record.", { cause });
109
+ }
110
+ const date = (v) => typeof v === "string" && Number.isFinite(Date.parse(v));
111
+ if (!isPlainObject(value) ||
112
+ value.version !== 1 ||
113
+ value.id !== id ||
114
+ !date(value.createdAt) ||
115
+ typeof value.status !== "string" ||
116
+ !["pending", "queued", "running", "exhausted"].includes(value.status) ||
117
+ !isPlainObject(value.event) ||
118
+ value.event.source !== "wake" ||
119
+ typeof value.event.channelId !== "string" ||
120
+ !value.event.channelId ||
121
+ typeof value.event.desk !== "string" ||
122
+ !value.event.desk ||
123
+ typeof value.event.ts !== "string" ||
124
+ !value.event.ts ||
125
+ typeof value.event.producer !== "string" ||
126
+ !value.event.producer ||
127
+ (value.event.presentation !== undefined && value.event.presentation !== "awaited") ||
128
+ (value.event.images !== undefined &&
129
+ (!Array.isArray(value.event.images) ||
130
+ value.event.images.some((image) => !isPlainObject(image) ||
131
+ typeof image.path !== "string" ||
132
+ typeof image.mimeType !== "string" ||
133
+ !Number.isSafeInteger(image.byteSize) ||
134
+ image.byteSize < 0 ||
135
+ (image.unsupportedFormat !== undefined && typeof image.unsupportedFormat !== "boolean")))) ||
136
+ typeof value.event.text !== "string" ||
137
+ value.event.dispatchId !== id ||
138
+ !Number.isSafeInteger(value.deliveries) ||
139
+ value.deliveries < 0 ||
140
+ (value.nextAttemptAt !== undefined && !date(value.nextAttemptAt)) ||
141
+ (value.leaseExpiresAt !== undefined && !date(value.leaseExpiresAt)) ||
142
+ (value.exhaustedAt !== undefined && !date(value.exhaustedAt))) {
143
+ throw new CorruptDispatchError("Invalid dispatch structure; have the deployer inspect the record.");
123
144
  }
145
+ return value;
124
146
  }
125
147
  /**
126
148
  * Tiny file-backed outbox for synthetic work. It intentionally provides
@@ -129,12 +151,24 @@ function parseRecord(raw) {
129
151
  * channel queue.
130
152
  */
131
153
  export class DurableDispatchService {
154
+ run(id, work) {
155
+ const pending = this.queue.run(id, work);
156
+ this.pendingWrites.add(pending);
157
+ void pending.finally(() => this.pendingWrites.delete(pending)).catch(() => undefined);
158
+ return pending;
159
+ }
160
+ /** stop() closes background admission; after active turns settle, wait for started writes
161
+ * before another process can acquire the daemon lock. A hung write keeps that lock retained. */
162
+ async flush() {
163
+ await Promise.allSettled([...this.pendingWrites]);
164
+ }
132
165
  constructor(options) {
133
166
  this.options = options;
134
167
  this.stopped = false;
135
168
  this.capacityRejected = new Map();
136
169
  this.capacityDrains = new Map();
137
170
  this.queue = createSerialQueue();
171
+ this.pendingWrites = new Set();
138
172
  this.timer = null;
139
173
  /**
140
174
  * Dispatch ids whose turn this process is still running (spec 031, D2).
@@ -155,6 +189,7 @@ export class DurableDispatchService {
155
189
  /** Bumped by `discardQueuedClaims`; lets an in-flight `absorbPending` notice that its closures were dropped. */
156
190
  this.discardEpoch = new Map();
157
191
  this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
192
+ this.exhaustedRetentionMs = options.exhaustedRetentionMs ?? DEFAULT_EXHAUSTED_RETENTION_MS;
158
193
  }
159
194
  start() {
160
195
  if (this.timer)
@@ -199,7 +234,12 @@ export class DurableDispatchService {
199
234
  for (const id of [...(this.capacityRejected.get(channelId) ?? [])]) {
200
235
  if (this.stopped)
201
236
  return;
202
- await this.drainRecord(id, Date.now());
237
+ try {
238
+ await this.drainRecord(id, Date.now());
239
+ }
240
+ catch (error) {
241
+ this.reportRecordFault(id, error);
242
+ }
203
243
  }
204
244
  } while (drain.dirty && !this.stopped);
205
245
  })()
@@ -226,6 +266,8 @@ export class DurableDispatchService {
226
266
  }
227
267
  }
228
268
  async dispatch(event) {
269
+ if (this.stopped)
270
+ return false;
229
271
  // Spec 058, D7: every in-process producer stamps its desk. An event without one cannot be
230
272
  // checked against the channel's binding at admission, so it is refused here, at the door.
231
273
  if (!event.desk) {
@@ -236,7 +278,7 @@ export class DurableDispatchService {
236
278
  return false;
237
279
  }
238
280
  const id = event.dispatchId ?? dispatchId(event);
239
- await this.queue.run(id, async () => {
281
+ await this.run(id, async () => {
240
282
  const existing = await this.read(id);
241
283
  if (existing)
242
284
  return;
@@ -268,27 +310,38 @@ export class DurableDispatchService {
268
310
  try {
269
311
  filenames = (await readdir(this.options.stateDir)).filter((name) => name.endsWith(".json"));
270
312
  }
271
- catch {
272
- return 0;
313
+ catch (error) {
314
+ if (error.code === "ENOENT")
315
+ return 0;
316
+ throw error;
273
317
  }
274
318
  let canceled = 0;
275
319
  for (const filename of filenames) {
276
- const id = decodeDispatchId(filename.slice(0, -".json".length));
277
- await this.queue.run(id, async () => {
278
- const record = await this.read(id);
279
- if (!record || record.event.channelId !== channelId)
280
- return;
281
- if (record.status !== "queued" && record.status !== "running")
282
- return;
283
- // Drop the liveness claim too, or the renew branch above would keep this record
284
- // alive forever and the cancelled turn would never be redelivered.
285
- this.running.delete(id);
286
- // `/stop` already dropped the queued closures; the redelivery must not be turned away.
287
- this.absorbed.delete(id);
288
- record.leaseExpiresAt = undefined;
289
- await this.write(record);
290
- canceled++;
291
- });
320
+ if (this.stopped)
321
+ break;
322
+ const id = this.idFromFilename(filename);
323
+ if (id === undefined)
324
+ continue;
325
+ try {
326
+ await this.run(id, async () => {
327
+ const record = await this.read(id);
328
+ if (!record || record.event.channelId !== channelId)
329
+ return;
330
+ if (record.status !== "queued" && record.status !== "running")
331
+ return;
332
+ // Drop the liveness claim too, or the renew branch above would keep this record
333
+ // alive forever and the cancelled turn would never be redelivered.
334
+ this.running.delete(id);
335
+ // `/stop` already dropped the queued closures; the redelivery must not be turned away.
336
+ this.absorbed.delete(id);
337
+ record.leaseExpiresAt = undefined;
338
+ await this.write(record);
339
+ canceled++;
340
+ });
341
+ }
342
+ catch (error) {
343
+ this.reportRecordFault(id, error);
344
+ }
292
345
  }
293
346
  return canceled;
294
347
  }
@@ -318,14 +371,14 @@ export class DurableDispatchService {
318
371
  return true;
319
372
  if (this.absorbed.delete(id))
320
373
  return false;
321
- this.running.add(id);
322
- await this.queue.run(id, async () => {
374
+ await this.run(id, async () => {
323
375
  const record = await this.read(id);
324
376
  if (!record)
325
377
  return;
326
378
  record.status = "running";
327
379
  record.leaseExpiresAt = new Date(Date.now() + this.leaseMs).toISOString();
328
380
  await this.write(record);
381
+ this.running.add(id);
329
382
  });
330
383
  return true;
331
384
  }
@@ -346,23 +399,32 @@ export class DurableDispatchService {
346
399
  try {
347
400
  filenames = (await readdir(this.options.stateDir)).filter((name) => name.endsWith(".json"));
348
401
  }
349
- catch {
350
- return [];
402
+ catch (error) {
403
+ if (error.code === "ENOENT")
404
+ return [];
405
+ throw error;
351
406
  }
352
407
  const candidates = [];
353
408
  for (const filename of filenames) {
354
- const id = decodeDispatchId(filename.slice(0, -".json".length));
409
+ const id = this.idFromFilename(filename);
410
+ if (id === undefined)
411
+ continue;
355
412
  if (id === primaryId || this.running.has(id))
356
413
  continue;
357
- const record = await this.read(id);
358
- if (record && this.isAbsorbable(record, channelId, accept))
359
- candidates.push({ id, createdAt: record.createdAt });
414
+ try {
415
+ const record = await this.read(id);
416
+ if (record && this.isAbsorbable(record, channelId, accept))
417
+ candidates.push({ id, createdAt: record.createdAt });
418
+ }
419
+ catch (error) {
420
+ this.reportRecordFault(id, error);
421
+ }
360
422
  }
361
423
  candidates.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
362
424
  const events = [];
363
425
  for (const { id } of candidates.slice(0, limit)) {
364
426
  try {
365
- await this.queue.run(id, async () => {
427
+ await this.run(id, async () => {
366
428
  // Re-checked under the record's own lock: a drain or its own delivery may have moved it.
367
429
  const record = await this.read(id);
368
430
  if (!record || this.running.has(id) || !this.isAbsorbable(record, channelId, accept))
@@ -409,8 +471,16 @@ export class DurableDispatchService {
409
471
  return;
410
472
  this.running.delete(id);
411
473
  this.untrack(id);
412
- await this.queue.run(id, async () => {
413
- await unlink(recordPath(this.options.stateDir, id)).catch(() => undefined);
474
+ await this.run(id, async () => {
475
+ if (!(await this.read(id)))
476
+ return;
477
+ try {
478
+ await unlink(recordPath(this.options.stateDir, id));
479
+ }
480
+ catch (error) {
481
+ if (error.code !== "ENOENT")
482
+ throw error;
483
+ }
414
484
  });
415
485
  }
416
486
  /** Release a failed handler's in-process claim without deleting its durable record. Structured
@@ -426,7 +496,7 @@ export class DurableDispatchService {
426
496
  if (!id)
427
497
  return;
428
498
  this.running.delete(id);
429
- await this.queue.run(id, async () => {
499
+ await this.run(id, async () => {
430
500
  const record = await this.read(id);
431
501
  if (!record)
432
502
  return;
@@ -442,27 +512,73 @@ export class DurableDispatchService {
442
512
  try {
443
513
  filenames = (await readdir(this.options.stateDir)).filter((name) => name.endsWith(".json")).sort();
444
514
  }
445
- catch {
446
- return;
515
+ catch (error) {
516
+ if (error.code === "ENOENT")
517
+ return;
518
+ throw error;
447
519
  }
520
+ const candidates = [];
448
521
  for (const filename of filenames) {
449
- const id = decodeDispatchId(filename.slice(0, -".json".length));
450
- await this.drainRecord(id, now);
522
+ if (this.stopped)
523
+ break;
524
+ const id = this.idFromFilename(filename);
525
+ if (id === undefined)
526
+ continue;
527
+ try {
528
+ const record = await this.read(id);
529
+ if (record) {
530
+ candidates.push({ id, createdAtMs: Date.parse(record.createdAt), filename });
531
+ }
532
+ else {
533
+ this.untrack(id);
534
+ }
535
+ }
536
+ catch (error) {
537
+ this.reportRecordFault(id, error);
538
+ }
539
+ }
540
+ candidates.sort((a, b) => a.createdAtMs - b.createdAtMs || a.filename.localeCompare(b.filename));
541
+ for (const { id } of candidates) {
542
+ if (this.stopped)
543
+ break;
544
+ try {
545
+ await this.drainRecord(id, now);
546
+ }
547
+ catch (error) {
548
+ this.reportRecordFault(id, error);
549
+ }
451
550
  }
452
551
  }
453
552
  async drainRecord(id, now) {
454
- await this.queue.run(id, async () => {
553
+ if (this.stopped)
554
+ return;
555
+ await this.run(id, async () => {
556
+ if (this.stopped)
557
+ return;
455
558
  const record = await this.read(id);
559
+ if (this.stopped)
560
+ return;
456
561
  if (!record) {
457
562
  this.untrack(id);
458
563
  return;
459
564
  }
460
565
  if (record.status === "pending")
461
566
  this.trackRejected(record.event.channelId, id);
462
- // A poison pill: give up on redelivery for good, once. Left on disk (not deleted) so
463
- // `onExhausted`'s notice stays inspectable and the record is available for manual retry.
567
+ // A poison pill: give up on redelivery for good, once. Kept on disk during the retention
568
+ // window so `onExhausted`'s notice stays inspectable, then unlinked so dead-letter files
569
+ // do not accumulate across every future drain tick.
464
570
  if (record.status === "exhausted") {
465
571
  this.untrack(id);
572
+ const exhaustedSinceMs = Date.parse(record.exhaustedAt ?? record.createdAt);
573
+ if (now - exhaustedSinceMs >= this.exhaustedRetentionMs) {
574
+ try {
575
+ await unlink(recordPath(this.options.stateDir, id));
576
+ }
577
+ catch (error) {
578
+ if (error.code !== "ENOENT")
579
+ throw error;
580
+ }
581
+ }
466
582
  return;
467
583
  }
468
584
  // The turn is still running in this process: renew its lease rather than treating a
@@ -490,6 +606,7 @@ export class DurableDispatchService {
490
606
  return;
491
607
  if (record.deliveries >= MAX_DELIVERIES) {
492
608
  record.status = "exhausted";
609
+ record.exhaustedAt = new Date(now).toISOString();
493
610
  this.untrack(id);
494
611
  record.leaseExpiresAt = undefined;
495
612
  record.nextAttemptAt = undefined;
@@ -528,13 +645,38 @@ export class DurableDispatchService {
528
645
  await this.write(record);
529
646
  });
530
647
  }
648
+ idFromFilename(filename) {
649
+ const id = decodeDispatchId(filename.slice(0, -".json".length));
650
+ if (`${encodeDispatchId(id)}.json` === filename)
651
+ return id;
652
+ log.logWarn("dispatch.record.failed", "Dispatch record failed", {
653
+ reason: "Invalid dispatch filename; have the deployer inspect the record.",
654
+ fields: { path: join(this.options.stateDir, filename), classification: "corrupt" },
655
+ });
656
+ return undefined;
657
+ }
658
+ reportRecordFault(id, error) {
659
+ log.logWarn("dispatch.record.failed", "Dispatch record failed", {
660
+ reason: errorMessage(error),
661
+ fields: {
662
+ dispatchId: id,
663
+ path: recordPath(this.options.stateDir, id),
664
+ classification: error instanceof CorruptDispatchError ? "corrupt" : "io",
665
+ code: error.code,
666
+ },
667
+ });
668
+ }
531
669
  async read(id) {
670
+ let raw;
532
671
  try {
533
- return parseRecord(await readFile(recordPath(this.options.stateDir, id), "utf-8"));
672
+ raw = await readFile(recordPath(this.options.stateDir, id), "utf-8");
534
673
  }
535
- catch {
536
- return undefined;
674
+ catch (error) {
675
+ if (error.code === "ENOENT")
676
+ return undefined;
677
+ throw error;
537
678
  }
679
+ return parseRecord(raw, id);
538
680
  }
539
681
  async write(record) {
540
682
  await writeFileAtomically(recordPath(this.options.stateDir, record.id), `${JSON.stringify(record)}\n`);
@@ -96,21 +96,29 @@ export function createBusyHandlers(deps, queues) {
96
96
  * output is ended at once (the card is closed, late events dropped).
97
97
  */
98
98
  function abortTurn(channelId, runner) {
99
+ if (isShuttingDown())
100
+ return;
99
101
  runner.requestStop();
100
102
  void runner.abort().catch((err) => {
101
- log.logWarn("agent.turn.abort_failed", "Turn abort failed", {
102
- channelId: channelId,
103
- reason: errorMessage(err),
104
- });
103
+ if (!isShuttingDown())
104
+ log.logWarn("agent.turn.abort_failed", "Turn abort failed", {
105
+ channelId: channelId,
106
+ reason: errorMessage(err),
107
+ });
105
108
  });
106
- if (stopWatchdogs.has(channelId))
109
+ const generation = runner.getTurnStatus().generation;
110
+ const existing = stopWatchdogs.get(channelId);
111
+ if (existing?.runner === runner && existing.generation === generation)
107
112
  return;
108
- stopWatchdogs.add(channelId);
113
+ const registration = { runner, generation };
114
+ stopWatchdogs.set(channelId, registration);
109
115
  void forceEndStuckTurnAfterStop({
110
116
  channelId,
111
117
  runner,
112
118
  graceMs: options.stopForceEndGraceMs,
113
- isCurrent: () => channelRunners.get(channelId) === runner,
119
+ isCurrent: () => !isShuttingDown() &&
120
+ stopWatchdogs.get(channelId) === registration &&
121
+ channelRunners.get(channelId) === runner,
114
122
  recover: () => {
115
123
  runner.retireForRecovery();
116
124
  channelRunners.delete(channelId);
@@ -126,7 +134,8 @@ export function createBusyHandlers(deps, queues) {
126
134
  });
127
135
  })
128
136
  .finally(() => {
129
- stopWatchdogs.delete(channelId);
137
+ if (!isShuttingDown() && stopWatchdogs.get(channelId) === registration)
138
+ stopWatchdogs.delete(channelId);
130
139
  });
131
140
  }
132
141
  /** One message's turn is no longer wanted (its caller cancelled or left): abort only that turn. */
@@ -30,6 +30,12 @@ function lazyTaskControl(get) {
30
30
  message: (...args) => control().message(...args),
31
31
  pause: (...args) => control().pause(...args),
32
32
  resume: (...args) => control().resume(...args),
33
+ adopt: (desk, id, channel) => {
34
+ const current = control();
35
+ if (!current.adopt)
36
+ throw new Error("当前环境不支持接管任务汇报频道。");
37
+ return current.adopt(desk, id, channel);
38
+ },
33
39
  cancel: (...args) => control().cancel(...args),
34
40
  };
35
41
  }
@@ -39,16 +45,30 @@ export function createCommandHandlers(deps, resetChannelQueue) {
39
45
  text,
40
46
  ...(event.source === "human" && event.ref !== undefined ? { ref: event.ref } : {}),
41
47
  });
42
- /** The desk port a command runs with: a sender limited to some desks may bind only to those. */
48
+ /** The desk port a command runs with: a sender limited to some desks may bind/archive only those. */
43
49
  const deskPortFor = (event) => {
44
50
  const port = deskPort(event.channelId);
45
51
  const allowed = event.source === "human" ? event.allowedDesks : undefined;
46
- const bind = port.bind;
47
- if (!allowed || !bind)
52
+ if (!allowed)
48
53
  return port;
54
+ const { bind, archive, unarchive } = port;
49
55
  return {
50
56
  ...port,
51
- bind: async (name) => allowed.includes(name) ? bind(name) : { kind: "forbidden", desk: name },
57
+ ...(bind
58
+ ? {
59
+ bind: async (name) => allowed.includes(name) ? bind(name) : { kind: "forbidden", desk: name },
60
+ }
61
+ : {}),
62
+ ...(archive
63
+ ? {
64
+ archive: async (name) => allowed.includes(name) ? archive(name) : { kind: "forbidden", desk: name },
65
+ }
66
+ : {}),
67
+ ...(unarchive
68
+ ? {
69
+ unarchive: async (name) => allowed.includes(name) ? unarchive(name) : { kind: "forbidden", desk: name },
70
+ }
71
+ : {}),
52
72
  };
53
73
  };
54
74
  /** `/new` bypasses the old per-channel queue and live SDK session. */
@@ -32,7 +32,10 @@ export interface IngressDeps {
32
32
  channelRunners: Map<string, AgentRunner>;
33
33
  sessionResetChains: Map<string, Promise<void>>;
34
34
  activeTasks: Set<Promise<void>>;
35
- stopWatchdogs: Set<string>;
35
+ stopWatchdogs: Map<string, {
36
+ runner: AgentRunner;
37
+ generation?: number;
38
+ }>;
36
39
  channelIndex: ChannelIndex;
37
40
  archiveIncomingMessage: (channelId: string, message: ArchivedMessage, contextLabel: string) => Promise<void>;
38
41
  /** The channel's runner; `undefined` when it is not bound to an available desk — none is ever built then. */
@@ -27,7 +27,12 @@ export function createIngress(deps) {
27
27
  let queue = queues.get(channelId);
28
28
  if (!queue) {
29
29
  queue = new ChannelQueue((current) => {
30
- if (stopped || isShuttingDown() || deps.stopWatchdogs.has(channelId) || queues.get(channelId) !== current)
30
+ const watchdog = deps.stopWatchdogs.get(channelId);
31
+ const runner = channelRunners.get(channelId);
32
+ if (stopped ||
33
+ isShuttingDown() ||
34
+ (watchdog && watchdog.runner === runner && watchdog.generation === runner?.getTurnStatus().generation) ||
35
+ queues.get(channelId) !== current)
31
36
  return;
32
37
  deps.getDurableDispatch()?.notifyCapacity(channelId);
33
38
  });
@@ -56,14 +56,15 @@ export function createRequestExecution(deps) {
56
56
  });
57
57
  }
58
58
  finally {
59
- runner.endTurn();
60
- try {
61
- await runner.dispose();
62
- }
63
- finally {
64
- running.delete(message.channelId);
59
+ // Detach from shared maps before `endTurn()` flips `isBusy()` to false and before
60
+ // `dispose()` awaits, so `evictIdleRunnersOverCap` / `shutdown` can never double-dispose
61
+ // a request-scoped runner or count an ended request against chat's idle LRU cap.
62
+ running.delete(message.channelId);
63
+ if (deps.runners.get(message.channelId) === runner) {
65
64
  deps.runners.delete(message.channelId);
66
65
  }
66
+ runner.endTurn();
67
+ await runner.dispose();
67
68
  }
68
69
  };
69
70
  const task = run();
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Ordered daemon shutdown: stop the schedulers, stop admission (the transports still deliver), wait
3
3
  * for active turns (aborting them past a grace window), dispose idle runners, close the transports,
4
- * then flush storage and logs. Idempotent: every
4
+ * then drain credential writes and flush storage and logs. Idempotent: every
5
5
  * call after the first returns the first call's promise.
6
6
  */
7
7
  import type { AgentRunner } from "../agent/types.js";
@@ -13,6 +13,7 @@ export interface ShutdownDeps {
13
13
  };
14
14
  getDurableDispatch: () => {
15
15
  stop(): void;
16
+ flush?(): Promise<void>;
16
17
  } | undefined;
17
18
  memoryMaintenanceScheduler: {
18
19
  stop(): void;
@@ -39,6 +40,8 @@ export interface ShutdownDeps {
39
40
  channelIndex: ChannelIndex;
40
41
  channelRunners: Map<string, AgentRunner>;
41
42
  activeTasks: Set<Promise<void>>;
43
+ /** Includes auth still finishing after a cancelled request, evicted runner or detached sidecar. */
44
+ flushCredentials: () => Promise<void>;
42
45
  /** Flips the runtime's `isShuttingDown()` the moment shutdown begins. */
43
46
  markShuttingDown: () => void;
44
47
  /** Frees `state/daemon.lock`, last of all: until then no other runtime may open this app home. */