@xzzpig/pi-subagents 0.6.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 (98) hide show
  1. package/CHANGELOG.md +45 -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/node_modules/@xzzpig/pi-components/CHANGELOG.md +102 -0
  13. package/node_modules/@xzzpig/pi-components/LICENSE +21 -0
  14. package/node_modules/@xzzpig/pi-components/README.md +59 -0
  15. package/node_modules/@xzzpig/pi-components/dist/index.d.ts +1 -0
  16. package/node_modules/@xzzpig/pi-components/dist/index.js +1 -0
  17. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +345 -0
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +1169 -0
  19. package/node_modules/@xzzpig/pi-components/package.json +49 -0
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +1785 -0
  21. package/package.json +7 -3
  22. package/prompts/council.md +19 -7
  23. package/prompts/parallel-review.md +5 -1
  24. package/prompts/review-loop.md +9 -5
  25. package/skills/council-mode/SKILL.md +50 -26
  26. package/skills/pi-subagents/SKILL.md +5 -1
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +16 -1
  28. package/skills/pi-subagents/references/execution-controls.md +13 -4
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -3
  30. package/skills/pi-subagents/references/prompting-and-roles.md +14 -7
  31. package/src/agents/agent-management.ts +115 -14
  32. package/src/agents/agent-serializer.ts +4 -2
  33. package/src/agents/agents.ts +226 -48
  34. package/src/api/external-job-provider.ts +10 -1
  35. package/src/api/preflight.ts +52 -19
  36. package/src/api/project-panes.ts +2 -0
  37. package/src/extension/doctor.ts +10 -0
  38. package/src/extension/fanout-child.ts +3 -2
  39. package/src/extension/index.ts +24 -4
  40. package/src/extension/public-execution.ts +12 -9
  41. package/src/extension/rpc.ts +77 -3
  42. package/src/extension/schemas.ts +7 -1
  43. package/src/extension/tool-description.ts +9 -6
  44. package/src/extension/tool-result.ts +19 -0
  45. package/src/inspectors/herdr/client.ts +3 -3
  46. package/src/inspectors/herdr/focus.ts +55 -0
  47. package/src/inspectors/herdr/project-panes.ts +228 -44
  48. package/src/integrations/herdr-status.ts +26 -4
  49. package/src/runs/background/async-execution.ts +146 -17
  50. package/src/runs/background/async-job-tracker.ts +33 -14
  51. package/src/runs/background/async-resume.ts +23 -2
  52. package/src/runs/background/async-retention.ts +1 -1
  53. package/src/runs/background/async-status.ts +10 -0
  54. package/src/runs/background/chain-root-attachment.ts +5 -0
  55. package/src/runs/background/control-channel.ts +98 -10
  56. package/src/runs/background/notify.ts +62 -1
  57. package/src/runs/background/result-watcher.ts +4 -3
  58. package/src/runs/background/run-status.ts +15 -1
  59. package/src/runs/background/stale-run-reconciler.ts +3 -0
  60. package/src/runs/background/subagent-runner.ts +333 -48
  61. package/src/runs/background/wait-completions.ts +2 -0
  62. package/src/runs/background/wait-tool.ts +4 -3
  63. package/src/runs/foreground/async-stop-action.ts +23 -2
  64. package/src/runs/foreground/execution.ts +148 -13
  65. package/src/runs/foreground/foreground-history.ts +3 -2
  66. package/src/runs/foreground/subagent-executor.ts +417 -50
  67. package/src/runs/foreground/workflow-detach-reconcile.ts +18 -6
  68. package/src/runs/shared/acceptance.ts +11 -5
  69. package/src/runs/shared/agent-contract.ts +1 -1
  70. package/src/runs/shared/child-identity.ts +36 -0
  71. package/src/runs/shared/completion-guard.ts +52 -2
  72. package/src/runs/shared/dynamic-fanout.ts +1 -1
  73. package/src/runs/shared/extension-bindings.ts +78 -0
  74. package/src/runs/shared/external-cli-runner.ts +2 -0
  75. package/src/runs/shared/external-job-bridge.ts +53 -37
  76. package/src/runs/shared/external-job-runner.ts +126 -23
  77. package/src/runs/shared/fast-mode-extension.ts +10 -0
  78. package/src/runs/shared/model-exclusions.ts +2 -1
  79. package/src/runs/shared/model-fallback.ts +48 -22
  80. package/src/runs/shared/model-scope.ts +106 -39
  81. package/src/runs/shared/mutation-evidence.ts +145 -0
  82. package/src/runs/shared/orca-progress-tabs.ts +71 -9
  83. package/src/runs/shared/parallel-utils.ts +15 -0
  84. package/src/runs/shared/pi-args.ts +78 -1
  85. package/src/runs/shared/structured-output.ts +18 -4
  86. package/src/runs/shared/subagent-prompt-runtime.ts +48 -15
  87. package/src/runs/shared/tool-availability.ts +1 -3
  88. package/src/shared/launch-contract.ts +12 -5
  89. package/src/shared/settings.ts +6 -1
  90. package/src/shared/thinking-ceiling.ts +52 -0
  91. package/src/shared/types.ts +121 -5
  92. package/src/tui/fleet-native-transcript.ts +374 -0
  93. package/src/tui/fleet-status.ts +66 -13
  94. package/src/tui/fleet-transcript.ts +47 -1
  95. package/src/tui/fleet.ts +96 -24
  96. package/src/tui/render.ts +5 -4
  97. package/src/watchdog/permission-arbiter.ts +59 -52
  98. package/src/workflows/scripted-workflow.ts +156 -12
@@ -0,0 +1,145 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import * as fs from "node:fs";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import type { ArtifactPaths, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationFingerprint, TrackedMutationSnapshot } from "../../shared/types.ts";
7
+
8
+ const MAX_TRACKED_PATHS = 500;
9
+ const MAX_HASH_BYTES = 1024 * 1024;
10
+ const MAX_TIMEOUT_FILES = 20;
11
+
12
+ function gitOutput(cwd: string, args: string[], maxBuffer = MAX_HASH_BYTES): string {
13
+ return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
14
+ }
15
+
16
+ function splitNul(output: string): string[] {
17
+ return output.split("\0").filter((part) => part.length > 0);
18
+ }
19
+
20
+ function hashLargeDiff(cwd: string, relativePath: string): string {
21
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-tracked-diff-"));
22
+ const diffPath = path.join(tempDir, "diff.patch");
23
+ try {
24
+ execFileSync("git", ["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath], { cwd, stdio: "ignore" });
25
+ const hash = createHash("sha256");
26
+ const buffer = Buffer.allocUnsafe(64 * 1024);
27
+ const fd = fs.openSync(diffPath, "r");
28
+ try {
29
+ for (;;) {
30
+ const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
31
+ if (bytesRead === 0) break;
32
+ hash.update(buffer.subarray(0, bytesRead));
33
+ }
34
+ } finally {
35
+ fs.closeSync(fd);
36
+ }
37
+ return hash.digest("hex");
38
+ } finally {
39
+ fs.rmSync(tempDir, { recursive: true, force: true });
40
+ }
41
+ }
42
+
43
+ function listChangedTrackedFiles(cwd: string): { paths: string[]; truncated: boolean } {
44
+ const paths = splitNul(gitOutput(cwd, ["diff", "--no-ext-diff", "--name-only", "-z", "HEAD", "--"], MAX_HASH_BYTES));
45
+ return { paths: paths.slice(0, MAX_TRACKED_PATHS), truncated: paths.length > MAX_TRACKED_PATHS };
46
+ }
47
+
48
+ function fingerprintPath(cwd: string, relativePath: string): TrackedMutationFingerprint {
49
+ try {
50
+ const diff = gitOutput(cwd, ["diff", "--no-ext-diff", "--binary", "HEAD", "--", relativePath], MAX_HASH_BYTES);
51
+ return { kind: "diff", digest: createHash("sha256").update(diff).digest("hex") };
52
+ } catch {
53
+ return { kind: "diff", digest: hashLargeDiff(cwd, relativePath) };
54
+ }
55
+ }
56
+
57
+ function sameFingerprint(left: TrackedMutationFingerprint | undefined, right: TrackedMutationFingerprint): boolean {
58
+ if (!left || left.kind !== "diff" || right.kind !== "diff") return false;
59
+ return left.digest === right.digest;
60
+ }
61
+
62
+ export function snapshotTrackedMutations(cwd: string): TrackedMutationSnapshot {
63
+ try {
64
+ const changed = listChangedTrackedFiles(cwd);
65
+ const fingerprints: Record<string, TrackedMutationFingerprint> = {};
66
+ for (const file of changed.paths) fingerprints[file] = fingerprintPath(cwd, file);
67
+ return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: changed.paths, fingerprints, truncated: changed.truncated };
68
+ } catch (error) {
69
+ return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: [], fingerprints: {}, unavailable: error instanceof Error ? error.message : String(error) };
70
+ }
71
+ }
72
+
73
+ export function collectTrackedMutationEvidence(snapshot: TrackedMutationSnapshot, cwd = snapshot.cwd): TrackedMutationEvidence {
74
+ if (snapshot.unavailable) {
75
+ return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: snapshot.unavailable };
76
+ }
77
+ try {
78
+ const current = listChangedTrackedFiles(cwd);
79
+ const startDirty = new Set(snapshot.dirtyFiles);
80
+ const candidates = new Set([...snapshot.dirtyFiles, ...current.paths]);
81
+ const changedFiles: string[] = [];
82
+ for (const file of candidates) {
83
+ if (!startDirty.has(file)) {
84
+ if (!snapshot.truncated) changedFiles.push(file);
85
+ continue;
86
+ }
87
+ if (!sameFingerprint(snapshot.fingerprints[file], fingerprintPath(cwd, file))) changedFiles.push(file);
88
+ }
89
+ changedFiles.sort();
90
+ return {
91
+ source: "tracked-files",
92
+ trackedOnly: true,
93
+ changedFiles,
94
+ attemptedMutation: changedFiles.length > 0,
95
+ truncated: snapshot.truncated || current.truncated || undefined,
96
+ };
97
+ } catch (error) {
98
+ return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: error instanceof Error ? error.message : String(error) };
99
+ }
100
+ }
101
+
102
+ function formatPathList(paths: string[]): string {
103
+ if (paths.length === 0) return "none";
104
+ const shown = paths.slice(0, MAX_TIMEOUT_FILES).join(", ");
105
+ return paths.length > MAX_TIMEOUT_FILES ? `${shown}, ... (${paths.length - MAX_TIMEOUT_FILES} more)` : shown;
106
+ }
107
+
108
+ export function buildTimeoutRecoverySummary(input: {
109
+ termination: "timed-out" | "stopped";
110
+ evidence: TrackedMutationEvidence;
111
+ currentTool?: string;
112
+ currentToolArgs?: string;
113
+ currentPath?: string;
114
+ sessionFile?: string;
115
+ transcriptPath?: string;
116
+ artifactPaths?: ArtifactPaths;
117
+ }): TimeoutRecoverySummary {
118
+ const warning = "Inspect partial changes before retrying or resuming the child.";
119
+ const changedFiles = input.evidence.changedFiles.slice(0, MAX_TIMEOUT_FILES);
120
+ const lines = [
121
+ "Recovery summary:",
122
+ `- termination: ${input.termination}`,
123
+ `- changed tracked files: ${input.evidence.unavailable ? `unavailable (${input.evidence.unavailable})` : formatPathList(input.evidence.changedFiles)}`,
124
+ ];
125
+ if (input.currentTool) lines.push(`- active tool: ${input.currentTool}${input.currentToolArgs ? ` — ${input.currentToolArgs}` : ""}`);
126
+ if (input.currentPath) lines.push(`- active path: ${input.currentPath}`);
127
+ if (input.sessionFile) lines.push(`- session file: ${input.sessionFile}`);
128
+ if (input.transcriptPath) lines.push(`- transcript: ${input.transcriptPath}`);
129
+ if (input.artifactPaths?.outputPath) lines.push(`- output artifact: ${input.artifactPaths.outputPath}`);
130
+ if (input.artifactPaths?.metadataPath) lines.push(`- metadata artifact: ${input.artifactPaths.metadataPath}`);
131
+ lines.push(`Warning: ${warning}`);
132
+ return {
133
+ termination: input.termination,
134
+ changedFiles,
135
+ truncated: input.evidence.changedFiles.length > changedFiles.length || input.evidence.truncated || undefined,
136
+ currentTool: input.currentTool,
137
+ currentToolArgs: input.currentToolArgs,
138
+ currentPath: input.currentPath,
139
+ sessionFile: input.sessionFile,
140
+ transcriptPath: input.transcriptPath,
141
+ artifactPaths: input.artifactPaths,
142
+ warning,
143
+ message: lines.join("\n"),
144
+ };
145
+ }
@@ -4,6 +4,7 @@ import * as path from "node:path";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import type { Message } from "@earendil-works/pi-ai";
6
6
  import { resolveNodeExecutable } from "../../shared/node-executable.ts";
7
+ import { getProjectSubagentsDir } from "../../shared/artifacts.ts";
7
8
  import { TEMP_ROOT_DIR, type OrcaProgressTabsConfig } from "../../shared/types.ts";
8
9
  import { extractTextFromContent, extractToolArgsPreview, getAgentDir } from "../../shared/utils.ts";
9
10
 
@@ -23,20 +24,22 @@ const ORCA_CREATE_WATCHDOG_SCRIPT = [
23
24
  "const {spawn}=require('node:child_process');",
24
25
  "const fs=require('node:fs');",
25
26
  "const timeout=Number(process.argv[1]),grace=Number(process.argv[2]),waitTimeout=Number(process.argv[3]);",
26
- "const previous=process.argv[4],done=process.argv[5],command=process.argv[6],args=process.argv.slice(7);",
27
+ "const previous=process.argv[4],done=process.argv[5],manifest=process.argv[6],command=process.argv[7],args=process.argv.slice(8);",
27
28
  "function mark(){try{fs.writeFileSync(done.replace(/\\.pending$/,'.ready'),'')}catch{}}",
28
29
  "function exists(file){try{return fs.existsSync(file)}catch{return false}}",
29
30
  "function keepQueued(){try{const now=new Date();fs.utimesSync(done,now,now)}catch{}}",
30
31
  "function predecessorReady(){if(previous==='-')return true;if(exists(previous.replace(/\\.pending$/,'.ready')))return true;try{return Date.now()-fs.statSync(previous).mtimeMs>=waitTimeout}catch{return true}}",
32
+ "function updateManifest(state,stdout=''){if(manifest==='-')return;try{const payload=JSON.parse(fs.readFileSync(manifest,'utf8'));payload.state=state;payload.updatedAt=new Date().toISOString();const raw=stdout.trim().split(/\\r?\\n/).filter(Boolean).at(-1);if(raw){try{payload.orca=JSON.parse(raw)}catch{payload.orcaRaw=raw.slice(0,4096)}}fs.writeFileSync(manifest,JSON.stringify(payload,null,2)+'\\n')}catch{}}",
31
33
  "function start(){",
32
34
  " try{",
33
- " const child=spawn(command,args,{stdio:'ignore',windowsHide:true});",
34
- " let hardKill;",
35
+ " const child=spawn(command,args,{stdio:['ignore','pipe','ignore'],windowsHide:true});",
36
+ " let hardKill,stdout='';",
37
+ " if(child.stdout)child.stdout.on('data',chunk=>{stdout+=String(chunk);if(stdout.length>65536)stdout=stdout.slice(-65536)});",
35
38
  " const timer=setTimeout(()=>{child.kill('SIGTERM');hardKill=setTimeout(()=>child.kill('SIGKILL'),grace)},timeout);",
36
39
  " const clear=()=>{clearTimeout(timer);if(hardKill)clearTimeout(hardKill);mark()};",
37
- " child.once('error',()=>{clear();process.exitCode=1});",
38
- " child.once('close',code=>{clear();process.exitCode=code===0?0:1});",
39
- " }catch{mark();process.exitCode=1}",
40
+ " child.once('error',()=>{updateManifest('failed');clear();process.exitCode=1});",
41
+ " child.once('close',code=>{updateManifest(code===0?'open':'failed',stdout);clear();process.exitCode=code===0?0:1});",
42
+ " }catch{updateManifest('failed');mark();process.exitCode=1}",
40
43
  "}",
41
44
  "if(predecessorReady())start();",
42
45
  "else{(function waitPrev(){keepQueued();if(predecessorReady())return start();setTimeout(waitPrev,20)})();}",
@@ -51,6 +54,7 @@ const ORCA_CLEANUP_WATCHDOG_SCRIPT = [
51
54
 
52
55
  export interface OrcaProgressTab {
53
56
  append(text: string): void;
57
+ section(input: { agent: string; index: number; count: number }): void;
54
58
  event(event: { type?: string; message?: Message; toolName?: string; args?: unknown }): void;
55
59
  finish(status: "completed" | "failed" | "stopped", sessionFile?: string): void;
56
60
  }
@@ -143,6 +147,41 @@ function safeSegment(value: unknown, fallback = "subagent"): string {
143
147
  return value.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || fallback;
144
148
  }
145
149
 
150
+ interface OrcaObserverManifest {
151
+ schemaVersion: 1;
152
+ kind: "orca-observer-view";
153
+ observer: "orca";
154
+ role: "run";
155
+ runId: string;
156
+ title: string;
157
+ worktree: string;
158
+ state: "opening" | "open" | "failed";
159
+ createdAt: string;
160
+ updatedAt?: string;
161
+ logPath: string;
162
+ orca?: unknown;
163
+ orcaRaw?: string;
164
+ }
165
+
166
+ function observerManifestPath(cwd: string, stem: string): string | undefined {
167
+ try {
168
+ const dir = path.join(getProjectSubagentsDir(resolveSequenceScope(cwd)), "views", "orca");
169
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
170
+ return path.join(dir, `${stem}.json`);
171
+ } catch {
172
+ return undefined;
173
+ }
174
+ }
175
+
176
+ function writeObserverManifest(manifestPath: string | undefined, manifest: OrcaObserverManifest): void {
177
+ if (!manifestPath) return;
178
+ try {
179
+ fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: "utf-8", mode: 0o600 });
180
+ } catch {
181
+ // The Orca observer stays display-only when project-local manifests cannot be written.
182
+ }
183
+ }
184
+
146
185
  function sleepSync(ms: number): void {
147
186
  const signal = new Int32Array(new SharedArrayBuffer(4));
148
187
  Atomics.wait(signal, 0, 0, ms);
@@ -280,6 +319,7 @@ export function createOrcaProgressTab(input: {
280
319
  runId: string;
281
320
  agent: string;
282
321
  index: number;
322
+ stepCount?: number;
283
323
  config?: OrcaProgressTabsConfig;
284
324
  env?: NodeJS.ProcessEnv;
285
325
  command?: string;
@@ -305,14 +345,28 @@ export function createOrcaProgressTab(input: {
305
345
  if (reservation === undefined) return undefined;
306
346
  const tabSequence = reservation.sequence;
307
347
  const stem = `${runId}-${index}-${randomUUID()}`;
348
+ const stepCount = typeof input.stepCount === "number" && Number.isInteger(input.stepCount) && input.stepCount > 0 ? input.stepCount : 1;
308
349
  const logPath = path.join(root, `${stem}.log`);
309
350
  const donePath = path.join(root, `${stem}.done`);
310
- const title = `subagent · ${agent} · ${tabSequence}`;
351
+ const title = `subagents · ${agent} · ${tabSequence}`;
311
352
  const markCreateReady = () => {
312
353
  try { fs.writeFileSync(reservation.createDone.replace(/\.pending$/, ".ready"), ""); } catch { /* unblock later tabs */ }
313
354
  };
355
+ const manifestPath = observerManifestPath(cwd, stem);
356
+ writeObserverManifest(manifestPath, {
357
+ schemaVersion: 1,
358
+ kind: "orca-observer-view",
359
+ observer: "orca",
360
+ role: "run",
361
+ runId,
362
+ title,
363
+ worktree: path.resolve(cwd),
364
+ state: "opening",
365
+ createdAt: new Date().toISOString(),
366
+ logPath,
367
+ });
314
368
  try {
315
- fs.writeFileSync(logPath, `pi-subagents / ${agent}\nrun ${runId} · child ${index + 1}\n${"─".repeat(48)}\n`, { encoding: "utf-8", mode: 0o600 });
369
+ fs.writeFileSync(logPath, `pi-subagents / ${agent}\nrun ${runId} · ${stepCount === 1 ? "1 child" : `${stepCount} children`}\n${"─".repeat(48)}\n`, { encoding: "utf-8", mode: 0o600 });
316
370
  fs.rmSync(donePath, { force: true });
317
371
  } catch {
318
372
  markCreateReady();
@@ -361,6 +415,7 @@ export function createOrcaProgressTab(input: {
361
415
  String(ORCA_CREATE_WAIT_TIMEOUT_MS),
362
416
  reservation.previousCreateDone ?? "-",
363
417
  reservation.createDone,
418
+ manifestPath ?? "-",
364
419
  command,
365
420
  "terminal", "create",
366
421
  "--worktree", `path:${path.resolve(cwd)}`,
@@ -398,6 +453,13 @@ export function createOrcaProgressTab(input: {
398
453
  if (finished) return;
399
454
  writeProgress(text);
400
455
  },
456
+ section(section) {
457
+ if (finished) return;
458
+ const label = safeSegment(section.agent, "subagent");
459
+ const count = Number.isInteger(section.count) && section.count > 0 ? section.count : 1;
460
+ const index = Number.isInteger(section.index) && section.index >= 0 ? section.index : 0;
461
+ writeProgress(`\n${"─".repeat(16)} child ${index + 1}/${count} · ${label} ${"─".repeat(16)}\n`);
462
+ },
401
463
  event(event) {
402
464
  if (!available || finished) return;
403
465
  if (event.type === "tool_execution_start" && event.toolName) {
@@ -421,7 +483,7 @@ export function createOrcaProgressTab(input: {
421
483
  try { verifiedSessionFile = fs.realpathSync(sessionFile); } catch { /* the session is no longer available */ }
422
484
  }
423
485
  const terminalMessage = verifiedSessionFile
424
- ? `completed. To remove the Pi session of this subagent, run rm -- ${shellQuote(verifiedSessionFile)}`
486
+ ? `completed. To remove the Pi session for this run, run rm -- ${shellQuote(verifiedSessionFile)}`
425
487
  : status;
426
488
  const truncation = truncated ? `\n[progress mirror truncated at ${MAX_MIRROR_BYTES} bytes]\n` : "";
427
489
  let footer = `${truncation}\n${"─".repeat(48)}\n${terminalMessage}\n`;
@@ -8,6 +8,13 @@ export interface RunnerSubagentStep {
8
8
  agent: string;
9
9
  task: string;
10
10
  runner?: ResolvedRunnerConfig;
11
+ externalJobFollowUp?: {
12
+ sourceRunId: string;
13
+ sourceStepIndex: number;
14
+ parentProviderJobId: string;
15
+ requestId: string;
16
+ requestDigest: string;
17
+ };
11
18
  /** Resolved launch context for this child. */
12
19
  context?: "fresh" | "fork";
13
20
  importAsyncRoot?: {
@@ -22,8 +29,13 @@ export interface RunnerSubagentStep {
22
29
  structured?: boolean;
23
30
  cwd?: string;
24
31
  model?: string;
32
+ fast?: boolean;
25
33
  thinking?: string;
34
+ thinkingCeiling?: import("../../shared/model-info.ts").ThinkingLevel;
26
35
  modelCandidates?: string[];
36
+ /** The primary model is inherited from the parent session and should not be verified against the child-reported active registry model. */
37
+ skipPrimaryModelVerification?: boolean;
38
+ modelVerificationRegistry?: Array<{ provider: string; id: string; fullId: string }>;
27
39
  tools?: string[];
28
40
  extensions?: string[];
29
41
  subagentOnlyExtensions?: string[];
@@ -48,12 +60,14 @@ export interface RunnerSubagentStep {
48
60
  schema: import("../../shared/types.ts").JsonSchemaObject;
49
61
  schemaPath: string;
50
62
  outputPath: string;
63
+ acceptanceReportPath?: string;
51
64
  };
52
65
  structuredOutputSchema?: import("../../shared/types.ts").JsonSchemaObject;
53
66
  agentContract?: import("../../shared/types.ts").AgentContract;
54
67
  definitionDigest?: string;
55
68
  launchBindingTask?: string;
56
69
  launchContractDigest?: string;
70
+ extensionBindings?: import("./extension-bindings.ts").ExtensionBindings;
57
71
  launchResolvedExtensions?: import("../../shared/types.ts").LaunchResolvedChildExtensionsV1;
58
72
  runtimeAcknowledgedExtensions?: import("../../shared/types.ts").RuntimeAcknowledgedChildExtensionsV1;
59
73
  effectiveAcceptance?: import("../../shared/types.ts").ResolvedAcceptanceConfig;
@@ -93,6 +107,7 @@ export interface DynamicRunnerGroup {
93
107
  gateOn?: import("../../shared/types.ts").ChainGateLayer;
94
108
  capabilityCeiling?: import("./capability-ceiling.ts").ResolvedSubagentCapabilityCeiling;
95
109
  capabilityAudit?: import("./capability-ceiling.ts").SubagentCapabilityAudit;
110
+ thinkingCeiling?: import("../../shared/model-info.ts").ThinkingLevel;
96
111
  }
97
112
 
98
113
  export type RunnerStep = RunnerSubagentStep | ParallelStepGroup | DynamicRunnerGroup;
@@ -13,8 +13,10 @@ import {
13
13
  type ResolvedMcpDirectToolSelection,
14
14
  } from "./mcp-direct-tool-allowlist.ts";
15
15
  import { resolvePiPackageRoot } from "./pi-spawn.ts";
16
+ import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
16
17
  import { RUNTIME_EXTENSION_ACK_PATH_ENV } from "./runtime-acknowledged-extensions.ts";
17
18
  import {
19
+ STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE_ENV,
18
20
  STRUCTURED_OUTPUT_CAPTURE_ENV,
19
21
  STRUCTURED_OUTPUT_SCHEMA_ENV,
20
22
  } from "./structured-output.ts";
@@ -26,6 +28,7 @@ import {
26
28
  type RunFanoutBudgetDescriptor,
27
29
  } from "../../shared/types.ts";
28
30
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
31
+ import { decodeThinkingCeiling, intersectThinkingCeilings, SUBAGENT_THINKING_CEILING_ENV } from "../../shared/thinking-ceiling.ts";
29
32
  import { encodeRunFanoutBudgetDescriptor, RUN_FANOUT_BUDGET_ENV } from "./run-fanout-budget.ts";
30
33
  import {
31
34
  TOOL_BUDGET_ENV,
@@ -103,6 +106,14 @@ const FANOUT_CHILD_EXTENSION_PATH = path.join(
103
106
  "extension",
104
107
  "fanout-child.ts",
105
108
  );
109
+ const FAST_MODE_EXTENSION_PATH = path.join(
110
+ path.dirname(fileURLToPath(import.meta.url)),
111
+ "fast-mode-extension.ts",
112
+ );
113
+ const FAST_MODE_ALLOWED_MODELS = new Set([
114
+ "openai-codex/gpt-5.6-luna",
115
+ "openai-codex/gpt-5.6-sol",
116
+ ]);
106
117
  export const SUBAGENT_CHILD_ENV = "PI_SUBAGENT_CHILD";
107
118
  export const SUBAGENT_ORCHESTRATOR_TARGET_ENV =
108
119
  "PI_SUBAGENT_ORCHESTRATOR_TARGET";
@@ -172,7 +183,10 @@ export interface BuildPiArgsInput {
172
183
  schema: JsonSchemaObject;
173
184
  schemaPath: string;
174
185
  outputPath: string;
186
+ acceptanceReportPath?: string;
175
187
  };
188
+ fast?: boolean;
189
+ modelCandidates?: readonly string[];
176
190
  toolBudget?: ResolvedToolBudget;
177
191
  allowZeroToolBudget?: boolean;
178
192
  permissionRules?: PermissionRules;
@@ -186,11 +200,14 @@ export interface BuildPiArgsInput {
186
200
  taskDelivery?: SubagentTaskDelivery;
187
201
  waitToolEnabled?: boolean;
188
202
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
203
+ thinkingCeiling?: import("../../shared/model-info.ts").ThinkingLevel;
204
+ extensionBindings?: ExtensionBindings;
189
205
  }
190
206
 
191
207
  export interface BuildPiArgsResult {
192
208
  args: string[];
193
209
  env: Record<string, string | undefined>;
210
+ warnings: string[];
194
211
  tempDir?: string;
195
212
  toolDiagnosticPath?: string;
196
213
  runtimeAcknowledgedExtensionsPath?: string;
@@ -234,6 +251,28 @@ export function applyThinkingSuffix(
234
251
  return `${model}:${thinking}`;
235
252
  }
236
253
 
254
+ function stripThinkingSuffix(model: string): string {
255
+ const colonIdx = model.lastIndexOf(":");
256
+ if (colonIdx === -1) return model;
257
+ return THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
258
+ ? model.slice(0, colonIdx)
259
+ : model;
260
+ }
261
+
262
+ function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fast" | "model" | "modelCandidates" | "agentName">): string[] {
263
+ if (!input.fast) return [];
264
+ const candidates = (input.modelCandidates?.length ? input.modelCandidates : input.model ? [input.model] : [])
265
+ .map(stripThinkingSuffix);
266
+ if (candidates.length === 0) {
267
+ throw new Error(`fast mode requires an explicit supported native OpenAI-Codex model${input.agentName ? ` for agent '${input.agentName}'` : ""}.`);
268
+ }
269
+ const unsupported = candidates.filter((model) => !FAST_MODE_ALLOWED_MODELS.has(model));
270
+ if (unsupported.length > 0) {
271
+ throw new Error(`fast mode supports only ${[...FAST_MODE_ALLOWED_MODELS].join(", ")}; unsupported model${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
272
+ }
273
+ return [FAST_MODE_EXTENSION_PATH];
274
+ }
275
+
237
276
  export interface ResolvePiLaunchToolPlanInput {
238
277
  tools?: string[];
239
278
  extensions?: string[];
@@ -248,9 +287,13 @@ export interface ResolvePiLaunchToolPlanInput {
248
287
  schemaPath: string;
249
288
  outputPath: string;
250
289
  };
290
+ fast?: boolean;
291
+ model?: string;
292
+ modelCandidates?: readonly string[];
251
293
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
252
294
  inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
253
295
  agentName?: string;
296
+ permissionRules?: PermissionRules;
254
297
  }
255
298
 
256
299
  export interface PiLaunchToolPlan {
@@ -271,6 +314,8 @@ export interface PiLaunchToolPlan {
271
314
  extensionArgs: string[];
272
315
  disableAmbientExtensions: boolean;
273
316
  capabilityAudit?: SubagentCapabilityAudit;
317
+ /** Non-fatal launch warnings; they do not change behavior. */
318
+ warnings: string[];
274
319
  }
275
320
 
276
321
  function extensionIdentifier(value: string): string {
@@ -288,6 +333,10 @@ function boundedExtensionIdentifiers(values: string[]): {
288
333
  };
289
334
  }
290
335
 
336
+ function hasPermissionRules(rules: PermissionRules | undefined): boolean {
337
+ return rules !== undefined && Object.keys(rules).length > 0;
338
+ }
339
+
291
340
  export function projectLaunchResolvedChildExtensions(
292
341
  toolPlan: Pick<
293
342
  PiLaunchToolPlan,
@@ -461,15 +510,30 @@ export function resolvePiLaunchToolPlan(
461
510
  : [];
462
511
  const permSystemExt = capabilityCeiling?.denyExtensions
463
512
  ? undefined
464
- : resolvePermissionSystemExtension();
513
+ : hasPermissionRules(input.permissionRules)
514
+ ? resolvePermissionSystemExtension()
515
+ : undefined;
516
+ if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
517
+ const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, modelCandidates: input.modelCandidates, agentName: input.agentName });
465
518
  const runtimeExtensions = [
466
519
  PROMPT_RUNTIME_EXTENSION_PATH,
520
+ ...fastModeExtensions,
467
521
  ...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
468
522
  ...(permSystemExt ? [permSystemExt] : []),
469
523
  ];
470
524
  const disableAmbientExtensions =
471
525
  capabilityCeiling?.denyExtensions === true ||
472
526
  input.extensions !== undefined;
527
+ const warnings: string[] = [];
528
+ // An explicit empty list disables ambient extensions, including model providers.
529
+ if (capabilityCeiling?.denyExtensions !== true && Array.isArray(input.extensions) && input.extensions.length === 0) {
530
+ const agentLabel = input.agentName ? ` for agent '${input.agentName}'` : "";
531
+ warnings.push(
532
+ `extensions: [] override${agentLabel} disables ALL ambient extensions for this child (not just "adds nothing"), `
533
+ + "including any model-provider extension needed to resolve a provider-qualified model. "
534
+ + "List the extensions this child actually needs instead of an empty array.",
535
+ );
536
+ }
473
537
  const configuredExtensions = capabilityCeiling?.denyExtensions
474
538
  ? []
475
539
  : [
@@ -550,6 +614,7 @@ export function resolvePiLaunchToolPlan(
550
614
  configuredExtensions,
551
615
  extensionArgs,
552
616
  disableAmbientExtensions,
617
+ warnings,
553
618
  ...(capabilityAudit ? { capabilityAudit } : {}),
554
619
  };
555
620
  }
@@ -592,11 +657,15 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
592
657
  cwd: input.cwd,
593
658
  requireReadTool: input.requireReadTool,
594
659
  structuredOutput: input.structuredOutput,
660
+ fast: input.fast,
661
+ model: modelArg,
662
+ modelCandidates: input.modelCandidates,
595
663
  capabilityCeiling: input.capabilityCeiling,
596
664
  inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(
597
665
  process.env[SUBAGENT_CAPABILITY_CEILING_ENV],
598
666
  ),
599
667
  agentName: input.childAgentName,
668
+ permissionRules: input.permissionRules,
600
669
  });
601
670
  if (toolPlan.explicitToolAllowlist) {
602
671
  args.push(
@@ -654,6 +723,7 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
654
723
  }
655
724
 
656
725
  const env: Record<string, string | undefined> = {};
726
+ env[PI_SUBAGENT_EXTENSION_BINDINGS_ENV] = encodeExtensionBindings(input.extensionBindings);
657
727
  const piPackageRoot =
658
728
  process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV] ?? resolvePiPackageRoot();
659
729
  if (piPackageRoot) env[PI_CODING_AGENT_PACKAGE_ROOT_ENV] = piPackageRoot;
@@ -812,6 +882,11 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
812
882
  const encodedCapabilityCeiling = encodeSubagentCapabilityCeiling(
813
883
  toolPlan.capabilityCeiling,
814
884
  );
885
+ const thinkingCeiling = intersectThinkingCeilings(
886
+ input.thinkingCeiling,
887
+ decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
888
+ );
889
+ if (thinkingCeiling) env[SUBAGENT_THINKING_CEILING_ENV] = thinkingCeiling;
815
890
  if (encodedCapabilityCeiling)
816
891
  env[SUBAGENT_CAPABILITY_CEILING_ENV] = encodedCapabilityCeiling;
817
892
  if (encodedPermissionRules)
@@ -819,6 +894,7 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
819
894
  if (input.structuredOutput) {
820
895
  env[STRUCTURED_OUTPUT_CAPTURE_ENV] = input.structuredOutput.outputPath;
821
896
  env[STRUCTURED_OUTPUT_SCHEMA_ENV] = input.structuredOutput.schemaPath;
897
+ if (input.structuredOutput.acceptanceReportPath) env[STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE_ENV] = input.structuredOutput.acceptanceReportPath;
822
898
  }
823
899
  if (input.steerInboxDir) {
824
900
  env[SUBAGENT_STEER_INBOX_ENV] = input.steerInboxDir;
@@ -839,6 +915,7 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
839
915
  return {
840
916
  args,
841
917
  env,
918
+ warnings: toolPlan.warnings,
842
919
  tempDir,
843
920
  toolDiagnosticPath,
844
921
  runtimeAcknowledgedExtensionsPath,
@@ -8,12 +8,14 @@ import type { JsonSchemaObject } from "../../shared/types.ts";
8
8
 
9
9
  export const STRUCTURED_OUTPUT_SCHEMA_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA";
10
10
  export const STRUCTURED_OUTPUT_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";
11
+ export const STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE";
11
12
  export const MISSING_STRUCTURED_OUTPUT_CALL_ERROR = "Missing structured_output call; this step has outputSchema and must finish by calling structured_output.";
12
13
 
13
14
  export interface StructuredOutputRuntime {
14
15
  schema: JsonSchemaObject;
15
16
  schemaPath: string;
16
17
  outputPath: string;
18
+ acceptanceReportPath?: string;
17
19
  }
18
20
 
19
21
  const SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"] as const;
@@ -59,10 +61,13 @@ function rewriteLocalJsonPointerRefs(schema: unknown, pointerPrefix: string, inh
59
61
  return rewritten;
60
62
  }
61
63
 
62
- export function createStructuredOutputToolParameters(schema: JsonSchemaObject): JsonSchemaObject {
64
+ export function createStructuredOutputToolParameters(schema: JsonSchemaObject, options: { acceptanceReport?: boolean } = {}): JsonSchemaObject {
63
65
  return {
64
66
  type: "object",
65
- properties: { value: rewriteLocalJsonPointerRefs(schema, "#/properties/value") },
67
+ properties: {
68
+ value: rewriteLocalJsonPointerRefs(schema, "#/properties/value"),
69
+ ...(options.acceptanceReport ? { acceptanceReport: { type: "object" } } : {}),
70
+ },
66
71
  required: ["value"],
67
72
  additionalProperties: false,
68
73
  };
@@ -124,7 +129,7 @@ export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"):
124
129
  }
125
130
  }
126
131
 
127
- export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string): StructuredOutputRuntime {
132
+ export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string, options: { captureAcceptanceReport?: boolean } = {}): StructuredOutputRuntime {
128
133
  assertJsonSchemaObject(schema);
129
134
  const rootDir = baseDir ?? os.tmpdir();
130
135
  fs.mkdirSync(rootDir, { recursive: true });
@@ -132,7 +137,7 @@ export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?
132
137
  const schemaPath = path.join(dir, "schema.json");
133
138
  const outputPath = path.join(dir, "output.json");
134
139
  fs.writeFileSync(schemaPath, JSON.stringify(schema), { mode: 0o600 });
135
- return { schema, schemaPath, outputPath };
140
+ return { schema, schemaPath, outputPath, ...(options.captureAcceptanceReport ? { acceptanceReportPath: path.join(dir, "acceptance-report.json") } : {}) };
136
141
  }
137
142
 
138
143
  export async function validateStructuredOutputValue(schema: JsonSchemaObject, value: unknown): Promise<{ status: "valid" } | { status: "invalid"; message: string }> {
@@ -172,6 +177,15 @@ export async function readStructuredOutput(runtime: StructuredOutputRuntime): Pr
172
177
  return { value };
173
178
  }
174
179
 
180
+ export function readStructuredOutputAcceptanceReport(runtime: StructuredOutputRuntime): { value?: unknown; error?: string } {
181
+ if (!runtime.acceptanceReportPath || !fs.existsSync(runtime.acceptanceReportPath)) return {};
182
+ try {
183
+ return { value: JSON.parse(fs.readFileSync(runtime.acceptanceReportPath, "utf-8")) };
184
+ } catch (error) {
185
+ return { error: `Failed to read structured output acceptance report: ${error instanceof Error ? error.message : String(error)}` };
186
+ }
187
+ }
188
+
175
189
  export function cleanupStructuredOutputRuntime(runtime: StructuredOutputRuntime | undefined): void {
176
190
  if (!runtime) return;
177
191
  try {