@oyasmi/pipiclaw 0.9.5 → 0.9.6-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.en.md +220 -126
  2. package/README.md +217 -123
  3. package/dist/agent/channel-runner.d.ts +1 -1
  4. package/dist/agent/channel-runner.js +1 -1
  5. package/dist/agent/prompt/sections.js +1 -1
  6. package/dist/agent/prompt/types.d.ts +2 -1
  7. package/dist/agent/session/compaction.d.ts +2 -0
  8. package/dist/agent/session/compaction.js +22 -14
  9. package/dist/agent/session/session-host.d.ts +1 -1
  10. package/dist/agent/session/session-host.js +3 -1
  11. package/dist/agent/stop-watchdog.js +5 -1
  12. package/dist/agent/turn/turn-state.d.ts +2 -0
  13. package/dist/agent/turn/turn-state.js +2 -1
  14. package/dist/agent/types.d.ts +3 -1
  15. package/dist/channel/attachments.d.ts +4 -0
  16. package/dist/channel/attachments.js +4 -0
  17. package/dist/channel/store.d.ts +1 -1
  18. package/dist/commands/catalog.js +25 -9
  19. package/dist/commands/router.js +5 -1
  20. package/dist/desk/commands.d.ts +14 -2
  21. package/dist/desk/commands.js +68 -20
  22. package/dist/desk/registry.d.ts +6 -2
  23. package/dist/desk/registry.js +70 -4
  24. package/dist/desk/types.d.ts +17 -0
  25. package/dist/dingtalk/bot.d.ts +1 -1
  26. package/dist/dingtalk/bot.js +4 -3
  27. package/dist/dingtalk/delivery.js +13 -8
  28. package/dist/dingtalk/inbound-media.d.ts +36 -14
  29. package/dist/dingtalk/inbound-media.js +71 -12
  30. package/dist/dingtalk/inbound.d.ts +9 -2
  31. package/dist/dingtalk/inbound.js +18 -2
  32. package/dist/dingtalk/media.d.ts +4 -10
  33. package/dist/dingtalk/media.js +58 -32
  34. package/dist/events/commands.d.ts +2 -0
  35. package/dist/events/commands.js +13 -8
  36. package/dist/events/history.d.ts +9 -0
  37. package/dist/events/history.js +66 -0
  38. package/dist/events/parse.js +7 -3
  39. package/dist/events/types.d.ts +3 -0
  40. package/dist/events/watcher.d.ts +3 -7
  41. package/dist/events/watcher.js +51 -56
  42. package/dist/jobs/kill.d.ts +23 -0
  43. package/dist/jobs/kill.js +65 -0
  44. package/dist/jobs/manager.d.ts +19 -18
  45. package/dist/jobs/manager.js +36 -103
  46. package/dist/memory/reflect.js +23 -3
  47. package/dist/memory/session-corpus.d.ts +1 -1
  48. package/dist/memory/session-corpus.js +70 -1
  49. package/dist/memory/session-search.js +13 -11
  50. package/dist/memory/store.d.ts +2 -0
  51. package/dist/memory/store.js +19 -9
  52. package/dist/playbooks/agent-delegation.md +5 -4
  53. package/dist/playbooks/memory-and-learning.md +1 -1
  54. package/dist/playbooks/task-lead.md +4 -4
  55. package/dist/runtime/bootstrap.d.ts +6 -0
  56. package/dist/runtime/bootstrap.js +11 -7
  57. package/dist/runtime/desk-runtime.d.ts +8 -2
  58. package/dist/runtime/desk-runtime.js +35 -4
  59. package/dist/runtime/durable-dispatch.d.ts +14 -2
  60. package/dist/runtime/durable-dispatch.js +207 -65
  61. package/dist/runtime/ingress-busy.js +17 -8
  62. package/dist/runtime/ingress-deps.d.ts +4 -1
  63. package/dist/runtime/ingress.js +6 -1
  64. package/dist/runtime/request-execution.js +7 -6
  65. package/dist/runtime/shutdown.d.ts +1 -0
  66. package/dist/runtime/shutdown.js +87 -35
  67. package/dist/runtime/task-control.d.ts +1 -0
  68. package/dist/runtime/task-control.js +25 -2
  69. package/dist/runtime/task-lane.d.ts +1 -0
  70. package/dist/runtime/task-lane.js +21 -6
  71. package/dist/runtime/task-step.js +11 -2
  72. package/dist/runtime/turn-run.js +103 -66
  73. package/dist/security/command-guard.d.ts +1 -1
  74. package/dist/security/command-guard.js +237 -314
  75. package/dist/security/path-guard.js +48 -7
  76. package/dist/security/shell-parse.d.ts +10 -0
  77. package/dist/security/shell-parse.js +224 -0
  78. package/dist/security/types.d.ts +2 -0
  79. package/dist/subagents/commands.d.ts +1 -1
  80. package/dist/subagents/detached-discovery.d.ts +1 -1
  81. package/dist/subagents/discovery.d.ts +18 -199
  82. package/dist/subagents/discovery.js +35 -289
  83. package/dist/subagents/dispatch.d.ts +1 -2
  84. package/dist/subagents/dispatch.js +39 -20
  85. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  86. package/dist/subagents/external/antigravity-cli.js +517 -0
  87. package/dist/subagents/external/claude-code.js +8 -17
  88. package/dist/subagents/external/codex-cli.js +8 -18
  89. package/dist/subagents/external/cursor-cli.js +34 -31
  90. package/dist/subagents/external/dispatch.d.ts +21 -7
  91. package/dist/subagents/external/dispatch.js +139 -11
  92. package/dist/subagents/external/exec.js +3 -0
  93. package/dist/subagents/external/harness.d.ts +57 -33
  94. package/dist/subagents/external/harness.js +69 -40
  95. package/dist/subagents/external/reconciliation.js +1 -0
  96. package/dist/subagents/external/registry.js +4 -1
  97. package/dist/subagents/external/role-warnings.d.ts +4 -13
  98. package/dist/subagents/external/role-warnings.js +4 -28
  99. package/dist/subagents/external/run.d.ts +1 -2
  100. package/dist/subagents/external/run.js +11 -11
  101. package/dist/subagents/external/settlement.d.ts +2 -0
  102. package/dist/subagents/external/settlement.js +8 -2
  103. package/dist/subagents/format.d.ts +1 -1
  104. package/dist/subagents/format.js +1 -1
  105. package/dist/subagents/internal/outcome.d.ts +1 -2
  106. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  107. package/dist/subagents/internal/provider-retry.js +1 -1
  108. package/dist/subagents/internal/run.d.ts +1 -2
  109. package/dist/subagents/internal/state.d.ts +1 -2
  110. package/dist/subagents/internal/worker.d.ts +1 -2
  111. package/dist/subagents/internal/worker.js +3 -1
  112. package/dist/subagents/resolve.d.ts +56 -0
  113. package/dist/subagents/resolve.js +202 -0
  114. package/dist/subagents/result.d.ts +1 -2
  115. package/dist/subagents/result.js +7 -3
  116. package/dist/subagents/run-record.d.ts +33 -2
  117. package/dist/subagents/run-record.js +2 -0
  118. package/dist/subagents/runs.d.ts +2 -24
  119. package/dist/subagents/runs.js +6 -0
  120. package/dist/subagents/task-envelope.d.ts +1 -2
  121. package/dist/subagents/task-envelope.js +8 -4
  122. package/dist/subagents/types.d.ts +93 -4
  123. package/dist/subagents/types.js +16 -1
  124. package/dist/subagents/workspace-lease.d.ts +11 -21
  125. package/dist/subagents/workspace-lease.js +48 -21
  126. package/dist/subagents/worktree.d.ts +10 -0
  127. package/dist/subagents/worktree.js +77 -0
  128. package/dist/tasks/archive.js +4 -0
  129. package/dist/tasks/commands.d.ts +3 -0
  130. package/dist/tasks/commands.js +16 -2
  131. package/dist/tasks/control.d.ts +2 -0
  132. package/dist/tasks/delivery.d.ts +2 -0
  133. package/dist/tasks/delivery.js +141 -21
  134. package/dist/tasks/loop-log.d.ts +2 -0
  135. package/dist/tasks/loop-log.js +9 -0
  136. package/dist/tools/bash.js +2 -0
  137. package/dist/tools/contract/presentation.js +3 -4
  138. package/dist/tools/event-manage.d.ts +2 -0
  139. package/dist/tools/event-manage.js +20 -2
  140. package/dist/tools/index.d.ts +2 -1
  141. package/dist/tools/index.js +2 -0
  142. package/dist/tools/registry.js +3 -1
  143. package/dist/tools/send-media.js +9 -5
  144. package/dist/tools/session-search.js +1 -1
  145. package/dist/tools/subagent-manage.d.ts +1 -1
  146. package/dist/tools/subagent-manage.js +15 -149
  147. package/dist/tools/subagent.d.ts +2 -0
  148. package/dist/tools/subagent.js +6 -1
  149. package/dist/tools/task-manage/factory.js +2 -2
  150. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  151. package/dist/tools/task-manage/lifecycle.js +49 -9
  152. package/dist/tools/task-manage/schema.d.ts +4 -1
  153. package/dist/tools/task-manage/schema.js +4 -1
  154. package/dist/tools/task-manage/types.d.ts +4 -1
  155. package/dist/tui/cli.d.ts +1 -6
  156. package/dist/tui/cli.js +29 -3
  157. package/dist/tui/client.d.ts +2 -0
  158. package/dist/tui/client.js +13 -4
  159. package/dist/usage/ledger.d.ts +1 -1
  160. package/dist/usage/render.js +1 -1
  161. package/examples/sub-agents/README.md +39 -73
  162. package/examples/sub-agents/agents/agy-main.md +23 -0
  163. package/examples/sub-agents/agents/claude-high.md +9 -9
  164. package/examples/sub-agents/agents/claude-main.md +9 -9
  165. package/examples/sub-agents/agents/codex-flash.md +9 -9
  166. package/examples/sub-agents/agents/codex-high.md +9 -9
  167. package/examples/sub-agents/agents/codex-main.md +9 -9
  168. package/examples/sub-agents/agents/codex-review.md +9 -9
  169. package/examples/sub-agents/agents/cursor-high.md +9 -9
  170. package/examples/sub-agents/agents/cursor-main.md +9 -9
  171. package/examples/sub-agents/agents/glm-flash.md +9 -9
  172. package/examples/sub-agents/agents/glm-high.md +9 -9
  173. package/package.json +8 -8
  174. package/examples/sub-agents/agents/scout.md +0 -30
  175. package/examples/sub-agents/roles/builder-hard.md +0 -34
  176. package/examples/sub-agents/roles/builder.md +0 -34
  177. package/examples/sub-agents/roles/explorer.md +0 -39
  178. package/examples/sub-agents/roles/git-committer.md +0 -43
  179. package/examples/sub-agents/roles/planner.md +0 -33
  180. package/examples/sub-agents/roles/reviewer.md +0 -33
  181. package/examples/sub-agents/roles/verifier.md +0 -35
  182. package/examples/sub-agents/roles/worker.md +0 -34
@@ -6,6 +6,7 @@ const SHUTDOWN_WAIT_MS = 15000;
6
6
  const SHUTDOWN_FLUSH_WAIT_MS = 45000;
7
7
  const SHUTDOWN_ABORT_WAIT_MS = 5000;
8
8
  const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
9
+ const SHUTDOWN_TOTAL_MS = 90_000;
9
10
  function waitForTasks(tasks, timeoutMs) {
10
11
  if (tasks.length === 0) {
11
12
  return Promise.resolve(true);
@@ -27,6 +28,31 @@ export function createShutdown(deps) {
27
28
  return shutdownPromise;
28
29
  }
29
30
  shutdownPromise = (async () => {
31
+ const deadline = Date.now() + SHUTDOWN_TOTAL_MS;
32
+ let closed = false;
33
+ let quiescent = true;
34
+ const wait = (tasks, budget) => waitForTasks(tasks, Math.max(0, Math.min(budget, deadline - Date.now())));
35
+ const phase = async (name, work, budget) => {
36
+ const settled = await wait([
37
+ Promise.resolve()
38
+ .then(work)
39
+ .catch((error) => {
40
+ quiescent = false;
41
+ if (!closed)
42
+ log.logWarn("runtime.shutdown.phase_failed", "Shutdown phase failed", {
43
+ reason: errorMessage(error),
44
+ fields: { phase: name },
45
+ });
46
+ }),
47
+ ], budget);
48
+ if (!settled) {
49
+ quiescent = false;
50
+ log.logWarn("runtime.shutdown.phase_timeout", "Shutdown phase failed", {
51
+ reason: "deadline exceeded",
52
+ fields: { phase: name },
53
+ });
54
+ }
55
+ };
30
56
  deps.markShuttingDown();
31
57
  log.logInfoEvent("runtime.shutdown.started", "Shutting down", { fields: { reason } });
32
58
  taskLane.stop();
@@ -37,14 +63,14 @@ export function createShutdown(deps) {
37
63
  jobs.stop();
38
64
  // Admission closes first; the transports keep delivering, so a turn that finishes inside
39
65
  // the grace window below still reaches its channel (its card, its Web API response).
40
- await transports.stopAcceptingAll();
66
+ await phase("stop-accepting", () => transports.stopAcceptingAll(), SHUTDOWN_ABORT_WAIT_MS);
41
67
  ingress.stop();
42
68
  const runningTasks = Array.from(activeTasks);
43
69
  if (runningTasks.length > 0) {
44
70
  log.logInfoEvent("runtime.shutdown.waiting", "Waiting for active turns to finish", {
45
71
  fields: { activeTurns: runningTasks.length },
46
72
  });
47
- const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
73
+ const completed = await wait(runningTasks, SHUTDOWN_WAIT_MS);
48
74
  if (!completed) {
49
75
  log.logWarn("runtime.shutdown.grace_exceeded", "Shutdown grace period exceeded; aborting active turns", {
50
76
  fields: { waitMs: SHUTDOWN_WAIT_MS },
@@ -58,21 +84,23 @@ export function createShutdown(deps) {
58
84
  channelId: channelId,
59
85
  });
60
86
  aborts.push(runner.abort().catch((err) => {
61
- log.logWarn("runtime.shutdown.abort_failed", "Turn abort during shutdown failed", {
62
- channelId: channelId,
63
- reason: errorMessage(err),
64
- });
87
+ if (!closed)
88
+ log.logWarn("runtime.shutdown.abort_failed", "Turn abort during shutdown failed", {
89
+ channelId: channelId,
90
+ reason: errorMessage(err),
91
+ });
65
92
  }));
66
93
  }
67
- await Promise.allSettled(aborts);
94
+ // abort() can itself hang before reaching the SDK. It shares the same
95
+ // abort window with the turns; it never extends the shutdown deadline.
96
+ await wait([...aborts, ...activeTasks], SHUTDOWN_ABORT_WAIT_MS);
68
97
  const remainingTasks = Array.from(activeTasks);
69
98
  if (remainingTasks.length > 0) {
70
- const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
71
- if (!abortedCompleted) {
72
- log.logWarn("runtime.shutdown.forced", "Shutdown forced with turns still active", {
73
- fields: { activeTurns: remainingTasks.length },
74
- });
75
- }
99
+ quiescent = false;
100
+ log.logWarn("runtime.shutdown.forced", "Shutdown turn drain failed", {
101
+ reason: "deadline exceeded",
102
+ fields: { activeTurns: remainingTasks.length },
103
+ });
76
104
  }
77
105
  }
78
106
  }
@@ -81,21 +109,26 @@ export function createShutdown(deps) {
81
109
  // left to unwind on its own as the process exits.
82
110
  const disposals = [];
83
111
  for (const [channelId, runner] of channelRunners) {
84
- if (runner.isBusy())
112
+ if (runner.isBusy()) {
113
+ runner.retireForRecovery();
85
114
  continue;
115
+ }
86
116
  disposals.push(runner.dispose().catch((err) => {
87
- log.logWarn("runtime.shutdown.dispose_failed", "Runner dispose during shutdown failed", {
88
- channelId: channelId,
89
- reason: errorMessage(err),
90
- });
117
+ quiescent = false;
118
+ if (!closed)
119
+ log.logWarn("runtime.shutdown.dispose_failed", "Runner dispose during shutdown failed", {
120
+ channelId: channelId,
121
+ reason: errorMessage(err),
122
+ });
91
123
  }));
92
124
  }
93
125
  if (disposals.length > 0) {
94
126
  log.logInfoEvent("runtime.shutdown.disposing", "Disposing idle channel runners", {
95
127
  fields: { count: disposals.length },
96
128
  });
97
- const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
129
+ const disposed = await wait(disposals, SHUTDOWN_FLUSH_WAIT_MS);
98
130
  if (!disposed) {
131
+ quiescent = false;
99
132
  log.logWarn("runtime.shutdown.dispose_timeout", "Runner disposal during shutdown timed out", {
100
133
  fields: { waitMs: SHUTDOWN_FLUSH_WAIT_MS },
101
134
  });
@@ -103,23 +136,42 @@ export function createShutdown(deps) {
103
136
  }
104
137
  channelRunners.clear();
105
138
  // Only now do connections close: what is still unfinished ends as interrupted.
106
- await transports.stopAll();
107
- const storageFlushes = [
108
- store.close(),
109
- // Cancels the debounce timer and lands the last activity times.
110
- channelIndex.close(),
111
- getUsageLedger().flush?.() ?? Promise.resolve(),
112
- flushSecurityLogs(),
113
- ...(deskRuntime.flush ? [deskRuntime.flush()] : []),
114
- ];
115
- const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
116
- if (!storageFlushed) {
117
- log.logWarn("runtime.shutdown.flush_timeout", "Log flush during shutdown timed out", {
118
- fields: { waitMs: SHUTDOWN_LOG_FLUSH_WAIT_MS },
119
- });
139
+ await phase("stop-transports", () => transports.stopAll(), SHUTDOWN_ABORT_WAIT_MS);
140
+ await phase("storage", async () => {
141
+ await Promise.all([
142
+ deps.getDurableDispatch()?.flush?.() ?? Promise.resolve(),
143
+ store.close(),
144
+ channelIndex.close(),
145
+ getUsageLedger().flush?.() ?? Promise.resolve(),
146
+ flushSecurityLogs(),
147
+ ...(deskRuntime.flush ? [deskRuntime.flush()] : []),
148
+ ]);
149
+ }, SHUTDOWN_LOG_FLUSH_WAIT_MS);
150
+ await phase("logging", () => log.flushLogging(), SHUTDOWN_LOG_FLUSH_WAIT_MS);
151
+ // A deadline cannot cancel an arbitrary storage promise. Do not hand this home to
152
+ // a new writer while such work (or an active turn) can still mutate it. Process exit
153
+ // makes the retained PID lock reclaimable; an embedded caller must exit before reopen.
154
+ // A task drive can finish by starting its runner's asynchronous disposal. That
155
+ // cleanup joins activeTasks synchronously and must also fence lock hand-off.
156
+ quiescent &&= activeTasks.size === 0;
157
+ closed = true;
158
+ if (quiescent) {
159
+ const released = await wait([
160
+ deps.releaseDaemonLock().catch((error) => {
161
+ log.logWarn("runtime.shutdown.unlock_failed", "Daemon lock release failed", {
162
+ reason: errorMessage(error),
163
+ });
164
+ }),
165
+ ], Math.max(0, deadline - Date.now()));
166
+ if (!released)
167
+ log.logWarn("runtime.shutdown.unlock_timeout", "Daemon lock release failed", {
168
+ reason: "deadline exceeded",
169
+ });
120
170
  }
121
- await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
122
- await deps.releaseDaemonLock();
171
+ else
172
+ log.logWarn("runtime.shutdown.lock_retained", "Shutdown quiescence failed", {
173
+ reason: "unfinished work may still write; daemon lock retained until process exit",
174
+ });
123
175
  })();
124
176
  return shutdownPromise;
125
177
  };
@@ -24,6 +24,7 @@ export declare class LaneControl implements TaskControl {
24
24
  reason: string;
25
25
  }): Promise<TaskControlOutcome>;
26
26
  resume(desk: string, id: string, grants: Partial<TaskBudget>): Promise<TaskControlOutcome>;
27
+ adopt(desk: string, id: string, channel: string): Promise<TaskControlOutcome>;
27
28
  cancel(desk: string, id: string, input: {
28
29
  by: "user";
29
30
  note: string;
@@ -4,12 +4,12 @@ import { withTimeout } from "../shared/with-timeout.js";
4
4
  import { isTaskArchiving } from "../tasks/archive.js";
5
5
  import { pendingTaskClose } from "../tasks/completion.js";
6
6
  import { extractTaskTitle, readActiveTasks } from "../tasks/contract.js";
7
- import { drainTaskDeliveries } from "../tasks/delivery.js";
7
+ import { drainTaskDeliveries, redirectTaskDeliveries } from "../tasks/delivery.js";
8
8
  import { taskInputTag } from "../tasks/input-receipts.js";
9
9
  import { appendTaskLog, readTaskLog } from "../tasks/loop-log.js";
10
10
  import { withTaskMutation } from "../tasks/mutation-lock.js";
11
11
  import { cancelledByUserReceipt } from "../tasks/receipts.js";
12
- import { closeTask as closeStoredTask, pauseTask as pauseStoredTask, readStoredTask, resumeTask as resumeStoredTask, tasksDir, } from "../tasks/store.js";
12
+ import { closeTask as closeStoredTask, pauseTask as pauseStoredTask, readStoredTask, resumeTask as resumeStoredTask, tasksDir, updateStoredTask, } from "../tasks/store.js";
13
13
  import { describeToolCall } from "../tools/contract/presentation.js";
14
14
  import { submitTaskInput } from "./task-input.js";
15
15
  import { taskKey } from "./task-lane-types.js";
@@ -157,6 +157,29 @@ export class LaneControl {
157
157
  this.ctx.notify();
158
158
  return { kind: "ok" };
159
159
  }
160
+ async adopt(desk, id, channel) {
161
+ const { ctx } = this;
162
+ const deskDir = ctx.options.getDeskDir(desk);
163
+ if (!deskDir)
164
+ return { kind: "not_found" };
165
+ const existing = await readStoredTask(deskDir, id);
166
+ if (!existing || existing.fields.outcome)
167
+ return { kind: "not_found" };
168
+ if (existing.fields.channel === channel)
169
+ return { kind: "unchanged" };
170
+ const updated = await updateStoredTask(deskDir, id, (doc) => {
171
+ doc.fields = { ...doc.fields, channel };
172
+ });
173
+ if (!updated)
174
+ return { kind: "not_found" };
175
+ const live = ctx.live.get(taskKey(desk, id));
176
+ if (live)
177
+ live.channelId = channel;
178
+ await redirectTaskDeliveries(deskDir, id, channel).catch(() => undefined);
179
+ await drainTaskDeliveries(deskDir, (targetChannel, text) => ctx.options.deliver(desk, targetChannel, text), (targetChannel) => ctx.options.isBoundTo(targetChannel, desk) && ctx.options.isReachable(targetChannel), ctx.now()).catch(() => undefined);
180
+ ctx.notify();
181
+ return { kind: "ok" };
182
+ }
160
183
  async cancel(desk, id, input) {
161
184
  const { ctx } = this;
162
185
  const deskDir = ctx.options.getDeskDir(desk);
@@ -56,6 +56,7 @@ export declare class TaskLane implements TaskControl {
56
56
  reason: string;
57
57
  }): Promise<TaskControlOutcome>;
58
58
  resume(desk: string, id: string, grants: Partial<TaskBudget>): Promise<TaskControlOutcome>;
59
+ adopt(desk: string, id: string, channel: string): Promise<TaskControlOutcome>;
59
60
  cancel(desk: string, id: string, input: {
60
61
  by: "user";
61
62
  note: string;
@@ -56,7 +56,7 @@ export class TaskLane {
56
56
  this.questionRetry = new Map();
57
57
  const timing = {
58
58
  stepTimeLimitMs: options.timing?.stepTimeLimitMs ?? STEP_TIME_LIMIT_MS,
59
- stopGraceMs: options.timing?.stopGraceMs ?? 3_000,
59
+ stopGraceMs: options.timing?.stopGraceMs ?? 15_000,
60
60
  maxSleepMs: options.timing?.maxSleepMs ?? MAX_SLEEP_MS,
61
61
  notifyDebounceMs: options.timing?.notifyDebounceMs ?? NOTIFY_DEBOUNCE_MS,
62
62
  errorBackoffMs: options.timing?.errorBackoffMs ?? ERROR_BACKOFF_MS,
@@ -152,6 +152,9 @@ export class TaskLane {
152
152
  resume(desk, id, grants) {
153
153
  return this.control.resume(desk, id, grants);
154
154
  }
155
+ adopt(desk, id, channel) {
156
+ return this.control.adopt(desk, id, channel);
157
+ }
155
158
  cancel(desk, id, input) {
156
159
  return this.control.cancel(desk, id, input);
157
160
  }
@@ -204,12 +207,17 @@ export class TaskLane {
204
207
  let entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
205
208
  let pending = await listPendingWork(this.options, desk, now);
206
209
  // D10: whatever state the previous process left becomes true to the facts before anything is decided.
210
+ let reconciled = false;
207
211
  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);
212
+ if (!isFrozen(this.ctx, desk, entry.fields)) {
213
+ if (await this.reconcile(desk, deskDir, entry, pending.get(entry.id)?.length ?? 0))
214
+ reconciled = true;
215
+ }
216
+ }
217
+ if (reconciled) {
218
+ entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
219
+ pending = await listPendingWork(this.options, desk, now);
210
220
  }
211
- entries = (await readActiveTasks(join(deskDir, "tasks"))).filter((entry) => !entry.fields.outcome);
212
- pending = await listPendingWork(this.options, desk, now);
213
221
  const seen = [];
214
222
  for (const entry of entries) {
215
223
  const key = taskKey(desk, entry.id);
@@ -686,7 +694,14 @@ export class TaskLane {
686
694
  if (!runner)
687
695
  return;
688
696
  try {
689
- await runner.dispose();
697
+ const disposal = runner.dispose();
698
+ this.options.activeTasks.add(disposal);
699
+ try {
700
+ await disposal;
701
+ }
702
+ finally {
703
+ this.options.activeTasks.delete(disposal);
704
+ }
690
705
  }
691
706
  catch (error) {
692
707
  log.logWarn("tasks.runner.dispose_failed", "Task runner dispose failed", {
@@ -69,13 +69,15 @@ export function abortStep(ctx, live, reason) {
69
69
  if (live.step !== step)
70
70
  return;
71
71
  live.quarantined = true;
72
+ if (live.runner === runner)
73
+ live.runner = undefined;
72
74
  runner.retireForRecovery();
73
75
  void pauseTask(live.deskDir, live.taskId, {
74
76
  by: "runtime",
75
- reason: "当前步骤未能停止,请联系部署者重启服务后再恢复任务",
77
+ reason: "当前步骤未能及时停止,已暂停后续执行;待该步退出后可用 /tasks resume 恢复,持续卡死时请重启服务",
76
78
  })
77
79
  .then(async () => {
78
- await ctx.options.deliver(live.desk, live.channelId, `⚠️ 任务 \`${live.taskId}\` 的当前步骤未能停止,已暂停后续执行。请联系部署者重启服务,再用 \`/tasks resume ${live.taskId}\` 恢复。`);
80
+ await ctx.options.deliver(live.desk, live.channelId, `⚠️ 任务 \`${live.taskId}\` 的当前步骤未能及时停止,已暂停后续执行。待当前步骤退出后可用 \`/tasks resume ${live.taskId}\` 恢复;若持续未退出请联系部署者重启服务。`);
79
81
  })
80
82
  .catch((error) => log.logWarn("tasks.step.quarantine_failed", "Task step quarantine failed", {
81
83
  reason: errorMessage(error),
@@ -217,6 +219,13 @@ export async function executeStep(ctx, live) {
217
219
  generation: runner.generation,
218
220
  });
219
221
  live.step = undefined;
222
+ if (live.runner !== runner) {
223
+ await runner.dispose().catch((disposeErr) => log.logWarn("tasks.runner.dispose_failed", "Retired task runner dispose failed", {
224
+ channelId: live.channelId,
225
+ reason: errorMessage(disposeErr),
226
+ fields: { taskId: live.taskId, desk: live.desk },
227
+ }));
228
+ }
220
229
  // A stop from the lane decides the result whatever the turn reported on its way out.
221
230
  switch (step.abort) {
222
231
  case "shutdown":
@@ -54,6 +54,18 @@ function turnInfoOf(event) {
54
54
  */
55
55
  export function createEventTurnRunner(deps) {
56
56
  const { transports, store, activeTasks, archiveIncomingMessage, getRunner, isShuttingDown, getDurableDispatch } = deps;
57
+ const reportDispatchFailure = (phase, event, dispatchId, operation, error) => {
58
+ log.logWarn(`dispatch.turn.${phase}_failed`, phase === "admit" ? "Wake admission failed" : "Wake settlement failed", {
59
+ channelId: event.channelId,
60
+ reason: errorMessage(error),
61
+ fields: {
62
+ dispatchId,
63
+ primaryDispatchId: event.dispatchId,
64
+ operation,
65
+ code: error?.code,
66
+ },
67
+ });
68
+ };
57
69
  /**
58
70
  * Dispatch admission: refuse a stale redelivery of a wake an earlier turn already handled (the
59
71
  * turn is released), and fold other pending completion wakes into this one. `undefined` = skip.
@@ -61,42 +73,54 @@ export function createEventTurnRunner(deps) {
61
73
  const admitTurn = async (inboundEvent, runner) => {
62
74
  let event = inboundEvent;
63
75
  const durable = getDurableDispatch();
64
- // Sampled synchronously, before any await: `/stop` after this point cleared the queued closures.
65
76
  const stopEpoch = durable?.stopEpoch(inboundEvent.channelId) ?? 0;
77
+ const claimedIds = [];
78
+ let operation = "markStarted";
79
+ let admitted = false;
66
80
  deps.reservedTurns.delete(inboundEvent);
67
- if (durable && !(await durable.markStarted(event.dispatchId))) {
68
- // A stale delivery of a wake an earlier turn already absorbed and handled.
69
- runner.endTurn();
70
- return undefined;
81
+ try {
82
+ if (durable && !(await durable.markStarted(event.dispatchId)))
83
+ return undefined;
84
+ if (durable && event.dispatchId)
85
+ claimedIds.push(event.dispatchId);
86
+ let absorbedDispatchIds = [];
87
+ if (durable && event.source === "wake" && event.dispatchId && isCoalescableWake(event)) {
88
+ operation = "absorbPending";
89
+ const primary = event;
90
+ const absorbed = await durable.absorbPending(event.channelId, event.dispatchId, (candidate) => canAbsorbWake(primary, candidate), MAX_COALESCED_WAKES - 1, stopEpoch);
91
+ absorbedDispatchIds = absorbed.flatMap((item) => (item.dispatchId ? [item.dispatchId] : []));
92
+ claimedIds.push(...absorbedDispatchIds);
93
+ if (absorbed.length > 0) {
94
+ event = mergeCompletionWakes(event, absorbed);
95
+ log.logInfoEvent("dispatch.wake.coalesced", "Completion wakes coalesced", {
96
+ channelId: event.channelId,
97
+ fields: { primary: event.dispatchId, absorbed: absorbedDispatchIds.length },
98
+ });
99
+ }
100
+ }
101
+ admitted = true;
102
+ return { event, output: undefined, absorbedDispatchIds, mergedWakesHandled: false, threw: false };
71
103
  }
72
- let absorbedDispatchIds = [];
73
- if (durable && event.source === "wake" && event.dispatchId && isCoalescableWake(event)) {
74
- const primary = event;
75
- const absorbed = await durable
76
- .absorbPending(event.channelId, event.dispatchId, (candidate) => canAbsorbWake(primary, candidate), MAX_COALESCED_WAKES - 1, stopEpoch)
77
- .catch((error) => {
78
- log.logWarn("dispatch.wake.absorb_failed", "Wake coalescing failed", {
79
- channelId: event.channelId,
80
- reason: errorMessage(error),
81
- });
82
- return [];
83
- });
84
- if (absorbed.length > 0) {
85
- event = mergeCompletionWakes(event, absorbed);
86
- absorbedDispatchIds = absorbed.flatMap((absorbedEvent) => absorbedEvent.dispatchId ? [absorbedEvent.dispatchId] : []);
87
- log.logInfoEvent("dispatch.wake.coalesced", "Completion wakes coalesced", {
88
- channelId: event.channelId,
89
- fields: { primary: event.dispatchId, absorbed: absorbedDispatchIds.length },
90
- });
104
+ catch (error) {
105
+ reportDispatchFailure("admit", inboundEvent, inboundEvent.dispatchId, operation, error);
106
+ // Admission never reached execution. Release successful claims for redelivery, not
107
+ // completion. A failed rollback keeps its original record and is diagnosed separately.
108
+ for (const id of claimedIds) {
109
+ if (!deps.isCurrentRunner(runner))
110
+ break;
111
+ try {
112
+ await durable?.markRetryable(id);
113
+ }
114
+ catch (retryError) {
115
+ reportDispatchFailure("settle", inboundEvent, id, "markRetryable", retryError);
116
+ }
91
117
  }
118
+ throw error;
119
+ }
120
+ finally {
121
+ if (!admitted)
122
+ runner.endTurn();
92
123
  }
93
- return {
94
- event,
95
- output: undefined,
96
- absorbedDispatchIds,
97
- mergedWakesHandled: false,
98
- threw: false,
99
- };
100
124
  };
101
125
  /** Say something to the channel in answer to `event`, carrying its reference back to the transport. */
102
126
  const replyTo = (transport, event, text, opts) => transport.push(event.channelId, {
@@ -215,45 +239,58 @@ export function createEventTurnRunner(deps) {
215
239
  /** Always runs: finish the output, settle the dispatch records, release the turn. */
216
240
  const finishTurn = async (turn, runner) => {
217
241
  const { event } = turn;
218
- // The runner finishes the output when it runs; a command, or a turn that failed before the
219
- // runner took over, finishes here so the transport never keeps one open. A human message that
220
- // threw before any output was opened still gets one, so its transport sees it end.
221
- if (!turn.output && turn.threw && event.source === "human") {
222
- const transport = transports.forChannel(event.channelId);
223
- if (transport)
224
- turn.output = trackOutput(transport.openTurn(turnInfoOf(event), { quiet: true }));
225
- }
226
- if (turn.output && !turn.output.finished) {
227
- const outcome = turn.threw
228
- ? {
229
- kind: "failed",
230
- message: TURN_FAILED_MESSAGE,
231
- usage: createEmptyUsageTotals(),
232
- executionDesk: runner.conversation.desk,
233
- }
234
- : { kind: "completed", usage: createEmptyUsageTotals(), executionDesk: runner.conversation.desk };
235
- await turn.output.ctx.finish(outcome).catch((error) => {
236
- log.logWarn("delivery.close.failed", "Delivery close failed", {
237
- channelId: event.channelId,
238
- reason: errorMessage(error),
242
+ const errors = [];
243
+ const settle = async (id, operation) => {
244
+ if (!deps.isCurrentRunner(runner))
245
+ return;
246
+ try {
247
+ await getDurableDispatch()?.[operation](id);
248
+ }
249
+ catch (error) {
250
+ errors.push(error);
251
+ reportDispatchFailure("settle", event, id, operation, error);
252
+ }
253
+ };
254
+ try {
255
+ // The runner finishes the output when it runs; a command, or a turn that failed before the
256
+ // runner took over, finishes here so the transport never keeps one open. A human message that
257
+ // threw before any output was opened still gets one, so its transport sees it end.
258
+ if (!turn.output && turn.threw && event.source === "human") {
259
+ const transport = transports.forChannel(event.channelId);
260
+ if (transport)
261
+ turn.output = trackOutput(transport.openTurn(turnInfoOf(event), { quiet: true }));
262
+ }
263
+ if (turn.output && !turn.output.finished) {
264
+ const outcome = turn.threw
265
+ ? {
266
+ kind: "failed",
267
+ message: TURN_FAILED_MESSAGE,
268
+ usage: createEmptyUsageTotals(),
269
+ executionDesk: runner.conversation.desk,
270
+ }
271
+ : { kind: "completed", usage: createEmptyUsageTotals(), executionDesk: runner.conversation.desk };
272
+ await turn.output.ctx.finish(outcome).catch((error) => {
273
+ log.logWarn("delivery.close.failed", "Delivery close failed", {
274
+ channelId: event.channelId,
275
+ reason: errorMessage(error),
276
+ });
239
277
  });
240
- });
278
+ }
279
+ if (!deps.isCurrentRunner(runner))
280
+ return;
281
+ await settle(event.dispatchId, "markCompleted");
282
+ // Failure of one record must not strand later absorbed claims. Re-check ownership
283
+ // before each await: /new or watchdog recovery may replace the runner meanwhile.
284
+ const stopped = !turn.mergedWakesHandled || runner.getTurnStatus().stopRequested;
285
+ for (const id of turn.absorbedDispatchIds)
286
+ await settle(id, stopped ? "markRetryable" : "markCompleted");
287
+ if (errors.length)
288
+ throw new AggregateError(errors, "Durable wake settlement failed; inspect the logged dispatch ids and storage errors before retrying.");
241
289
  }
242
- if (!deps.isCurrentRunner(runner)) {
290
+ finally {
291
+ // Release the captured runner, never whichever generation now owns the channel.
243
292
  runner.endTurn();
244
- return;
245
- }
246
- await getDurableDispatch()?.markCompleted(event.dispatchId);
247
- // A stopped turn has not finished handling its merged notifications. Release their
248
- // claims even if /stop's asynchronous cancelChannel reset raced admission or failed.
249
- const stopped = !turn.mergedWakesHandled || runner.getTurnStatus().stopRequested;
250
- for (const absorbedId of turn.absorbedDispatchIds) {
251
- if (stopped)
252
- await getDurableDispatch()?.markRetryable(absorbedId);
253
- else
254
- await getDurableDispatch()?.markCompleted(absorbedId);
255
293
  }
256
- runner.endTurn();
257
294
  };
258
295
  /** Release a turn `reserveEvent` began for an event that admission then refused. */
259
296
  const releaseReservation = (event) => {
@@ -4,8 +4,8 @@ interface ParsedCommand {
4
4
  args: string[];
5
5
  normalized: string;
6
6
  }
7
- declare function splitCommandChain(command: string): string[];
8
7
  declare function parseShellWords(command: string): string[];
8
+ declare function splitCommandChain(command: string): string[];
9
9
  declare function parseCommand(command: string): ParsedCommand | null;
10
10
  export declare function guardCommand(command: string, config: SecurityConfig["commandGuard"]): CommandGuardResult;
11
11
  export declare const internalCommandGuard: {