@xzzpig/pi-subagents 0.18.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.
- package/CHANGELOG.md +129 -0
- package/README.md +1 -1
- package/docs/agents.md +32 -16
- package/docs/configuration.md +76 -9
- package/docs/extension-api.md +6 -5
- package/docs/missions.md +28 -14
- package/docs/models.md +8 -4
- package/docs/observability.md +10 -5
- package/docs/standalone-background.md +1 -1
- package/docs/tool-reference.md +90 -88
- package/docs/workflows.md +171 -173
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +6 -6
- package/prompts/review-loop.md +1 -1
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +12 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
- package/skills/pi-subagents/references/execution-controls.md +68 -67
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-management.ts +2 -2
- package/src/agents/agents.ts +66 -3
- package/src/api/preflight.ts +109 -63
- package/src/extension/config.ts +15 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +1 -0
- package/src/extension/fanout-child.ts +12 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +90 -174
- package/src/extension/public-execution.ts +72 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +29 -10
- package/src/extension/schemas.ts +40 -135
- package/src/extension/tool-activation.ts +57 -108
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/native-supervisor-channel.ts +4 -1
- package/src/missions/goal-driver.ts +44 -31
- package/src/missions/store.ts +10 -1
- package/src/profiles/profiles.ts +5 -2
- package/src/runs/background/async-execution.ts +146 -59
- package/src/runs/background/async-job-tracker.ts +66 -24
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/await-async-run.ts +78 -0
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +61 -2
- package/src/runs/background/notify.ts +5 -0
- package/src/runs/background/run-child-session.ts +17 -7
- package/src/runs/background/run-status.ts +6 -0
- package/src/runs/background/runner-aliases.ts +37 -6
- package/src/runs/background/runner-child-launch.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +33 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -2
- package/src/runs/background/subagent-runner.ts +58 -5
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/command-action.ts +41 -0
- package/src/runs/foreground/execution.ts +145 -131
- package/src/runs/foreground/subagent-executor.ts +546 -296
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/child-commands.ts +228 -0
- package/src/runs/shared/child-launch.ts +15 -2
- package/src/runs/shared/child-session.ts +184 -24
- package/src/runs/shared/child-tool-plan.ts +16 -4
- package/src/runs/shared/claude-code-adapter.ts +157 -2
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/external-cli-preflight.ts +54 -6
- package/src/runs/shared/external-cli-runner.ts +5 -1
- package/src/runs/shared/mcp-config-sources.ts +2 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
- package/src/runs/shared/model-resolution.ts +38 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +55 -55
- package/src/runs/shared/parallel-utils.ts +4 -0
- package/src/runs/shared/pi-spawn.ts +7 -95
- package/src/runs/shared/run-history.ts +87 -0
- package/src/runs/shared/subagent-control.ts +32 -17
- package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
- package/src/runs/shared/worktree.ts +1 -1
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/model-info.ts +9 -0
- package/src/shared/required-child-extensions.ts +39 -5
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +27 -1
- package/src/slash/prompt-template-bridge.ts +2 -2
- package/src/slash/slash-commands.ts +10 -5
- package/src/slash/subagent-cost.ts +9 -5
- package/src/slash/subagents-admin.ts +24 -24
- package/src/tui/fleet-status.ts +14 -6
- package/src/tui/fleet.ts +14 -2
- package/src/tui/render.ts +117 -56
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +23 -9
- package/src/watchdog/register-child.ts +3 -3
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +2 -2
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +117 -37
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-receipt.ts +10 -4
- package/src/workflows/workflow-resources.ts +44 -16
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
|
@@ -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,26 +285,32 @@ 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
|
-
if (target.agent !== undefined || target.task !== undefined) throw new Error(`Schedule record '${file}' uses a removed legacy agent target; recreate it with
|
|
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.`);
|
|
301
308
|
}
|
|
302
309
|
|
|
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
|
-
|
|
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 {
|
|
@@ -434,18 +443,20 @@ function publicScheduleRecord(schedule: ScheduleRecord): PublicScheduleRecord {
|
|
|
434
443
|
|
|
435
444
|
function targetLabel(target: ScheduleTarget): string {
|
|
436
445
|
const preview = previewSimpleWorkflowRun(target.workflowScript);
|
|
437
|
-
return preview?.agent ? `
|
|
446
|
+
return preview?.agent ? `workflow -> agent ${preview.agent}` : "workflow (dynamic)";
|
|
438
447
|
}
|
|
439
448
|
|
|
440
449
|
function sanitizeTarget(params: SubagentParamsLike): { target?: ScheduleTarget; error?: string } {
|
|
441
|
-
if (params.tasks || params.chain) return { error: "Recurring schedules require
|
|
442
|
-
if (params.agent !== undefined || params.task !== undefined) return { error: "schedule.create requires
|
|
443
|
-
if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) return { error: "schedule.create requires a
|
|
450
|
+
if (params.tasks || params.chain) return { error: "Recurring schedules require a workflow script; legacy tasks and chain inputs are unsupported." };
|
|
451
|
+
if (params.agent !== undefined || params.task !== undefined) return { error: "schedule.create requires workflow: true or a workflow script path, e.g. a ```js workflow block containing return runs.run('main', { agent, task })." };
|
|
452
|
+
if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) return { error: "schedule.create requires workflow: true or a workflow script path." };
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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;
|
|
@@ -12,7 +12,7 @@ import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilie
|
|
|
12
12
|
import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
|
|
13
13
|
import { updateActiveRunIndex } from "./active-run-index.ts";
|
|
14
14
|
import { createChildTranscriptWriter, type ChildTranscriptWriter } from "../../shared/child-transcript.ts";
|
|
15
|
-
import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, consumeStopRequestPayloads, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, watchAsyncControlInbox, type SteerRequest, type StopRequest } from "./control-channel.ts";
|
|
15
|
+
import { closeSteerInbox, closeStopInbox, consumeInterruptRequest, consumeSteerRequests, consumeStopRequestPayloads, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, watchAsyncControlInbox, type SteerRequest, type StopRequest } from "./control-channel.ts";
|
|
16
16
|
import { appendJsonl as appendRawJsonl, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata } from "../../shared/artifacts.ts";
|
|
17
17
|
import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.ts";
|
|
18
18
|
import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
|
|
@@ -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,
|
|
@@ -190,6 +191,8 @@ export interface SubagentRunConfig {
|
|
|
190
191
|
childSessionFactoryModule?: string;
|
|
191
192
|
/** The launching executor's own child runtime when it was itself an in-process child. */
|
|
192
193
|
inheritedChildRuntime?: InheritedChildRuntime;
|
|
194
|
+
/** The launching session's project trust; undefined keeps Pi's default for hosts without trust. */
|
|
195
|
+
projectTrusted?: boolean;
|
|
193
196
|
worktreeSetupHook?: string;
|
|
194
197
|
worktreeSetupHookTimeoutMs?: number;
|
|
195
198
|
worktreeBaseDir?: string;
|
|
@@ -685,6 +688,7 @@ interface SingleStepContext {
|
|
|
685
688
|
childSessions: ChildSessionFactory;
|
|
686
689
|
/** The launching executor's own child runtime; nested route, depth, and ceilings come from here. */
|
|
687
690
|
inheritedChildRuntime?: InheritedChildRuntime;
|
|
691
|
+
projectTrusted?: boolean;
|
|
688
692
|
registerInterrupt?: (interrupt: (() => void) | undefined) => void;
|
|
689
693
|
registerTimeout?: (interrupt: (() => void) | undefined) => void;
|
|
690
694
|
registerStop?: (stop: (() => void) | undefined) => void;
|
|
@@ -830,6 +834,7 @@ export async function runSingleStepInner(
|
|
|
830
834
|
fast: step.fast,
|
|
831
835
|
model: step.model,
|
|
832
836
|
mcpDirectTools: step.mcpDirectTools,
|
|
837
|
+
builtinMcpTools: step.builtinMcpTools,
|
|
833
838
|
cwd: step.cwd ?? ctx.cwd,
|
|
834
839
|
requireReadTool: Boolean(step.skills?.length),
|
|
835
840
|
structuredOutput: Boolean(effectiveStructuredOutput),
|
|
@@ -922,7 +927,7 @@ export async function runSingleStepInner(
|
|
|
922
927
|
const adapterLaunch = step.runner.adapter === "codex-exec" || step.runner.adapter === "codex-exec-writer"
|
|
923
928
|
? resolveCodexExecLaunch({ adapter: step.runner.adapter, command: step.runner.command, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
|
|
924
929
|
: step.runner.adapter === "claude-code" || step.runner.adapter === "claude-code-writer"
|
|
925
|
-
? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command })
|
|
930
|
+
? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command, overrideArgs: step.claudeCodeOverrideArgs })
|
|
926
931
|
: step.runner.adapter === "cursor-agent" || step.runner.adapter === "cursor-agent-writer"
|
|
927
932
|
? resolveCursorAgentLaunch({ adapter: step.runner.adapter, command: step.runner.command, cwd: externalCwd, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
|
|
928
933
|
: undefined;
|
|
@@ -1164,6 +1169,7 @@ export async function runSingleStepInner(
|
|
|
1164
1169
|
fast: step.fast,
|
|
1165
1170
|
model: step.model,
|
|
1166
1171
|
mcpDirectTools: step.mcpDirectTools,
|
|
1172
|
+
builtinMcpTools: step.builtinMcpTools,
|
|
1167
1173
|
cwd: step.cwd ?? ctx.cwd,
|
|
1168
1174
|
requireReadTool: Boolean(step.skills?.length),
|
|
1169
1175
|
structuredOutput: Boolean(effectiveStructuredOutput),
|
|
@@ -1663,7 +1669,12 @@ function markParallelGroupSetupFailure(input: {
|
|
|
1663
1669
|
if (!task) throw new Error(`Missing parallel task at index ${taskIndex}`);
|
|
1664
1670
|
const stopped = statusStep.stopped || statusStep.stopRequested || input.statusPayload.stopped;
|
|
1665
1671
|
const paused = !stopped && input.statusPayload.state === "paused";
|
|
1672
|
+
const timedOut = !stopped && !paused && input.statusPayload.timedOut === true;
|
|
1666
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;
|
|
1667
1678
|
statusStep.startedAt = input.failedAt;
|
|
1668
1679
|
statusStep.endedAt = input.failedAt;
|
|
1669
1680
|
statusStep.durationMs = 0;
|
|
@@ -1880,6 +1891,11 @@ export async function runSubagent(
|
|
|
1880
1891
|
let previousOutput = "";
|
|
1881
1892
|
const outputs: ChainOutputMap = {};
|
|
1882
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>();
|
|
1883
1899
|
const overallStartTime = Date.now();
|
|
1884
1900
|
const shareEnabled = config.share === true;
|
|
1885
1901
|
const asyncDir = config.asyncDir;
|
|
@@ -2649,7 +2665,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
2649
2665
|
const activeLongRunningSteps = new Set<number>();
|
|
2650
2666
|
const mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());
|
|
2651
2667
|
const pendingToolResults: Array<{ tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined> = initialStatusSteps.map(() => undefined);
|
|
2652
|
-
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 };
|
|
2653
2669
|
const activeToolCalls = initialStatusSteps.map(() => new Map<string, ActiveToolCall>());
|
|
2654
2670
|
const activeToolKeysByName = initialStatusSteps.map(() => new Map<string, string[]>());
|
|
2655
2671
|
const activeToolSequences = initialStatusSteps.map(() => 0);
|
|
@@ -2713,7 +2729,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
2713
2729
|
return key ? removeActiveToolCallKey(flatIndex, key) : undefined;
|
|
2714
2730
|
};
|
|
2715
2731
|
const openToolAttentionTarget = (flatIndex: number, now: number): ActiveToolCall | undefined => [...(activeToolCalls[flatIndex]?.values() ?? [])]
|
|
2716
|
-
.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 }))
|
|
2717
2733
|
.sort((left, right) => left.startedAt - right.startedAt)[0];
|
|
2718
2734
|
const supervisorAttentionSteps = new Map<number, ActivityState | undefined>();
|
|
2719
2735
|
const mutatingFailureWindowMs = 5 * 60_000;
|
|
@@ -2765,9 +2781,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
2765
2781
|
};
|
|
2766
2782
|
const maybeEmitOpenToolAttention = (flatIndex: number, now: number): boolean => {
|
|
2767
2783
|
const step = statusPayload.steps[flatIndex];
|
|
2768
|
-
if (!step || step.status !== "running"
|
|
2784
|
+
if (!step || step.status !== "running") return false;
|
|
2769
2785
|
const target = openToolAttentionTarget(flatIndex, now);
|
|
2770
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");
|
|
2771
2790
|
const previous = step.activityState;
|
|
2772
2791
|
step.activityState = "needs_attention";
|
|
2773
2792
|
statusPayload.activityState = "needs_attention";
|
|
@@ -2786,6 +2805,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
2786
2805
|
tokens: step.tokens?.total,
|
|
2787
2806
|
toolCount: step.toolCount,
|
|
2788
2807
|
currentTool: target.tool,
|
|
2808
|
+
toolCallId: target.key.startsWith("id:") ? target.key.slice(3) : undefined,
|
|
2789
2809
|
currentToolDurationMs: toolDurationMs,
|
|
2790
2810
|
currentPath: target.path,
|
|
2791
2811
|
})));
|
|
@@ -3617,6 +3637,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
3617
3637
|
return omitUndefinedProperties({
|
|
3618
3638
|
agent: task.agent,
|
|
3619
3639
|
...(task.sessionName ? { sessionName: task.sessionName } : {}),
|
|
3640
|
+
...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
|
|
3620
3641
|
...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
|
|
3621
3642
|
...(task.context ? { context: task.context } : {}),
|
|
3622
3643
|
...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
|
|
@@ -3719,6 +3740,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
3719
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 });
|
|
3720
3741
|
}
|
|
3721
3742
|
const taskStartTime = Date.now();
|
|
3743
|
+
launchedFlatIndices.add(fi);
|
|
3722
3744
|
statusPayload.currentStep = fi;
|
|
3723
3745
|
requiredStatusStep(statusPayload, fi).status = "running";
|
|
3724
3746
|
delete requiredStatusStep(statusPayload, fi).error;
|
|
@@ -3739,6 +3761,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
3739
3761
|
artifactsDir, artifactConfig, id,
|
|
3740
3762
|
flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
|
|
3741
3763
|
outputFile: path.join(asyncDir, `output-${fi}.log`),
|
|
3764
|
+
projectTrusted: config.projectTrusted,
|
|
3742
3765
|
piPackageRoot: config.piPackageRoot,
|
|
3743
3766
|
childSessions,
|
|
3744
3767
|
inheritedChildRuntime: config.inheritedChildRuntime,
|
|
@@ -4123,6 +4146,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
4123
4146
|
}
|
|
4124
4147
|
|
|
4125
4148
|
const taskStartTime = Date.now();
|
|
4149
|
+
launchedFlatIndices.add(fi);
|
|
4126
4150
|
statusPayload.currentStep = fi;
|
|
4127
4151
|
requiredStatusStep(statusPayload, fi).status = "running";
|
|
4128
4152
|
delete requiredStatusStep(statusPayload, fi).error;
|
|
@@ -4153,6 +4177,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
4153
4177
|
sessionDir: taskSessionDir,
|
|
4154
4178
|
artifactsDir, artifactConfig, id,
|
|
4155
4179
|
flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
|
|
4180
|
+
projectTrusted: config.projectTrusted,
|
|
4156
4181
|
outputFile: path.join(asyncDir, `output-${fi}.log`),
|
|
4157
4182
|
piPackageRoot: config.piPackageRoot,
|
|
4158
4183
|
childSessions,
|
|
@@ -4511,6 +4536,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
4511
4536
|
}
|
|
4512
4537
|
const singleCwd = singleWorktreeSetup?.worktrees[0]?.agentCwd ?? cwd;
|
|
4513
4538
|
const stepStartTime = Date.now();
|
|
4539
|
+
launchedFlatIndices.add(flatIndex);
|
|
4514
4540
|
statusPayload.currentStep = flatIndex;
|
|
4515
4541
|
requiredStatusStep(statusPayload, flatIndex).status = "running";
|
|
4516
4542
|
delete requiredStatusStep(statusPayload, flatIndex).activityState;
|
|
@@ -4543,6 +4569,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
4543
4569
|
outputs: statusPayload.mode === "single" ? undefined : outputs,
|
|
4544
4570
|
sessionDir: config.sessionDir,
|
|
4545
4571
|
artifactsDir, artifactConfig, id,
|
|
4572
|
+
projectTrusted: config.projectTrusted,
|
|
4546
4573
|
flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
|
|
4547
4574
|
outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
|
|
4548
4575
|
piPackageRoot: config.piPackageRoot,
|
|
@@ -4890,6 +4917,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
4890
4917
|
timedOut = true;
|
|
4891
4918
|
}
|
|
4892
4919
|
disposeControlInbox();
|
|
4920
|
+
try {
|
|
4921
|
+
closeStopInbox(asyncDir);
|
|
4922
|
+
} catch (error) {
|
|
4923
|
+
// Result publication must not depend on the marker; without it a late stop is accepted as before.
|
|
4924
|
+
appendJsonl(eventsPath, JSON.stringify({ type: "subagent.run.stop_inbox_close_failed", ts: Date.now(), runId: id, message: error instanceof Error ? error.message : String(error) }));
|
|
4925
|
+
}
|
|
4893
4926
|
for (const request of consumeStopRequestPayloads(asyncDir)) stopChildStep(request);
|
|
4894
4927
|
const signalTerminated = !stopped && !timedOut && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
|
|
4895
4928
|
processSignal: result.processSignal,
|
|
@@ -5087,6 +5120,26 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
|
|
|
5087
5120
|
usageBudget: statusPayload.usageBudget,
|
|
5088
5121
|
}),
|
|
5089
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
|
+
}
|
|
5090
5143
|
writeRunLog(logPath, omitUndefinedProperties({
|
|
5091
5144
|
id,
|
|
5092
5145
|
mode: statusPayload.mode,
|
|
@@ -4,11 +4,12 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
|
4
4
|
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
5
5
|
import { DIRS, type AsyncStatus, type Details, type SubagentState } from "../../shared/types.ts";
|
|
6
6
|
import { updateActiveRunIndex } from "../background/active-run-index.ts";
|
|
7
|
-
import { deliverStopRequest } from "../background/control-channel.ts";
|
|
7
|
+
import { deliverStopRequest, stopInboxClosedPath } from "../background/control-channel.ts";
|
|
8
8
|
import { readProcessTerminal } from "../background/process-terminal.ts";
|
|
9
9
|
import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
|
|
10
10
|
import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
|
|
11
|
-
import {
|
|
11
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
12
|
+
import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
|
|
12
13
|
|
|
13
14
|
function getAsyncStopTarget(
|
|
14
15
|
state: SubagentState,
|
|
@@ -108,6 +109,18 @@ export function stopAsyncRun(
|
|
|
108
109
|
childId?: string,
|
|
109
110
|
): AgentToolResult<Details> | null {
|
|
110
111
|
const target = getAsyncStopTarget(state, runId, location);
|
|
112
|
+
// An async workflow runs in this process: it has no runner to read a stop request, so stop it through its controller.
|
|
113
|
+
const workflowRunId = target?.asyncId ?? runId;
|
|
114
|
+
const workflowController = childId === undefined && workflowRunId ? state.workflowControllers?.get(workflowRunId) : undefined;
|
|
115
|
+
const workflowAsyncDir = workflowController && workflowRunId ? target?.asyncDir ?? state.asyncJobs.get(workflowRunId)?.asyncDir : undefined;
|
|
116
|
+
const workflowStatus = workflowAsyncDir ? readStatus(workflowAsyncDir) : undefined;
|
|
117
|
+
// Controllers outlive a session switch; a workflow owned by another session falls through to the ownership check below.
|
|
118
|
+
const foreignWorkflow = Boolean(state.currentSessionId && workflowStatus && workflowStatus.sessionId !== state.currentSessionId);
|
|
119
|
+
if (workflowController && workflowRunId && !foreignWorkflow) {
|
|
120
|
+
if (workflowStatus) stopStoppableAsyncStatusChildren(workflowStatus, state.workflowChildStops?.get(workflowRunId), "Workflow stopped.");
|
|
121
|
+
workflowController.abort(new Error("Workflow stopped."));
|
|
122
|
+
return { content: [{ type: "text", text: `Stop requested for async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
|
|
123
|
+
}
|
|
111
124
|
if (!target) return null;
|
|
112
125
|
const status = reconcileAsyncRun(target.asyncDir, { kill }).status;
|
|
113
126
|
if (state.currentSessionId && status?.sessionId !== state.currentSessionId) {
|
|
@@ -145,7 +158,8 @@ export function stopAsyncRun(
|
|
|
145
158
|
}
|
|
146
159
|
}
|
|
147
160
|
try {
|
|
148
|
-
|
|
161
|
+
// A paused run whose runner closed its inbox can only be sealed from exact exit proof below.
|
|
162
|
+
if (!(pausedWholeRun && fs.existsSync(stopInboxClosedPath(target.asyncDir)))) deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
|
|
149
163
|
if (pausedWholeRun) {
|
|
150
164
|
const failure = sealPausedRun(target.asyncDir, status);
|
|
151
165
|
if (failure) {
|
|
@@ -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
|
+
}
|