pi-subagents-extend 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/pi-subagents-extend-helper-linux-arm64 +0 -0
  4. package/bin/pi-subagents-extend-helper-linux-x64 +0 -0
  5. package/package.json +63 -4
  6. package/skills/pi-subagents-extend/SKILL.md +312 -0
  7. package/skills/pi-subagents-extend-context/SKILL.md +103 -0
  8. package/skills/pi-subagents-extend-probes/SKILL.md +151 -0
  9. package/src/bash/env.ts +108 -0
  10. package/src/bash/index.ts +27 -0
  11. package/src/bash/network.ts +97 -0
  12. package/src/bash/programs.ts +367 -0
  13. package/src/bash/rules.ts +247 -0
  14. package/src/bash/tokens.ts +169 -0
  15. package/src/bash/unreachable.ts +429 -0
  16. package/src/budgets.ts +89 -0
  17. package/src/child-context.ts +24 -0
  18. package/src/context-scope.ts +93 -0
  19. package/src/deliverable.ts +216 -0
  20. package/src/dependencies.ts +320 -0
  21. package/src/handoff-hint.ts +69 -0
  22. package/src/index.ts +181 -0
  23. package/src/main-context.ts +30 -0
  24. package/src/main-skills.ts +77 -0
  25. package/src/notices.ts +299 -0
  26. package/src/paths/index.ts +165 -0
  27. package/src/policy/glob.ts +146 -0
  28. package/src/policy/index.ts +36 -0
  29. package/src/policy/payload.ts +312 -0
  30. package/src/probe.ts +495 -0
  31. package/src/role-config.ts +434 -0
  32. package/src/sandbox/grants.ts +339 -0
  33. package/src/sandbox/helper.ts +137 -0
  34. package/src/sandbox/index.ts +12 -0
  35. package/src/sandbox/spec.ts +285 -0
  36. package/src/sandbox-note.ts +194 -0
  37. package/src/wiring/agent-start.ts +371 -0
  38. package/src/wiring/context.ts +216 -0
  39. package/src/wiring/misc.ts +55 -0
  40. package/src/wiring/session-start.ts +69 -0
  41. package/src/wiring/tool-call/anchor.ts +138 -0
  42. package/src/wiring/tool-call/bash-path.ts +0 -0
  43. package/src/wiring/tool-call/dispatch-preflight.ts +0 -0
  44. package/src/wiring/tool-call/judge.ts +585 -0
  45. package/src/wiring/tool-call/original-args.ts +64 -0
  46. package/src/wiring/tool-call/paths.ts +235 -0
  47. package/src/wiring/tool-result.ts +68 -0
  48. package/src/worktree-default.ts +27 -0
package/src/probe.ts ADDED
@@ -0,0 +1,495 @@
1
+ /**
2
+ * 探针:检测子代理的无效工作,warn → abort 两级停机。
3
+ *
4
+ * 四条判据(全部可选,零配置不激活):
5
+ * 1. 只读空转:idleWriteMs 内没有任何「写入活动」→ warn;再过 abortGraceMs → abort。
6
+ * 「写入活动」只算 edit/write 工具调用与命中 bash write 列的命令;read 列的 bash
7
+ * 与 read/grep/find/ls 一律不算,否则拿 bash 只读打转就绕过了这条判据。
8
+ * 2. 原地打转:同一条 bash 命令原文重复 repeatBash 次 → warn;再多一次 → abort。
9
+ * 3. 早可收工:bash 输出命中 successPatterns 后起 successIdleMs 计时,期间无写入活动 → abort。
10
+ * 4. 造杂物:write/edit 目标路径命中 forbidWritePatterns → 直接拒绝。
11
+ *
12
+ * warn 的载体是「拦截下一次 tool_call」:定时器到点自己拦不了正在跑的调用,边界才是
13
+ * 能保证模型看到文案的地方。停机由调用方用 terminate: true 硬停(见 index.ts),
14
+ * 探针只负责把「为什么停」写进 stopReason。
15
+ */
16
+
17
+ import { createHash } from "node:crypto";
18
+
19
+ export interface ProbeConfig {
20
+ idleWriteMs: number;
21
+ abortGraceMs: number;
22
+ repeatBash: number;
23
+ successIdleMs: number;
24
+ successPatterns: string[];
25
+ forbidWritePatterns: string[];
26
+ }
27
+
28
+ export const DEFAULT_PROBE: ProbeConfig = {
29
+ idleWriteMs: 6 * 60 * 1000,
30
+ abortGraceMs: 2 * 60 * 1000,
31
+ repeatBash: 3,
32
+ successIdleMs: 5 * 60 * 1000,
33
+ successPatterns: ["fail=0", "0 failed", "0 failing", "all tests passed"],
34
+ forbidWritePatterns: [],
35
+ };
36
+
37
+ /**
38
+ * 停机之后每个调用收到的话。
39
+ *
40
+ * 不能拿停机理由顶:那句话描述的是**触发停机的那一次动作**(「同一条命令重复 3 次:
41
+ * ls -la …/.pnpm」),而后续调用早就换了事,却收到同一句,模型于是把它读成「这条新命令
42
+ * 也犯了那个错」。这个 bug 是真的——一个子代理被判定打转后改去 `ls -la docs`,回来的
43
+ * 仍是那条点名 .pnpm 的旧文案。#stopNotice 与 index.ts 的硬停共用这句。
44
+ */
45
+ export const STOP_NOTICE =
46
+ "pi-subagents-extend: this run stops here — it was stopped earlier and nothing further will execute (the stop message above says why). Report to the parent with contact_supervisor.";
47
+
48
+ export interface ProbeEvent {
49
+ /** 命中判据时给模型看的文案。 */
50
+ reason: string;
51
+ /** warn 之外还要做的事:停掉本轮。 */
52
+ stop: boolean;
53
+ }
54
+
55
+ export interface ProbeHooks {
56
+ warn: (text: string) => void;
57
+ }
58
+
59
+ /**
60
+ * 定时器句柄:Node 返回的 Timeout 对象,或浏览器/假时钟里的数字。探针从不看内容,
61
+ * 只原样交回宿主的 clearTimeout。
62
+ */
63
+ export type TimerHandle = object | number;
64
+
65
+ export interface ProbeHost {
66
+ setTimeout: (fn: () => void, ms: number) => TimerHandle;
67
+ clearTimeout: (handle: TimerHandle) => void;
68
+ now: () => number;
69
+ }
70
+
71
+ /**
72
+ * 一条判据的时窗状态:armed 时,下一个 tool 边界把 warn 抛给模型;到 abortAt 仍没
73
+ * 恢复就停。
74
+ */
75
+ interface Window {
76
+ /** 还没在边界上抛给模型。 */
77
+ armed: boolean;
78
+ /** 已经抛过,等宽限到期。 */
79
+ warned: boolean;
80
+ message: string;
81
+ abortAt: number;
82
+ }
83
+
84
+ function nonNegativeInt(value: unknown, fallback: number): number {
85
+ const n = typeof value === "number" ? value : Number(value);
86
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
87
+ }
88
+
89
+ function patternList(value: unknown, fallback: string[]): string[] {
90
+ if (!Array.isArray(value)) return fallback;
91
+ return (value as unknown[])
92
+ .filter((v): v is string => typeof v === "string" && v.trim() !== "")
93
+ .map((v) => v.trim());
94
+ }
95
+
96
+ /**
97
+ * 解析 bindings 的 probe 字段。
98
+ *
99
+ * 打转与撞权限是纯错误信号,默认开启;时间基判据(只读空转、早可收工)会误伤
100
+ * 慢任务,必须由父代理显式配置。没有 probe 字段时,时间判据的阈值取 0 = 关闭。
101
+ */
102
+ export function parseProbeConfig(raw: unknown): ProbeConfig | undefined {
103
+ if (raw === false) return undefined;
104
+ if (raw === undefined) return { ...DEFAULT_PROBE, idleWriteMs: 0, abortGraceMs: 0, successIdleMs: 0 };
105
+ if (raw === true) return DEFAULT_PROBE;
106
+ if (typeof raw !== "object" || Array.isArray(raw)) return DEFAULT_PROBE;
107
+ const cfg = raw as Record<string, unknown>;
108
+ // `{}` = 全部默认值;只写部分字段时,没写的那些保持关闭(0)。
109
+ const blank = Object.keys(cfg).length === 0;
110
+ const pick = (value: unknown, fallback: number) => {
111
+ if (blank) return fallback;
112
+ if (value === undefined) return 0;
113
+ return nonNegativeInt(value, fallback);
114
+ };
115
+ return {
116
+ idleWriteMs: pick(cfg.idleWriteMs, DEFAULT_PROBE.idleWriteMs),
117
+ abortGraceMs: pick(cfg.abortGraceMs, DEFAULT_PROBE.abortGraceMs),
118
+ repeatBash: Math.max(2, nonNegativeInt(cfg.repeatBash, DEFAULT_PROBE.repeatBash)),
119
+ successIdleMs: pick(cfg.successIdleMs, DEFAULT_PROBE.successIdleMs),
120
+ successPatterns: patternList(cfg.successPatterns, DEFAULT_PROBE.successPatterns),
121
+ forbidWritePatterns: patternList(cfg.forbidWritePatterns, []),
122
+ };
123
+ }
124
+
125
+ function compilePatterns(patterns: string[]): { source: string; re: RegExp }[] {
126
+ const out: { source: string; re: RegExp }[] = [];
127
+ for (const p of patterns) {
128
+ try {
129
+ out.push({ source: p, re: new RegExp(p) });
130
+ } catch {
131
+ // 写坏的模式跳过(不因此误伤所有写入)。
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+
137
+ function matchesAny(patterns: string[], text: string): string | undefined {
138
+ for (const p of patterns) {
139
+ try {
140
+ if (new RegExp(p).test(text)) return p;
141
+ } catch {
142
+ // 忽略坏模式
143
+ }
144
+ }
145
+ return undefined;
146
+ }
147
+
148
+ export interface ProbeDeps {
149
+ config: ProbeConfig;
150
+ /** 只读任务(pi-subagents-extend 的 readOnly):跳过判据 1 与 3。 */
151
+ readOnly: boolean;
152
+ hooks: ProbeHooks;
153
+ host?: ProbeHost;
154
+ /** 写入活动间隔超过这个值就 warn/abort(缺省 clamp 到一个合理下限,便于测试缩短)。 */
155
+ }
156
+
157
+ const MIN_IDLE_MS = 1000;
158
+ const BASH_TEXT_LIMIT = 24_000;
159
+
160
+ /**
161
+ * 探针实例。调用方在 tool_call / tool_result / session_shutdown 上转发事件。
162
+ */
163
+ export class Probe {
164
+ #cfg: ProbeConfig;
165
+ #readOnly: boolean;
166
+ #hooks: ProbeHooks;
167
+ #host: ProbeHost;
168
+ #timers = new Set<TimerHandle>();
169
+ #idleTimer?: TimerHandle;
170
+ #successTimer?: TimerHandle;
171
+ #idle: Window = { armed: false, warned: false, message: "", abortAt: 0 };
172
+ #repeat: Window = { armed: false, warned: false, message: "", abortAt: 0 };
173
+ #bashCounts = new Map<string, number>();
174
+ /**
175
+ * 进行中的命令:`toolCallId → 命令原文`。
176
+ *
177
+ * 不能用单个槽位:pi 默认让一条助手消息里的多个工具调用并行执行,两个 bash 调用会先后
178
+ * 进入、结果以任意顺序回来。单槽会把先到的结果记到后一条命令名下,再丢掉另一条 —— 输出
179
+ * 比对于是张冠李戴,而这条判据的全部代价就是「记错就误杀」。
180
+ */
181
+ #pending = new Map<string, string>();
182
+ /** 每条命令上一次输出的摘要,条数封顶。 */
183
+ #lastOutputs = new Map<string, string>();
184
+ #forbidPatterns: { source: string; re: RegExp }[];
185
+ #stopped = false;
186
+ #stopReason = "";
187
+ /** 停机原因是不是真的交给了模型(只有交给过才可以说「上面的消息」)。 */
188
+ #causeSent = false;
189
+ #successArmed = false;
190
+
191
+ constructor(deps: ProbeDeps) {
192
+ this.#cfg = deps.config;
193
+ this.#readOnly = deps.readOnly;
194
+ this.#hooks = deps.hooks;
195
+ this.#host = deps.host ?? defaultHost();
196
+ this.#forbidPatterns = compilePatterns(deps.config.forbidWritePatterns);
197
+ this.#startIdleTimer();
198
+ }
199
+
200
+ get config(): ProbeConfig {
201
+ return this.#cfg;
202
+ }
203
+
204
+ /** 有写入活动:重置空转计时器,清掉已武装的 warn,并把打转计数清零。 */
205
+ noteWriteActivity(): void {
206
+ if (this.#stopped) return;
207
+ this.#idle = { armed: false, warned: false, message: "", abortAt: 0 };
208
+ // 判据 2 的语义是「同一件事没有进展地重复」,写活动就是进展:计数清零。
209
+ // 已经发出的 spin warn 也要撤掉——否则子代理改完文件再跑同一条测试,仍会被
210
+ // 宽限计时器判死。dogfooding 实测过:一个 coder 子代理第 3 次跑同一条测试收到
211
+ // warn,中途改了代码,宽限到期照样被停。代价是写类命令自身不再受这条判据约束,
212
+ // 读类命令(真正的原地打转)不受影响。
213
+ this.#bashCounts.clear();
214
+ this.#lastOutputs.clear();
215
+ this.#repeat = { armed: false, warned: false, message: "", abortAt: 0 };
216
+ this.#disarmSuccess();
217
+ this.#startIdleTimer();
218
+ }
219
+
220
+ /** bash 命令进入:判据 2 计数;命中 write 列时也记为写入活动。 */
221
+ noteBashStart(command: string, access: "read" | "write" | undefined, callId?: string): ProbeEvent | undefined {
222
+ if (this.#stopped) return undefined;
223
+ if (access === "write") this.noteWriteActivity();
224
+ const key = command.trim();
225
+ if (!key) return undefined;
226
+ this.#pending.set(callId ?? "", key);
227
+ if (this.#pending.size > 64) {
228
+ const stalest = this.#pending.keys().next().value as string | undefined;
229
+ if (stalest !== undefined) this.#pending.delete(stalest);
230
+ }
231
+ const count = (this.#bashCounts.get(key) ?? 0) + 1;
232
+ this.#bashCounts.set(key, count);
233
+ if (count === this.#cfg.repeatBash) {
234
+ const message =
235
+ `Same bash command repeated ${count} times (criterion: spinning): ${key.slice(0, 160)}. ` +
236
+ `One more stops the run — change approach or report to the parent.`;
237
+ this.#repeat = {
238
+ armed: true,
239
+ warned: true,
240
+ message,
241
+ abortAt: this.#host.now() + this.#cfg.abortGraceMs,
242
+ };
243
+ // 第 N 次直接拦下这次调用并给 warn:放行到下一次就没机会说了。
244
+ this.#hooks.warn(message);
245
+ return { reason: message, stop: false };
246
+ }
247
+ if (count > this.#cfg.repeatBash) {
248
+ return {
249
+ reason:
250
+ `Same bash command repeated ${count} times (criterion: spinning): ${key.slice(0, 160)}. ` +
251
+ "The run stops here: state what you kept retrying and what the parent must supply.",
252
+ stop: true,
253
+ };
254
+ }
255
+ return undefined;
256
+ }
257
+
258
+ /** bash 输出:判据 3 的成功标记;并判定这一次重复是不是带回了新信息。 */
259
+ noteBashResult(output: string, callId?: string): void {
260
+ // 输出判定与 readOnly 无关:那条开关只关「早可收工」,不关打转。
261
+ this.#noteOutput(output, callId);
262
+ if (this.#readOnly || this.#stopped) return;
263
+ const text = output.length > BASH_TEXT_LIMIT ? output.slice(-BASH_TEXT_LIMIT) : output;
264
+ const hit = matchesAny(this.#cfg.successPatterns, text);
265
+ if (!hit) return;
266
+ this.#startSuccessTimer(hit);
267
+ }
268
+
269
+ /**
270
+ * 一条命令的输出回来了:和上一次不同,就说明这次重复拿到了新信息,不算原地打转。
271
+ *
272
+ * 判据原来的口径是「同一条命令出现 N 次」,不看结果。dogfooding 里一个在量目录布局的
273
+ * 子代理因此被杀:它三次 `ls` 同一个目录、每次输出都不一样,可那正是测量任务在做的事。
274
+ * 现在计数归零、并撤掉已武装的 warn —— 拿到新输出就是进展,跟写了文件是一回事。
275
+ * 真正卡住的孩子输出一字不差,仍然会被数到阈值上。
276
+ */
277
+ #noteOutput(output: string, callId?: string): void {
278
+ const slot = callId ?? "";
279
+ const key = this.#pending.get(slot);
280
+ this.#pending.delete(slot);
281
+ if (!key) return;
282
+ const digest = digestOf(output);
283
+ const previous = this.#lastOutputs.get(key);
284
+ if (this.#lastOutputs.size >= 64 && !this.#lastOutputs.has(key)) {
285
+ const oldest = this.#lastOutputs.keys().next().value as string | undefined;
286
+ if (oldest !== undefined) {
287
+ this.#lastOutputs.delete(oldest);
288
+ // 被淘汰的命令失去基线,计数也一并丢掉:下一次从 1 重新开始。
289
+ // 保留计数就会在“没基线”的情况下继续累加,那是往误杀的方向偏。
290
+ this.#bashCounts.delete(oldest);
291
+ }
292
+ }
293
+ // 先删后插:Map 保留首次插入的位置,不删就成了按首次出现排序的 FIFO,
294
+ // 而重复最多的那条命令正好坐在队头,会成为第一个被淘汰的对象。
295
+ this.#lastOutputs.delete(key);
296
+ this.#lastOutputs.set(key, digest);
297
+ if (previous === undefined || previous === digest) return;
298
+ this.#bashCounts.delete(key);
299
+ this.#repeat = { armed: false, warned: false, message: "", abortAt: 0 };
300
+ }
301
+
302
+ /** write/edit 目标路径:判据 4。命中返回拒绝事件。 */
303
+ checkWriteTarget(path: string): ProbeEvent | undefined {
304
+ if (this.#stopped) return undefined;
305
+ for (const p of this.#forbidPatterns) {
306
+ if (p.re.test(path)) {
307
+ return {
308
+ reason:
309
+ `pi-subagents-extend: refusing to write "${path}" into the repo (criterion: junk files, matched "` +
310
+ `${p.source}"); put debug and temp files under /tmp.`,
311
+ stop: false,
312
+ };
313
+ }
314
+ }
315
+ return undefined;
316
+ }
317
+
318
+ /** tool 边界:把已武装的 warn 抛给模型;宽限走完就停。 */
319
+ atToolBoundary(): ProbeEvent | undefined {
320
+ // 停过之后每个边界都要拒绝:没有这条,停机只停在内部状态里,子代理照跑。
321
+ // 给的是「已停」的状态说明,不是那条触发停机的旧描述(见 #stopNotice)。
322
+ if (this.#stopped && this.#stopReason) {
323
+ // 计时器触发的停机(只读空转、早可收工)从没把原因交给过模型:`#hooks.warn` 是 UI
324
+ // 提示,不进上下文。那种情形的第一次边界必须把原因说完,否则模型收到的是
325
+ // 「原因见上面的消息」,而上面根本没有那条消息。
326
+ if (!this.#causeSent) {
327
+ this.#causeSent = true;
328
+ return { reason: this.#stopReason, stop: true };
329
+ }
330
+ return { reason: STOP_NOTICE, stop: true };
331
+ }
332
+ if (this.#stopped) return undefined;
333
+ const now = this.#host.now();
334
+ const expired = [this.#idle, this.#repeat].find((w) => w.warned && now >= w.abortAt);
335
+ if (expired) {
336
+ // 这一次的原因就由这次调用返回,所以标记为「已交给模型」。
337
+ this.#stopWith(`${expired.message}\nGrace expired; the run stops here. Summarize what changed and what blocks you.`, true);
338
+ return { reason: this.#stopReason, stop: true };
339
+ }
340
+ const armed = [this.#repeat, this.#idle].find((w) => w.armed);
341
+ if (armed) {
342
+ armed.armed = false;
343
+ armed.warned = true;
344
+ this.#hooks.warn(armed.message);
345
+ return { reason: armed.message, stop: false };
346
+ }
347
+ return undefined;
348
+ }
349
+
350
+ /** 定时器到点:空转的 warn 与 abort 都不依赖 tool 边界。 */
351
+ #fireIdle(): void {
352
+ if (this.#stopped) return;
353
+ if (!this.#idle.armed) {
354
+ this.#idle = {
355
+ armed: true,
356
+ warned: false,
357
+ message:
358
+ `Nothing written for ${ms(this.#cfg.idleWriteMs)} and no write-capable bash ran (criterion: idle). ` +
359
+ "Start the change, or report what blocks you to the parent.",
360
+ abortAt: this.#host.now() + this.#cfg.abortGraceMs,
361
+ };
362
+ this.#idleTimer = this.#schedule(() => this.#fireIdleAbort(), this.#cfg.abortGraceMs);
363
+ return;
364
+ }
365
+ this.#fireIdleAbort();
366
+ }
367
+
368
+ /**
369
+ * 停机。三处(grace 到期、空转、早可收工)都走这里,因为 `#causeSent` 的正确值取决于调用点:
370
+ * 由这次调用把原因返回出去的,标 true;由计时器触发、只能等下一个边界补发的,标 false。
371
+ * 原先三处各写三行,新加一处忘了写就不会补发 —— 那正是这次要修的 bug 的形状。
372
+ */
373
+ #stopWith(reason: string, causeSent: boolean): void {
374
+ this.#stopped = true;
375
+ this.#clearTimers();
376
+ this.#stopReason = reason;
377
+ this.#causeSent = causeSent;
378
+ }
379
+
380
+ #fireIdleAbort(): void {
381
+ if (this.#stopped) return;
382
+ // 计时器停机没有工具调用可以带回原因,`#hooks.warn` 只是 UI 提示,所以留给下一个边界补发。
383
+ this.#stopWith(
384
+ `Criterion: idle — nothing written for over ${ms(this.#cfg.idleWriteMs + this.#cfg.abortGraceMs)} ` +
385
+ "and no write-capable bash ran. The run stops here: state what you confirmed and why nothing changed.",
386
+ false,
387
+ );
388
+ this.#hooks.warn(this.#stopReason);
389
+ }
390
+
391
+ #startIdleTimer(): void {
392
+ if (this.#readOnly || this.#cfg.idleWriteMs < MIN_IDLE_MS) return;
393
+ this.#clearIdleTimer();
394
+ this.#idleTimer = this.#schedule(() => this.#fireIdle(), this.#cfg.idleWriteMs);
395
+ }
396
+
397
+ #startSuccessTimer(marker: string): void {
398
+ if (this.#cfg.successIdleMs < MIN_IDLE_MS) return;
399
+ this.#disarmSuccess();
400
+ this.#successArmed = true;
401
+ this.#successTimer = this.#schedule(() => {
402
+ if (this.#stopped) return;
403
+ this.#stopWith(
404
+ `Criterion: work is done — success marker "${marker}" matched and nothing changed for ${ms(this.#cfg.successIdleMs)}. ` +
405
+ "The run stops here; report the result.",
406
+ false,
407
+ );
408
+ this.#hooks.warn(this.#stopReason);
409
+ }, this.#cfg.successIdleMs);
410
+ }
411
+
412
+ #disarmSuccess(): void {
413
+ if (this.#successTimer !== undefined) {
414
+ this.#host.clearTimeout(this.#successTimer);
415
+ this.#successTimer = undefined;
416
+ }
417
+ this.#successArmed = false;
418
+ }
419
+
420
+ #schedule(fn: () => void, ms: number): TimerHandle {
421
+ const handle = this.#host.setTimeout(() => {
422
+ this.#timers.delete(handle);
423
+ fn();
424
+ }, ms);
425
+ this.#timers.add(handle);
426
+ return handle;
427
+ }
428
+
429
+ #clearIdleTimer(): void {
430
+ if (this.#idleTimer !== undefined) {
431
+ this.#host.clearTimeout(this.#idleTimer);
432
+ this.#timers.delete(this.#idleTimer);
433
+ this.#idleTimer = undefined;
434
+ }
435
+ }
436
+
437
+ #clearTimers(): void {
438
+ for (const handle of this.#timers) this.#host.clearTimeout(handle);
439
+ this.#timers.clear();
440
+ this.#idleTimer = undefined;
441
+ this.#successTimer = undefined;
442
+ }
443
+
444
+ /** 会话结束:清定时器,避免残留。 */
445
+ dispose(): void {
446
+ this.#stopped = true;
447
+ this.#clearTimers();
448
+ }
449
+
450
+ /** 诊断用:当前状态。 */
451
+ status(): string[] {
452
+ // 空闲阈值:只读任务不适用;关闭时写「关闭」。
453
+ let idleLimit = "off";
454
+ if (this.#readOnly) idleLimit = "n/a (read-only task)";
455
+ else if (this.#cfg.idleWriteMs > 0) {
456
+ idleLimit = `${ms(this.#cfg.idleWriteMs)} + grace ${ms(this.#cfg.abortGraceMs)}`;
457
+ }
458
+ const lines = [
459
+ `Idle: ${idleLimit}`,
460
+ `Spin: same command warns at ${this.#cfg.repeatBash}, stops at ${this.#cfg.repeatBash + 1} (${this.#bashCounts.size} commands recorded)`,
461
+ `Done-early: ${this.#readOnly ? "n/a (read-only task)" : `stops after ${ms(this.#cfg.successIdleMs)} with no new change`}`,
462
+ `Junk files: ${this.#forbidPatterns.length} forbidden path patterns`,
463
+ `State: ${this.#stopped ? "stopped" : "running"}${this.#successArmed ? " (success marker matched)" : ""}`,
464
+ ];
465
+ return lines;
466
+ }
467
+ }
468
+
469
+ /**
470
+ * 判断两条输出是不是一字不差,只需要一个摘要:存原文会让 64 条命令各自攒着几十 KB
471
+ * (bash 结果的设计上限就是 24 KB),只为了回答一个相等问题。
472
+ */
473
+ function digestOf(output: string): string {
474
+ return createHash("sha1").update(output).digest("hex");
475
+ }
476
+
477
+ function ms(value: number): string {
478
+ if (value >= 60_000) { const m = value / 60_000;
479
+ return `${Number.isInteger(m) ? m : m.toFixed(1)} min`;
480
+ }
481
+ return `${Math.round(value / 1000)} s`;
482
+ }
483
+
484
+ function defaultHost(): ProbeHost {
485
+ return {
486
+ setTimeout: (fn, delay) => {
487
+ const h = setTimeout(fn, delay);
488
+ // 定时器不该把进程留住。
489
+ if (typeof (h as { unref?: () => void }).unref === "function") (h as { unref: () => void }).unref();
490
+ return h;
491
+ },
492
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
493
+ now: () => Date.now(),
494
+ };
495
+ }