@oyasmi/pipiclaw 0.9.0-beta.7 → 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 (35) hide show
  1. package/dist/memory/review-log.js +0 -0
  2. package/dist/memory/scheduler.d.ts +1 -0
  3. package/dist/memory/scheduler.js +64 -6
  4. package/dist/playbooks/agent-delegation.md +2 -2
  5. package/dist/runtime/bootstrap.js +9 -5
  6. package/dist/runtime/durable-dispatch.d.ts +1 -0
  7. package/dist/runtime/durable-dispatch.js +36 -25
  8. package/dist/runtime/subagent-commands.js +48 -10
  9. package/dist/shared/host-process.d.ts +25 -9
  10. package/dist/shared/host-process.js +59 -10
  11. package/dist/subagents/discovery.d.ts +24 -0
  12. package/dist/subagents/discovery.js +103 -17
  13. package/dist/subagents/external/claude-code.js +10 -3
  14. package/dist/subagents/external/codex-cli.js +9 -3
  15. package/dist/subagents/external/exec.js +1 -0
  16. package/dist/subagents/external/harness.d.ts +22 -0
  17. package/dist/subagents/external/harness.js +22 -4
  18. package/dist/subagents/external/run.d.ts +23 -3
  19. package/dist/subagents/external/run.js +110 -123
  20. package/dist/subagents/external/settlement.d.ts +50 -0
  21. package/dist/subagents/external/settlement.js +123 -0
  22. package/dist/subagents/format.d.ts +4 -0
  23. package/dist/subagents/format.js +7 -0
  24. package/dist/subagents/runs.d.ts +70 -13
  25. package/dist/subagents/runs.js +195 -108
  26. package/dist/subagents/tool.d.ts +27 -2
  27. package/dist/subagents/tool.js +92 -48
  28. package/dist/subagents/verification-outcome.d.ts +26 -0
  29. package/dist/subagents/verification-outcome.js +16 -0
  30. package/dist/subagents/workspace-lease.d.ts +10 -1
  31. package/dist/subagents/workspace-lease.js +15 -2
  32. package/dist/tools/index.js +6 -0
  33. package/dist/tools/subagent-manage.d.ts +20 -6
  34. package/dist/tools/subagent-manage.js +86 -16
  35. package/package.json +1 -1
Binary file
@@ -27,6 +27,7 @@ export interface MemoryMaintenanceSchedulerOptions {
27
27
  isChannelActive: (channelId: string) => boolean;
28
28
  getSettings: () => {
29
29
  memoryMaintenance: PipiclawMemoryMaintenanceSettings;
30
+ sessionMemory: PipiclawSessionMemorySettings;
30
31
  };
31
32
  intervalMs?: number;
32
33
  }
@@ -6,9 +6,57 @@ import * as log from "../log.js";
6
6
  import { discoverWorkspaceChannelIds } from "../runtime/channel-index.js";
7
7
  import { isChannelId } from "../runtime/channel-paths.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
+ import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
9
10
  import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
10
- import { getMemoryMaintenanceStateDir } from "./maintenance-state.js";
11
+ import { getMemoryMaintenanceStateDir, readMemoryMaintenanceState } from "./maintenance-state.js";
11
12
  const DEFAULT_TICK_INTERVAL_MS = 60_000;
13
+ /**
14
+ * Cheap due-time predicate, evaluated before `getRuntimeContext` (transcript access, model
15
+ * resolution, settings reload) is paid for.
16
+ *
17
+ * Reuses the real gates with optimistic material (transcript-derived checks always pass), so the
18
+ * only work here is one state-file read plus timestamp arithmetic. A gate's material checks are
19
+ * purely additive restrictions on top of the cheap checks (interval/backoff/idle/dirty), so
20
+ * optimistic material can only ever make this predicate *more* permissive than the real job would
21
+ * be — it never wrongly skips a channel that a job would actually run for.
22
+ */
23
+ async function mightAnyMaintenanceJobBeDue(input) {
24
+ const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
25
+ const sessionRefresh = shouldRunSessionRefresh({
26
+ now: input.now,
27
+ state,
28
+ sessionMemory: input.settings.sessionMemory,
29
+ maintenance: input.settings.memoryMaintenance,
30
+ channelActive: false,
31
+ hasNewSessionEntry: () => true,
32
+ hasMeaningfulMaterial: () => true,
33
+ });
34
+ if (sessionRefresh.allowed)
35
+ return true;
36
+ const checkpoint = shouldRunMemoryCheckpoint({
37
+ now: input.now,
38
+ state,
39
+ maintenance: input.settings.memoryMaintenance,
40
+ channelActive: false,
41
+ material: () => ({ hasNewEntry: true, hasMeaningfulExchange: true, batchSize: Number.MAX_SAFE_INTEGER }),
42
+ });
43
+ if (checkpoint.allowed)
44
+ return true;
45
+ const structural = await shouldRunStructuralMaintenance({
46
+ now: input.now,
47
+ state,
48
+ maintenance: input.settings.memoryMaintenance,
49
+ channelActive: false,
50
+ material: async () => ({
51
+ memoryCleanupNeeded: true,
52
+ historyFoldingNeeded: true,
53
+ hasMemoryContent: true,
54
+ hasHistoryContent: true,
55
+ expiredEntryCount: 1,
56
+ }),
57
+ });
58
+ return structural.allowed;
59
+ }
12
60
  async function listStateChannels(appHomeDir) {
13
61
  try {
14
62
  const entries = await readdir(getMemoryMaintenanceStateDir(appHomeDir), { withFileTypes: true });
@@ -47,9 +95,12 @@ export class MemoryMaintenanceScheduler {
47
95
  this.nextChannelIndex = 0;
48
96
  }
49
97
  start() {
50
- if (this.timer || !this.options.getSettings().memoryMaintenance.enabled) {
98
+ if (this.timer) {
51
99
  return;
52
100
  }
101
+ // `enabled` is re-checked on every tick inside `runOnce`, which is nearly free when
102
+ // disabled (one cached settings read, no channel scan). Gating `start()` on it too would
103
+ // mean flipping `memoryMaintenance.enabled` on at runtime never actually starts the timer.
53
104
  this.timer = setInterval(() => {
54
105
  void this.runOnce().catch((error) => {
55
106
  log.logWarning("Memory maintenance scheduler tick failed", errorMessage(error));
@@ -65,8 +116,8 @@ export class MemoryMaintenanceScheduler {
65
116
  this.timer = null;
66
117
  }
67
118
  async runOnce(now = new Date()) {
68
- const settings = this.options.getSettings().memoryMaintenance;
69
- if (!settings.enabled || this.running) {
119
+ const settings = this.options.getSettings();
120
+ if (!settings.memoryMaintenance.enabled || this.running) {
70
121
  return;
71
122
  }
72
123
  this.running = true;
@@ -76,7 +127,7 @@ export class MemoryMaintenanceScheduler {
76
127
  workspaceDir: this.options.workspaceDir,
77
128
  knownChannelIds: this.options.getKnownChannelIds?.(),
78
129
  });
79
- const maxConcurrent = normalizeMaxConcurrentChannels(settings.maxConcurrentChannels);
130
+ const maxConcurrent = normalizeMaxConcurrentChannels(settings.memoryMaintenance.maxConcurrentChannels);
80
131
  if (channelIds.length === 0) {
81
132
  return;
82
133
  }
@@ -85,7 +136,14 @@ export class MemoryMaintenanceScheduler {
85
136
  let index = this.nextChannelIndex % channelIds.length;
86
137
  while (scanned < channelIds.length && selected.length < maxConcurrent) {
87
138
  const channelId = channelIds[index];
88
- if (channelId && !this.options.isChannelActive(channelId)) {
139
+ if (channelId &&
140
+ !this.options.isChannelActive(channelId) &&
141
+ (await mightAnyMaintenanceJobBeDue({
142
+ appHomeDir: this.options.appHomeDir,
143
+ channelId,
144
+ settings,
145
+ now,
146
+ }))) {
89
147
  selected.push(channelId);
90
148
  }
91
149
  index = (index + 1) % channelIds.length;
@@ -40,7 +40,7 @@ order: 36
40
40
 
41
41
  - **每次委派都显式传 `workingDirectory`**,不要依赖默认值。
42
42
  - **并行的写入分片各自 `git worktree add` 后指向不同 checkout**,绝不让两个写入者共享一棵树。
43
- - runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。
43
+ - runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。**这把锁只保护声明了 `mutates: write` 的委派**——内置角色的 `mutates` 是按 `tools` 推定(只看 `write`/`edit`,不看 `bash`),外部角色是自述,两者都可能与角色实际行为不符,写清楚 `mutates` 是你的责任,不是 runtime 能替你核实的事。
44
44
  - **你自己的 `write` / `edit` / `bash` 不受这把锁保护。** 一个目录上有活跃写委派时,不要同时自己去改它——先等它结束,或者换一棵 worktree。
45
45
  - **创建的 worktree 在使用结束后要记得关闭**
46
46
 
@@ -57,7 +57,7 @@ order: 36
57
57
  ## 五、纠偏与续接
58
58
 
59
59
  - `subagent_manage op=cancel <runId>`:提前终止。**`/stop` 不会连带停止已派发的委派**,这是有意的——停止一个正在写工作区的进程永远需要一次显式决定。取消不产生唤醒,因为那是你自己的决定。
60
- - `subagent_manage op=follow_up <runId>`:在一个**已结束**的可续接外部 run(claude-code / codex-cli)上追加一轮,省掉重新交代上下文。它产生新的 `runId`,同样异步唤醒。内置 run 和 `exec` 不支持续接(内置的隔离上下文本就不持久化),改为带着上一轮产出开一个新委派。
60
+ - `subagent_manage op=follow_up <runId>`:在一个**已结束**的可续接外部 run(claude-code / codex-cli)上追加一轮,省掉重新交代上下文。它产生新的 `runId`,同样异步唤醒,走与首次派发相同的信封(运行时上下文、上下文块、verify 协议)。内置 run 和 `exec` 不支持续接(内置的隔离上下文本就不持久化),改为带着上一轮产出开一个新委派。角色的 `command`/`model`/`shell` 若在两次派发之间变过,续接会被拒绝——把变化当作"开新任务"而不是想办法绕过去。
61
61
  - 不要仅因为耗时长就中断在跑的委派。只在明确阻塞、循环、崩溃、需要纠偏或用户要求时才取消。
62
62
 
63
63
  ## 六、产物与验收
@@ -18,7 +18,7 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
18
18
  import { fileStamp } from "../shared/file-stamp.js";
19
19
  import { errorMessage } from "../shared/text-utils.js";
20
20
  import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
21
- import { configureSubAgentRuntime, restoreAllSubAgentRuns, stopSubAgentSweeper } from "../subagents/runs.js";
21
+ import { configureSubAgentRuntime, restoreAllSubAgentRuns, stopSubAgentGarbageCollector } from "../subagents/runs.js";
22
22
  import { readActiveTasks } from "../tasks/ledger.js";
23
23
  import { finishTaskAttempt } from "../tasks/store.js";
24
24
  import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
@@ -526,7 +526,6 @@ export async function createRuntimeContext(options) {
526
526
  jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
527
527
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
528
528
  });
529
- void restoreChannelJobs(executor);
530
529
  // Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
531
530
  // and the usage/archive authority, wired before any turn can start a run.
532
531
  configureSubAgentRuntime({
@@ -535,9 +534,13 @@ export async function createRuntimeContext(options) {
535
534
  ledger: getUsageLedger(),
536
535
  store,
537
536
  });
538
- // Admission (bot.start() below) must not open until every persisted run is back in memory
539
- // (P0-1): a message arriving mid-restore would see partial running-count/short-id/lease state,
537
+ // Admission (bot.start() below) must not open until every persisted job and run is back in
538
+ // memory: a message arriving mid-restore would see partial running-count/short-id/lease state,
540
539
  // and durableDispatch's redelivery of a pending completion wake would find no record to claim.
540
+ // Spec 042 D11: `restoreChannelJobs` used to be a bare `void` while `restoreAllSubAgentRuns`
541
+ // was already awaited — the same admission race P0-1 closed for delegation runs was still open
542
+ // for background jobs.
543
+ await restoreChannelJobs(executor);
541
544
  await restoreAllSubAgentRuns();
542
545
  const eventsWatcher = options.createEventsWatcher
543
546
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
@@ -570,6 +573,7 @@ export async function createRuntimeContext(options) {
570
573
  runtimeSettingsManager.reload();
571
574
  return {
572
575
  memoryMaintenance: runtimeSettingsManager.getMemoryMaintenanceSettings(),
576
+ sessionMemory: runtimeSettingsManager.getSessionMemorySettings(),
573
577
  };
574
578
  },
575
579
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
@@ -614,7 +618,7 @@ export async function createRuntimeContext(options) {
614
618
  durableDispatch?.stop();
615
619
  memoryMaintenanceScheduler.stop();
616
620
  eventsWatcher.stop();
617
- stopSubAgentSweeper();
621
+ stopSubAgentGarbageCollector();
618
622
  await bot.stop();
619
623
  const runningTasks = Array.from(activeTasks);
620
624
  if (runningTasks.length > 0) {
@@ -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(", ")}`);
@@ -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
+ }
@@ -142,6 +142,17 @@ export declare function validateToolNames(values: string[] | undefined): {
142
142
  tools: SubAgentToolName[];
143
143
  error?: string;
144
144
  };
145
+ type FieldSupport = "supported" | "rejected";
146
+ /**
147
+ * Which role-file fields mean something under which runtime (spec 040 D5's "对某种 runtime 无意义
148
+ * 的字段一律驳回", made into data per spec 042 D3/F3). A field present under a runtime marked
149
+ * `"rejected"` here is rejected outright, not silently ignored — silently ignoring one is a
150
+ * defect, not a leniency (the review that produced spec 042 found `shell`/`env` on an internal
151
+ * role doing exactly that before this table existed). `cwd` is deliberately absent: it is rejected
152
+ * for *both* runtimes with a different message ("not a role field at all"), handled separately in
153
+ * `loadAgentsFromDir` rather than as a per-runtime mismatch.
154
+ */
155
+ export declare const ROLE_FIELD_MATRIX: Record<string, Record<SubAgentRuntime, FieldSupport>>;
145
156
  export declare function discoverSubAgents(workspaceDir: string, availableModels: Model<Api>[]): SubAgentDiscoveryResult;
146
157
  export declare function resolveSubAgentConfig(availableModels: Model<Api>[], currentModel: Model<Api>, predefinedAgents: SubAgentConfig[], overrides: SubAgentInvocationOverrides,
147
158
  /**
@@ -154,4 +165,17 @@ subagentDefaultModelRef?: string): {
154
165
  error?: string;
155
166
  };
156
167
  export declare function formatSubAgentList(agents: SubAgentConfig[], maxItems?: number): string;
168
+ /**
169
+ * Spec 042 D7: a fingerprint of the parts of an external role that decide *how a launched process
170
+ * is built* — `command`, `externalModelRef`, `shell`. Persisted on a run at launch and compared
171
+ * against the role's current config on `follow_up`: a mismatch means the role was hot-edited in a
172
+ * way that would resume under a harness or executable it never actually wrote, so `follow_up`
173
+ * refuses rather than silently reinterpreting the old session with the new config.
174
+ *
175
+ * Deliberately narrow — `systemPrompt` and `maxWallTimeSec` are excluded on purpose. A resumed
176
+ * session already carries its own context, and folding prompt edits in would mean "fix a typo in
177
+ * the role" breaks every in-flight follow-up; a full invocation snapshot was considered and
178
+ * rejected for the same reason (spec 042 design doc, "已驳回的方案").
179
+ */
180
+ export declare function externalRoleFingerprint(role: Pick<SubAgentConfig, "command" | "externalModelRef" | "shell">): string;
157
181
  export {};