@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -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 +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -1,11 +1,13 @@
1
1
  const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
2
2
 
3
- export type McpToolPrefix = "server" | "none" | "short";
3
+ export type McpToolPrefix = "server" | "none" | "short" | "mcp";
4
4
 
5
5
  export interface McpGrantServerFacts {
6
6
  readonly exposeResources?: boolean;
7
7
  readonly includeTools?: readonly unknown[];
8
8
  readonly excludeTools?: readonly unknown[];
9
+ /** Per-server prefix override, matching the adapter's `ServerEntry.toolPrefix`. */
10
+ readonly toolPrefix?: unknown;
9
11
  }
10
12
 
11
13
  export interface McpGrantToolMetadata {
@@ -73,7 +75,6 @@ export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirec
73
75
  const { servers: selectedServers, tools: selectedTools } = parseMcpDirectToolSelectors(selectors);
74
76
  const selections: ResolvedMcpDirectToolSelection[] = [];
75
77
  const seenNames = new Set<string>();
76
- const prefix = normalizeMcpToolPrefix(input.toolPrefix);
77
78
 
78
79
  for (const [serverName, server] of Object.entries(input.servers)) {
79
80
  const metadata = input.metadata[serverName];
@@ -83,6 +84,7 @@ export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirec
83
84
  ? true
84
85
  : selectedTools.get(serverName);
85
86
  if (!toolFilter) continue;
87
+ const prefix = normalizeMcpToolPrefix(server.toolPrefix ?? input.toolPrefix);
86
88
 
87
89
  for (const tool of Array.isArray(metadata.tools) ? metadata.tools : []) {
88
90
  if (typeof tool?.name !== "string" || !tool.name) continue;
@@ -116,7 +118,7 @@ export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirec
116
118
  }
117
119
 
118
120
  export function normalizeMcpToolPrefix(value: unknown): McpToolPrefix {
119
- return value === "none" || value === "short" || value === "server" ? value : "server";
121
+ return value === "none" || value === "short" || value === "mcp" || value === "server" ? value : "server";
120
122
  }
121
123
 
122
124
  export function formatUnresolvedMcpDirectToolSelectors(selectors: readonly string[]): string {
@@ -125,13 +127,26 @@ export function formatUnresolvedMcpDirectToolSelectors(selectors: readonly strin
125
127
 
126
128
  function getServerPrefix(serverName: string, mode: McpToolPrefix): string {
127
129
  if (mode === "none") return "";
128
- if (mode === "short") return serverName.replace(/-?mcp$/i, "") || "mcp";
129
- return serverName;
130
+ if (mode === "short") return sanitizeServerPrefix(serverName.replace(/-?mcp$/i, "")) || "mcp";
131
+ if (mode === "mcp") return `mcp__${sanitizeServerPrefix(serverName)}`;
132
+ return sanitizeServerPrefix(serverName);
133
+ }
134
+
135
+ /** Adapter parity: characters outside [A-Za-z0-9_-] become `_<code point in hex>_`. */
136
+ function sanitizeServerPrefix(serverName: string): string {
137
+ return Array.from(serverName, (char) => /^[A-Za-z0-9_-]$/.test(char) ? char : `_${char.codePointAt(0)!.toString(16)}_`).join("");
130
138
  }
131
139
 
132
140
  function formatToolName(toolName: string, serverName: string, prefix: McpToolPrefix): string {
133
141
  const serverPrefix = getServerPrefix(serverName, prefix);
134
- return serverPrefix ? `${serverPrefix}_${toolName}` : toolName;
142
+ const sanitized = toolName.replace(/\./g, "_");
143
+ // Some servers prefix their tool names with the server name (codegraph ->
144
+ // codegraph_explore). pi-mcp-adapter registers such a name unchanged, so
145
+ // keep the two sides in agreement instead of demanding codegraph_codegraph_explore.
146
+ if (serverPrefix && sanitized.startsWith(`${serverPrefix}_`) && sanitized.length > serverPrefix.length + 1) {
147
+ return sanitized;
148
+ }
149
+ return serverPrefix ? `${serverPrefix}_${sanitized}` : sanitized;
135
150
  }
136
151
 
137
152
  function isToolAllowed(
@@ -153,6 +168,7 @@ function toolNameCandidates(toolName: string, serverName: string, prefix: McpToo
153
168
  formatToolName(toolName, serverName, prefix),
154
169
  formatToolName(toolName, serverName, "server"),
155
170
  formatToolName(toolName, serverName, "short"),
171
+ formatToolName(toolName, serverName, "mcp"),
156
172
  formatToolName(toolName, serverName, "none"),
157
173
  ]);
158
174
  }
@@ -1,5 +1,5 @@
1
1
  import { splitKnownThinkingSuffix as splitThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
2
- import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
2
+ import { checkModelScope, SCOPED_PATTERN, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
3
3
 
4
4
  export type { AvailableModelInfo };
5
5
 
@@ -50,6 +50,23 @@ export function normalizeParentModel(model: unknown): ParentModel | undefined {
50
50
  return { provider: candidate.provider, id: candidate.id };
51
51
  }
52
52
 
53
+ /**
54
+ * Provider/id ids of the host session's scoped-model snapshot (`ctx.scopedModels`).
55
+ * Pi reports an empty set when the session is unscoped (nothing configured, or no
56
+ * pattern matched), and then allows every model; `scoped` narrows that to `inherit`.
57
+ */
58
+ export function scopedModelIdsFromContext(ctx: { scopedModels?: ReadonlyArray<{ model?: unknown }> }): string[] {
59
+ const scoped = ctx.scopedModels;
60
+ if (!Array.isArray(scoped)) return [];
61
+ const ids: string[] = [];
62
+ for (const entry of scoped) {
63
+ const model = entry?.model;
64
+ const normalized = normalizeParentModel(model);
65
+ if (normalized) ids.push(`${normalized.provider}/${normalized.id}`);
66
+ }
67
+ return ids;
68
+ }
69
+
53
70
  /**
54
71
  * Normalize a model id or provider segment for fuzzy comparison: case-fold,
55
72
  * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse
@@ -140,7 +157,12 @@ function resolveBaseModelCandidate(
140
157
  if (exactId) return exactId;
141
158
  }
142
159
 
143
- return fuzzyResolveModel(baseModel, availableModels, preferredProvider);
160
+ const fuzzy = fuzzyResolveModel(baseModel, availableModels, preferredProvider);
161
+ if (fuzzy || queryProvider === undefined) return fuzzy;
162
+ // Some catalogs (OpenRouter's `openrouter/auto-beta`) repeat the provider inside the id.
163
+ const queryId = normalizeModelSegment(baseModel);
164
+ const prefixedIdMatches = availableModels.filter((entry) => normalizeModelSegment(entry.id) === queryId && normalizeModelSegment(entry.provider) === queryProvider);
165
+ return prefixedIdMatches.length === 1 ? prefixedIdMatches[0]!.fullId : undefined;
144
166
  }
145
167
 
146
168
  /**
@@ -262,12 +284,15 @@ function configuredScopes(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | u
262
284
  return scope ? (Array.isArray(scope) ? scope : [scope]) : [];
263
285
  }
264
286
 
265
- function throwForUnresolvedEnforcedInheritScope(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined, includeMixed = false): void {
266
- const unresolvedInheritScope = configuredScopes(scope)
267
- .find((entry) => entry.enforce === true && (includeMixed ? entry.allow?.includes(INHERIT_MODEL) : entry.allow?.length === 1 && entry.allow[0] === INHERIT_MODEL));
268
- if (!unresolvedInheritScope) return;
269
- const origin = unresolvedInheritScope.origin ?? "modelScope";
270
- throw new Error(`Cannot enforce subagent model scope (${origin}): 'inherit' requires a current parent session model.`);
287
+ function throwForUnresolvedEnforcedReservedScope(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined, includeMixed = false): void {
288
+ const unresolvedReservedScope = configuredScopes(scope)
289
+ .find((entry) => entry.enforce === true && (includeMixed
290
+ ? entry.allow?.some((pattern) => pattern === INHERIT_MODEL || pattern === SCOPED_PATTERN)
291
+ : entry.allow?.length === 1 && (entry.allow[0] === INHERIT_MODEL || entry.allow[0] === SCOPED_PATTERN)));
292
+ if (!unresolvedReservedScope) return;
293
+ const origin = unresolvedReservedScope.origin ?? "modelScope";
294
+ const token = unresolvedReservedScope.allow?.includes(INHERIT_MODEL) ? INHERIT_MODEL : SCOPED_PATTERN;
295
+ throw new Error(`Cannot enforce subagent model scope (${origin}): '${token}' requires a current parent session model.`);
271
296
  }
272
297
 
273
298
  function enforceModelScopes(
@@ -311,7 +336,7 @@ export function resolveSubagentModelOverride(
311
336
  ): string | undefined {
312
337
  const trimmed = typeof requestedModel === "string" ? requestedModel.trim() : "";
313
338
  const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;
314
- if (!parentModel) throwForUnresolvedEnforcedInheritScope(options?.scope, explicit === undefined || options?.source === "inherited");
339
+ if (!parentModel) throwForUnresolvedEnforcedReservedScope(options?.scope, explicit === undefined || options?.source === "inherited");
315
340
  let resolved: string | undefined;
316
341
  let resolvedFromRegistry = explicit === undefined;
317
342
  if (explicit === undefined) {
@@ -402,7 +427,7 @@ export function resolveModelSelection(
402
427
  preferredProvider?: string,
403
428
  options?: ResolveModelSelectionOptions,
404
429
  ): ModelSelectionEvidence {
405
- if (!model) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
430
+ if (!model) throwForUnresolvedEnforcedReservedScope(options?.scope, true);
406
431
  const origin = options?.origin ?? (options?.primaryModelFromParent ? "inherited" : "configured");
407
432
  const requestedModel = origin === "inherited" ? undefined : model;
408
433
  const scopes = configuredScopes(options?.scope);
@@ -48,6 +48,10 @@ export interface ModelScopeViolation {
48
48
  origin: string;
49
49
  }
50
50
 
51
+ export const SCOPED_PATTERN = "scoped";
52
+
53
+ const MAX_RENDERED_PATTERNS = 8;
54
+
51
55
  function stripThinkingSuffix(model: string): string {
52
56
  return splitKnownThinkingSuffix(model).baseModel;
53
57
  }
@@ -86,6 +90,9 @@ export function checkModelScope(
86
90
  const baseModel = stripThinkingSuffix(model);
87
91
  const severity: ModelScopeViolation["severity"] = source === "explicit" || scope.strict === true ? "error" : "warn";
88
92
  const origin = scope.origin ?? "modelScope";
93
+ const rendered = allow.length <= MAX_RENDERED_PATTERNS
94
+ ? allow.join(", ")
95
+ : `${allow.slice(0, MAX_RENDERED_PATTERNS).join(", ")}, … (${allow.length} patterns total)`;
89
96
  return {
90
97
  model: baseModel,
91
98
  severity,
@@ -93,12 +100,22 @@ export function checkModelScope(
93
100
  origin,
94
101
  message:
95
102
  `Model '${baseModel}' is outside the configured subagent model scope (${origin}). ` +
96
- `Allowed patterns: ${allow.join(", ")}.`,
103
+ `Allowed patterns: ${rendered}.`,
97
104
  };
98
105
  }
99
106
 
100
- function expandInheritPattern(pattern: string, parentModel: { provider: string; id: string } | undefined): string {
101
- return pattern === "inherit" && parentModel ? `${parentModel.provider}/${parentModel.id}` : pattern;
107
+ /** An empty scoped snapshot degrades `scoped` to `inherit`; absent inputs stay literal so enforced resolution fails closed. */
108
+ function expandReservedPatterns(
109
+ pattern: string,
110
+ parentModel: { provider: string; id: string } | undefined,
111
+ scopedModelIds: readonly string[] | undefined,
112
+ ): string[] {
113
+ if (pattern === SCOPED_PATTERN) {
114
+ if (scopedModelIds?.length) return [...scopedModelIds];
115
+ return parentModel ? [`${parentModel.provider}/${parentModel.id}`] : [pattern];
116
+ }
117
+ if (pattern === "inherit") return parentModel ? [`${parentModel.provider}/${parentModel.id}`] : [pattern];
118
+ return [pattern];
102
119
  }
103
120
 
104
121
  function assertRecord(value: unknown, field: string, meta: { filePath: string }, expected = "an object"): Record<string, unknown> {
@@ -145,23 +162,25 @@ export function resolveModelScopesForAgent(
145
162
  config: ModelScopeConfig | undefined,
146
163
  agentName: string,
147
164
  parentModel: { provider: string; id: string } | undefined,
165
+ scopedModelIds?: readonly string[],
148
166
  ): ResolvedModelScope[] {
149
167
  if (!config) return [];
150
168
  const scopes: ResolvedModelScope[] = [];
151
169
  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)),
170
+ const globalScope: ResolvedModelScope = {
171
+ allow: config.allow.flatMap((pattern) => expandReservedPatterns(pattern, parentModel, scopedModelIds)),
156
172
  origin: "modelScope",
157
- });
173
+ };
174
+ if (config.enforce !== undefined) globalScope.enforce = config.enforce;
175
+ if (config.strict !== undefined) globalScope.strict = config.strict;
176
+ scopes.push(globalScope);
158
177
  }
159
178
  const agentScope = config.agents?.[agentName];
160
179
  if (agentScope?.allow) {
161
180
  scopes.push({
162
181
  enforce: agentScope.enforce ?? config.enforce,
163
182
  strict: agentScope.strict ?? config.strict,
164
- allow: agentScope.allow.map((pattern) => expandInheritPattern(pattern, parentModel)),
183
+ allow: agentScope.allow.flatMap((pattern) => expandReservedPatterns(pattern, parentModel, scopedModelIds)),
165
184
  origin: `modelScope.agents.${agentName}`,
166
185
  });
167
186
  }
@@ -634,6 +634,18 @@ export interface NestedRunMatch {
634
634
  run: NestedRunSummary;
635
635
  }
636
636
 
637
+ export function retainNestedLookupRoute(
638
+ state: Pick<SubagentState, "currentSessionId" | "retainedNestedLookupRoutes">,
639
+ route: NestedRouteInfo | undefined,
640
+ sessionId: string | undefined,
641
+ ): void {
642
+ if (!route || !sessionId || sessionId !== state.currentSessionId) return;
643
+ if (state.retainedNestedLookupRoutes?.sessionId !== sessionId) {
644
+ state.retainedNestedLookupRoutes = { sessionId, routes: new Map() };
645
+ }
646
+ state.retainedNestedLookupRoutes.routes.set(route.rootRunId, route);
647
+ }
648
+
637
649
  export interface NestedRunResolutionScope {
638
650
  routes: NestedRoute[];
639
651
  descendantOf?: { parentRunId: string; parentStepIndex?: number };
@@ -105,9 +105,10 @@ const VIEWER_SCRIPT = [
105
105
  "if(state==='escape'){if(char==='[')state='csi';else if(char===']')state='osc';else if(char==='P'||char==='X'||char==='^'||char==='_')state='string';else if(code<32||code>47)state='text';continue}",
106
106
  "if(state==='csi'){if(code>=64&&code<=126)state='text';continue}",
107
107
  "if(state==='osc'){if(code===7)state='text';else if(code===27)state='osc-escape';continue}",
108
- "if(state==='osc-escape'){state=char==='\\\\'?'text':code===27?'osc-escape':'osc';continue}",
108
+ "const BACKSLASH=String.fromCharCode(92);",
109
+ "if(state==='osc-escape'){state=char===BACKSLASH?'text':code===27?'osc-escape':'osc';continue}",
109
110
  "if(state==='string'){if(code===27)state='string-escape';continue}",
110
- "if(state==='string-escape')state=char==='\\\\'?'text':code===27?'string-escape':'string';",
111
+ "if(state==='string-escape')state=char===BACKSLASH?'text':code===27?'string-escape':'string';",
111
112
  "}return output}",
112
113
  "function write(buffer){const output=sanitize(decoder.write(buffer));if(output)process.stdout.write(output)}",
113
114
  "function pump(){",
@@ -53,13 +53,16 @@ export interface RunnerSubagentStep {
53
53
  tools?: string[];
54
54
  excludeTools?: string[];
55
55
  allowNestedSubagents?: boolean;
56
+ /** Resolved selected-agent policy for launches made by this child. */
57
+ allowedAgents?: string[];
56
58
  extensions?: string[];
57
59
  subagentOnlyExtensions?: string[];
58
60
  /** Private immutable host policy snapshot serialized to the native runner. */
59
61
  requiredExtensions?: import("../../shared/required-child-extensions.ts").RequiredChildExtensionSnapshot;
60
62
  mcpDirectTools?: string[];
63
+ /** The parent's resolution of `mcpDirectTools` against Pi's built-in MCP; the runner has no host to repeat it. */
64
+ builtinMcpTools?: import("./mcp-direct-tool-grant.ts").ResolvedMcpDirectToolSelection[];
61
65
  mutationTools?: string[];
62
- completionGuard?: boolean;
63
66
  sandbox?: string;
64
67
  permissionProfile?: string;
65
68
  systemPrompt?: string | null;
@@ -6,9 +6,7 @@ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
6
6
  export const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
7
7
  export const PI_SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
8
8
 
9
- export function findPiPackageRootFromEntry(
10
- entryPoint: string,
11
- ): string | undefined {
9
+ export function findPiPackageRootFromEntry(entryPoint: string): string | undefined {
12
10
  let dir = path.dirname(entryPoint);
13
11
  while (dir !== path.dirname(dir)) {
14
12
  const packageJsonPath = path.join(dir, "package.json");
@@ -2,7 +2,16 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { Message } from "@earendil-works/pi-ai";
4
4
  import type { OutputMode, SavedOutputReference } from "../../shared/types.ts";
5
- import { hasMutationToolCapability } from "./completion-guard.ts";
5
+
6
+ const READ_ONLY_OUTPUT_TOOLS = new Set([
7
+ "read", "grep", "find", "ls", "web_search", "fetch_content", "get_search_content",
8
+ "source_check", "intercom", "contact_supervisor", "structured_output", "watchdog_diff",
9
+ ]);
10
+
11
+ function hasOutputWriteCapability(tools: string[] | undefined, mcpDirectTools: string[] | undefined): boolean {
12
+ if ((mcpDirectTools?.length ?? 0) > 0 || tools === undefined) return true;
13
+ return tools.some((tool) => !READ_ONLY_OUTPUT_TOOLS.has(tool));
14
+ }
6
15
 
7
16
  export interface SingleOutputSnapshot {
8
17
  exists: boolean;
@@ -93,7 +102,7 @@ interface OutputInstructionCapabilities {
93
102
  }
94
103
 
95
104
  function formatOutputPathInstruction(outputPath: string, capabilities?: OutputInstructionCapabilities): string {
96
- const delivery = !capabilities || hasMutationToolCapability(capabilities.tools, capabilities.mcpDirectTools)
105
+ const delivery = !capabilities || hasOutputWriteCapability(capabilities.tools, capabilities.mcpDirectTools)
97
106
  ? `Write your findings to exactly this path: ${outputPath}`
98
107
  : [
99
108
  "Return the complete artifact in your final response.",
@@ -3,12 +3,81 @@ import { createRequire } from "node:module";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
+ import type { Message } from "@earendil-works/pi-ai";
6
7
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
7
8
  import type { JsonSchemaObject } from "../../shared/types.ts";
8
9
  import type { ResolvedAcceptanceReportMode } from "./acceptance.ts";
9
10
 
10
11
  export const MISSING_STRUCTURED_OUTPUT_CALL_ERROR = "Missing structured_output call; this step has outputSchema and must finish by calling structured_output.";
11
12
  export const MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR = "Missing acceptanceReport in structured_output call; acceptance.report is \"on\".";
13
+ export const STRUCTURED_OUTPUT_REJECTION_ERROR = "structured_output was invoked but no valid output was captured.";
14
+ export const INVALID_STRUCTURED_OUTPUT_SCHEMA_ERROR = "Structured output invocation was rejected: invalid outputSchema.";
15
+ export const STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE_ERROR = "Structured output invocation was rejected: validator unavailable.";
16
+ export const MAX_STRUCTURED_OUTPUT_REJECTION_ERROR_BYTES = 4096;
17
+
18
+ function utf8Prefix(value: string, maxBytes: number): string {
19
+ if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
20
+ const suffix = "...";
21
+ const contentLimit = maxBytes - Buffer.byteLength(suffix, "utf8");
22
+ let bytes = 0;
23
+ let result = "";
24
+ for (const character of value) {
25
+ const characterBytes = Buffer.byteLength(character, "utf8");
26
+ if (bytes + characterBytes > contentLimit) break;
27
+ result += character;
28
+ bytes += characterBytes;
29
+ }
30
+ return result + suffix;
31
+ }
32
+
33
+ function messageText(content: unknown): string {
34
+ if (typeof content === "string") return content;
35
+ if (!Array.isArray(content)) return "";
36
+ return content
37
+ .filter((part): part is { type: "text"; text: string } => Boolean(part) && typeof part === "object" && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string")
38
+ .map((part) => part.text)
39
+ .join("\n");
40
+ }
41
+
42
+ function sanitizeStructuredOutputRejection(text: string): string {
43
+ const withoutControls = text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "");
44
+ if (/invalid outputSchema(?:\s*:|$)/i.test(withoutControls)) return INVALID_STRUCTURED_OUTPUT_SCHEMA_ERROR;
45
+ if (/failed to validate structured output:|cannot load typebox\/compile/i.test(withoutControls)) return STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE_ERROR;
46
+ const validationMarker = "Structured output validation failed:";
47
+ const markerIndex = withoutControls.indexOf(validationMarker);
48
+ const diagnostic = markerIndex >= 0 ? withoutControls.slice(markerIndex) : withoutControls;
49
+ const lines = diagnostic.split(/\r?\n/).filter((line) => {
50
+ const trimmed = line.trim();
51
+ return trimmed.length > 0
52
+ && !/^at\s/.test(trimmed)
53
+ && !/^(?:arguments?|parameters?|submitted value|input|outputSchema|schema|stack)\s*:/i.test(trimmed);
54
+ });
55
+ const sanitized = lines.join("\n")
56
+ .replace(/\b(received|actual|got)(?:\s+value)?\s*[:=]\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\{[^\n]*\}|\[[^\n]*\]|\S+)/gi, "$1: [redacted]")
57
+ .trim();
58
+ return sanitized || STRUCTURED_OUTPUT_REJECTION_ERROR;
59
+ }
60
+
61
+ /** Returns bounded evidence from the latest failed structured_output result in a terminal transcript. */
62
+ export function formatStructuredOutputRejectionError(messages: readonly Message[]): string {
63
+ const toolCallIds = new Set<string>();
64
+ for (const message of messages) {
65
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
66
+ for (const part of message.content) {
67
+ const call = part as { type?: unknown; id?: unknown; name?: unknown };
68
+ if (call.type === "toolCall" && call.name === "structured_output" && typeof call.id === "string") toolCallIds.add(call.id);
69
+ }
70
+ }
71
+ for (let index = messages.length - 1; index >= 0; index--) {
72
+ const message = messages[index] as Message & { toolCallId?: unknown; toolName?: unknown; isError?: unknown };
73
+ if (message.role !== "toolResult" || message.isError !== true) continue;
74
+ const matchingName = message.toolName === "structured_output";
75
+ const matchingId = typeof message.toolCallId === "string" && toolCallIds.has(message.toolCallId);
76
+ if (!matchingName && !matchingId) continue;
77
+ return utf8Prefix(sanitizeStructuredOutputRejection(messageText(message.content)), MAX_STRUCTURED_OUTPUT_REJECTION_ERROR_BYTES);
78
+ }
79
+ return STRUCTURED_OUTPUT_REJECTION_ERROR;
80
+ }
12
81
 
13
82
  export interface StructuredOutputRuntime {
14
83
  schema: JsonSchemaObject;
@@ -75,7 +144,15 @@ export function createStructuredOutputToolParameters(schema: JsonSchemaObject, o
75
144
 
76
145
  interface CompiledJsonSchema {
77
146
  Check(value: unknown): boolean;
78
- Errors(value: unknown): Iterable<{ instancePath?: string; message?: string }>;
147
+ Errors(value: unknown): Iterable<JsonSchemaValidationError>;
148
+ }
149
+
150
+ interface JsonSchemaValidationError {
151
+ keyword?: string;
152
+ schemaPath?: string;
153
+ instancePath?: string;
154
+ params?: { failingKeyword?: string; requiredProperties?: string[] };
155
+ message?: string;
79
156
  }
80
157
 
81
158
  type CompileJsonSchema = (schema: unknown) => CompiledJsonSchema;
@@ -123,6 +200,142 @@ function loadCompile(): Promise<CompileJsonSchema> {
123
200
  return cachedCompile;
124
201
  }
125
202
 
203
+ function jsonPointerTarget(root: unknown, pointer: string): unknown {
204
+ if (pointer === "#") return root;
205
+ if (!pointer.startsWith("#/")) return undefined;
206
+ let current = root;
207
+ for (const encoded of pointer.slice(2).split("/")) {
208
+ if (!current || typeof current !== "object") return undefined;
209
+ const key = encoded.replace(/~1/g, "/").replace(/~0/g, "~");
210
+ current = (current as Record<string, unknown>)[key];
211
+ }
212
+ return current;
213
+ }
214
+
215
+ function resolveLocalRefs(root: unknown, node: unknown): Record<string, unknown> | undefined {
216
+ const seen = new Set<unknown>();
217
+ while (node && typeof node === "object" && !Array.isArray(node) && !seen.has(node)) {
218
+ seen.add(node);
219
+ const record = node as Record<string, unknown>;
220
+ if (typeof record.$ref !== "string" || !record.$ref.startsWith("#")) return record;
221
+ node = jsonPointerTarget(root, record.$ref);
222
+ }
223
+ return undefined;
224
+ }
225
+
226
+ type InstanceSchemaStep = { kind: "property"; key: string } | { kind: "index"; index: number };
227
+
228
+ function traverseInstanceSchema(root: unknown, instancePath: string | undefined): { node: Record<string, unknown>; steps: InstanceSchemaStep[] } | undefined {
229
+ let node = resolveLocalRefs(root, root);
230
+ const steps: InstanceSchemaStep[] = [];
231
+ for (const encoded of instancePath?.replace(/^\//, "").split("/") ?? []) {
232
+ if (!encoded || !node) continue;
233
+ const key = encoded.replace(/~1/g, "/").replace(/~0/g, "~");
234
+ const properties = node.properties;
235
+ if (properties && typeof properties === "object" && !Array.isArray(properties) && key in properties) {
236
+ steps.push({ kind: "property", key });
237
+ node = resolveLocalRefs(root, (properties as Record<string, unknown>)[key]);
238
+ continue;
239
+ }
240
+ if (/^(0|[1-9]\d*)$/.test(key)) {
241
+ const index = Number(key);
242
+ const prefixItems = node.prefixItems;
243
+ const itemSchema = Array.isArray(prefixItems) && index < prefixItems.length ? prefixItems[index] : node.items;
244
+ if (itemSchema !== undefined) {
245
+ steps.push({ kind: "index", index });
246
+ node = resolveLocalRefs(root, itemSchema);
247
+ continue;
248
+ }
249
+ }
250
+ return undefined;
251
+ }
252
+ return node ? { node, steps } : undefined;
253
+ }
254
+
255
+ function conditionalTarget(root: unknown, schemaPath: string, instancePath: string | undefined): { node: Record<string, unknown>; steps: InstanceSchemaStep[] } | undefined {
256
+ const traversed = traverseInstanceSchema(root, instancePath);
257
+ if (!traversed) return undefined;
258
+ let pointer = schemaPath;
259
+ const seen = new Set<string>();
260
+ while (!seen.has(pointer)) {
261
+ seen.add(pointer);
262
+ const record = resolveLocalRefs(root, jsonPointerTarget(root, pointer));
263
+ if (!record) break;
264
+ if (record.if !== undefined) return { node: record, steps: traversed.steps };
265
+ if (typeof record.$ref !== "string" || !record.$ref.startsWith("#")) break;
266
+ pointer = record.$ref;
267
+ }
268
+ if (traversed.node.if !== undefined) return traversed;
269
+ return undefined;
270
+ }
271
+
272
+ function errorKey(error: JsonSchemaValidationError): string {
273
+ return JSON.stringify([error.keyword, error.instancePath, error.params, error.message]);
274
+ }
275
+
276
+ function branchDiagnosticSchema(schema: JsonSchemaObject, steps: InstanceSchemaStep[], branch: unknown): JsonSchemaObject {
277
+ const diagnostic: Record<string, unknown> = {};
278
+ for (const keyword of ["$schema", "$id", "$defs", "definitions"] as const) {
279
+ if (schema[keyword] !== undefined) diagnostic[keyword] = schema[keyword];
280
+ }
281
+ let target = diagnostic;
282
+ for (const step of steps) {
283
+ if (step.kind === "index") {
284
+ const index = step.index;
285
+ const prefixItems = Array.from({ length: index + 1 }, () => true as unknown);
286
+ const nested: Record<string, unknown> = {};
287
+ prefixItems[index] = nested;
288
+ target.prefixItems = prefixItems;
289
+ target.items = true;
290
+ target = nested;
291
+ } else {
292
+ const nested: Record<string, unknown> = {};
293
+ target.properties = { [step.key]: nested };
294
+ target = nested;
295
+ }
296
+ }
297
+ target.allOf = [branch];
298
+ return diagnostic as JsonSchemaObject;
299
+ }
300
+
301
+ function expandConditionalError(compile: CompileJsonSchema, schema: JsonSchemaObject, value: unknown, error: JsonSchemaValidationError): { schema: JsonSchemaObject; errors: JsonSchemaValidationError[] } | undefined {
302
+ const branch = error.params?.failingKeyword;
303
+ if (error.keyword !== "if" || (branch !== "then" && branch !== "else") || !error.schemaPath) return undefined;
304
+ try {
305
+ const target = conditionalTarget(schema, error.schemaPath, error.instancePath);
306
+ if (!target || target.node[branch] === undefined) return undefined;
307
+ const expandedSchema = branchDiagnosticSchema(schema, target.steps, target.node[branch]);
308
+ const expandedErrors = [...compile(expandedSchema).Errors(value)];
309
+ if (expandedErrors.length === 0) return undefined;
310
+ return { schema: expandedSchema, errors: expandedErrors };
311
+ } catch {
312
+ return undefined;
313
+ }
314
+ }
315
+
316
+ function formatValidationError(error: JsonSchemaValidationError): string[] {
317
+ const pathText = error.instancePath ? error.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root";
318
+ if (error.keyword === "required" && error.params?.requiredProperties?.length) {
319
+ return error.params.requiredProperties.map((property) => `${pathText === "root" ? property : `${pathText}.${property}`}: is required`);
320
+ }
321
+ return [`${pathText}: ${error.message}`];
322
+ }
323
+
324
+ function expandedErrorMessages(compile: CompileJsonSchema, schema: JsonSchemaObject, value: unknown, error: JsonSchemaValidationError, limit: number, seen: Set<string>): string[] {
325
+ if (limit <= 0) return [];
326
+ const state = `${errorKey(error)}\0${JSON.stringify(schema)}`;
327
+ if (seen.has(state)) return formatValidationError(error).slice(0, limit);
328
+ seen.add(state);
329
+ const expanded = expandConditionalError(compile, schema, value, error);
330
+ if (!expanded) return formatValidationError(error).slice(0, limit);
331
+ const messages: string[] = [];
332
+ for (const candidate of expanded.errors) {
333
+ messages.push(...expandedErrorMessages(compile, expanded.schema, value, candidate, limit - messages.length, seen));
334
+ if (messages.length >= limit) break;
335
+ }
336
+ return messages;
337
+ }
338
+
126
339
  export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"): asserts schema is JsonSchemaObject {
127
340
  if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
128
341
  throw new Error(`${label} must be a JSON Schema object.`);
@@ -156,12 +369,19 @@ export async function validateStructuredOutputValue(schema: JsonSchemaObject, va
156
369
  return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
157
370
  }
158
371
  if (validator.Check(value)) return { status: "valid" };
159
- const errors = [...validator.Errors(value)]
160
- .slice(0, 8)
161
- .map((error) => {
162
- const pathText = error.instancePath ? error.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root";
163
- return `${pathText}: ${error.message}`;
164
- });
372
+ const originalErrors = [...validator.Errors(value)];
373
+ const errors: string[] = [];
374
+ const uniqueErrors = new Set<string>();
375
+ const seen = new Set<string>();
376
+ for (const error of originalErrors) {
377
+ for (const message of expandedErrorMessages(compile, schema, value, error, 8 - errors.length, seen)) {
378
+ if (!uniqueErrors.has(message)) {
379
+ uniqueErrors.add(message);
380
+ errors.push(message);
381
+ }
382
+ }
383
+ if (errors.length >= 8) break;
384
+ }
165
385
  return { status: "invalid", message: errors.join("; ") || "schema validation failed" };
166
386
  }
167
387
 
@@ -225,16 +225,6 @@ export function formatControlNudge(event: ControlEvent): string {
225
225
 
226
226
  export function formatControlNoticeMessage(event: ControlEvent, childIntercomTarget?: string): string {
227
227
  const runTarget = event.runId;
228
- if (event.reason === "completion_guard") {
229
- return [
230
- `Subagent failed: ${event.agent}`,
231
- `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
232
- `Signal: ${event.message}`,
233
- "Next: read the output artifact or session from the subagent result, then retry with a more explicit implementation prompt or handle the fix directly.",
234
- childIntercomTarget ? `Run intercom target (may be inactive): ${childIntercomTarget}` : undefined,
235
- ].filter((line): line is string => Boolean(line)).join("\n");
236
- }
237
-
238
228
  const nudgeMessage = formatControlNudge(event);
239
229
  const steerCommand = `subagent({ action: "steer", id: "${runTarget}", ${event.index !== undefined ? `index: ${event.index}, ` : ""}message: ${JSON.stringify(nudgeMessage)} })`;
240
230
  const nestedResumeCommand = `subagent({ action: "resume", id: "${runTarget}", message: ${JSON.stringify(nudgeMessage)} })`;
@@ -275,17 +265,13 @@ export function formatControlNoticeMessage(event: ControlEvent, childIntercomTar
275
265
  }
276
266
 
277
267
  export function formatControlIntercomMessage(event: ControlEvent, childIntercomTarget?: string): string {
278
- const statusLabel = event.reason === "completion_guard"
279
- ? "subagent failed"
280
- : event.type === "active_long_running"
268
+ const statusLabel = event.type === "active_long_running"
281
269
  ? "subagent active but long-running"
282
270
  : "subagent needs attention";
283
271
  return [
284
272
  statusLabel,
285
273
  "",
286
- event.reason === "completion_guard"
287
- ? `${event.agent} failed in run ${event.runId}.`
288
- : event.type === "active_long_running"
274
+ event.type === "active_long_running"
289
275
  ? `${event.agent} is still active but long-running in run ${event.runId}.`
290
276
  : `${event.agent} needs attention in run ${event.runId}.`,
291
277
  "",