@oyasmi/pipiclaw 0.9.0-beta.6 → 0.9.0-beta.8

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 (82) hide show
  1. package/dist/agent/channel-runner.d.ts +8 -0
  2. package/dist/agent/channel-runner.js +154 -132
  3. package/dist/agent/commands.d.ts +6 -0
  4. package/dist/agent/job-manager.js +6 -10
  5. package/dist/agent/progress-formatter.js +3 -3
  6. package/dist/index.d.ts +2 -1
  7. package/dist/index.js +2 -1
  8. package/dist/main.js +2 -1
  9. package/dist/memory/extraction.js +0 -1
  10. package/dist/memory/maintenance-gates.d.ts +1 -1
  11. package/dist/memory/maintenance-jobs.js +2 -3
  12. package/dist/memory/metadata.d.ts +0 -15
  13. package/dist/memory/metadata.js +0 -7
  14. package/dist/memory/probation.d.ts +1 -5
  15. package/dist/memory/probation.js +2 -6
  16. package/dist/memory/review-log.js +0 -0
  17. package/dist/memory/scheduler.d.ts +1 -0
  18. package/dist/memory/scheduler.js +64 -6
  19. package/dist/models/auth-cli.d.ts +1 -1
  20. package/dist/models/auth-cli.js +3 -2
  21. package/dist/paths.d.ts +0 -6
  22. package/dist/paths.js +0 -6
  23. package/dist/playbooks/agent-delegation.md +2 -2
  24. package/dist/runtime/app-home.d.ts +32 -0
  25. package/dist/runtime/app-home.js +319 -0
  26. package/dist/runtime/bootstrap.d.ts +1 -67
  27. package/dist/runtime/bootstrap.js +114 -512
  28. package/dist/runtime/delivery.js +1 -1
  29. package/dist/runtime/dingtalk.d.ts +7 -6
  30. package/dist/runtime/dingtalk.js +5 -13
  31. package/dist/runtime/durable-dispatch.d.ts +1 -0
  32. package/dist/runtime/durable-dispatch.js +36 -25
  33. package/dist/runtime/subagent-commands.js +48 -10
  34. package/dist/runtime/task-wake.d.ts +54 -0
  35. package/dist/runtime/task-wake.js +99 -0
  36. package/dist/shared/host-process.d.ts +25 -9
  37. package/dist/shared/host-process.js +59 -10
  38. package/dist/shared/wake-claim.d.ts +23 -0
  39. package/dist/shared/wake-claim.js +26 -0
  40. package/dist/subagents/discovery.d.ts +25 -1
  41. package/dist/subagents/discovery.js +108 -17
  42. package/dist/subagents/external/claude-code.js +13 -5
  43. package/dist/subagents/external/codex-cli.js +9 -3
  44. package/dist/subagents/external/exec.js +1 -0
  45. package/dist/subagents/external/harness.d.ts +22 -0
  46. package/dist/subagents/external/harness.js +40 -7
  47. package/dist/subagents/external/run.d.ts +23 -3
  48. package/dist/subagents/external/run.js +113 -123
  49. package/dist/subagents/external/settlement.d.ts +50 -0
  50. package/dist/subagents/external/settlement.js +123 -0
  51. package/dist/subagents/format.d.ts +4 -0
  52. package/dist/subagents/format.js +7 -0
  53. package/dist/subagents/runs.d.ts +70 -13
  54. package/dist/subagents/runs.js +202 -118
  55. package/dist/subagents/tool.d.ts +27 -2
  56. package/dist/subagents/tool.js +92 -48
  57. package/dist/subagents/verification-outcome.d.ts +26 -0
  58. package/dist/subagents/verification-outcome.js +16 -0
  59. package/dist/subagents/workspace-lease.d.ts +10 -1
  60. package/dist/subagents/workspace-lease.js +15 -2
  61. package/dist/tools/index.js +6 -0
  62. package/dist/tools/memory-manage.js +0 -1
  63. package/dist/tools/subagent-manage.d.ts +20 -6
  64. package/dist/tools/subagent-manage.js +86 -16
  65. package/dist/tui/app.d.ts +1 -1
  66. package/dist/tui/app.js +3 -2
  67. package/dist/tui/cli.d.ts +1 -1
  68. package/dist/tui/cli.js +1 -1
  69. package/dist/tui/terminal-media-sender.d.ts +1 -1
  70. package/examples/sub-agents/README.md +15 -14
  71. package/examples/sub-agents/builder-hard.md +9 -8
  72. package/examples/sub-agents/builder.md +12 -11
  73. package/examples/sub-agents/documenter.md +11 -12
  74. package/examples/sub-agents/explorer.md +16 -13
  75. package/examples/sub-agents/git-committer.md +17 -16
  76. package/examples/sub-agents/log-sifter.md +19 -16
  77. package/examples/sub-agents/planner.md +17 -17
  78. package/examples/sub-agents/reviewer.md +13 -21
  79. package/examples/sub-agents/scout.md +5 -4
  80. package/examples/sub-agents/verifier.md +8 -12
  81. package/examples/sub-agents/worker.md +7 -6
  82. package/package.json +1 -1
@@ -128,7 +128,7 @@ class ChannelDeliveryController {
128
128
  if (this.progressStartedAt === 0) {
129
129
  this.progressStartedAt = Date.now();
130
130
  }
131
- if (text.startsWith("▶ ")) {
131
+ if (text.startsWith("➜ ")) {
132
132
  this.toolCallCount++;
133
133
  }
134
134
  if (this.progressSegments.length > 0) {
@@ -1,3 +1,4 @@
1
+ import { type RuntimeCommandName } from "../agent/commands.js";
1
2
  import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "./channel-context.js";
2
3
  import type { ChannelObservation } from "./channel-index.js";
3
4
  export type BusyMessageMode = "steer" | "followUp";
@@ -81,12 +82,12 @@ export interface DingTalkHandler {
81
82
  reserveEvent?(event: DingTalkEvent): void;
82
83
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
83
84
  handleStop(channelId: string, bot: DingTalkBot): Promise<StopOutcome>;
84
- handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
85
- handleTasksCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
86
- handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
87
- handleUsageCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
88
- handleContextCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
89
- handleSubagentsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
85
+ /**
86
+ * Render one of the stateless report commands (events/tasks/status/usage/context/subagents) to
87
+ * text. Single dispatch point shared by the busy-turn switch below and bootstrap's idle-turn
88
+ * switch — both used to hand-copy the same six-case table.
89
+ */
90
+ runRuntimeCommand(event: DingTalkEvent, name: RuntimeCommandName, args: string): Promise<string>;
90
91
  handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
91
92
  }
92
93
  export declare class DingTalkBot implements MediaSender {
@@ -11,7 +11,7 @@ import axios from "axios";
11
11
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
12
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
- import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp } from "../agent/commands.js";
14
+ import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, } from "../agent/commands.js";
15
15
  import * as log from "../log.js";
16
16
  import { errorMessage } from "../shared/text-utils.js";
17
17
  import { isRecord } from "../shared/type-guards.js";
@@ -1094,23 +1094,15 @@ export class DingTalkBot {
1094
1094
  return;
1095
1095
  }
1096
1096
  case "events":
1097
- await this.handler.handleEventsCommand(event, this, builtInCommand.args);
1098
- return;
1099
1097
  case "tasks":
1100
- await this.handler.handleTasksCommand(event, this, builtInCommand.args);
1101
- return;
1102
1098
  case "status":
1103
- await this.handler.handleStatusCommand(event, this);
1104
- return;
1105
1099
  case "usage":
1106
- await this.handler.handleUsageCommand(event, this, builtInCommand.args);
1107
- return;
1108
1100
  case "context":
1109
- await this.handler.handleContextCommand(event, this, builtInCommand.args);
1110
- return;
1111
- case "subagents":
1112
- await this.handler.handleSubagentsCommand(event, this, builtInCommand.args);
1101
+ case "subagents": {
1102
+ const response = await this.handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
1103
+ await this.sendPlain(channelId, response);
1113
1104
  return;
1105
+ }
1114
1106
  }
1115
1107
  }
1116
1108
  // Session commands (/model, /new, …) and unknown slash commands cannot
@@ -39,6 +39,7 @@ export declare class DurableDispatchService {
39
39
  * can retry the same dispatch id instead of losing the only completion signal. */
40
40
  markRetryable(id: string | undefined): Promise<void>;
41
41
  drainOnce(now?: number): Promise<void>;
42
+ private drainRecord;
42
43
  private read;
43
44
  private write;
44
45
  }
@@ -105,9 +105,11 @@ export class DurableDispatchService {
105
105
  };
106
106
  await this.write(record);
107
107
  });
108
- await this.drainOnce();
108
+ // Only this record needs draining here — a full directory scan would pay for every other
109
+ // channel's outstanding record just to learn the outcome of the one just written.
110
+ await this.drainRecord(id, Date.now());
109
111
  // The record is gone (delivered+completed already) or no longer "pending"
110
- // (drainOnce only reverts to "pending" when bot.enqueueEvent rejected it).
112
+ // (drainRecord only reverts to "pending" when bot.enqueueEvent rejected it).
111
113
  const after = await this.read(id);
112
114
  return after?.status !== "pending";
113
115
  }
@@ -186,32 +188,41 @@ export class DurableDispatchService {
186
188
  }
187
189
  for (const filename of filenames) {
188
190
  const id = filename.slice(0, -".json".length);
189
- await this.queue.run(id, async () => {
190
- const record = await this.read(id);
191
- if (!record)
192
- return;
193
- // The turn is still running in this process: renew its lease rather than treating a
194
- // long turn as a lost one and redelivering the wake underneath it (D2).
195
- if (record.status === "running" && this.running.has(id)) {
191
+ await this.drainRecord(id, now);
192
+ }
193
+ }
194
+ async drainRecord(id, now) {
195
+ await this.queue.run(id, async () => {
196
+ const record = await this.read(id);
197
+ if (!record)
198
+ return;
199
+ // The turn is still running in this process: renew its lease rather than treating a
200
+ // long turn as a lost one and redelivering the wake underneath it (D2).
201
+ if (record.status === "running" && this.running.has(id)) {
202
+ const currentLeaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : 0;
203
+ // Only persist the renewal once the lease is more than halfway to expiry, instead of
204
+ // on every drain tick — a live holder gets rediscovered by the next tick regardless,
205
+ // so there is no correctness reason to fsync a rename this often.
206
+ if (currentLeaseMs - now < this.leaseMs / 2) {
196
207
  record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
197
208
  await this.write(record);
198
- return;
199
209
  }
200
- const leaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : undefined;
201
- if ((record.status === "queued" || record.status === "running") && leaseMs && leaseMs > now)
202
- return;
203
- record.status = "queued";
204
- record.deliveries++;
205
- record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
206
- await this.write(record);
207
- const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
208
- if (accepted)
209
- return;
210
- record.status = "pending";
211
- record.leaseExpiresAt = undefined;
212
- await this.write(record);
213
- });
214
- }
210
+ return;
211
+ }
212
+ const leaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : undefined;
213
+ if ((record.status === "queued" || record.status === "running") && leaseMs && leaseMs > now)
214
+ return;
215
+ record.status = "queued";
216
+ record.deliveries++;
217
+ record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
218
+ await this.write(record);
219
+ const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
220
+ if (accepted)
221
+ return;
222
+ record.status = "pending";
223
+ record.leaseExpiresAt = undefined;
224
+ await this.write(record);
225
+ });
215
226
  }
216
227
  async read(id) {
217
228
  try {
@@ -1,7 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { errorMessage } from "../shared/text-utils.js";
4
- import { elapsedMs, formatCost, formatDuration, harnessLabel } from "../subagents/format.js";
4
+ import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
5
5
  import { getSubAgentRunManager } from "../subagents/runs.js";
6
6
  function usage() {
7
7
  return `# 委派 Run
@@ -69,7 +69,7 @@ function statusLabel(status) {
69
69
  }
70
70
  }
71
71
  function formatRunLine(record) {
72
- const bits = [harnessLabel(record), formatDuration(elapsedMs(record))];
72
+ const bits = [harnessLabel(record), formatRunDuration(record)];
73
73
  if (record.taskId)
74
74
  bits.push(`task ${record.taskId}`);
75
75
  if (record.leaseKey)
@@ -108,6 +108,18 @@ function formatRolesTail(discovery) {
108
108
  return line;
109
109
  }
110
110
  const DEFAULT_LIST_COMPLETED_LIMIT = 5;
111
+ /** Spec 042 D9: `running`/`failed`/`all` had no cap at all — a long-lived channel with thousands
112
+ * of historical runs (GC now reclaims them after 7 days, but that is still a lot in a busy week)
113
+ * would otherwise dump an unbounded list into a single reply. */
114
+ const LIST_FILTER_CAP = 50;
115
+ function capListForDisplay(records) {
116
+ if (records.length <= LIST_FILTER_CAP)
117
+ return { shown: records };
118
+ return {
119
+ shown: records.slice(0, LIST_FILTER_CAP),
120
+ truncatedNote: `显示最近 ${LIST_FILTER_CAP} 条,共 ${records.length} 条——用更具体的筛选缩小范围。`,
121
+ };
122
+ }
111
123
  async function listRuns(options, filter) {
112
124
  const records = getSubAgentRunManager(options.channelId).list();
113
125
  if (records.length === 0)
@@ -118,17 +130,25 @@ async function listRuns(options, filter) {
118
130
  .sort((a, b) => (b.finishedAt ?? b.startedAt) - (a.finishedAt ?? a.startedAt));
119
131
  const sections = [];
120
132
  if (filter === "running") {
121
- sections.push(running.length === 0 ? "没有正在运行的 run。" : running.map(formatRunLine).join("\n"));
122
- return `# 委派 Run — 运行中\n\n${sections.join("\n")}`;
133
+ const { shown, truncatedNote } = capListForDisplay(running);
134
+ sections.push(shown.length === 0 ? "没有正在运行的 run。" : shown.map(formatRunLine).join("\n"));
135
+ if (truncatedNote)
136
+ sections.push(truncatedNote);
137
+ return `# 委派 Run — 运行中\n\n${sections.join("\n\n")}`;
123
138
  }
124
139
  if (filter === "failed") {
125
- const failed = terminal.filter((record) => record.status === "failed");
126
- sections.push(failed.length === 0 ? "没有失败的 run。" : failed.map(formatRunLine).join("\n"));
127
- return `# 委派 Run — 失败\n\n${sections.join("\n")}`;
140
+ const { shown, truncatedNote } = capListForDisplay(terminal.filter((record) => record.status === "failed"));
141
+ sections.push(shown.length === 0 ? "没有失败的 run。" : shown.map(formatRunLine).join("\n"));
142
+ if (truncatedNote)
143
+ sections.push(truncatedNote);
144
+ return `# 委派 Run — 失败\n\n${sections.join("\n\n")}`;
128
145
  }
129
146
  if (filter === "all") {
130
- sections.push([...running, ...terminal].map(formatRunLine).join("\n"));
131
- return `# 委派 Run — 全部(${records.length})\n\n${sections.join("\n")}`;
147
+ const { shown, truncatedNote } = capListForDisplay([...running, ...terminal]);
148
+ sections.push(shown.map(formatRunLine).join("\n"));
149
+ if (truncatedNote)
150
+ sections.push(truncatedNote);
151
+ return `# 委派 Run — 全部(${records.length})\n\n${sections.join("\n\n")}`;
132
152
  }
133
153
  // default: an overview — every running run, plus a capped tail of recent completions.
134
154
  if (running.length > 0) {
@@ -169,7 +189,7 @@ async function showRun(channelId, ref) {
169
189
  "",
170
190
  `角色:${record.agent} (${harnessLabel(record)}, ${record.source})`,
171
191
  `标签:${record.label}`,
172
- `状态:${statusLabel(record.status)}(耗时 ${formatDuration(elapsedMs(record))})`,
192
+ `状态:${statusLabel(record.status)}(耗时 ${formatRunDuration(record)})`,
173
193
  ];
174
194
  if (record.failureReason)
175
195
  lines.push(`失败原因:${record.failureReason}`);
@@ -190,6 +210,18 @@ async function showRun(channelId, ref) {
190
210
  lines.push(`usage:input=${record.usage.input} output=${record.usage.output}${cost ? ` cost=${cost}` : record.costKnown ? "" : "(cost 未知)"}`);
191
211
  if (record.argv)
192
212
  lines.push("", "实际 argv:", "```", JSON.stringify(record.argv), "```");
213
+ if (record.parserVersion !== undefined || record.cliVersion) {
214
+ // Spec 042 D12: lets a human tell "the target CLI's own protocol drifted out from under this
215
+ // adapter" apart from "the agent itself failed" — the two look identical from status alone.
216
+ const parts = [];
217
+ if (record.parserVersion !== undefined)
218
+ parts.push(`parserVersion=${record.parserVersion}`);
219
+ parts.push(`cliVersion=${record.cliVersion ?? "(未知)"}`);
220
+ lines.push(`适配器/CLI:${parts.join(",")}`);
221
+ }
222
+ if (record.invocationWarnings?.length) {
223
+ lines.push("", "⚠ 派发时的警告:", ...record.invocationWarnings.map((warning) => `- ${warning}`));
224
+ }
193
225
  if (record.sessionId)
194
226
  lines.push(`sessionId:\`${record.sessionId}\`(可用于 subagent_manage op=follow_up)`);
195
227
  if (record.runtime === "external") {
@@ -261,6 +293,12 @@ function formatRoleDetail(agent) {
261
293
  lines.push(`command:\`${agent.command ?? ""}\`${agent.shell ? "(通过 shell 执行)" : ""}`, `maxWallTimeSec:${agent.maxWallTimeSec}`);
262
294
  if (agent.externalModelRef)
263
295
  lines.push(`模型:${agent.externalModelRef}`);
296
+ // spec 042 D4: contextMode/memory are effective for external roles too (memory 默认 none,
297
+ // 显式声明 session/relevant 才会把频道会话状态发给外部进程) — 显示出来而不是只在内置分支里说明。
298
+ lines.push(`contextMode:${agent.contextMode},memory:${agent.memory}`);
299
+ if (agent.memory !== "none") {
300
+ lines.push(`⚠ 该角色会把频道会话状态/记忆片段发送给外部进程(memory: ${agent.memory})`);
301
+ }
264
302
  }
265
303
  if (agent.paths.length > 0)
266
304
  lines.push(`paths:${agent.paths.join(", ")}`);
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Verifying and claiming a background job's or delegation run's completion wake before it may
3
+ * activate a task parked with `waitingFor` (spec 040, D7/T9). Split out of `bootstrap.ts`: these
4
+ * are pure functions over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
+ * `createRuntimeContext`'s closures.
6
+ */
7
+ import { type JobSnapshot } from "../agent/job-manager.js";
8
+ import type { Executor } from "../executor.js";
9
+ import { type RunRecord } from "../subagents/runs.js";
10
+ import { type WakeTaskTransitionHooks } from "../tasks/store.js";
11
+ import type { DingTalkEvent } from "./dingtalk.js";
12
+ /**
13
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
14
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
15
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
16
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
17
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
18
+ * untrusted stdout.
19
+ */
20
+ export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, taskId: string): boolean;
21
+ /**
22
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
23
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
24
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
25
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
26
+ */
27
+ export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
28
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
29
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
30
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
31
+ export declare function isTrustedInternalWake(event: DingTalkEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is DingTalkEvent & {
32
+ dispatchId: string;
33
+ };
34
+ export interface ClaimedDelegationWake {
35
+ taskId: string;
36
+ generation?: number;
37
+ activated: boolean;
38
+ finish(): Promise<void>;
39
+ rollback(): Promise<void>;
40
+ }
41
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
42
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
43
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
44
+ export declare function claimVerifiedDelegationWake(event: DingTalkEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
45
+ export interface ClaimedJobWake {
46
+ taskId: string;
47
+ generation?: number;
48
+ activated: boolean;
49
+ finish(): Promise<void>;
50
+ }
51
+ /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
52
+ * <taskId>.` completion wake. A background job has no handoff/rollback bookkeeping — its wake
53
+ * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
54
+ export declare function claimVerifiedJobWake(event: DingTalkEvent, workspaceDir: string, executor: Executor, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Verifying and claiming a background job's or delegation run's completion wake before it may
3
+ * activate a task parked with `waitingFor` (spec 040, D7/T9). Split out of `bootstrap.ts`: these
4
+ * are pure functions over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
+ * `createRuntimeContext`'s closures.
6
+ */
7
+ import { getChannelJobManager } from "../agent/job-manager.js";
8
+ import { getSubAgentRunManager } from "../subagents/runs.js";
9
+ import { activateWaitingTaskAndClaimAttempt, finishWakeTaskActivation, rollbackWakeTaskActivation, } from "../tasks/store.js";
10
+ import { getChannelDir } from "./channel-paths.js";
11
+ /**
12
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
13
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
14
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
15
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
16
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
17
+ * untrusted stdout.
18
+ */
19
+ export function isVerifiedJobWake(jobs, jobId, taskId) {
20
+ const job = jobs.find((candidate) => candidate.id === jobId);
21
+ return job !== undefined && job.status !== "running" && job.taskId === taskId;
22
+ }
23
+ /**
24
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
25
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
26
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
27
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
28
+ */
29
+ export function isVerifiedDelegationWake(record, taskId) {
30
+ return record !== undefined && record.settledAt !== undefined && record.taskId === taskId;
31
+ }
32
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
33
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
34
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
35
+ export function isTrustedInternalWake(event, kind, resourceId, taskId) {
36
+ const wake = event.internalWake;
37
+ return (wake?.kind === kind &&
38
+ wake.resourceId === resourceId &&
39
+ wake.taskId === taskId &&
40
+ typeof event.dispatchId === "string" &&
41
+ wake.dispatchId === event.dispatchId);
42
+ }
43
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
44
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
45
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
46
+ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
47
+ const wake = event.internalWake;
48
+ if (wake?.kind !== "subagent")
49
+ return undefined;
50
+ const runManager = getSubAgentRunManager(event.channelId);
51
+ const record = runManager.get(wake.resourceId);
52
+ if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
53
+ !isVerifiedDelegationWake(record, wake.taskId) ||
54
+ !(await runManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
55
+ return undefined;
56
+ }
57
+ const channelDir = getChannelDir(workspaceDir, event.channelId);
58
+ const handoff = {
59
+ kind: "subagent",
60
+ resourceId: wake.resourceId,
61
+ dispatchId: event.dispatchId,
62
+ };
63
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, wake.taskId, "external-signal", new Date(), hooks, handoff);
64
+ return {
65
+ taskId: wake.taskId,
66
+ generation: activated?.generation,
67
+ activated: activated !== undefined,
68
+ finish: async () => {
69
+ await runManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
70
+ await finishWakeTaskActivation(channelDir, wake.taskId, handoff);
71
+ },
72
+ rollback: () => rollbackWakeTaskActivation(channelDir, wake.taskId, handoff),
73
+ };
74
+ }
75
+ /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
76
+ * <taskId>.` completion wake. A background job has no handoff/rollback bookkeeping — its wake
77
+ * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
78
+ export async function claimVerifiedJobWake(event, workspaceDir, executor, hooks) {
79
+ const wake = event.internalWake;
80
+ if (wake?.kind !== "job")
81
+ return undefined;
82
+ const jobManager = getChannelJobManager(event.channelId, executor);
83
+ const jobs = await jobManager.list();
84
+ if (!isTrustedInternalWake(event, "job", wake.resourceId, wake.taskId) ||
85
+ !isVerifiedJobWake(jobs, wake.resourceId, wake.taskId) ||
86
+ !(await jobManager.beginWakeConsumption(wake.resourceId, wake.taskId, event.dispatchId))) {
87
+ return undefined;
88
+ }
89
+ const channelDir = getChannelDir(workspaceDir, event.channelId);
90
+ const activated = await activateWaitingTaskAndClaimAttempt(channelDir, wake.taskId, "job", new Date(), hooks);
91
+ return {
92
+ taskId: wake.taskId,
93
+ generation: activated?.generation,
94
+ activated: activated !== undefined,
95
+ finish: async () => {
96
+ await jobManager.finishWakeConsumption(wake.resourceId, event.dispatchId);
97
+ },
98
+ };
99
+ }
@@ -5,17 +5,33 @@
5
5
  * never as proof either way.
6
6
  */
7
7
  export declare function readProcessStartTime(pid: number): Promise<string | undefined>;
8
+ /**
9
+ * Best-effort `<executable> --version`, so a run persists which build of the target CLI it ran
10
+ * against (spec 042 D12) — the other half of `parserVersion`'s "adapter drift vs. agent failure"
11
+ * diagnosis. `undefined` on any failure or timeout; this must never block or fail a dispatch over
12
+ * a CLI that does not support `--version`, is slow to start, or fails outright.
13
+ */
14
+ export declare function probeCliVersion(executable: string): Promise<string | undefined>;
8
15
  /** True if `pid` names a live process this user can at least see, without sending a real signal. */
9
16
  export declare function isProcessAlive(pid: number): boolean;
17
+ /** True if any process in `pid`'s process group is still alive — probes the *group* (`-pid`), not
18
+ * just the leader, so a leader that already exited while a lingering descendant (e.g. a shell
19
+ * that forked and returned) is still running is correctly reported as "still something there". */
20
+ export declare function isProcessGroupAlive(pid: number): boolean;
10
21
  /**
11
- * SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
12
- * `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
13
- * it and everything it spawned.
14
- *
15
- * The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
16
- * lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
17
- * report false while the descendant is still alive and still holding the workspace, so probing
18
- * only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
19
- * A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
22
+ * SIGTERM the process group, then unconditionally SIGKILL it after `graceMs`. `detached: true` at
23
+ * spawn time makes the child its own process-group leader, so `-pid` reaches it and everything it
24
+ * spawned. The SIGKILL is not gated on a liveness probe first: a dead group simply makes it a
25
+ * harmless ESRCH, caught below — probing first would only add a syscall on the already-rare path
26
+ * where this function is used to actually terminate something (cancel/timeout, not a normal exit).
20
27
  */
21
28
  export declare function killProcessGroup(pid: number, graceMs?: number): Promise<void>;
29
+ /**
30
+ * Spec 042 D8: cleanup after a *normal* exit, as opposed to `killProcessGroup`'s explicit
31
+ * cancel/timeout termination. The common case — nothing left in the group — returns immediately
32
+ * with no signal and no wait, so a normal settlement no longer pays `killProcessGroup`'s grace
33
+ * period on every single run. The rare case — a descendant outlived its already-exited leader —
34
+ * still needs terminating, so it falls through to the same TERM-then-KILL sequence, just off the
35
+ * hot path and with a short grace since a genuinely finished CLI has nothing left to flush.
36
+ */
37
+ export declare function reapProcessGroup(pid: number): Promise<void>;
@@ -24,6 +24,24 @@ export async function readProcessStartTime(pid) {
24
24
  return undefined;
25
25
  }
26
26
  }
27
+ const CLI_VERSION_PROBE_TIMEOUT_MS = 1_000;
28
+ const CLI_VERSION_MAX_CHARS = 200;
29
+ /**
30
+ * Best-effort `<executable> --version`, so a run persists which build of the target CLI it ran
31
+ * against (spec 042 D12) — the other half of `parserVersion`'s "adapter drift vs. agent failure"
32
+ * diagnosis. `undefined` on any failure or timeout; this must never block or fail a dispatch over
33
+ * a CLI that does not support `--version`, is slow to start, or fails outright.
34
+ */
35
+ export async function probeCliVersion(executable) {
36
+ try {
37
+ const { stdout } = await execFileAsync(executable, ["--version"], { timeout: CLI_VERSION_PROBE_TIMEOUT_MS });
38
+ const value = stdout.trim().split("\n")[0]?.slice(0, CLI_VERSION_MAX_CHARS);
39
+ return value || undefined;
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
27
45
  /** True if `pid` names a live process this user can at least see, without sending a real signal. */
28
46
  export function isProcessAlive(pid) {
29
47
  try {
@@ -35,18 +53,36 @@ export function isProcessAlive(pid) {
35
53
  return error.code === "EPERM";
36
54
  }
37
55
  }
56
+ /** True if any process in `pid`'s process group is still alive — probes the *group* (`-pid`), not
57
+ * just the leader, so a leader that already exited while a lingering descendant (e.g. a shell
58
+ * that forked and returned) is still running is correctly reported as "still something there". */
59
+ export function isProcessGroupAlive(pid) {
60
+ try {
61
+ process.kill(-pid, 0);
62
+ return true;
63
+ }
64
+ catch (error) {
65
+ return error.code === "EPERM";
66
+ }
67
+ }
38
68
  /**
39
- * SIGTERM the process group, then unconditionally SIGKILL it after a short grace period.
40
- * `detached: true` at spawn time makes the child its own process-group leader, so `-pid` reaches
41
- * it and everything it spawned.
42
- *
43
- * The SIGKILL is not gated on a liveness probe of the leader pid: a leader that exits before a
44
- * lingering descendant (e.g. a shell that forked and returned) would make `isProcessAlive(pid)`
45
- * report false while the descendant is still alive and still holding the workspace, so probing
46
- * only the leader and skipping the SIGKILL on that basis is exactly the wrong direction to err in.
47
- * A dead group simply makes the SIGKILL a harmless ESRCH, caught below.
69
+ * Spec 042 D8: cancel/timeout grace before SIGKILL — long enough for a coding agent CLI to flush
70
+ * its protocol terminal event and buffered output before being force-killed (300ms was rarely
71
+ * enough for that, which is why D1's "keep parsed output on cancel/timeout" fix had little to
72
+ * actually keep). Not used on the normal-exit path below, so it costs nothing on the common case.
48
73
  */
49
- export async function killProcessGroup(pid, graceMs = 300) {
74
+ const KILL_GRACE_MS = 5_000;
75
+ /** Grace for `reapProcessGroup`'s rare non-empty branch — a lingering descendant outliving its
76
+ * already-exited leader is not the hot path a normal exit takes, so this stays short. */
77
+ const REAP_GRACE_MS = 300;
78
+ /**
79
+ * SIGTERM the process group, then unconditionally SIGKILL it after `graceMs`. `detached: true` at
80
+ * spawn time makes the child its own process-group leader, so `-pid` reaches it and everything it
81
+ * spawned. The SIGKILL is not gated on a liveness probe first: a dead group simply makes it a
82
+ * harmless ESRCH, caught below — probing first would only add a syscall on the already-rare path
83
+ * where this function is used to actually terminate something (cancel/timeout, not a normal exit).
84
+ */
85
+ export async function killProcessGroup(pid, graceMs = KILL_GRACE_MS) {
50
86
  try {
51
87
  process.kill(-pid, "SIGTERM");
52
88
  }
@@ -61,3 +97,16 @@ export async function killProcessGroup(pid, graceMs = 300) {
61
97
  // Already gone.
62
98
  }
63
99
  }
100
+ /**
101
+ * Spec 042 D8: cleanup after a *normal* exit, as opposed to `killProcessGroup`'s explicit
102
+ * cancel/timeout termination. The common case — nothing left in the group — returns immediately
103
+ * with no signal and no wait, so a normal settlement no longer pays `killProcessGroup`'s grace
104
+ * period on every single run. The rare case — a descendant outlived its already-exited leader —
105
+ * still needs terminating, so it falls through to the same TERM-then-KILL sequence, just off the
106
+ * hot path and with a short grace since a genuinely finished CLI has nothing left to flush.
107
+ */
108
+ export async function reapProcessGroup(pid) {
109
+ if (!isProcessGroupAlive(pid))
110
+ return;
111
+ await killProcessGroup(pid, REAP_GRACE_MS);
112
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The two-phase "claim, then finish" decision shared by `job-manager.ts` and `subagents/runs.ts`
3
+ * for reserving a completion wake exactly once (spec 040, D7/T9). Both managers persist a
4
+ * `RunRecord`/`JobRecord` differently and gate eligibility on a different terminal condition
5
+ * (job: `status !== "running"`; run: `settledAt` set), so only the claim/consume decision on the
6
+ * two shared fields is factored out here — not the queue, the persistence, or the eligibility check.
7
+ */
8
+ export interface WakeClaimFields {
9
+ wakeClaimDispatchId?: string;
10
+ wakeConsumedAt?: number;
11
+ }
12
+ /**
13
+ * Reserve `dispatchId` as the claim on `fields`, if `eligible` (the caller's terminal/taskId/
14
+ * dispatch-id-match check) holds and no conflicting claim or consumption already exists. Mutates
15
+ * `fields` in place and returns whether the claim was taken; the caller persists the result and
16
+ * rolls the mutation back on a failed write.
17
+ */
18
+ export declare function beginWakeClaim(fields: WakeClaimFields, eligible: boolean, dispatchId: string): boolean;
19
+ /**
20
+ * Mark a previously claimed wake consumed, if `dispatchId` matches the outstanding claim and it
21
+ * has not already been consumed. Mutates `fields` in place and returns whether it changed.
22
+ */
23
+ export declare function finishWakeClaim(fields: WakeClaimFields, dispatchId: string): boolean;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Reserve `dispatchId` as the claim on `fields`, if `eligible` (the caller's terminal/taskId/
3
+ * dispatch-id-match check) holds and no conflicting claim or consumption already exists. Mutates
4
+ * `fields` in place and returns whether the claim was taken; the caller persists the result and
5
+ * rolls the mutation back on a failed write.
6
+ */
7
+ export function beginWakeClaim(fields, eligible, dispatchId) {
8
+ if (!eligible ||
9
+ fields.wakeConsumedAt !== undefined ||
10
+ (fields.wakeClaimDispatchId !== undefined && fields.wakeClaimDispatchId !== dispatchId)) {
11
+ return false;
12
+ }
13
+ fields.wakeClaimDispatchId = dispatchId;
14
+ return true;
15
+ }
16
+ /**
17
+ * Mark a previously claimed wake consumed, if `dispatchId` matches the outstanding claim and it
18
+ * has not already been consumed. Mutates `fields` in place and returns whether it changed.
19
+ */
20
+ export function finishWakeClaim(fields, dispatchId) {
21
+ if (fields.wakeClaimDispatchId !== dispatchId || fields.wakeConsumedAt !== undefined) {
22
+ return false;
23
+ }
24
+ fields.wakeConsumedAt = Date.now();
25
+ return true;
26
+ }