@xzzpig/pi-subagents 0.16.0 → 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 (133) hide show
  1. package/CHANGELOG.md +164 -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 +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. package/src/runs/shared/task-intent.ts +0 -244
@@ -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 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
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) } : {}),
@@ -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 };
@@ -1009,7 +1021,7 @@ export function hasLiveNestedDescendants(children: NestedRunSummary[] | undefine
1009
1021
  }
1010
1022
 
1011
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 {
1012
- const sandbox = validateSandboxProfileNameOptional(status.sandbox);
1024
+ const sandbox = validateSandboxProfileNameOptional(status.sandbox);
1013
1025
  return {
1014
1026
  id: status.runId || fallback.id,
1015
1027
  parentRunId: fallback.parentRunId,
@@ -1020,7 +1032,7 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
1020
1032
  ...(status.pid ? { pid: status.pid } : {}),
1021
1033
  ...(status.sessionId ? { sessionId: status.sessionId } : {}),
1022
1034
  mode: status.mode ?? fallback.mode,
1023
- ...(sandbox ? { sandbox } : {}),
1035
+ ...(sandbox ? { sandbox } : {}),
1024
1036
  ...(status.steps?.length === 1 && status.steps[0]?.model ? { model: status.steps[0].model } : {}),
1025
1037
  ...(status.steps?.length === 1 && status.steps[0]?.thinking ? { thinking: status.steps[0].thinking } : {}),
1026
1038
  ...(status.steps?.length === 1 && status.steps[0]?.sessionName ? { sessionName: status.steps[0].sessionName } : {}),
@@ -1052,40 +1064,40 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
1052
1064
  ...(status.endedAt !== undefined ? { endedAt: status.endedAt } : {}),
1053
1065
  lastUpdate: status.lastUpdate ?? fallback.ts,
1054
1066
  ...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
1055
- ...(status.steps?.length ? {
1056
- steps: status.steps.map((step, index) => {
1057
- const stepSandbox = validateSandboxProfileNameOptional(step.sandbox);
1058
- return {
1059
- agent: step.agent,
1060
- ...(step.sessionName ? { sessionName: step.sessionName } : {}),
1061
- status: step.status,
1062
- ...(step.model ? { model: step.model } : {}),
1063
- ...(step.thinking ? { thinking: step.thinking } : {}),
1064
- ...(stepSandbox ? { sandbox: stepSandbox } : {}),
1065
- ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
1066
- ...(step.activityState ? { activityState: step.activityState } : {}),
1067
- ...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),
1068
- ...(step.currentTool ? { currentTool: step.currentTool } : {}),
1069
- ...(step.currentToolStartedAt !== undefined ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
1070
- ...(step.currentPath ? { currentPath: step.currentPath } : {}),
1071
- ...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),
1072
- ...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),
1073
- ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
1074
- ...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
1075
- ...(step.error ? { error: step.error } : {}),
1076
- ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
1077
- ...runtimeAcknowledgedEntry(step.runtimeAcknowledgedExtensions),
1078
- ...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),
1079
- ...(step.stopped !== undefined ? { stopped: step.stopped } : {}),
1080
- ...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),
1081
- ...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),
1082
- ...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),
1083
- ...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId || fallback.id, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${asyncDir}/status.json step ${index}`) } : {}),
1084
- ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
1085
- ...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),
1086
- };
1087
- }).slice(0, MAX_STEPS),
1088
- } : {}),
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
+ } : {}),
1089
1101
  };
1090
1102
  }
1091
1103
 
@@ -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,14 @@ 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[];
61
63
  mutationTools?: string[];
62
- completionGuard?: boolean;
63
64
  sandbox?: string;
64
65
  permissionProfile?: string;
65
66
  systemPrompt?: string | null;
@@ -5,20 +5,25 @@ 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";
8
9
 
9
10
  export function findPiPackageRootFromEntry(
10
11
  entryPoint: string,
12
+ deps: Pick<PiSpawnDeps, "platform" | "existsSync" | "readFileSync"> = {},
11
13
  ): string | undefined {
12
- let dir = path.dirname(entryPoint);
13
- while (dir !== path.dirname(dir)) {
14
- const packageJsonPath = path.join(dir, "package.json");
15
- if (fs.existsSync(packageJsonPath)) {
16
- const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
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 {
17
22
  name?: unknown;
18
23
  };
19
24
  if (pkg.name === PI_CODING_AGENT_PACKAGE) return dir;
20
25
  }
21
- dir = path.dirname(dir);
26
+ dir = pathApi.dirname(dir);
22
27
  }
23
28
  return undefined;
24
29
  }
@@ -59,6 +64,87 @@ export interface PiSpawnDeps {
59
64
  env?: NodeJS.ProcessEnv;
60
65
  }
61
66
 
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
+
62
148
  /** Compiled Pi's entrypoint is virtual; execPath is the real (possibly renamed) image. */
63
149
  export function resolveBunPiExecutable(deps: PiSpawnDeps = {}): string | undefined {
64
150
  const bunVersion = deps.bunVersion ?? process.versions.bun;
@@ -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