@xzzpig/pi-subagents 0.18.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 (95) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +18 -12
  4. package/docs/configuration.md +66 -9
  5. package/docs/extension-api.md +5 -4
  6. package/docs/missions.md +13 -13
  7. package/docs/models.md +2 -2
  8. package/docs/observability.md +2 -2
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +63 -86
  11. package/docs/workflows.md +170 -172
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +7 -0
  25. package/src/api/preflight.ts +67 -62
  26. package/src/extension/config.ts +12 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +68 -159
  32. package/src/extension/public-execution.ts +69 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +36 -133
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/runs/background/async-execution.ts +58 -53
  42. package/src/runs/background/async-job-tracker.ts +63 -22
  43. package/src/runs/background/async-retention.ts +46 -16
  44. package/src/runs/background/await-async-run.ts +76 -0
  45. package/src/runs/background/chain-root-attachment.ts +4 -4
  46. package/src/runs/background/control-channel.ts +18 -2
  47. package/src/runs/background/notify.ts +5 -0
  48. package/src/runs/background/run-child-session.ts +4 -1
  49. package/src/runs/background/run-status.ts +6 -0
  50. package/src/runs/background/runner-aliases.ts +30 -2
  51. package/src/runs/background/runner-child-launch.ts +3 -0
  52. package/src/runs/background/scheduled-runs.ts +5 -5
  53. package/src/runs/background/subagent-runner.ts +15 -1
  54. package/src/runs/foreground/async-stop-action.ts +17 -3
  55. package/src/runs/foreground/execution.ts +130 -125
  56. package/src/runs/foreground/subagent-executor.ts +487 -288
  57. package/src/runs/shared/async-status-projection.ts +5 -0
  58. package/src/runs/shared/child-launch.ts +15 -2
  59. package/src/runs/shared/child-session.ts +92 -6
  60. package/src/runs/shared/child-tool-plan.ts +15 -3
  61. package/src/runs/shared/dynamic-fanout.ts +1 -1
  62. package/src/runs/shared/mcp-config-sources.ts +2 -1
  63. package/src/runs/shared/mcp-direct-tool-allowlist.ts +103 -11
  64. package/src/runs/shared/model-resolution.ts +29 -9
  65. package/src/runs/shared/model-scope.ts +28 -9
  66. package/src/runs/shared/nested-events.ts +55 -55
  67. package/src/runs/shared/parallel-utils.ts +2 -0
  68. package/src/runs/shared/pi-spawn.ts +7 -95
  69. package/src/runs/shared/subagent-prompt-runtime.ts +2 -0
  70. package/src/runs/shared/worktree.ts +1 -1
  71. package/src/shared/disabled-features.ts +123 -0
  72. package/src/shared/extension-context.ts +13 -0
  73. package/src/shared/model-info.ts +9 -0
  74. package/src/shared/settings.ts +1 -1
  75. package/src/shared/types.ts +21 -0
  76. package/src/slash/prompt-template-bridge.ts +2 -2
  77. package/src/slash/slash-commands.ts +10 -5
  78. package/src/slash/subagents-admin.ts +24 -24
  79. package/src/tui/fleet-status.ts +14 -6
  80. package/src/tui/fleet.ts +14 -2
  81. package/src/tui/render.ts +113 -52
  82. package/src/tui/running-tone.ts +28 -0
  83. package/src/watchdog/diff-tool.ts +23 -9
  84. package/src/watchdog/register-child.ts +3 -3
  85. package/src/watchdog/register-main.ts +3 -3
  86. package/src/watchdog/review.ts +2 -2
  87. package/src/watchdog/turn-delta.ts +1 -1
  88. package/src/workflows/chat-progress.ts +2 -2
  89. package/src/workflows/scripted-workflow.ts +117 -37
  90. package/src/workflows/structured-workflow-scripts.ts +177 -0
  91. package/src/workflows/workflow-checklist.ts +6 -0
  92. package/src/workflows/workflow-receipt.ts +8 -2
  93. package/src/workflows/workflow-resources.ts +37 -12
  94. package/src/workflows/workflow-reuse.ts +120 -0
  95. package/src/workflows/workflow-revival.ts +123 -0
@@ -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
  }
@@ -138,17 +138,17 @@ export function resolveNestedRoute(route: NestedRoute): NestedRoute {
138
138
  const { rootRunId, capabilityToken } = route;
139
139
  validateRouteShape(route);
140
140
  const routeFile = path.join(commonRouteRoot(route), ROUTE_FILE);
141
- let metadata: { rootRunId?: unknown; capabilityToken?: unknown };
142
- try {
143
- const parsed: unknown = JSON.parse(fs.readFileSync(routeFile, "utf-8"));
144
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
145
- throw new Error("route metadata must be an object");
146
- }
147
- metadata = parsed as { rootRunId?: unknown; capabilityToken?: unknown };
148
- } catch (error) {
149
- const message = error instanceof Error ? error.message : String(error);
150
- throw new Error(`Nested event route metadata is unreadable: ${message}`);
151
- }
141
+ let metadata: { rootRunId?: unknown; capabilityToken?: unknown };
142
+ try {
143
+ const parsed: unknown = JSON.parse(fs.readFileSync(routeFile, "utf-8"));
144
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
145
+ throw new Error("route metadata must be an object");
146
+ }
147
+ metadata = parsed as { rootRunId?: unknown; capabilityToken?: unknown };
148
+ } catch (error) {
149
+ const message = error instanceof Error ? error.message : String(error);
150
+ throw new Error(`Nested event route metadata is unreadable: ${message}`);
151
+ }
152
152
  if (metadata.rootRunId !== rootRunId || metadata.capabilityToken !== capabilityToken) {
153
153
  throw new Error("Nested event route metadata does not match the provided root id and capability token.");
154
154
  }
@@ -315,16 +315,16 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
315
315
  : "pending";
316
316
  const model = stringValue(raw.model);
317
317
  const thinking = THINKING_LEVELS.find((level) => level === raw.thinking);
318
- const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
319
- const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
318
+ const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
319
+ const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
320
320
  return {
321
321
  agent,
322
322
  status,
323
323
  ...(model ? { model } : {}),
324
324
  ...(thinking ? { thinking } : {}),
325
325
  ...(stringValue(raw.sessionName, 256) ? { sessionName: stringValue(raw.sessionName, 256) } : {}),
326
- ...(sandbox ? { sandbox } : {}),
327
- ...(permissionProfile ? { permissionProfile } : {}),
326
+ ...(sandbox ? { sandbox } : {}),
327
+ ...(permissionProfile ? { permissionProfile } : {}),
328
328
  ...(stringValue(raw.sessionFile, 2048) ? { sessionFile: stringValue(raw.sessionFile, 2048) } : {}),
329
329
  ...(raw.activityState === "active_long_running" || raw.activityState === "needs_attention" ? { activityState: raw.activityState } : {}),
330
330
  ...(clampNumber(raw.lastActivityAt) !== undefined ? { lastActivityAt: clampNumber(raw.lastActivityAt) } : {}),
@@ -357,8 +357,8 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
357
357
  : undefined;
358
358
  const totalTokens = sanitizeTokenUsage(raw.totalTokens);
359
359
  const totalCost = sanitizeCost(raw.totalCost);
360
- const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
361
- const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
360
+ const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
361
+ const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
362
362
  return {
363
363
  id: raw.id,
364
364
  parentRunId: raw.parentRunId,
@@ -382,8 +382,8 @@ const permissionProfile = validatePermissionProfileNameOptional(raw.permissionPr
382
382
  ...(stringValue(raw.capabilityToken, 128) ? { capabilityToken: stringValue(raw.capabilityToken, 128) } : {}),
383
383
  ...(raw.mode === "single" || raw.mode === "parallel" || raw.mode === "chain" ? { mode: raw.mode } : {}),
384
384
  ...(stringValue(raw.agent, 128) ? { agent: stringValue(raw.agent, 128) } : {}),
385
- ...(sandbox ? { sandbox } : {}),
386
- ...(permissionProfile ? { permissionProfile } : {}),
385
+ ...(sandbox ? { sandbox } : {}),
386
+ ...(permissionProfile ? { permissionProfile } : {}),
387
387
  ...(Array.isArray(raw.agents) ? { agents: raw.agents.map((agent) => stringValue(agent, 128)).filter((agent): agent is string => Boolean(agent)).slice(0, MAX_STEPS) } : {}),
388
388
 
389
389
  ...(clampNumber(raw.currentStep) !== undefined ? { currentStep: clampNumber(raw.currentStep) } : {}),
@@ -1021,7 +1021,7 @@ export function hasLiveNestedDescendants(children: NestedRunSummary[] | undefine
1021
1021
  }
1022
1022
 
1023
1023
  export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: string, fallback: { id: string; parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }>; mode?: SubagentRunMode; ts: number }): NestedRunSummary {
1024
- const sandbox = validateSandboxProfileNameOptional(status.sandbox);
1024
+ const sandbox = validateSandboxProfileNameOptional(status.sandbox);
1025
1025
  return {
1026
1026
  id: status.runId || fallback.id,
1027
1027
  parentRunId: fallback.parentRunId,
@@ -1032,7 +1032,7 @@ const sandbox = validateSandboxProfileNameOptional(status.sandbox);
1032
1032
  ...(status.pid ? { pid: status.pid } : {}),
1033
1033
  ...(status.sessionId ? { sessionId: status.sessionId } : {}),
1034
1034
  mode: status.mode ?? fallback.mode,
1035
- ...(sandbox ? { sandbox } : {}),
1035
+ ...(sandbox ? { sandbox } : {}),
1036
1036
  ...(status.steps?.length === 1 && status.steps[0]?.model ? { model: status.steps[0].model } : {}),
1037
1037
  ...(status.steps?.length === 1 && status.steps[0]?.thinking ? { thinking: status.steps[0].thinking } : {}),
1038
1038
  ...(status.steps?.length === 1 && status.steps[0]?.sessionName ? { sessionName: status.steps[0].sessionName } : {}),
@@ -1064,40 +1064,40 @@ const sandbox = validateSandboxProfileNameOptional(status.sandbox);
1064
1064
  ...(status.endedAt !== undefined ? { endedAt: status.endedAt } : {}),
1065
1065
  lastUpdate: status.lastUpdate ?? fallback.ts,
1066
1066
  ...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
1067
- ...(status.steps?.length ? {
1068
- steps: status.steps.map((step, index) => {
1069
- const stepSandbox = validateSandboxProfileNameOptional(step.sandbox);
1070
- return {
1071
- agent: step.agent,
1072
- ...(step.sessionName ? { sessionName: step.sessionName } : {}),
1073
- status: step.status,
1074
- ...(step.model ? { model: step.model } : {}),
1075
- ...(step.thinking ? { thinking: step.thinking } : {}),
1076
- ...(stepSandbox ? { sandbox: stepSandbox } : {}),
1077
- ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
1078
- ...(step.activityState ? { activityState: step.activityState } : {}),
1079
- ...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),
1080
- ...(step.currentTool ? { currentTool: step.currentTool } : {}),
1081
- ...(step.currentToolStartedAt !== undefined ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
1082
- ...(step.currentPath ? { currentPath: step.currentPath } : {}),
1083
- ...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),
1084
- ...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),
1085
- ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
1086
- ...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
1087
- ...(step.error ? { error: step.error } : {}),
1088
- ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
1089
- ...runtimeAcknowledgedEntry(step.runtimeAcknowledgedExtensions),
1090
- ...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),
1091
- ...(step.stopped !== undefined ? { stopped: step.stopped } : {}),
1092
- ...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),
1093
- ...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),
1094
- ...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),
1095
- ...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId || fallback.id, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${asyncDir}/status.json step ${index}`) } : {}),
1096
- ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
1097
- ...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),
1098
- };
1099
- }).slice(0, MAX_STEPS),
1100
- } : {}),
1067
+ ...(status.steps?.length ? {
1068
+ steps: status.steps.map((step, index) => {
1069
+ const stepSandbox = validateSandboxProfileNameOptional(step.sandbox);
1070
+ return {
1071
+ agent: step.agent,
1072
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
1073
+ status: step.status,
1074
+ ...(step.model ? { model: step.model } : {}),
1075
+ ...(step.thinking ? { thinking: step.thinking } : {}),
1076
+ ...(stepSandbox ? { sandbox: stepSandbox } : {}),
1077
+ ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
1078
+ ...(step.activityState ? { activityState: step.activityState } : {}),
1079
+ ...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),
1080
+ ...(step.currentTool ? { currentTool: step.currentTool } : {}),
1081
+ ...(step.currentToolStartedAt !== undefined ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
1082
+ ...(step.currentPath ? { currentPath: step.currentPath } : {}),
1083
+ ...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),
1084
+ ...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),
1085
+ ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
1086
+ ...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
1087
+ ...(step.error ? { error: step.error } : {}),
1088
+ ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
1089
+ ...runtimeAcknowledgedEntry(step.runtimeAcknowledgedExtensions),
1090
+ ...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),
1091
+ ...(step.stopped !== undefined ? { stopped: step.stopped } : {}),
1092
+ ...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),
1093
+ ...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),
1094
+ ...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),
1095
+ ...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId || fallback.id, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${asyncDir}/status.json step ${index}`) } : {}),
1096
+ ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
1097
+ ...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),
1098
+ };
1099
+ }).slice(0, MAX_STEPS),
1100
+ } : {}),
1101
1101
  };
1102
1102
  }
1103
1103
 
@@ -60,6 +60,8 @@ export interface RunnerSubagentStep {
60
60
  /** Private immutable host policy snapshot serialized to the native runner. */
61
61
  requiredExtensions?: import("../../shared/required-child-extensions.ts").RequiredChildExtensionSnapshot;
62
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[];
63
65
  mutationTools?: string[];
64
66
  sandbox?: string;
65
67
  permissionProfile?: string;
@@ -5,25 +5,18 @@ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
5
5
 
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
- export const PI_PACKAGE_DIR_ENV = "PI_PACKAGE_DIR";
9
8
 
10
- export function findPiPackageRootFromEntry(
11
- entryPoint: string,
12
- deps: Pick<PiSpawnDeps, "platform" | "existsSync" | "readFileSync"> = {},
13
- ): string | undefined {
14
- const pathApi = (deps.platform ?? process.platform) === "win32" ? path.win32 : path.posix;
15
- const existsSync = deps.existsSync ?? fs.existsSync;
16
- const readFileSync = deps.readFileSync ?? ((filePath, encoding) => fs.readFileSync(filePath, encoding));
17
- let dir = pathApi.dirname(entryPoint);
18
- while (dir !== pathApi.dirname(dir)) {
19
- const packageJsonPath = pathApi.join(dir, "package.json");
20
- if (existsSync(packageJsonPath)) {
21
- const pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as {
9
+ export function findPiPackageRootFromEntry(entryPoint: string): string | undefined {
10
+ let dir = path.dirname(entryPoint);
11
+ while (dir !== path.dirname(dir)) {
12
+ const packageJsonPath = path.join(dir, "package.json");
13
+ if (fs.existsSync(packageJsonPath)) {
14
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
22
15
  name?: unknown;
23
16
  };
24
17
  if (pkg.name === PI_CODING_AGENT_PACKAGE) return dir;
25
18
  }
26
- dir = pathApi.dirname(dir);
19
+ dir = path.dirname(dir);
27
20
  }
28
21
  return undefined;
29
22
  }
@@ -64,87 +57,6 @@ export interface PiSpawnDeps {
64
57
  env?: NodeJS.ProcessEnv;
65
58
  }
66
59
 
67
- export type RunningPiPackageRoot =
68
- | { root: string; source: "argv" | "PI_PACKAGE_DIR" | "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT" | "bun-adjacent" | "bun-share" }
69
- | { reason: string };
70
-
71
- function validateRunningPiRoot(
72
- root: string,
73
- source: Exclude<RunningPiPackageRoot, { reason: string }>["source"],
74
- readFileSync: (filePath: string, encoding: "utf-8") => string,
75
- manifestPath: string,
76
- ): RunningPiPackageRoot {
77
- const sourceLabel = source === "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT" ? `${source} override` : source;
78
- let parsed: unknown;
79
- try {
80
- parsed = JSON.parse(readFileSync(manifestPath, "utf-8"));
81
- } catch (error) {
82
- const message = error instanceof Error ? error.message : String(error);
83
- return { reason: `Could not read a valid Pi package manifest at ${manifestPath} (${sourceLabel}): ${message}` };
84
- }
85
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || (parsed as { name?: unknown }).name !== PI_CODING_AGENT_PACKAGE) {
86
- return { reason: `${manifestPath} is not ${PI_CODING_AGENT_PACKAGE} (${sourceLabel})` };
87
- }
88
- return { root, source };
89
- }
90
-
91
- /** Resolve only package roots that can be attributed to the process that owns this session. */
92
- export function resolveRunningPiPackageRoot(deps: PiSpawnDeps = {}): RunningPiPackageRoot | undefined {
93
- const env = deps.env ?? process.env;
94
- const platform = deps.platform ?? process.platform;
95
- const pathApi = platform === "win32" ? path.win32 : path.posix;
96
- const argv1 = deps.argv1 ?? process.argv[1];
97
- const readFileSync = deps.readFileSync ?? ((filePath, encoding) => fs.readFileSync(filePath, encoding));
98
- const existsSync = deps.existsSync ?? fs.existsSync;
99
- const realpathSync = deps.realpathSync ?? fs.realpathSync;
100
-
101
- if (argv1) {
102
- let entry: string | undefined;
103
- try {
104
- entry = realpathSync(argv1);
105
- } catch {
106
- // Virtual Bun entries and non-filesystem launchers continue to explicit host evidence.
107
- }
108
- if (entry) {
109
- try {
110
- const root = findPiPackageRootFromEntry(entry, { platform, existsSync, readFileSync });
111
- if (root) return { root, source: "argv" };
112
- } catch (error) {
113
- return { reason: `Could not inspect the running Pi entry at ${entry}: ${error instanceof Error ? error.message : String(error)}` };
114
- }
115
- }
116
- }
117
-
118
- for (const [source, value] of [
119
- [PI_PACKAGE_DIR_ENV, env[PI_PACKAGE_DIR_ENV]],
120
- [PI_CODING_AGENT_PACKAGE_ROOT_ENV, env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]],
121
- ] as const) {
122
- const root = value?.trim();
123
- if (root) return validateRunningPiRoot(root, source, readFileSync, pathApi.join(root, "package.json"));
124
- }
125
-
126
- const bunVersion = deps.bunVersion ?? process.versions.bun;
127
- if (!bunVersion || !argv1 || !/^(?:\/\$bunfs\/|B:[\\/]~BUN[\\/])/.test(argv1)) return undefined;
128
- const imagePath = deps.execPath ?? process.execPath;
129
- let canonicalImage = imagePath;
130
- try {
131
- canonicalImage = realpathSync(imagePath);
132
- } catch {
133
- // A validated adjacent manifest can still establish ownership when canonicalization is unavailable.
134
- }
135
- const imageDir = pathApi.dirname(canonicalImage);
136
- const candidates = [
137
- { root: imageDir, source: "bun-adjacent" as const },
138
- { root: pathApi.resolve(imageDir, "..", "share", "pi-coding-agent"), source: "bun-share" as const },
139
- ];
140
- for (const candidate of candidates) {
141
- const manifestPath = pathApi.join(candidate.root, "package.json");
142
- if (!existsSync(manifestPath)) continue;
143
- return validateRunningPiRoot(candidate.root, candidate.source, readFileSync, manifestPath);
144
- }
145
- return undefined;
146
- }
147
-
148
60
  /** Compiled Pi's entrypoint is virtual; execPath is the real (possibly renamed) image. */
149
61
  export function resolveBunPiExecutable(deps: PiSpawnDeps = {}): string | undefined {
150
62
  const bunVersion = deps.bunVersion ?? process.versions.bun;
@@ -22,6 +22,7 @@ import { captureWatchdogDiffBaseline, createWatchdogDiffTool, WATCHDOG_DIFF_TOOL
22
22
  import { inheritedNestedRouteOf } from "./nested-events.ts";
23
23
  import { registerWaitTool } from "../background/wait-tool.ts";
24
24
  import { drainOutstandingWork } from "../background/auto-drain.ts";
25
+ import { MODEL_ONLY_TOOL } from "../../shared/extension-context.ts";
25
26
  import {
26
27
  childSupervisorMetadata,
27
28
  evaluateChildToolDiagnostic,
@@ -417,6 +418,7 @@ function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<
417
418
  }) => void;
418
419
  registerTool({
419
420
  name: "structured_output",
421
+ ...MODEL_ONLY_TOOL,
420
422
  label: "Structured Output",
421
423
  description: "Submit the required final structured output for this subagent step. This terminates the step.",
422
424
  parameters,
@@ -20,7 +20,7 @@ const WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
20
20
  const WORKTREE_COMMAND_OUTPUT_MAX_BYTES = 128 * 1024;
21
21
  const WORKTRUNK_COMMAND = process.platform === "win32" ? "git" : "wt";
22
22
  const WORKTRUNK_ARG_PREFIX = process.platform === "win32" ? ["wt"] : [];
23
- export const MACHINE_DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--default-prefix", "--line-prefix=", "--no-relative"] as const;
23
+ export const MACHINE_DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", "--line-prefix=", "--no-relative"] as const;
24
24
  const MACHINE_PATCH_OPTIONS = [...MACHINE_DIFF_OPTIONS, "--binary"] as const;
25
25
  const PATCH_VALIDATION_OPTIONS = ["apply", "--check", "--cached", "--reverse", "--binary", "--whitespace=nowarn"] as const;
26
26
 
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Opt-in feature groups an operator can remove from the parent-facing `subagent` tool.
3
+ * Groups own parameters and actions that enabled features do not need, so hiding them
4
+ * cannot remove a field that enabled behavior still needs. `preflight` is the one shared
5
+ * parameter: it is script-only, so `workflow-scripts` removes it too. Per-call options
6
+ * disable only the per-call override; configured defaults keep applying.
7
+ */
8
+ export const SUBAGENT_FEATURES = {
9
+ "agent-management": {
10
+ actions: ["create", "update", "delete", "eject", "disable", "enable", "reset", "refine", "refine.show", "refine.rollback"],
11
+ params: ["config"],
12
+ },
13
+ watchdog: {
14
+ actions: ["watchdog.status", "watchdog.check", "watchdog.configure", "watchdog.recommend-model"],
15
+ params: ["scope", "target", "thinking"],
16
+ },
17
+ panes: {
18
+ actions: ["inspector.open", "inspector.command", "inspector.status", "inspector.close", "project.open", "project.status", "project.close"],
19
+ params: ["focus"],
20
+ },
21
+ missions: {
22
+ actions: ["mission.create", "mission.list", "mission.show", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close"],
23
+ params: ["mission", "missionUpdate", "missionStatus", "missionScope", "missionId", "runMode", "runStatus", "summary"],
24
+ },
25
+ "lane-management": {
26
+ actions: ["lane.status", "lane.recordMerge", "lane.recordSupersession", "worktree.discard", "worktree.cleanup"],
27
+ params: ["handoffPath", "laneId", "merge", "supersession", "repo", "planId"],
28
+ },
29
+ "spawn-budget-grants": { actions: ["grant-spawn-budget"], params: ["additional"] },
30
+ preflight: { actions: [], params: ["preflight"] },
31
+ "lane-metadata": { actions: [], params: ["lane"] },
32
+ gates: { actions: [], params: ["gate"] },
33
+ "usage-budgets": { actions: [], params: ["usageBudget"] },
34
+ "tool-budgets": { actions: [], params: ["toolBudget"] },
35
+ "control-overrides": { actions: [], params: ["control"] },
36
+ "extension-bindings": { actions: [], params: ["extensionBindings"] },
37
+ "external-machines": { actions: [], params: ["machine"] },
38
+ "workflow-scripts": { actions: ["validate"], params: ["workflow", "args", "preflight", "globalConcurrencyLimit", "maxSubagentSpawnsPerRun"] },
39
+ } as const satisfies Record<string, { actions: readonly string[]; params: readonly string[] }>;
40
+
41
+ export type SubagentFeature = keyof typeof SUBAGENT_FEATURES;
42
+
43
+ /** Schedules are turned off by `scheduledRuns.enabled: false`, not by `disabledFeatures`. */
44
+ export type SubagentSurfaceFeature = SubagentFeature | "schedules";
45
+
46
+ const SCHEDULE_SURFACE = {
47
+ actions: ["schedule.create", "schedule.list", "schedule.show", "schedule.history", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"],
48
+ params: ["name", "at", "every", "sessionOnly", "quiet", "on", "timezone", "overlap", "catchUp"],
49
+ } as const;
50
+
51
+ export function validateDisabledFeatures(value: unknown): void {
52
+ if (value === undefined) return;
53
+ if (!Array.isArray(value)) throw new Error("config.disabledFeatures must be an array of feature names");
54
+ const seen = new Set<string>();
55
+ for (const entry of value) {
56
+ if (entry === "schedules") throw new Error(`config.disabledFeatures does not accept "schedules"; set config.scheduledRuns.enabled to false instead`);
57
+ if (typeof entry !== "string" || !Object.hasOwn(SUBAGENT_FEATURES, entry)) {
58
+ throw new Error(`config.disabledFeatures entry ${JSON.stringify(entry)} is not one of: ${Object.keys(SUBAGENT_FEATURES).join(", ")}`);
59
+ }
60
+ if (seen.has(entry)) throw new Error(`config.disabledFeatures lists "${entry}" more than once`);
61
+ seen.add(entry);
62
+ }
63
+ }
64
+
65
+ /** Disabled features, and each disabled parameter and action mapped to the setting that disabled it. */
66
+ export interface DisabledFeatureSurface {
67
+ features: ReadonlySet<SubagentSurfaceFeature>;
68
+ params: ReadonlyMap<string, string>;
69
+ actions: ReadonlyMap<string, string>;
70
+ }
71
+
72
+ interface FeatureConfig {
73
+ disabledFeatures?: readonly SubagentFeature[];
74
+ scheduledRuns?: { enabled?: boolean };
75
+ }
76
+
77
+ function featureSurface(feature: SubagentSurfaceFeature): { actions: readonly string[]; params: readonly string[]; disabledBy: string } {
78
+ if (feature === "schedules") return { ...SCHEDULE_SURFACE, disabledBy: "scheduledRuns.enabled=false" };
79
+ return { ...SUBAGENT_FEATURES[feature], disabledBy: `disabledFeatures "${feature}"` };
80
+ }
81
+
82
+ export function resolveDisabledFeatureSurface(config: FeatureConfig): DisabledFeatureSurface {
83
+ const features = new Set<SubagentSurfaceFeature>(config.disabledFeatures);
84
+ if (config.scheduledRuns?.enabled === false) features.add("schedules");
85
+ const params = new Map<string, string>();
86
+ const actions = new Map<string, string>();
87
+ for (const feature of features) {
88
+ const surface = featureSurface(feature);
89
+ // A parameter shared with workflow-scripts is always attributed to workflow-scripts,
90
+ // whatever order the config lists the features in.
91
+ for (const param of surface.params) if (feature === "workflow-scripts" || !params.has(param)) params.set(param, surface.disabledBy);
92
+ for (const action of surface.actions) actions.set(action, surface.disabledBy);
93
+ }
94
+ return { features, params, actions };
95
+ }
96
+
97
+ /** Returns why a request uses a disabled feature, or undefined when every requested field is enabled. */
98
+ export function disabledFeatureUseError(request: object, surface: DisabledFeatureSurface, label = "subagent"): string | undefined {
99
+ const params = request as Record<string, unknown>;
100
+ const action = typeof params.action === "string" ? params.action.trim() : undefined;
101
+ const disabledAction = action === undefined ? undefined : surface.actions.get(action);
102
+ if (disabledAction) return `${label} action '${action}' is disabled by config ${disabledAction}.`;
103
+ for (const [param, disabledBy] of surface.params) {
104
+ if (params[param] !== undefined) return `${label} option '${param}' is disabled by config ${disabledBy}.`;
105
+ }
106
+ // workflowScript is the internal carrier for slash, prompt-workflow, RPC, and scheduled scripts.
107
+ // Callers check the original request, before the package lowers chain/tasks into its own script.
108
+ if (params.workflowScript !== undefined && surface.features.has("workflow-scripts")) {
109
+ return `${label} workflow scripts are disabled by config ${featureSurface("workflow-scripts").disabledBy}.`;
110
+ }
111
+ return undefined;
112
+ }
113
+
114
+ /** Lists what config disabled, for prepending to static reference docs that describe the full tool. */
115
+ export function disabledFeatureNotice(surface: DisabledFeatureSurface): string | undefined {
116
+ if (surface.features.size === 0) return undefined;
117
+ const lines = [...surface.features].map((feature) => {
118
+ const { actions, params, disabledBy } = featureSurface(feature);
119
+ const parts = [`options ${params.join(", ")}`, ...(actions.length > 0 ? [`actions ${actions.join(", ")}`] : [])];
120
+ return `- ${disabledBy}: ${parts.join("; ")}`;
121
+ });
122
+ return `Disabled by config in this session. The reference below still lists these, but calls that use them are rejected:\n${lines.join("\n")}`;
123
+ }
@@ -1,11 +1,24 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
+ /**
4
+ * Declares a tool to the model but keeps it out of codemode scripts and other `ctx.executeTool()`
5
+ * callers. These tools need model-issued calls: nested calls hide their progress, block the script
6
+ * on supervisor replies, and drop `terminate`. Pi 0.99 reads `exposure`; the pinned SDK types
7
+ * predate it and older hosts ignore it.
8
+ */
9
+ export const MODEL_ONLY_TOOL = { exposure: "model-only" } as const;
10
+
3
11
  /** Pi exposes replaced extension contexts as ordinary Errors without a stable code. */
4
12
  export function isStaleExtensionContextError(error: unknown): boolean {
5
13
  return error instanceof Error
6
14
  && /extension ctx is stale|extension context no longer active|stale after session replacement or reload/i.test(error.message);
7
15
  }
8
16
 
17
+ /** Pi throws this from action methods while extensions are still loading, before it binds the runtime. */
18
+ export function isUnboundExtensionRuntimeError(error: unknown): boolean {
19
+ return error instanceof Error && /extension runtime not initialized/i.test(error.message);
20
+ }
21
+
9
22
  /** Run a synchronous operation against a cached UI context without leaking replacement errors. */
10
23
  export function withCachedUiContext<T>(
11
24
  ctx: ExtensionContext | null | undefined,
@@ -60,6 +60,15 @@ export function resolveEffectiveThinking(model: string | undefined, configThinki
60
60
  return THINKING_LEVELS.find((level) => level === configThinking);
61
61
  }
62
62
 
63
+ /** The recorded thinking level of one child: the first known level among the places it is recorded. */
64
+ export function childThinkingLevel(...sources: Array<{ thinking?: string } | undefined>): ThinkingLevel | undefined {
65
+ for (const source of sources) {
66
+ const level = THINKING_LEVELS.find((candidate) => candidate === source?.thinking);
67
+ if (level) return level;
68
+ }
69
+ return undefined;
70
+ }
71
+
63
72
  export function splitKnownThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {
64
73
  const colonIdx = model.lastIndexOf(":");
65
74
  if (colonIdx === -1) return { baseModel: model, thinkingSuffix: "" };
@@ -46,7 +46,7 @@ export interface SequentialStep {
46
46
  acceptance?: AcceptanceInput;
47
47
  agentContract?: AgentContract;
48
48
  gateOn?: ChainGateLayer;
49
- /** Internal workflow child isolation; public workflowScript supplies this on runs.run. */
49
+ /** Internal workflow child isolation; public workflow scripts supply this on runs.run. */
50
50
  worktree?: boolean;
51
51
  }
52
52