@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,336 @@
1
+ import type { ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
2
+ import type { Usage } from "../../shared/types.ts";
3
+ import { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
4
+
5
+ export type { AvailableModelInfo };
6
+
7
+ interface ModelAttemptSummary {
8
+ model: string;
9
+ success: boolean;
10
+ exitCode?: number | null;
11
+ error?: string;
12
+ usage?: Usage;
13
+ }
14
+
15
+ export function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {
16
+ const colonIdx = model.lastIndexOf(":");
17
+ if (colonIdx === -1) return { baseModel: model, thinkingSuffix: "" };
18
+ return {
19
+ baseModel: model.substring(0, colonIdx),
20
+ thinkingSuffix: model.substring(colonIdx),
21
+ };
22
+ }
23
+
24
+ /** Sentinel model value requesting that a subagent inherit the parent session's model. */
25
+ export const INHERIT_MODEL = "inherit";
26
+
27
+ /** Minimal shape of the parent session's in-memory model (`ctx.model`). */
28
+ export interface ParentModel {
29
+ provider: string;
30
+ id: string;
31
+ }
32
+
33
+ export function normalizeParentModel(model: unknown): ParentModel | undefined {
34
+ if (!model || typeof model !== "object") return undefined;
35
+ const candidate = model as { provider?: unknown; id?: unknown };
36
+ if (typeof candidate.provider !== "string" || typeof candidate.id !== "string") return undefined;
37
+ if (!candidate.provider || !candidate.id) return undefined;
38
+ return { provider: candidate.provider, id: candidate.id };
39
+ }
40
+
41
+ /**
42
+ * Normalize a model id or provider segment for fuzzy comparison: case-fold,
43
+ * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse
44
+ * repeated separators. Pure.
45
+ */
46
+ export function normalizeModelSegment(segment: string): string {
47
+ return segment
48
+ .toLowerCase()
49
+ .replace(/[._]+/g, "-")
50
+ .replace(/-+/g, "-")
51
+ .replace(/^-|-$/g, "");
52
+ }
53
+
54
+ function isPlausibleDateStamp(year: string, month: string, day: string): boolean {
55
+ const yyyy = Number(year);
56
+ const mm = Number(month);
57
+ const dd = Number(day);
58
+ return yyyy >= 1900 && yyyy <= 2099 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31;
59
+ }
60
+
61
+ /** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. Pure. */
62
+ function stripTrailingDateStamp(segment: string): string {
63
+ const dashed = /^(.*)-(\d{4})-(\d{2})-(\d{2})$/.exec(segment);
64
+ if (dashed && isPlausibleDateStamp(dashed[2]!, dashed[3]!, dashed[4]!)) return dashed[1]!;
65
+ const compact = /^(.*)-(\d{4})(\d{2})(\d{2})$/.exec(segment);
66
+ if (compact && isPlausibleDateStamp(compact[2]!, compact[3]!, compact[4]!)) return compact[1]!;
67
+ return segment;
68
+ }
69
+
70
+ function resolveBaseModelCandidate(
71
+ baseModel: string,
72
+ availableModels: AvailableModelInfo[],
73
+ preferredProvider?: string,
74
+ ): string | undefined {
75
+ if (baseModel.includes("/")) {
76
+ const exact = availableModels.find((entry) => entry.fullId === baseModel);
77
+ if (exact) return exact.fullId;
78
+ } else {
79
+ const exactMatches = availableModels.filter((entry) => entry.id === baseModel);
80
+ if (preferredProvider) {
81
+ const preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);
82
+ if (preferredMatch) return preferredMatch.fullId;
83
+ }
84
+ if (exactMatches.length === 1) return exactMatches[0]!.fullId;
85
+ }
86
+
87
+ return fuzzyResolveModel(baseModel, availableModels, preferredProvider);
88
+ }
89
+
90
+ /**
91
+ * Fuzzy-resolve a base model id (thinking suffix already stripped) against the
92
+ * registry, tolerating separator, case, and optional date-stamp differences so
93
+ * users do not have to spell provider/model exactly. A qualified `provider/id`
94
+ * query only matches within the named provider — this never silently switches
95
+ * providers for security/cost-sensitive configs. Returns the matched `fullId`,
96
+ * or `undefined` when there is no match or the match is ambiguous across
97
+ * providers (and no `preferredProvider` disambiguates). Pure.
98
+ */
99
+ export function fuzzyResolveModel(
100
+ baseModel: string,
101
+ availableModels: AvailableModelInfo[],
102
+ preferredProvider?: string,
103
+ ): string | undefined {
104
+ let queryProvider: string | undefined;
105
+ let queryIdRaw = baseModel;
106
+ const slashIdx = baseModel.indexOf("/");
107
+ if (slashIdx !== -1) {
108
+ queryProvider = normalizeModelSegment(baseModel.slice(0, slashIdx));
109
+ queryIdRaw = baseModel.slice(slashIdx + 1);
110
+ } else {
111
+ const providerSeparators = [":", "."];
112
+ for (const separator of providerSeparators) {
113
+ const separatorIdx = baseModel.indexOf(separator);
114
+ if (separatorIdx <= 0) continue;
115
+ const providerPart = normalizeModelSegment(baseModel.slice(0, separatorIdx));
116
+ if (!availableModels.some((entry) => normalizeModelSegment(entry.provider) === providerPart)) continue;
117
+ queryProvider = providerPart;
118
+ queryIdRaw = baseModel.slice(separatorIdx + 1);
119
+ break;
120
+ }
121
+ }
122
+ const queryId = normalizeModelSegment(queryIdRaw);
123
+ const queryIdNoDate = stripTrailingDateStamp(queryId);
124
+
125
+ const candidates = availableModels.filter((entry) => {
126
+ const entryId = normalizeModelSegment(entry.id);
127
+ if (entryId !== queryId && stripTrailingDateStamp(entryId) !== queryIdNoDate) return false;
128
+ if (queryProvider !== undefined && normalizeModelSegment(entry.provider) !== queryProvider) return false;
129
+ return true;
130
+ });
131
+ if (candidates.length === 0) return undefined;
132
+ if (preferredProvider) {
133
+ const preferredProviderNorm = normalizeModelSegment(preferredProvider);
134
+ const preferred = candidates.find((entry) => normalizeModelSegment(entry.provider) === preferredProviderNorm);
135
+ if (preferred) return preferred.fullId;
136
+ }
137
+ if (candidates.length === 1) return candidates[0]!.fullId;
138
+ return undefined;
139
+ }
140
+
141
+ /**
142
+ * Resolve a possibly-loose model id to a canonical `provider/id` (plus any
143
+ * thinking suffix). Exact registry matches win; fuzzy normalization
144
+ * (separator/case/date-stamp via {@link fuzzyResolveModel}) is a fallback so
145
+ * spelling differences still resolve. Never switches providers for a qualified
146
+ * query. Pure.
147
+ */
148
+ export function resolveModelCandidate(
149
+ model: string | undefined,
150
+ availableModels: AvailableModelInfo[] | undefined,
151
+ preferredProvider?: string,
152
+ ): string | undefined {
153
+ if (!model) return undefined;
154
+ if (!availableModels || availableModels.length === 0) return model;
155
+
156
+ const resolvedWhole = resolveBaseModelCandidate(model, availableModels, preferredProvider);
157
+ if (resolvedWhole) return resolvedWhole;
158
+
159
+ const { baseModel, thinkingSuffix } = splitThinkingSuffix(model);
160
+ if (!thinkingSuffix) return model;
161
+ const resolvedBase = resolveBaseModelCandidate(baseModel, availableModels, preferredProvider);
162
+ if (resolvedBase) return `${resolvedBase}${thinkingSuffix}`;
163
+ return model;
164
+ }
165
+
166
+ export interface ResolveSubagentModelOverrideOptions {
167
+ /** When set with `enforce: true`, out-of-scope models are rejected. */
168
+ scope?: ModelScopeConfig;
169
+ /** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `"inherited"`. */
170
+ source?: ModelSource;
171
+ /** Called for warn-severity violations instead of `console.warn`. */
172
+ onWarn?: (violation: ModelScopeViolation) => void;
173
+ }
174
+
175
+ function defaultScopeWarn(violation: ModelScopeViolation): void {
176
+ console.warn(`[pi-subagents] ${violation.message}`);
177
+ }
178
+
179
+ /**
180
+ * Resolve the `--model` override passed to a spawned subagent.
181
+ *
182
+ * When no model is requested (`undefined`, `false`, empty, or the `"inherit"`
183
+ * sentinel), the child must inherit the parent session's *in-memory* model
184
+ * (`provider/id`) instead of being left to resolve its own model. Without an
185
+ * explicit `provider/id`, the child falls back to the global
186
+ * `~/.pi/agent/settings.json` default, which is shared across every open PI
187
+ * session — so a different session that last changed its model in the TUI would
188
+ * silently contaminate this session's subagents (see issue #266). Passing an
189
+ * explicit `provider/id` keeps each session's children isolated to that
190
+ * session's model.
191
+ *
192
+ * An explicitly requested model string is resolved via {@link resolveModelCandidate}.
193
+ * When `options.scope.enforce` is on, an out-of-scope resolved model throws for
194
+ * an explicit (`source: "explicit"`) request and warns for an inherited one.
195
+ */
196
+ export function resolveSubagentModelOverride(
197
+ requestedModel: string | boolean | undefined,
198
+ parentModel: ParentModel | undefined,
199
+ availableModels: AvailableModelInfo[] | undefined,
200
+ preferredProvider?: string,
201
+ options?: ResolveSubagentModelOverrideOptions,
202
+ ): string | undefined {
203
+ const trimmed = typeof requestedModel === "string" ? requestedModel.trim() : "";
204
+ const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;
205
+ let resolved: string | undefined;
206
+ if (explicit === undefined) {
207
+ resolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;
208
+ } else {
209
+ resolved = resolveModelCandidate(explicit, availableModels, preferredProvider);
210
+ }
211
+ if (resolved && options?.scope?.enforce) {
212
+ const source: ModelSource = explicit === undefined ? "inherited" : (options.source ?? "inherited");
213
+ const violation = checkModelScope(resolved, options.scope, source);
214
+ if (violation) {
215
+ if (violation.severity === "error") throw new Error(violation.message);
216
+ (options.onWarn ?? defaultScopeWarn)(violation);
217
+ }
218
+ }
219
+ return resolved;
220
+ }
221
+
222
+ export function resolveEffectiveSubagentModel(
223
+ explicitModel: string | boolean | undefined,
224
+ agentModel: string | boolean | undefined,
225
+ parentModel: ParentModel | undefined,
226
+ availableModels: AvailableModelInfo[] | undefined,
227
+ preferredProvider?: string,
228
+ options?: Omit<ResolveSubagentModelOverrideOptions, "source">,
229
+ ): string | undefined {
230
+ const resolved = resolveSubagentModelOverride(
231
+ explicitModel ?? agentModel,
232
+ parentModel,
233
+ availableModels,
234
+ preferredProvider,
235
+ { ...options, source: explicitModel !== undefined ? "explicit" : "inherited" },
236
+ );
237
+ if (resolved || explicitModel === undefined) return resolved;
238
+ return resolveSubagentModelOverride(
239
+ agentModel,
240
+ parentModel,
241
+ availableModels,
242
+ preferredProvider,
243
+ { ...options, source: "inherited" },
244
+ );
245
+ }
246
+
247
+ export interface BuildModelCandidatesOptions {
248
+ /** Fallback models are inherited agent config and warn, rather than error, when out of scope. */
249
+ scope?: ModelScopeConfig;
250
+ onWarn?: (violation: ModelScopeViolation) => void;
251
+ }
252
+
253
+ export function buildModelCandidates(
254
+ primaryModel: string | undefined,
255
+ fallbackModels: string[] | undefined,
256
+ availableModels: AvailableModelInfo[] | undefined,
257
+ preferredProvider?: string,
258
+ options?: BuildModelCandidatesOptions,
259
+ ): string[] {
260
+ const seen = new Set<string>();
261
+ const candidates: string[] = [];
262
+ const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];
263
+ for (let index = 0; index < rawCandidates.length; index++) {
264
+ const raw = rawCandidates[index];
265
+ if (!raw) continue;
266
+ const normalized = resolveModelCandidate(raw.trim(), availableModels, preferredProvider);
267
+ if (!normalized || seen.has(normalized)) continue;
268
+ if (index > 0 && options?.scope?.enforce) {
269
+ const violation = checkModelScope(normalized, options.scope, "inherited");
270
+ if (violation) (options.onWarn ?? defaultScopeWarn)(violation);
271
+ }
272
+ seen.add(normalized);
273
+ candidates.push(normalized);
274
+ }
275
+ return candidates;
276
+ }
277
+
278
+ const RETRYABLE_MODEL_FAILURE_PATTERNS = [
279
+ /rate\s*limit/i,
280
+ /too many requests/i,
281
+ /\b429\b/,
282
+ /quota/i,
283
+ /billing/i,
284
+ /credit/i,
285
+ /auth(?:entication)?/i,
286
+ /unauthori[sz]ed/i,
287
+ /forbidden/i,
288
+ /api key/i,
289
+ /token expired/i,
290
+ /invalid key/i,
291
+ /provider.*unavailable/i,
292
+ /model.*unavailable/i,
293
+ /model.*disabled/i,
294
+ /model.*not found/i,
295
+ /unknown model/i,
296
+ /overloaded/i,
297
+ /service unavailable/i,
298
+ /temporar(?:ily)? unavailable/i,
299
+ /connection refused/i,
300
+ /fetch failed/i,
301
+ /network error/i,
302
+ /socket hang up/i,
303
+ /stream ended without finish_reason/i,
304
+ /upstream/i,
305
+ /timed? out/i,
306
+ /timeout/i,
307
+ /\b502\b/,
308
+ /\b503\b/,
309
+ /\b504\b/,
310
+ /cold.?start/i,
311
+ /empty response/i,
312
+ /no output/i,
313
+ /model.*(?:load|fail|error)/i,
314
+ ];
315
+
316
+ /**
317
+ * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with
318
+ * exit code N` come from a tool call inside the child's task, not from the
319
+ * provider/model, however network-flavored their details read. Retrying a
320
+ * different model cannot fix them and would rerun the whole task. Tool names
321
+ * include namespaced forms like `mcp.server/write`.
322
+ */
323
+ const TOOL_FAILURE_PREFIX = /^[\w.:@/-]+ failed (?:(?:\(exit \d+\):)|(?:with exit code \d+))(?:\s|$)/i;
324
+
325
+ export function isRetryableModelFailure(error: string | undefined): boolean {
326
+ if (!error) return false;
327
+ if (TOOL_FAILURE_PREFIX.test(error.trim())) return false;
328
+ return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));
329
+ }
330
+
331
+ export function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {
332
+ const failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;
333
+ return nextModel
334
+ ? `[fallback] ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`
335
+ : `[fallback] ${attempt.model} failed: ${failure}.`;
336
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Optional model-scope enforcement for subagent model resolution.
3
+ *
4
+ * When `subagents.modelScope.enforce` is enabled in settings, a resolved model
5
+ * that does not match any `allow` pattern is rejected. The severity depends on
6
+ * where the model came from: an explicit caller-supplied model (`--model`,
7
+ * tool-call `model`, or a TUI clarify pick) is a hard error, while a model
8
+ * inherited from agent frontmatter / `defaultModel` / the parent session only
9
+ * emits a warning so existing configurations keep working.
10
+ *
11
+ * The decision logic ({@link checkModelScope}) is a pure function of its
12
+ * inputs so it can be unit-tested without touching the filesystem or config.
13
+ */
14
+
15
+ import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
16
+
17
+ export interface ModelScopeConfig {
18
+ enforce?: boolean;
19
+ /** Glob-style allow patterns (only `*` is special), matched against `provider/id`. */
20
+ allow?: string[];
21
+ }
22
+
23
+ /** Where a resolved model originated, deciding enforcement severity. */
24
+ export type ModelSource = "explicit" | "inherited";
25
+
26
+ export interface ModelScopeViolation {
27
+ /** Resolved model id (without thinking suffix) that fell outside the scope. */
28
+ model: string;
29
+ severity: "warn" | "error";
30
+ message: string;
31
+ allowedPatterns: string[];
32
+ }
33
+
34
+ function stripThinkingSuffix(model: string): string {
35
+ return splitKnownThinkingSuffix(model).baseModel;
36
+ }
37
+
38
+ /** Escape RegExp specials except `*`, then turn `*` into `.*`. */
39
+ function globToRegExp(pattern: string): RegExp {
40
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
41
+ return new RegExp(`^${escaped}$`, "i");
42
+ }
43
+
44
+ /**
45
+ * Test whether a resolved model matches a single allow pattern. Both sides are
46
+ * compared case-insensitively against the full `provider/id` (thinking suffix
47
+ * stripped from the model).
48
+ */
49
+ export function matchesScopePattern(model: string, pattern: string): boolean {
50
+ return globToRegExp(pattern).test(stripThinkingSuffix(model));
51
+ }
52
+
53
+ /**
54
+ * Pure scope decision. Returns a {@link ModelScopeViolation} when the model is
55
+ * out of scope and enforcement is on, otherwise `undefined`. Enforcement with
56
+ * no `allow` list is a no-op (the settings parser rejects that combination, but
57
+ * this stays defensive for callers that build configs programmatically).
58
+ */
59
+ export function checkModelScope(
60
+ model: string | undefined,
61
+ scope: ModelScopeConfig | undefined,
62
+ source: ModelSource,
63
+ ): ModelScopeViolation | undefined {
64
+ if (!model || !scope?.enforce) return undefined;
65
+ const allow = scope.allow;
66
+ if (!allow || allow.length === 0) return undefined;
67
+ if (allow.some((pattern) => matchesScopePattern(model, pattern))) return undefined;
68
+
69
+ const baseModel = stripThinkingSuffix(model);
70
+ const severity: ModelScopeViolation["severity"] = source === "explicit" ? "error" : "warn";
71
+ return {
72
+ model: baseModel,
73
+ severity,
74
+ allowedPatterns: allow,
75
+ message:
76
+ `Model '${baseModel}' is outside the configured subagent model scope. ` +
77
+ `Allowed patterns: ${allow.join(", ")}.`,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Validate and normalize a raw `subagents.modelScope` value from settings.
83
+ * Throws a descriptive error for malformed configs (matching the surrounding
84
+ * settings-parsing style). Returns `undefined` when the field is absent.
85
+ */
86
+ export function parseModelScopeConfig(
87
+ value: unknown,
88
+ meta: { filePath: string },
89
+ ): ModelScopeConfig | undefined {
90
+ if (value === undefined) return undefined;
91
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
92
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope'; expected an object.`);
93
+ }
94
+
95
+ const input = value as Record<string, unknown>;
96
+ const config: ModelScopeConfig = {};
97
+
98
+ if ("enforce" in input) {
99
+ if (typeof input.enforce !== "boolean") {
100
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.enforce'; expected a boolean.`);
101
+ }
102
+ config.enforce = input.enforce;
103
+ }
104
+
105
+ if ("allow" in input) {
106
+ if (!Array.isArray(input.allow)) {
107
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected an array of strings.`);
108
+ }
109
+ const allow: string[] = [];
110
+ for (const entry of input.allow) {
111
+ if (typeof entry !== "string") {
112
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected an array of strings.`);
113
+ }
114
+ const trimmed = entry.trim();
115
+ if (trimmed) allow.push(trimmed);
116
+ }
117
+ if (allow.length === 0) {
118
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected a non-empty array of patterns.`);
119
+ }
120
+ config.allow = allow;
121
+ }
122
+
123
+ if (config.enforce === true && (!config.allow || config.allow.length === 0)) {
124
+ throw new Error(`Subagent settings in '${meta.filePath}' set modelScope.enforce without a non-empty 'allow' list; supply allowed model patterns or disable enforcement.`);
125
+ }
126
+
127
+ return Object.keys(config).length > 0 ? config : undefined;
128
+ }