@xzzpig/pi-subagents 0.19.0 → 0.20.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 (53) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/docs/agents.md +15 -5
  3. package/docs/configuration.md +10 -0
  4. package/docs/extension-api.md +1 -1
  5. package/docs/missions.md +15 -1
  6. package/docs/models.md +6 -2
  7. package/docs/observability.md +8 -3
  8. package/docs/tool-reference.md +28 -3
  9. package/docs/workflows.md +2 -2
  10. package/package.json +1 -1
  11. package/src/agents/agents.ts +59 -3
  12. package/src/api/preflight.ts +42 -1
  13. package/src/extension/config.ts +4 -1
  14. package/src/extension/index.ts +23 -16
  15. package/src/extension/public-execution.ts +3 -0
  16. package/src/extension/reply-workflow-script.ts +1 -1
  17. package/src/extension/rpc.ts +1 -1
  18. package/src/extension/schemas.ts +5 -3
  19. package/src/extension/tool-description.ts +1 -1
  20. package/src/missions/goal-driver.ts +44 -31
  21. package/src/missions/store.ts +10 -1
  22. package/src/profiles/profiles.ts +5 -2
  23. package/src/runs/background/async-execution.ts +88 -6
  24. package/src/runs/background/async-job-tracker.ts +3 -2
  25. package/src/runs/background/await-async-run.ts +4 -2
  26. package/src/runs/background/control-channel.ts +43 -0
  27. package/src/runs/background/run-child-session.ts +13 -6
  28. package/src/runs/background/runner-aliases.ts +7 -4
  29. package/src/runs/background/scheduled-runs.ts +28 -13
  30. package/src/runs/background/stale-run-reconciler.ts +13 -2
  31. package/src/runs/background/subagent-runner.ts +43 -4
  32. package/src/runs/foreground/command-action.ts +41 -0
  33. package/src/runs/foreground/execution.ts +16 -7
  34. package/src/runs/foreground/subagent-executor.ts +63 -12
  35. package/src/runs/shared/child-commands.ts +228 -0
  36. package/src/runs/shared/child-session.ts +93 -19
  37. package/src/runs/shared/child-tool-plan.ts +1 -1
  38. package/src/runs/shared/claude-code-adapter.ts +157 -2
  39. package/src/runs/shared/dynamic-fanout.ts +1 -1
  40. package/src/runs/shared/external-cli-preflight.ts +54 -6
  41. package/src/runs/shared/external-cli-runner.ts +5 -1
  42. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -4
  43. package/src/runs/shared/model-resolution.ts +9 -1
  44. package/src/runs/shared/parallel-utils.ts +2 -0
  45. package/src/runs/shared/run-history.ts +87 -0
  46. package/src/runs/shared/subagent-control.ts +32 -17
  47. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  48. package/src/shared/required-child-extensions.ts +39 -5
  49. package/src/shared/types.ts +6 -1
  50. package/src/slash/subagent-cost.ts +9 -5
  51. package/src/tui/render.ts +4 -4
  52. package/src/workflows/workflow-receipt.ts +2 -2
  53. package/src/workflows/workflow-resources.ts +7 -4
@@ -331,6 +331,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
331
331
  const fleetViewEnabled = config.fleetView !== false;
332
332
  const fleetViewPlacement = resolveFleetViewPlacement(config.fleetViewPlacement);
333
333
  const asyncWidgetEnabled = config.asyncWidget !== false;
334
+ const asyncWidgetCollapsed = config.asyncWidgetCollapsed === true;
334
335
  const summaryInlineToolDisplay = config.inlineToolDisplay === "summary";
335
336
  const tempArtifactsDir = getArtifactsDir(null);
336
337
  const artifactCleanupDays = config.artifactConfig?.cleanupDays ?? DEFAULT_ARTIFACT_CONFIG.cleanupDays;
@@ -485,6 +486,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
485
486
  };
486
487
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
487
488
  widgetEnabled: asyncWidgetEnabled,
489
+ widgetCollapsed: asyncWidgetCollapsed,
488
490
  onJobTerminal: () => refreshResultDelivery(),
489
491
  supervisorRequestState: supervisorChannel.getSupervisorRequestState,
490
492
  });
@@ -745,7 +747,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
745
747
  }
746
748
  if (args.workflow !== undefined)
747
749
  return new Text(
748
- `${title}${gap}${theme.fg("accent", args.workflow === true ? "workflow (reply block)" : `workflow ${String(args.workflow)}`)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${args.preflight !== undefined ? `${gap}${theme.fg("dim", formatWorkflowPreflightCall(args.preflight))}` : ""}`,
750
+ `${title}${gap}${theme.fg("accent", args.workflow === true || args.workflow === "true" ? "workflow (reply block)" : `workflow ${String(args.workflow)}`)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}${args.preflight !== undefined ? `${gap}${theme.fg("dim", formatWorkflowPreflightCall(args.preflight))}` : ""}`,
749
751
  0,
750
752
  0,
751
753
  );
@@ -792,23 +794,28 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
792
794
  registerWaitTool(pi, state, waitToolConfig.enabled, waitSubscriptionManager, waitToolConfig.defaultTimeoutMs, undefined, supervisorChannel.hasPendingRequests);
793
795
 
794
796
  pi.on("agent_end", async (_event, ctx) => {
795
- if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests });
796
- const ownerSessionId = state.currentSessionId;
797
- if (!ownerSessionId) return;
798
- goalTurnId += 1;
799
797
  try {
800
- const location = resolveMissionStoreLocation({ projectRoot: state.baseCwd, ...(config.missions ? { config: config.missions } : {}) });
801
- const retainedChildren = listRetainedChildren(DIRS.async, ownerSessionId);
802
- for (const notice of collectGoalContinuationNotices({ location, ownerSessionId, retainedChildren, turnId: goalTurnId })) {
803
- handleSubagentControlNotice({
804
- pi,
805
- state,
806
- visibleControlNotices: new Set(),
807
- details: { source: "goal", event: notice.event, noticeText: notice.message },
808
- });
798
+ if (!ctx.hasUI) await drainOutstandingWork({ state, events: pi.events, hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests });
799
+ } finally {
800
+ // Deliver notices after a failed drain without suppressing its rejection.
801
+ const ownerSessionId = state.currentSessionId;
802
+ if (ownerSessionId) {
803
+ goalTurnId += 1;
804
+ try {
805
+ const location = resolveMissionStoreLocation({ projectRoot: state.baseCwd, ...(config.missions ? { config: config.missions } : {}) });
806
+ const retainedChildren = listRetainedChildren(DIRS.async, ownerSessionId);
807
+ for (const notice of collectGoalContinuationNotices({ location, ownerSessionId, retainedChildren, turnId: goalTurnId })) {
808
+ handleSubagentControlNotice({
809
+ pi,
810
+ state,
811
+ visibleControlNotices: new Set(),
812
+ details: { source: "goal", event: notice.event, noticeText: notice.message },
813
+ });
814
+ }
815
+ } catch (error) {
816
+ console.error("Failed to evaluate goal missions:", error);
817
+ }
809
818
  }
810
- } catch (error) {
811
- console.error("Failed to evaluate goal missions:", error);
812
819
  }
813
820
  });
814
821
 
@@ -101,6 +101,9 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
101
101
  if (params.workflowScriptPath !== undefined) {
102
102
  return { ok: false, error: REMOVED_WORKFLOW_SCRIPT_PATH, mode: params.action === undefined ? "workflow" : "management" };
103
103
  }
104
+ // Some MCP clients send the boolean branch of the workflow union as the string "true" (#2600).
105
+ // Coerce it here so no path can resolve it as a named resource or script file called "true".
106
+ if (params.workflow === "true") params = { ...params, workflow: true };
104
107
  const workflow = params.workflow;
105
108
  if (workflow !== undefined && workflow !== true && (typeof workflow !== "string" || !workflow.trim())) {
106
109
  return { ok: false, error: "workflow must be true (the ```js workflow block in this reply), a script path containing '/', or a named workflow resource.", mode: "workflow" };
@@ -26,7 +26,7 @@ export function readReplyWorkflowScript(sessionManager: Pick<ExtensionContext["s
26
26
 
27
27
  function scriptFromReply(content: AssistantMessage["content"]): ReplyWorkflowScript {
28
28
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent"
29
- && block.arguments?.workflow === true).length;
29
+ && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
30
30
  if (replyCalls > 1) return { error: `This reply has ${replyCalls} subagent calls with workflow: true; a reply can carry only one. Pass other scripts as workflow file paths.` };
31
31
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
32
32
  const { blocks, unclosed } = workflowBlocks(text);
@@ -524,7 +524,7 @@ function spawnParams(params: unknown, options: RegisterSubagentRpcBridgeOptions)
524
524
  const { script, ...input } = assertRecordParams(params, "spawn");
525
525
  if (Object.hasOwn(input, "workflowScript")) throw new SubagentRpcError("invalid_params", "RPC spawn workflowScript was removed; pass inline script text as script.");
526
526
  if (Object.hasOwn(input, "workflowScriptPath")) throw new SubagentRpcError("invalid_params", "RPC spawn workflowScriptPath was removed; pass the file as workflow: \"./path/to/script.js\".");
527
- if (input.workflow === true) throw new SubagentRpcError("invalid_params", "RPC spawn has no reply block for workflow: true; pass inline script text as script or a file as workflow: \"./path/to/script.js\".");
527
+ if (input.workflow === true || input.workflow === "true") throw new SubagentRpcError("invalid_params", "RPC spawn has no reply block for workflow: true; pass inline script text as script or a file as workflow: \"./path/to/script.js\".");
528
528
  if (script !== undefined) {
529
529
  if (typeof script !== "string" || !script.trim()) throw new SubagentRpcError("invalid_params", "RPC spawn script must be a non-empty string.");
530
530
  if (input.workflow !== undefined) throw new SubagentRpcError("invalid_params", "RPC spawn script cannot be combined with workflow.");
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { Type } from "typebox";
6
6
  import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
7
+ import { MAX_ARGS_BYTES, MAX_ARGS_DEPTH, MAX_ARGS_FIELDS, MAX_ARGS_ITEMS } from "../workflows/workflow-resources.ts";
7
8
 
8
9
  function keepTopLevelParameterDescriptions<T extends object>(schema: T): T {
9
10
  return pruneNestedDescriptions(schema, []);
@@ -180,6 +181,7 @@ const SubagentParamProperties = {
180
181
  supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
181
182
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child/transcript index." })),
182
183
  childId: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Child-scoped stop identity." })),
184
+ toolCallId: Type.Optional(Type.String({ description: "Command tool-call id." })),
183
185
  view: Type.Optional(Type.String({
184
186
  enum: ["fleet", "transcript"],
185
187
  description: "status view: fleet overview or transcript tail with id/dir and optional index.",
@@ -202,7 +204,7 @@ const SubagentParamProperties = {
202
204
  timezone: Type.Optional(Type.String()),
203
205
  overlap: Type.Optional(Type.String({ enum: ["skip"] })),
204
206
  catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed schedule occurrences; default latest." })),
205
- missionId: Type.Optional(Type.String()),
207
+ missionId: Type.Optional(Type.String({ description: "Existing mission to attach to a workflow or schedule.create; read guide missions for lifecycle and retention." })),
206
208
  mission: Type.Optional(Type.Unsafe({ ...MissionLaunchOverride, description: "false disables; true invalid. Object: exactly one non-empty title or summary; objective/labels optional; goal only true, requires budget.tokens." })),
207
209
  missionUpdate: Type.Optional(Type.Unsafe({ ...MissionUpdateOverride, description: "Mission patch; read guide missions." })),
208
210
  missionStatus: Type.Optional(Type.String()),
@@ -222,7 +224,7 @@ const SubagentParamProperties = {
222
224
  anyOf: [{ type: "boolean" }, { type: "string", minLength: 1 }],
223
225
  description: "true: run the one ```js workflow block written in this same reply (false invalid). String with '/': script file read from request cwd. Other string: named workflow resource. Raw scripts (true or path) have no runs.host.",
224
226
  })),
225
- args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Bounded plain-JSON args for workflow; raw-script args are exposed deeply frozen and persisted, so do not include secrets." })),
227
+ args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: MAX_ARGS_FIELDS, additionalProperties: true, description: `Plain-JSON args for workflow; ${MAX_ARGS_FIELDS} fields/object, ${MAX_ARGS_ITEMS} items/array, depth ${MAX_ARGS_DEPTH}, ${MAX_ARGS_BYTES / 1024} KiB total; raw-script args are exposed deeply frozen and persisted, so do not include secrets.` })),
226
228
  globalConcurrencyLimit: Type.Optional(Type.Integer({ minimum: 1 })),
227
229
  maxSubagentSpawnsPerRun: Type.Optional(Type.Integer({ minimum: 1 })),
228
230
  preflight: Type.Optional(WorkflowPreflightOverride),
@@ -272,7 +274,7 @@ const SubagentParamProperties = {
272
274
  { type: "string", minLength: 1 },
273
275
  { type: "object", properties: { command: { type: "string", minLength: 1 }, output: { type: "string", enum: ["json"] }, schema: { type: "object" }, timeoutMs: { type: "integer", minimum: 1 } }, required: ["command"], additionalProperties: false },
274
276
  ],
275
- description: "Host gate command run after the child finishes: a string, or { command, output: \"json\", schema?, timeoutMs? } whose passing stdout becomes structuredOutput (not with outputSchema). Cannot be combined with acceptance; an explicit acceptance of false is treated as omitted.",
277
+ description: "Host gate command run after the child finishes: a string, or an object; with output \"json\", passing stdout becomes structuredOutput (not with outputSchema). Cannot be combined with acceptance except false (treated as omitted).",
276
278
  })),
277
279
  };
278
280
 
@@ -24,7 +24,7 @@ const safetyGuidance = (on: FeatureText) => `SAFETY-CRITICAL SUBAGENT GUIDANCE:
24
24
  • Ordinary child subagents are not orchestrators; only configured fanout within depth/session limits. For an authorized delegated workflow, keep one writer per cwd/worktree and isolate concurrent writers. Use fresh-context read-only reviewers when independent review was requested, then parent synthesis/fixes. Oracle/advisor unknowns use supervisor dialogue; one-shot only when requested.
25
25
  • Bind durable output ${on("workflow-scripts", "on runs.run/runs.all", "with output")}, not task filename prose; return actual outputReference/outputPathMapping/artifactPaths, evidence and residual risks.
26
26
  • children.list is workflow-only, not an exhaustive list of direct native children: resume only resumable rows. When an intended child's exact run id is known, inspect it with {action:"status",id}; if status identifies the candidate, attempt {action:"resume",id,message}. Resume authoritatively checks eligibility, may reject it, and otherwise detaches a follow-up/challenge with the stored agent/model/tool contract. Use a labeled same-role fallback only when no known candidate exists or resume rejects eligibility.${on("workflow-scripts", " Scripts await runs.run(newKey,{resume:runId,task}); continue from latest returned runId. Each distinct resume pass needs a new stable key; same-key reuse requires identical launch parameters.")}
27
- ${on("workflow-scripts", "• Named resources own authority; raw scripts (workflow:true or a path) cannot use runs.host. Granted commands/relative outputs use workflow cwd, never per-step cwd.\n")}• Inspect asyncId/asyncDir (status.json, events.jsonl, logs) with status/debug.run; control with interrupt/stop/resume/steer. Read {action:"guide",topic:"tool-reference"} for controls/evidence gates.`;
27
+ ${on("workflow-scripts", "• Named resources own authority; raw scripts (workflow:true or a path) cannot use runs.host. Granted commands/relative outputs use workflow cwd, never per-step cwd.\n")}• Inspect asyncId/asyncDir (status.json, events.jsonl, logs) with status/debug.run; control with interrupt/stop/resume/steer. For local Pi children explicitly granted subagent_command, command.status/yield/cancel targets one exact toolCallId without interrupting the child. Read {action:"guide",topic:"tool-reference"} for controls/evidence gates.`;
28
28
 
29
29
  const scriptExecutionGuidance = (on: FeatureText) => `Delegate one child with {agent,task?}; otherwise set exactly one workflow source, with optional args.
30
30
  Workflow script: write it as one \`\`\`js workflow block in this reply, then call subagent({workflow:true,...}). workflow:'./path.js' (any value with '/') loads a file from request cwd; other strings name a resource.
@@ -31,7 +31,14 @@ function readLinkedRun(run: MissionRunLink): MissionRunLink {
31
31
  if (!run.asyncDir) return run;
32
32
  const statusPath = path.join(run.asyncDir, "status.json");
33
33
  if (!fs.existsSync(statusPath)) return run;
34
- const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as Record<string, unknown>;
34
+ let parsed: unknown;
35
+ try {
36
+ parsed = JSON.parse(fs.readFileSync(statusPath, "utf-8"));
37
+ } catch (error) {
38
+ throw new Error(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
39
+ }
40
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`Linked run status '${statusPath}' must be an object`);
41
+ const status = parsed as Record<string, unknown>;
35
42
  if (typeof status.state !== "string" || !status.state.trim()) throw new Error(`Linked run status '${statusPath}' is missing state`);
36
43
  const tokens = tokenUsage(status.totalTokens)
37
44
  ?? (Array.isArray(status.steps)
@@ -123,42 +130,48 @@ export function collectGoalContinuationNotices(input: {
123
130
  retainedChildren: RetainedChild[];
124
131
  turnId: number;
125
132
  now?: number;
133
+ onError?: (missionId: string, error: unknown) => void;
126
134
  }): GoalContinuationNotice[] {
127
135
  const notices: GoalContinuationNotice[] = [];
128
136
  const seen = new Set<string>();
137
+ const onError = input.onError ?? ((missionId: string, error: unknown) => console.error("Failed to evaluate goal mission", missionId, error));
129
138
  for (const listed of listMissions(input.location).records) {
130
139
  if (listed.ownerSessionId !== input.ownerSessionId || !listed.goal || TERMINAL_MISSION_STATUSES.has(listed.status)) continue;
131
- let record = refreshGoalMission(input.location, readMission(input.location, listed.id));
132
- if (!record.goal || record.goal.status !== "active" || !record.budget) continue;
133
- if ((record.usage?.tokens ?? 0) >= record.budget.tokens) {
134
- record = updateMission(input.location, record.id, { usage: record.usage ?? { tokens: 0 } });
135
- if (record.goal?.status === "budget-exhausted") continue;
136
- }
137
- if (record.runs.some((run) => run.status && ACTIVE_RUN_STATUSES.has(run.status))) continue;
138
- if (seen.has(record.id) || !record.budget) continue;
139
- seen.add(record.id);
140
- const budget = record.budget.tokens;
141
- const used = record.usage?.tokens ?? 0;
142
- const remaining = Math.max(0, budget - used);
143
- const message = [
144
- `Goal mission needs attention: ${bounded(record.title)}`,
145
- `Mission: ${record.id}`,
146
- `Remaining budget: ${remaining} tokens (${used}/${budget} used)`,
147
- `Next ready action: ${nextReadyAction(input.location, record, input.retainedChildren)}`,
148
- ].join("\n");
149
- notices.push({
150
- missionId: record.id,
151
- message,
152
- event: {
153
- type: "needs_attention",
154
- to: "needs_attention",
155
- ts: input.now ?? Date.now(),
156
- runId: `goal-${record.id}-turn-${input.turnId}`,
157
- agent: "goal mission",
140
+ try {
141
+ let record = refreshGoalMission(input.location, readMission(input.location, listed.id));
142
+ if (!record.goal || record.goal.status !== "active" || !record.budget) continue;
143
+ if ((record.usage?.tokens ?? 0) >= record.budget.tokens) {
144
+ record = updateMission(input.location, record.id, { usage: record.usage ?? { tokens: 0 } });
145
+ if (record.goal?.status === "budget-exhausted") continue;
146
+ }
147
+ if (record.runs.some((run) => run.status && ACTIVE_RUN_STATUSES.has(run.status))) continue;
148
+ if (seen.has(record.id) || !record.budget) continue;
149
+ seen.add(record.id);
150
+ const budget = record.budget.tokens;
151
+ const used = record.usage?.tokens ?? 0;
152
+ const remaining = Math.max(0, budget - used);
153
+ const message = [
154
+ `Goal mission needs attention: ${bounded(record.title)}`,
155
+ `Mission: ${record.id}`,
156
+ `Remaining budget: ${remaining} tokens (${used}/${budget} used)`,
157
+ `Next ready action: ${nextReadyAction(input.location, record, input.retainedChildren)}`,
158
+ ].join("\n");
159
+ notices.push({
160
+ missionId: record.id,
158
161
  message,
159
- reason: "idle",
160
- },
161
- });
162
+ event: {
163
+ type: "needs_attention",
164
+ to: "needs_attention",
165
+ ts: input.now ?? Date.now(),
166
+ runId: `goal-${record.id}-turn-${input.turnId}`,
167
+ agent: "goal mission",
168
+ message,
169
+ reason: "idle",
170
+ },
171
+ });
172
+ } catch (error) {
173
+ onError(listed.id, error);
174
+ }
162
175
  }
163
176
  return notices;
164
177
  }
@@ -562,7 +562,16 @@ export function listGlobalMissions(globalIndexDir: string): GlobalMissionListRes
562
562
  try {
563
563
  const record = parseMissionRecord(JSON.parse(fs.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
564
564
  if (record.id !== entry.missionId) throw new Error(`record id '${record.id}' does not match index id '${entry.missionId}'`);
565
- entries.push({ ...entry, stale: false });
565
+ const projection: MissionIndexEntry = {
566
+ ...entry,
567
+ title: record.title,
568
+ status: record.status,
569
+ updatedAt: record.updatedAt,
570
+ };
571
+ delete projection.lastRunId;
572
+ const lastRunId = record.runs.at(-1)?.runId;
573
+ if (lastRunId) projection.lastRunId = lastRunId;
574
+ entries.push({ ...projection, stale: false });
566
575
  } catch (error) {
567
576
  if ((error as NodeJS.ErrnoException).code === "ENOENT") {
568
577
  try {
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
- import { BUILTIN_AGENT_NAMES } from "../agents/agents.ts";
5
+ import { BUILTIN_AGENT_NAMES, validateOptionalMachine } from "../agents/agents.ts";
6
6
  import { getPiSpawnCommand } from "../runs/shared/pi-spawn.ts";
7
7
  import { findModelInfo, getSupportedThinkingLevels, splitKnownThinkingSuffix, toModelInfo } from "../shared/model-info.ts";
8
8
  import { getAgentDir } from "../shared/utils.ts";
@@ -20,7 +20,7 @@ export type RecommendedRoleTier = "cheap" | "medium" | "strong";
20
20
  interface ProfileAgentOverride {
21
21
  model?: string;
22
22
  thinking?: string | false;
23
- machine?: string;
23
+ machine?: string | false;
24
24
  }
25
25
 
26
26
  export interface SubagentProfileFile {
@@ -144,6 +144,9 @@ function validateSubagentProfile(filePath: string, parsed: Record<string, unknow
144
144
  if (thinking !== undefined && thinking !== false && typeof thinking !== "string") {
145
145
  throw new Error(`Profile '${filePath}' has invalid thinking for '${name}'; expected a string or false.`);
146
146
  }
147
+ if (override.machine !== undefined && override.machine !== false) {
148
+ override.machine = validateOptionalMachine(override.machine, `Profile '${filePath}' has invalid machine for '${name}'`);
149
+ }
147
150
  if ((override as Record<string, unknown>).fallbackModels !== undefined) throw new Error(`Profile '${filePath}' uses removed field fallbackModels for '${name}'; configure one model instead.`);
148
151
  }
149
152
  const disableBuiltins = (subagents as Record<string, unknown>).disableBuiltins;
@@ -17,6 +17,7 @@ import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
17
17
  import { planChildLaunch, projectChainOutputSchemas, resolveStepBehavior, suppressProgressForReadOnlyTask, type ResolvedStepBehavior } from "../shared/child-launch-plan.ts";
18
18
  import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
19
19
  import { applyThinkingSuffix, getHostBuiltinToolNames, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/child-tool-plan.ts";
20
+ import { assertClaudeCodeModelScope, isClaudeCodeAdapterId, resolveClaudeCodeOverride, type ClaudeCodeOverride } from "../shared/claude-code-adapter.ts";
20
21
  import { injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
21
22
  import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.ts";
22
23
  import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile, type ChainStep, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
@@ -89,7 +90,7 @@ import { resolvePermissionRules, type PermissionConfig } from "../shared/permiss
89
90
  import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
90
91
  import { omitGitRoutingEnv } from "../shared/git-environment.ts";
91
92
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
92
- import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
93
+ import { assertRequiredChildExtensionsAdmitted, resolveRequiredChildExtensions, writeRetainedRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
93
94
 
94
95
  const require = nodeModule.createRequire(import.meta.url);
95
96
  const piPackageRoot = resolveAsyncPiPackageRoot();
@@ -253,6 +254,7 @@ interface AsyncChainParams {
253
254
  /** Global cap on simultaneously-running subagent tasks within the async run. */
254
255
  globalConcurrencyLimit?: number;
255
256
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
257
+ requiredExtensions?: RequiredChildExtensionSnapshot;
256
258
  thinkingCeiling?: ThinkingLevel;
257
259
  runFanoutBudget?: RunFanoutBudgetDescriptor;
258
260
  parentWorkflowRunId?: string;
@@ -394,6 +396,8 @@ export interface AsyncRunnerStepBuildParams {
394
396
  /** PI_SUBAGENT_TOOL_TIMEOUT_MS override (lowest precedence). */
395
397
  toolTimeoutMsEnv?: string | undefined;
396
398
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
399
+ /** Retained snapshot from the launch being continued; takes precedence over the live registry, as in single launches. */
400
+ requiredExtensions?: RequiredChildExtensionSnapshot;
397
401
  thinkingCeiling?: ThinkingLevel;
398
402
  }
399
403
 
@@ -884,6 +888,23 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
884
888
  }
885
889
  }
886
890
 
891
+ /**
892
+ * An explicit `thinking: false` clears the level, so only `undefined` falls
893
+ * through to the agent's own value. Treating `false` as absent would silently
894
+ * apply the agent default the caller just cleared.
895
+ */
896
+ export function resolveClaudeCodeThinking(source: string | false | undefined, fallback: string | false | undefined): string | undefined {
897
+ const value = source === undefined ? fallback : source;
898
+ return typeof value === "string" ? value : undefined;
899
+ }
900
+
901
+ /** A pinned Claude Code model cannot survive pane-native saved-machine placement, which
902
+ * owns the remote model registry, so the combination fails instead of losing both flags. */
903
+ export function assertClaudeCodeOverrideIsLocal(agent: string, machine: string | undefined, override: ClaudeCodeOverride | undefined): void {
904
+ if (!machine || !override) return;
905
+ throw new Error(`Agent '${agent}' requested machine '${machine}', but a Claude Code model or thinking level cannot be honored on a saved machine. Remove the model or thinking request, or run the agent locally.`);
906
+ }
907
+
887
908
  function formatAsyncStartError(mode: SubagentRunMode, message: string): AsyncExecutionResult {
888
909
  return {
889
910
  content: [{ type: "text", text: message }],
@@ -1001,6 +1022,12 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1001
1022
  const externalRunnerType = a.runner?.type;
1002
1023
  const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: a.name, runnerType: a.runner?.type, adapter: a.runner?.type === "external-cli" ? a.runner.adapter : undefined, worktree: s.worktree });
1003
1024
  if (machineUnsupported) throw new AsyncStartValidationError(machineUnsupported);
1025
+ const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1026
+ try {
1027
+ assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: a.name, runnerType: a.runner?.type, machine: requestedMachine });
1028
+ } catch (error) {
1029
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1030
+ }
1004
1031
  let machine: HerdrMachineReference | undefined;
1005
1032
  let machineEnv: Record<string, string> | undefined;
1006
1033
  if (requestedMachine) {
@@ -1012,9 +1039,12 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1012
1039
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1013
1040
  }
1014
1041
  }
1042
+ // A code-owned Claude Code adapter owns its argv, but it does accept an explicit
1043
+ // model/thinking request; those become --model/--effort on the launch below.
1044
+ const claudeCodeAdapter = a.runner?.type === "external-cli" && isClaudeCodeAdapterId(a.runner.adapter);
1015
1045
  if (externalRunner) {
1016
1046
  const unsupported: string[] = [];
1017
- if (s.model !== undefined) unsupported.push("model override");
1047
+ if (s.model !== undefined && !claudeCodeAdapter) unsupported.push("model override");
1018
1048
  if (effectiveBehavior.outputSchema !== undefined) unsupported.push("structured output");
1019
1049
  if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1020
1050
  if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
@@ -1094,6 +1124,23 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1094
1124
  { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
1095
1125
  );
1096
1126
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
1127
+ let claudeCodeOverride: ClaudeCodeOverride | undefined;
1128
+ if (claudeCodeAdapter) {
1129
+ try {
1130
+ claudeCodeOverride = resolveClaudeCodeOverride({
1131
+ model: typeof s.model === "string" ? s.model : undefined,
1132
+ agent: a,
1133
+ thinking: resolveClaudeCodeThinking(thinkingOverride, a.thinking),
1134
+ thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, a.maxThinking, ctx.childRuntime?.thinkingCeiling),
1135
+ agentName: a.name,
1136
+ runId: id,
1137
+ });
1138
+ assertClaudeCodeModelScope({ scopes: modelScopes, model: claudeCodeOverride?.model, agent: a.name, runId: id });
1139
+ assertClaudeCodeOverrideIsLocal(a.name, machine ? requestedMachine : undefined, claudeCodeOverride);
1140
+ } catch (error) {
1141
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1142
+ }
1143
+ }
1097
1144
  const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
1098
1145
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
1099
1146
  const contextLimit = model ? findModelInfo(model, availableModels, a.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
@@ -1130,7 +1177,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1130
1177
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
1131
1178
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
1132
1179
  const fast = s.fast ?? params.fast ?? a.fast;
1133
- const requiredExtensions = externalRunner ? [] : ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1180
+ const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1134
1181
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1135
1182
  const toolPlan = resolvePiLaunchToolPlan({
1136
1183
  tools: a.tools,
@@ -1167,6 +1214,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1167
1214
  agent: s.agent,
1168
1215
  task,
1169
1216
  ...(a.runner ? { runner: a.runner } : {}),
1217
+ ...(claudeCodeOverride ? { claudeCodeOverrideArgs: claudeCodeOverride.args } : {}),
1170
1218
  ...(machine ? { machine } : {}),
1171
1219
  ...(machineEnv ? { machineEnv } : {}),
1172
1220
  ...(params.contextForAgent ? { context: params.contextForAgent(s.agent) } : {}),
@@ -1461,6 +1509,7 @@ export function executeAsyncChain(
1461
1509
  toolTimeoutMsEnv: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
1462
1510
  capabilityCeiling,
1463
1511
  thinkingCeiling: params.thinkingCeiling,
1512
+ requiredExtensions: params.requiredExtensions,
1464
1513
  });
1465
1514
  if ("error" in built) {
1466
1515
  try {
@@ -1504,6 +1553,12 @@ export function executeAsyncChain(
1504
1553
  const initialStatusAt = Date.now();
1505
1554
  const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1506
1555
  const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
1556
+ try {
1557
+ writeRetainedRequiredChildExtensions(asyncDir, params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(launchParentSessionId ?? undefined));
1558
+ } catch (error) {
1559
+ fs.rmSync(asyncDir, { recursive: true, force: true });
1560
+ return formatAsyncStartError(resultMode, `Failed to record required child extensions: ${error instanceof Error ? error.message : String(error)}`);
1561
+ }
1507
1562
 
1508
1563
  let spawnResult: SpawnRunnerResult = {};
1509
1564
  try {
@@ -1759,11 +1814,14 @@ export function executeAsyncSingle(
1759
1814
  const externalRunnerType = agentConfig.runner?.type;
1760
1815
  const permissionRules = resolvePermissionRules(ctx.permissions, agentConfig.permissions);
1761
1816
  const sandbox = params.sandbox ?? agentConfig.sandbox;
1817
+ // See the chain path: the Claude Code adapter accepts an explicit model/thinking
1818
+ // request even though no other external runner does.
1819
+ const claudeCodeAdapter = agentConfig.runner?.type === "external-cli" && isClaudeCodeAdapterId(agentConfig.runner.adapter);
1762
1820
  if (externalRunner) {
1763
1821
  const unsupported: string[] = [];
1764
- if (params.modelOverride !== undefined) unsupported.push("model override");
1822
+ if (params.modelOverride !== undefined && !claudeCodeAdapter) unsupported.push("model override");
1765
1823
  if ((params.fast ?? agentConfig.fast) === true) unsupported.push("fast mode");
1766
- if (params.thinkingOverride !== undefined) unsupported.push("thinking override");
1824
+ if (params.thinkingOverride !== undefined && !claudeCodeAdapter) unsupported.push("thinking override");
1767
1825
  if (params.structuredOutputSchema !== undefined) unsupported.push("structured output");
1768
1826
  if (params.acceptance !== undefined || params.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1769
1827
  if (params.toolBudget !== undefined || agentConfig.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
@@ -1784,6 +1842,12 @@ export function executeAsyncSingle(
1784
1842
  const requestedMachine = params.machine ?? agentConfig.machine;
1785
1843
  const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: agentConfig.name, runnerType: agentConfig.runner?.type, adapter: agentConfig.runner?.type === "external-cli" ? agentConfig.runner.adapter : undefined, worktree: params.worktree });
1786
1844
  if (machineUnsupported) return formatAsyncStartError("single", machineUnsupported);
1845
+ const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1846
+ try {
1847
+ assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
1848
+ } catch (error) {
1849
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1850
+ }
1787
1851
  let machine: HerdrMachineReference | undefined;
1788
1852
  let machineEnv: Record<string, string> | undefined;
1789
1853
  if (requestedMachine) {
@@ -1888,6 +1952,23 @@ export function executeAsyncSingle(
1888
1952
  } catch (error) {
1889
1953
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1890
1954
  }
1955
+ let singleClaudeCodeOverride: ClaudeCodeOverride | undefined;
1956
+ if (claudeCodeAdapter) {
1957
+ try {
1958
+ singleClaudeCodeOverride = resolveClaudeCodeOverride({
1959
+ model: typeof params.modelOverride === "string" ? params.modelOverride : undefined,
1960
+ agent: agentConfig,
1961
+ thinking: resolveClaudeCodeThinking(params.thinkingOverride, agentConfig.thinking),
1962
+ thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, agentConfig.maxThinking, ctx.childRuntime?.thinkingCeiling),
1963
+ agentName: agentConfig.name,
1964
+ runId: id,
1965
+ });
1966
+ assertClaudeCodeModelScope({ scopes: modelScopes, model: singleClaudeCodeOverride?.model, agent: agentConfig.name, runId: id });
1967
+ assertClaudeCodeOverrideIsLocal(agentConfig.name, machine ? requestedMachine : undefined, singleClaudeCodeOverride);
1968
+ } catch (error) {
1969
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1970
+ }
1971
+ }
1891
1972
  const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1892
1973
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1893
1974
  const contextLimit = model ? findModelInfo(model, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
@@ -1940,7 +2021,7 @@ export function executeAsyncSingle(
1940
2021
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1941
2022
  }
1942
2023
  }
1943
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
2024
+ const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1944
2025
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1945
2026
  const toolPlan = resolvePiLaunchToolPlan({
1946
2027
  tools: agentConfig.tools,
@@ -2077,6 +2158,7 @@ export function executeAsyncSingle(
2077
2158
  agent,
2078
2159
  task: taskText,
2079
2160
  ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
2161
+ ...(singleClaudeCodeOverride ? { claudeCodeOverrideArgs: singleClaudeCodeOverride.args } : {}),
2080
2162
  ...(machine ? { machine } : {}),
2081
2163
  ...(!externalRunner && machine && params.reads !== undefined ? { remoteReads: params.reads } : {}),
2082
2164
  ...(machineEnv ? { machineEnv } : {}),
@@ -35,6 +35,7 @@ interface AsyncJobTrackerOptions {
35
35
  pollIntervalMs?: number;
36
36
  resultsDir?: string;
37
37
  widgetEnabled?: boolean;
38
+ widgetCollapsed?: boolean;
38
39
  platform?: NodeJS.Platform;
39
40
  onJobTerminal?: () => void;
40
41
  watch?: typeof fs.watch;
@@ -104,7 +105,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
104
105
  };
105
106
  const rerenderWidget = (ctx: ExtensionContext, jobs = Array.from(state.asyncJobs.values())) => {
106
107
  if (state.widgetsSuspended) return;
107
- renderWidget(ctx, options.widgetEnabled === false ? [] : jobs);
108
+ renderWidget(ctx, options.widgetEnabled === false ? [] : jobs, options.widgetCollapsed);
108
109
  (ctx.ui as { requestRender?: () => void }).requestRender?.();
109
110
  };
110
111
  const rerenderLastWidget = (jobs = Array.from(state.asyncJobs.values())) => {
@@ -124,7 +125,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
124
125
  if (state.widgetsSuspended) return;
125
126
  const requestRender = (ctx.ui as { requestRender?: () => void }).requestRender;
126
127
  if (requestRender) requestRender.call(ctx.ui);
127
- else renderWidget(ctx, Array.from(state.asyncJobs.values()));
128
+ else renderWidget(ctx, Array.from(state.asyncJobs.values()), options.widgetCollapsed);
128
129
  });
129
130
  };
130
131
  const refreshWidget = (ctx: ExtensionContext) => rerenderWidget(ctx);
@@ -18,8 +18,10 @@ function errorMessage(error: unknown): string {
18
18
  function runnerExitedWithoutResult(asyncDir: string, runId: string, resultPath: string): boolean {
19
19
  const status = readStatus(asyncDir);
20
20
  if (!status || (status.state !== "running" && status.state !== "queued") || typeof status.pid !== "number") return false;
21
- if (status.pidNamespaceScope !== undefined && status.pidNamespaceScope !== currentPidNamespaceScope()) return false;
22
- if (checkPidLiveness(status.pid) !== "dead") return false;
21
+ const observedScope = currentPidNamespaceScope();
22
+ if (status.pidNamespaceScope !== undefined && status.pidNamespaceScope !== observedScope) return false;
23
+ const pidScopeVerified = status.pidNamespaceScope !== undefined && status.pidNamespaceScope === observedScope;
24
+ if (checkPidLiveness(status.pid, undefined, pidScopeVerified) !== "dead") return false;
23
25
  return !fs.existsSync(resultPath) && !(status.sessionId && resultPayloadPathForSessionRun(asyncDir, status.sessionId, runId));
24
26
  }
25
27
 
@@ -74,6 +74,44 @@ export interface SteerRequest {
74
74
  source?: string;
75
75
  }
76
76
 
77
+ export interface CommandRequest {
78
+ type: "command";
79
+ id: string;
80
+ ownerId: string;
81
+ operation: "status" | "yield" | "cancel";
82
+ toolCallId?: string;
83
+ deadlineAt: number;
84
+ }
85
+
86
+ function validCommandRequest(raw: unknown): raw is CommandRequest {
87
+ if (!raw || typeof raw !== "object") return false;
88
+ const value = raw as Partial<CommandRequest>;
89
+ return value.type === "command" && typeof value.id === "string" && /^[a-f0-9-]{36}$/.test(value.id)
90
+ && typeof value.ownerId === "string" && /^[a-f0-9-]{36}$/.test(value.ownerId)
91
+ && (value.operation === "status" || value.operation === "yield" || value.operation === "cancel")
92
+ && Number.isSafeInteger(value.deadlineAt) && value.deadlineAt! > 0
93
+ && (value.toolCallId === undefined ? value.operation === "status" : typeof value.toolCallId === "string" && value.toolCallId.length > 0 && value.toolCallId.length <= 256);
94
+ }
95
+
96
+ function commandRequestsDir(dir: string): string { return path.join(controlInboxDir(dir), "command-requests"); }
97
+ export function requestAsyncCommand(dir: string, request: CommandRequest): void {
98
+ if (!validCommandRequest(request)) throw new Error("Malformed command request.");
99
+ writeAtomicJson(path.join(commandRequestsDir(dir), `${request.id}.json`), request);
100
+ }
101
+ function consumeCommandRequests(dir: string, fsImpl: ControlChannelFs): CommandRequest[] {
102
+ const requests: CommandRequest[] = [];
103
+ for (const name of fsImpl.readdirSync(commandRequestsDir(dir)).filter((entry) => entry.endsWith(".json")).sort()) {
104
+ const file = path.join(commandRequestsDir(dir), name);
105
+ let value: unknown;
106
+ try { value = JSON.parse(fsImpl.readFileSync(file, "utf8")); }
107
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; }
108
+ try { fsImpl.rmSync(file); }
109
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
110
+ if (validCommandRequest(value)) requests.push(value);
111
+ }
112
+ return requests;
113
+ }
114
+
77
115
  const STEER_REQUESTS_DIR = "steer-requests";
78
116
  const STOP_REQUESTS_DIR = "stop-requests";
79
117
  const REVIVAL_BRIEFS_DIR = "revival-briefs";
@@ -519,6 +557,7 @@ export function watchAsyncControlInbox(
519
557
  onTimeout?: () => void;
520
558
  onStop?: (request: StopRequest) => void;
521
559
  onSteer?: (request: SteerRequest) => void;
560
+ onCommand?: (request: CommandRequest) => void;
522
561
  onError?: (error: unknown, phase: "install" | "scan" | "callback", request?: SteerRequest) => void;
523
562
  pollIntervalMs?: number;
524
563
  safetyPollIntervalMs?: number;
@@ -542,6 +581,7 @@ export function watchAsyncControlInbox(
542
581
  ...(opts.onInterrupt || opts.onTimeout || opts.onStop ? [dir] : []),
543
582
  ...(opts.onStop ? [stopRequestsDir(asyncDir)] : []),
544
583
  ...(opts.onSteer ? [steerRequestsDir(asyncDir)] : []),
584
+ ...(opts.onCommand ? [commandRequestsDir(asyncDir)] : []),
545
585
  ];
546
586
  if (dirs.length === 0) return () => {};
547
587
  try {
@@ -554,6 +594,9 @@ export function watchAsyncControlInbox(
554
594
  const check = (): void => {
555
595
  if (disposed) return;
556
596
  try {
597
+ if (opts.onCommand) for (const request of consumeCommandRequests(asyncDir, fsImpl)) {
598
+ try { opts.onCommand(request); } catch (error) { report(error, "callback"); }
599
+ }
557
600
  if (opts.onStop) for (const request of consumeStopRequestPayloads(asyncDir, fsImpl, (error) => report(error, "scan"))) {
558
601
  try { opts.onStop(request); } catch (error) { report(error, "callback"); }
559
602
  }