@xzzpig/pi-subagents 0.15.1 → 0.18.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 (135) hide show
  1. package/CHANGELOG.md +178 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +19 -12
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/fork-extensions.md +23 -15
  12. package/docs/models.md +5 -3
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +4 -4
  15. package/docs/tool-reference.md +40 -19
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +57 -3
  18. package/inspector-runner.mjs +1 -1
  19. package/package.json +14 -8
  20. package/prompts/council.md +6 -3
  21. package/runner-peer-loader.mjs +4 -7
  22. package/runner-peer-preload.mjs +5 -7
  23. package/skills/pi-subagents/SKILL.md +1 -0
  24. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  25. package/skills/pi-subagents/references/execution-controls.md +6 -4
  26. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  27. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  28. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  29. package/src/agents/agent-eject.ts +3 -3
  30. package/src/agents/agent-management.ts +61 -52
  31. package/src/agents/agent-memory.ts +90 -3
  32. package/src/agents/agent-serializer.ts +4 -4
  33. package/src/agents/agents.ts +125 -51
  34. package/src/agents/global-npm-root.ts +58 -0
  35. package/src/agents/proactive-skills.ts +4 -1
  36. package/src/agents/runtime-agent-registry.ts +14 -11
  37. package/src/agents/skills.ts +42 -9
  38. package/src/api/delegation.ts +15 -0
  39. package/src/api/inspectors.ts +27 -0
  40. package/src/api/preflight.ts +60 -60
  41. package/src/extension/doctor.ts +9 -4
  42. package/src/extension/fanout-child.ts +8 -0
  43. package/src/extension/index.ts +101 -48
  44. package/src/extension/rpc.ts +10 -1
  45. package/src/extension/schemas.ts +12 -6
  46. package/src/extension/subagent-guide.ts +12 -4
  47. package/src/extension/tool-activation.ts +197 -0
  48. package/src/extension/tool-description.ts +1 -1
  49. package/src/inspectors/ghostty/plugin.ts +13 -1
  50. package/src/inspectors/plugins.ts +70 -3
  51. package/src/intercom/intercom-bridge.ts +2 -0
  52. package/src/intercom/native-supervisor-channel.ts +22 -15
  53. package/src/intercom/result-intercom.ts +4 -0
  54. package/src/runs/background/active-async-capacity.ts +3 -25
  55. package/src/runs/background/async-execution.ts +100 -140
  56. package/src/runs/background/async-job-tracker.ts +28 -34
  57. package/src/runs/background/async-resume.ts +16 -8
  58. package/src/runs/background/async-status.ts +2 -0
  59. package/src/runs/background/binary-bootstrap.ts +34 -6
  60. package/src/runs/background/fleet-view.ts +51 -7
  61. package/src/runs/background/notify.ts +93 -7
  62. package/src/runs/background/pid-namespace.ts +18 -0
  63. package/src/runs/background/process-terminal-candidate.ts +98 -0
  64. package/src/runs/background/process-terminal.ts +17 -96
  65. package/src/runs/background/result-watcher.ts +1 -1
  66. package/src/runs/background/retained-children.ts +3 -2
  67. package/src/runs/background/run-child-session.ts +16 -5
  68. package/src/runs/background/run-id-resolver.ts +10 -5
  69. package/src/runs/background/run-status.ts +10 -4
  70. package/src/runs/background/runner-aliases.ts +25 -15
  71. package/src/runs/background/runner-child-launch.ts +1 -2
  72. package/src/runs/background/runner-startup-failure.ts +56 -0
  73. package/src/runs/background/stale-run-reconciler.ts +19 -3
  74. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  75. package/src/runs/background/subagent-runner.ts +96 -287
  76. package/src/runs/background/wait-tool.ts +2 -0
  77. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  78. package/src/runs/foreground/execution.ts +217 -250
  79. package/src/runs/foreground/prompt-audit.ts +3 -9
  80. package/src/runs/foreground/subagent-executor.ts +377 -119
  81. package/src/runs/shared/acceptance.ts +167 -68
  82. package/src/runs/shared/capability-ceiling.ts +4 -1
  83. package/src/runs/shared/child-hooks.ts +1 -16
  84. package/src/runs/shared/child-launch.ts +22 -14
  85. package/src/runs/shared/child-runtime-config.ts +3 -0
  86. package/src/runs/shared/child-session.ts +52 -2
  87. package/src/runs/shared/child-tool-plan.ts +23 -113
  88. package/src/runs/shared/dynamic-fanout.ts +1 -1
  89. package/src/runs/shared/external-cli-runner.ts +3 -1
  90. package/src/runs/shared/external-job-bridge.ts +54 -0
  91. package/src/runs/shared/git-environment.ts +29 -0
  92. package/src/runs/shared/mcp-config-sources.ts +3 -0
  93. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  94. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  95. package/src/runs/shared/model-resolution.ts +6 -1
  96. package/src/runs/shared/nested-events.ts +67 -55
  97. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  98. package/src/runs/shared/parallel-utils.ts +2 -1
  99. package/src/runs/shared/pi-spawn.ts +92 -6
  100. package/src/runs/shared/profile-launch-env.ts +10 -2
  101. package/src/runs/shared/single-output.ts +11 -2
  102. package/src/runs/shared/structured-output.ts +227 -7
  103. package/src/runs/shared/subagent-control.ts +2 -16
  104. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  105. package/src/runs/shared/tool-availability.ts +2 -2
  106. package/src/runs/shared/tool-budget.ts +21 -0
  107. package/src/runs/shared/usage-reconciliation.ts +73 -0
  108. package/src/runs/shared/worktree.ts +35 -8
  109. package/src/shared/child-session-name.ts +4 -2
  110. package/src/shared/fork-context.ts +11 -4
  111. package/src/shared/launch-contract.ts +1 -1
  112. package/src/shared/pruned-fork.ts +69 -56
  113. package/src/shared/types.ts +52 -16
  114. package/src/slash/delegation-adapters.ts +25 -1
  115. package/src/slash/prompt-template-bridge.ts +16 -1
  116. package/src/slash/prompt-workflows.ts +12 -1
  117. package/src/slash/slash-commands.ts +7 -241
  118. package/src/slash/subagent-cost.ts +313 -0
  119. package/src/slash/subagents-admin.ts +28 -29
  120. package/src/tui/fleet-status.ts +24 -2
  121. package/src/tui/fleet.ts +7 -4
  122. package/src/tui/render.ts +53 -19
  123. package/src/watchdog/diff-tool.ts +24 -3
  124. package/src/watchdog/permission-arbiter.ts +13 -15
  125. package/src/watchdog/register-child.ts +10 -2
  126. package/src/watchdog/review.ts +14 -14
  127. package/src/watchdog/runtime.ts +2 -1
  128. package/src/watchdog/turn-delta.ts +11 -5
  129. package/src/workflows/scripted-workflow.ts +109 -23
  130. package/src/workflows/workflow-child-summary.ts +4 -2
  131. package/src/workflows/workflow-settlement.ts +4 -1
  132. package/src/runs/shared/completion-evidence.ts +0 -89
  133. package/src/runs/shared/completion-guard.ts +0 -255
  134. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  135. package/src/runs/shared/task-intent.ts +0 -244
@@ -18,6 +18,7 @@ import type {
18
18
  AcceptanceReviewResult,
19
19
  AcceptanceVerifyCommand,
20
20
  AcceptanceVerifyResult,
21
+ JsonSchemaObject,
21
22
  ResolvedAcceptanceConfig,
22
23
  ResolvedAcceptanceGate,
23
24
  SingleResult,
@@ -26,7 +27,7 @@ import type {
26
27
  } from "../../shared/types.ts";
27
28
  import { unresolvedChildWatchdogBlockers } from "../../watchdog/child-status.ts";
28
29
  import { isAgentContract } from "./agent-contract.ts";
29
- import { classifyTaskMutationIntent, stripSeverityCompounds, taskMayMutate } from "./task-intent.ts";
30
+ import { validateStructuredOutputValue } from "./structured-output.ts";
30
31
 
31
32
  const LEVEL_RANK: Record<Exclude<AcceptanceLevel, "auto">, number> = {
32
33
  none: 0,
@@ -50,9 +51,9 @@ const VALID_EVIDENCE_KINDS: AcceptanceEvidenceKind[] = [
50
51
  const VALID_EVIDENCE = new Set<AcceptanceEvidenceKind>(VALID_EVIDENCE_KINDS);
51
52
  const ACCEPTANCE_EVIDENCE_HELP = `Supported evidence kinds: ${VALID_EVIDENCE_KINDS.join(", ")}. Example: { level: "checked", evidence: ["commands-run", "changed-files"] }.`;
52
53
  const ACCEPTANCE_OBJECT_EXAMPLE = "Example: { level: \"checked\", evidence: [\"commands-run\", \"changed-files\"] }.";
53
- const ACCEPTANCE_CONFIG_KEYS = new Set(["level", "report", "criteria", "evidence", "verify", "review", "stopRules", "reason"]);
54
+ const ACCEPTANCE_CONFIG_KEYS = new Set(["level", "report", "preserveStagedIndex", "criteria", "evidence", "verify", "review", "stopRules", "reason"]);
54
55
  const ACCEPTANCE_GATE_KEYS = new Set(["id", "must", "evidence", "severity"]);
55
- const ACCEPTANCE_VERIFY_KEYS = new Set(["id", "command", "timeoutMs", "cwd", "env", "allowFailure"]);
56
+ const ACCEPTANCE_VERIFY_KEYS = new Set(["id", "command", "timeoutMs", "cwd", "env", "allowFailure", "output", "schema"]);
56
57
  const ACCEPTANCE_REVIEW_KEYS = new Set(["agent", "focus", "required"]);
57
58
  const EXPLICIT_REVIEWED_UNAVAILABLE = "is an achieved status, not a requestable acceptance level. For a read-only reviewer call, omit acceptance. To require independent review of a writer result, use acceptance.review.required and orchestrate the reviewer separately.";
58
59
 
@@ -86,38 +87,8 @@ function inferLevel(input: {
86
87
  dynamic?: boolean;
87
88
  dynamicGroup?: boolean;
88
89
  }): { level: Exclude<AcceptanceLevel, "auto">; reasons: string[]; criteria: string[]; evidence: AcceptanceEvidenceKind[]; review?: { agent?: string; required?: boolean } } {
89
- const agent = input.agentName.toLowerCase();
90
- const task = input.task?.toLowerCase() ?? "";
91
- const reasons: string[] = [];
92
- // Declared roles replace name heuristics, so use the full writer grammar to detect explicit mutation independently of the actual agent name.
93
- const intent = classifyTaskMutationIntent(input.acceptanceRole ? "worker" : input.agentName, input.task ?? "");
94
- const readOnlyTask = intent.kind === "read-only"
95
- || (intent.kind === "unknown" && /\b(?:read[- ]only|review[- ]only|no edits|without edits|inspect|summari[sz]e)\b/.test(task));
96
- const rolePatchTask = input.acceptanceRole !== undefined
97
- && intent.kind !== "read-only"
98
- && !/\b(?:do not|don't|must not)\s+patch\b/.test(task)
99
- && /\bpatch\s+(?:(?:\.{0,2}[\\/])?(?:[\w.-]+[\\/])+[\w.-]+|[\w.-]+\.[a-z0-9]+\b|(?:the\s+)?parser\b)/.test(stripSeverityCompounds(task));
100
- const taskMayWrite = readOnlyTask ? false : taskMayMutate(input.task ?? "") || intent.kind === "implementation" || rolePatchTask;
101
- const readOnlyAgent = input.acceptanceRole === "read-only"
102
- || (input.acceptanceRole === undefined && /\b(?:reviewer|oracle|scout|researcher|analyst)\b/.test(agent));
103
- const writeTask = taskMayWrite
104
- || (input.acceptanceRole === "writer" && !readOnlyTask)
105
- || (input.acceptanceRole === undefined && /\bworker\b/.test(agent) && !readOnlyTask);
106
- const inferredReadOnly = readOnlyTask || ((readOnlyAgent || input.acceptanceRole === "read-only") && !taskMayWrite);
107
- const roleResolvesReadOnly = input.acceptanceRole !== undefined && inferredReadOnly;
108
- const dynamicResolvesReadOnly = inferredReadOnly && !writeTask;
109
- const riskyKeywordPattern = /\b(?:release|migration|migrate|security|data[- ]loss|destructive|post-review|fix pass)\b/;
110
- // Topic keywords cannot override classified read-only intent; unknown tasks keep their risk gate.
111
- const keywordRiskReadOnly = input.acceptanceRole === undefined
112
- ? intent.kind === "read-only"
113
- : inferredReadOnly;
114
- const risky = Boolean(input.async && writeTask)
115
- || (Boolean(input.dynamic) && !roleResolvesReadOnly && !dynamicResolvesReadOnly)
116
- || (Boolean(input.dynamicGroup) && !roleResolvesReadOnly && !dynamicResolvesReadOnly)
117
- || (!keywordRiskReadOnly && riskyKeywordPattern.test(task));
118
-
119
- if (risky) {
120
- reasons.push(input.async ? "async write-capable or risky run" : "risky write-capable run");
90
+ if (input.acceptanceRole === "writer" && (input.async || input.dynamic || input.dynamicGroup)) {
91
+ const reasons = [input.async ? "async declared writer" : "dynamic declared writer"];
121
92
  if (input.dynamic || input.dynamicGroup) reasons.push("dynamic fanout context");
122
93
  return {
123
94
  level: "checked",
@@ -127,28 +98,25 @@ function inferLevel(input: {
127
98
  review: { agent: "reviewer", required: true },
128
99
  };
129
100
  }
130
- if (writeTask && !readOnlyTask) {
131
- reasons.push(input.acceptanceRole === "writer" && !taskMayWrite ? "declared writer acceptance role" : "write-capable worker/task");
101
+ if (input.acceptanceRole === "writer") {
132
102
  return {
133
103
  level: "checked",
134
- reasons,
104
+ reasons: ["declared writer acceptance role"],
135
105
  criteria: ["Implement the requested change without widening scope"],
136
106
  evidence: requiredEvidenceForLevel("checked"),
137
107
  };
138
108
  }
139
- if (readOnlyAgent || readOnlyTask) {
140
- reasons.push(input.acceptanceRole === "read-only" && !readOnlyTask ? "declared read-only acceptance role" : readOnlyAgent ? "read-only/reviewer-style agent" : "read-only task wording");
109
+ if (input.acceptanceRole === "read-only") {
141
110
  return {
142
111
  level: "none",
143
- reasons,
112
+ reasons: ["declared read-only acceptance role"],
144
113
  criteria: ["Return concrete findings with file paths and severity when applicable"],
145
114
  evidence: ["review-findings", "residual-risks"],
146
115
  };
147
116
  }
148
- reasons.push("default lightweight attestation");
149
117
  return {
150
118
  level: "attested",
151
- reasons,
119
+ reasons: ["default lightweight attestation"],
152
120
  criteria: ["Return a concise result and residual risks when applicable"],
153
121
  evidence: ["manual-notes", "residual-risks"],
154
122
  };
@@ -200,15 +168,59 @@ type GateAcceptanceNormalizationResult =
200
168
  | { ok: true; acceptance?: AcceptanceInput }
201
169
  | { ok: false; error: string };
202
170
 
171
+ const GATE_OBJECT_KEYS = new Set(["command", "output", "schema", "timeoutMs"]);
172
+ export const GATE_INPUT_ERROR = "gate must be a non-empty command string or { command, output?: \"json\", schema?, timeoutMs? }.";
173
+
174
+ export interface GateObjectInput {
175
+ command: string;
176
+ output?: "json";
177
+ schema?: JsonSchemaObject;
178
+ timeoutMs?: number;
179
+ }
180
+
181
+ /** Validates the two accepted gate shapes without normalizing them. Shared by preflight and the workflow sandbox mirror. */
182
+ export function parseGateInput(gate: unknown): { ok: true; gate: GateObjectInput } | { ok: false; error: string } {
183
+ if (typeof gate === "string") {
184
+ return gate.trim() ? { ok: true, gate: { command: gate.trim() } } : { ok: false, error: GATE_INPUT_ERROR };
185
+ }
186
+ if (!gate || typeof gate !== "object" || Array.isArray(gate)) return { ok: false, error: GATE_INPUT_ERROR };
187
+ const value = gate as Record<string, unknown>;
188
+ for (const key of Object.keys(value)) {
189
+ if (!GATE_OBJECT_KEYS.has(key)) return { ok: false, error: `gate.${key} is not supported.` };
190
+ }
191
+ if (typeof value.command !== "string" || !value.command.trim()) return { ok: false, error: GATE_INPUT_ERROR };
192
+ if (value.output !== undefined && value.output !== "json") return { ok: false, error: "gate.output must be \"json\" when present." };
193
+ if (value.schema !== undefined) {
194
+ if (value.output !== "json") return { ok: false, error: "gate.schema requires gate.output: \"json\"." };
195
+ if (!value.schema || typeof value.schema !== "object" || Array.isArray(value.schema)) return { ok: false, error: "gate.schema must be a JSON Schema object." };
196
+ }
197
+ if (value.timeoutMs !== undefined && (!Number.isInteger(value.timeoutMs) || (value.timeoutMs as number) < 1)) return { ok: false, error: "gate.timeoutMs must be an integer >= 1." };
198
+ const parsed: GateObjectInput = { command: value.command.trim() };
199
+ if (value.output === "json") parsed.output = "json";
200
+ // SAFETY: schema was checked above to be a non-array object; timeoutMs to be an integer >= 1.
201
+ if (value.schema !== undefined) parsed.schema = value.schema as JsonSchemaObject;
202
+ if (value.timeoutMs !== undefined) parsed.timeoutMs = value.timeoutMs as number;
203
+ return { ok: true, gate: parsed };
204
+ }
205
+
206
+ /** True when an acceptance policy declares at least one `output: "json"` verify command, from either the gate shorthand or an explicit verify list. */
207
+ export function acceptanceHasTypedVerify(acceptance: AcceptanceInput | undefined): boolean {
208
+ if (!acceptance || typeof acceptance !== "object") return false;
209
+ return Array.isArray(acceptance.verify) && acceptance.verify.some((command) => command && typeof command === "object" && command.output === "json");
210
+ }
211
+
212
+ export const TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT = "a typed verify command (output: \"json\") cannot be combined with outputSchema; the child would have two structured-output sources.";
213
+
203
214
  export function normalizeGateAcceptance(gate: unknown, acceptance: AcceptanceInput | undefined): GateAcceptanceNormalizationResult {
204
215
  if (gate === undefined) {
205
216
  if (acceptance === undefined) return { ok: true };
206
217
  const normalized = normalizeAcceptanceValue(acceptance);
207
218
  return normalized.error ? { ok: false, error: normalized.error } : { ok: true, acceptance: normalized.value as AcceptanceInput };
208
219
  }
209
- if (typeof gate !== "string" || !gate.trim()) return { ok: false, error: "gate must be a non-empty command string." };
220
+ const parsed = parseGateInput(gate);
221
+ if (!parsed.ok) return { ok: false, error: parsed.error };
210
222
  if (acceptance !== undefined && acceptance !== false) return { ok: false, error: "gate cannot be combined with acceptance; use one gate command or acceptance.verify." + describeGateAcceptanceConflict(gate, acceptance) };
211
- return { ok: true, acceptance: { level: "verified", verify: [{ id: "gate", command: gate.trim() }] } };
223
+ return { ok: true, acceptance: { level: "verified", verify: [{ id: "gate", ...parsed.gate }] } };
212
224
  }
213
225
 
214
226
  export function describeGateAcceptanceConflict(gate: unknown, acceptance: unknown): string {
@@ -267,6 +279,12 @@ export function validateAcceptanceInput(input: unknown, pathLabel = "acceptance"
267
279
  if (value.report !== undefined && value.report !== "on" && value.report !== "off") {
268
280
  errors.push(`${pathLabel}.report must be on or off.`);
269
281
  }
282
+ if (value.preserveStagedIndex !== undefined && value.preserveStagedIndex !== true) {
283
+ errors.push(`${pathLabel}.preserveStagedIndex must be true when provided.`);
284
+ }
285
+ if (value.preserveStagedIndex === true && value.level !== "checked" && value.level !== "verified") {
286
+ errors.push(`${pathLabel}.preserveStagedIndex requires level checked or verified.`);
287
+ }
270
288
  if (value.level === "none" && (typeof value.reason !== "string" || !value.reason.trim())) {
271
289
  errors.push(`${pathLabel}.reason is required when level is none.`);
272
290
  }
@@ -348,6 +366,11 @@ export function validateAcceptanceInput(input: unknown, pathLabel = "acceptance"
348
366
  if (cmd.allowFailure !== undefined && typeof cmd.allowFailure !== "boolean") {
349
367
  errors.push(`${pathLabel}.verify[${index}].allowFailure must be a boolean.`);
350
368
  }
369
+ if (cmd.output !== undefined && cmd.output !== "json") errors.push(`${pathLabel}.verify[${index}].output must be "json" when present.`);
370
+ if (cmd.schema !== undefined) {
371
+ if (cmd.output !== "json") errors.push(`${pathLabel}.verify[${index}].schema requires output: "json".`);
372
+ if (!cmd.schema || typeof cmd.schema !== "object" || Array.isArray(cmd.schema)) errors.push(`${pathLabel}.verify[${index}].schema must be a JSON Schema object.`);
373
+ }
351
374
  }
352
375
  }
353
376
  if (value.review !== undefined && value.review !== false) {
@@ -471,6 +494,7 @@ export function resolveEffectiveAcceptance(input: {
471
494
  inferredReason: [],
472
495
  criteria,
473
496
  evidence,
497
+ preserveStagedIndex: explicit.preserveStagedIndex,
474
498
  verify: explicit.verify ?? [],
475
499
  review: explicit.review,
476
500
  stopRules: explicit.stopRules ?? [],
@@ -496,6 +520,7 @@ export function resolveEffectiveAcceptance(input: {
496
520
  inferredReason: inferred.reasons,
497
521
  criteria: level === "none" ? [] : criteria,
498
522
  evidence: level === "none" ? [] : evidence,
523
+ preserveStagedIndex: explicit.preserveStagedIndex,
499
524
  verify: explicit.verify ?? [],
500
525
  review,
501
526
  stopRules: explicit.stopRules ?? [],
@@ -527,6 +552,9 @@ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, opt
527
552
  "",
528
553
  `Required evidence: ${acceptance.evidence.join(", ") || "none"}`,
529
554
  ];
555
+ if (acceptance.preserveStagedIndex) {
556
+ lines.push("The host will verify that the staged index is unchanged from launch; report noStagedFiles truthfully even when the preserved index is non-empty.");
557
+ }
530
558
  if (acceptance.verify.length > 0) {
531
559
  lines.push("", "Runtime verification commands configured by parent:");
532
560
  for (const command of acceptance.verify) lines.push(`- ${command.id}: ${command.command}`);
@@ -1079,9 +1107,32 @@ function checkNoStagedFiles(cwd: string): AcceptanceRuntimeCheck {
1079
1107
  : { id: "no-staged-files", status: "failed", message: `Staged files present: ${staged.join(", ")}` };
1080
1108
  }
1081
1109
 
1110
+ /** Capture the repository-wide index tree. Throws when Git cannot provide trustworthy evidence. */
1111
+ export function captureStagedIndexBaseline(cwd: string): string {
1112
+ const result = spawnSync("git", ["write-tree"], { cwd, encoding: "utf-8", windowsHide: true });
1113
+ const oid = result.stdout.trim();
1114
+ if (result.status !== 0 || !oid) {
1115
+ const detail = result.stderr.trim();
1116
+ throw new Error(`Unable to capture staged index baseline${detail ? `: ${detail}` : "."}`);
1117
+ }
1118
+ return oid;
1119
+ }
1120
+
1121
+ function checkStagedIndexUnchanged(cwd: string, baseline: string): AcceptanceRuntimeCheck {
1122
+ try {
1123
+ const terminal = captureStagedIndexBaseline(cwd);
1124
+ return terminal === baseline
1125
+ ? { id: "staged-index-unchanged", status: "passed", message: "Staged index matches the launch baseline." }
1126
+ : { id: "staged-index-unchanged", status: "failed", message: "Staged index changed after launch." };
1127
+ } catch (error) {
1128
+ return { id: "staged-index-unchanged", status: "failed", message: error instanceof Error ? error.message : String(error) };
1129
+ }
1130
+ }
1131
+
1082
1132
  function runStructuralChecks(acceptance: ResolvedAcceptanceConfig, report: AcceptanceReport, cwd: string): AcceptanceRuntimeCheck[] {
1083
1133
  const checks: AcceptanceRuntimeCheck[] = [];
1084
1134
  for (const kind of acceptance.evidence) {
1135
+ if (kind === "no-staged-files" && acceptance.preserveStagedIndex) continue;
1085
1136
  if (kind === "no-staged-files" && report.noStagedFiles === undefined) continue;
1086
1137
  const status = reportEvidenceStatus(report, kind);
1087
1138
  checks.push({
@@ -1094,7 +1145,7 @@ function runStructuralChecks(acceptance: ResolvedAcceptanceConfig, report: Accep
1094
1145
  : `${kind} evidence missing from child report.`,
1095
1146
  });
1096
1147
  }
1097
- if (acceptance.evidence.includes("no-staged-files")) checks.push(checkNoStagedFiles(cwd));
1148
+ if (!acceptance.preserveStagedIndex && acceptance.evidence.includes("no-staged-files")) checks.push(checkNoStagedFiles(cwd));
1098
1149
  return checks;
1099
1150
  }
1100
1151
 
@@ -1202,6 +1253,43 @@ function isCachedVerifyResult(value: unknown): value is AcceptanceVerifyResult {
1202
1253
  && typeof result.durationMs === "number";
1203
1254
  }
1204
1255
 
1256
+ const TYPED_VERIFY_OUTPUT_MAX_BYTES = 12_000;
1257
+
1258
+ /**
1259
+ * A passing `output: "json"` command must print one JSON document on stdout.
1260
+ * The parsed value becomes the run's structured output; anything else turns
1261
+ * the passing run into a failed one so acceptance rejects rather than
1262
+ * silently dropping the verdict. Stdout is already bounded by trimOutput, so a
1263
+ * truncated document is detected by its marker instead of a parse guess.
1264
+ */
1265
+ async function applyTypedVerifyOutput(command: AcceptanceVerifyCommand, run: AcceptanceVerifyResult): Promise<void> {
1266
+ if (run.status !== "passed") return;
1267
+ const stdout = run.stdout ?? "";
1268
+ const fail = (message: string): void => {
1269
+ run.status = "failed";
1270
+ run.structuredOutputError = message;
1271
+ };
1272
+ if (!stdout.trim()) return fail("output: \"json\" command printed nothing on stdout.");
1273
+ if (stdout.endsWith("...[truncated]")) return fail(`output: "json" stdout exceeded ${TYPED_VERIFY_OUTPUT_MAX_BYTES} characters and was truncated.`);
1274
+ let value: unknown;
1275
+ try {
1276
+ value = JSON.parse(stdout);
1277
+ } catch (error) {
1278
+ return fail(`output: "json" stdout is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
1279
+ }
1280
+ if (command.schema) {
1281
+ const validation = await validateStructuredOutputValue(command.schema, value);
1282
+ if (validation.status === "invalid") return fail(`output: "json" stdout does not match gate.schema: ${validation.message}`);
1283
+ }
1284
+ run.structuredOutput = value;
1285
+ }
1286
+
1287
+ /** The first typed verify result on a ledger, if any command produced one. */
1288
+ export function typedVerifyOutput(ledger: AcceptanceLedger | undefined): { value: unknown } | undefined {
1289
+ const run = ledger?.verifyRuns?.find((entry) => entry.structuredOutput !== undefined);
1290
+ return run ? { value: run.structuredOutput } : undefined;
1291
+ }
1292
+
1205
1293
  async function runMemoizedVerifyCommand(command: AcceptanceVerifyCommand, defaultCwd: string, options: {
1206
1294
  signal?: AbortSignal;
1207
1295
  abortMessage?: string;
@@ -1215,7 +1303,9 @@ async function runMemoizedVerifyCommand(command: AcceptanceVerifyCommand, defaul
1215
1303
  } catch {
1216
1304
  workspaceState = undefined;
1217
1305
  }
1218
- if (!workspaceState || !options.artifactsDir || !options.runId) {
1306
+ // Typed gates read inputs (a report file, a log) that can change without
1307
+ // the tracked tree changing, so their verdicts are never reused.
1308
+ if (!workspaceState || !options.artifactsDir || !options.runId || command.output === "json") {
1219
1309
  return runVerifyCommand(command, defaultCwd, options);
1220
1310
  }
1221
1311
  const envKeys = Object.keys(command.env ?? {}).sort();
@@ -1387,6 +1477,8 @@ export async function evaluateAcceptance(input: {
1387
1477
  acceptance: ResolvedAcceptanceConfig;
1388
1478
  output: string;
1389
1479
  cwd: string;
1480
+ /** Host-captured launch index tree; required by preserveStagedIndex. */
1481
+ stagedIndexBaseline?: string;
1390
1482
  /**
1391
1483
  * Content the child sent to its configured output file (from its own write
1392
1484
  * tool calls, not from disk, so a concurrent writer to the same path cannot
@@ -1482,30 +1574,36 @@ export async function evaluateAcceptance(input: {
1482
1574
  ledger.runtimeChecks.push({ id: "verification-config", status: "failed", message: "verified acceptance requires runtime verify commands." });
1483
1575
  ledger.status = "rejected";
1484
1576
  ledger.evidenceStatus = "rejected";
1485
- return ledger;
1486
- }
1487
- ledger.verifyRuns = [];
1488
- for (const command of acceptance.verify) {
1489
- ledger.verifyRuns.push(await runMemoizedVerifyCommand(command, input.cwd, {
1490
- signal: input.signal,
1491
- abortMessage: input.abortMessage,
1492
- artifactsDir: input.artifactsDir,
1493
- runId: input.runId,
1494
- }));
1495
- if (input.signal?.aborted) break;
1496
- }
1497
- if (ledger.verifyRuns.some((run) => run.status === "failed" || run.status === "timed-out")) {
1498
- ledger.status = "rejected";
1499
- ledger.evidenceStatus = "rejected";
1500
- return ledger;
1501
- }
1502
- if (!ledger.runtimeChecks.some((check) => check.status === "failed")) {
1503
- ledger.status = "verified";
1504
- ledger.evidenceStatus = "verified";
1577
+ } else {
1578
+ ledger.verifyRuns = [];
1579
+ for (const command of acceptance.verify) {
1580
+ const run = await runMemoizedVerifyCommand(command, input.cwd, {
1581
+ signal: input.signal,
1582
+ abortMessage: input.abortMessage,
1583
+ artifactsDir: input.artifactsDir,
1584
+ runId: input.runId,
1585
+ });
1586
+ if (command.output === "json") await applyTypedVerifyOutput(command, run);
1587
+ ledger.verifyRuns.push(run);
1588
+ if (input.signal?.aborted) break;
1589
+ }
1590
+ if (ledger.verifyRuns.some((run) => run.status === "failed" || run.status === "timed-out")) {
1591
+ ledger.status = "rejected";
1592
+ ledger.evidenceStatus = "rejected";
1593
+ } else if (!ledger.runtimeChecks.some((check) => check.status === "failed")) {
1594
+ ledger.status = "verified";
1595
+ ledger.evidenceStatus = "verified";
1596
+ }
1505
1597
  }
1506
1598
  }
1507
1599
 
1508
- if (ledger.runtimeChecks.some((check) => check.status === "failed")) {
1600
+ if (acceptance.preserveStagedIndex) {
1601
+ ledger.runtimeChecks.push(input.stagedIndexBaseline
1602
+ ? checkStagedIndexUnchanged(input.cwd, input.stagedIndexBaseline)
1603
+ : { id: "staged-index-unchanged", status: "failed", message: "Staged index launch baseline is unavailable." });
1604
+ }
1605
+
1606
+ if (ledger.status === "rejected" || ledger.runtimeChecks.some((check) => check.status === "failed")) {
1509
1607
  ledger.status = "rejected";
1510
1608
  ledger.evidenceStatus = "rejected";
1511
1609
  return ledger;
@@ -1559,6 +1657,7 @@ export function acceptanceFailureMessage(ledger: AcceptanceLedger): string | und
1559
1657
  const failedCheck = ledger.runtimeChecks.find((check) => check.status === "failed");
1560
1658
  if (failedCheck) return `Acceptance rejected: ${failedCheck.message}`;
1561
1659
  const failedVerify = ledger.verifyRuns.find((run) => run.status === "failed" || run.status === "timed-out");
1660
+ if (failedVerify?.structuredOutputError) return `Acceptance verification '${failedVerify.id}' failed: ${failedVerify.structuredOutputError}`;
1562
1661
  if (failedVerify) return `Acceptance verification '${failedVerify.id}' ${failedVerify.status}.`;
1563
1662
  if (ledger.reviewResult?.status === "blockers") return "Acceptance review found blockers.";
1564
1663
  return "Acceptance rejected.";
@@ -30,7 +30,6 @@ export interface SubagentCapabilityAudit {
30
30
  agentAllowed: boolean;
31
31
  agentRestrictionSources?: string[];
32
32
  /** Builtin tools declared but unavailable on the host runtime. */
33
- unavailableHostBuiltins?: string[];
34
33
  }
35
34
 
36
35
  export interface RegisterSubagentCapabilityCeilingOptions {
@@ -64,6 +63,10 @@ function validateText(value: unknown, field: string): string {
64
63
  return value.trim();
65
64
  }
66
65
 
66
+ export function normalizeCapabilityCeilingAllowedAgents(values: unknown): string[] {
67
+ return normalizeCeiling({ allowedAgents: values } as SubagentCapabilityCeiling).allowedAgents!;
68
+ }
69
+
67
70
  function normalizeCeiling(ceiling: SubagentCapabilityCeiling): ResolvedSubagentCapabilityCeiling {
68
71
  if (!ceiling || typeof ceiling !== "object" || Array.isArray(ceiling)) throw new Error("Invalid capability ceiling; expected an object.");
69
72
  const hasAllowedTools = Object.hasOwn(ceiling, "allowedTools");
@@ -7,7 +7,6 @@ import registerSubagentPromptRuntime from "./subagent-prompt-runtime.ts";
7
7
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
8
8
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
9
9
  import type { ChildSessionLaunch } from "./child-session.ts";
10
- import type { ArbiterModelContext } from "./llm-intent-arbiter.ts";
11
10
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
12
11
  import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.ts";
13
12
 
@@ -128,10 +127,9 @@ export function createChildHooks(config: ChildRuntimeConfig): ChildHookExtension
128
127
  }
129
128
 
130
129
  /** Launch-owned bookkeeping, paired with the same private hook certificate (no callback registration API). */
131
- export function createCapturedChildHooks(config: ChildRuntimeConfig, runner = false) {
130
+ export function createCapturedChildHooks(config: ChildRuntimeConfig) {
132
131
  let diagnostic: ChildToolDiagnostic | undefined;
133
132
  let acknowledgedIds: string[] | undefined;
134
- let completionIntentContext: ArbiterModelContext | undefined;
135
133
  let finalDrainHeld = false;
136
134
  const capture: OwnedCapture = {
137
135
  toolDiagnostic: (value) => { diagnostic = value; },
@@ -139,21 +137,8 @@ export function createCapturedChildHooks(config: ChildRuntimeConfig, runner = fa
139
137
  };
140
138
  Object.assign(config, capture);
141
139
  const hooks = childHooks(config, capture, (held) => { finalDrainHeld = held; });
142
- if (runner) {
143
- hooks.push({ name: "pi-subagents:completion-intent", factory: (pi) => pi.on("session_start", (_event, childCtx) => {
144
- // Retain only attempt model services and the session id string, not the live child session.
145
- completionIntentContext = {
146
- model: childCtx.model,
147
- modelRegistry: childCtx.modelRegistry,
148
- sessionId: childCtx.sessionManager.getSessionId(),
149
- };
150
- }) });
151
- const proof = promptProofs.get(hooks[0]!.factory);
152
- if (proof) proof.factories = hooks.map((hook) => hook.factory);
153
- }
154
140
  return {
155
141
  hooks,
156
- completionIntentContext: () => completionIntentContext,
157
142
  toolDiagnostic: () => diagnostic,
158
143
  runtimeAcknowledgedExtensions: () => acknowledgedIds ? projectRuntimeAcknowledgedExtensions(acknowledgedIds) : undefined,
159
144
  finalDrainHeld: () => finalDrainHeld,
@@ -23,7 +23,7 @@ import type { StructuredOutputRuntime } from "./structured-output.ts";
23
23
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
24
24
  import type { RuntimeAcknowledgedChildExtensions } from "../../shared/types.ts";
25
25
  import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV, type ExtensionBindings } from "./extension-bindings.ts";
26
- import type { ResolvedSubagentCapabilityCeiling, SubagentCapabilityAudit } from "./capability-ceiling.ts";
26
+ import { intersectSubagentCapabilityCeilings, type ResolvedSubagentCapabilityCeiling, type SubagentCapabilityAudit } from "./capability-ceiling.ts";
27
27
  import { buildProfileLaunchEnv } from "./profile-launch-env.ts";
28
28
  import {
29
29
  isSubagentRuntimeExtensionPath,
@@ -36,7 +36,6 @@ import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
36
36
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.ts";
37
37
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
38
38
  import type { ChildSessionLaunch, ChildSessionStorage } from "./child-session.ts";
39
- import type { ArbiterModelContext } from "./llm-intent-arbiter.ts";
40
39
  import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
41
40
 
42
41
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
@@ -107,6 +106,7 @@ export interface BuildInProcessChildLaunchInput {
107
106
  waitToolEnabled?: boolean;
108
107
  waitToolDefaultTimeoutMs?: number;
109
108
  allowNestedSubagents?: boolean;
109
+ descendantAllowedAgents?: string[];
110
110
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
111
111
  thinkingCeiling?: ThinkingLevel;
112
112
  maxSubagentDepth?: number;
@@ -115,6 +115,8 @@ export interface BuildInProcessChildLaunchInput {
115
115
  sandbox?: string;
116
116
  /** A validated global pi-permission-system profile selected by the agent definition. */
117
117
  permissionProfile?: string;
118
+ /** Builtin tool names the host runtime provides; intersects agent-declared core tools. */
119
+ hostAvailableBuiltins?: readonly string[];
118
120
  /** Parent-authoritative trust state for profile-aware project config merging. */
119
121
  projectTrusted?: boolean;
120
122
  /** Exact trusted parent cwd; profile project config applies only when the child cwd matches it. */
@@ -128,17 +130,9 @@ export interface BuildInProcessChildLaunchInput {
128
130
  * them and exposes the child environment external extensions read.
129
131
  */
130
132
  host: "parent" | "runner";
131
- /**
132
- * Pi core tool names the host runtime provides. When set, child tool plans
133
- * intersect known core slots with this set; declared non-core names remain
134
- * for child startup validation. Review/scout lanes fail closed when a requested,
135
- * still-permitted repository inspection tool is missing from that set.
136
- */
137
- hostAvailableBuiltins?: readonly string[];
138
133
  }
139
134
 
140
135
  export interface InProcessChildCapture {
141
- completionIntentContext?(): ArbiterModelContext | undefined;
142
136
  structuredOutput(): { called: boolean; value?: unknown; acceptanceReport?: unknown; acceptanceReportProvided: boolean };
143
137
  toolDiagnostic(): ChildToolDiagnostic | undefined;
144
138
  runtimeAcknowledgedExtensions(): RuntimeAcknowledgedChildExtensions | undefined;
@@ -202,6 +196,13 @@ function childStorage(input: BuildInProcessChildLaunchInput): ChildSessionStorag
202
196
 
203
197
  export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput): InProcessChildLaunch {
204
198
  const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
199
+ const agentCapabilityCeiling: ResolvedSubagentCapabilityCeiling | undefined = input.descendantAllowedAgents === undefined
200
+ ? undefined
201
+ : { version: 1, allowedAgents: [...input.descendantAllowedAgents], denyExtensions: false, sources: [`agent:${input.childAgentName}`] };
202
+ const inheritedCeiling = inheritedCapabilityCeiling(input.inherited);
203
+ const capabilityCeilingForPlanning = agentCapabilityCeiling && !input.capabilityCeiling && !inheritedCeiling
204
+ ? { version: 1 as const, denyExtensions: false, sources: [] }
205
+ : input.capabilityCeiling;
205
206
  const toolPlan = resolvePiLaunchToolPlan({
206
207
  tools: input.tools,
207
208
  excludeTools: input.excludeTools,
@@ -215,8 +216,8 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
215
216
  structuredOutput: Boolean(input.structuredOutput),
216
217
  fast: input.fast,
217
218
  model: input.model,
218
- capabilityCeiling: input.capabilityCeiling,
219
- inheritedCapabilityCeiling: inheritedCapabilityCeiling(input.inherited),
219
+ capabilityCeiling: capabilityCeilingForPlanning,
220
+ inheritedCapabilityCeiling: inheritedCeiling,
220
221
  agentName: input.childAgentName,
221
222
  permissionRules: input.permissionRules,
222
223
  runtimeSnapshotHost: input.runtimeSnapshotHost,
@@ -224,6 +225,10 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
224
225
  permissionProfile: input.permissionProfile,
225
226
  hostAvailableBuiltins: input.hostAvailableBuiltins,
226
227
  });
228
+ toolPlan.capabilityCeiling = intersectSubagentCapabilityCeilings(toolPlan.capabilityCeiling, agentCapabilityCeiling);
229
+ if (toolPlan.capabilityAudit && toolPlan.capabilityCeiling) {
230
+ toolPlan.capabilityAudit = { ...toolPlan.capabilityAudit, ceiling: toolPlan.capabilityCeiling };
231
+ }
227
232
 
228
233
  // Profile env construction (ack/diagnostics paths, sandbox and permission
229
234
  // profile keys, the pinned profile, and the transient host key list) lives
@@ -257,8 +262,10 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
257
262
  let structuredAcceptanceReport: unknown;
258
263
  let structuredCalled = false;
259
264
  let structuredAcceptanceProvided = false;
265
+ const structuredTerminalState = { captured: false };
260
266
 
261
267
  const config: ChildRuntimeConfig = {
268
+ cwd: input.cwd,
262
269
  ...(input.runId ? { runId: input.runId } : {}),
263
270
  agent: input.childAgentName,
264
271
  childIndex: input.childIndex,
@@ -292,6 +299,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
292
299
  ? {
293
300
  structuredOutput: {
294
301
  schema: input.structuredOutput.schema,
302
+ terminalState: structuredTerminalState,
295
303
  ...(input.structuredOutput.acceptanceReportPath
296
304
  ? { acceptanceReport: input.structuredOutput.acceptanceReportRequired ? "required" as const : "optional" as const }
297
305
  : {}),
@@ -300,6 +308,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
300
308
  structuredValue = value;
301
309
  structuredAcceptanceProvided = acceptanceReport !== undefined;
302
310
  structuredAcceptanceReport = acceptanceReport;
311
+ structuredTerminalState.captured = true;
303
312
  },
304
313
  },
305
314
  }
@@ -308,7 +317,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
308
317
  ...(toolPlan.effectiveMcpTools.length > 0 ? { mcpDirectTools: toolPlan.effectiveMcpTools } : {}),
309
318
  fast: input.fast === true,
310
319
  };
311
- const capturedHooks = createCapturedChildHooks(config, input.host === "runner");
320
+ const capturedHooks = createCapturedChildHooks(config);
312
321
 
313
322
  const extensionPaths = toolPlan.extensionArgs.filter((extensionPath) => !isSubagentRuntimeExtensionPath(extensionPath));
314
323
  const ambientExtensions = input.host === "runner" && !toolPlan.disableAmbientExtensions;
@@ -351,7 +360,6 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
351
360
  config,
352
361
  session,
353
362
  capture: {
354
- completionIntentContext: capturedHooks.completionIntentContext,
355
363
  structuredOutput: () => ({ called: structuredCalled, value: structuredValue, acceptanceReport: structuredAcceptanceReport, acceptanceReportProvided: structuredAcceptanceProvided }),
356
364
  toolDiagnostic: capturedHooks.toolDiagnostic,
357
365
  runtimeAcknowledgedExtensions: capturedHooks.runtimeAcknowledgedExtensions,
@@ -39,6 +39,8 @@ export interface ChildPermissions {
39
39
  export interface ChildStructuredOutput {
40
40
  schema: JsonSchemaObject;
41
41
  acceptanceReport?: "optional" | "required";
42
+ /** Authoritative child-local state set only after validated capture succeeds. */
43
+ terminalState?: { captured: boolean };
42
44
  /** Receives the validated value; `acceptanceReport` is undefined when the child omitted it. */
43
45
  capture: (value: unknown, acceptanceReport: unknown | undefined) => void;
44
46
  }
@@ -58,6 +60,7 @@ export interface ChildSupervisorMetadata {
58
60
  * that hosts the child session builds it and passes it to the hooks directly.
59
61
  */
60
62
  export interface ChildRuntimeConfig {
63
+ cwd?: string;
61
64
  runId?: string;
62
65
  agent?: string;
63
66
  childIndex?: number;