@xzzpig/pi-subagents 0.1.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -0,0 +1,187 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
+ import type { Details, ForegroundRunControl, SubagentState } from "../../shared/types.ts";
6
+ import { readStatus } from "../../shared/utils.ts";
7
+ import {
8
+ consumeSteerAckFromDir,
9
+ readSteerCapability,
10
+ steerAcksDir,
11
+ steerCapabilityPath,
12
+ stepSteerInboxDir,
13
+ writeSteerRequestToExistingDir,
14
+ type SteerDeliveryMode,
15
+ type SteerRequest,
16
+ } from "../background/control-channel.ts";
17
+
18
+ export interface WorkflowForegroundSteeringTarget {
19
+ control: ForegroundRunControl;
20
+ workflowRunId: string;
21
+ sourceRunId: string;
22
+ }
23
+
24
+ export type WorkflowForegroundSteeringResolution =
25
+ | { ok: true; target: WorkflowForegroundSteeringTarget }
26
+ | { ok: false; message: string };
27
+
28
+ function activeWorkflowError(state: SubagentState, workflowRunId: string, asyncDirRoot: string): string | undefined {
29
+ if (!state.currentSessionId) return "Workflow steering requires an active parent session.";
30
+ if (!state.workflowControllers?.has(workflowRunId)) return `Workflow '${workflowRunId}' has no live foreground child.`;
31
+ const status = readStatus(path.join(asyncDirRoot, workflowRunId));
32
+ if (!status || status.mode !== "workflow" || (status.state !== "running" && status.state !== "queued")) {
33
+ return `Workflow '${workflowRunId}' has no live foreground child.`;
34
+ }
35
+ if (status.sessionId !== state.currentSessionId) return `Workflow '${workflowRunId}' was not found in the active session.`;
36
+ return undefined;
37
+ }
38
+
39
+ function controlIsLiveInWorkflow(control: ForegroundRunControl, workflowRunId: string, sessionId: string): boolean {
40
+ return control.parentWorkflowRunId === workflowRunId
41
+ && control.sessionId === sessionId
42
+ && Boolean(control.workflowSteeringDir)
43
+ && (control.activeChildren?.size ?? 0) > 0;
44
+ }
45
+
46
+ export function resolveWorkflowForegroundSteeringTarget(input: {
47
+ state: SubagentState;
48
+ childRunId?: string;
49
+ workflowRunId?: string;
50
+ asyncDirRoot: string;
51
+ }): WorkflowForegroundSteeringResolution {
52
+ const { state, childRunId, asyncDirRoot } = input;
53
+ if (childRunId) {
54
+ const control = state.foregroundControls.get(childRunId);
55
+ if (!control?.parentWorkflowRunId) return { ok: false, message: `Foreground run '${childRunId}' is not a live workflow-owned child.` };
56
+ const workflowRunId = control.parentWorkflowRunId;
57
+ const workflowError = activeWorkflowError(state, workflowRunId, asyncDirRoot);
58
+ if (workflowError) return { ok: false, message: workflowError };
59
+ if (!controlIsLiveInWorkflow(control, workflowRunId, state.currentSessionId!)) {
60
+ return { ok: false, message: `Foreground run '${childRunId}' is not a live workflow-owned child in the active session.` };
61
+ }
62
+ return { ok: true, target: { control, workflowRunId, sourceRunId: childRunId } };
63
+ }
64
+
65
+ const workflowRunId = input.workflowRunId;
66
+ if (!workflowRunId) return { ok: false, message: "Workflow steering requires a workflow or child run id." };
67
+ const workflowError = activeWorkflowError(state, workflowRunId, asyncDirRoot);
68
+ if (workflowError) return { ok: false, message: workflowError };
69
+ const controls = [...state.foregroundControls.values()].filter((control) => controlIsLiveInWorkflow(control, workflowRunId, state.currentSessionId!));
70
+ if (controls.length === 0) return { ok: false, message: `Workflow '${workflowRunId}' has no live foreground child.` };
71
+ if (controls.length > 1) return { ok: false, message: `Workflow '${workflowRunId}' has ${controls.length} live foreground children; steer a child run id instead.` };
72
+ return { ok: true, target: { control: controls[0]!, workflowRunId, sourceRunId: workflowRunId } };
73
+ }
74
+
75
+ function managementError(message: string): AgentToolResult<Details> {
76
+ return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
77
+ }
78
+
79
+ export async function steerWorkflowForegroundTarget(input: {
80
+ target: WorkflowForegroundSteeringTarget;
81
+ message: string;
82
+ mode?: SteerDeliveryMode;
83
+ index?: number;
84
+ signal?: AbortSignal;
85
+ ackTimeoutMs?: number;
86
+ }): Promise<AgentToolResult<Details>> {
87
+ const { control, sourceRunId } = input.target;
88
+ const routeDir = control.workflowSteeringDir;
89
+ if (!routeDir || !fs.existsSync(routeDir)) return managementError(`Foreground run '${control.runId}' has no live workflow steering route.`);
90
+ const activeIndexes = [...(control.activeChildren?.keys() ?? [])].sort((left, right) => left - right);
91
+ const index = input.index ?? (activeIndexes.length === 1 ? activeIndexes[0] : undefined);
92
+ if (index === undefined) {
93
+ return managementError(activeIndexes.length === 0
94
+ ? `Foreground run '${control.runId}' has no live child session.`
95
+ : `Foreground run '${control.runId}' has ${activeIndexes.length} live child sessions; provide index.`);
96
+ }
97
+ if (!activeIndexes.includes(index)) return managementError(`Foreground run '${control.runId}' child ${index} is not live.`);
98
+ const capability = readSteerCapability(routeDir, index);
99
+ if (capability?.supported === false) return managementError(`Foreground run '${control.runId}' child ${index} does not support steering.`);
100
+
101
+ const request: SteerRequest = {
102
+ type: "steer",
103
+ id: randomUUID(),
104
+ ts: Date.now(),
105
+ message: input.message.trim(),
106
+ ...(input.mode && input.mode !== "steer" ? { mode: input.mode } : {}),
107
+ targetIndex: index,
108
+ source: "steer-action",
109
+ };
110
+ try {
111
+ writeSteerRequestToExistingDir(stepSteerInboxDir(routeDir, index), request);
112
+ } catch (error) {
113
+ if (typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT") {
114
+ return managementError(`Foreground run '${control.runId}' has no live workflow steering route.`);
115
+ }
116
+ return managementError(`Failed to queue steering for foreground run ${control.runId}: ${error instanceof Error ? error.message : String(error)}`);
117
+ }
118
+
119
+ const deadline = Date.now() + (input.ackTimeoutMs ?? 3_000);
120
+ let ack;
121
+ let routeRemoved = false;
122
+ while (Date.now() <= deadline) {
123
+ ack = consumeSteerAckFromDir(steerAcksDir(routeDir, index), request.id);
124
+ if (ack || input.signal?.aborted) break;
125
+ if (!fs.existsSync(routeDir)) {
126
+ routeRemoved = true;
127
+ break;
128
+ }
129
+ await new Promise<void>((resolve) => setTimeout(resolve, Math.min(50, Math.max(1, deadline - Date.now()))));
130
+ }
131
+ if (routeRemoved || (!ack && !input.signal?.aborted && !fs.existsSync(routeDir))) {
132
+ return managementError(`Foreground run '${control.runId}' has no live child session.`);
133
+ }
134
+ const target = ack?.state === "delivered"
135
+ ? { index, state: "delivered" as const, deliveredAt: ack.ts }
136
+ : ack?.state === "queued"
137
+ ? { index, state: "queued" as const }
138
+ : ack?.state === "failed"
139
+ ? { index, state: "failed" as const, reason: ack.message }
140
+ : { index, state: "pending" as const };
141
+ const steering = {
142
+ requestId: request.id,
143
+ state: ack?.state === "delivered" ? "delivered" as const : ack?.state === "failed" ? "failed" as const : "pending" as const,
144
+ deliveryStatus: ack?.state === "delivered" ? "delivered" as const : "queued" as const,
145
+ sourceRunId,
146
+ targets: [target],
147
+ };
148
+ if (input.signal?.aborted) {
149
+ return { content: [{ type: "text", text: `Steering pending for foreground run ${control.runId} (request ${request.id}); caller aborted before acknowledgment.` }], details: { mode: "management", results: [], steering } };
150
+ }
151
+ if (ack?.state === "delivered") {
152
+ return { content: [{ type: "text", text: `Steering delivered for foreground run ${control.runId} (request ${request.id}).` }], details: { mode: "management", results: [], steering } };
153
+ }
154
+ if (ack?.state === "queued") {
155
+ return { content: [{ type: "text", text: `Steering queued for foreground run ${control.runId} (request ${request.id}).` }], details: { mode: "management", results: [], steering } };
156
+ }
157
+ if (ack?.state === "failed") {
158
+ return { content: [{ type: "text", text: `Steering failed for foreground run ${control.runId} (request ${request.id}): ${ack.message}` }], isError: true, details: { mode: "management", results: [], steering } };
159
+ }
160
+ return { content: [{ type: "text", text: `Steering pending for foreground run ${control.runId} (request ${request.id}); no acknowledgment was received.` }], details: { mode: "management", results: [], steering } };
161
+ }
162
+
163
+ export function workflowForegroundSteeringDir(asyncDirRoot: string, workflowRunId: string, childRunId: string): string {
164
+ return path.join(asyncDirRoot, workflowRunId, "control", "workflow-foreground", childRunId);
165
+ }
166
+
167
+ export function removeWorkflowForegroundSteeringRoute(control: ForegroundRunControl): void {
168
+ if (!control.workflowSteeringDir) return;
169
+ try {
170
+ fs.rmSync(control.workflowSteeringDir, { recursive: true, force: true });
171
+ } catch (error) {
172
+ console.warn(`[pi-subagents] Failed to remove workflow foreground steering route '${control.workflowSteeringDir}': ${error instanceof Error ? error.message : String(error)}`);
173
+ }
174
+ }
175
+
176
+ export function workflowForegroundSteeringLaunchOptions(control: ForegroundRunControl | undefined, index: number): Pick<import("../../shared/types.ts").RunSyncOptions, "steerInboxDir" | "steerCapabilityPath" | "steerAckDir"> {
177
+ if (!control?.workflowSteeringDir) return {};
178
+ const steerInboxDir = stepSteerInboxDir(control.workflowSteeringDir, index);
179
+ const steerAckDir = steerAcksDir(control.workflowSteeringDir, index);
180
+ fs.mkdirSync(steerInboxDir, { recursive: true });
181
+ fs.mkdirSync(steerAckDir, { recursive: true });
182
+ return {
183
+ steerInboxDir,
184
+ steerCapabilityPath: steerCapabilityPath(control.workflowSteeringDir, index),
185
+ steerAckDir,
186
+ };
187
+ }
@@ -23,7 +23,7 @@ import type {
23
23
  SubagentRunMode,
24
24
  } from "../../shared/types.ts";
25
25
  import { isAgentContractV1 } from "./agent-contract.ts";
26
- import { classifyTaskMutationIntent, taskMayMutate } from "./task-intent.ts";
26
+ import { classifyTaskMutationIntent, stripSeverityCompounds, taskMayMutate } from "./task-intent.ts";
27
27
 
28
28
  const LEVEL_RANK: Record<Exclude<AcceptanceLevel, "auto">, number> = {
29
29
  none: 0,
@@ -93,7 +93,7 @@ function inferLevel(input: {
93
93
  const rolePatchTask = input.acceptanceRole !== undefined
94
94
  && intent.kind !== "read-only"
95
95
  && !/\b(?:do not|don't|must not)\s+patch\b/.test(task)
96
- && /\bpatch\s+(?:(?:\.{0,2}[\\/])?(?:[\w.-]+[\\/])+[\w.-]+|[\w.-]+\.[a-z0-9]+\b|(?:the\s+)?parser\b)/.test(task);
96
+ && /\bpatch\s+(?:(?:\.{0,2}[\\/])?(?:[\w.-]+[\\/])+[\w.-]+|[\w.-]+\.[a-z0-9]+\b|(?:the\s+)?parser\b)/.test(stripSeverityCompounds(task));
97
97
  const taskMayWrite = readOnlyTask ? false : taskMayMutate(input.task ?? "") || intent.kind === "implementation" || rolePatchTask;
98
98
  const readOnlyAgent = input.acceptanceRole === "read-only"
99
99
  || (input.acceptanceRole === undefined && /\b(?:reviewer|oracle|scout|researcher|analyst)\b/.test(agent));
@@ -433,6 +433,7 @@ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, opt
433
433
  "",
434
434
  "Finish with a fenced JSON block tagged `acceptance-report` in this shape:",
435
435
  "Use empty arrays when no items apply; array fields contain strings unless object entries are shown.",
436
+ "Empty-string entries (`[\"\"]`) are ignored; use `[]` when nothing applies.",
436
437
  "`criteriaSatisfied[].status` must be exactly one of: satisfied, not-satisfied, not-applicable.",
437
438
  "`commandsRun[].result` must be exactly one of: passed, failed, not-run.",
438
439
  "`manualNotes` and `notes` are optional strings; an empty string means no note and does not satisfy `manual-notes` evidence.",
@@ -612,9 +613,17 @@ function normalizeAcceptanceReportValue(value: unknown, pathLabel = ""): { value
612
613
  case "testsAddedOrUpdated":
613
614
  case "validationOutput":
614
615
  case "residualRisks":
615
- case "reviewFindings":
616
- normalized[canonical] = typeof fieldValue === "string" ? [fieldValue] : fieldValue;
616
+ case "reviewFindings": {
617
+ // Tolerate empty-string entries ("[\"\"]"): models write them for "no items"
618
+ // and a single empty entry must not reject the whole report. Drop them at
619
+ // parse time; non-string entries are kept so validateStringArrayField still
620
+ // flags structural garbage.
621
+ const items = typeof fieldValue === "string" ? [fieldValue] : fieldValue;
622
+ normalized[canonical] = Array.isArray(items)
623
+ ? items.filter((item) => typeof item !== "string" || item.trim().length > 0)
624
+ : items;
617
625
  break;
626
+ }
618
627
  case "noStagedFiles": {
619
628
  const token = typeof fieldValue === "string" ? fieldValue.trim().toLowerCase() : undefined;
620
629
  normalized[canonical] = token === "true" ? true : token === "false" ? false : fieldValue;
@@ -22,6 +22,10 @@ const READ_ONLY_BUILTIN_TOOLS = new Set([
22
22
  const CURSOR_FILE_MUTATION_THINKING =
23
23
  /(?:^|\n)\s*Cursor (?:edit|write)\s*:/i;
24
24
 
25
+ const IMPLEMENTATION_CHALLENGE_TASK_PATTERN = /^You are reviving a previous subagent conversation\.\n\nOriginal run: .+\nOriginal agent: .+(?:\nOriginal session file: .+)?\n\nUse the stored session context as background\. Answer the orchestrator's follow-up below\. Do not assume the original child process is still alive\.\n\nFollow-up:\nRun implementation challenge pass (?:one|two|\d+) and implement any better current-scope change\.$/;
26
+ const NO_BETTER_CHANGE_NEEDED_PATTERN = /^\s*no (?:better|further|additional) (?:current[- ]scope )?(?:code |source |file )?(?:change|changes|edit|edits|patch|patches) (?:is|are) needed[.!]?\s*$/i;
27
+ const NO_BETTER_CHANGE_QUALIFIER_PATTERN = /\b(?:do\s+not|don't|dont|not|never|cannot|can't|cant|unable|uncertain|unsure|unclear|maybe|might|may|\w+n['’]t)\b/i;
28
+
25
29
  interface CompletionMutationGuardInput {
26
30
  agent: string;
27
31
  task: string;
@@ -82,14 +86,26 @@ export function hasMutationToolCall(messages: Message[]): boolean {
82
86
  return false;
83
87
  }
84
88
 
89
+ function reportsNoBetterChallengeChange(messages: Message[]): boolean {
90
+ const report = messages
91
+ .filter((message) => message.role === "assistant")
92
+ .flatMap((message) => message.content)
93
+ .flatMap((part) => part.type === "text" ? [part.text] : [])
94
+ .join("\n");
95
+ return NO_BETTER_CHANGE_NEEDED_PATTERN.test(report)
96
+ && !NO_BETTER_CHANGE_QUALIFIER_PATTERN.test(report);
97
+ }
98
+
85
99
  export function evaluateCompletionMutationGuard(input: CompletionMutationGuardInput): CompletionMutationGuardResult {
86
100
  const expectedMutation = hasMutationToolCapability(input.tools, input.mcpDirectTools)
87
101
  ? expectsImplementationMutation(input.agent, input.task)
88
102
  : false;
89
103
  const attemptedMutation = hasMutationToolCall(input.messages);
104
+ const noEditChallengeComplete = IMPLEMENTATION_CHALLENGE_TASK_PATTERN.test(input.task)
105
+ && reportsNoBetterChallengeChange(input.messages);
90
106
  return {
91
107
  expectedMutation,
92
108
  attemptedMutation,
93
- triggered: expectedMutation && !attemptedMutation,
109
+ triggered: expectedMutation && !attemptedMutation && !noEditChallengeComplete,
94
110
  };
95
111
  }
@@ -49,7 +49,7 @@ const DYNAMIC_EXPAND_FROM_KEYS = new Set(["output", "path"]);
49
49
  const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outputSchema", "cwd", "output", "outputMode", "reads", "progress", "skill", "model", "toolBudget", "acceptance", "agentContract", "gateOn"]);
50
50
  const RUNNER_DYNAMIC_PARALLEL_KEYS = new Set([
51
51
  ...DYNAMIC_PARALLEL_KEYS,
52
- "outputName", "structured", "inheritProjectContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "waitToolEnabled",
52
+ "outputName", "structured", "inheritProjectContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled",
53
53
  "structuredOutput", "structuredOutputSchema", "tools", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "capabilityCeiling", "completionGuard", "systemPrompt",
54
54
  "systemPromptMode", "thinking", "modelCandidates", "sessionFile", "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "parentSessionId", "launchResolvedExtensions",
55
55
  ]);
@@ -0,0 +1,302 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Agent, type AgentTool, type StreamFn } from "@earendil-works/pi-agent-core";
3
+ import { convertToLlm, type ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
5
+ import type { ProviderHeaders } from "@earendil-works/pi-ai";
6
+ import { Type, type Static } from "typebox";
7
+ import { agentStreamOptions } from "../../shared/agent-stream-options.ts";
8
+
9
+ /**
10
+ * LLM intent arbiter for the completion mutation guard.
11
+ *
12
+ * The regex classifier (task-intent.ts) is deliberately narrow, so exotic
13
+ * review wording can still look like an implementation task ("to fix this,
14
+ * compare the outputs", verbs inside URLs or quoted text). When the guard is
15
+ * about to hard-fail a run that made no edits, this arbiter asks a model
16
+ * whether the task actually instructed file changes. It can only downgrade a
17
+ * failure to a pass; every error, timeout, or non-read-only verdict keeps the
18
+ * guard's original behavior.
19
+ *
20
+ * Enabled by default; set PI_SUBAGENTS_LLM_INTENT_ARBITER=0 to disable.
21
+ */
22
+
23
+ const COMPLETION_GUARD_ERROR_PREFIX =
24
+ "Subagent completed without making edits for an implementation task.";
25
+
26
+ export type TaskMutationVerdict = "read-only" | "implementation" | "unavailable";
27
+
28
+ export type TaskMutationArbiter = (task: string) => Promise<TaskMutationVerdict>;
29
+
30
+ const DecisionParams = Type.Object(
31
+ {
32
+ classification: Type.String({ enum: ["read_only", "implementation"] }),
33
+ confidence: Type.String({
34
+ enum: ["low", "medium", "high"],
35
+ description: "Confidence in the classification. Only read_only with high confidence rescues a failed run.",
36
+ }),
37
+ reason: Type.String({ description: "One concise reason for this classification." }),
38
+ },
39
+ { additionalProperties: false },
40
+ );
41
+
42
+ type DecisionParams = Static<typeof DecisionParams>;
43
+
44
+ /** Map a model decision to a verdict. Only a high-confidence read_only rescues. */
45
+ export function mapArbiterDecision(
46
+ decision: { classification?: string; confidence?: string } | undefined,
47
+ ): TaskMutationVerdict {
48
+ if (!decision) return "unavailable";
49
+ if (decision.classification === "read_only" && decision.confidence === "high") return "read-only";
50
+ return "implementation";
51
+ }
52
+
53
+ interface ArbiterRuntime {
54
+ model: NonNullable<RegistryModel>;
55
+ baseStreamFn: StreamFn;
56
+ timeoutMs: number;
57
+ }
58
+
59
+ interface ArbiterAuth {
60
+ apiKey?: string;
61
+ headers?: ProviderHeaders;
62
+ env?: Record<string, string>;
63
+ }
64
+
65
+ export interface TaskMutationArbiterOptions {
66
+ /** Explicit "provider/id" model override (tests, config). */
67
+ model?: string;
68
+ /** Injectable stream function (tests). */
69
+ streamFn?: StreamFn;
70
+ timeoutMs?: number;
71
+ }
72
+
73
+ const DEFAULT_ARBITER_TIMEOUT_MS = 10_000;
74
+
75
+ type RegistryModel = ReturnType<NonNullable<ExtensionContext["modelRegistry"]["find"]>>;
76
+
77
+ function resolveArbiterModel(
78
+ ctx: ExtensionContext,
79
+ options?: TaskMutationArbiterOptions,
80
+ ): NonNullable<RegistryModel> | null {
81
+ const registry = ctx.modelRegistry as {
82
+ find?: (provider: string, modelId: string) => RegistryModel | undefined;
83
+ getAvailable?: () => Array<{ provider?: string; id?: string }>;
84
+ };
85
+ const explicit = options?.model?.trim();
86
+ if (explicit) {
87
+ const [provider, id] = explicit.split("/");
88
+ if (provider && id) return registry.find?.(provider, id) ?? null;
89
+ return null;
90
+ }
91
+ if (ctx.model) return ctx.model as NonNullable<RegistryModel>;
92
+ const first = registry.getAvailable?.()[0];
93
+ if (first?.provider && first.id) return registry.find?.(first.provider, first.id) ?? null;
94
+ return null;
95
+ }
96
+
97
+ function resolveArbiterRuntime(
98
+ ctx: ExtensionContext,
99
+ options?: TaskMutationArbiterOptions,
100
+ ): ArbiterRuntime | null {
101
+ const model = resolveArbiterModel(ctx, options);
102
+ if (!model?.provider || !model.id) return null;
103
+ const registry = ctx.modelRegistry as {
104
+ getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
105
+ };
106
+ const modelApi = (model as { api?: string }).api;
107
+ const registered = registry.getRegisteredProviderConfig?.(model.provider);
108
+ const baseStreamFn = options?.streamFn
109
+ ?? (registered?.streamSimple && registered.api === modelApi
110
+ ? registered.streamSimple
111
+ : streamSimple);
112
+ return {
113
+ model,
114
+ baseStreamFn,
115
+ timeoutMs: options?.timeoutMs ?? DEFAULT_ARBITER_TIMEOUT_MS,
116
+ };
117
+ }
118
+
119
+ async function resolveArbiterAuth(
120
+ ctx: ExtensionContext,
121
+ model: RegistryModel,
122
+ ): Promise<ArbiterAuth> {
123
+ const registry = ctx.modelRegistry as {
124
+ getApiKeyAndHeaders?: (m: RegistryModel) => Promise<{
125
+ ok: boolean;
126
+ apiKey?: string;
127
+ headers?: ProviderHeaders;
128
+ env?: Record<string, string>;
129
+ error?: string;
130
+ }>;
131
+ };
132
+ // Call as a METHOD on the registry: the host ModelRegistry implementation
133
+ // is a class whose method reads instance state (this.runtime), so a
134
+ // detached call silently fails auth. Same shape as the watchdog.
135
+ if (!registry.getApiKeyAndHeaders) return {};
136
+ try {
137
+ const auth = await registry.getApiKeyAndHeaders(model);
138
+ if (auth.ok === false) return {};
139
+ return {
140
+ ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
141
+ ...(auth.headers ? { headers: auth.headers } : {}),
142
+ ...(auth.env ? { env: auth.env } : {}),
143
+ };
144
+ } catch {
145
+ return {};
146
+ }
147
+ }
148
+
149
+ /** Build the effective stream function with resolved credentials wrapped in (watchdog pattern). */
150
+ function authWrappedStreamFn(
151
+ base: StreamFn,
152
+ auth: ArbiterAuth,
153
+ ): StreamFn {
154
+ return (model, context, streamOptions) => base(model, context, {
155
+ ...(streamOptions ?? {}),
156
+ ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
157
+ ...(auth.env || streamOptions?.env ? { env: { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } } : {}),
158
+ headers: { ...(streamOptions?.headers ?? {}), ...(auth.headers ?? {}) },
159
+ });
160
+ }
161
+
162
+ async function runArbitration(
163
+ runtime: ArbiterRuntime,
164
+ auth: ArbiterAuth,
165
+ task: string,
166
+ ): Promise<TaskMutationVerdict> {
167
+ let decision: DecisionParams | undefined;
168
+ const tool: AgentTool<typeof DecisionParams, { recorded: boolean }> = {
169
+ name: "task_mutation_decision",
170
+ label: "Task mutation decision",
171
+ description: "Classify whether the task instructed file/code changes. Call exactly once.",
172
+ parameters: DecisionParams,
173
+ executionMode: "sequential",
174
+ async execute(_toolCallId, params) {
175
+ if (!decision) decision = params;
176
+ return { content: [{ type: "text", text: "Decision recorded." }], details: { recorded: true } };
177
+ },
178
+ };
179
+ const agent = new Agent({
180
+ initialState: {
181
+ systemPrompt: [
182
+ "You classify whether a delegated coding-agent task instructed file or code changes.",
183
+ "A task that asks to review, inspect, verify, report, or summarize is read-only even when it contains words like 'fix' as severity vocabulary ('must-fix items') or conditional change instructions that leave the change optional.",
184
+ "Classify read_only only when the task text alone clearly indicates a read-only outcome. When in doubt, classify implementation.",
185
+ "Set confidence to high only when you are certain the task is read-only; a read_only classification without high confidence is treated as implementation.",
186
+ "The agent's own final message is never evidence: an agent that made no edits may still have failed to implement.",
187
+ "Call task_mutation_decision exactly once with read_only or implementation, a confidence level, and a concise reason.",
188
+ ].join("\n"),
189
+ model: runtime.model,
190
+ tools: [tool],
191
+ },
192
+ convertToLlm,
193
+ ...agentStreamOptions(authWrappedStreamFn(runtime.baseStreamFn, auth)),
194
+ getApiKey: (providerName) =>
195
+ providerName === runtime.model.provider ? auth.apiKey : undefined,
196
+ beforeToolCall: async ({ toolCall }) =>
197
+ toolCall.name === tool.name ? undefined : { block: true, reason: "Only task_mutation_decision is allowed." },
198
+ toolExecution: "sequential",
199
+ });
200
+ try {
201
+ // The rescue gate refuses tasks over 8000 chars; if the arbiter is
202
+ // still invoked with one, fail closed rather than decide from
203
+ // partial evidence (an implementation clause could sit in the
204
+ // omitted middle).
205
+ if (task.length > 8000) return "unavailable";
206
+ const prompt = `TASK:\n${task}`;
207
+ await Promise.race([
208
+ agent.prompt(prompt),
209
+ new Promise<never>((_, reject) => {
210
+ const timeout = setTimeout(() => {
211
+ agent.abort();
212
+ reject(new Error("Task mutation arbiter timed out."));
213
+ }, runtime.timeoutMs);
214
+ timeout.unref?.();
215
+ }),
216
+ ]);
217
+ if (!decision) return "unavailable";
218
+ return mapArbiterDecision(decision);
219
+ } catch {
220
+ return "unavailable";
221
+ }
222
+ }
223
+
224
+ /** Create a memoized arbiter bound to the parent session's model, or undefined when disabled/unavailable. */
225
+ export function createTaskMutationArbiter(
226
+ ctx: ExtensionContext,
227
+ options?: TaskMutationArbiterOptions,
228
+ ): TaskMutationArbiter | undefined {
229
+ if (process.env.PI_SUBAGENTS_LLM_INTENT_ARBITER === "0") return undefined;
230
+ const runtime = resolveArbiterRuntime(ctx, options);
231
+ if (!runtime) return undefined;
232
+ const cache = new Map<string, TaskMutationVerdict>();
233
+ return async (task) => {
234
+ const key = createHash("sha256").update(task).digest("base64url");
235
+ const cached = cache.get(key);
236
+ if (cached) return cached;
237
+ const auth = await resolveArbiterAuth(ctx, runtime.model);
238
+ const verdict = await runArbitration(runtime, auth, task);
239
+ if (cache.size > 200) cache.clear();
240
+ cache.set(key, verdict);
241
+ return verdict;
242
+ };
243
+ }
244
+
245
+ export function isCompletionGuardFailure(result: { error?: string }): boolean {
246
+ return result.error?.startsWith(COMPLETION_GUARD_ERROR_PREFIX) === true;
247
+ }
248
+
249
+ export async function arbitrateCompletionGuardRescue(input: {
250
+ guardTriggered: boolean;
251
+ task: string;
252
+ arbiter?: TaskMutationArbiter;
253
+ }): Promise<{ triggered: boolean; rescued: boolean }> {
254
+ if (!input.guardTriggered || !input.arbiter) {
255
+ return { triggered: input.guardTriggered, rescued: false };
256
+ }
257
+ // Never decide from partial evidence: refuse tasks over 8000 chars before
258
+ // even consulting the model.
259
+ if (input.task.length > 8000) {
260
+ return { triggered: true, rescued: false };
261
+ }
262
+ try {
263
+ const verdict = await input.arbiter(input.task);
264
+ if (verdict === "read-only") return { triggered: false, rescued: true };
265
+ return { triggered: true, rescued: false };
266
+ } catch {
267
+ return { triggered: true, rescued: false };
268
+ }
269
+ }
270
+
271
+ /**
272
+ * When the completion guard hard-failed a run and the arbiter classifies the
273
+ * task as read-only, clear the failure. Returns true when rescued. All other
274
+ * verdicts and every failure mode keep the original guard behavior.
275
+ *
276
+ * Classification uses the task text only: the agent's own final message is
277
+ * never evidence, so a child that failed to implement cannot talk its way
278
+ * out of the guard by claiming the work was read-only.
279
+ */
280
+ export async function maybeRescueCompletionGuardFailure(
281
+ result: { exitCode?: number; error?: string },
282
+ task: string,
283
+ arbiter: TaskMutationArbiter | undefined,
284
+ ): Promise<boolean> {
285
+ if (!arbiter || !isCompletionGuardFailure(result)) return false;
286
+ const verdict = await arbitrateWithGuard(arbiter, task);
287
+ if (verdict !== "read-only") return false;
288
+ result.exitCode = 0;
289
+ delete result.error;
290
+ return true;
291
+ }
292
+
293
+ async function arbitrateWithGuard(
294
+ arbiter: TaskMutationArbiter,
295
+ task: string,
296
+ ): Promise<TaskMutationVerdict> {
297
+ try {
298
+ return await arbiter(task);
299
+ } catch {
300
+ return "unavailable";
301
+ }
302
+ }
@@ -191,7 +191,8 @@ function defaultScopeWarn(violation: ModelScopeViolation): void {
191
191
  *
192
192
  * An explicitly requested model string is resolved via {@link resolveModelCandidate}.
193
193
  * When `options.scope.enforce` is on, an out-of-scope resolved model throws for
194
- * an explicit (`source: "explicit"`) request and warns for an inherited one.
194
+ * an explicit (`source: "explicit"`) request and warns for an inherited one,
195
+ * unless strict scope enforcement makes inherited violations hard errors.
195
196
  */
196
197
  export function resolveSubagentModelOverride(
197
198
  requestedModel: string | boolean | undefined,
@@ -245,7 +246,7 @@ export function resolveEffectiveSubagentModel(
245
246
  }
246
247
 
247
248
  export interface BuildModelCandidatesOptions {
248
- /** Fallback models are inherited agent config and warn, rather than error, when out of scope. */
249
+ /** Fallback models warn by default and throw when strict scope enforcement is enabled. */
249
250
  scope?: ModelScopeConfig;
250
251
  onWarn?: (violation: ModelScopeViolation) => void;
251
252
  }
@@ -265,9 +266,12 @@ export function buildModelCandidates(
265
266
  if (!raw) continue;
266
267
  const normalized = resolveModelCandidate(raw.trim(), availableModels, preferredProvider);
267
268
  if (!normalized || seen.has(normalized)) continue;
268
- if (index > 0 && options?.scope?.enforce) {
269
+ if ((index > 0 || options?.scope?.strict === true) && options?.scope?.enforce) {
269
270
  const violation = checkModelScope(normalized, options.scope, "inherited");
270
- if (violation) (options.onWarn ?? defaultScopeWarn)(violation);
271
+ if (violation) {
272
+ if (violation.severity === "error") throw new Error(violation.message);
273
+ (options.onWarn ?? defaultScopeWarn)(violation);
274
+ }
271
275
  }
272
276
  seen.add(normalized);
273
277
  candidates.push(normalized);
@@ -6,7 +6,8 @@
6
6
  * where the model came from: an explicit caller-supplied model (`--model`,
7
7
  * tool-call `model`, or a TUI clarify pick) is a hard error, while a model
8
8
  * inherited from agent frontmatter / `defaultModel` / the parent session only
9
- * emits a warning so existing configurations keep working.
9
+ * emits a warning so existing configurations keep working. Optional strict
10
+ * enforcement makes inherited models hard errors too.
10
11
  *
11
12
  * The decision logic ({@link checkModelScope}) is a pure function of its
12
13
  * inputs so it can be unit-tested without touching the filesystem or config.
@@ -16,6 +17,8 @@ import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
16
17
 
17
18
  export interface ModelScopeConfig {
18
19
  enforce?: boolean;
20
+ /** Reject inherited and fallback models outside the allowlist instead of warning. */
21
+ strict?: boolean;
19
22
  /** Glob-style allow patterns (only `*` is special), matched against `provider/id`. */
20
23
  allow?: string[];
21
24
  }
@@ -67,7 +70,7 @@ export function checkModelScope(
67
70
  if (allow.some((pattern) => matchesScopePattern(model, pattern))) return undefined;
68
71
 
69
72
  const baseModel = stripThinkingSuffix(model);
70
- const severity: ModelScopeViolation["severity"] = source === "explicit" ? "error" : "warn";
73
+ const severity: ModelScopeViolation["severity"] = source === "explicit" || scope.strict === true ? "error" : "warn";
71
74
  return {
72
75
  model: baseModel,
73
76
  severity,
@@ -102,6 +105,13 @@ export function parseModelScopeConfig(
102
105
  config.enforce = input.enforce;
103
106
  }
104
107
 
108
+ if ("strict" in input) {
109
+ if (typeof input.strict !== "boolean") {
110
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.strict'; expected a boolean.`);
111
+ }
112
+ config.strict = input.strict;
113
+ }
114
+
105
115
  if ("allow" in input) {
106
116
  if (!Array.isArray(input.allow)) {
107
117
  throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected an array of strings.`);