@xzzpig/pi-subagents 0.7.0 → 0.8.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 (86) hide show
  1. package/CHANGELOG.md +13 -4
  2. package/README.md +1 -1
  3. package/agents/reviewer.md +12 -2
  4. package/docs/agents.md +4 -4
  5. package/docs/configuration.md +6 -6
  6. package/docs/extension-api.md +14 -4
  7. package/docs/models.md +47 -6
  8. package/docs/observability.md +14 -3
  9. package/docs/tool-reference.md +21 -6
  10. package/docs/workflows.md +7 -1
  11. package/index.ts +10 -1
  12. package/package.json +3 -3
  13. package/prompts/council.md +19 -7
  14. package/prompts/parallel-review.md +5 -1
  15. package/prompts/review-loop.md +9 -5
  16. package/skills/council-mode/SKILL.md +50 -26
  17. package/skills/pi-subagents/SKILL.md +5 -1
  18. package/skills/pi-subagents/references/constraints-and-recipes.md +16 -1
  19. package/skills/pi-subagents/references/execution-controls.md +13 -4
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -3
  21. package/skills/pi-subagents/references/prompting-and-roles.md +14 -7
  22. package/src/agents/agent-management.ts +115 -14
  23. package/src/agents/agent-serializer.ts +4 -2
  24. package/src/agents/agents.ts +226 -48
  25. package/src/api/external-job-provider.ts +10 -1
  26. package/src/api/preflight.ts +52 -19
  27. package/src/api/project-panes.ts +2 -0
  28. package/src/extension/doctor.ts +10 -0
  29. package/src/extension/fanout-child.ts +3 -2
  30. package/src/extension/index.ts +24 -4
  31. package/src/extension/public-execution.ts +12 -9
  32. package/src/extension/rpc.ts +77 -3
  33. package/src/extension/schemas.ts +7 -1
  34. package/src/extension/tool-description.ts +9 -6
  35. package/src/extension/tool-result.ts +19 -0
  36. package/src/inspectors/herdr/client.ts +3 -3
  37. package/src/inspectors/herdr/focus.ts +55 -0
  38. package/src/inspectors/herdr/project-panes.ts +228 -44
  39. package/src/integrations/herdr-status.ts +26 -4
  40. package/src/runs/background/async-execution.ts +146 -17
  41. package/src/runs/background/async-job-tracker.ts +33 -14
  42. package/src/runs/background/async-resume.ts +23 -2
  43. package/src/runs/background/async-retention.ts +1 -1
  44. package/src/runs/background/async-status.ts +10 -0
  45. package/src/runs/background/chain-root-attachment.ts +5 -0
  46. package/src/runs/background/control-channel.ts +98 -10
  47. package/src/runs/background/notify.ts +62 -1
  48. package/src/runs/background/result-watcher.ts +4 -3
  49. package/src/runs/background/run-status.ts +15 -1
  50. package/src/runs/background/stale-run-reconciler.ts +3 -0
  51. package/src/runs/background/subagent-runner.ts +333 -48
  52. package/src/runs/background/wait-completions.ts +2 -0
  53. package/src/runs/background/wait-tool.ts +4 -3
  54. package/src/runs/foreground/async-stop-action.ts +23 -2
  55. package/src/runs/foreground/execution.ts +148 -13
  56. package/src/runs/foreground/foreground-history.ts +3 -2
  57. package/src/runs/foreground/subagent-executor.ts +417 -50
  58. package/src/runs/foreground/workflow-detach-reconcile.ts +18 -6
  59. package/src/runs/shared/acceptance.ts +11 -5
  60. package/src/runs/shared/agent-contract.ts +1 -1
  61. package/src/runs/shared/child-identity.ts +36 -0
  62. package/src/runs/shared/completion-guard.ts +52 -2
  63. package/src/runs/shared/dynamic-fanout.ts +1 -1
  64. package/src/runs/shared/extension-bindings.ts +78 -0
  65. package/src/runs/shared/external-cli-runner.ts +2 -0
  66. package/src/runs/shared/external-job-bridge.ts +53 -37
  67. package/src/runs/shared/external-job-runner.ts +126 -23
  68. package/src/runs/shared/fast-mode-extension.ts +10 -0
  69. package/src/runs/shared/model-exclusions.ts +2 -1
  70. package/src/runs/shared/model-fallback.ts +48 -22
  71. package/src/runs/shared/model-scope.ts +106 -39
  72. package/src/runs/shared/mutation-evidence.ts +145 -0
  73. package/src/runs/shared/orca-progress-tabs.ts +71 -9
  74. package/src/runs/shared/parallel-utils.ts +15 -0
  75. package/src/runs/shared/pi-args.ts +78 -1
  76. package/src/runs/shared/structured-output.ts +18 -4
  77. package/src/runs/shared/subagent-prompt-runtime.ts +48 -15
  78. package/src/runs/shared/tool-availability.ts +1 -3
  79. package/src/shared/launch-contract.ts +12 -5
  80. package/src/shared/settings.ts +6 -1
  81. package/src/shared/thinking-ceiling.ts +52 -0
  82. package/src/shared/types.ts +120 -5
  83. package/src/tui/fleet-status.ts +66 -13
  84. package/src/tui/render.ts +5 -4
  85. package/src/watchdog/permission-arbiter.ts +59 -52
  86. package/src/workflows/scripted-workflow.ts +156 -12
@@ -20,6 +20,31 @@ export function externalJobPromptDigest(prompt: string): string {
20
20
  return createHash("sha256").update(prompt).digest("hex");
21
21
  }
22
22
 
23
+ export function externalJobStableJson(value: unknown): string {
24
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
25
+ if (Array.isArray(value)) return `[${value.map(externalJobStableJson).join(",")}]`;
26
+ const record = value as Record<string, unknown>;
27
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${externalJobStableJson(record[key])}`).join(",")}}`;
28
+ }
29
+
30
+ export function externalJobFollowUpRequestDigest(input: { provider: string; parentProviderJobId: string; promptDigest: string; options: Record<string, unknown> }): string {
31
+ return createHash("sha256")
32
+ .update(externalJobStableJson({ provider: input.provider, parentProviderJobId: input.parentProviderJobId, promptDigest: input.promptDigest, options: input.options }))
33
+ .digest("hex");
34
+ }
35
+
36
+ export function externalJobFollowUpRequestId(requestDigest: string): string {
37
+ return `follow-up-${requestDigest.slice(0, 48)}`;
38
+ }
39
+
40
+ export function externalJobFollowUpRunId(requestDigest: string): string {
41
+ const hex = requestDigest.padEnd(32, "0").slice(0, 32).split("");
42
+ hex[12] = "4";
43
+ hex[16] = ((Number.parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16);
44
+ const value = hex.join("");
45
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20, 32)}`;
46
+ }
47
+
23
48
  function sleep(ms: number): Promise<void> {
24
49
  return new Promise((resolve) => setTimeout(resolve, ms));
25
50
  }
@@ -70,11 +95,29 @@ function parseExternalJobStatus(value: unknown, statusPath: string): ExternalJob
70
95
  if (failureCode !== undefined && typeof failureCode !== "string") throw malformedStatus(statusPath);
71
96
  if (failureMessage !== undefined && typeof failureMessage !== "string") throw malformedStatus(statusPath);
72
97
  if (blockingJobId !== undefined && typeof blockingJobId !== "string") throw malformedStatus(statusPath);
98
+ const operation = value.operation;
99
+ const sourceRunId = value.sourceRunId;
100
+ const sourceStepIndex = value.sourceStepIndex;
101
+ const parentProviderJobId = value.parentProviderJobId;
102
+ const requestId = value.requestId;
103
+ const requestDigest = value.requestDigest;
104
+ if (operation !== undefined && operation !== "start" && operation !== "follow-up") throw malformedStatus(statusPath);
105
+ if (sourceRunId !== undefined && (typeof sourceRunId !== "string" || sourceRunId.length === 0)) throw malformedStatus(statusPath);
106
+ if (sourceStepIndex !== undefined && (typeof sourceStepIndex !== "number" || !Number.isInteger(sourceStepIndex) || sourceStepIndex < 0)) throw malformedStatus(statusPath);
107
+ if (parentProviderJobId !== undefined && (typeof parentProviderJobId !== "string" || parentProviderJobId.length === 0)) throw malformedStatus(statusPath);
108
+ if (requestId !== undefined && (typeof requestId !== "string" || requestId.length === 0)) throw malformedStatus(statusPath);
109
+ if (requestDigest !== undefined && (typeof requestDigest !== "string" || requestDigest.length === 0)) throw malformedStatus(statusPath);
73
110
  if (startedAt !== undefined && typeof startedAt !== "number") throw malformedStatus(statusPath);
74
111
  if (updatedAt !== undefined && typeof updatedAt !== "number") throw malformedStatus(statusPath);
75
112
  return {
76
113
  provider,
77
114
  promptDigest,
115
+ ...(operation ? { operation } : {}),
116
+ ...(sourceRunId ? { sourceRunId } : {}),
117
+ ...(sourceStepIndex !== undefined ? { sourceStepIndex } : {}),
118
+ ...(parentProviderJobId ? { parentProviderJobId } : {}),
119
+ ...(requestId ? { requestId } : {}),
120
+ ...(requestDigest ? { requestDigest } : {}),
78
121
  options: value.options ?? {},
79
122
  state,
80
123
  ...(providerJobId ? { providerJobId } : {}),
@@ -111,10 +154,30 @@ function readExistingExternalJob(asyncDir: string, stepIndex: number): ExternalJ
111
154
  return parseExternalJobStatus(step.externalJob, statusPath);
112
155
  }
113
156
 
157
+ function externalJobLineage(followUp: ExternalJobFollowUpDescriptor | undefined, previous: ExternalJobStatus | undefined) {
158
+ return {
159
+ operation: followUp ? "follow-up" as const : previous?.operation,
160
+ ...(followUp ? {
161
+ sourceRunId: followUp.sourceRunId,
162
+ sourceStepIndex: followUp.sourceStepIndex,
163
+ parentProviderJobId: followUp.parentProviderJobId,
164
+ requestId: followUp.requestId,
165
+ requestDigest: followUp.requestDigest,
166
+ } : {
167
+ ...(previous?.sourceRunId ? { sourceRunId: previous.sourceRunId } : {}),
168
+ ...(previous?.sourceStepIndex !== undefined ? { sourceStepIndex: previous.sourceStepIndex } : {}),
169
+ ...(previous?.parentProviderJobId ? { parentProviderJobId: previous.parentProviderJobId } : {}),
170
+ ...(previous?.requestId ? { requestId: previous.requestId } : {}),
171
+ ...(previous?.requestDigest ? { requestDigest: previous.requestDigest } : {}),
172
+ }),
173
+ };
174
+ }
175
+
114
176
  function statusFromHandle(input: {
115
177
  provider: string;
116
178
  promptDigest: string;
117
179
  options: Record<string, unknown>;
180
+ followUp?: ExternalJobFollowUpDescriptor;
118
181
  startedAt?: number;
119
182
  previous?: ExternalJobStatus;
120
183
  handle: ExternalJobHandle;
@@ -124,6 +187,7 @@ function statusFromHandle(input: {
124
187
  provider: input.provider,
125
188
  providerJobId: input.handle.providerJobId,
126
189
  promptDigest: input.promptDigest,
190
+ ...externalJobLineage(input.followUp, input.previous),
127
191
  options: input.options,
128
192
  handleUrl: input.handle.handleUrl ?? input.previous?.handleUrl,
129
193
  conversationUrl: input.handle.conversationUrl ?? input.previous?.conversationUrl,
@@ -141,6 +205,7 @@ function failureStatus(input: {
141
205
  provider: string;
142
206
  promptDigest: string;
143
207
  options: Record<string, unknown>;
208
+ followUp?: ExternalJobFollowUpDescriptor;
144
209
  previous?: ExternalJobStatus;
145
210
  code: string;
146
211
  message: string;
@@ -150,6 +215,7 @@ function failureStatus(input: {
150
215
  provider: input.provider,
151
216
  providerJobId: input.previous?.providerJobId,
152
217
  promptDigest: input.promptDigest,
218
+ ...externalJobLineage(input.followUp, input.previous),
153
219
  options: input.options,
154
220
  handleUrl: input.previous?.handleUrl,
155
221
  conversationUrl: input.previous?.conversationUrl,
@@ -176,6 +242,24 @@ function blocksStartRedispatch(status: ExternalJobStatus, provider: string, prom
176
242
  && status.failureCode !== "provider-unavailable";
177
243
  }
178
244
 
245
+ interface ExternalJobFollowUpDescriptor {
246
+ sourceRunId: string;
247
+ sourceStepIndex: number;
248
+ parentProviderJobId: string;
249
+ requestId: string;
250
+ requestDigest: string;
251
+ }
252
+
253
+ function sameFollowUpLineage(status: ExternalJobStatus, followUp: ExternalJobFollowUpDescriptor | undefined): boolean {
254
+ if (!followUp) return status.operation !== "follow-up";
255
+ return status.operation === "follow-up"
256
+ && status.sourceRunId === followUp.sourceRunId
257
+ && status.sourceStepIndex === followUp.sourceStepIndex
258
+ && status.parentProviderJobId === followUp.parentProviderJobId
259
+ && status.requestId === followUp.requestId
260
+ && status.requestDigest === followUp.requestDigest;
261
+ }
262
+
179
263
  export async function runExternalJob(input: {
180
264
  provider: string;
181
265
  options?: Record<string, unknown>;
@@ -191,6 +275,7 @@ export async function runExternalJob(input: {
191
275
  timeoutMessage?: string;
192
276
  stopMessage?: string;
193
277
  onExternalJob?: (status: ExternalJobStatus) => void;
278
+ followUp?: ExternalJobFollowUpDescriptor;
194
279
  }): Promise<ExternalJobRunResult> {
195
280
  const provider = input.provider;
196
281
  const options = input.options ?? {};
@@ -218,37 +303,55 @@ export async function runExternalJob(input: {
218
303
  current = readExistingExternalJob(input.asyncDir, input.stepIndex);
219
304
  let handle: ExternalJobHandle;
220
305
  if (current?.providerJobId) {
221
- if (current.provider !== provider || current.promptDigest !== promptDigest) {
222
- const message = `Existing external job '${current.providerJobId}' does not match provider or prompt digest. Refusing to redispatch prompt.`;
223
- const status = failureStatus({ provider, promptDigest, options, previous: current, code: "recovery-mismatch", message });
306
+ if (current.provider !== provider || current.promptDigest !== promptDigest || !sameFollowUpLineage(current, input.followUp)) {
307
+ const message = `Existing external job '${current.providerJobId}' does not match provider, prompt digest, or follow-up lineage. Refusing to redispatch prompt.`;
308
+ const status = failureStatus({ provider, promptDigest, options, followUp: input.followUp, previous: current, code: "recovery-mismatch", message });
224
309
  publish(status);
225
310
  return { output: message, exitCode: 1, error: message, externalJob: status };
226
311
  }
227
312
  handle = await requestExternalJobOperation<ExternalJobHandle>(input.asyncDir, { operation: "reattach", provider, providerJobId: current.providerJobId });
228
313
  } else {
229
314
  if (current && blocksStartRedispatch(current, provider, promptDigest)) {
230
- const message = `External-job start for provider '${provider}' previously ended without a durable provider job id. Refusing to redispatch the prompt automatically.`;
231
- const status = failureStatus({ provider, promptDigest, options, previous: current, code: "start-redispatch-blocked", message });
315
+ const message = `External-job ${input.followUp ? "follow-up" : "start"} for provider '${provider}' previously ended without a durable provider job id. Refusing to redispatch the prompt automatically.`;
316
+ const status = failureStatus({ provider, promptDigest, options, followUp: input.followUp, previous: current, code: input.followUp ? "dispatch-redispatch-blocked" : "start-redispatch-blocked", message });
232
317
  publish(status);
233
318
  return { output: message, exitCode: 1, error: message, externalJob: status };
234
319
  }
235
- publish({ provider, promptDigest, options, state: "queued", startedAt, updatedAt: Date.now() });
320
+ publish({ provider, promptDigest, ...(input.followUp ? { operation: "follow-up" as const, ...input.followUp } : {}), options, state: "queued", startedAt, updatedAt: Date.now() });
321
+ if (input.followUp) {
236
322
  handle = await requestExternalJobOperation<ExternalJobHandle>(input.asyncDir, {
237
- operation: "start",
238
- provider,
239
- start: {
240
- prompt: input.prompt,
241
- promptDigest,
242
- cwd: input.cwd,
243
- runId: input.runId,
244
- stepIndex: input.stepIndex,
245
- agent: input.agent,
246
- options,
247
- ...(input.sessionId ? { sessionId: input.sessionId } : {}),
248
- },
249
- }, undefined, localCancellation);
323
+ operation: "follow-up",
324
+ provider,
325
+ followUp: {
326
+ prompt: input.prompt,
327
+ promptDigest,
328
+ cwd: input.cwd,
329
+ runId: input.runId,
330
+ stepIndex: input.stepIndex,
331
+ agent: input.agent,
332
+ options,
333
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
334
+ ...input.followUp,
335
+ },
336
+ }, undefined, localCancellation);
337
+ } else {
338
+ handle = await requestExternalJobOperation<ExternalJobHandle>(input.asyncDir, {
339
+ operation: "start",
340
+ provider,
341
+ start: {
342
+ prompt: input.prompt,
343
+ promptDigest,
344
+ cwd: input.cwd,
345
+ runId: input.runId,
346
+ stepIndex: input.stepIndex,
347
+ agent: input.agent,
348
+ options,
349
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
350
+ },
351
+ }, undefined, localCancellation);
352
+ }
250
353
  }
251
- publish(statusFromHandle({ provider, promptDigest, options, startedAt, previous: current, handle }));
354
+ publish(statusFromHandle({ provider, promptDigest, options, followUp: input.followUp, startedAt, previous: current, handle }));
252
355
  while (!terminal(handle.state)) {
253
356
  if (timedOut || stopped) {
254
357
  const message = stopped
@@ -258,7 +361,7 @@ export async function runExternalJob(input: {
258
361
  }
259
362
  await sleep(STATUS_POLL_INTERVAL_MS);
260
363
  handle = await requestExternalJobOperation<ExternalJobHandle>(input.asyncDir, { operation: "status", provider, providerJobId: handle.providerJobId });
261
- publish(statusFromHandle({ provider, promptDigest, options, previous: current, handle }));
364
+ publish(statusFromHandle({ provider, promptDigest, options, followUp: input.followUp, previous: current, handle }));
262
365
  }
263
366
  const result = await requestExternalJobOperation<ExternalJobResult>(input.asyncDir, { operation: "result", provider, providerJobId: handle.providerJobId });
264
367
  let artifactPath = result.artifactPath;
@@ -266,7 +369,7 @@ export async function runExternalJob(input: {
266
369
  artifactPath = path.join(input.asyncDir, `external-job-${input.stepIndex}.result.md`);
267
370
  fs.writeFileSync(artifactPath, result.output, "utf-8");
268
371
  }
269
- const finalStatus = statusFromHandle({ provider, promptDigest, options, previous: current, handle: result, resultArtifactPath: artifactPath });
372
+ const finalStatus = statusFromHandle({ provider, promptDigest, options, followUp: input.followUp, previous: current, handle: result, resultArtifactPath: artifactPath });
270
373
  publish(finalStatus);
271
374
  const output = resultOutput(result, artifactPath);
272
375
  const error = result.state === "completed" ? undefined : result.failureMessage ?? `External job ${result.state}.`;
@@ -276,7 +379,7 @@ export async function runExternalJob(input: {
276
379
  ? error
277
380
  : new ExternalJobProviderError(error instanceof Error ? error.message : String(error), { code: "provider-error", cause: error });
278
381
  const message = formatError(providerError, provider);
279
- const status = failureStatus({ provider, promptDigest, options, previous: current, code: providerError.code, message, ...(providerError.blockingJobId ? { blockingJobId: providerError.blockingJobId } : {}) });
382
+ const status = failureStatus({ provider, promptDigest, options, followUp: input.followUp, previous: current, code: providerError.code, message, ...(providerError.blockingJobId ? { blockingJobId: providerError.blockingJobId } : {}) });
280
383
  publish(status);
281
384
  return { output: message, exitCode: 1, error: message, ...(timedOut ? { timedOut: true } : {}), ...(stopped ? { stopped: true } : {}), externalJob: status };
282
385
  } finally {
@@ -0,0 +1,10 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ function withPriorityServiceTier(payload: unknown): unknown {
4
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
5
+ return { ...payload, service_tier: "priority" };
6
+ }
7
+
8
+ export default function registerSubagentFastModeExtension(pi: ExtensionAPI): void {
9
+ pi.on("before_provider_request", (event) => ({ payload: withPriorityServiceTier(event.payload) }));
10
+ }
@@ -1,5 +1,6 @@
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";
4
5
 
5
6
  export const EXCLUSIONS_PATH_ENV = "PI_MODEL_EXCLUSIONS_PATH";
@@ -194,7 +195,7 @@ export function getExcludedCount(): number {
194
195
  * {@link recordModelFailure} is later recognised by the candidate filter.
195
196
  */
196
197
  export function parseModelKey(fullId: string): { provider?: string; modelId: string } {
197
- const base = fullId.includes(":") ? fullId.substring(0, fullId.lastIndexOf(":")) : fullId;
198
+ const base = splitKnownThinkingSuffix(fullId).baseModel;
198
199
  if (!base.includes("/")) return { modelId: base };
199
200
  const slash = base.indexOf("/");
200
201
  return { provider: base.slice(0, slash), modelId: base.slice(slash + 1) };
@@ -1,7 +1,7 @@
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
3
  import { filterFallbackCandidates, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
4
- import { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
4
+ import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
5
5
 
6
6
  export type { AvailableModelInfo };
7
7
 
@@ -14,12 +14,17 @@ interface ModelAttemptSummary {
14
14
  }
15
15
 
16
16
  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
- };
17
+ return splitKnownThinkingSuffix(model);
18
+ }
19
+
20
+ export function formatSubagentModelVerificationError(expectedModel: string, observedModel: string, availableModels: AvailableModelInfo[] | undefined): string | undefined {
21
+ if (!availableModels || availableModels.length === 0) return undefined;
22
+ const expectedBase = splitThinkingSuffix(expectedModel).baseModel;
23
+ const observedBase = splitThinkingSuffix(observedModel).baseModel;
24
+ if (expectedBase === observedBase) return undefined;
25
+ const expectedEntry = availableModels.find((entry) => entry.fullId === expectedBase);
26
+ if (expectedEntry && expectedEntry.id === observedBase) return undefined;
27
+ return `model_verification_failed: child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'.`;
23
28
  }
24
29
 
25
30
  /** Sentinel model value requesting that a subagent inherit the parent session's model. */
@@ -236,7 +241,7 @@ function resolveRequiredSubagentModelCandidate(
236
241
 
237
242
  export interface ResolveSubagentModelOverrideOptions {
238
243
  /** When set with `enforce: true`, out-of-scope models are rejected. */
239
- scope?: ModelScopeConfig;
244
+ scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
240
245
  /** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `"inherited"`. */
241
246
  source?: ModelSource;
242
247
  /** Called for warn-severity violations instead of `console.warn`. */
@@ -247,6 +252,32 @@ function defaultScopeWarn(violation: ModelScopeViolation): void {
247
252
  console.warn(`[pi-subagents] ${violation.message}`);
248
253
  }
249
254
 
255
+ function configuredScopes(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined): ModelScopeCheckRule[] {
256
+ return scope ? (Array.isArray(scope) ? scope : [scope]) : [];
257
+ }
258
+
259
+ function throwForUnresolvedEnforcedInheritScope(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined, includeMixed = false): void {
260
+ const unresolvedInheritScope = configuredScopes(scope)
261
+ .find((entry) => entry.enforce === true && (includeMixed ? entry.allow?.includes(INHERIT_MODEL) : entry.allow?.length === 1 && entry.allow[0] === INHERIT_MODEL));
262
+ if (!unresolvedInheritScope) return;
263
+ const origin = unresolvedInheritScope.origin ?? "modelScope";
264
+ throw new Error(`Cannot enforce subagent model scope (${origin}): 'inherit' requires a current parent session model.`);
265
+ }
266
+
267
+ function enforceModelScopes(
268
+ model: string,
269
+ scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined,
270
+ source: ModelSource,
271
+ onWarn: ((violation: ModelScopeViolation) => void) | undefined,
272
+ ): void {
273
+ const violations = configuredScopes(scope)
274
+ .map((entry) => checkModelScope(model, entry, source))
275
+ .filter((violation): violation is ModelScopeViolation => violation !== undefined);
276
+ const error = violations.find((violation) => violation.severity === "error");
277
+ if (error) throw new Error(error.message);
278
+ for (const violation of violations) (onWarn ?? defaultScopeWarn)(violation);
279
+ }
280
+
250
281
  /**
251
282
  * Resolve the `--model` override passed to a spawned subagent.
252
283
  *
@@ -274,19 +305,16 @@ export function resolveSubagentModelOverride(
274
305
  ): string | undefined {
275
306
  const trimmed = typeof requestedModel === "string" ? requestedModel.trim() : "";
276
307
  const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;
308
+ if (!parentModel) throwForUnresolvedEnforcedInheritScope(options?.scope, explicit === undefined || options?.source === "inherited");
277
309
  let resolved: string | undefined;
278
310
  if (explicit === undefined) {
279
311
  resolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;
280
312
  } else {
281
313
  resolved = resolveRequiredSubagentModelCandidate(explicit, availableModels, preferredProvider);
282
314
  }
283
- if (resolved && options?.scope?.enforce) {
315
+ if (resolved && options?.scope) {
284
316
  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
- }
317
+ enforceModelScopes(resolved, options.scope, source, options.onWarn);
290
318
  }
291
319
  return resolved;
292
320
  }
@@ -318,7 +346,7 @@ export function resolveEffectiveSubagentModel(
318
346
 
319
347
  export interface BuildModelCandidatesOptions {
320
348
  /** Fallback models warn by default and throw when strict scope enforcement is enabled. */
321
- scope?: ModelScopeConfig;
349
+ scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
322
350
  onWarn?: (violation: ModelScopeViolation) => void;
323
351
  /** The primary model came from the running parent session, not configuration. */
324
352
  primaryModelFromParent?: boolean;
@@ -341,6 +369,7 @@ export function buildModelCandidates(
341
369
  preferredProvider?: string,
342
370
  options?: BuildModelCandidatesOptions,
343
371
  ): string[] {
372
+ if (!primaryModel) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
344
373
  const seen = new Set<string>();
345
374
  const candidates: string[] = [];
346
375
  const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];
@@ -358,12 +387,9 @@ export function buildModelCandidates(
358
387
  continue;
359
388
  }
360
389
  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
- }
390
+ const scopes = configuredScopes(options?.scope);
391
+ if (index > 0 || scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
392
+ enforceModelScopes(normalized, scopes, "inherited", options?.onWarn);
367
393
  }
368
394
  seen.add(normalized);
369
395
  candidates.push(normalized);
@@ -15,7 +15,7 @@
15
15
 
16
16
  import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
17
17
 
18
- export interface ModelScopeConfig {
18
+ export interface ModelScopeRule {
19
19
  enforce?: boolean;
20
20
  /** Reject inherited and fallback models outside the allowlist instead of warning. */
21
21
  strict?: boolean;
@@ -23,6 +23,19 @@ export interface ModelScopeConfig {
23
23
  allow?: string[];
24
24
  }
25
25
 
26
+ export interface ModelScopeConfig extends ModelScopeRule {
27
+ /** Additional restrictions keyed by canonical agent name. */
28
+ agents?: Record<string, ModelScopeRule>;
29
+ }
30
+
31
+ export interface ModelScopeCheckRule extends ModelScopeRule {
32
+ origin?: string;
33
+ }
34
+
35
+ export interface ResolvedModelScope extends ModelScopeCheckRule {
36
+ origin: string;
37
+ }
38
+
26
39
  /** Where a resolved model originated, deciding enforcement severity. */
27
40
  export type ModelSource = "explicit" | "inherited";
28
41
 
@@ -32,6 +45,7 @@ export interface ModelScopeViolation {
32
45
  severity: "warn" | "error";
33
46
  message: string;
34
47
  allowedPatterns: string[];
48
+ origin: string;
35
49
  }
36
50
 
37
51
  function stripThinkingSuffix(model: string): string {
@@ -61,7 +75,7 @@ export function matchesScopePattern(model: string, pattern: string): boolean {
61
75
  */
62
76
  export function checkModelScope(
63
77
  model: string | undefined,
64
- scope: ModelScopeConfig | undefined,
78
+ scope: ModelScopeCheckRule | undefined,
65
79
  source: ModelSource,
66
80
  ): ModelScopeViolation | undefined {
67
81
  if (!model || !scope?.enforce) return undefined;
@@ -71,16 +85,89 @@ export function checkModelScope(
71
85
 
72
86
  const baseModel = stripThinkingSuffix(model);
73
87
  const severity: ModelScopeViolation["severity"] = source === "explicit" || scope.strict === true ? "error" : "warn";
88
+ const origin = scope.origin ?? "modelScope";
74
89
  return {
75
90
  model: baseModel,
76
91
  severity,
77
92
  allowedPatterns: allow,
93
+ origin,
78
94
  message:
79
- `Model '${baseModel}' is outside the configured subagent model scope. ` +
95
+ `Model '${baseModel}' is outside the configured subagent model scope (${origin}). ` +
80
96
  `Allowed patterns: ${allow.join(", ")}.`,
81
97
  };
82
98
  }
83
99
 
100
+ function expandInheritPattern(pattern: string, parentModel: { provider: string; id: string } | undefined): string {
101
+ return pattern === "inherit" && parentModel ? `${parentModel.provider}/${parentModel.id}` : pattern;
102
+ }
103
+
104
+ function assertRecord(value: unknown, field: string, meta: { filePath: string }, expected = "an object"): Record<string, unknown> {
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
106
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected ${expected}.`);
107
+ }
108
+ return value as Record<string, unknown>;
109
+ }
110
+
111
+ function parseAllowList(value: unknown, field: string, meta: { filePath: string }): string[] {
112
+ if (!Array.isArray(value)) {
113
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected an array of strings.`);
114
+ }
115
+ const allow: string[] = [];
116
+ for (const entry of value) {
117
+ if (typeof entry !== "string") {
118
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected an array of strings.`);
119
+ }
120
+ const trimmed = entry.trim();
121
+ if (trimmed) allow.push(trimmed);
122
+ }
123
+ if (allow.length === 0) {
124
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected a non-empty array of patterns.`);
125
+ }
126
+ return allow;
127
+ }
128
+
129
+ function parseScopeRule(input: Record<string, unknown>, field: string, meta: { filePath: string }): ModelScopeRule {
130
+ const rule: ModelScopeRule = {};
131
+ if ("enforce" in input) {
132
+ if (typeof input.enforce !== "boolean") throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}.enforce'; expected a boolean.`);
133
+ rule.enforce = input.enforce;
134
+ }
135
+ if ("strict" in input) {
136
+ if (typeof input.strict !== "boolean") throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}.strict'; expected a boolean.`);
137
+ rule.strict = input.strict;
138
+ }
139
+ if ("allow" in input) rule.allow = parseAllowList(input.allow, `${field}.allow`, meta);
140
+ return rule;
141
+ }
142
+
143
+ /** Resolve the global and matching agent policies into independent launch-time checks. */
144
+ export function resolveModelScopesForAgent(
145
+ config: ModelScopeConfig | undefined,
146
+ agentName: string,
147
+ parentModel: { provider: string; id: string } | undefined,
148
+ ): ResolvedModelScope[] {
149
+ if (!config) return [];
150
+ const scopes: ResolvedModelScope[] = [];
151
+ if (config.allow) {
152
+ scopes.push({
153
+ ...(config.enforce !== undefined ? { enforce: config.enforce } : {}),
154
+ ...(config.strict !== undefined ? { strict: config.strict } : {}),
155
+ allow: config.allow.map((pattern) => expandInheritPattern(pattern, parentModel)),
156
+ origin: "modelScope",
157
+ });
158
+ }
159
+ const agentScope = config.agents?.[agentName];
160
+ if (agentScope?.allow) {
161
+ scopes.push({
162
+ enforce: agentScope.enforce ?? config.enforce,
163
+ strict: agentScope.strict ?? config.strict,
164
+ allow: agentScope.allow.map((pattern) => expandInheritPattern(pattern, parentModel)),
165
+ origin: `modelScope.agents.${agentName}`,
166
+ });
167
+ }
168
+ return scopes;
169
+ }
170
+
84
171
  /**
85
172
  * Validate and normalize a raw `subagents.modelScope` value from settings.
86
173
  * Throws a descriptive error for malformed configs (matching the surrounding
@@ -91,46 +178,26 @@ export function parseModelScopeConfig(
91
178
  meta: { filePath: string },
92
179
  ): ModelScopeConfig | undefined {
93
180
  if (value === undefined) return undefined;
94
- if (!value || typeof value !== "object" || Array.isArray(value)) {
95
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope'; expected an object.`);
96
- }
97
-
98
- const input = value as Record<string, unknown>;
99
- const config: ModelScopeConfig = {};
100
-
101
- if ("enforce" in input) {
102
- if (typeof input.enforce !== "boolean") {
103
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.enforce'; expected a boolean.`);
104
- }
105
- config.enforce = input.enforce;
106
- }
107
-
108
- if ("strict" in input) {
109
- if (typeof input.strict !== "boolean") {
110
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.strict'; expected a boolean.`);
111
- }
112
- config.strict = input.strict;
113
- }
114
-
115
- if ("allow" in input) {
116
- if (!Array.isArray(input.allow)) {
117
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected an array of strings.`);
118
- }
119
- const allow: string[] = [];
120
- for (const entry of input.allow) {
121
- if (typeof entry !== "string") {
122
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected an array of strings.`);
181
+ const input = assertRecord(value, "modelScope", meta);
182
+ const config: ModelScopeConfig = parseScopeRule(input, "modelScope", meta);
183
+
184
+ if ("agents" in input) {
185
+ const agents: Record<string, ModelScopeRule> = {};
186
+ for (const [rawName, rawScope] of Object.entries(assertRecord(input.agents, "modelScope.agents", meta, "an object keyed by agent name"))) {
187
+ const name = rawName.trim();
188
+ const field = `modelScope.agents.${name}`;
189
+ if (!name) throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.agents' key; expected a non-empty agent name.`);
190
+ const agentInput = assertRecord(rawScope, field, meta);
191
+ if ("agents" in agentInput) {
192
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}.agents'; nested agent scopes are not supported.`);
123
193
  }
124
- const trimmed = entry.trim();
125
- if (trimmed) allow.push(trimmed);
126
- }
127
- if (allow.length === 0) {
128
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected a non-empty array of patterns.`);
194
+ agents[name] = parseScopeRule(agentInput, field, meta);
129
195
  }
130
- config.allow = allow;
196
+ config.agents = agents;
131
197
  }
132
198
 
133
- if (config.enforce === true && (!config.allow || config.allow.length === 0)) {
199
+ const hasAnyAllow = Boolean(config.allow?.length) || Object.values(config.agents ?? {}).some((scope) => Boolean(scope.allow?.length));
200
+ if (config.enforce === true && !hasAnyAllow) {
134
201
  throw new Error(`Subagent settings in '${meta.filePath}' set modelScope.enforce without a non-empty 'allow' list; supply allowed model patterns or disable enforcement.`);
135
202
  }
136
203