@xzzpig/pi-subagents 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +13 -4
  2. package/README.md +1 -1
  3. package/agents/reviewer.md +12 -2
  4. package/docs/agents.md +4 -4
  5. package/docs/configuration.md +6 -6
  6. package/docs/extension-api.md +14 -4
  7. package/docs/models.md +47 -6
  8. package/docs/observability.md +14 -3
  9. package/docs/tool-reference.md +21 -6
  10. package/docs/workflows.md +7 -1
  11. package/index.ts +10 -1
  12. package/package.json +3 -3
  13. package/prompts/council.md +19 -7
  14. package/prompts/parallel-review.md +5 -1
  15. package/prompts/review-loop.md +9 -5
  16. package/skills/council-mode/SKILL.md +50 -26
  17. package/skills/pi-subagents/SKILL.md +5 -1
  18. package/skills/pi-subagents/references/constraints-and-recipes.md +16 -1
  19. package/skills/pi-subagents/references/execution-controls.md +13 -4
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -3
  21. package/skills/pi-subagents/references/prompting-and-roles.md +14 -7
  22. package/src/agents/agent-management.ts +115 -14
  23. package/src/agents/agent-serializer.ts +4 -2
  24. package/src/agents/agents.ts +226 -48
  25. package/src/api/external-job-provider.ts +10 -1
  26. package/src/api/preflight.ts +52 -19
  27. package/src/api/project-panes.ts +2 -0
  28. package/src/extension/doctor.ts +10 -0
  29. package/src/extension/fanout-child.ts +3 -2
  30. package/src/extension/index.ts +24 -4
  31. package/src/extension/public-execution.ts +12 -9
  32. package/src/extension/rpc.ts +77 -3
  33. package/src/extension/schemas.ts +7 -1
  34. package/src/extension/tool-description.ts +9 -6
  35. package/src/extension/tool-result.ts +19 -0
  36. package/src/inspectors/herdr/client.ts +3 -3
  37. package/src/inspectors/herdr/focus.ts +55 -0
  38. package/src/inspectors/herdr/project-panes.ts +228 -44
  39. package/src/integrations/herdr-status.ts +26 -4
  40. package/src/runs/background/async-execution.ts +146 -17
  41. package/src/runs/background/async-job-tracker.ts +33 -14
  42. package/src/runs/background/async-resume.ts +23 -2
  43. package/src/runs/background/async-retention.ts +1 -1
  44. package/src/runs/background/async-status.ts +10 -0
  45. package/src/runs/background/chain-root-attachment.ts +5 -0
  46. package/src/runs/background/control-channel.ts +98 -10
  47. package/src/runs/background/notify.ts +62 -1
  48. package/src/runs/background/result-watcher.ts +4 -3
  49. package/src/runs/background/run-status.ts +15 -1
  50. package/src/runs/background/stale-run-reconciler.ts +3 -0
  51. package/src/runs/background/subagent-runner.ts +333 -48
  52. package/src/runs/background/wait-completions.ts +2 -0
  53. package/src/runs/background/wait-tool.ts +4 -3
  54. package/src/runs/foreground/async-stop-action.ts +23 -2
  55. package/src/runs/foreground/execution.ts +148 -13
  56. package/src/runs/foreground/foreground-history.ts +3 -2
  57. package/src/runs/foreground/subagent-executor.ts +417 -50
  58. package/src/runs/foreground/workflow-detach-reconcile.ts +18 -6
  59. package/src/runs/shared/acceptance.ts +11 -5
  60. package/src/runs/shared/agent-contract.ts +1 -1
  61. package/src/runs/shared/child-identity.ts +36 -0
  62. package/src/runs/shared/completion-guard.ts +52 -2
  63. package/src/runs/shared/dynamic-fanout.ts +1 -1
  64. package/src/runs/shared/extension-bindings.ts +78 -0
  65. package/src/runs/shared/external-cli-runner.ts +2 -0
  66. package/src/runs/shared/external-job-bridge.ts +53 -37
  67. package/src/runs/shared/external-job-runner.ts +126 -23
  68. package/src/runs/shared/fast-mode-extension.ts +10 -0
  69. package/src/runs/shared/model-exclusions.ts +2 -1
  70. package/src/runs/shared/model-fallback.ts +48 -22
  71. package/src/runs/shared/model-scope.ts +106 -39
  72. package/src/runs/shared/mutation-evidence.ts +145 -0
  73. package/src/runs/shared/orca-progress-tabs.ts +71 -9
  74. package/src/runs/shared/parallel-utils.ts +15 -0
  75. package/src/runs/shared/pi-args.ts +78 -1
  76. package/src/runs/shared/structured-output.ts +18 -4
  77. package/src/runs/shared/subagent-prompt-runtime.ts +48 -15
  78. package/src/runs/shared/tool-availability.ts +1 -3
  79. package/src/shared/launch-contract.ts +12 -5
  80. package/src/shared/settings.ts +6 -1
  81. package/src/shared/thinking-ceiling.ts +52 -0
  82. package/src/shared/types.ts +120 -5
  83. package/src/tui/fleet-status.ts +66 -13
  84. package/src/tui/render.ts +5 -4
  85. package/src/watchdog/permission-arbiter.ts +59 -52
  86. package/src/workflows/scripted-workflow.ts +156 -12
@@ -23,13 +23,16 @@ function cloneWorkflowStatus(status: AsyncStatus): AsyncStatus {
23
23
  };
24
24
  }
25
25
 
26
- function childSucceeded(result: Pick<SingleResult, "exitCode" | "error">): boolean {
27
- return result.exitCode === 0 && !result.error;
26
+ function childSucceeded(result: Pick<SingleResult, "exitCode" | "error" | "interrupted">): boolean {
27
+ return result.exitCode === 0 && !result.error && !result.interrupted;
28
28
  }
29
29
 
30
+ const UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION = "unsupported-continuation: detached workflow child settled, but JavaScript workflow continuation was not persisted. Resume the workflow explicitly instead of treating the completed child as top-level workflow completion.";
31
+ const INTERRUPTED_DETACHED_CHILD = "Interrupted. Waiting for explicit next action.";
32
+
30
33
  export function applyDetachedChildToPausedWorkflow(
31
34
  status: AsyncStatus,
32
- input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "sessionFile">; workflowKey?: string },
35
+ input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "interrupted" | "sessionFile">; workflowKey?: string },
33
36
  ): AsyncStatus | undefined {
34
37
  if (status.mode !== "workflow" || status.state !== "paused") return undefined;
35
38
  const next = cloneWorkflowStatus(status);
@@ -37,6 +40,7 @@ export function applyDetachedChildToPausedWorkflow(
37
40
  ?? (input.workflowKey ? next.steps?.find((candidate) => candidate.workflowKey === input.workflowKey) : undefined);
38
41
  if (!step) return undefined;
39
42
  const succeeded = childSucceeded(input.result);
43
+ const failedSiblingError = next.steps?.find((candidate) => candidate !== step && candidate.status === "failed" && candidate.error)?.error;
40
44
  const updatedAt = Date.now();
41
45
  step.status = succeeded ? "completed" : "failed";
42
46
  step.endedAt = updatedAt;
@@ -45,10 +49,12 @@ export function applyDetachedChildToPausedWorkflow(
45
49
  delete step.currentToolStartedAt;
46
50
  if (input.result.sessionFile) step.sessionFile = input.result.sessionFile;
47
51
  if (succeeded) delete step.error;
52
+ else if (input.result.interrupted) step.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
48
53
  else if (input.result.error) step.error = input.result.error;
49
54
  next.lastUpdate = updatedAt;
50
55
  const promoted = promotePausedWorkflowIfSettled(next);
51
- if (promoted?.state === "failed" && input.result.error) promoted.error = input.result.error;
56
+ if (promoted?.state === "failed" && input.result.interrupted && !failedSiblingError) promoted.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
57
+ else if (promoted?.state === "failed" && input.result.error) promoted.error = input.result.error;
52
58
  return promoted ?? next;
53
59
  }
54
60
 
@@ -63,10 +69,11 @@ export function promotePausedWorkflowIfSettled(status: AsyncStatus): AsyncStatus
63
69
  const failed = next.steps.some((candidate) => candidate.status === "failed");
64
70
  const updatedAt = Date.now();
65
71
  next.lastUpdate = updatedAt;
66
- next.state = failed ? "failed" : "complete";
72
+ next.state = "failed";
67
73
  next.endedAt = updatedAt;
68
74
  delete next.activityState;
69
- if (!failed) delete next.error;
75
+ if (failed) return next;
76
+ next.error = UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION;
70
77
  return next;
71
78
  }
72
79
 
@@ -83,6 +90,7 @@ function workflowResultChildren(status: AsyncStatus, childRunId: string, result:
83
90
  output,
84
91
  outputState: output.trim() ? "present" : "absent",
85
92
  detached: undefined,
93
+ ...(result.interrupted ? { interrupted: true } : {}),
86
94
  ...(result.error ? { error: result.error } : {}),
87
95
  };
88
96
  });
@@ -94,6 +102,7 @@ function workflowResultChildren(status: AsyncStatus, childRunId: string, result:
94
102
  success: step.status === "completed" || step.status === "complete",
95
103
  output: step.runId === childRunId ? output : "",
96
104
  outputState: step.runId === childRunId && output.trim() ? "present" : "absent",
105
+ ...(step.runId === childRunId && result.interrupted ? { interrupted: true } : {}),
97
106
  ...(step.error ? { error: step.error } : {}),
98
107
  }));
99
108
  }
@@ -119,6 +128,7 @@ function publishedWorkflowResult(status: AsyncStatus, childRunId: string, result
119
128
  timestamp: Date.now(),
120
129
  results: workflowResultChildren(status, childRunId, result, existing?.results),
121
130
  workflow: status.workflow,
131
+ reconciledFromDetachedChild: childRunId,
122
132
  ...(receipt ? { workflowReceipt: { path: path.join(asyncDir, "workflow-receipt.json"), receipt } } : {}),
123
133
  asyncDir,
124
134
  cwd: status.cwd,
@@ -252,6 +262,8 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
252
262
  success: next.state === "complete",
253
263
  state: next.state,
254
264
  summary: typeof published.summary === "string" ? published.summary : (next.state === "complete" ? "Workflow completed." : next.error),
265
+ reconciledFromDetachedChild: input.childRunId,
266
+ ...(Array.isArray(published.results) ? { results: published.results } : {}),
255
267
  sessionId: next.sessionId,
256
268
  completionOwnerId: next.completionOwnerId,
257
269
  timestamp: Date.now(),
@@ -404,7 +404,7 @@ function acceptanceRequiresChildReport(acceptance: ResolvedAcceptanceConfig): bo
404
404
  return acceptance.criteria.length > 0 || acceptance.evidence.length > 0;
405
405
  }
406
406
 
407
- export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, options: { reportOptional?: boolean } = {}): string {
407
+ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, options: { reportOptional?: boolean; structuredOutput?: boolean } = {}): string {
408
408
  if (acceptance.level === "none") return "";
409
409
  if (options.reportOptional && !acceptanceRequiresChildReport(acceptance)) return "";
410
410
  const lines = [
@@ -431,13 +431,15 @@ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, opt
431
431
  }
432
432
  lines.push(
433
433
  "",
434
- "Finish with a fenced JSON block tagged `acceptance-report` in this shape:",
434
+ options.structuredOutput
435
+ ? "Include an `acceptanceReport` object in your final `structured_output` tool call in this shape:"
436
+ : "Finish with a fenced JSON block tagged `acceptance-report` in this shape:",
435
437
  "Use empty arrays when no items apply; array fields contain strings unless object entries are shown.",
436
438
  "Empty-string entries (`[\"\"]`) are ignored; use `[]` when nothing applies.",
437
439
  "`criteriaSatisfied[].status` must be exactly one of: satisfied, not-satisfied, not-applicable.",
438
440
  "`commandsRun[].result` must be exactly one of: passed, failed, not-run.",
439
441
  "`manualNotes` and `notes` are optional strings; an empty string means no note and does not satisfy `manual-notes` evidence.",
440
- "```acceptance-report",
442
+ ...(options.structuredOutput ? [] : ["```acceptance-report"]),
441
443
  JSON.stringify({
442
444
  criteriaSatisfied: acceptance.criteria
443
445
  .filter((criterion) => criterion.severity !== "recommended")
@@ -452,7 +454,7 @@ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, opt
452
454
  reviewFindings: ["blocker: file.ts:12 - issue found, or no blockers"],
453
455
  manualNotes: "anything else the parent should know",
454
456
  }, null, 2),
455
- "```",
457
+ ...(options.structuredOutput ? [] : ["```"]),
456
458
  );
457
459
  return lines.join("\n");
458
460
  }
@@ -959,6 +961,7 @@ function checkNoStagedFiles(cwd: string): AcceptanceRuntimeCheck {
959
961
  function runStructuralChecks(acceptance: ResolvedAcceptanceConfig, report: AcceptanceReport, cwd: string): AcceptanceRuntimeCheck[] {
960
962
  const checks: AcceptanceRuntimeCheck[] = [];
961
963
  for (const kind of acceptance.evidence) {
964
+ if (kind === "no-staged-files" && report.noStagedFiles === undefined) continue;
962
965
  const status = reportEvidenceStatus(report, kind);
963
966
  checks.push({
964
967
  id: `evidence:${kind}`,
@@ -1271,6 +1274,7 @@ export async function evaluateAcceptance(input: {
1271
1274
  */
1272
1275
  fileOutput?: { content: string; path: string; authoritative?: boolean };
1273
1276
  report?: AcceptanceReport;
1277
+ reportError?: string;
1274
1278
  reviewResult?: AcceptanceReviewResult;
1275
1279
  signal?: AbortSignal;
1276
1280
  abortMessage?: string;
@@ -1292,7 +1296,9 @@ export async function evaluateAcceptance(input: {
1292
1296
  };
1293
1297
  if (acceptance.level === "none") return ledger;
1294
1298
 
1295
- const parsed = input.report
1299
+ const parsed = input.reportError
1300
+ ? { error: input.reportError }
1301
+ : input.report
1296
1302
  ? (() => {
1297
1303
  const validation = validateAcceptanceReport(input.report);
1298
1304
  return validation.report
@@ -12,7 +12,7 @@ export function buildExecutionProjection(result: Pick<SingleResult, "exitCode" |
12
12
  return { status: "stopped", success: false, exitCode: result.exitCode, stopped: true, ...(result.error ? { error: result.error } : {}) };
13
13
  }
14
14
  if (result.interrupted) {
15
- return { status: "paused", success: true, exitCode: result.exitCode, interrupted: true, ...(result.error ? { error: result.error } : {}) };
15
+ return { status: "paused", success: false, exitCode: result.exitCode, interrupted: true, ...(result.error ? { error: result.error } : {}) };
16
16
  }
17
17
  const success = result.exitCode === 0 && !result.error && !result.timedOut;
18
18
  return {
@@ -0,0 +1,36 @@
1
+ import type { AsyncStatus } from "../../shared/types.ts";
2
+
3
+ export type AsyncStatusStep = NonNullable<AsyncStatus["steps"]>[number];
4
+
5
+ export interface ResolvedAsyncStatusChild {
6
+ index: number;
7
+ step: AsyncStatusStep;
8
+ id: string;
9
+ }
10
+
11
+ export type AsyncStatusChildResolution =
12
+ | { ok: true; child: ResolvedAsyncStatusChild }
13
+ | { ok: false; code: "not_found" | "ambiguous"; message: string };
14
+
15
+ export function asyncStatusChildIdentity(step: AsyncStatusStep, index: number): string {
16
+ return step.workflowKey ?? step.runId ?? `step:${index}`;
17
+ }
18
+
19
+ export function asyncStatusChildIdentityCandidates(step: AsyncStatusStep, index: number): string[] {
20
+ return [...new Set([step.workflowKey, step.runId, `step:${index}`].filter((value): value is string => typeof value === "string" && value.length > 0))];
21
+ }
22
+
23
+ export function resolveAsyncStatusChild(status: Pick<AsyncStatus, "runId" | "steps">, childId: string): AsyncStatusChildResolution {
24
+ const matches: ResolvedAsyncStatusChild[] = [];
25
+ for (const [index, step] of (status.steps ?? []).entries()) {
26
+ if (!asyncStatusChildIdentityCandidates(step, index).includes(childId)) continue;
27
+ matches.push({ index, step, id: asyncStatusChildIdentity(step, index) });
28
+ }
29
+ if (matches.length === 1) return { ok: true, child: matches[0]! };
30
+ if (matches.length > 1) return { ok: false, code: "ambiguous", message: `Child '${childId}' is ambiguous under async run '${status.runId}'.` };
31
+ return { ok: false, code: "not_found", message: `Child '${childId}' was not found under async run '${status.runId}'.` };
32
+ }
33
+
34
+ export function isStoppableAsyncStatusStep(step: AsyncStatusStep): boolean {
35
+ return step.status === "pending" || step.status === "running";
36
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Message } from "@earendil-works/pi-ai";
2
+ import type { AcceptanceRole, TrackedMutationEvidence } from "../../shared/types.ts";
2
3
  import { isMutatingTool } from "./long-running-guard.ts";
3
- import { expectsImplementationMutation } from "./task-intent.ts";
4
+ import { classifyTaskMutationIntent, expectsImplementationMutation, taskMayMutate } from "./task-intent.ts";
4
5
 
5
6
  export { expectsImplementationMutation };
6
7
 
@@ -14,6 +15,7 @@ const READ_ONLY_BUILTIN_TOOLS = new Set([
14
15
  "get_search_content",
15
16
  "intercom",
16
17
  "contact_supervisor",
18
+ "structured_output",
17
19
  ]);
18
20
 
19
21
  // Cursor native edit/write often land as thinking traces (inactive_trace /
@@ -45,12 +47,16 @@ interface CompletionMutationGuardInput {
45
47
  messages: Message[];
46
48
  tools?: string[];
47
49
  mcpDirectTools?: string[];
50
+ toolAvailabilityError?: string;
51
+ mutationEvidence?: TrackedMutationEvidence;
48
52
  }
49
53
 
50
54
  interface CompletionMutationGuardResult {
51
55
  expectedMutation: boolean;
52
56
  attemptedMutation: boolean;
53
57
  triggered: boolean;
58
+ blocked: boolean;
59
+ message?: string;
54
60
  }
55
61
 
56
62
  interface ReportSentence {
@@ -64,6 +70,40 @@ export function hasMutationToolCapability(tools: string[] | undefined, mcpDirect
64
70
  return !tools.every((tool) => READ_ONLY_BUILTIN_TOOLS.has(tool));
65
71
  }
66
72
 
73
+ function hasBuiltinMutationTool(tools: string[] | undefined): boolean {
74
+ return tools === undefined || tools.some((tool) => !READ_ONLY_BUILTIN_TOOLS.has(tool));
75
+ }
76
+
77
+ function isWriterRole(agent: string, acceptanceRole: AcceptanceRole | undefined): boolean {
78
+ return acceptanceRole === "writer"
79
+ || (acceptanceRole === undefined && /\bworker\b/i.test(agent));
80
+ }
81
+
82
+ const WRITER_DELIVERY_PATTERN = /\b(?:address|resolve|work)\s+(?:backlog\s+)?(?:item|issue)\b|\b(?:land|ship)\s+(?:the\s+)?(?:change|changes|fix|feature|implementation)\b/i;
83
+
84
+ export function validateImplementationToolContract(input: {
85
+ agent: string;
86
+ task: string;
87
+ tools?: string[];
88
+ mcpDirectTools?: string[];
89
+ configuredExtensions?: string[];
90
+ requestedTools?: string[];
91
+ acceptanceRole?: AcceptanceRole;
92
+ completionGuard?: boolean;
93
+ }): string | undefined {
94
+ if (input.completionGuard === false) return undefined;
95
+ const requestedMutationTools = input.requestedTools?.filter((tool) => !READ_ONLY_BUILTIN_TOOLS.has(tool)) ?? [];
96
+ const declaredMutationToolsWereRemoved = requestedMutationTools.length > 0 && !hasBuiltinMutationTool(input.tools);
97
+ const configuredExtensionCapability = (input.configuredExtensions?.length ?? 0) > 0 && !declaredMutationToolsWereRemoved;
98
+ if (hasMutationToolCapability(input.tools, input.mcpDirectTools) || configuredExtensionCapability) return undefined;
99
+ const intent = classifyTaskMutationIntent(input.agent, input.task);
100
+ if (intent.kind === "read-only") return undefined;
101
+ const writerTaskMayMutate = isWriterRole(input.agent, input.acceptanceRole)
102
+ && (taskMayMutate(input.task) || WRITER_DELIVERY_PATTERN.test(input.task));
103
+ if (intent.kind !== "implementation" && !writerTaskMayMutate && !declaredMutationToolsWereRemoved) return undefined;
104
+ return `Agent '${input.agent}' was given an implementation task, but its tool allowlist has no mutation-capable tools. Add bash, edit, write, or another mutation-capable tool to the agent, or use a read-only task/agent.`;
105
+ }
106
+
67
107
  function hasCheckpointMutationEvidence(message: Message): boolean {
68
108
  const record = message as unknown as {
69
109
  role?: string;
@@ -187,15 +227,25 @@ function reportsNoBetterChallengeChange(messages: Message[]): boolean {
187
227
  }
188
228
 
189
229
  export function evaluateCompletionMutationGuard(input: CompletionMutationGuardInput): CompletionMutationGuardResult {
230
+ if (input.toolAvailabilityError && expectsImplementationMutation(input.agent, input.task)) {
231
+ return {
232
+ expectedMutation: true,
233
+ attemptedMutation: false,
234
+ triggered: false,
235
+ blocked: true,
236
+ message: input.toolAvailabilityError,
237
+ };
238
+ }
190
239
  const expectedMutation = hasMutationToolCapability(input.tools, input.mcpDirectTools)
191
240
  ? expectsImplementationMutation(input.agent, input.task)
192
241
  : false;
193
- const attemptedMutation = hasMutationToolCall(input.messages);
242
+ const attemptedMutation = hasMutationToolCall(input.messages) || input.mutationEvidence?.attemptedMutation === true;
194
243
  const noEditChallengeComplete = isImplementationChallengeTask(input.task)
195
244
  && reportsNoBetterChallengeChange(input.messages);
196
245
  return {
197
246
  expectedMutation,
198
247
  attemptedMutation,
199
248
  triggered: expectedMutation && !attemptedMutation && !noEditChallengeComplete,
249
+ blocked: false,
200
250
  };
201
251
  }
@@ -46,7 +46,7 @@ const DYNAMIC_STEP_KEYS = new Set(["expand", "parallel", "collect", "concurrency
46
46
  const RUNNER_DYNAMIC_STEP_KEYS = new Set([...DYNAMIC_STEP_KEYS, "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "sessionFiles", "thinkingOverrides"]);
47
47
  const DYNAMIC_EXPAND_KEYS = new Set(["from", "item", "key", "maxItems", "onEmpty"]);
48
48
  const DYNAMIC_EXPAND_FROM_KEYS = new Set(["output", "path"]);
49
- const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outputSchema", "cwd", "output", "outputMode", "reads", "progress", "skill", "model", "toolBudget", "acceptance", "agentContract", "gateOn"]);
49
+ const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outputSchema", "cwd", "output", "outputMode", "reads", "progress", "skill", "model", "fast", "toolBudget", "acceptance", "agentContract", "gateOn"]);
50
50
  const RUNNER_DYNAMIC_PARALLEL_KEYS = new Set([
51
51
  ...DYNAMIC_PARALLEL_KEYS,
52
52
  "outputName", "structured", "inheritProjectContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled",
@@ -0,0 +1,78 @@
1
+ export const PI_SUBAGENT_EXTENSION_BINDINGS_ENV = "PI_SUBAGENT_EXTENSION_BINDINGS";
2
+ export const MAX_EXTENSION_BINDING_NAMESPACES = 16;
3
+ export const MAX_EXTENSION_BINDINGS_BYTES = 16 * 1024;
4
+ export const MAX_EXTENSION_BINDINGS_DEPTH = 16;
5
+ export const MAX_EXTENSION_BINDINGS_PROPERTIES = 256;
6
+
7
+ const EXTENSION_BINDING_NAMESPACE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62})\/[1-9][0-9]{0,8}$/;
8
+
9
+ export type ExtensionBindingJson = null | boolean | number | string | ReadonlyArray<ExtensionBindingJson> | { readonly [key: string]: ExtensionBindingJson };
10
+ export type ExtensionBindings = Readonly<Record<string, ExtensionBindingJson>>;
11
+
12
+ export interface NormalizedExtensionBindings {
13
+ value: ExtensionBindings;
14
+ json: string;
15
+ }
16
+
17
+ function canonicalizeJson(value: unknown, path: string, depth: number, seen: Set<object>, propertyCount: { value: number }): ExtensionBindingJson {
18
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
19
+ if (typeof value === "number") {
20
+ if (!Number.isFinite(value)) throw new Error(`${path} must contain only finite JSON numbers.`);
21
+ return value;
22
+ }
23
+ if (typeof value !== "object") throw new Error(`${path} must contain only plain JSON values.`);
24
+ if (depth > MAX_EXTENSION_BINDINGS_DEPTH) throw new Error(`${path} exceeds the maximum nesting depth of ${MAX_EXTENSION_BINDINGS_DEPTH}.`);
25
+ if (seen.has(value)) throw new Error(`${path} must not contain cycles.`);
26
+ seen.add(value);
27
+ try {
28
+ if (Array.isArray(value)) {
29
+ const output: ExtensionBindingJson[] = [];
30
+ for (let index = 0; index < value.length; index++) {
31
+ if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(`${path} must not contain sparse arrays.`);
32
+ output.push(canonicalizeJson(value[index], `${path}[${index}]`, depth + 1, seen, propertyCount));
33
+ }
34
+ return Object.freeze(output);
35
+ }
36
+ const prototype = Object.getPrototypeOf(value);
37
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${path} must contain only plain JSON objects.`);
38
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path} must not contain symbol keys.`);
39
+ const descriptors = Object.getOwnPropertyDescriptors(value);
40
+ const output: Record<string, ExtensionBindingJson> = {};
41
+ for (const key of Object.keys(descriptors).sort()) {
42
+ const descriptor = descriptors[key]!;
43
+ if (!descriptor.enumerable || !("value" in descriptor)) throw new Error(`${path}.${key} must be an enumerable data property.`);
44
+ propertyCount.value += 1;
45
+ if (propertyCount.value > MAX_EXTENSION_BINDINGS_PROPERTIES) throw new Error(`extensionBindings exceeds ${MAX_EXTENSION_BINDINGS_PROPERTIES} total properties.`);
46
+ Object.defineProperty(output, key, { value: canonicalizeJson(descriptor.value, `${path}.${key}`, depth + 1, seen, propertyCount), enumerable: true, writable: false, configurable: false });
47
+ }
48
+ return Object.freeze(output);
49
+ } finally {
50
+ seen.delete(value);
51
+ }
52
+ }
53
+
54
+ export function normalizeExtensionBindings(input: unknown): NormalizedExtensionBindings | undefined {
55
+ if (input === undefined) return undefined;
56
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("extensionBindings must be a plain JSON object.");
57
+ const prototype = Object.getPrototypeOf(input);
58
+ if (prototype !== Object.prototype && prototype !== null) throw new Error("extensionBindings must be a plain JSON object.");
59
+ const keys = Object.keys(input);
60
+ if (keys.length > MAX_EXTENSION_BINDING_NAMESPACES) throw new Error(`extensionBindings supports at most ${MAX_EXTENSION_BINDING_NAMESPACES} namespaces.`);
61
+ for (const key of keys) {
62
+ if (!EXTENSION_BINDING_NAMESPACE.test(key)) throw new Error(`extensionBindings namespace '${key}' must use a package-like name followed by '/<positive-version>'.`);
63
+ }
64
+ const value = canonicalizeJson(input, "extensionBindings", 0, new Set(), { value: 0 }) as ExtensionBindings;
65
+ const json = JSON.stringify(value);
66
+ const bytes = Buffer.byteLength(json, "utf8");
67
+ if (bytes > MAX_EXTENSION_BINDINGS_BYTES) throw new Error(`extensionBindings canonical JSON is ${bytes} bytes; maximum is ${MAX_EXTENSION_BINDINGS_BYTES}.`);
68
+ return { value, json };
69
+ }
70
+
71
+ export function encodeExtensionBindings(input: ExtensionBindings | undefined): string | undefined {
72
+ return input === undefined ? undefined : normalizeExtensionBindings(input)!.json;
73
+ }
74
+
75
+ export function omitExtensionBindingsEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
76
+ const { [PI_SUBAGENT_EXTENSION_BINDINGS_ENV]: _extensionBindings, ...sanitized } = env;
77
+ return sanitized;
78
+ }
@@ -4,6 +4,7 @@ import * as path from "node:path";
4
4
  import { finished } from "node:stream/promises";
5
5
  import { trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
6
6
  import type { ExternalProcessStatus } from "../../shared/types.ts";
7
+ import { omitExtensionBindingsEnv } from "./extension-bindings.ts";
7
8
 
8
9
  const HARD_KILL_DELAY_MS = 2_000;
9
10
  const MAX_OUTPUT_TAIL_BYTES = 64 * 1024;
@@ -54,6 +55,7 @@ export function runExternalCli(input: {
54
55
  let hardKillTimer: NodeJS.Timeout | undefined;
55
56
  const child = spawn(input.command, input.args ?? [], {
56
57
  cwd: input.cwd,
58
+ env: omitExtensionBindingsEnv(process.env),
57
59
  stdio: ["pipe", "pipe", "pipe"],
58
60
  shell: false,
59
61
  windowsHide: true,
@@ -11,6 +11,7 @@ import {
11
11
  type ExternalJobHandle,
12
12
  type ExternalJobOperation,
13
13
  type ExternalJobResult,
14
+ type ExternalJobFollowUpInput,
14
15
  type ExternalJobStartInput,
15
16
  } from "../../api/external-job-provider.ts";
16
17
 
@@ -26,6 +27,7 @@ interface ExternalJobBridgeRequest {
26
27
  provider: string;
27
28
  providerJobId?: string;
28
29
  start?: ExternalJobStartInput;
30
+ followUp?: ExternalJobFollowUpInput;
29
31
  createdAt: number;
30
32
  claimedAt?: number;
31
33
  }
@@ -72,32 +74,36 @@ function requestPath(asyncDir: string, id: string): string {
72
74
  return path.join(requestDir(asyncDir), `${id}.json`);
73
75
  }
74
76
 
75
- function startClaimDir(asyncDir: string, id: string): string {
77
+ function isDispatchOperation(operation: ExternalJobOperation): boolean {
78
+ return operation === "start" || operation === "follow-up";
79
+ }
80
+
81
+ function dispatchClaimDir(asyncDir: string, id: string): string {
76
82
  return path.join(requestDir(asyncDir), `${id}.claim`);
77
83
  }
78
84
 
79
- function startClaimTempDir(asyncDir: string, id: string): string {
85
+ function dispatchClaimTempDir(asyncDir: string, id: string): string {
80
86
  return path.join(requestDir(asyncDir), `${id}.claim.tmp-${randomUUID()}`);
81
87
  }
82
88
 
83
- function startClaimCompletedPath(claimDir: string): string {
89
+ function dispatchClaimCompletedPath(claimDir: string): string {
84
90
  return path.join(claimDir, "completed.json");
85
91
  }
86
92
 
87
- function startClaimHandlePath(claimDir: string): string {
93
+ function dispatchClaimHandlePath(claimDir: string): string {
88
94
  return path.join(claimDir, "handle.json");
89
95
  }
90
96
 
91
- function completedStartClaimExists(asyncDir: string, id: string): boolean {
92
- return fs.existsSync(startClaimCompletedPath(startClaimDir(asyncDir, id)));
97
+ function completedDispatchClaimExists(asyncDir: string, id: string): boolean {
98
+ return fs.existsSync(dispatchClaimCompletedPath(dispatchClaimDir(asyncDir, id)));
93
99
  }
94
100
 
95
- function cancelStartRequest(asyncDir: string, request: ExternalJobBridgeRequest): boolean {
96
- const claimDir = startClaimDir(asyncDir, request.id);
97
- const tempClaimDir = startClaimTempDir(asyncDir, request.id);
101
+ function cancelDispatchRequest(asyncDir: string, request: ExternalJobBridgeRequest): boolean {
102
+ const claimDir = dispatchClaimDir(asyncDir, request.id);
103
+ const tempClaimDir = dispatchClaimTempDir(asyncDir, request.id);
98
104
  try {
99
105
  fs.mkdirSync(tempClaimDir);
100
- writeAtomicJson(startClaimCompletedPath(tempClaimDir), { completedAt: Date.now() });
106
+ writeAtomicJson(dispatchClaimCompletedPath(tempClaimDir), { completedAt: Date.now() });
101
107
  fs.renameSync(tempClaimDir, claimDir);
102
108
  } catch (error) {
103
109
  fs.rmSync(tempClaimDir, { recursive: true, force: true });
@@ -190,12 +196,14 @@ function assertRequest(value: unknown, filePath: string): ExternalJobBridgeReque
190
196
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`External-job bridge request '${filePath}' must be an object.`);
191
197
  const request = value as ExternalJobBridgeRequest;
192
198
  if (typeof request.id !== "string" || !request.id) throw new Error(`External-job bridge request '${filePath}' has invalid id.`);
193
- if (request.operation !== "start" && request.operation !== "status" && request.operation !== "result" && request.operation !== "reattach") throw new Error(`External-job bridge request '${filePath}' has invalid operation.`);
199
+ if (request.operation !== "start" && request.operation !== "follow-up" && request.operation !== "status" && request.operation !== "result" && request.operation !== "reattach") throw new Error(`External-job bridge request '${filePath}' has invalid operation.`);
194
200
  if (typeof request.provider !== "string" || !request.provider.trim()) throw new Error(`External-job bridge request '${filePath}' has invalid provider.`);
195
201
  if (typeof request.createdAt !== "number") throw new Error(`External-job bridge request '${filePath}' has invalid createdAt.`);
196
202
  if (request.claimedAt !== undefined && typeof request.claimedAt !== "number") throw new Error(`External-job bridge request '${filePath}' has invalid claimedAt.`);
197
203
  if (request.operation === "start") {
198
204
  if (!request.start || typeof request.start !== "object" || Array.isArray(request.start)) throw new Error(`External-job bridge start request '${filePath}' is missing start input.`);
205
+ } else if (request.operation === "follow-up") {
206
+ if (!request.followUp || typeof request.followUp !== "object" || Array.isArray(request.followUp)) throw new Error(`External-job bridge follow-up request '${filePath}' is missing follow-up input.`);
199
207
  } else if (typeof request.providerJobId !== "string" || !request.providerJobId.trim()) {
200
208
  throw new Error(`External-job bridge ${request.operation} request '${filePath}' is missing providerJobId.`);
201
209
  }
@@ -216,17 +224,25 @@ async function executeBridgeRequest(request: ExternalJobBridgeRequest, claimDir?
216
224
  };
217
225
  }
218
226
  try {
219
- const raw = request.operation === "start"
220
- ? await provider.start(request.start!)
221
- : request.operation === "status"
227
+ let raw: ExternalJobHandle | ExternalJobResult;
228
+ if (request.operation === "start") {
229
+ raw = await provider.start(request.start!);
230
+ } else if (request.operation === "follow-up") {
231
+ if (typeof provider.followUp !== "function") {
232
+ throw new ExternalJobProviderError(`External-job provider '${request.provider}' does not support follow-up. Update or reload the provider package, then retry action='resume'.`, { code: "follow-up-unsupported" });
233
+ }
234
+ raw = await provider.followUp(request.followUp!);
235
+ } else {
236
+ raw = request.operation === "status"
222
237
  ? await provider.status(request.providerJobId!)
223
238
  : request.operation === "reattach"
224
239
  ? await provider.reattach(request.providerJobId!)
225
240
  : await provider.result(request.providerJobId!);
241
+ }
226
242
  const result = request.operation === "result"
227
243
  ? validateExternalJobResult(provider.name, raw, "External-job bridge result")
228
244
  : validateExternalJobHandle(provider.name, raw, "External-job bridge handle");
229
- if (request.operation === "start" && claimDir) writeAtomicJson(startClaimHandlePath(claimDir), result);
245
+ if (isDispatchOperation(request.operation) && claimDir) writeAtomicJson(dispatchClaimHandlePath(claimDir), result);
230
246
  return { id: request.id, ok: true, operation: request.operation, provider: request.provider, result, completedAt: Date.now() };
231
247
  } catch (error) {
232
248
  const details = bridgeError(error);
@@ -241,11 +257,11 @@ async function executeBridgeRequest(request: ExternalJobBridgeRequest, claimDir?
241
257
  }
242
258
  }
243
259
 
244
- function claimStartRequest(asyncDir: string, filePath: string, request: ExternalJobBridgeRequest): { request: ExternalJobBridgeRequest; filePath: string } | undefined {
260
+ function claimDispatchRequest(asyncDir: string, filePath: string, request: ExternalJobBridgeRequest): { request: ExternalJobBridgeRequest; filePath: string } | undefined {
245
261
  const owner = currentClaimOwner();
246
262
  const claimed: ExternalJobBridgeRequest = { ...request, claimedAt: owner.claimedAt };
247
- const claimDir = startClaimDir(asyncDir, request.id);
248
- const tempClaimDir = startClaimTempDir(asyncDir, request.id);
263
+ const claimDir = dispatchClaimDir(asyncDir, request.id);
264
+ const tempClaimDir = dispatchClaimTempDir(asyncDir, request.id);
249
265
  try {
250
266
  fs.mkdirSync(tempClaimDir);
251
267
  writeAtomicJson(path.join(tempClaimDir, "owner.json"), owner);
@@ -287,7 +303,7 @@ function readClaimOwner(claimDir: string): ExternalJobClaimOwner | undefined {
287
303
 
288
304
  function readClaimHandle(provider: string, claimDir: string): ExternalJobHandle | undefined {
289
305
  try {
290
- return validateExternalJobHandle(provider, readJson(startClaimHandlePath(claimDir)), "External-job bridge recovered start handle");
306
+ return validateExternalJobHandle(provider, readJson(dispatchClaimHandlePath(claimDir)), "External-job bridge recovered dispatch handle");
291
307
  } catch {
292
308
  return undefined;
293
309
  }
@@ -297,7 +313,7 @@ export function serviceExternalJobBridgeRequests(asyncDir: string): void {
297
313
  let files: string[];
298
314
  try {
299
315
  files = fs.readdirSync(requestDir(asyncDir), { withFileTypes: true })
300
- .filter((entry) => (entry.isFile() && entry.name.endsWith(".json") && !completedStartClaimExists(asyncDir, entry.name.replace(/\.json$/, ""))) || (entry.isDirectory() && entry.name.endsWith(".claim") && !fs.existsSync(startClaimCompletedPath(path.join(requestDir(asyncDir), entry.name)))))
316
+ .filter((entry) => (entry.isFile() && entry.name.endsWith(".json") && !completedDispatchClaimExists(asyncDir, entry.name.replace(/\.json$/, ""))) || (entry.isDirectory() && entry.name.endsWith(".claim") && !fs.existsSync(dispatchClaimCompletedPath(path.join(requestDir(asyncDir), entry.name)))))
301
317
  .map((entry) => entry.name)
302
318
  .slice(0, MAX_REQUESTS_PER_SWEEP);
303
319
  } catch (error) {
@@ -313,7 +329,7 @@ export function serviceExternalJobBridgeRequests(asyncDir: string): void {
313
329
  export function serviceExternalJobBridgeRequestFile(asyncDir: string, file: string): void {
314
330
  fs.mkdirSync(responseDir(asyncDir), { recursive: true });
315
331
  if (file.endsWith(".claim")) {
316
- serviceExternalJobStartClaim(asyncDir, file);
332
+ serviceExternalJobDispatchClaim(asyncDir, file);
317
333
  return;
318
334
  }
319
335
  const filePath = path.join(requestDir(asyncDir), file);
@@ -335,20 +351,20 @@ export function serviceExternalJobBridgeRequestFile(asyncDir: string, file: stri
335
351
  fs.rmSync(filePath, { force: true });
336
352
  return;
337
353
  }
338
- if (request.operation === "start" && completedStartClaimExists(asyncDir, request.id)) {
354
+ if (isDispatchOperation(request.operation) && completedDispatchClaimExists(asyncDir, request.id)) {
339
355
  fs.rmSync(filePath, { force: true });
340
356
  return;
341
357
  }
342
358
  if (inFlight.has(request.id) || fs.existsSync(responsePath(asyncDir, request.id))) return;
343
- if (request.operation === "start" && request.claimedAt !== undefined) return;
344
- const claimed = request.operation === "start" ? claimStartRequest(asyncDir, filePath, request) : { request, filePath };
359
+ if (isDispatchOperation(request.operation) && request.claimedAt !== undefined) return;
360
+ const claimed = isDispatchOperation(request.operation) ? claimDispatchRequest(asyncDir, filePath, request) : { request, filePath };
345
361
  if (!claimed) return;
346
362
  const claimedRequest = claimed.request;
347
363
  inFlight.add(claimedRequest.id);
348
- void executeBridgeRequest(claimedRequest, claimedRequest.operation === "start" ? claimed.filePath : undefined).then((response) => {
364
+ void executeBridgeRequest(claimedRequest, isDispatchOperation(claimedRequest.operation) ? claimed.filePath : undefined).then((response) => {
349
365
  writeAtomicJson(responsePath(asyncDir, claimedRequest.id), response);
350
- if (claimedRequest.operation === "start") {
351
- writeAtomicJson(startClaimCompletedPath(claimed.filePath), { completedAt: Date.now() });
366
+ if (isDispatchOperation(claimedRequest.operation)) {
367
+ writeAtomicJson(dispatchClaimCompletedPath(claimed.filePath), { completedAt: Date.now() });
352
368
  } else {
353
369
  fs.rmSync(claimed.filePath, { recursive: true, force: true });
354
370
  }
@@ -362,15 +378,15 @@ export function serviceExternalJobBridgeRequestFile(asyncDir: string, file: stri
362
378
  message: error instanceof Error ? error.message : String(error),
363
379
  completedAt: Date.now(),
364
380
  } satisfies ExternalJobBridgeResponse);
365
- if (claimedRequest.operation === "start") writeAtomicJson(startClaimCompletedPath(claimed.filePath), { completedAt: Date.now() });
381
+ if (isDispatchOperation(claimedRequest.operation)) writeAtomicJson(dispatchClaimCompletedPath(claimed.filePath), { completedAt: Date.now() });
366
382
  }).finally(() => {
367
383
  inFlight.delete(claimedRequest.id);
368
384
  });
369
385
  }
370
386
 
371
- function serviceExternalJobStartClaim(asyncDir: string, file: string): void {
387
+ function serviceExternalJobDispatchClaim(asyncDir: string, file: string): void {
372
388
  const claimDir = path.join(requestDir(asyncDir), file);
373
- if (fs.existsSync(startClaimCompletedPath(claimDir))) return;
389
+ if (fs.existsSync(dispatchClaimCompletedPath(claimDir))) return;
374
390
  const owner = readClaimOwner(claimDir);
375
391
  if (!owner && fs.existsSync(requestPath(asyncDir, file.replace(/\.claim$/, ""))) && !fs.existsSync(responsePath(asyncDir, file.replace(/\.claim$/, "")))) {
376
392
  fs.rmSync(claimDir, { recursive: true, force: true });
@@ -383,7 +399,7 @@ function serviceExternalJobStartClaim(asyncDir: string, file: string): void {
383
399
  } catch {
384
400
  return;
385
401
  }
386
- if (request.operation !== "start" || fs.existsSync(responsePath(asyncDir, request.id))) return;
402
+ if (!isDispatchOperation(request.operation) || fs.existsSync(responsePath(asyncDir, request.id))) return;
387
403
  const handle = readClaimHandle(request.provider, claimDir);
388
404
  if (handle) {
389
405
  writeAtomicJson(responsePath(asyncDir, request.id), {
@@ -394,7 +410,7 @@ function serviceExternalJobStartClaim(asyncDir: string, file: string): void {
394
410
  result: handle,
395
411
  completedAt: Date.now(),
396
412
  } satisfies ExternalJobBridgeResponse);
397
- writeAtomicJson(startClaimCompletedPath(claimDir), { completedAt: Date.now() });
413
+ writeAtomicJson(dispatchClaimCompletedPath(claimDir), { completedAt: Date.now() });
398
414
  fs.rmSync(requestPath(asyncDir, request.id), { force: true });
399
415
  return;
400
416
  }
@@ -403,8 +419,8 @@ function serviceExternalJobStartClaim(asyncDir: string, file: string): void {
403
419
  ok: false,
404
420
  operation: request.operation,
405
421
  provider: request.provider,
406
- code: "start-dispatch-abandoned",
407
- message: `External-job start for provider '${request.provider}' was claimed by a host process that is no longer alive before a provider job id was committed. Refusing to redispatch the prompt automatically.`,
422
+ code: `${request.operation}-dispatch-abandoned`,
423
+ message: `External-job ${request.operation} for provider '${request.provider}' was claimed by a host process that is no longer alive before a provider job id was committed. Refusing to redispatch the prompt automatically.`,
408
424
  completedAt: Date.now(),
409
425
  } satisfies ExternalJobBridgeResponse);
410
426
  fs.rmSync(claimDir, { recursive: true, force: true });
@@ -417,16 +433,16 @@ export async function requestExternalJobOperation<T extends ExternalJobHandle |
417
433
  fs.mkdirSync(responseDir(asyncDir), { recursive: true });
418
434
  const bridgeRequest = { ...request, id, createdAt: Date.now() } satisfies ExternalJobBridgeRequest;
419
435
  writeAtomicJson(requestPath(asyncDir, id), bridgeRequest);
420
- const deadline = request.operation === "start" ? undefined : Date.now() + timeoutMs;
436
+ const deadline = isDispatchOperation(request.operation) ? undefined : Date.now() + timeoutMs;
421
437
  const outPath = responsePath(asyncDir, id);
422
438
  while (!fs.existsSync(outPath)) {
423
439
  const canceled = cancel?.();
424
440
  if (canceled) {
425
- if (request.operation === "start" && !cancelStartRequest(asyncDir, bridgeRequest)) {
441
+ if (isDispatchOperation(request.operation) && !cancelDispatchRequest(asyncDir, bridgeRequest)) {
426
442
  await sleep(POLL_INTERVAL_MS);
427
443
  continue;
428
444
  }
429
- if (request.operation !== "start") fs.rmSync(requestPath(asyncDir, id), { force: true });
445
+ if (!isDispatchOperation(request.operation)) fs.rmSync(requestPath(asyncDir, id), { force: true });
430
446
  throw canceled;
431
447
  }
432
448
  if (deadline !== undefined && Date.now() >= deadline) {