@xzzpig/pi-subagents 0.8.0 → 0.10.0

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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
4
4
  import { TEMP_ROOT_DIR } from "../../shared/types.ts";
5
+ import { getAgentDir } from "../../shared/utils.ts";
5
6
 
6
7
  export const EXCLUSIONS_PATH_ENV = "PI_MODEL_EXCLUSIONS_PATH";
7
8
 
@@ -20,14 +21,67 @@ type RecordModelFailureOptions = ModelExclusionTarget & {
20
21
 
21
22
  let exclusions: ModelExclusion[] = [];
22
23
  let loaded = false;
23
- let defaultTTLMs = 24 * 60 * 60_000; // 24 hours, overridable via setDefaultTTL
24
+ /** Default duration for a new model exclusion when no per-record TTL is supplied. */
25
+ export const DEFAULT_MODEL_EXCLUSION_TTL_MS = 24 * 60 * 60_000;
26
+ /** Keeps a new expiry safely below JavaScript's maximum Date timestamp. */
27
+ export const MAX_MODEL_EXCLUSION_TTL_MS = 8_000_000_000_000_000;
28
+ const MAX_DATE_TIMESTAMP_MS = 8_640_000_000_000_000;
29
+ let defaultTTLMs = DEFAULT_MODEL_EXCLUSION_TTL_MS;
30
+ let loadedTTLCeilingMs: number | undefined;
24
31
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
25
32
  let persistSeq = 0;
26
33
 
27
- /** Override the default exclusion TTL. */
28
- export function setDefaultTTL(ms: number): void {
29
- if (!Number.isFinite(ms) || ms <= 0) throw new Error("Default model exclusion TTL must be a finite positive number.");
34
+ const AUTH_FAILURE_PATTERNS = [
35
+ /auth(?:entication)?/i,
36
+ /unauthori[sz]ed/i,
37
+ /forbidden/i,
38
+ /api key/i,
39
+ /token expired/i,
40
+ /invalid key/i,
41
+ ];
42
+
43
+ function isAuthModelExclusion(entry: ModelExclusion): boolean {
44
+ const reason = entry.reason;
45
+ return typeof reason === "string" && AUTH_FAILURE_PATTERNS.some((pattern) => pattern.test(reason));
46
+ }
47
+
48
+ function getAuthStoreMtimeMs(): number | undefined {
49
+ const authStorePath = path.join(getAgentDir(), "auth.json");
50
+ try {
51
+ const stats = fs.statSync(authStorePath);
52
+ return stats.isFile() && Number.isFinite(stats.mtimeMs) ? stats.mtimeMs : undefined;
53
+ } catch (error) {
54
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
55
+ console.error(`[model-exclusions] Failed to stat Pi auth store at ${authStorePath}; preserving auth-related exclusions:`, error);
56
+ }
57
+ return undefined;
58
+ }
59
+ }
60
+
61
+ function invalidateAuthExclusions(): void {
62
+ if (!exclusions.some(isAuthModelExclusion)) return;
63
+ const authStoreMtimeMs = getAuthStoreMtimeMs();
64
+ if (authStoreMtimeMs === undefined) return;
65
+ const retained = exclusions.filter((entry) => !isAuthModelExclusion(entry) || authStoreMtimeMs <= entry.recordedAt);
66
+ if (retained.length === exclusions.length) return;
67
+ exclusions = retained;
68
+ schedulePersist();
69
+ }
70
+
71
+ /**
72
+ * Override the default TTL applied to newly recorded model exclusions.
73
+ *
74
+ * @param ms Duration in milliseconds. Must be finite and positive.
75
+ * @returns Nothing.
76
+ */
77
+ // TEST:test/unit/model-exclusions.test.ts[model exclusions — TTL expiry]
78
+ export function setDefaultTTL(ms: number, options?: { shortenExisting?: boolean }): void {
79
+ if (!Number.isFinite(ms) || ms <= 0 || ms > MAX_MODEL_EXCLUSION_TTL_MS) {
80
+ throw new Error(`Default model exclusion TTL must be a finite positive number no greater than ${MAX_MODEL_EXCLUSION_TTL_MS}.`);
81
+ }
30
82
  defaultTTLMs = ms;
83
+ loadedTTLCeilingMs = options?.shortenExisting ? ms : undefined;
84
+ if (loaded && loadedTTLCeilingMs !== undefined && shortenExclusionsToTTL(exclusions, loadedTTLCeilingMs, Date.now())) schedulePersist();
31
85
  }
32
86
 
33
87
  /**
@@ -78,10 +132,24 @@ function ensureLoaded(): void {
78
132
  const raw = fs.readFileSync(getExclusionsFilePath(), "utf-8");
79
133
  const data = JSON.parse(raw);
80
134
  if (data.version === 1) {
135
+ if (!Array.isArray(data.exclusions)) throw new Error("Model exclusion store version 1 must contain an exclusions array.");
81
136
  const now = Date.now();
82
- exclusions = (data.exclusions ?? []).filter((e: ModelExclusion) => e.expiresAt > now);
137
+ let droppedInvalid = false;
138
+ exclusions = data.exclusions.flatMap((entry: unknown, index: number) => {
139
+ const result = readPersistedExclusion(entry, index);
140
+ if (!result.ok) {
141
+ droppedInvalid = true;
142
+ console.warn(`[model-exclusions] Ignoring invalid exclusion: ${result.message}`);
143
+ return [];
144
+ }
145
+ return [result.exclusion];
146
+ }).filter((e: ModelExclusion) => e.expiresAt > now);
147
+ const shortened = loadedTTLCeilingMs !== undefined && shortenExclusionsToTTL(exclusions, loadedTTLCeilingMs, now);
83
148
  exclusions = deduplicate(exclusions);
149
+ if (droppedInvalid) flushPersist();
150
+ else if (shortened) schedulePersist();
84
151
  }
152
+ invalidateAuthExclusions();
85
153
  } catch (error) {
86
154
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
87
155
  console.error(`[model-exclusions] Failed to load exclusions from ${getExclusionsFilePath()}:`, error);
@@ -89,6 +157,32 @@ function ensureLoaded(): void {
89
157
  }
90
158
  }
91
159
 
160
+ type PersistedExclusionRead =
161
+ | { ok: true; exclusion: ModelExclusion }
162
+ | { ok: false; message: string };
163
+
164
+ function invalidPersistedExclusion(index: number, message: string): PersistedExclusionRead {
165
+ return { ok: false, message: `Model exclusion store entry ${index} ${message}.` };
166
+ }
167
+
168
+ function readPersistedExclusion(entry: unknown, index: number): PersistedExclusionRead {
169
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return invalidPersistedExclusion(index, "must be an object");
170
+ const candidate = entry as { modelId?: unknown; provider?: unknown; reason?: unknown; recordedAt?: unknown; expiresAt?: unknown };
171
+ const { modelId, provider, reason } = candidate;
172
+ if (modelId !== undefined && (typeof modelId !== "string" || modelId.length === 0)) return invalidPersistedExclusion(index, "has an invalid modelId");
173
+ if (provider !== undefined && (typeof provider !== "string" || provider.length === 0)) return invalidPersistedExclusion(index, "has an invalid provider");
174
+ if (reason !== undefined && typeof reason !== "string") return invalidPersistedExclusion(index, "has an invalid reason");
175
+ const { recordedAt, expiresAt } = candidate;
176
+ if (typeof recordedAt !== "number" || !Number.isFinite(recordedAt) || recordedAt <= 0 || recordedAt > MAX_DATE_TIMESTAMP_MS) return invalidPersistedExclusion(index, "has an invalid recordedAt");
177
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= 0 || expiresAt > MAX_DATE_TIMESTAMP_MS) return invalidPersistedExclusion(index, "has an invalid expiresAt");
178
+ const metadata = { ...(reason === undefined ? {} : { reason }), recordedAt, expiresAt };
179
+ if (modelId === undefined) {
180
+ if (provider === undefined) return invalidPersistedExclusion(index, "must include modelId or provider");
181
+ return { ok: true, exclusion: { provider, ...metadata } };
182
+ }
183
+ return { ok: true, exclusion: { modelId, ...(provider === undefined ? {} : { provider }), ...metadata } };
184
+ }
185
+
92
186
  function dedupKey(entry: ModelExclusion): string {
93
187
  return `${entry.provider ?? ""}|${entry.modelId ?? ""}`;
94
188
  }
@@ -135,6 +229,7 @@ export function recordModelFailure(options: RecordModelFailureOptions): void {
135
229
  */
136
230
  export function clearExpiredExclusions(): void {
137
231
  ensureLoaded();
232
+ invalidateAuthExclusions();
138
233
  prune(exclusions, Date.now());
139
234
  schedulePersist();
140
235
  }
@@ -160,7 +255,7 @@ export function clearExclusions(): void {
160
255
  */
161
256
  function entryMatches(entry: ModelExclusion, candidateModelId: string, candidateProvider: string | undefined, now: number): boolean {
162
257
  if (entry.expiresAt <= now) return false;
163
- if (entry.modelId) {
258
+ if (entry.modelId !== undefined) {
164
259
  if (entry.modelId !== candidateModelId) return false;
165
260
  return !entry.provider || !candidateProvider || entry.provider === candidateProvider;
166
261
  }
@@ -172,9 +267,23 @@ function entryMatches(entry: ModelExclusion, candidateModelId: string, candidate
172
267
  */
173
268
  export function isExcluded(modelId: string, provider: string): boolean {
174
269
  ensureLoaded();
270
+ invalidateAuthExclusions();
175
271
  return exclusions.some((entry) => entryMatches(entry, modelId, provider, Date.now()));
176
272
  }
177
273
 
274
+ /**
275
+ * Return the active exclusion matching a full model id, if any.
276
+ *
277
+ * The caller uses this for hard-fail diagnostics; fallback filtering should
278
+ * continue to use {@link filterFallbackCandidates}.
279
+ */
280
+ export function findModelExclusion(fullId: string, now = Date.now()): Readonly<ModelExclusion> | undefined {
281
+ ensureLoaded();
282
+ invalidateAuthExclusions();
283
+ const { provider, modelId } = parseModelKey(fullId);
284
+ return exclusions.find((entry) => entryMatches(entry, modelId, provider, now));
285
+ }
286
+
178
287
  /**
179
288
  * Number of live (non-expired) exclusions.
180
289
  */
@@ -205,16 +314,23 @@ export function parseModelKey(fullId: string): { provider?: string; modelId: str
205
314
  * Filter a list of candidate fullIds, removing excluded models/providers and
206
315
  * duplicates while preserving order.
207
316
  */
208
- export function filterFallbackCandidates(candidates: string[], opts?: { now?: number }): string[] {
317
+ export function filterFallbackCandidates(candidates: string[], opts?: {
318
+ now?: number;
319
+ onExcluded?: (candidate: string, exclusion: Readonly<ModelExclusion>) => void;
320
+ }): string[] {
209
321
  ensureLoaded();
322
+ invalidateAuthExclusions();
210
323
  const timestamp = opts?.now ?? Date.now();
211
324
  const seen = new Set<string>();
212
325
  const filtered: string[] = [];
213
326
  for (const raw of candidates) {
214
327
  if (!raw || seen.has(raw)) continue;
215
328
  const { provider: candidateProvider, modelId: candidateModelId } = parseModelKey(raw);
216
- const excluded = exclusions.some((entry) => entryMatches(entry, candidateModelId, candidateProvider, timestamp));
217
- if (excluded) continue;
329
+ const exclusion = exclusions.find((entry) => entryMatches(entry, candidateModelId, candidateProvider, timestamp));
330
+ if (exclusion) {
331
+ opts?.onExcluded?.(raw, exclusion);
332
+ continue;
333
+ }
218
334
  seen.add(raw);
219
335
  filtered.push(raw);
220
336
  }
@@ -241,3 +357,17 @@ function prune(items: ModelExclusion[], now: number): void {
241
357
  }
242
358
  items.length = write;
243
359
  }
360
+
361
+ function shortenExclusionsToTTL(items: ModelExclusion[], ttlMs: number, now: number): boolean {
362
+ let changed = false;
363
+ for (const entry of items) {
364
+ const configuredExpiry = entry.recordedAt + ttlMs;
365
+ if (entry.expiresAt > configuredExpiry) {
366
+ entry.expiresAt = configuredExpiry;
367
+ changed = true;
368
+ }
369
+ }
370
+ const previousLength = items.length;
371
+ prune(items, now);
372
+ return changed || items.length !== previousLength;
373
+ }
@@ -1,7 +1,8 @@
1
1
  import { splitKnownThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
2
2
  import type { Usage } from "../../shared/types.ts";
3
- import { filterFallbackCandidates, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
3
+ import { filterFallbackCandidates, findModelExclusion, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
4
4
  import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
5
+ import { redactSecretValues } from "./permissions.ts";
5
6
 
6
7
  export type { AvailableModelInfo };
7
8
 
@@ -23,7 +24,12 @@ export function formatSubagentModelVerificationError(expectedModel: string, obse
23
24
  const observedBase = splitThinkingSuffix(observedModel).baseModel;
24
25
  if (expectedBase === observedBase) return undefined;
25
26
  const expectedEntry = availableModels.find((entry) => entry.fullId === expectedBase);
26
- if (expectedEntry && expectedEntry.id === observedBase) return undefined;
27
+ if (expectedEntry) {
28
+ if (expectedEntry.id === observedBase) return undefined;
29
+ const expectedIdLeaf = expectedEntry.id.slice(expectedEntry.id.lastIndexOf("/") + 1);
30
+ const expectedFullIdLeaf = expectedEntry.fullId.slice(expectedEntry.fullId.lastIndexOf("/") + 1);
31
+ if (expectedIdLeaf === observedBase || expectedFullIdLeaf === observedBase) return undefined;
32
+ }
27
33
  return `model_verification_failed: child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'.`;
28
34
  }
29
35
 
@@ -278,6 +284,39 @@ function enforceModelScopes(
278
284
  for (const violation of violations) (onWarn ?? defaultScopeWarn)(violation);
279
285
  }
280
286
 
287
+ const MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH = 240;
288
+ const MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES = 20;
289
+
290
+ function sanitizeModelExclusionDiagnostic(value: string | undefined, fallback: string): string {
291
+ const normalized = typeof value === "string"
292
+ ? value.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").trim()
293
+ : "";
294
+ return redactSecretValues(normalized || fallback).slice(0, MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH);
295
+ }
296
+
297
+ function formatModelExclusionExpiry(expiresAt: number): string {
298
+ if (!Number.isFinite(expiresAt)) return "unknown";
299
+ const date = new Date(expiresAt);
300
+ return Number.isNaN(date.getTime()) ? "unknown" : date.toISOString();
301
+ }
302
+
303
+ function formatExcludedCandidateEvidence(candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>): string {
304
+ const { provider, modelId } = parseModelKey(candidate);
305
+ const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
306
+ const displayModel = sanitizeModelExclusionDiagnostic(modelId, "unknown");
307
+ const displayProvider = sanitizeModelExclusionDiagnostic(provider ?? exclusion.provider, "unspecified");
308
+ const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
309
+ return `${displayCandidate} — model: ${displayModel}; provider: ${displayProvider}; reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}`;
310
+ }
311
+
312
+ function throwForExplicitModelExclusion(model: string): void {
313
+ const exclusion = findModelExclusion(model);
314
+ if (!exclusion) return;
315
+ const reason = redactSecretValues((exclusion.reason ?? "runtime-failure").replace(/[\u0000-\u001f\u007f]+/g, " ")).slice(0, 240);
316
+ const expiry = Number.isFinite(exclusion.expiresAt) ? `; expires: ${new Date(exclusion.expiresAt).toISOString()}` : "";
317
+ throw new Error(`Requested subagent model '${model}' is excluded and cannot be replaced by a fallback (reason: ${reason}${expiry}).`);
318
+ }
319
+
281
320
  /**
282
321
  * Resolve the `--model` override passed to a spawned subagent.
283
322
  *
@@ -307,12 +346,23 @@ export function resolveSubagentModelOverride(
307
346
  const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;
308
347
  if (!parentModel) throwForUnresolvedEnforcedInheritScope(options?.scope, explicit === undefined || options?.source === "inherited");
309
348
  let resolved: string | undefined;
349
+ let resolvedFromRegistry = explicit === undefined;
310
350
  if (explicit === undefined) {
311
351
  resolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;
312
352
  } else {
313
- resolved = resolveRequiredSubagentModelCandidate(explicit, availableModels, preferredProvider);
353
+ const candidate = resolveSubagentModelCandidate(explicit, availableModels, preferredProvider);
354
+ if (options?.source === "explicit") {
355
+ resolved = candidate ?? resolveRequiredSubagentModelCandidate(explicit, availableModels, preferredProvider);
356
+ throwForExplicitModelExclusion(resolved);
357
+ resolvedFromRegistry = true;
358
+ } else if (candidate) {
359
+ resolved = candidate;
360
+ resolvedFromRegistry = true;
361
+ } else {
362
+ resolved = explicit;
363
+ }
314
364
  }
315
- if (resolved && options?.scope) {
365
+ if (resolved && options?.scope && resolvedFromRegistry) {
316
366
  const source: ModelSource = explicit === undefined ? "inherited" : (options.source ?? "inherited");
317
367
  enforceModelScopes(resolved, options.scope, source, options.onWarn);
318
368
  }
@@ -325,14 +375,15 @@ export function resolveEffectiveSubagentModel(
325
375
  parentModel: ParentModel | undefined,
326
376
  availableModels: AvailableModelInfo[] | undefined,
327
377
  preferredProvider?: string,
328
- options?: Omit<ResolveSubagentModelOverrideOptions, "source">,
378
+ options?: ResolveSubagentModelOverrideOptions,
329
379
  ): string | undefined {
380
+ const source = options?.source ?? (explicitModel !== undefined ? "explicit" : "inherited");
330
381
  const resolved = resolveSubagentModelOverride(
331
382
  explicitModel ?? agentModel,
332
383
  parentModel,
333
384
  availableModels,
334
385
  preferredProvider,
335
- { ...options, source: explicitModel !== undefined ? "explicit" : "inherited" },
386
+ { ...options, source },
336
387
  );
337
388
  if (resolved || explicitModel === undefined) return resolved;
338
389
  return resolveSubagentModelOverride(
@@ -340,16 +391,37 @@ export function resolveEffectiveSubagentModel(
340
391
  parentModel,
341
392
  availableModels,
342
393
  preferredProvider,
343
- { ...options, source: "inherited" },
394
+ { ...options, source: options?.source ?? "inherited" },
344
395
  );
345
396
  }
346
397
 
398
+ export type ModelOrigin = ModelSource | "configured";
399
+
347
400
  export interface BuildModelCandidatesOptions {
348
401
  /** Fallback models warn by default and throw when strict scope enforcement is enabled. */
349
402
  scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
350
403
  onWarn?: (violation: ModelScopeViolation) => void;
351
404
  /** The primary model came from the running parent session, not configuration. */
352
405
  primaryModelFromParent?: boolean;
406
+ /** How the primary model was selected. Explicit stays strict and does not rotate to fallbacks. */
407
+ origin?: ModelOrigin;
408
+ }
409
+
410
+ const ZERO_USABLE_MODEL_CANDIDATES_ERROR =
411
+ "No usable subagent models remain after registry, scope, and cached-exclusion filtering.";
412
+
413
+ export function resolveModelOrigin(input: {
414
+ explicitModel?: string | boolean;
415
+ agentModel?: string | boolean;
416
+ parentModel?: ParentModel;
417
+ fromParent?: boolean;
418
+ storedOrigin?: ModelOrigin;
419
+ }): ModelOrigin {
420
+ if (input.storedOrigin) return input.storedOrigin;
421
+ if (input.fromParent) return "inherited";
422
+ if (inheritsParentModel(input.explicitModel, input.agentModel, input.parentModel)) return "inherited";
423
+ const trimmed = typeof input.explicitModel === "string" ? input.explicitModel.trim() : "";
424
+ return trimmed && trimmed !== INHERIT_MODEL ? "explicit" : "configured";
353
425
  }
354
426
 
355
427
  export function inheritsParentModel(
@@ -370,31 +442,69 @@ export function buildModelCandidates(
370
442
  options?: BuildModelCandidatesOptions,
371
443
  ): string[] {
372
444
  if (!primaryModel) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
445
+ const origin = options?.origin ?? (options?.primaryModelFromParent ? "inherited" : "configured");
446
+ const scopes = configuredScopes(options?.scope);
447
+ type ExcludedCandidate = { candidate: string; exclusion: NonNullable<ReturnType<typeof findModelExclusion>> };
448
+ const excludedCandidates: ExcludedCandidate[] = [];
449
+ let excludedCandidateCount = 0;
450
+ const warnCachedExclusion = (candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>) => {
451
+ excludedCandidateCount++;
452
+ if (excludedCandidates.length < MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES) excludedCandidates.push({ candidate, exclusion });
453
+ const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
454
+ const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
455
+ console.warn(`[pi-subagents] Skipping model '${displayCandidate}' due to a cached exclusion (reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}).`);
456
+ };
457
+ if (origin === "explicit" && primaryModel) {
458
+ const normalized = resolveRequiredSubagentModelCandidate(primaryModel.trim(), availableModels, preferredProvider);
459
+ throwForExplicitModelExclusion(normalized);
460
+ enforceModelScopes(normalized, scopes, "explicit", options?.onWarn);
461
+ primaryModel = normalized;
462
+ }
373
463
  const seen = new Set<string>();
374
464
  const candidates: string[] = [];
375
465
  const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];
466
+ let skippedPrimary: string | undefined;
467
+ let skippedFallback: string | undefined;
376
468
  for (let index = 0; index < rawCandidates.length; index++) {
377
469
  const raw = rawCandidates[index];
378
470
  if (!raw) continue;
379
471
  const model = raw.trim();
380
- const normalized = index === 0
381
- ? options?.primaryModelFromParent
382
- ? model
383
- : resolveRequiredSubagentModelCandidate(model, availableModels, preferredProvider)
472
+ const normalized = index === 0 && (origin === "inherited" || origin === "explicit" || options?.primaryModelFromParent)
473
+ ? model
384
474
  : resolveSubagentModelCandidate(model, availableModels, preferredProvider);
385
475
  if (!normalized) {
386
- console.warn(`[pi-subagents] Skipping fallback model '${model}' because it is unavailable in this environment.`);
476
+ if (index === 0) skippedPrimary = model;
477
+ else {
478
+ skippedFallback ??= model;
479
+ console.warn(`[pi-subagents] Skipping fallback model '${model}' because it is unavailable in this environment.`);
480
+ }
387
481
  continue;
388
482
  }
389
483
  if (seen.has(normalized)) continue;
390
- const scopes = configuredScopes(options?.scope);
391
484
  if (index > 0 || scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
392
485
  enforceModelScopes(normalized, scopes, "inherited", options?.onWarn);
393
486
  }
394
487
  seen.add(normalized);
395
488
  candidates.push(normalized);
396
489
  }
397
- return filterFallbackCandidates(candidates);
490
+ const resolved = filterFallbackCandidates(candidates, { onExcluded: warnCachedExclusion });
491
+ if (resolved.length === 0) {
492
+ if (skippedPrimary) resolveRequiredSubagentModelCandidate(skippedPrimary, availableModels, preferredProvider);
493
+ if (candidates.length === 0 && skippedFallback) resolveRequiredSubagentModelCandidate(skippedFallback, availableModels, preferredProvider);
494
+ if (candidates.length > 0) {
495
+ const shownExclusions = excludedCandidates;
496
+ const omittedExclusions = excludedCandidateCount - shownExclusions.length;
497
+ const evidence = shownExclusions.length > 0
498
+ ? ` (excluded: ${shownExclusions.map(({ candidate, exclusion }) => formatExcludedCandidateEvidence(candidate, exclusion)).join("; ")}${omittedExclusions > 0 ? `; ... and ${omittedExclusions} more` : ""})`
499
+ : "";
500
+ throw new Error(`${ZERO_USABLE_MODEL_CANDIDATES_ERROR}${evidence}`);
501
+ }
502
+ return resolved;
503
+ }
504
+ if (skippedPrimary) {
505
+ console.warn(`[pi-subagents] Skipping primary model '${skippedPrimary}' because it is unavailable in this environment.`);
506
+ }
507
+ return resolved;
398
508
  }
399
509
 
400
510
  const RETRYABLE_MODEL_FAILURE_PATTERNS = [
@@ -419,6 +529,7 @@ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
419
529
  /overloaded/i,
420
530
  /service unavailable/i,
421
531
  /temporar(?:ily)? unavailable/i,
532
+ /connection\s+(?:error|reset|closed|aborted)/i,
422
533
  /connection refused/i,
423
534
  /fetch failed/i,
424
535
  /network error/i,
@@ -427,9 +538,11 @@ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
427
538
  /upstream/i,
428
539
  /timed? out/i,
429
540
  /timeout/i,
541
+ /\b500\b/,
430
542
  /\b502\b/,
431
543
  /\b503\b/,
432
544
  /\b504\b/,
545
+ /internal server error/i,
433
546
  /cold.?start/i,
434
547
  /empty response/i,
435
548
  /no output/i,
@@ -451,6 +564,25 @@ export function isRetryableModelFailure(error: string | undefined): boolean {
451
564
  return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));
452
565
  }
453
566
 
567
+ function messageError(message: unknown): string | undefined {
568
+ if (!message || typeof message !== "object") return undefined;
569
+ const value = (message as { errorMessage?: unknown }).errorMessage;
570
+ return typeof value === "string" ? value : undefined;
571
+ }
572
+
573
+ export function isRetryableModelFailureAttempt(input: { error: string | undefined; messages?: readonly unknown[]; toolCount?: number; startupBlocked?: boolean }): boolean {
574
+ // A startup guard blocked the child before its first model turn: no model
575
+ // change can fix it, and recording it as a model failure would poison the
576
+ // model registry with a long-lived exclusion for a policy decision.
577
+ if (input.startupBlocked === true) return false;
578
+ if (!isRetryableModelFailure(input.error)) return false;
579
+ if ((input.toolCount ?? 0) > 0) return false;
580
+ if (input.error === "Subagent produced no output (possible model cold-start or empty response)." || /^Subagent produced no output after terminal assistant stopReason "[^"]+"\.$/.test(input.error ?? "")) return true;
581
+ if ((input.toolCount ?? 0) === 0 && (input.messages?.length ?? 0) === 0) return true;
582
+ const error = input.error?.trim();
583
+ return Boolean(error && input.messages?.some((message) => messageError(message)?.trim() === error));
584
+ }
585
+
454
586
  export function recordRetryableModelFailure(model: string | undefined, error: string | undefined): void {
455
587
  if (!model || !isRetryableModelFailure(error)) return;
456
588
  const { provider, modelId } = parseModelKey(model);
@@ -3,14 +3,19 @@ import { createHash } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
4
  import * as os from "node:os";
5
5
  import * as path from "node:path";
6
- import type { ArtifactPaths, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationFingerprint, TrackedMutationSnapshot } from "../../shared/types.ts";
6
+ import type { ArtifactPaths, TimeoutRecoveryProjection, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationFingerprint, TrackedMutationSnapshot } from "../../shared/types.ts";
7
7
 
8
8
  const MAX_TRACKED_PATHS = 500;
9
9
  const MAX_HASH_BYTES = 1024 * 1024;
10
10
  const MAX_TIMEOUT_FILES = 20;
11
11
 
12
+ function gitArguments(args: string[]): string[] {
13
+ // Mutation evidence must not block child startup on a stale fsmonitor daemon.
14
+ return ["-c", "core.fsmonitor=false", ...args];
15
+ }
16
+
12
17
  function gitOutput(cwd: string, args: string[], maxBuffer = MAX_HASH_BYTES): string {
13
- return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
18
+ return execFileSync("git", gitArguments(args), { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer, windowsHide: true });
14
19
  }
15
20
 
16
21
  function splitNul(output: string): string[] {
@@ -21,7 +26,7 @@ function hashLargeDiff(cwd: string, relativePath: string): string {
21
26
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-tracked-diff-"));
22
27
  const diffPath = path.join(tempDir, "diff.patch");
23
28
  try {
24
- execFileSync("git", ["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath], { cwd, stdio: "ignore" });
29
+ execFileSync("git", gitArguments(["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath]), { cwd, stdio: "ignore", windowsHide: true });
25
30
  const hash = createHash("sha256");
26
31
  const buffer = Buffer.allocUnsafe(64 * 1024);
27
32
  const fd = fs.openSync(diffPath, "r");
@@ -105,9 +110,48 @@ function formatPathList(paths: string[]): string {
105
110
  return paths.length > MAX_TIMEOUT_FILES ? `${shown}, ... (${paths.length - MAX_TIMEOUT_FILES} more)` : shown;
106
111
  }
107
112
 
113
+ /** Keep status and completion details to bounded routing evidence, not raw output or effects. */
114
+ export function projectTimeoutRecovery(value: unknown): TimeoutRecoveryProjection | undefined {
115
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
116
+ const source = value as Record<string, unknown>;
117
+ const termination = source.termination === "timed-out" || source.termination === "stopped" ? source.termination : undefined;
118
+ if (!termination || !Array.isArray(source.changedFiles)) return undefined;
119
+ const allChangedFiles = source.changedFiles.filter((file): file is string => typeof file === "string");
120
+ const changedFiles = allChangedFiles.slice(0, MAX_TIMEOUT_FILES);
121
+ const reportStatus = source.reportStatus === "missing"
122
+ || source.reportStatus === "written"
123
+ || source.reportStatus === "not-requested"
124
+ || source.reportStatus === "unknown"
125
+ ? source.reportStatus
126
+ : undefined;
127
+ return {
128
+ termination,
129
+ changedFiles,
130
+ ...(source.truncated === true || allChangedFiles.length > changedFiles.length ? { truncated: true } : {}),
131
+ ...(source.recoveryNeeded === true ? { recoveryNeeded: true } : {}),
132
+ ...(source.reason === "timed-out-with-dirty-worktree" ? { reason: source.reason } : {}),
133
+ ...(reportStatus ? { reportStatus } : {}),
134
+ };
135
+ }
136
+
137
+ /** Render only the bounded recovery route needed by a parent/operator. */
138
+ export function formatTimeoutRecoveryLines(value: unknown, indent = ""): string[] {
139
+ const recovery = projectTimeoutRecovery(value);
140
+ if (!recovery?.recoveryNeeded) return [];
141
+ const changedFiles = recovery.changedFiles.length > 0
142
+ ? `${recovery.changedFiles.join(", ")}${recovery.truncated ? ", …" : ""}`
143
+ : "none";
144
+ const changedFileCount = recovery.changedFiles.length > 0 ? `${recovery.changedFiles.length}${recovery.truncated ? "+" : ""}` : "0";
145
+ return [
146
+ `${indent}Recovery needed: review the diff and artifacts before resuming or launching dependent stages.`,
147
+ `${indent}Recovery evidence: requested report: ${recovery.reportStatus ?? "unknown"}; changed tracked files: ${changedFiles} (${changedFileCount}); classification: ${recovery.reason ?? recovery.termination}`,
148
+ ];
149
+ }
150
+
108
151
  export function buildTimeoutRecoverySummary(input: {
109
152
  termination: "timed-out" | "stopped";
110
153
  evidence: TrackedMutationEvidence;
154
+ requiredOutputMissing?: boolean;
111
155
  currentTool?: string;
112
156
  currentToolArgs?: string;
113
157
  currentPath?: string;
@@ -117,11 +161,19 @@ export function buildTimeoutRecoverySummary(input: {
117
161
  }): TimeoutRecoverySummary {
118
162
  const warning = "Inspect partial changes before retrying or resuming the child.";
119
163
  const changedFiles = input.evidence.changedFiles.slice(0, MAX_TIMEOUT_FILES);
164
+ let reportStatus: "missing" | "written" | "not-requested" = "not-requested";
165
+ if (input.requiredOutputMissing === true) reportStatus = "missing";
166
+ else if (input.requiredOutputMissing === false) reportStatus = "written";
167
+ const recoveryNeeded = input.termination === "timed-out"
168
+ && reportStatus === "missing"
169
+ && input.evidence.changedFiles.length > 0;
120
170
  const lines = [
121
171
  "Recovery summary:",
122
172
  `- termination: ${input.termination}`,
123
173
  `- changed tracked files: ${input.evidence.unavailable ? `unavailable (${input.evidence.unavailable})` : formatPathList(input.evidence.changedFiles)}`,
124
174
  ];
175
+ if (input.requiredOutputMissing !== undefined) lines.push(`- requested report: ${reportStatus}`);
176
+ if (recoveryNeeded) lines.push("- Recovery needed: review the diff and artifacts before resuming or launching dependent stages.");
125
177
  if (input.currentTool) lines.push(`- active tool: ${input.currentTool}${input.currentToolArgs ? ` — ${input.currentToolArgs}` : ""}`);
126
178
  if (input.currentPath) lines.push(`- active path: ${input.currentPath}`);
127
179
  if (input.sessionFile) lines.push(`- session file: ${input.sessionFile}`);
@@ -133,6 +185,8 @@ export function buildTimeoutRecoverySummary(input: {
133
185
  termination: input.termination,
134
186
  changedFiles,
135
187
  truncated: input.evidence.changedFiles.length > changedFiles.length || input.evidence.truncated || undefined,
188
+ ...(recoveryNeeded ? { recoveryNeeded: true, reason: "timed-out-with-dirty-worktree" as const } : {}),
189
+ reportStatus,
136
190
  currentTool: input.currentTool,
137
191
  currentToolArgs: input.currentToolArgs,
138
192
  currentPath: input.currentPath,