@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
@@ -514,7 +514,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
514
514
  if (event.message.model) {
515
515
  model = event.message.model;
516
516
  if (input.expectedModelForVerification && !hasToolCall) {
517
- const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases);
517
+ const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases, session?.virtualModelId);
518
518
  if (modelVerificationError && !error) error = modelVerificationError;
519
519
  }
520
520
  }
@@ -545,7 +545,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
545
545
  };
546
546
 
547
547
  /** Stops observing the child and returns when its extensions have shut down. */
548
- const finish = (): Promise<void> => {
548
+ const finish = async (): Promise<string | undefined> => {
549
549
  clearFinalDrainTimers();
550
550
  clearWatchdogTailTimer();
551
551
  clearAllToolTimeouts();
@@ -559,7 +559,13 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
559
559
  input.registerSteer?.(undefined);
560
560
  input.registerWatchdogStatus?.(undefined);
561
561
  unsubscribe?.();
562
- return Promise.resolve().then(() => session?.dispose()).catch(() => undefined);
562
+ let commandError: string | undefined;
563
+ if (!interrupted && !timedOut && !stopped) {
564
+ try { await session?.finishCommands?.(); }
565
+ catch (error) { commandError = error instanceof Error ? error.message : String(error); }
566
+ }
567
+ await Promise.resolve().then(() => session?.dispose()).catch(() => undefined);
568
+ return commandError;
563
569
  };
564
570
 
565
571
  /** The child run ended (or was forced to end); fold in the outcome once the child's shutdown work is done. */
@@ -599,12 +605,13 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
599
605
  if (!finalError && forced && !forcedDrainAfterFinalSuccess && !interrupted && !timedOut && !stopped) {
600
606
  finalError = "Subagent session did not settle after it was aborted.";
601
607
  }
602
- const exitCode = timedOut || stopped
608
+ let exitCode = timedOut || stopped
603
609
  ? 1
604
610
  : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal)
605
611
  ? 0
606
612
  : finalError || promptError !== undefined ? 1 : 0;
607
- void closed.then(() => {
613
+ void closed.then((commandError) => {
614
+ if (commandError) { finalError ??= commandError; exitCode = 1; }
608
615
  const result: RunChildSessionResult = omitUndefined({
609
616
  exitCode,
610
617
  messages,
@@ -613,7 +620,7 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
613
620
  durationMs: Date.now() - startedAt,
614
621
  model,
615
622
  nativeMachine: session?.machineEvidence ? { provider: "herdr", machineId: session.machineEvidence.machineId, ...(session.machineEvidence.initial ? { initialGit: session.machineEvidence.initial } : {}), ...(session.machineEvidence.final ? { finalGit: session.machineEvidence.final } : {}) } : undefined,
616
- error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal) ? undefined : finalError,
623
+ error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal && !commandError) ? undefined : finalError,
617
624
  finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage() : error ?? timeoutMessage()) : finalOutput,
618
625
  outputState: finalOutput.trim() ? "present" : "absent",
619
626
  interrupted: interrupted || undefined,
@@ -15,10 +15,11 @@ import * as path from "node:path";
15
15
  export const JITI_ALIAS_ENV = "JITI_ALIAS";
16
16
 
17
17
  /** Specifiers the runner's import graph may use, with the package and export subpath each resolves to. */
18
- export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string; subpath: string }> = [
18
+ export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string; subpath: string; optional?: boolean }> = [
19
19
  { specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
20
20
  { specifier: "@earendil-works/pi-agent-core", pkg: "@earendil-works/pi-agent-core", subpath: "." },
21
- { specifier: "@earendil-works/pi-agent-core/node", pkg: "@earendil-works/pi-agent-core", subpath: "./node" },
21
+ // Optional: hosts whose pi-agent-core declares no "./node" export cannot import it, so no alias is needed.
22
+ { specifier: "@earendil-works/pi-agent-core/node", pkg: "@earendil-works/pi-agent-core", subpath: "./node", optional: true },
22
23
  { specifier: "@earendil-works/pi-tui", pkg: "@earendil-works/pi-tui", subpath: "." },
23
24
  { specifier: "@earendil-works/pi-ai", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
24
25
  { specifier: "@earendil-works/pi-ai/compat", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
@@ -160,10 +161,12 @@ export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record
160
161
  // hosts retain the required aliases, rather than hiding a broken install.
161
162
  const stableVersion = typeof hostManifest?.version === "string" ? /^0\.(\d+)\.\d+$/.exec(hostManifest.version) : null;
162
163
  const isPreChord = stableVersion !== null && Number(stableVersion[1]) < 85;
163
- const required = [...HOST_PEER_ALIASES, ...(isPreChord ? [] : CHORD_PEER_ALIASES)];
164
- for (const { specifier, pkg, subpath } of required) {
164
+ const required: ReadonlyArray<(typeof HOST_PEER_ALIASES)[number]> = [...HOST_PEER_ALIASES, ...(isPreChord ? [] : CHORD_PEER_ALIASES)];
165
+ for (const { specifier, pkg, subpath, optional } of required) {
165
166
  const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
166
167
  const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
168
+ // An optional subpath the package does not declare is unreachable, so skip it; a declared but missing file still fails.
169
+ if (optional && packageDir && target === undefined) continue;
167
170
  // Native loaders short-circuit resolution, so aliases must retain the real package's dependency scope.
168
171
  if (target && fs.existsSync(target)) {
169
172
  aliases[specifier] = fs.realpathSync(target);
@@ -16,6 +16,7 @@ import { resolveGitRepositoryIdentity } from "../../workflows/chat-progress.ts";
16
16
  import { getConfigDirName } from "../../shared/utils.ts";
17
17
  import { normalizeWorktreeBaseRef } from "../shared/worktree.ts";
18
18
  import { deepFreezeWorkflowArgs, normalizeWorkflowArgs } from "../../workflows/workflow-resources.ts";
19
+ import { readMission, resolveMissionStoreLocation, validateMissionId } from "../../missions/store.ts";
19
20
 
20
21
  export const SCHEDULED_RUN_ACTIONS = [
21
22
  "schedule.create",
@@ -41,10 +42,10 @@ export type ScheduleRunState = "running" | "skipped" | "missed" | "completed" |
41
42
  export type ScheduleTrigger =
42
43
  | { kind: "once"; at: string; nextRunAt?: string }
43
44
  | { kind: "interval"; every: string; everyMs: number; anchorAt: string; nextRunAt: string };
44
- export type ScheduleTarget = { workflowScript: string; args: Record<string, unknown>; baseRef?: string };
45
+ export type ScheduleTarget = { workflowScript: string; args: Record<string, unknown>; baseRef?: string; missionId?: string };
45
46
 
46
47
  export interface ScheduleRecord {
47
- schemaVersion: 1;
48
+ schemaVersion: 1 | 2;
48
49
  id: string;
49
50
  name: string;
50
51
  cwd: string;
@@ -284,17 +285,23 @@ function readJson(file: string, label: string): unknown {
284
285
 
285
286
  function parseScheduleTarget(value: unknown, file: string): ScheduleTarget {
286
287
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Schedule record '${file}' has invalid trigger or target.`);
287
- const target = value as { workflowScript?: unknown; args?: unknown; baseRef?: unknown; agent?: unknown; task?: unknown };
288
+ const target = value as { workflowScript?: unknown; args?: unknown; baseRef?: unknown; missionId?: unknown; agent?: unknown; task?: unknown };
288
289
  if (typeof target.workflowScript === "string" && target.workflowScript.trim()) {
289
290
  let baseRef: string | undefined;
291
+ let missionId: string | undefined;
290
292
  try {
291
293
  baseRef = normalizeWorktreeBaseRef(target.baseRef);
292
294
  } catch (error) {
293
295
  throw new Error(`Schedule record '${file}' has an invalid baseRef: ${error instanceof Error ? error.message : String(error)}`);
294
296
  }
297
+ try {
298
+ missionId = target.missionId === undefined ? undefined : validateMissionId(target.missionId);
299
+ } catch (error) {
300
+ throw new Error(`Schedule record '${file}' has an invalid missionId: ${error instanceof Error ? error.message : String(error)}`);
301
+ }
295
302
  const normalizedArgs = normalizeWorkflowArgs(target.args);
296
303
  if ("error" in normalizedArgs) throw new Error(`Schedule record '${file}' has invalid args: ${normalizedArgs.error}`);
297
- return { workflowScript: target.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }) };
304
+ return { workflowScript: target.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }), ...(missionId === undefined ? {} : { missionId }) };
298
305
  }
299
306
  if (target.agent !== undefined || target.task !== undefined) throw new Error(`Schedule record '${file}' uses a removed legacy agent target; recreate it with schedule.create and workflow: true or a workflow script path.`);
300
307
  throw new Error(`Schedule record '${file}' requires a workflowScript target.`);
@@ -303,7 +310,7 @@ function parseScheduleTarget(value: unknown, file: string): ScheduleTarget {
303
310
  function parseSchedule(value: unknown, file: string): ScheduleRecord {
304
311
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Schedule record '${file}' must be a JSON object.`);
305
312
  const record = value as Partial<ScheduleRecord>;
306
- if (record.schemaVersion !== 1 || typeof record.id !== "string" || typeof record.name !== "string" || typeof record.cwd !== "string" || typeof record.createdAt !== "string" || typeof record.updatedAt !== "string" || typeof record.paused !== "boolean") throw new Error(`Schedule record '${file}' has invalid required fields.`);
313
+ if ((record.schemaVersion !== 1 && record.schemaVersion !== 2) || typeof record.id !== "string" || typeof record.name !== "string" || typeof record.cwd !== "string" || typeof record.createdAt !== "string" || typeof record.updatedAt !== "string" || typeof record.paused !== "boolean") throw new Error(`Schedule record '${file}' has invalid required fields.`);
307
314
  validateScheduleId(record.id);
308
315
  if (!record.trigger || typeof record.trigger !== "object" || !record.target || typeof record.target !== "object") throw new Error(`Schedule record '${file}' has invalid trigger or target.`);
309
316
  if (record.overlap !== "skip" || (record.catchUp !== "none" && record.catchUp !== "latest")) throw new Error(`Schedule record '${file}' has unsupported policy fields.`);
@@ -315,7 +322,9 @@ function parseSchedule(value: unknown, file: string): ScheduleRecord {
315
322
  if (record.sessionOnly !== undefined && typeof record.sessionOnly !== "boolean") throw new Error(`Schedule record '${file}' has invalid sessionOnly.`);
316
323
  if (record.quiet !== undefined && typeof record.quiet !== "boolean") throw new Error(`Schedule record '${file}' has invalid quiet.`);
317
324
  if (record.sessionOnly === true && (typeof record.ownerSessionFile !== "string" || !record.ownerSessionFile.trim())) throw new Error(`Schedule record '${file}' is session-only but has no owner session file.`);
318
- return { ...record, target: parseScheduleTarget(record.target, file) } as ScheduleRecord;
325
+ const target = parseScheduleTarget(record.target, file);
326
+ if ((record.schemaVersion === 2) !== (target.missionId !== undefined)) throw new Error(`Schedule record '${file}' requires schemaVersion 2 exactly when missionId is present.`);
327
+ return { ...record, target } as ScheduleRecord;
319
328
  }
320
329
 
321
330
  class ScheduleStore {
@@ -444,8 +453,10 @@ function sanitizeTarget(params: SubagentParamsLike): { target?: ScheduleTarget;
444
453
  if (params.context === "fork") return { error: "Scheduled runs require fresh context." };
445
454
  if (params.async === false) return { error: "Scheduled runs are always async." };
446
455
  let baseRef: string | undefined;
456
+ let missionId: string | undefined;
447
457
  try {
448
458
  baseRef = normalizeWorktreeBaseRef(params.baseRef);
459
+ missionId = params.missionId === undefined ? undefined : validateMissionId(params.missionId);
449
460
  } catch (error) {
450
461
  return { error: error instanceof Error ? error.message : String(error) };
451
462
  }
@@ -453,7 +464,7 @@ function sanitizeTarget(params: SubagentParamsLike): { target?: ScheduleTarget;
453
464
  if (acceptanceErrors.length) return { error: acceptanceErrors.join(" ") };
454
465
  const normalizedArgs = normalizeWorkflowArgs(params.args);
455
466
  if ("error" in normalizedArgs) return { error: normalizedArgs.error };
456
- return { target: { workflowScript: params.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }) } };
467
+ return { target: { workflowScript: params.workflowScript.trim(), args: deepFreezeWorkflowArgs(normalizedArgs.args), ...(baseRef === undefined ? {} : { baseRef }), ...(missionId === undefined ? {} : { missionId }) } };
457
468
  }
458
469
 
459
470
  function executionParams(schedule: ScheduleRecord, quiet = false): SubagentParamsLike {
@@ -462,7 +473,7 @@ function executionParams(schedule: ScheduleRecord, quiet = false): SubagentParam
462
473
  async: true,
463
474
  context: "fresh",
464
475
  cwd: schedule.cwd,
465
- mission: false,
476
+ ...(schedule.target.missionId === undefined ? { mission: false as const } : {}),
466
477
  // Scheduled fires have no operator watching, so completions must name the origin.
467
478
  scheduleOrigin: { id: schedule.id, ...(schedule.name ? { name: schedule.name } : {}), ...(quiet ? { quiet: true } : {}) },
468
479
  ...(schedule.timeoutMs === undefined ? {} : { timeoutMs: schedule.timeoutMs }),
@@ -618,7 +629,7 @@ export class ScheduledRunManager {
618
629
  if (Boolean(at) === Boolean(every)) return textResult("schedule.create requires exactly one trigger: at or every.", undefined, undefined, true);
619
630
  if (params.overlap !== undefined && params.overlap !== "skip") return textResult("This first recurring slice supports overlap='skip' only.", undefined, undefined, true);
620
631
  if (params.catchUp !== undefined && params.catchUp !== "none" && params.catchUp !== "latest") return textResult("catchUp must be 'none' or 'latest'.", undefined, undefined, true);
621
- if (params.missionId !== undefined || params.mission !== undefined || params.missionUpdate !== undefined || params.missionStatus !== undefined || params.missionScope !== undefined) return textResult("Mission attachment is deferred from this first schedule slice.", undefined, undefined, true);
632
+ if (params.mission !== undefined || params.missionUpdate !== undefined || params.missionStatus !== undefined || params.missionScope !== undefined) return textResult("Schedules accept only an existing missionId; mission creation and updates are unsupported.", undefined, undefined, true);
622
633
  if (params.on !== undefined || params.timezone !== undefined || every === "day" || every === "week" || every === "month" || every === "year") return textResult("Calendar schedules are deferred from this first safe slice. Use a fixed interval such as every:'24h' or every:'7d'.", undefined, undefined, true);
623
634
  if (params.quiet !== undefined && typeof params.quiet !== "boolean") return textResult("quiet must be a boolean.", undefined, undefined, true);
624
635
  if (at && params.quiet === true) return textResult("quiet is only supported for recurring schedules.", undefined, undefined, true);
@@ -626,6 +637,9 @@ export class ScheduledRunManager {
626
637
  if (sessionOnly && params.cwd !== undefined && !samePath(params.cwd, ctx.cwd)) return textResult("sessionOnly schedules cannot use an explicit cross-project cwd.", undefined, undefined, true);
627
638
  const ownerSessionFile = sessionOnly ? ctx.sessionManager.getSessionFile() : undefined;
628
639
  if (sessionOnly && !ownerSessionFile) return textResult("sessionOnly schedules require a persisted current session.", undefined, undefined, true);
640
+ if (target.target!.missionId !== undefined) {
641
+ readMission(resolveMissionStoreLocation({ projectRoot: path.resolve(params.cwd ?? ctx.cwd), ...(this.deps.config.missions ? { config: this.deps.config.missions } : {}) }), target.target!.missionId);
642
+ }
629
643
  const sessionId = ctx.sessionManager.getSessionId() ?? "unknown";
630
644
  if (this.deps.resolveCapabilityCeiling?.(sessionId)) return textResult("Cannot persist a schedule while a capability ceiling is active.", undefined, undefined, true);
631
645
  const pendingCount = store.list().filter(hasPendingScheduleWork).length;
@@ -643,7 +657,8 @@ export class ScheduledRunManager {
643
657
  trigger = { kind: "interval", every: every!, everyMs, anchorAt: timestamp(now), nextRunAt: timestamp(now + everyMs) };
644
658
  }
645
659
  const schedule: ScheduleRecord = {
646
- schemaVersion: 1,
660
+ // Older readers ignore unknown target fields; they must reject mission-bound definitions.
661
+ schemaVersion: target.target!.missionId === undefined ? 1 : 2,
647
662
  id,
648
663
  name: params.name?.trim() || targetLabel(target.target!),
649
664
  cwd: path.resolve(params.cwd ?? ctx.cwd),
@@ -661,18 +676,18 @@ export class ScheduledRunManager {
661
676
  store.write(schedule);
662
677
  store.appendEvent(schedule, "schedule.created");
663
678
  this.arm(schedule, store);
664
- return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${at ? `at ${at}` : `every ${every}`}\nSession only: ${schedule.sessionOnly === true ? "yes" : "no"}\nQuiet: ${schedule.quiet === true ? "yes" : "no"}\nNext: ${schedule.trigger.nextRunAt}\nTarget: ${targetLabel(schedule.target)}`, [schedule]);
679
+ return textResult(`Created schedule ${id}.\nName: ${schedule.name}\nTrigger: ${at ? `at ${at}` : `every ${every}`}\nSession only: ${schedule.sessionOnly === true ? "yes" : "no"}\nQuiet: ${schedule.quiet === true ? "yes" : "no"}\nNext: ${schedule.trigger.nextRunAt}\nTarget: ${targetLabel(schedule.target)}${schedule.target.missionId === undefined ? "" : `\nMission: ${schedule.target.missionId}`}`, [schedule]);
665
680
  }
666
681
 
667
682
  private list(): AgentToolResult<Details> {
668
683
  const schedules = this.requireStore().list().sort((a, b) => (a.trigger.nextRunAt ?? "").localeCompare(b.trigger.nextRunAt ?? ""));
669
684
  if (!schedules.length) return textResult("No project schedules.", []);
670
- return textResult([`Project schedules: ${schedules.length}`, ...schedules.map((item) => `- ${item.id} | ${item.paused ? "paused" : item.activeRunId ? "running" : "scheduled"} | ${item.trigger.nextRunAt ?? "no next run"} | ${item.sessionOnly === true ? "session-only" : "project"} | ${item.name}`)].join("\n"), schedules);
685
+ return textResult([`Project schedules: ${schedules.length}`, ...schedules.map((item) => `- ${item.id} | ${item.paused ? "paused" : item.activeRunId ? "running" : "scheduled"} | ${item.trigger.nextRunAt ?? "no next run"} | ${item.sessionOnly === true ? "session-only" : "project"} | ${item.name}${item.target.missionId === undefined ? "" : ` | mission ${item.target.missionId}`}`)].join("\n"), schedules);
671
686
  }
672
687
 
673
688
  private show(params: SubagentParamsLike): AgentToolResult<Details> {
674
689
  const schedule = this.resolve(params);
675
- return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Session only: ${schedule.sessionOnly === true ? "yes" : "no"}`, `Quiet: ${schedule.quiet === true ? "yes" : "no"}`, `Target: ${targetLabel(schedule.target)}`, `CWD: ${shortenPath(schedule.cwd)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
690
+ return textResult([`Schedule: ${schedule.id}`, `Name: ${schedule.name}`, `State: ${schedule.paused ? "paused" : schedule.activeRunId ? "running" : "scheduled"}`, `Session only: ${schedule.sessionOnly === true ? "yes" : "no"}`, `Quiet: ${schedule.quiet === true ? "yes" : "no"}`, `Target: ${targetLabel(schedule.target)}`, schedule.target.missionId === undefined ? undefined : `Mission: ${schedule.target.missionId}`, `CWD: ${shortenPath(schedule.cwd)}`, `Next: ${schedule.trigger.nextRunAt ?? "none"}`, `Catch up: ${schedule.catchUp}`, schedule.activeRunId ? `Active run: ${schedule.activeRunId}` : undefined].filter(Boolean).join("\n"), [schedule]);
676
691
  }
677
692
 
678
693
  private history(params: SubagentParamsLike): AgentToolResult<Details> {
@@ -357,9 +357,18 @@ export function reconcileNestedAsyncDescendants(route: NestedRoute, options: Rec
357
357
  }
358
358
  }
359
359
 
360
- export function checkPidLiveness(pid: number, kill: KillFn = process.kill): PidLiveness {
360
+ export function checkPidLiveness(pid: number, kill: KillFn = process.kill, probeZombie = false): PidLiveness {
361
361
  try {
362
362
  kill(pid, 0);
363
+ if (probeZombie && process.platform === "linux") {
364
+ try {
365
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
366
+ const closeParen = stat.lastIndexOf(") ");
367
+ if (closeParen >= 0 && stat[closeParen + 2] === "Z") return "dead";
368
+ } catch {
369
+ // Fall back to kill(pid, 0) when procfs is unavailable or unreadable.
370
+ }
371
+ }
363
372
  return "alive";
364
373
  } catch (error) {
365
374
  const code = typeof error === "object" && error !== null && "code" in error
@@ -437,7 +446,9 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
437
446
  const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
438
447
  // An observer without a scope (macOS/Windows host sharing a container's temp root) cannot match a recorded one.
439
448
  const pidScopeMismatch = effectiveStatus.pidNamespaceScope !== undefined && effectiveStatus.pidNamespaceScope !== observedScope;
440
- const observedLiveness = checkPidLiveness(effectiveStatus.pid, options.kill);
449
+ // A local zombie is evidence about this runner only when its namespace is known to match.
450
+ const pidScopeVerified = effectiveStatus.pidNamespaceScope !== undefined && effectiveStatus.pidNamespaceScope === observedScope;
451
+ const observedLiveness = checkPidLiveness(effectiveStatus.pid, options.kill, pidScopeVerified);
441
452
  const liveness = observedLiveness === "dead" && pidScopeMismatch ? "unknown" : observedLiveness;
442
453
  if (liveness !== "dead") {
443
454
  const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
@@ -99,6 +99,7 @@ import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
99
99
  import { currentPidNamespaceScope } from "./pid-namespace.ts";
100
100
  import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, unconsumedSteerReason, updateSteeringTarget } from "./steering.ts";
101
101
  import { PROMPT_REDACTED, detectSubagentError, extractTextFromContent, extractToolArgsPreview, formatEmptyTerminalAssistantResponseError, getAgentDir, getFinalOutput, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.ts";
102
+ import { planBackgroundRunHistory, recordRun } from "../shared/run-history.ts";
102
103
  import { planAbortRecovery } from "../shared/abort-recovery.ts";
103
104
  import {
104
105
  createMutatingFailureState,
@@ -926,7 +927,7 @@ export async function runSingleStepInner(
926
927
  const adapterLaunch = step.runner.adapter === "codex-exec" || step.runner.adapter === "codex-exec-writer"
927
928
  ? resolveCodexExecLaunch({ adapter: step.runner.adapter, command: step.runner.command, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
928
929
  : step.runner.adapter === "claude-code" || step.runner.adapter === "claude-code-writer"
929
- ? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command })
930
+ ? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command, overrideArgs: step.claudeCodeOverrideArgs })
930
931
  : step.runner.adapter === "cursor-agent" || step.runner.adapter === "cursor-agent-writer"
931
932
  ? resolveCursorAgentLaunch({ adapter: step.runner.adapter, command: step.runner.command, cwd: externalCwd, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
932
933
  : undefined;
@@ -1668,7 +1669,12 @@ function markParallelGroupSetupFailure(input: {
1668
1669
  if (!task) throw new Error(`Missing parallel task at index ${taskIndex}`);
1669
1670
  const stopped = statusStep.stopped || statusStep.stopRequested || input.statusPayload.stopped;
1670
1671
  const paused = !stopped && input.statusPayload.state === "paused";
1672
+ const timedOut = !stopped && !paused && input.statusPayload.timedOut === true;
1671
1673
  statusStep.status = stopped ? "stopped" : paused ? "paused" : "failed";
1674
+ // Mirror the run-level timeout onto the step so consumers (status readers,
1675
+ // run-history recording) see timed_out rather than a bare failure — the
1676
+ // StepResult below already carries it, the status step must too.
1677
+ if (timedOut) statusStep.timedOut = true;
1672
1678
  statusStep.startedAt = input.failedAt;
1673
1679
  statusStep.endedAt = input.failedAt;
1674
1680
  statusStep.durationMs = 0;
@@ -1885,6 +1891,11 @@ export async function runSubagent(
1885
1891
  let previousOutput = "";
1886
1892
  const outputs: ChainOutputMap = {};
1887
1893
  const results: StepResult[] = [];
1894
+ // Flat indices of steps a child session was actually dispatched for — the
1895
+ // ground truth for run-history: stopRunner/timeoutRunner/fail-fast/budget
1896
+ // skips relabel never-launched steps to terminal statuses, so status alone
1897
+ // cannot distinguish them from steps that really ran.
1898
+ const launchedFlatIndices = new Set<number>();
1888
1899
  const overallStartTime = Date.now();
1889
1900
  const shareEnabled = config.share === true;
1890
1901
  const asyncDir = config.asyncDir;
@@ -2654,7 +2665,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2654
2665
  const activeLongRunningSteps = new Set<number>();
2655
2666
  const mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());
2656
2667
  const pendingToolResults: Array<{ tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined> = initialStatusSteps.map(() => undefined);
2657
- type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string; blocksSupervisor: boolean };
2668
+ type ActiveToolCall = { attentionEmitted?: boolean; key: string; tool: string; args: string; startedAt: number; path?: string; blocksSupervisor: boolean };
2658
2669
  const activeToolCalls = initialStatusSteps.map(() => new Map<string, ActiveToolCall>());
2659
2670
  const activeToolKeysByName = initialStatusSteps.map(() => new Map<string, string[]>());
2660
2671
  const activeToolSequences = initialStatusSteps.map(() => 0);
@@ -2718,7 +2729,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2718
2729
  return key ? removeActiveToolCallKey(flatIndex, key) : undefined;
2719
2730
  };
2720
2731
  const openToolAttentionTarget = (flatIndex: number, now: number): ActiveToolCall | undefined => [...(activeToolCalls[flatIndex]?.values() ?? [])]
2721
- .filter((active) => shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
2732
+ .filter((active) => !active.attentionEmitted && shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
2722
2733
  .sort((left, right) => left.startedAt - right.startedAt)[0];
2723
2734
  const supervisorAttentionSteps = new Map<number, ActivityState | undefined>();
2724
2735
  const mutatingFailureWindowMs = 5 * 60_000;
@@ -2770,9 +2781,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2770
2781
  };
2771
2782
  const maybeEmitOpenToolAttention = (flatIndex: number, now: number): boolean => {
2772
2783
  const step = statusPayload.steps[flatIndex];
2773
- if (!step || step.status !== "running" || step.activityState === "needs_attention") return false;
2784
+ if (!step || step.status !== "running") return false;
2774
2785
  const target = openToolAttentionTarget(flatIndex, now);
2775
2786
  if (!target) return false;
2787
+ target.attentionEmitted = true;
2788
+ // Keep this attention when a concurrent supervisor request ends and restores its saved state.
2789
+ if (supervisorAttentionSteps.has(flatIndex)) supervisorAttentionSteps.set(flatIndex, "needs_attention");
2776
2790
  const previous = step.activityState;
2777
2791
  step.activityState = "needs_attention";
2778
2792
  statusPayload.activityState = "needs_attention";
@@ -2791,6 +2805,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
2791
2805
  tokens: step.tokens?.total,
2792
2806
  toolCount: step.toolCount,
2793
2807
  currentTool: target.tool,
2808
+ toolCallId: target.key.startsWith("id:") ? target.key.slice(3) : undefined,
2794
2809
  currentToolDurationMs: toolDurationMs,
2795
2810
  currentPath: target.path,
2796
2811
  })));
@@ -3622,6 +3637,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3622
3637
  return omitUndefinedProperties({
3623
3638
  agent: task.agent,
3624
3639
  ...(task.sessionName ? { sessionName: task.sessionName } : {}),
3640
+ ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
3625
3641
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
3626
3642
  ...(task.context ? { context: task.context } : {}),
3627
3643
  ...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
@@ -3724,6 +3740,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3724
3740
  return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3725
3741
  }
3726
3742
  const taskStartTime = Date.now();
3743
+ launchedFlatIndices.add(fi);
3727
3744
  statusPayload.currentStep = fi;
3728
3745
  requiredStatusStep(statusPayload, fi).status = "running";
3729
3746
  delete requiredStatusStep(statusPayload, fi).error;
@@ -4129,6 +4146,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4129
4146
  }
4130
4147
 
4131
4148
  const taskStartTime = Date.now();
4149
+ launchedFlatIndices.add(fi);
4132
4150
  statusPayload.currentStep = fi;
4133
4151
  requiredStatusStep(statusPayload, fi).status = "running";
4134
4152
  delete requiredStatusStep(statusPayload, fi).error;
@@ -4518,6 +4536,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4518
4536
  }
4519
4537
  const singleCwd = singleWorktreeSetup?.worktrees[0]?.agentCwd ?? cwd;
4520
4538
  const stepStartTime = Date.now();
4539
+ launchedFlatIndices.add(flatIndex);
4521
4540
  statusPayload.currentStep = flatIndex;
4522
4541
  requiredStatusStep(statusPayload, flatIndex).status = "running";
4523
4542
  delete requiredStatusStep(statusPayload, flatIndex).activityState;
@@ -5101,6 +5120,26 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
5101
5120
  usageBudget: statusPayload.usageBudget,
5102
5121
  }),
5103
5122
  );
5123
+ // Paused runs record an interrupted attempt; a later resume records another.
5124
+ for (const historyEntry of planBackgroundRunHistory({
5125
+ steps,
5126
+ resultMode,
5127
+ statusSteps: statusPayload.steps.map((step, index) => ({
5128
+ agent: step.agent,
5129
+ status: step.status,
5130
+ durationMs: step.durationMs,
5131
+ timedOut: step.timedOut,
5132
+ stopped: step.stopped,
5133
+ launched: launchedFlatIndices.has(index),
5134
+ })),
5135
+ stepResults: results,
5136
+ runDurationMs: runEndedAt - overallStartTime,
5137
+ stopped,
5138
+ interrupted,
5139
+ timedOut,
5140
+ })) {
5141
+ recordRun(historyEntry.agent, historyEntry.task, historyEntry.exitCode, historyEntry.durationMs, historyEntry.terminal);
5142
+ }
5104
5143
  writeRunLog(logPath, omitUndefinedProperties({
5105
5144
  id,
5106
5145
  mode: statusPayload.mode,
@@ -0,0 +1,41 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { Details, SubagentState } from "../../shared/types.ts";
3
+ import { readStatus } from "../../shared/utils.ts";
4
+ import type { ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
5
+ import { supervisorChannelDir } from "../shared/child-tool-plan.ts";
6
+ import { controlChildCommand, type CommandOperation } from "../shared/child-commands.ts";
7
+
8
+ function commandChildren(state: SubagentState, target: ResolvedSubagentRunId): Array<{ index: number; agent: string }> {
9
+ if (!state.currentSessionId) throw new Error("Command controls require an owning parent session.");
10
+ if (target.kind === "nested") throw new Error("Command controls support direct local Pi children only.");
11
+ if (target.kind === "foreground") {
12
+ const live = state.foregroundControls.get(target.id);
13
+ const retained = state.foregroundRuns?.get(target.id);
14
+ if ((live?.sessionId ?? retained?.sessionId) !== state.currentSessionId) throw new Error("Run is not owned by this session.");
15
+ if (live?.activeChildren?.size) return [...live.activeChildren.values()].map(({ index, agent }) => ({ index, agent }));
16
+ if (live?.currentAgent) return [{ index: live.currentIndex ?? 0, agent: live.currentAgent }];
17
+ return retained?.children.map(({ index, agent }) => ({ index, agent })) ?? [];
18
+ }
19
+ const status = target.location.asyncDir ? readStatus(target.location.asyncDir) : undefined;
20
+ if (status?.sessionId !== state.currentSessionId) throw new Error("Run is not owned by this session.");
21
+ return status.steps?.map((step, index) => ({ index, agent: step.agent })) ?? [];
22
+ }
23
+
24
+ export async function commandAction(input: {
25
+ state: SubagentState;
26
+ target: ResolvedSubagentRunId;
27
+ operation: CommandOperation;
28
+ index?: number;
29
+ toolCallId?: string;
30
+ signal?: AbortSignal;
31
+ }): Promise<AgentToolResult<Details>> {
32
+ const children = commandChildren(input.state, input.target);
33
+ if (input.index === undefined && children.length !== 1) throw new Error("Command controls require an explicit child index for multi-child runs.");
34
+ const child = input.index === undefined ? children[0] : children.find(({ index }) => index === input.index);
35
+ if (!child) throw new Error(`No child index ${input.index ?? 0} in this run.`);
36
+ const result = await controlChildCommand(supervisorChannelDir(input.target.id, child.agent, child.index), input.operation, input.toolCallId, input.signal);
37
+ return {
38
+ content: [{ type: "text", text: JSON.stringify({ runId: input.target.id, index: child.index, commands: result.commands, closed: result.closed }) }],
39
+ details: { mode: "management", results: [], commands: result.commands },
40
+ };
41
+ }
@@ -787,7 +787,13 @@ async function runSingleAttempt(
787
787
  // JSONL artifact flush is best effort.
788
788
  });
789
789
  // Report the run only after the child's extensions have shut down.
790
- void Promise.resolve().then(() => session?.dispose()).catch(() => undefined).then(() => {
790
+ void Promise.resolve().then(async () => {
791
+ if (code === 0 && !result.interrupted && !result.timedOut && !result.stopped && !abortedBySignal) {
792
+ try { await session?.finishCommands?.(); }
793
+ catch (error) { result.error = error instanceof Error ? error.message : String(error); code = 1; }
794
+ }
795
+ await session?.dispose();
796
+ }).catch(() => undefined).then(() => {
791
797
  resolve(code);
792
798
  });
793
799
  };
@@ -806,7 +812,7 @@ async function runSingleAttempt(
806
812
  // Remember correlated ids so normalizing both forms cannot duplicate output.
807
813
  const handledToolResultIds = new Set<string>();
808
814
  const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
809
- type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string };
815
+ type ActiveToolCall = { attentionEmitted?: boolean; key: string; tool: string; args: string; startedAt: number; path?: string };
810
816
  let activeToolSequence = 0;
811
817
  const activeToolCalls = new Map<string, ActiveToolCall>();
812
818
  const activeToolKeysByName = new Map<string, string[]>();
@@ -862,12 +868,12 @@ async function runSingleAttempt(
862
868
  return key ? removeActiveToolCallKey(key) : undefined;
863
869
  };
864
870
  const openToolAttentionTarget = (now: number): ActiveToolCall | undefined => [...activeToolCalls.values()]
865
- .filter((active) => shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
871
+ .filter((active) => !active.attentionEmitted && shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
866
872
  .sort((left, right) => left.startedAt - right.startedAt)[0];
867
873
  const mutatingFailures = createMutatingFailureState();
868
874
  const mutatingFailureWindowMs = 5 * 60_000;
869
875
  const currentToolDurationMs = (now: number) => progress.currentToolStartedAt ? Math.max(0, now - progress.currentToolStartedAt) : undefined;
870
- const emitNeedsAttention = (now: number, input: { message?: string; reason?: ControlEvent["reason"]; recentFailureSummary?: string; currentTool?: string; currentPath?: string; currentToolDurationMs?: number } = {}): boolean => {
876
+ const emitNeedsAttention = (now: number, input: { message?: string; reason?: ControlEvent["reason"]; recentFailureSummary?: string; currentTool?: string; toolCallId?: string; currentPath?: string; currentToolDurationMs?: number } = {}): boolean => {
871
877
  if (!controlConfig.enabled) return false;
872
878
  const previous = progress.activityState;
873
879
  progress.activityState = "needs_attention";
@@ -886,13 +892,14 @@ async function runSingleAttempt(
886
892
  tokens: progress.tokens,
887
893
  toolCount: progress.toolCount,
888
894
  currentTool: input.currentTool ?? progress.currentTool,
895
+ toolCallId: input.toolCallId,
889
896
  currentToolDurationMs: input.currentToolDurationMs ?? currentToolDurationMs(now),
890
897
  currentPath: input.currentPath ?? progress.currentPath,
891
898
  recentFailureSummary: input.recentFailureSummary,
892
899
  taskPreview: task,
893
900
  });
894
901
  emitControlEvent(event);
895
- return previous !== "needs_attention";
902
+ return previous !== "needs_attention" || input.reason === "tool_open_threshold";
896
903
  };
897
904
  const emitActiveLongRunning = (now: number, reason: ControlEvent["reason"]): boolean => {
898
905
  if (!controlConfig.enabled || activeLongRunningNotified || progress.activityState === "needs_attention") return false;
@@ -934,13 +941,15 @@ async function runSingleAttempt(
934
941
  if (idleState === "needs_attention") {
935
942
  return progress.activityState === "needs_attention" ? false : emitNeedsAttention(now);
936
943
  }
937
- const toolAttentionTarget = progress.activityState !== "needs_attention" ? openToolAttentionTarget(now) : undefined;
944
+ const toolAttentionTarget = openToolAttentionTarget(now);
938
945
  if (toolAttentionTarget) {
946
+ toolAttentionTarget.attentionEmitted = true;
939
947
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
940
948
  return emitNeedsAttention(now, {
941
949
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1000)}s`,
942
950
  reason: "tool_open_threshold",
943
951
  currentTool: toolAttentionTarget.tool,
952
+ toolCallId: toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : undefined,
944
953
  currentPath: toolAttentionTarget.path,
945
954
  currentToolDurationMs: durationMs,
946
955
  });
@@ -1183,7 +1192,7 @@ async function runSingleAttempt(
1183
1192
  progress.model = evt.message.model;
1184
1193
  if (!result.model) result.model = evt.message.model;
1185
1194
  if (expectedModelForVerification && !hasToolCall) {
1186
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases);
1195
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases, session?.virtualModelId);
1187
1196
  if (modelVerificationError && !result.error) result.error = modelVerificationError;
1188
1197
  }
1189
1198
  }