@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  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 +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,6 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
3
4
  import { TEMP_ROOT_DIR } from "../../shared/types.ts";
5
+ import { getAgentDir } from "../../shared/utils.ts";
4
6
 
5
7
  export const EXCLUSIONS_PATH_ENV = "PI_MODEL_EXCLUSIONS_PATH";
6
8
 
@@ -19,14 +21,67 @@ type RecordModelFailureOptions = ModelExclusionTarget & {
19
21
 
20
22
  let exclusions: ModelExclusion[] = [];
21
23
  let loaded = false;
22
- 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;
23
31
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
24
32
  let persistSeq = 0;
25
33
 
26
- /** Override the default exclusion TTL. */
27
- export function setDefaultTTL(ms: number): void {
28
- 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
+ }
29
82
  defaultTTLMs = ms;
83
+ loadedTTLCeilingMs = options?.shortenExisting ? ms : undefined;
84
+ if (loaded && loadedTTLCeilingMs !== undefined && shortenExclusionsToTTL(exclusions, loadedTTLCeilingMs, Date.now())) schedulePersist();
30
85
  }
31
86
 
32
87
  /**
@@ -77,10 +132,24 @@ function ensureLoaded(): void {
77
132
  const raw = fs.readFileSync(getExclusionsFilePath(), "utf-8");
78
133
  const data = JSON.parse(raw);
79
134
  if (data.version === 1) {
135
+ if (!Array.isArray(data.exclusions)) throw new Error("Model exclusion store version 1 must contain an exclusions array.");
80
136
  const now = Date.now();
81
- 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);
82
148
  exclusions = deduplicate(exclusions);
149
+ if (droppedInvalid) flushPersist();
150
+ else if (shortened) schedulePersist();
83
151
  }
152
+ invalidateAuthExclusions();
84
153
  } catch (error) {
85
154
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
86
155
  console.error(`[model-exclusions] Failed to load exclusions from ${getExclusionsFilePath()}:`, error);
@@ -88,6 +157,32 @@ function ensureLoaded(): void {
88
157
  }
89
158
  }
90
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
+
91
186
  function dedupKey(entry: ModelExclusion): string {
92
187
  return `${entry.provider ?? ""}|${entry.modelId ?? ""}`;
93
188
  }
@@ -134,6 +229,7 @@ export function recordModelFailure(options: RecordModelFailureOptions): void {
134
229
  */
135
230
  export function clearExpiredExclusions(): void {
136
231
  ensureLoaded();
232
+ invalidateAuthExclusions();
137
233
  prune(exclusions, Date.now());
138
234
  schedulePersist();
139
235
  }
@@ -159,7 +255,7 @@ export function clearExclusions(): void {
159
255
  */
160
256
  function entryMatches(entry: ModelExclusion, candidateModelId: string, candidateProvider: string | undefined, now: number): boolean {
161
257
  if (entry.expiresAt <= now) return false;
162
- if (entry.modelId) {
258
+ if (entry.modelId !== undefined) {
163
259
  if (entry.modelId !== candidateModelId) return false;
164
260
  return !entry.provider || !candidateProvider || entry.provider === candidateProvider;
165
261
  }
@@ -171,9 +267,23 @@ function entryMatches(entry: ModelExclusion, candidateModelId: string, candidate
171
267
  */
172
268
  export function isExcluded(modelId: string, provider: string): boolean {
173
269
  ensureLoaded();
270
+ invalidateAuthExclusions();
174
271
  return exclusions.some((entry) => entryMatches(entry, modelId, provider, Date.now()));
175
272
  }
176
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
+
177
287
  /**
178
288
  * Number of live (non-expired) exclusions.
179
289
  */
@@ -194,7 +304,7 @@ export function getExcludedCount(): number {
194
304
  * {@link recordModelFailure} is later recognised by the candidate filter.
195
305
  */
196
306
  export function parseModelKey(fullId: string): { provider?: string; modelId: string } {
197
- const base = fullId.includes(":") ? fullId.substring(0, fullId.lastIndexOf(":")) : fullId;
307
+ const base = splitKnownThinkingSuffix(fullId).baseModel;
198
308
  if (!base.includes("/")) return { modelId: base };
199
309
  const slash = base.indexOf("/");
200
310
  return { provider: base.slice(0, slash), modelId: base.slice(slash + 1) };
@@ -204,16 +314,23 @@ export function parseModelKey(fullId: string): { provider?: string; modelId: str
204
314
  * Filter a list of candidate fullIds, removing excluded models/providers and
205
315
  * duplicates while preserving order.
206
316
  */
207
- 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[] {
208
321
  ensureLoaded();
322
+ invalidateAuthExclusions();
209
323
  const timestamp = opts?.now ?? Date.now();
210
324
  const seen = new Set<string>();
211
325
  const filtered: string[] = [];
212
326
  for (const raw of candidates) {
213
327
  if (!raw || seen.has(raw)) continue;
214
328
  const { provider: candidateProvider, modelId: candidateModelId } = parseModelKey(raw);
215
- const excluded = exclusions.some((entry) => entryMatches(entry, candidateModelId, candidateProvider, timestamp));
216
- 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
+ }
217
334
  seen.add(raw);
218
335
  filtered.push(raw);
219
336
  }
@@ -240,3 +357,17 @@ function prune(items: ModelExclusion[], now: number): void {
240
357
  }
241
358
  items.length = write;
242
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
- import type { ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
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";
4
- import { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
3
+ import { filterFallbackCandidates, findModelExclusion, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
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
 
@@ -14,12 +15,22 @@ interface ModelAttemptSummary {
14
15
  }
15
16
 
16
17
  export function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {
17
- const colonIdx = model.lastIndexOf(":");
18
- if (colonIdx === -1) return { baseModel: model, thinkingSuffix: "" };
19
- return {
20
- baseModel: model.substring(0, colonIdx),
21
- thinkingSuffix: model.substring(colonIdx),
22
- };
18
+ return splitKnownThinkingSuffix(model);
19
+ }
20
+
21
+ export function formatSubagentModelVerificationError(expectedModel: string, observedModel: string, availableModels: AvailableModelInfo[] | undefined): string | undefined {
22
+ if (!availableModels || availableModels.length === 0) return undefined;
23
+ const expectedBase = splitThinkingSuffix(expectedModel).baseModel;
24
+ const observedBase = splitThinkingSuffix(observedModel).baseModel;
25
+ if (expectedBase === observedBase) return undefined;
26
+ const expectedEntry = availableModels.find((entry) => entry.fullId === expectedBase);
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
+ }
33
+ return `model_verification_failed: child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'.`;
23
34
  }
24
35
 
25
36
  /** Sentinel model value requesting that a subagent inherit the parent session's model. */
@@ -236,7 +247,7 @@ function resolveRequiredSubagentModelCandidate(
236
247
 
237
248
  export interface ResolveSubagentModelOverrideOptions {
238
249
  /** When set with `enforce: true`, out-of-scope models are rejected. */
239
- scope?: ModelScopeConfig;
250
+ scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
240
251
  /** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `"inherited"`. */
241
252
  source?: ModelSource;
242
253
  /** Called for warn-severity violations instead of `console.warn`. */
@@ -247,6 +258,65 @@ function defaultScopeWarn(violation: ModelScopeViolation): void {
247
258
  console.warn(`[pi-subagents] ${violation.message}`);
248
259
  }
249
260
 
261
+ function configuredScopes(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined): ModelScopeCheckRule[] {
262
+ return scope ? (Array.isArray(scope) ? scope : [scope]) : [];
263
+ }
264
+
265
+ function throwForUnresolvedEnforcedInheritScope(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined, includeMixed = false): void {
266
+ const unresolvedInheritScope = configuredScopes(scope)
267
+ .find((entry) => entry.enforce === true && (includeMixed ? entry.allow?.includes(INHERIT_MODEL) : entry.allow?.length === 1 && entry.allow[0] === INHERIT_MODEL));
268
+ if (!unresolvedInheritScope) return;
269
+ const origin = unresolvedInheritScope.origin ?? "modelScope";
270
+ throw new Error(`Cannot enforce subagent model scope (${origin}): 'inherit' requires a current parent session model.`);
271
+ }
272
+
273
+ function enforceModelScopes(
274
+ model: string,
275
+ scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined,
276
+ source: ModelSource,
277
+ onWarn: ((violation: ModelScopeViolation) => void) | undefined,
278
+ ): void {
279
+ const violations = configuredScopes(scope)
280
+ .map((entry) => checkModelScope(model, entry, source))
281
+ .filter((violation): violation is ModelScopeViolation => violation !== undefined);
282
+ const error = violations.find((violation) => violation.severity === "error");
283
+ if (error) throw new Error(error.message);
284
+ for (const violation of violations) (onWarn ?? defaultScopeWarn)(violation);
285
+ }
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
+
250
320
  /**
251
321
  * Resolve the `--model` override passed to a spawned subagent.
252
322
  *
@@ -274,19 +344,27 @@ export function resolveSubagentModelOverride(
274
344
  ): string | undefined {
275
345
  const trimmed = typeof requestedModel === "string" ? requestedModel.trim() : "";
276
346
  const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;
347
+ if (!parentModel) throwForUnresolvedEnforcedInheritScope(options?.scope, explicit === undefined || options?.source === "inherited");
277
348
  let resolved: string | undefined;
349
+ let resolvedFromRegistry = explicit === undefined;
278
350
  if (explicit === undefined) {
279
351
  resolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;
280
352
  } else {
281
- 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
+ }
282
364
  }
283
- if (resolved && options?.scope?.enforce) {
365
+ if (resolved && options?.scope && resolvedFromRegistry) {
284
366
  const source: ModelSource = explicit === undefined ? "inherited" : (options.source ?? "inherited");
285
- const violation = checkModelScope(resolved, options.scope, source);
286
- if (violation) {
287
- if (violation.severity === "error") throw new Error(violation.message);
288
- (options.onWarn ?? defaultScopeWarn)(violation);
289
- }
367
+ enforceModelScopes(resolved, options.scope, source, options.onWarn);
290
368
  }
291
369
  return resolved;
292
370
  }
@@ -297,14 +375,15 @@ export function resolveEffectiveSubagentModel(
297
375
  parentModel: ParentModel | undefined,
298
376
  availableModels: AvailableModelInfo[] | undefined,
299
377
  preferredProvider?: string,
300
- options?: Omit<ResolveSubagentModelOverrideOptions, "source">,
378
+ options?: ResolveSubagentModelOverrideOptions,
301
379
  ): string | undefined {
380
+ const source = options?.source ?? (explicitModel !== undefined ? "explicit" : "inherited");
302
381
  const resolved = resolveSubagentModelOverride(
303
382
  explicitModel ?? agentModel,
304
383
  parentModel,
305
384
  availableModels,
306
385
  preferredProvider,
307
- { ...options, source: explicitModel !== undefined ? "explicit" : "inherited" },
386
+ { ...options, source },
308
387
  );
309
388
  if (resolved || explicitModel === undefined) return resolved;
310
389
  return resolveSubagentModelOverride(
@@ -312,16 +391,37 @@ export function resolveEffectiveSubagentModel(
312
391
  parentModel,
313
392
  availableModels,
314
393
  preferredProvider,
315
- { ...options, source: "inherited" },
394
+ { ...options, source: options?.source ?? "inherited" },
316
395
  );
317
396
  }
318
397
 
398
+ export type ModelOrigin = ModelSource | "configured";
399
+
319
400
  export interface BuildModelCandidatesOptions {
320
401
  /** Fallback models warn by default and throw when strict scope enforcement is enabled. */
321
- scope?: ModelScopeConfig;
402
+ scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
322
403
  onWarn?: (violation: ModelScopeViolation) => void;
323
404
  /** The primary model came from the running parent session, not configuration. */
324
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";
325
425
  }
326
426
 
327
427
  export function inheritsParentModel(
@@ -341,34 +441,70 @@ export function buildModelCandidates(
341
441
  preferredProvider?: string,
342
442
  options?: BuildModelCandidatesOptions,
343
443
  ): string[] {
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
+ }
344
463
  const seen = new Set<string>();
345
464
  const candidates: string[] = [];
346
465
  const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];
466
+ let skippedPrimary: string | undefined;
467
+ let skippedFallback: string | undefined;
347
468
  for (let index = 0; index < rawCandidates.length; index++) {
348
469
  const raw = rawCandidates[index];
349
470
  if (!raw) continue;
350
471
  const model = raw.trim();
351
- const normalized = index === 0
352
- ? options?.primaryModelFromParent
353
- ? model
354
- : resolveRequiredSubagentModelCandidate(model, availableModels, preferredProvider)
472
+ const normalized = index === 0 && (origin === "inherited" || origin === "explicit" || options?.primaryModelFromParent)
473
+ ? model
355
474
  : resolveSubagentModelCandidate(model, availableModels, preferredProvider);
356
475
  if (!normalized) {
357
- 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
+ }
358
481
  continue;
359
482
  }
360
483
  if (seen.has(normalized)) continue;
361
- if ((index > 0 || options?.scope?.strict === true) && options?.scope?.enforce) {
362
- const violation = checkModelScope(normalized, options.scope, "inherited");
363
- if (violation) {
364
- if (violation.severity === "error") throw new Error(violation.message);
365
- (options.onWarn ?? defaultScopeWarn)(violation);
366
- }
484
+ if (index > 0 || scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
485
+ enforceModelScopes(normalized, scopes, "inherited", options?.onWarn);
367
486
  }
368
487
  seen.add(normalized);
369
488
  candidates.push(normalized);
370
489
  }
371
- 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;
372
508
  }
373
509
 
374
510
  const RETRYABLE_MODEL_FAILURE_PATTERNS = [
@@ -393,6 +529,7 @@ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
393
529
  /overloaded/i,
394
530
  /service unavailable/i,
395
531
  /temporar(?:ily)? unavailable/i,
532
+ /connection\s+(?:error|reset|closed|aborted)/i,
396
533
  /connection refused/i,
397
534
  /fetch failed/i,
398
535
  /network error/i,
@@ -401,9 +538,11 @@ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
401
538
  /upstream/i,
402
539
  /timed? out/i,
403
540
  /timeout/i,
541
+ /\b500\b/,
404
542
  /\b502\b/,
405
543
  /\b503\b/,
406
544
  /\b504\b/,
545
+ /internal server error/i,
407
546
  /cold.?start/i,
408
547
  /empty response/i,
409
548
  /no output/i,
@@ -425,6 +564,21 @@ export function isRetryableModelFailure(error: string | undefined): boolean {
425
564
  return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));
426
565
  }
427
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 }): boolean {
574
+ if (!isRetryableModelFailure(input.error)) return false;
575
+ if ((input.toolCount ?? 0) > 0) return false;
576
+ 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;
577
+ if ((input.toolCount ?? 0) === 0 && (input.messages?.length ?? 0) === 0) return true;
578
+ const error = input.error?.trim();
579
+ return Boolean(error && input.messages?.some((message) => messageError(message)?.trim() === error));
580
+ }
581
+
428
582
  export function recordRetryableModelFailure(model: string | undefined, error: string | undefined): void {
429
583
  if (!model || !isRetryableModelFailure(error)) return;
430
584
  const { provider, modelId } = parseModelKey(model);