@oyasmi/pipiclaw 0.9.5-beta.2 → 0.9.5-beta.3

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 (272) hide show
  1. package/README.en.md +9 -11
  2. package/README.md +9 -11
  3. package/dist/agent/channel-runner.d.ts +12 -24
  4. package/dist/agent/channel-runner.js +74 -30
  5. package/dist/agent/maintenance-context.d.ts +2 -0
  6. package/dist/agent/maintenance-context.js +15 -0
  7. package/dist/agent/prompt/sections.js +8 -6
  8. package/dist/agent/prompt/types.d.ts +1 -1
  9. package/dist/agent/runner-factory.js +1 -1
  10. package/dist/agent/session/command-extension.js +11 -0
  11. package/dist/agent/session/compaction-summary.js +6 -2
  12. package/dist/agent/session/execution-trace.d.ts +14 -0
  13. package/dist/agent/session/execution-trace.js +57 -0
  14. package/dist/agent/session/session-events.d.ts +2 -7
  15. package/dist/agent/session/session-events.js +35 -12
  16. package/dist/agent/session/session-host.d.ts +12 -22
  17. package/dist/agent/session/session-host.js +46 -65
  18. package/dist/agent/turn/task-digest.d.ts +1 -2
  19. package/dist/agent/turn/task-digest.js +33 -33
  20. package/dist/agent/turn/turn-context.d.ts +1 -1
  21. package/dist/agent/turn/turn-context.js +1 -1
  22. package/dist/agent/turn/turn-finish.d.ts +2 -2
  23. package/dist/agent/turn/turn-finish.js +3 -2
  24. package/dist/agent/turn/turn-pipeline.d.ts +4 -2
  25. package/dist/agent/turn/turn-pipeline.js +33 -5
  26. package/dist/agent/types.d.ts +64 -14
  27. package/dist/agent/types.js +3 -0
  28. package/dist/app/home.js +3 -4
  29. package/dist/channel/channel-event.d.ts +4 -12
  30. package/dist/channel/ingress.d.ts +1 -9
  31. package/dist/channel/store.d.ts +1 -1
  32. package/dist/commands/catalog.js +25 -19
  33. package/dist/commands/router.d.ts +5 -2
  34. package/dist/commands/router.js +9 -4
  35. package/dist/config/settings.d.ts +5 -12
  36. package/dist/config/settings.js +0 -7
  37. package/dist/config/tools.d.ts +2 -2
  38. package/dist/config/tools.js +2 -2
  39. package/dist/dingtalk/bot.d.ts +2 -0
  40. package/dist/dingtalk/bot.js +4 -0
  41. package/dist/dingtalk/cards.d.ts +7 -0
  42. package/dist/dingtalk/cards.js +32 -2
  43. package/dist/dingtalk/delivery.d.ts +5 -1
  44. package/dist/dingtalk/delivery.js +157 -142
  45. package/dist/dingtalk/progress.d.ts +55 -6
  46. package/dist/dingtalk/progress.js +195 -16
  47. package/dist/file-store.d.ts +4 -0
  48. package/dist/file-store.js +6 -1
  49. package/dist/jobs/completion-observer.d.ts +20 -0
  50. package/dist/jobs/completion-observer.js +107 -0
  51. package/dist/jobs/completion-signal.d.ts +9 -0
  52. package/dist/jobs/completion-signal.js +32 -0
  53. package/dist/jobs/completion-wake.d.ts +1 -1
  54. package/dist/jobs/completion-wake.js +2 -13
  55. package/dist/jobs/manager.d.ts +11 -29
  56. package/dist/jobs/manager.js +103 -176
  57. package/dist/jobs/probe.d.ts +3 -0
  58. package/dist/jobs/probe.js +42 -0
  59. package/dist/jobs/record.d.ts +3 -6
  60. package/dist/jobs/runtime.d.ts +28 -0
  61. package/dist/jobs/runtime.js +69 -0
  62. package/dist/memory/boundary-work.d.ts +2 -0
  63. package/dist/memory/boundary-work.js +79 -37
  64. package/dist/memory/commands.js +4 -1
  65. package/dist/memory/index-budget.js +18 -15
  66. package/dist/memory/journal.js +2 -1
  67. package/dist/memory/lifecycle.d.ts +4 -8
  68. package/dist/memory/lifecycle.js +21 -51
  69. package/dist/memory/reflect-job.d.ts +0 -6
  70. package/dist/memory/reflect-job.js +13 -34
  71. package/dist/memory/reflect.d.ts +4 -0
  72. package/dist/memory/reflect.js +32 -5
  73. package/dist/memory/review-log.d.ts +13 -0
  74. package/dist/memory/review-log.js +49 -0
  75. package/dist/memory/search.js +7 -4
  76. package/dist/memory/source-window.d.ts +18 -1
  77. package/dist/memory/source-window.js +59 -9
  78. package/dist/memory/store.d.ts +2 -0
  79. package/dist/memory/store.js +45 -13
  80. package/dist/playbooks/agent-delegation.md +10 -4
  81. package/dist/playbooks/background-jobs.md +4 -4
  82. package/dist/playbooks/event-scheduling.md +2 -2
  83. package/dist/playbooks/memory-and-learning.md +3 -3
  84. package/dist/playbooks/outbound-media.md +2 -2
  85. package/dist/playbooks/runtime-orientation.md +10 -6
  86. package/dist/playbooks/task-lead.md +54 -33
  87. package/dist/runtime/bootstrap.d.ts +11 -24
  88. package/dist/runtime/bootstrap.js +92 -59
  89. package/dist/runtime/channel-queue.d.ts +2 -0
  90. package/dist/runtime/channel-queue.js +5 -1
  91. package/dist/runtime/durable-dispatch.d.ts +7 -0
  92. package/dist/runtime/durable-dispatch.js +66 -7
  93. package/dist/runtime/ingress-busy.d.ts +1 -2
  94. package/dist/runtime/ingress-busy.js +2 -35
  95. package/dist/runtime/ingress-commands.d.ts +1 -1
  96. package/dist/runtime/ingress-commands.js +28 -20
  97. package/dist/runtime/ingress-deps.d.ts +4 -7
  98. package/dist/runtime/ingress.js +23 -13
  99. package/dist/runtime/shutdown.d.ts +1 -1
  100. package/dist/runtime/shutdown.js +2 -2
  101. package/dist/runtime/task-close.d.ts +4 -0
  102. package/dist/runtime/task-close.js +102 -0
  103. package/dist/runtime/task-control.d.ts +34 -0
  104. package/dist/runtime/task-control.js +225 -0
  105. package/dist/runtime/task-input.d.ts +13 -0
  106. package/dist/runtime/task-input.js +129 -0
  107. package/dist/runtime/task-lane-types.d.ts +123 -0
  108. package/dist/runtime/task-lane-types.js +14 -0
  109. package/dist/runtime/task-lane.d.ts +99 -0
  110. package/dist/runtime/task-lane.js +703 -0
  111. package/dist/runtime/task-pending.d.ts +8 -0
  112. package/dist/runtime/task-pending.js +40 -0
  113. package/dist/runtime/task-spawn.d.ts +4 -4
  114. package/dist/runtime/task-spawn.js +4 -4
  115. package/dist/runtime/task-step.d.ts +32 -0
  116. package/dist/runtime/task-step.js +276 -0
  117. package/dist/runtime/turn-run.d.ts +4 -16
  118. package/dist/runtime/turn-run.js +17 -155
  119. package/dist/runtime/wake-coalescing.d.ts +1 -3
  120. package/dist/runtime/wake-coalescing.js +2 -4
  121. package/dist/shared/format.d.ts +0 -6
  122. package/dist/shared/format.js +0 -17
  123. package/dist/shared/host-process.d.ts +2 -0
  124. package/dist/shared/host-process.js +16 -1
  125. package/dist/shared/jsonl-appender.d.ts +5 -0
  126. package/dist/shared/jsonl-appender.js +25 -2
  127. package/dist/skills/catalog.d.ts +9 -0
  128. package/dist/skills/catalog.js +34 -0
  129. package/dist/skills/commands.d.ts +3 -12
  130. package/dist/skills/commands.js +36 -22
  131. package/dist/skills/loader.d.ts +2 -31
  132. package/dist/skills/loader.js +101 -68
  133. package/dist/skills/roots.d.ts +12 -0
  134. package/dist/skills/roots.js +18 -0
  135. package/dist/skills/types.d.ts +24 -0
  136. package/dist/skills/types.js +1 -0
  137. package/dist/subagents/completion-wake.js +0 -10
  138. package/dist/subagents/discovery.d.ts +1 -1
  139. package/dist/subagents/discovery.js +10 -16
  140. package/dist/subagents/dispatch.js +8 -16
  141. package/dist/subagents/external/cursor-cli.d.ts +2 -0
  142. package/dist/subagents/external/cursor-cli.js +256 -0
  143. package/dist/subagents/external/harness.d.ts +5 -5
  144. package/dist/subagents/external/reconciliation.d.ts +7 -0
  145. package/dist/subagents/external/reconciliation.js +105 -0
  146. package/dist/subagents/external/recovery.d.ts +20 -0
  147. package/dist/subagents/external/recovery.js +71 -0
  148. package/dist/subagents/external/registry.js +2 -0
  149. package/dist/subagents/external/role-warnings.d.ts +17 -0
  150. package/dist/subagents/external/role-warnings.js +42 -0
  151. package/dist/subagents/external/run.js +18 -22
  152. package/dist/subagents/format.d.ts +1 -1
  153. package/dist/subagents/format.js +1 -1
  154. package/dist/subagents/grace.d.ts +2 -2
  155. package/dist/subagents/grace.js +3 -3
  156. package/dist/subagents/internal/run.js +7 -5
  157. package/dist/subagents/internal/worker.js +31 -2
  158. package/dist/subagents/result.js +2 -3
  159. package/dist/subagents/run-record.d.ts +4 -7
  160. package/dist/subagents/run-record.js +2 -2
  161. package/dist/subagents/runs.d.ts +33 -46
  162. package/dist/subagents/runs.js +126 -245
  163. package/dist/subagents/task-settlement.d.ts +3 -0
  164. package/dist/subagents/task-settlement.js +20 -0
  165. package/dist/subagents/types.d.ts +1 -2
  166. package/dist/subagents/workspace-summary.js +5 -1
  167. package/dist/tasks/archive.d.ts +11 -0
  168. package/dist/tasks/archive.js +141 -0
  169. package/dist/tasks/board.d.ts +5 -12
  170. package/dist/tasks/board.js +4 -30
  171. package/dist/tasks/bound-work.d.ts +12 -6
  172. package/dist/tasks/bound-work.js +37 -24
  173. package/dist/tasks/brief.d.ts +38 -14
  174. package/dist/tasks/brief.js +128 -70
  175. package/dist/tasks/budget.d.ts +3 -3
  176. package/dist/tasks/budget.js +9 -4
  177. package/dist/tasks/commands.d.ts +14 -9
  178. package/dist/tasks/commands.js +190 -121
  179. package/dist/tasks/completion.d.ts +12 -0
  180. package/dist/tasks/completion.js +35 -0
  181. package/dist/tasks/contract.d.ts +8 -17
  182. package/dist/tasks/contract.js +41 -43
  183. package/dist/tasks/control.d.ts +138 -0
  184. package/dist/tasks/control.js +1 -0
  185. package/dist/tasks/create.d.ts +1 -1
  186. package/dist/tasks/create.js +3 -3
  187. package/dist/tasks/delivery.d.ts +24 -0
  188. package/dist/tasks/delivery.js +221 -0
  189. package/dist/tasks/file-mutation.d.ts +5 -0
  190. package/dist/tasks/file-mutation.js +38 -0
  191. package/dist/tasks/frontmatter.d.ts +43 -28
  192. package/dist/tasks/frontmatter.js +83 -40
  193. package/dist/tasks/input-receipts.d.ts +7 -0
  194. package/dist/tasks/input-receipts.js +60 -0
  195. package/dist/tasks/loop-log.d.ts +147 -28
  196. package/dist/tasks/loop-log.js +239 -28
  197. package/dist/tasks/receipts.d.ts +19 -0
  198. package/dist/tasks/receipts.js +48 -0
  199. package/dist/tasks/state.d.ts +93 -0
  200. package/dist/tasks/state.js +156 -0
  201. package/dist/tasks/store.d.ts +81 -49
  202. package/dist/tasks/store.js +244 -147
  203. package/dist/tools/bash.d.ts +3 -5
  204. package/dist/tools/bash.js +8 -22
  205. package/dist/tools/contract/details.d.ts +6 -6
  206. package/dist/tools/contract/details.js +6 -6
  207. package/dist/tools/contract/execution-trace.d.ts +4 -0
  208. package/dist/tools/contract/execution-trace.js +23 -0
  209. package/dist/tools/contract/presentation.js +6 -2
  210. package/dist/tools/edit.d.ts +1 -0
  211. package/dist/tools/edit.js +45 -42
  212. package/dist/tools/index.d.ts +8 -12
  213. package/dist/tools/index.js +16 -6
  214. package/dist/tools/memory-manage.js +8 -1
  215. package/dist/tools/registry.d.ts +7 -11
  216. package/dist/tools/registry.js +52 -25
  217. package/dist/tools/skill.d.ts +2 -2
  218. package/dist/tools/skill.js +24 -10
  219. package/dist/tools/subagent-manage.js +7 -4
  220. package/dist/tools/subagent.d.ts +0 -2
  221. package/dist/tools/subagent.js +2 -7
  222. package/dist/tools/task-manage/control-tools.d.ts +4 -0
  223. package/dist/tools/task-manage/control-tools.js +65 -0
  224. package/dist/tools/task-manage/create.js +2 -1
  225. package/dist/tools/task-manage/factory.d.ts +12 -6
  226. package/dist/tools/task-manage/factory.js +72 -57
  227. package/dist/tools/task-manage/lifecycle.d.ts +7 -12
  228. package/dist/tools/task-manage/lifecycle.js +118 -66
  229. package/dist/tools/task-manage/log-view.js +8 -5
  230. package/dist/tools/task-manage/schema.d.ts +21 -26
  231. package/dist/tools/task-manage/schema.js +29 -35
  232. package/dist/tools/task-manage/shared.d.ts +8 -39
  233. package/dist/tools/task-manage/shared.js +19 -68
  234. package/dist/tools/task-manage/step-tools.d.ts +5 -0
  235. package/dist/tools/task-manage/step-tools.js +103 -0
  236. package/dist/tools/task-manage/types.d.ts +25 -18
  237. package/dist/tools/write-content.d.ts +1 -0
  238. package/dist/tools/write-content.js +6 -1
  239. package/dist/tools/write.d.ts +1 -0
  240. package/dist/tools/write.js +1 -0
  241. package/dist/usage/ledger.d.ts +4 -4
  242. package/dist/usage/render.js +2 -2
  243. package/dist/web/search-providers.js +0 -33
  244. package/dist/webapi/request-policy.js +1 -1
  245. package/examples/sub-agents/README.md +23 -16
  246. package/examples/sub-agents/agents/claude-high.md +1 -1
  247. package/examples/sub-agents/agents/claude-main.md +1 -1
  248. package/examples/sub-agents/agents/codex-flash.md +1 -1
  249. package/examples/sub-agents/agents/codex-high.md +1 -1
  250. package/examples/sub-agents/agents/codex-main.md +4 -4
  251. package/examples/sub-agents/agents/cursor-high.md +22 -0
  252. package/examples/sub-agents/agents/cursor-main.md +22 -0
  253. package/examples/sub-agents/agents/glm-flash.md +1 -1
  254. package/examples/sub-agents/agents/glm-high.md +2 -2
  255. package/examples/sub-agents/agents/scout.md +30 -0
  256. package/package.json +6 -6
  257. package/dist/runtime/task-driver.d.ts +0 -116
  258. package/dist/runtime/task-driver.js +0 -443
  259. package/dist/runtime/task-wake.d.ts +0 -48
  260. package/dist/runtime/task-wake.js +0 -32
  261. package/dist/shared/wake-claim.d.ts +0 -23
  262. package/dist/shared/wake-claim.js +0 -26
  263. package/dist/skills/validation.d.ts +0 -8
  264. package/dist/skills/validation.js +0 -91
  265. package/dist/skills/workspace.d.ts +0 -33
  266. package/dist/skills/workspace.js +0 -116
  267. package/dist/tasks/steer.d.ts +0 -8
  268. package/dist/tasks/steer.js +0 -81
  269. package/dist/tasks/ticket.d.ts +0 -71
  270. package/dist/tasks/ticket.js +0 -138
  271. package/dist/tools/task-manage/step-end.d.ts +0 -11
  272. package/dist/tools/task-manage/step-end.js +0 -117
@@ -0,0 +1,703 @@
1
+ import { join } from "node:path";
2
+ import * as log from "../log.js";
3
+ import { parseLocalTime } from "../shared/local-time.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
5
+ import { isTaskArchiving, recoverTaskArchives } from "../tasks/archive.js";
6
+ import { pendingTaskClose } from "../tasks/completion.js";
7
+ import { extractTaskTitle, readActiveTasks } from "../tasks/contract.js";
8
+ import { drainTaskDeliveries } from "../tasks/delivery.js";
9
+ import { appendTaskLog, lastStep, newInputs, readTaskLog } from "../tasks/loop-log.js";
10
+ import { withTaskMutation } from "../tasks/mutation-lock.js";
11
+ import { askReceipt, pausedReceipt } from "../tasks/receipts.js";
12
+ import { checkGuards, evaluateWaiting } from "../tasks/state.js";
13
+ import { pauseTask, readStoredTask, reconcileTaskState, requeueWaiting } from "../tasks/store.js";
14
+ import { finishTaskClose } from "./task-close.js";
15
+ import { isFrozen, LaneControl } from "./task-control.js";
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";
18
+ import { listPendingWork } from "./task-pending.js";
19
+ import { abortStep, executeStep } from "./task-step.js";
20
+ function isExecuting(seen, live) {
21
+ if (live?.driving)
22
+ return true;
23
+ if (seen.frozen)
24
+ return false;
25
+ const { fields } = seen.entry;
26
+ return (fields.state === "running" ||
27
+ (fields.state === "waiting" && fields.waiting?.kind === "work") ||
28
+ (live?.driving ?? false));
29
+ }
30
+ /**
31
+ * The task lane (spec 064, D11): the one place tasks execute. A task never enters a channel queue —
32
+ * the chat answers while a step runs and a step never waits for the chat (INV-1).
33
+ *
34
+ * The lane reads the task files, maintains them from facts (waits that came due, results that
35
+ * arrived, budgets that ran out), admits queued tasks into the execution slots, and runs each
36
+ * admitted task as a loop of steps in a runner of its own. Its in-memory state is only what a step
37
+ * in flight needs; losing it (a restart) loses nothing, because every decision is recomputed from
38
+ * the files and the log (D10).
39
+ */
40
+ export class TaskLane {
41
+ constructor(options) {
42
+ this.options = options;
43
+ this.timer = null;
44
+ this.notifyTimer = null;
45
+ this.started = false;
46
+ this.stopped = false;
47
+ this.scanning = false;
48
+ this.rescan = false;
49
+ this.nextDeskIndex = 0;
50
+ /** Tasks reported frozen, so the transition is logged once rather than every scan. */
51
+ this.frozenLogged = new Set();
52
+ /** Consecutive step errors per task in this process, and when it may be admitted again (D16). Not persisted: a restart starts from zero. */
53
+ /** Drive loops in flight, for `drained`. */
54
+ this.drives = new Set();
55
+ this.backoff = new Map();
56
+ this.questionRetry = new Map();
57
+ const timing = {
58
+ stepTimeLimitMs: options.timing?.stepTimeLimitMs ?? STEP_TIME_LIMIT_MS,
59
+ stopGraceMs: options.timing?.stopGraceMs ?? 3_000,
60
+ maxSleepMs: options.timing?.maxSleepMs ?? MAX_SLEEP_MS,
61
+ notifyDebounceMs: options.timing?.notifyDebounceMs ?? NOTIFY_DEBOUNCE_MS,
62
+ errorBackoffMs: options.timing?.errorBackoffMs ?? ERROR_BACKOFF_MS,
63
+ };
64
+ this.ctx = {
65
+ options,
66
+ live: new Map(),
67
+ now: options.now ?? (() => Date.now()),
68
+ timing,
69
+ notify: () => this.notify(),
70
+ inputAvailable: (desk, id) => this.inputAvailable(desk, id),
71
+ release: (live) => this.release(live),
72
+ isStopped: () => this.stopped,
73
+ };
74
+ this.control = new LaneControl(this.ctx);
75
+ this.inputs = new TaskInputDelivery(this.ctx);
76
+ }
77
+ // === Lifecycle ===
78
+ start() {
79
+ if (this.started)
80
+ return;
81
+ this.started = true;
82
+ this.stopped = false;
83
+ log.logInfoEvent("tasks.lane.started", "Task lane started", {
84
+ fields: { timezone: Intl.DateTimeFormat().resolvedOptions().timeZone },
85
+ });
86
+ this.notify();
87
+ }
88
+ /** Stop admitting, stop the steps in flight (their `step_end` is written by the next start, D10) and let go of every runner. */
89
+ stop() {
90
+ this.inputs.stop();
91
+ this.stopped = true;
92
+ this.started = false;
93
+ if (this.timer)
94
+ clearTimeout(this.timer);
95
+ if (this.notifyTimer)
96
+ clearTimeout(this.notifyTimer);
97
+ this.timer = null;
98
+ this.notifyTimer = null;
99
+ for (const live of this.ctx.live.values()) {
100
+ abortStep(this.ctx, live, "shutdown");
101
+ if (!live.driving)
102
+ void this.dispose(live);
103
+ }
104
+ }
105
+ inputAvailable(desk, taskId) {
106
+ this.inputs.notify(desk, taskId);
107
+ }
108
+ /** Something changed that a task may need to react to (a result, a message, a new task): look again soon. */
109
+ notify() {
110
+ if (this.stopped || !this.started || this.notifyTimer)
111
+ return;
112
+ if (this.timer) {
113
+ clearTimeout(this.timer);
114
+ this.timer = null;
115
+ }
116
+ this.notifyTimer = setTimeout(() => {
117
+ this.notifyTimer = null;
118
+ void this.scan();
119
+ }, this.ctx.timing.notifyDebounceMs);
120
+ this.notifyTimer.unref?.();
121
+ }
122
+ /** Resolves when no step is in flight (and none was just started by a scan). For tests and evaluation workers. */
123
+ async drained() {
124
+ await this.scanning_();
125
+ while (this.drives.size > 0)
126
+ await Promise.all([...this.drives]);
127
+ }
128
+ async scanning_() {
129
+ while (this.scanning)
130
+ await new Promise((resolve) => setTimeout(resolve, 2));
131
+ }
132
+ /** One scan now, outside the timer: the entry point tests and the runtime's own wiring use. */
133
+ async runOnce() {
134
+ await this.scan();
135
+ }
136
+ // === TaskControl ===
137
+ isRunning(desk, id) {
138
+ return this.ctx.live.get(taskKey(desk, id))?.driving ?? false;
139
+ }
140
+ created() {
141
+ this.control.created();
142
+ }
143
+ snapshot(desk, id) {
144
+ return this.control.snapshot(desk, id);
145
+ }
146
+ message(desk, id, input) {
147
+ return this.control.message(desk, id, input);
148
+ }
149
+ pause(desk, id, input) {
150
+ return this.control.pause(desk, id, input);
151
+ }
152
+ resume(desk, id, grants) {
153
+ return this.control.resume(desk, id, grants);
154
+ }
155
+ cancel(desk, id, input) {
156
+ return this.control.cancel(desk, id, input);
157
+ }
158
+ // === Scanning ===
159
+ async scan() {
160
+ if (this.stopped)
161
+ return;
162
+ if (this.scanning) {
163
+ this.rescan = true;
164
+ return;
165
+ }
166
+ this.scanning = true;
167
+ try {
168
+ do {
169
+ this.rescan = false;
170
+ await this.scanOnce();
171
+ } while (this.rescan && !this.stopped);
172
+ }
173
+ catch (error) {
174
+ log.logWarn("tasks.lane.scan_failed", "Task lane scan failed", { reason: errorMessage(error) });
175
+ }
176
+ finally {
177
+ this.scanning = false;
178
+ }
179
+ this.scheduleNext();
180
+ }
181
+ scheduleNext() {
182
+ if (this.stopped || !this.started || this.timer || this.notifyTimer)
183
+ return;
184
+ const untilNext = this.nextWakeMs !== undefined ? this.nextWakeMs - this.ctx.now() : Number.POSITIVE_INFINITY;
185
+ const sleepMs = Math.max(250, Math.min(this.ctx.timing.maxSleepMs, untilNext));
186
+ this.timer = setTimeout(() => {
187
+ this.timer = null;
188
+ void this.scan();
189
+ }, sleepMs);
190
+ this.timer.unref?.();
191
+ }
192
+ noteHorizon(atMs) {
193
+ const now = this.ctx.now();
194
+ if (atMs === undefined || !Number.isFinite(atMs) || atMs <= now)
195
+ return;
196
+ if (this.nextWakeMs === undefined || atMs < this.nextWakeMs)
197
+ this.nextWakeMs = atMs;
198
+ }
199
+ /** Read every active desk's tasks and note which are reachable (INV-7) and how much work each has in flight. */
200
+ async readDesk(desk, deskDir) {
201
+ await recoverTaskArchives(deskDir);
202
+ await this.flushDeliveries(desk, deskDir);
203
+ const now = this.ctx.now();
204
+ let entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
205
+ let pending = await listPendingWork(this.options, desk, now);
206
+ // D10: whatever state the previous process left becomes true to the facts before anything is decided.
207
+ 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);
210
+ }
211
+ entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
212
+ pending = await listPendingWork(this.options, desk, now);
213
+ const seen = [];
214
+ for (const entry of entries) {
215
+ const key = taskKey(desk, entry.id);
216
+ const frozen = !entry.readable || isFrozen(this.ctx, desk, entry.fields);
217
+ if (frozen && entry.readable)
218
+ this.noteFrozen(key, desk, entry, true);
219
+ else if (!frozen)
220
+ this.noteFrozen(key, desk, entry, false);
221
+ seen.push({ entry, frozen, pendingWork: pending.get(entry.id)?.length ?? 0 });
222
+ }
223
+ return { desk, deskDir, seen };
224
+ }
225
+ noteFrozen(key, desk, entry, frozen) {
226
+ if (frozen && !this.frozenLogged.has(key)) {
227
+ this.frozenLogged.add(key);
228
+ const channel = entry.fields.channel;
229
+ log.logInfoEvent("tasks.task.frozen", "Task frozen: report channel not usable", {
230
+ 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
+ },
240
+ });
241
+ }
242
+ else if (!frozen && this.frozenLogged.delete(key)) {
243
+ log.logInfoEvent("tasks.task.unfrozen", "Task unfrozen: report channel usable again", {
244
+ channelId: entry.fields.channel,
245
+ fields: { taskId: entry.id, desk },
246
+ });
247
+ }
248
+ }
249
+ async reconcile(desk, deskDir, entry, pendingWork) {
250
+ if (!entry.readable)
251
+ return false;
252
+ if (this.ctx.live.get(taskKey(desk, entry.id))?.driving)
253
+ return false;
254
+ try {
255
+ const changed = await reconcileTaskState(deskDir, entry.id, pendingWork, new Date(this.ctx.now()));
256
+ if (changed) {
257
+ log.logInfoEvent("tasks.task.reconciled", "Task state repaired from the log", {
258
+ fields: { taskId: entry.id, desk, was: entry.fields.state },
259
+ });
260
+ }
261
+ return changed;
262
+ }
263
+ catch (error) {
264
+ log.logWarn("tasks.task.reconcile_failed", "Task reconciliation failed", {
265
+ reason: errorMessage(error),
266
+ fields: { taskId: entry.id, desk },
267
+ });
268
+ return false;
269
+ }
270
+ }
271
+ async scanOnce() {
272
+ this.nextWakeMs = undefined;
273
+ const desks = this.options.getActiveDesks();
274
+ const scans = [];
275
+ for (const { desk, deskDir } of desks)
276
+ scans.push(await this.readDesk(desk, deskDir));
277
+ // A task that is frozen holds no slot and no runner (INV-7); one that left execution releases its runner.
278
+ for (const { desk, seen } of scans) {
279
+ for (const item of seen) {
280
+ const live = this.ctx.live.get(taskKey(desk, item.entry.id));
281
+ if (live && !live.driving && (item.frozen || !isExecuting(item, live)))
282
+ await this.release(live);
283
+ }
284
+ }
285
+ // A task that vanished from its desk (deleted by hand) leaves nothing to execute or to remember.
286
+ const seenKeys = new Set(scans.flatMap(({ desk, seen }) => seen.map((item) => taskKey(desk, item.entry.id))));
287
+ for (const [key, live] of this.ctx.live) {
288
+ if (!seenKeys.has(key) && !live.driving)
289
+ await this.release(live);
290
+ }
291
+ const executingByDesk = new Map();
292
+ let executing = 0;
293
+ for (const { desk, seen } of scans) {
294
+ const count = seen.filter((item) => isExecuting(item, this.ctx.live.get(taskKey(desk, item.entry.id)))).length;
295
+ executingByDesk.set(desk, count);
296
+ executing += count;
297
+ }
298
+ // Maintenance first, for every desk (zero tokens): waits that came due, results that arrived.
299
+ const enabled = this.options.isEnabled?.() !== false;
300
+ const candidates = new Map();
301
+ for (const scan of scans) {
302
+ const ready = [];
303
+ for (const item of scan.seen) {
304
+ if (item.frozen)
305
+ continue;
306
+ const decision = await this.maintain(scan, item);
307
+ if (decision === "queued")
308
+ ready.push(item);
309
+ else if (decision === "run" && enabled) {
310
+ // A work wait with news keeps its slot and runner: no admission, but the guards still apply.
311
+ if (await this.guard(scan, item))
312
+ continue;
313
+ this.startDrive(scan, item);
314
+ }
315
+ }
316
+ candidates.set(scan.desk, ready);
317
+ }
318
+ if (!enabled)
319
+ return;
320
+ // Admission: oldest project first within a desk, desks in rotation (D11/D12).
321
+ const start = scans.length > 0 ? this.nextDeskIndex % scans.length : 0;
322
+ let admitted = 0;
323
+ for (let offset = 0; offset < scans.length; offset++) {
324
+ const scan = scans[(start + offset) % scans.length];
325
+ if (!scan)
326
+ continue;
327
+ const ready = (candidates.get(scan.desk) ?? []).sort(compareByStart);
328
+ for (const item of ready) {
329
+ if (executing >= MAX_EXECUTING_TASKS)
330
+ break;
331
+ if ((executingByDesk.get(scan.desk) ?? 0) >= MAX_EXECUTING_TASKS_PER_DESK)
332
+ break;
333
+ if (this.ctx.live.get(taskKey(scan.desk, item.entry.id))?.driving)
334
+ continue;
335
+ const notBefore = this.backoff.get(taskKey(scan.desk, item.entry.id))?.notBefore;
336
+ if (notBefore !== undefined && notBefore > this.ctx.now()) {
337
+ this.noteHorizon(notBefore);
338
+ continue;
339
+ }
340
+ if (await this.guard(scan, item))
341
+ continue;
342
+ this.startDrive(scan, item);
343
+ executingByDesk.set(scan.desk, (executingByDesk.get(scan.desk) ?? 0) + 1);
344
+ executing++;
345
+ admitted++;
346
+ }
347
+ }
348
+ if (admitted > 0)
349
+ this.nextDeskIndex = (start + 1) % Math.max(1, scans.length);
350
+ }
351
+ /**
352
+ * Zero-token upkeep of one reachable task (D7/D9). Returns `queued` when the task is waiting
353
+ * its turn, `run` when a work wait has news and runs again in its own slot, `idle` otherwise.
354
+ */
355
+ async maintain(scan, item) {
356
+ const { fields } = item.entry;
357
+ const live = this.ctx.live.get(taskKey(scan.desk, item.entry.id));
358
+ if (live?.driving)
359
+ return "idle";
360
+ if (isTaskArchiving(scan.deskDir, item.entry.id)) {
361
+ this.noteHorizon(this.ctx.now() + 60_000);
362
+ return "idle";
363
+ }
364
+ const history = await readTaskLog(scan.deskDir, item.entry.id);
365
+ // A user's cancel pauses before writing close. A crash in between close and archive
366
+ // preparation must finish that close; a later explicit/error pause still takes precedence.
367
+ const lastBoundary = [...history].reverse().find((record) => record.kind === "close" || record.kind === "pause");
368
+ const committedAfterPause = lastBoundary?.kind === "close";
369
+ if (fields.state !== "paused" || committedAfterPause) {
370
+ const records = history;
371
+ const close = pendingTaskClose(records);
372
+ if (close) {
373
+ await this.closeForLeader({
374
+ key: taskKey(scan.desk, item.entry.id),
375
+ desk: scan.desk,
376
+ deskDir: scan.deskDir,
377
+ taskId: item.entry.id,
378
+ channelId: fields.channel ?? "",
379
+ seq: lastStep(records)?.step.seq ?? 0,
380
+ intent: { reports: 0 },
381
+ driving: false,
382
+ }, item.entry.title, { reports: 0, close });
383
+ return "idle";
384
+ }
385
+ }
386
+ if (fields.state === "queued")
387
+ return "queued";
388
+ if (fields.state === "running") {
389
+ // Marked running with no step in this process: repaired like a restart would (D10).
390
+ if (await this.reconcile(scan.desk, scan.deskDir, item.entry, item.pendingWork))
391
+ this.rescan = true;
392
+ return "idle";
393
+ }
394
+ if (fields.state !== "waiting" || !fields.waiting)
395
+ return "idle";
396
+ const records = await readTaskLog(scan.deskDir, item.entry.id);
397
+ const decision = evaluateWaiting({
398
+ waiting: fields.waiting,
399
+ inputs: newInputs(records),
400
+ pendingWork: item.pendingWork,
401
+ now: this.ctx.now(),
402
+ });
403
+ if (fields.waiting.kind === "time")
404
+ this.noteHorizon(parseLocalTime(fields.waiting.until));
405
+ if (decision === "stay") {
406
+ if (fields.waiting.kind === "user")
407
+ await this.deliverQuestion(scan.desk, scan.deskDir, item.entry.id, fields.channel);
408
+ return "idle";
409
+ }
410
+ if (decision === "run")
411
+ return "run";
412
+ const requeued = await requeueWaiting(scan.deskDir, item.entry.id);
413
+ return requeued ? "queued" : "idle";
414
+ }
415
+ /** Stop a task the guards say must not run again: pause it and tell the user why (D16). True when it was stopped. */
416
+ async guard(scan, item) {
417
+ const doc = await readStoredTask(scan.deskDir, item.entry.id);
418
+ if (!doc)
419
+ return true;
420
+ const records = await readTaskLog(scan.deskDir, item.entry.id);
421
+ const verdict = checkGuards(doc.fields, records);
422
+ if (!verdict)
423
+ return false;
424
+ await this.pauseForGuard(scan.desk, scan.deskDir, item.entry.id, doc.fields.channel, doc.body, verdict);
425
+ return true;
426
+ }
427
+ async pauseForGuard(desk, deskDir, taskId, channel, body, verdict) {
428
+ const paused = await pauseTask(deskDir, taskId, { by: "runtime", reason: verdict.reason });
429
+ if (!paused)
430
+ return;
431
+ log.logWarn("tasks.task.paused", "Task paused by a runtime guard", {
432
+ channelId: channel,
433
+ reason: verdict.reason,
434
+ fields: { taskId, desk, cause: verdict.breach },
435
+ });
436
+ if (!channel)
437
+ return;
438
+ await this.options
439
+ .deliver(desk, channel, pausedReceipt(taskId, extractTaskTitle(body, taskId), verdict.reason, verdict.breach))
440
+ .catch((error) => log.logWarn("tasks.task.receipt_failed", "Task pause receipt failed", {
441
+ channelId: channel,
442
+ reason: errorMessage(error),
443
+ fields: { taskId, desk },
444
+ }));
445
+ }
446
+ // === Execution ===
447
+ startDrive(scan, item) {
448
+ const drives = [...this.ctx.live.values()].filter((task) => task.driving);
449
+ if (drives.length >= MAX_EXECUTING_TASKS ||
450
+ drives.filter((task) => task.desk === scan.desk).length >= MAX_EXECUTING_TASKS_PER_DESK)
451
+ return;
452
+ const key = taskKey(scan.desk, item.entry.id);
453
+ let live = this.ctx.live.get(key);
454
+ if (!live) {
455
+ live = {
456
+ key,
457
+ desk: scan.desk,
458
+ deskDir: scan.deskDir,
459
+ taskId: item.entry.id,
460
+ channelId: item.entry.fields.channel ?? "",
461
+ seq: 0,
462
+ intent: { reports: 0 },
463
+ driving: false,
464
+ };
465
+ this.ctx.live.set(key, live);
466
+ }
467
+ if (live.driving)
468
+ return;
469
+ live.driving = true;
470
+ live.channelId = item.entry.fields.channel ?? live.channelId;
471
+ const task = this.drive(live).catch((error) => {
472
+ log.logWarn("tasks.step.failed", "Task step failed", {
473
+ channelId: live.channelId,
474
+ reason: errorMessage(error),
475
+ fields: { taskId: live.taskId, desk: live.desk },
476
+ });
477
+ });
478
+ const tracked = task.finally(() => {
479
+ this.options.activeTasks.delete(tracked);
480
+ this.drives.delete(tracked);
481
+ live.driving = false;
482
+ if (this.stopped)
483
+ void this.dispose(live);
484
+ else
485
+ this.notify();
486
+ });
487
+ this.options.activeTasks.add(tracked);
488
+ live.done = tracked;
489
+ this.drives.add(tracked);
490
+ }
491
+ /** Steps in a row while the task has something to do and a slot (D8: `continue` opens the next at once). */
492
+ async drive(live) {
493
+ while (!this.stopped) {
494
+ const document = await readStoredTask(live.deskDir, live.taskId);
495
+ if (!document ||
496
+ isFrozen(this.ctx, live.desk, document.fields) ||
497
+ this.options.isEnabled?.() === false ||
498
+ this.isBackingOff(live.key) ||
499
+ (await this.guardLive(live))) {
500
+ await this.dispose(live);
501
+ return;
502
+ }
503
+ const report = await executeStep(this.ctx, live);
504
+ if (report.kind === "interrupted")
505
+ return;
506
+ if (report.kind === "skipped") {
507
+ await this.dispose(live);
508
+ return;
509
+ }
510
+ if ((await this.afterStep(live, report)) !== "again")
511
+ return;
512
+ }
513
+ }
514
+ /** Act on a finished step: close, ask, pause, wait — or open the next. */
515
+ async afterStep(live, report) {
516
+ const { ended, derivation, result } = report;
517
+ if (!ended) {
518
+ // The task was cancelled or removed while the step ran.
519
+ await this.dispose(live);
520
+ return "done";
521
+ }
522
+ const title = extractTaskTitle(ended.document.body, live.taskId);
523
+ const previous = this.backoff.get(live.key);
524
+ const errors = result === "error" ? (previous?.errors ?? 0) + 1 : 0;
525
+ if (errors === 0)
526
+ this.backoff.delete(live.key);
527
+ else
528
+ this.backoff.set(live.key, { errors, notBefore: this.backoffUntil(errors) });
529
+ switch (derivation.next) {
530
+ case "closed":
531
+ this.backoff.delete(live.key);
532
+ await this.closeForLeader(live, title, report.intent);
533
+ return "done";
534
+ case "paused":
535
+ case "time":
536
+ await this.dispose(live);
537
+ return "done";
538
+ case "user":
539
+ await this.deliverQuestion(live.desk, live.deskDir, live.taskId, live.channelId);
540
+ await this.dispose(live);
541
+ return "done";
542
+ case "work":
543
+ // Results that arrived while the step ran wake the task at once instead of after a scan (D8).
544
+ return (await this.reevaluate(live)) === "run" ? "again" : "done";
545
+ case "continue":
546
+ // A failed step is re-run after a pause, and the third failure in a row stops the task (D16).
547
+ if (await this.guardLive(live)) {
548
+ await this.dispose(live);
549
+ return "done";
550
+ }
551
+ if (result !== "ok") {
552
+ await this.dispose(live);
553
+ return "done";
554
+ }
555
+ // Switching tasks off stops the next step, not the one in flight.
556
+ if (this.options.isEnabled?.() === false) {
557
+ await this.dispose(live);
558
+ return "done";
559
+ }
560
+ return "again";
561
+ }
562
+ }
563
+ isBackingOff(key) {
564
+ const until = this.backoff.get(key)?.notBefore;
565
+ if (until === undefined || until <= this.ctx.now())
566
+ return false;
567
+ this.noteHorizon(until);
568
+ return true;
569
+ }
570
+ async deliverQuestion(desk, deskDir, id, channel) {
571
+ const key = taskKey(desk, id);
572
+ if (!channel || (this.questionRetry.get(key) ?? 0) > this.ctx.now()) {
573
+ this.noteHorizon(this.questionRetry.get(key));
574
+ return;
575
+ }
576
+ const doc = await readStoredTask(deskDir, id);
577
+ if (!doc ||
578
+ doc.fields.state !== "waiting" ||
579
+ doc.fields.waiting?.kind !== "user" ||
580
+ isFrozen(this.ctx, desk, doc.fields))
581
+ return;
582
+ const question = doc.fields.waiting.question;
583
+ const records = await readTaskLog(deskDir, id);
584
+ const seq = lastStep(records)?.step.seq ?? 0;
585
+ if (records.some((record) => record.kind === "ask_delivered" && record.seq === seq))
586
+ return;
587
+ this.questionRetry.set(key, this.ctx.now() + 60_000);
588
+ try {
589
+ if (await this.options.deliver(desk, doc.fields.channel ?? channel, askReceipt(id, question))) {
590
+ await withTaskMutation(deskDir, id, async () => {
591
+ const current = await readStoredTask(deskDir, id);
592
+ if (current?.fields.state === "waiting" &&
593
+ current.fields.waiting?.kind === "user" &&
594
+ current.fields.waiting.question === question &&
595
+ current.fields.channel === doc.fields.channel &&
596
+ lastStep(await readTaskLog(deskDir, id))?.step.seq === seq) {
597
+ await appendTaskLog(deskDir, id, { kind: "ask_delivered", seq });
598
+ }
599
+ });
600
+ this.questionRetry.delete(key);
601
+ }
602
+ }
603
+ catch (error) {
604
+ log.logWarn("tasks.question.deliver_failed", "Task question delivery failed", {
605
+ reason: errorMessage(error),
606
+ fields: { taskId: id, desk },
607
+ });
608
+ }
609
+ this.noteHorizon(this.questionRetry.get(key));
610
+ }
611
+ backoffUntil(errors) {
612
+ const wait = this.ctx.timing.errorBackoffMs[Math.min(errors - 1, this.ctx.timing.errorBackoffMs.length - 1)];
613
+ return wait === undefined ? undefined : this.ctx.now() + wait;
614
+ }
615
+ /** After a step: the freshest state and log decide whether the task goes on (budget, idle, timeout, error). True when it was stopped. */
616
+ async guardLive(live) {
617
+ const doc = await readStoredTask(live.deskDir, live.taskId);
618
+ if (!doc)
619
+ return true;
620
+ const records = await readTaskLog(live.deskDir, live.taskId);
621
+ const verdict = checkGuards(doc.fields, records);
622
+ if (!verdict)
623
+ return false;
624
+ await this.pauseForGuard(live.desk, live.deskDir, live.taskId, doc.fields.channel, doc.body, verdict);
625
+ return true;
626
+ }
627
+ /** Whether a task waiting on work has news right now, and may run (guards included). */
628
+ async reevaluate(live) {
629
+ const doc = await readStoredTask(live.deskDir, live.taskId);
630
+ const waiting = doc?.fields.waiting;
631
+ if (!doc || doc.fields.state !== "waiting" || waiting?.kind !== "work")
632
+ return "stay";
633
+ if (isFrozen(this.ctx, live.desk, doc.fields)) {
634
+ await this.dispose(live);
635
+ return "stay";
636
+ }
637
+ const records = await readTaskLog(live.deskDir, live.taskId);
638
+ const pending = (await listPendingWork(this.options, live.desk, this.ctx.now())).get(live.taskId)?.length ?? 0;
639
+ const decision = evaluateWaiting({
640
+ waiting,
641
+ inputs: newInputs(records),
642
+ pendingWork: pending,
643
+ now: this.ctx.now(),
644
+ });
645
+ if (decision === "stay")
646
+ return "stay";
647
+ if (decision === "queue") {
648
+ await requeueWaiting(live.deskDir, live.taskId);
649
+ await this.dispose(live);
650
+ return "stay";
651
+ }
652
+ if (checkGuards(doc.fields, records)) {
653
+ await this.guardLive(live);
654
+ await this.dispose(live);
655
+ return "stay";
656
+ }
657
+ return "run";
658
+ }
659
+ async closeForLeader(live, title, intent) {
660
+ this.noteHorizon(await finishTaskClose(this.ctx, live, title, intent, (desk, id) => this.control.cancelBoundWork(desk, id), (live) => this.dispose(live)));
661
+ }
662
+ async flushDeliveries(desk, deskDir) {
663
+ 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()));
665
+ }
666
+ catch (error) {
667
+ log.logWarn("tasks.delivery.drain_failed", "Task delivery drain failed", {
668
+ reason: errorMessage(error),
669
+ fields: { desk },
670
+ });
671
+ this.noteHorizon(this.ctx.now() + 60_000);
672
+ }
673
+ }
674
+ /** Let go of a task that left execution — unless a drive loop is still working on it, which then does it itself. */
675
+ async release(live) {
676
+ if (live.driving && !this.stopped)
677
+ return;
678
+ await this.dispose(live);
679
+ }
680
+ /** Dispose a task's runner and forget its in-memory state (D13). */
681
+ async dispose(live) {
682
+ if (this.ctx.live.get(live.key) === live)
683
+ this.ctx.live.delete(live.key);
684
+ const runner = live.runner;
685
+ live.runner = undefined;
686
+ if (!runner)
687
+ return;
688
+ try {
689
+ await runner.dispose();
690
+ }
691
+ catch (error) {
692
+ log.logWarn("tasks.runner.dispose_failed", "Task runner dispose failed", {
693
+ channelId: live.channelId,
694
+ reason: errorMessage(error),
695
+ fields: { taskId: live.taskId, desk: live.desk },
696
+ });
697
+ }
698
+ }
699
+ }
700
+ function compareByStart(a, b) {
701
+ const start = (seen) => seen.entry.fields.usage?.startedAt ?? "";
702
+ return start(a) < start(b) ? -1 : start(a) > start(b) ? 1 : a.entry.id.localeCompare(b.entry.id);
703
+ }