@oyasmi/pipiclaw 0.9.3 → 0.9.4-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 (113) hide show
  1. package/dist/agent/channel-runner.js +137 -61
  2. package/dist/agent/command-extension.js +47 -34
  3. package/dist/agent/job-manager.js +31 -11
  4. package/dist/agent/model-fallback.js +1 -1
  5. package/dist/agent/prompt/manifest.d.ts +6 -1
  6. package/dist/agent/prompt/manifest.js +45 -64
  7. package/dist/agent/prompt/resources.js +4 -1
  8. package/dist/agent/run-queue.js +7 -2
  9. package/dist/agent/session-adapter.js +1 -1
  10. package/dist/agent/session-events.js +17 -6
  11. package/dist/agent/session-resource-gate.js +3 -1
  12. package/dist/agent/status-render.d.ts +0 -1
  13. package/dist/agent/status-render.js +4 -16
  14. package/dist/agent/turn-error.d.ts +31 -0
  15. package/dist/agent/turn-error.js +68 -0
  16. package/dist/app-services.js +7 -4
  17. package/dist/channel/channel-index.js +4 -1
  18. package/dist/channel/project-scope-store.js +1 -1
  19. package/dist/commands/catalog.d.ts +21 -4
  20. package/dist/commands/catalog.js +88 -41
  21. package/dist/commands/reply-limits.d.ts +6 -0
  22. package/dist/commands/reply-limits.js +24 -0
  23. package/dist/events/event-commands.js +94 -44
  24. package/dist/events/event-validation.d.ts +13 -2
  25. package/dist/events/event-validation.js +17 -9
  26. package/dist/events/events.js +77 -32
  27. package/dist/executor.js +2 -2
  28. package/dist/log.d.ts +12 -2
  29. package/dist/log.js +26 -34
  30. package/dist/main.js +1 -1
  31. package/dist/memory/commands.js +29 -23
  32. package/dist/memory/lifecycle.js +26 -5
  33. package/dist/memory/maintenance-state.js +4 -1
  34. package/dist/memory/scheduler.js +3 -1
  35. package/dist/models/auth-cli.js +3 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +9 -0
  38. package/dist/playbooks/agent-delegation.md +2 -2
  39. package/dist/runtime/app-home.d.ts +6 -0
  40. package/dist/runtime/app-home.js +21 -3
  41. package/dist/runtime/bootstrap.js +189 -60
  42. package/dist/runtime/channel-queue.js +1 -1
  43. package/dist/runtime/delivery.js +29 -15
  44. package/dist/runtime/dingtalk.js +96 -42
  45. package/dist/runtime/durable-dispatch.d.ts +27 -1
  46. package/dist/runtime/durable-dispatch.js +111 -3
  47. package/dist/runtime/project-commands.js +16 -15
  48. package/dist/runtime/proxy.js +4 -2
  49. package/dist/runtime/report-commands.js +1 -1
  50. package/dist/runtime/skill-commands.d.ts +1 -1
  51. package/dist/runtime/skill-commands.js +17 -10
  52. package/dist/runtime/subagent-commands.d.ts +5 -4
  53. package/dist/runtime/subagent-commands.js +116 -77
  54. package/dist/runtime/task-commands.d.ts +1 -1
  55. package/dist/runtime/task-commands.js +110 -64
  56. package/dist/runtime/task-driver.d.ts +4 -2
  57. package/dist/runtime/task-driver.js +55 -20
  58. package/dist/runtime/task-migration.js +23 -6
  59. package/dist/runtime/task-spawn.js +12 -5
  60. package/dist/runtime/wake-coalescing.d.ts +18 -0
  61. package/dist/runtime/wake-coalescing.js +29 -0
  62. package/dist/security/block-message.d.ts +22 -1
  63. package/dist/security/block-message.js +66 -1
  64. package/dist/security/network.d.ts +2 -1
  65. package/dist/security/network.js +3 -2
  66. package/dist/security/path-guard-check.js +2 -2
  67. package/dist/settings.d.ts +3 -2
  68. package/dist/settings.js +4 -1
  69. package/dist/shared/format.d.ts +12 -0
  70. package/dist/shared/format.js +37 -0
  71. package/dist/shared/host-process.js +15 -3
  72. package/dist/shared/with-timeout.d.ts +3 -2
  73. package/dist/shared/with-timeout.js +14 -3
  74. package/dist/subagents/external/claude-code.js +23 -1
  75. package/dist/subagents/external/progress-tail.d.ts +17 -0
  76. package/dist/subagents/external/progress-tail.js +64 -17
  77. package/dist/subagents/external/run.d.ts +3 -0
  78. package/dist/subagents/external/run.js +21 -7
  79. package/dist/subagents/external/settlement.d.ts +3 -0
  80. package/dist/subagents/external/settlement.js +1 -1
  81. package/dist/subagents/runs.d.ts +21 -1
  82. package/dist/subagents/runs.js +137 -32
  83. package/dist/subagents/tool.d.ts +22 -15
  84. package/dist/subagents/tool.js +226 -32
  85. package/dist/subagents/workspace-summary.d.ts +16 -4
  86. package/dist/subagents/workspace-summary.js +74 -18
  87. package/dist/tasks/board.d.ts +8 -1
  88. package/dist/tasks/board.js +37 -2
  89. package/dist/tasks/frontmatter.d.ts +5 -0
  90. package/dist/tasks/frontmatter.js +8 -0
  91. package/dist/tasks/log.d.ts +11 -1
  92. package/dist/tasks/log.js +58 -2
  93. package/dist/tasks/store.js +4 -2
  94. package/dist/tasks/ticket.d.ts +3 -1
  95. package/dist/tasks/ticket.js +19 -1
  96. package/dist/tools/bash.js +2 -2
  97. package/dist/tools/index.d.ts +2 -0
  98. package/dist/tools/index.js +1 -0
  99. package/dist/tools/memory-manage.js +4 -1
  100. package/dist/tools/subagent-manage.d.ts +1 -1
  101. package/dist/tools/subagent-manage.js +16 -11
  102. package/dist/tools/task-manage/step-end.js +4 -1
  103. package/dist/tools/tool-details.d.ts +10 -2
  104. package/dist/tools/tool-details.js +39 -2
  105. package/dist/tui/cli.js +2 -2
  106. package/dist/tui/commands.js +4 -4
  107. package/dist/tui/pitui-frontend.js +1 -1
  108. package/dist/tui/renderer.js +3 -2
  109. package/dist/tui/turn-controller.d.ts +2 -0
  110. package/dist/tui/turn-controller.js +36 -21
  111. package/dist/usage/ledger.js +3 -1
  112. package/dist/usage/render.js +3 -1
  113. package/package.json +1 -1
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Consumer-side merging of completion wakes. K parallel delegations (or background jobs) used to
3
+ * settle into K separate main-agent turns, each re-reading the whole session to handle one result
4
+ * — and with the event queue capped at a handful of items, the rest waited out a 30s+ retry. Now
5
+ * the turn that starts one completion wake also takes every other one still waiting for this
6
+ * channel, so results that arrive while the channel is busy are handled together in the next turn.
7
+ * Nothing is delayed to make that happen: the first result still wakes the channel immediately.
8
+ *
9
+ * Only chat-level wakes merge. A task-bound wake carries `internalWake` and goes through its own
10
+ * claim (`task-wake.ts`), which already lets sibling wakes of one fan-out drop out once the task
11
+ * is reopened.
12
+ */
13
+ /** The merged turn's prompt grows with every result's tail; past this many it is better split. */
14
+ export const MAX_COALESCED_WAKES = 6;
15
+ const COMPLETION_WAKE_ID = /^(subagent|job):.+:done$/;
16
+ export function isCoalescableWake(event) {
17
+ return !event.internalWake && typeof event.dispatchId === "string" && COMPLETION_WAKE_ID.test(event.dispatchId);
18
+ }
19
+ /** The primary wake keeps its own text (and `[KIND:id]` tag) first; the others follow it. */
20
+ export function mergeCompletionWakes(primary, others) {
21
+ if (others.length === 0)
22
+ return primary;
23
+ const header = `[${others.length} more completion wake(s) arrived while this channel was busy and are delivered with the one above. ` +
24
+ "Handle all of them in this turn; reply with exactly [SILENT] only if none of them needs a follow-up.]";
25
+ return {
26
+ ...primary,
27
+ text: [primary.text, header, ...others.map((event) => event.text)].join("\n\n---\n\n"),
28
+ };
29
+ }
@@ -4,8 +4,29 @@ export interface BlockMessageDetail {
4
4
  value: string;
5
5
  }
6
6
  /**
7
- * Shared scaffold for a guard's user/model-facing block message: `"<Subject> blocked [category]"`
7
+ * Shared scaffold for a guard's model-facing block message: `"<Subject> blocked [category]"`
8
8
  * followed by one line per detail. Used by both the path guard and the command guard so their
9
9
  * wording does not drift line by line as each grows its own detail set.
10
10
  */
11
11
  export declare function formatBlockMessage(subject: string, category: string | undefined, details: BlockMessageDetail[]): string;
12
+ export type GuardKind = "path" | "command" | "network";
13
+ /** What a guard refused, in structured form — the user-facing rendering is built from this. */
14
+ export interface GuardBlock {
15
+ guard: GuardKind;
16
+ category?: string;
17
+ /** What was refused: the resolved path, the command, or the URL. */
18
+ target: string;
19
+ /** Path guard only. */
20
+ operation?: "read" | "write";
21
+ }
22
+ /**
23
+ * A guard refusal (spec 053, D5.2). Its `message` is the model-facing English text, unchanged —
24
+ * it steers the model to explain the intent to the user. `blocked` carries the same refusal as
25
+ * data, so the chat can show a short Chinese line instead of the model's text.
26
+ */
27
+ export declare class GuardBlockedError extends Error {
28
+ readonly blocked: GuardBlock;
29
+ constructor(message: string, blocked: GuardBlock);
30
+ }
31
+ /** The one chat line for a guard refusal, e.g. `已拦截:写入允许范围以外的路径 \`/x/y\`(…)`. */
32
+ export declare function renderGuardBlockForUser(block: GuardBlock): string;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Shared scaffold for a guard's user/model-facing block message: `"<Subject> blocked [category]"`
2
+ * Shared scaffold for a guard's model-facing block message: `"<Subject> blocked [category]"`
3
3
  * followed by one line per detail. Used by both the path guard and the command guard so their
4
4
  * wording does not drift line by line as each grows its own detail set.
5
5
  */
@@ -10,3 +10,68 @@ export function formatBlockMessage(subject, category, details) {
10
10
  }
11
11
  return lines.join("\n");
12
12
  }
13
+ /**
14
+ * A guard refusal (spec 053, D5.2). Its `message` is the model-facing English text, unchanged —
15
+ * it steers the model to explain the intent to the user. `blocked` carries the same refusal as
16
+ * data, so the chat can show a short Chinese line instead of the model's text.
17
+ */
18
+ export class GuardBlockedError extends Error {
19
+ constructor(message, blocked) {
20
+ super(message);
21
+ this.blocked = blocked;
22
+ this.name = "GuardBlockedError";
23
+ }
24
+ }
25
+ const PATH_BLOCK = {
26
+ "outside-allowed-roots": (op) => `${op}允许范围以外的路径`,
27
+ "system-path": (op) => `${op}系统路径`,
28
+ "sensitive-read-path": (op) => `${op}敏感路径`,
29
+ "sensitive-write-path": (op) => `${op}敏感路径`,
30
+ "symlink-write": () => "通过符号链接写入",
31
+ "configured-deny": (op) => `${op} security.json 禁止的路径`,
32
+ };
33
+ const COMMAND_BLOCK = {
34
+ "destructive-file-op": "属于破坏性文件操作",
35
+ "system-manipulation": "会修改系统配置",
36
+ "privilege-escalation": "涉及提权",
37
+ "process-manipulation": "会操作其他进程",
38
+ "network-abuse": "属于高风险网络操作",
39
+ "container-escape": "可能突破容器隔离",
40
+ obfuscation: "包含混淆或动态拼接的内容",
41
+ "configured-command-deny": "被 security.json 禁止",
42
+ };
43
+ /** Network refusals a deployer can lift in security.json; the rest are just unreachable URLs. */
44
+ const NETWORK_BLOCK = {
45
+ "private-address": { reason: "指向内网地址", adjustable: true },
46
+ "blocked-host": { reason: "是被禁止访问的主机", adjustable: true },
47
+ "dns-failure": { reason: "主机名无法解析", adjustable: false },
48
+ "invalid-url": { reason: "不是有效的网址", adjustable: false },
49
+ "unsupported-scheme": { reason: "使用了不支持的协议", adjustable: false },
50
+ "missing-host": { reason: "缺少主机名", adjustable: false },
51
+ };
52
+ function clipTarget(target, max) {
53
+ const flat = target.replace(/\s+/g, " ").trim();
54
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
55
+ }
56
+ const ADJUST_HINT = "(如需放行,由部署者调整 security.json)";
57
+ /** The one chat line for a guard refusal, e.g. `已拦截:写入允许范围以外的路径 \`/x/y\`(…)`. */
58
+ export function renderGuardBlockForUser(block) {
59
+ switch (block.guard) {
60
+ case "path": {
61
+ const op = block.operation === "write" ? "写入" : "读取";
62
+ const what = (block.category ? PATH_BLOCK[block.category] : undefined)?.(op) ?? `${op}受保护的路径`;
63
+ return `已拦截:${what} \`${clipTarget(block.target, 160)}\`${ADJUST_HINT}`;
64
+ }
65
+ case "command": {
66
+ const why = (block.category ? COMMAND_BLOCK[block.category] : undefined) ?? "属于高危操作";
67
+ return `已拦截:命令 \`${clipTarget(block.target, 80)}\` ${why}${ADJUST_HINT}`;
68
+ }
69
+ case "network": {
70
+ const known = block.category ? NETWORK_BLOCK[block.category] : undefined;
71
+ const url = `\`${clipTarget(block.target, 120)}\``;
72
+ if (known && !known.adjustable)
73
+ return `无法访问 ${url}:${known.reason}`;
74
+ return `已拦截:访问 ${url}${known ? ` ${known.reason}` : ""}${ADJUST_HINT}`;
75
+ }
76
+ }
77
+ }
@@ -1,3 +1,4 @@
1
+ import { GuardBlockedError } from "./block-message.js";
1
2
  import type { SecurityConfig } from "./types.js";
2
3
  type ValidationStage = "request" | "redirect";
3
4
  export interface NetworkGuardContext {
@@ -8,7 +9,7 @@ export interface ValidatedNetworkTarget {
8
9
  hostname: string;
9
10
  resolvedAddress?: string;
10
11
  }
11
- export declare class NetworkGuardError extends Error {
12
+ export declare class NetworkGuardError extends GuardBlockedError {
12
13
  readonly url: string;
13
14
  readonly stage: ValidationStage;
14
15
  readonly category: string;
@@ -1,9 +1,10 @@
1
1
  import { lookup } from "node:dns/promises";
2
2
  import { isIP } from "node:net";
3
3
  import { errorMessage } from "../shared/text-utils.js";
4
- export class NetworkGuardError extends Error {
4
+ import { GuardBlockedError } from "./block-message.js";
5
+ export class NetworkGuardError extends GuardBlockedError {
5
6
  constructor(options) {
6
- super(options.message);
7
+ super(options.message, { guard: "network", category: options.category, target: options.url });
7
8
  this.name = "NetworkGuardError";
8
9
  this.url = options.url;
9
10
  this.stage = options.stage;
@@ -1,4 +1,4 @@
1
- import { formatBlockMessage } from "./block-message.js";
1
+ import { formatBlockMessage, GuardBlockedError } from "./block-message.js";
2
2
  import { logSecurityEvent } from "./logger.js";
3
3
  import { guardPath } from "./path-guard.js";
4
4
  function formatPathBlockMessage(resolvedPath, category, reason) {
@@ -32,7 +32,7 @@ export async function checkPathGuard(rawPath, operation, securityConfig, securit
32
32
  category: guardResult.category,
33
33
  reason: guardResult.reason,
34
34
  });
35
- throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
35
+ throw new GuardBlockedError(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason), { guard: "path", category: guardResult.category, target: guardResult.resolvedPath ?? rawPath, operation });
36
36
  }
37
37
  // `guardPath` always populates `resolvedPath` on an allowed result (see D1.1 above).
38
38
  return guardResult.resolvedPath;
@@ -49,8 +49,9 @@ export interface PipiclawSessionSearchSettings {
49
49
  * How much out-of-band commentary a delegation run (`src/subagents/`) or background job produces
50
50
  * outside of its own completion wake — plain text, not an LLM turn, so it reaches the channel in
51
51
  * roughly the time the run itself takes rather than waiting on a wake turn's latency.
52
- * `"off"` is today's behavior; `"settled"` adds only the one-line completion receipt; `"live"`
53
- * also adds a sparse trickle of running-progress notices for long external runs.
52
+ * `"off"` is today's behavior; `"settled"` adds the one-line completion receipt and the "may be
53
+ * stuck" warning for an external run that stopped producing output; `"live"` also adds a sparse
54
+ * trickle of running-progress notices for long runs (external, or internal ones gone async).
54
55
  */
55
56
  export interface PipiclawDelegationSettings {
56
57
  notices: "off" | "settled" | "live";
package/dist/settings.js CHANGED
@@ -267,7 +267,10 @@ export class PipiclawSettingsManager {
267
267
  writeFileAtomicallySync(this.settingsPath, JSON.stringify(this.settings, null, 2));
268
268
  }
269
269
  catch (error) {
270
- log.logWarning(`Could not save settings file`, `${this.settingsPath}\n${String(error)}`);
270
+ log.logWarn("config.settings.save_failed", "Settings file save failed", {
271
+ reason: String(error),
272
+ fields: { path: this.settingsPath },
273
+ });
271
274
  }
272
275
  }
273
276
  /**
@@ -1,5 +1,17 @@
1
1
  /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
2
2
  export declare function formatDuration(ms: number): string;
3
+ /**
4
+ * User-facing elapsed time in Chinese, two units at most (`42秒`, `1分02秒`, `3小时05分`, `2天3小时`) —
5
+ * for "how long did this take / has this been running" in replies, receipts and cards (spec 053,
6
+ * D4). Model-facing text keeps `formatDuration` above.
7
+ */
8
+ export declare function formatElapsedZh(ms: number): string;
9
+ /**
10
+ * A coarse, single-unit span in Chinese (`30 秒`, `12 分钟`, `3 小时`, `2 天`) — for "how far away is
11
+ * this deadline", where a second unit is noise. Rounds within a unit and promotes to the next unit
12
+ * when rounding reaches it, so the output never reads `60 分钟` or `24 小时`.
13
+ */
14
+ export declare function formatSpanZh(ms: number): string;
3
15
  /**
4
16
  * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
5
17
  * falling back to `fallback` for anything not a finite number or out of range. Shared by the
@@ -6,6 +6,43 @@ export function formatDuration(ms) {
6
6
  return `${seconds}s`;
7
7
  return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
8
8
  }
9
+ /**
10
+ * User-facing elapsed time in Chinese, two units at most (`42秒`, `1分02秒`, `3小时05分`, `2天3小时`) —
11
+ * for "how long did this take / has this been running" in replies, receipts and cards (spec 053,
12
+ * D4). Model-facing text keeps `formatDuration` above.
13
+ */
14
+ export function formatElapsedZh(ms) {
15
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
16
+ if (totalSeconds < 60)
17
+ return `${totalSeconds}秒`;
18
+ const totalMinutes = Math.floor(totalSeconds / 60);
19
+ if (totalMinutes < 60)
20
+ return `${totalMinutes}分${String(totalSeconds % 60).padStart(2, "0")}秒`;
21
+ const totalHours = Math.floor(totalMinutes / 60);
22
+ if (totalHours < 24) {
23
+ const minutes = totalMinutes % 60;
24
+ return minutes > 0 ? `${totalHours}小时${String(minutes).padStart(2, "0")}分` : `${totalHours}小时`;
25
+ }
26
+ const hours = totalHours % 24;
27
+ return hours > 0 ? `${Math.floor(totalHours / 24)}天${hours}小时` : `${Math.floor(totalHours / 24)}天`;
28
+ }
29
+ /**
30
+ * A coarse, single-unit span in Chinese (`30 秒`, `12 分钟`, `3 小时`, `2 天`) — for "how far away is
31
+ * this deadline", where a second unit is noise. Rounds within a unit and promotes to the next unit
32
+ * when rounding reaches it, so the output never reads `60 分钟` or `24 小时`.
33
+ */
34
+ export function formatSpanZh(ms) {
35
+ const seconds = Math.max(0, Math.round(ms / 1000));
36
+ if (seconds < 60)
37
+ return `${seconds} 秒`;
38
+ const minutes = Math.round(ms / 60_000);
39
+ if (minutes < 60)
40
+ return `${minutes} 分钟`;
41
+ const hours = Math.round(ms / 3_600_000);
42
+ if (hours < 24)
43
+ return `${hours} 小时`;
44
+ return `${Math.round(ms / 86_400_000)} 天`;
45
+ }
9
46
  /**
10
47
  * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
11
48
  * falling back to `fallback` for anything not a finite number or out of range. Shared by the
@@ -26,6 +26,8 @@ export async function readProcessStartTime(pid) {
26
26
  }
27
27
  const CLI_VERSION_PROBE_TIMEOUT_MS = 1_000;
28
28
  const CLI_VERSION_MAX_CHARS = 200;
29
+ const CLI_VERSION_CACHE_TTL_MS = 10 * 60_000;
30
+ const cliVersionCache = new Map();
29
31
  /**
30
32
  * Best-effort `<executable> --version`, so a run persists which build of the target CLI it ran
31
33
  * against (spec 042 D12) — the other half of `parserVersion`'s "adapter drift vs. agent failure"
@@ -33,14 +35,24 @@ const CLI_VERSION_MAX_CHARS = 200;
33
35
  * a CLI that does not support `--version`, is slow to start, or fails outright.
34
36
  */
35
37
  export async function probeCliVersion(executable) {
38
+ // A CLI's version changes only when someone upgrades it, while a busy channel dispatches the
39
+ // same executable many times an hour — re-spawning `<cli> --version` (a cold Node start for
40
+ // claude/codex) per dispatch bought nothing. A short TTL keeps an upgrade visible soon after.
41
+ const cached = cliVersionCache.get(executable);
42
+ if (cached && Date.now() - cached.at < CLI_VERSION_CACHE_TTL_MS)
43
+ return cached.value;
44
+ let value;
36
45
  try {
37
46
  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;
47
+ value = stdout.trim().split("\n")[0]?.slice(0, CLI_VERSION_MAX_CHARS) || undefined;
40
48
  }
41
49
  catch {
42
- return undefined;
50
+ value = undefined;
43
51
  }
52
+ // Only a real answer is cached: a timeout on a cold start should not hide the version for the TTL.
53
+ if (value)
54
+ cliVersionCache.set(executable, { value, at: Date.now() });
55
+ return value;
44
56
  }
45
57
  /** True if `pid` names a live process this user can at least see, without sending a real signal. */
46
58
  export function isProcessAlive(pid) {
@@ -12,6 +12,7 @@ export declare class OperationTimeoutError extends Error {
12
12
  constructor(operation: string, timeoutMs: number);
13
13
  }
14
14
  /** A delay that never keeps the process alive on its own — every background-loop backoff and
15
- * budget wait in the codebase wants this, not a bare `setTimeout` promise. */
16
- export declare function sleepUnref(ms: number): Promise<void>;
15
+ * budget wait in the codebase wants this, not a bare `setTimeout` promise. An aborted `signal`
16
+ * ends the wait early (it still resolves; callers re-check whatever aborted it). */
17
+ export declare function sleepUnref(ms: number, signal?: AbortSignal): Promise<void>;
17
18
  export declare function withTimeout<T>(operation: string, timeoutMs: number, run: () => Promise<T>): Promise<T>;
@@ -15,11 +15,22 @@ export class OperationTimeoutError extends Error {
15
15
  }
16
16
  }
17
17
  /** A delay that never keeps the process alive on its own — every background-loop backoff and
18
- * budget wait in the codebase wants this, not a bare `setTimeout` promise. */
19
- export function sleepUnref(ms) {
18
+ * budget wait in the codebase wants this, not a bare `setTimeout` promise. An aborted `signal`
19
+ * ends the wait early (it still resolves; callers re-check whatever aborted it). */
20
+ export function sleepUnref(ms, signal) {
20
21
  return new Promise((resolve) => {
21
- const timer = setTimeout(resolve, ms);
22
+ if (signal?.aborted) {
23
+ resolve();
24
+ return;
25
+ }
26
+ const done = () => {
27
+ clearTimeout(timer);
28
+ signal?.removeEventListener("abort", done);
29
+ resolve();
30
+ };
31
+ const timer = setTimeout(done, ms);
22
32
  timer.unref?.();
33
+ signal?.addEventListener("abort", done, { once: true });
23
34
  });
24
35
  }
25
36
  export async function withTimeout(operation, timeoutMs, run) {
@@ -210,9 +210,31 @@ export const claudeCodeHarness = {
210
210
  const parts = Array.isArray(event.message.content) ? event.message.content : [];
211
211
  for (const part of parts) {
212
212
  if (isRecord(part) && part.type === "tool_use" && typeof part.name === "string") {
213
- return part.name;
213
+ return describeClaudeToolUse(part.name, isRecord(part.input) ? part.input : {});
214
214
  }
215
215
  }
216
216
  return undefined;
217
217
  },
218
218
  };
219
+ const PROGRESS_LABEL_MAX_CHARS = 80;
220
+ /** The one input field that says what a claude-code tool call is acting on, in priority order. */
221
+ const TOOL_SUBJECT_FIELDS = ["command", "file_path", "notebook_path", "path", "pattern", "url", "query", "description"];
222
+ /**
223
+ * A bare tool name (`Bash`, `Edit`) says nothing about where a run is; the command or path it is
224
+ * acting on does. The todo list gets the same "done/total" shape codex-cli's progress uses.
225
+ */
226
+ function describeClaudeToolUse(name, input) {
227
+ if (Array.isArray(input.todos) && input.todos.length > 0) {
228
+ const done = input.todos.filter((todo) => isRecord(todo) && todo.status === "completed").length;
229
+ return `待办 ${done}/${input.todos.length}`;
230
+ }
231
+ for (const field of TOOL_SUBJECT_FIELDS) {
232
+ const value = input[field];
233
+ if (typeof value !== "string")
234
+ continue;
235
+ const subject = value.split("\n")[0]?.trim();
236
+ if (subject)
237
+ return `${name} ${subject}`.slice(0, PROGRESS_LABEL_MAX_CHARS);
238
+ }
239
+ return name;
240
+ }
@@ -1,4 +1,19 @@
1
1
  import type { RunHarness } from "../runs.js";
2
+ /** No output to either artifact file for this long reads as "possibly stuck". */
3
+ export declare const STALL_THRESHOLD_MS: number;
4
+ /**
5
+ * The pacing rules above, shared by the external tail and an internal run that has gone async
6
+ * (its worker reports steps in-process, so it has labels but no file to poll).
7
+ */
8
+ export interface ProgressPacer {
9
+ /** Whether a label offered now could be reported — lets a caller skip the work of finding one. */
10
+ ready(now?: number): boolean;
11
+ /** Report `label` if pacing allows and it differs from the last one reported. */
12
+ offer(label: string, now?: number): void;
13
+ }
14
+ export declare function createProgressPacer(startedAt: number, emit: (label: string) => void): ProgressPacer;
15
+ /** When the run last wrote anything to its output files, or `undefined` if neither exists yet. */
16
+ export declare function readLastOutputAt(artifactDir: string): Promise<number | undefined>;
2
17
  export interface ExternalProgressTailInput {
3
18
  artifactDir: string;
4
19
  harnessId: RunHarness;
@@ -6,6 +21,8 @@ export interface ExternalProgressTailInput {
6
21
  * run actually started producing output, not from registration. */
7
22
  startedAt: number;
8
23
  onProgress: (label: string) => void;
24
+ /** Called once per stall (re-armed when output resumes) with how long the run has been silent. */
25
+ onStall?: (silentMs: number) => void;
9
26
  }
10
27
  export interface ExternalProgressTail {
11
28
  stop(): void;
@@ -1,4 +1,4 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { getExternalHarness } from "./registry.js";
4
4
  /**
@@ -12,6 +12,10 @@ import { getExternalHarness } from "./registry.js";
12
12
  * has to handle a half-written trailing line, this doesn't, and a run's artifact file is small
13
13
  * enough (single-digit MB even for a long run) that re-reading it every `POLL_MS` costs nothing a
14
14
  * background process needs to care about.
15
+ *
16
+ * The same poll also watches for a stall: a process that is alive but has written nothing to
17
+ * either output file for `STALL_THRESHOLD_MS` gets one "needs attention" signal — it is not killed,
18
+ * since a long silent build or test run is legitimate; only its wall-time budget ends it.
15
19
  */
16
20
  const POLL_MS = 15_000;
17
21
  /** A run that finishes inside this window never gets a progress notice — the settled notice
@@ -22,25 +26,64 @@ const FIRST_NOTICE_DELAY_MS = 45_000;
22
26
  const MIN_NOTICE_GAP_MS = 180_000;
23
27
  /** Ceiling on notices for a single run — even a multi-hour run stops narrating after this many. */
24
28
  const MAX_NOTICES = 6;
25
- const NOOP_TAIL = { stop() { } };
29
+ /** No output to either artifact file for this long reads as "possibly stuck". */
30
+ export const STALL_THRESHOLD_MS = 10 * 60_000;
31
+ /** A run that keeps stalling and recovering stops being reported after this many stall notices. */
32
+ const MAX_STALL_NOTICES = 3;
33
+ const OUTPUT_FILENAMES = ["events.jsonl", "stderr.log"];
34
+ export function createProgressPacer(startedAt, emit) {
35
+ let lastLabel;
36
+ let lastNoticeAt = 0;
37
+ let noticeCount = 0;
38
+ const ready = (now = Date.now()) => noticeCount < MAX_NOTICES &&
39
+ now - startedAt >= FIRST_NOTICE_DELAY_MS &&
40
+ (!lastNoticeAt || now - lastNoticeAt >= MIN_NOTICE_GAP_MS);
41
+ return {
42
+ ready,
43
+ offer(label, now = Date.now()) {
44
+ if (!label || label === lastLabel || !ready(now))
45
+ return;
46
+ lastLabel = label;
47
+ lastNoticeAt = now;
48
+ noticeCount++;
49
+ emit(label);
50
+ },
51
+ };
52
+ }
53
+ /** When the run last wrote anything to its output files, or `undefined` if neither exists yet. */
54
+ export async function readLastOutputAt(artifactDir) {
55
+ const times = await Promise.all(OUTPUT_FILENAMES.map((name) => stat(join(artifactDir, name)).then((info) => (info.size > 0 ? info.mtimeMs : undefined), () => undefined)));
56
+ const known = times.filter((time) => time !== undefined);
57
+ return known.length > 0 ? Math.max(...known) : undefined;
58
+ }
26
59
  /** Starts polling; returns a handle whose `stop()` is idempotent and always safe to call. */
27
60
  export function startExternalProgressTail(input) {
28
61
  const harness = getExternalHarness(input.harnessId);
62
+ // exec has no structured protocol to read mid-run, so it gets stall detection only.
29
63
  const toProgressLabel = harness?.toProgressLabel;
30
- if (!toProgressLabel)
31
- return NOOP_TAIL; // exec, or a harness that hasn't implemented this.
32
64
  const eventsPath = join(input.artifactDir, "events.jsonl");
33
- let lastLabel;
34
- let lastNoticeAt = 0;
35
- let noticeCount = 0;
65
+ const pacer = createProgressPacer(input.startedAt, input.onProgress);
36
66
  let stopped = false;
37
- const tick = async () => {
38
- if (stopped || noticeCount >= MAX_NOTICES)
67
+ /** Output time the current stall was reported against; a newer write re-arms detection. */
68
+ let stalledSince;
69
+ let stallCount = 0;
70
+ const checkStall = async (now) => {
71
+ if (!input.onStall || stallCount >= MAX_STALL_NOTICES)
39
72
  return;
40
- const now = Date.now();
41
- if (now - input.startedAt < FIRST_NOTICE_DELAY_MS)
73
+ const lastOutputAt = (await readLastOutputAt(input.artifactDir)) ?? input.startedAt;
74
+ if (stalledSince !== undefined && lastOutputAt > stalledSince)
75
+ stalledSince = undefined;
76
+ if (stalledSince !== undefined || stopped)
77
+ return;
78
+ const silentMs = now - lastOutputAt;
79
+ if (silentMs < STALL_THRESHOLD_MS)
42
80
  return;
43
- if (lastNoticeAt && now - lastNoticeAt < MIN_NOTICE_GAP_MS)
81
+ stalledSince = lastOutputAt;
82
+ stallCount++;
83
+ input.onStall(silentMs);
84
+ };
85
+ const checkProgress = async (now) => {
86
+ if (!toProgressLabel || !pacer.ready(now))
44
87
  return;
45
88
  let text;
46
89
  try {
@@ -66,12 +109,16 @@ export function startExternalProgressTail(input) {
66
109
  if (label)
67
110
  break;
68
111
  }
69
- if (!label || label === lastLabel || stopped)
112
+ if (!label || stopped)
70
113
  return;
71
- lastLabel = label;
72
- lastNoticeAt = now;
73
- noticeCount++;
74
- input.onProgress(label);
114
+ pacer.offer(label, now);
115
+ };
116
+ const tick = async () => {
117
+ if (stopped)
118
+ return;
119
+ const now = Date.now();
120
+ await checkStall(now);
121
+ await checkProgress(now);
75
122
  };
76
123
  // `tick` is async and its result is discarded: a rejection here (a throwing `onProgress`
77
124
  // callback, say) would otherwise surface as an unhandled rejection and reach the process-level
@@ -3,6 +3,7 @@ import type { SecurityConfig } from "../../security/types.js";
3
3
  import { probeCliVersion, readProcessStartTime } from "../../shared/host-process.js";
4
4
  import type { SubAgentThinkingLevel } from "../discovery.js";
5
5
  import type { RunMutates, SubAgentRunManager } from "../runs.js";
6
+ import type { WorkspaceBaseline } from "../workspace-summary.js";
6
7
  /**
7
8
  * The external-run orchestrator (spec 040, D1/D3/D4). One prompt, one short-lived, argv-direct,
8
9
  * detached process. The launch order matters (D1): admission and the lease are the caller's job
@@ -44,6 +45,8 @@ export interface LaunchExternalRunInput {
44
45
  resumeSessionId?: string;
45
46
  /** The role's own `mutates` declaration, carried through to the dispatch audit event (D8.1). */
46
47
  mutates?: RunMutates;
48
+ /** A write run's dispatch-time dirty-path snapshot (see `workspace-summary.ts`). */
49
+ workspaceBaseline?: WorkspaceBaseline;
47
50
  /** Spec 042 D7: fingerprint of the role's `command`/`externalModelRef`/`shell`, persisted so a
48
51
  * later `follow_up` can detect a hot-edited role before resuming under it. */
49
52
  roleFingerprint?: string;
@@ -169,6 +169,7 @@ export async function launchExternalRun(input) {
169
169
  channelDir: input.channelDir,
170
170
  leaseKey: input.leaseKey,
171
171
  mutates: input.mutates,
172
+ workspaceBaseline: input.workspaceBaseline,
172
173
  });
173
174
  // The final executable/argv/cwd/capability record must be durable before a process can exist.
174
175
  // `external-agent` uses the strict appender path and rejects on queue or I/O failure; a failure
@@ -305,7 +306,10 @@ export async function launchExternalRun(input) {
305
306
  await closePromise;
306
307
  const reason = `Failed to persist external launch state: ${errorMessage(error)}`;
307
308
  await runManager.settle(input.runId, failedSettleInput(reason), { announce: false }).catch((settleError) => {
308
- log.logWarning(`Failed to settle external run ${input.runId} after launch persistence failed`, errorMessage(settleError));
309
+ log.logWarn("subagent.settle.failed", "External run settlement after launch-persistence failure failed", {
310
+ reason: errorMessage(settleError),
311
+ fields: { runId: input.runId },
312
+ });
309
313
  });
310
314
  throw error;
311
315
  }
@@ -346,15 +350,19 @@ export async function launchExternalRun(input) {
346
350
  Promise.resolve().then(() => (input.probeCliVersionFn ?? probeCliVersion)(invocation.executable)),
347
351
  ])
348
352
  .then(async ([pidStartedAt, cliVersion]) => {
349
- await runManager
350
- .updateLaunchMetadata(input.runId, { pidStartedAt, cliVersion })
351
- .catch((error) => log.logWarning(`Failed to persist launch probes for run ${input.runId}`, errorMessage(error)));
353
+ await runManager.updateLaunchMetadata(input.runId, { pidStartedAt, cliVersion }).catch((error) => log.logWarn("subagent.launch_probes.persist_failed", "Launch probe persist failed", {
354
+ reason: errorMessage(error),
355
+ fields: { runId: input.runId },
356
+ }));
352
357
  })
353
358
  .catch((error) => {
354
359
  // The production probes are already best-effort; keep the same property for test seams or
355
360
  // a future host implementation and never leave a spawned child unobserved because metadata
356
361
  // collection failed.
357
- log.logWarning(`Failed to collect launch probes for run ${input.runId}`, errorMessage(error));
362
+ log.logWarn("subagent.launch_probes.collect_failed", "Launch probe collection failed", {
363
+ reason: errorMessage(error),
364
+ fields: { runId: input.runId },
365
+ });
358
366
  });
359
367
  // Deliberately attach the close watcher before waiting for probe metadata. A fast child can exit
360
368
  // during that wait; the promise is already listening, and finalization waits for the launch
@@ -384,17 +392,23 @@ export async function launchExternalRun(input) {
384
392
  terminationReason,
385
393
  maxWallTimeSec: input.maxWallTimeSec,
386
394
  mutates: input.mutates,
395
+ workspaceBaseline: input.workspaceBaseline,
387
396
  }, (settleInput, options) => runManager.settle(input.runId, settleInput, options), { announce: terminationReason !== "cancelled" }).catch((error) => {
388
- log.logWarning(`Failed to settle external run ${input.runId}`, errorMessage(error));
397
+ log.logWarn("subagent.settle.failed", "External run settlement failed", {
398
+ reason: errorMessage(error),
399
+ fields: { runId: input.runId },
400
+ });
389
401
  });
390
402
  });
391
- await launchMetadataPromise;
392
403
  // The narrow window between the pre-spawn placeholder handle (claimExternalLaunch) and the
393
404
  // real one just above: a cancel arriving there durably marked `terminationReason` (P1-1) but
394
405
  // had no live process to kill yet. Act on it now.
395
406
  if (runManager.get(input.runId)?.terminationReason === "cancelled") {
396
407
  void killProcessGroup(pid);
397
408
  }
409
+ // The dispatching tool call does not wait for the probes: the pid is already durable and the
410
+ // cancel handle installed, so they are diagnostics only. Settlement still waits for them (the
411
+ // close watcher above) so a run's terminal record carries them.
398
412
  return { ok: true };
399
413
  function failedSettleInput(reason) {
400
414
  return {
@@ -1,4 +1,5 @@
1
1
  import type { RunHarness, RunMutates, SettleInput } from "../runs.js";
2
+ import { type WorkspaceBaseline } from "../workspace-summary.js";
2
3
  import { type ExternalOutcome } from "./harness.js";
3
4
  export interface BuildExternalSettleInputInput {
4
5
  harnessId: RunHarness;
@@ -30,6 +31,8 @@ export interface FinalizeExternalRunInput {
30
31
  /** P2-2: only a `write` run's completion pays for a `git status` summary — a `read` run cannot
31
32
  * have changed anything, and this must never become a hidden cost on the common read-only path. */
32
33
  mutates?: RunMutates;
34
+ /** The run's dispatch-time snapshot, so the summary leaves out paths that were already dirty. */
35
+ workspaceBaseline?: WorkspaceBaseline;
33
36
  }
34
37
  /**
35
38
  * Read this run's artifact files, parse them through its harness, decide its verdict (for a
@@ -83,7 +83,7 @@ export async function finalizeExternalRun(input, settle, options) {
83
83
  // P2-2: only for a run that actually could have changed the working directory, and only once it
84
84
  // is known to have finished cleanly — best-effort, never blocks or fails settlement.
85
85
  if (input.mutates === "write" && settleInput.status === "completed") {
86
- const workspaceSummary = await changedPathsSummary(input.workingDirectory).catch(() => undefined);
86
+ const workspaceSummary = await changedPathsSummary(input.workingDirectory, input.workspaceBaseline).catch(() => undefined);
87
87
  if (workspaceSummary)
88
88
  settleInput = { ...settleInput, workspaceSummary };
89
89
  }