@xzzpig/pi-subagents 0.15.1 → 0.18.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 +178 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +19 -12
- package/docs/configuration.md +21 -3
- package/docs/extension-api.md +70 -4
- package/docs/fork-extensions.md +23 -15
- package/docs/models.md +5 -3
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +4 -4
- package/docs/tool-reference.md +40 -19
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +57 -3
- package/inspector-runner.mjs +1 -1
- package/package.json +14 -8
- package/prompts/council.md +6 -3
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/pi-subagents/SKILL.md +1 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
- package/skills/pi-subagents/references/execution-controls.md +6 -4
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +61 -52
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +125 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +60 -60
- package/src/extension/doctor.ts +9 -4
- package/src/extension/fanout-child.ts +8 -0
- package/src/extension/index.ts +101 -48
- package/src/extension/rpc.ts +10 -1
- package/src/extension/schemas.ts +12 -6
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +197 -0
- package/src/extension/tool-description.ts +1 -1
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +22 -15
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +100 -140
- package/src/runs/background/async-job-tracker.ts +28 -34
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +93 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +16 -5
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +10 -4
- package/src/runs/background/runner-aliases.ts +25 -15
- package/src/runs/background/runner-child-launch.ts +1 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +96 -287
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/execution.ts +217 -250
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +377 -119
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +22 -14
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +52 -2
- package/src/runs/shared/child-tool-plan.ts +23 -113
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +3 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +6 -1
- package/src/runs/shared/nested-events.ts +67 -55
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +2 -1
- package/src/runs/shared/pi-spawn.ts +92 -6
- package/src/runs/shared/profile-launch-env.ts +10 -2
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +35 -8
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/types.ts +52 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +16 -1
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +7 -241
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +28 -29
- package/src/tui/fleet-status.ts +24 -2
- package/src/tui/fleet.ts +7 -4
- package/src/tui/render.ts +53 -19
- package/src/watchdog/diff-tool.ts +24 -3
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/review.ts +14 -14
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +11 -5
- package/src/workflows/scripted-workflow.ts +109 -23
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -3,6 +3,7 @@ import * as path from "node:path";
|
|
|
3
3
|
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
4
4
|
import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "./result-files.ts";
|
|
5
5
|
import { updateActiveRunIndex } from "./active-run-index.ts";
|
|
6
|
+
import { readProcessTerminal } from "./process-terminal.ts";
|
|
6
7
|
import { readStatus } from "../../shared/utils.ts";
|
|
7
8
|
import { DIRS, type AsyncParallelGroupStatus, type AsyncStatus, type NestedRunSummary, type SubagentRunMode } from "../../shared/types.ts";
|
|
8
9
|
import { resolveEffectiveThinking } from "../../shared/model-info.ts";
|
|
@@ -10,6 +11,7 @@ import { normalizeParallelGroups } from "./parallel-groups.ts";
|
|
|
10
11
|
import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent, type NestedRoute } from "../shared/nested-events.ts";
|
|
11
12
|
import { assertWorkflowGraphHostSteps } from "../shared/host-step-status.ts";
|
|
12
13
|
import type { RawDrainStatusObserver } from "../shared/readonly-drain-observation.ts";
|
|
14
|
+
import { currentPidNamespaceScope } from "./pid-namespace.ts";
|
|
13
15
|
|
|
14
16
|
export type PidLiveness = "alive" | "dead" | "unknown";
|
|
15
17
|
|
|
@@ -36,6 +38,7 @@ interface ReconcileAsyncRunOptions {
|
|
|
36
38
|
startedRun?: StartedRunMetadata;
|
|
37
39
|
missingStatusGraceMs?: number;
|
|
38
40
|
staleAlivePidMs?: number;
|
|
41
|
+
pidNamespaceScope?: () => string | undefined;
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
interface ReconcileAsyncRunResult {
|
|
@@ -210,6 +213,7 @@ function buildStartedStatus(asyncDir: string, startedRun: StartedRunMetadata, no
|
|
|
210
213
|
mode: startedRun.mode ?? "single",
|
|
211
214
|
state: "running",
|
|
212
215
|
pid: startedRun.pid,
|
|
216
|
+
pidNamespaceScope: currentPidNamespaceScope(),
|
|
213
217
|
startedAt,
|
|
214
218
|
lastUpdate: now,
|
|
215
219
|
currentStep: 0,
|
|
@@ -227,7 +231,14 @@ function buildStartedStatus(asyncDir: string, startedRun: StartedRunMetadata, no
|
|
|
227
231
|
function buildFailedRepair(status: AsyncStatus, asyncDir: string, now: number, reason?: string): { status: AsyncStatus; result: Record<string, unknown>; message: string } {
|
|
228
232
|
const runId = status.runId || path.basename(asyncDir);
|
|
229
233
|
const pid = typeof status.pid === "number" ? status.pid : "unknown";
|
|
230
|
-
const
|
|
234
|
+
const terminal = readProcessTerminal(asyncDir, { runId }) ?? status.processTerminal;
|
|
235
|
+
const runnerExit = terminal?.state === "observed" || terminal?.state === "unknown"
|
|
236
|
+
? terminal.instances?.find((instance) => instance.kind === "runner" && instance.processInstanceId === terminal.runnerProcessInstanceId)
|
|
237
|
+
: undefined;
|
|
238
|
+
const exitText = runnerExit?.kind === "runner"
|
|
239
|
+
? `exited with code ${runnerExit.exitCode ?? "none"}${runnerExit.signal ? ` (signal ${runnerExit.signal})` : ""}`
|
|
240
|
+
: "exited or disappeared";
|
|
241
|
+
const baseMessage = reason ?? `Async runner process ${pid} ${exitText} before writing a result. Marked run failed by stale-run reconciliation.`;
|
|
231
242
|
const diagnostics = readRunnerStartupDiagnostics(asyncDir);
|
|
232
243
|
const message = diagnostics ? `${baseMessage}\n\nRunner stderr tail:\n${diagnostics}` : baseMessage;
|
|
233
244
|
const steps = status.steps?.length ? status.steps : [{ agent: "subagent", status: "running" as const }];
|
|
@@ -423,12 +434,17 @@ export function reconcileAsyncRun(asyncDir: string, options: ReconcileAsyncRunOp
|
|
|
423
434
|
}
|
|
424
435
|
}
|
|
425
436
|
|
|
426
|
-
const
|
|
437
|
+
const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
|
|
438
|
+
// An observer without a scope (macOS/Windows host sharing a container's temp root) cannot match a recorded one.
|
|
439
|
+
const pidScopeMismatch = effectiveStatus.pidNamespaceScope !== undefined && effectiveStatus.pidNamespaceScope !== observedScope;
|
|
440
|
+
const observedLiveness = checkPidLiveness(effectiveStatus.pid, options.kill);
|
|
441
|
+
const liveness = observedLiveness === "dead" && pidScopeMismatch ? "unknown" : observedLiveness;
|
|
427
442
|
if (liveness !== "dead") {
|
|
428
443
|
const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
|
|
429
444
|
const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
|
|
430
445
|
if (now - lastUpdate <= staleAfterMs) return { status: status ?? null, repaired: false, resultPath };
|
|
431
|
-
const
|
|
446
|
+
const probe = liveness === "alive" ? "is still live" : "cannot be probed from this process";
|
|
447
|
+
const message = `Async runner PID ${effectiveStatus.pid} ${probe}; status has not updated for ${now - lastUpdate}ms, so stale-run reconciliation marked the run failed because PID ownership is unverified.`;
|
|
432
448
|
return writeFailedRepair(asyncDir, effectiveStatus, resultPath, now, message);
|
|
433
449
|
}
|
|
434
450
|
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
5
|
+
import { acquireSessionLease } from "../shared/session-lease.ts";
|
|
6
|
+
import { readProcessTerminalCandidate, writeProcessTerminalCandidate, markProcessTerminalCandidateLeaseRelease } from "./process-terminal-candidate.ts";
|
|
7
|
+
import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
|
|
8
|
+
import type { DefaultChildSessionFactoryOptions } from "../shared/child-session.ts";
|
|
9
|
+
import type { SubagentRunConfig } from "./subagent-runner.ts";
|
|
10
|
+
|
|
11
|
+
export type { SubagentRunConfig } from "./subagent-runner.ts";
|
|
12
|
+
|
|
13
|
+
type ExecutionModule = {
|
|
14
|
+
runConfiguredSubagentExecution(config: SubagentRunConfig, options?: DefaultChildSessionFactoryOptions): Promise<void>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export interface RunnerBootstrapOptions extends DefaultChildSessionFactoryOptions {
|
|
18
|
+
/** Test-only seam for proving that execution loading stays behind startup commit. */
|
|
19
|
+
loadExecutionModule?: () => Promise<ExecutionModule>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
23
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function validateChildStep(value: unknown, field: string): void {
|
|
27
|
+
if (!isRecord(value)) {
|
|
28
|
+
throw new Error(`Invalid runner configuration: '${field}' must be an object.`);
|
|
29
|
+
}
|
|
30
|
+
if (typeof value.agent !== "string" || !value.agent) {
|
|
31
|
+
throw new Error(`Invalid runner configuration: '${field}.agent' must be a non-empty string.`);
|
|
32
|
+
}
|
|
33
|
+
if (typeof value.task !== "string") {
|
|
34
|
+
throw new Error(`Invalid runner configuration: '${field}.task' must be a string.`);
|
|
35
|
+
}
|
|
36
|
+
for (const requiredBoolean of ["inheritProjectContext", "inheritGlobalContext", "inheritSkills"] as const) {
|
|
37
|
+
if (typeof value[requiredBoolean] !== "boolean") {
|
|
38
|
+
throw new Error(`Invalid runner configuration: '${field}.${requiredBoolean}' must be a boolean.`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function validateStep(value: unknown, index: number): void {
|
|
44
|
+
const field = `steps[${index}]`;
|
|
45
|
+
if (!isRecord(value)) {
|
|
46
|
+
throw new Error(`Invalid runner configuration: '${field}' must be an object.`);
|
|
47
|
+
}
|
|
48
|
+
if ("expand" in value || "collect" in value) {
|
|
49
|
+
if (!isRecord(value.expand)) {
|
|
50
|
+
throw new Error(`Invalid runner configuration: '${field}.expand' must be an object.`);
|
|
51
|
+
}
|
|
52
|
+
if (!isRecord(value.collect)) {
|
|
53
|
+
throw new Error(`Invalid runner configuration: '${field}.collect' must be an object.`);
|
|
54
|
+
}
|
|
55
|
+
validateChildStep(value.parallel, `${field}.parallel`);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (Array.isArray(value.parallel)) {
|
|
59
|
+
if (value.parallel.length === 0) {
|
|
60
|
+
throw new Error(`Invalid runner configuration: '${field}.parallel' must not be empty.`);
|
|
61
|
+
}
|
|
62
|
+
value.parallel.forEach((step, childIndex) => validateChildStep(step, `${field}.parallel[${childIndex}]`));
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
validateChildStep(value, field);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function validateSubagentRunConfig(value: unknown): asserts value is SubagentRunConfig {
|
|
69
|
+
if (!isRecord(value)) {
|
|
70
|
+
throw new Error("Invalid runner configuration: root must be an object.");
|
|
71
|
+
}
|
|
72
|
+
for (const field of ["id", "resultPath", "cwd", "asyncDir"] as const) {
|
|
73
|
+
if (typeof value[field] !== "string" || !value[field]) {
|
|
74
|
+
throw new Error(`Invalid runner configuration: '${field}' must be a non-empty string.`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (typeof value.placeholder !== "string") {
|
|
78
|
+
throw new Error("Invalid runner configuration: 'placeholder' must be a string.");
|
|
79
|
+
}
|
|
80
|
+
if (!Array.isArray(value.steps) || value.steps.length === 0) {
|
|
81
|
+
throw new Error("Invalid runner configuration: 'steps' must be a non-empty array.");
|
|
82
|
+
}
|
|
83
|
+
value.steps.forEach(validateStep);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function waitForStartupControl(controlPath: string, token: string, action: "ack" | "confirm" | "proceed", timeoutMs = 30_000): Promise<void> {
|
|
87
|
+
const deadline = Date.now() + timeoutMs;
|
|
88
|
+
while (Date.now() <= deadline) {
|
|
89
|
+
if (fs.existsSync(controlPath)) {
|
|
90
|
+
let payload: { action?: unknown; token?: unknown };
|
|
91
|
+
try {
|
|
92
|
+
payload = JSON.parse(fs.readFileSync(controlPath, "utf-8")) as { action?: unknown; token?: unknown };
|
|
93
|
+
} catch (error) {
|
|
94
|
+
throw new Error(`Failed to read runner startup control '${controlPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
95
|
+
}
|
|
96
|
+
if (payload.token !== token) {
|
|
97
|
+
throw new Error("Runner startup control token does not match.");
|
|
98
|
+
}
|
|
99
|
+
if (payload.action === action) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (payload.action !== "ack" && payload.action !== "confirm" && payload.action !== "proceed") {
|
|
103
|
+
throw new Error("Runner startup control action is invalid.");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
107
|
+
}
|
|
108
|
+
throw new Error(`Timed out after ${timeoutMs}ms waiting for runner startup control '${action}'.`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Owns startup authorization and any revival lease across dynamically loaded execution. */
|
|
112
|
+
export async function runConfiguredSubagent(rawConfig: unknown, options: RunnerBootstrapOptions = {}): Promise<void> {
|
|
113
|
+
validateSubagentRunConfig(rawConfig);
|
|
114
|
+
const config = rawConfig;
|
|
115
|
+
let lease: ReturnType<typeof acquireSessionLease> | undefined;
|
|
116
|
+
let startupCommitted = config.revivalLease === undefined && config.launchBarrierToken === undefined;
|
|
117
|
+
let executionLoaded = false;
|
|
118
|
+
const startupPath = path.join(config.asyncDir, "runner-startup.json");
|
|
119
|
+
const startupAckPath = path.join(config.asyncDir, "runner-startup-ack.json");
|
|
120
|
+
const startupConfirmPath = path.join(config.asyncDir, "runner-startup-confirm.json");
|
|
121
|
+
const startupProceedPath = path.join(config.asyncDir, "runner-startup-proceed.json");
|
|
122
|
+
const releaseOnExit = (): void => {
|
|
123
|
+
try {
|
|
124
|
+
lease?.release();
|
|
125
|
+
} catch {
|
|
126
|
+
// Dead-owner leases are reclaimed on the next revival.
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
process.once("exit", releaseOnExit);
|
|
130
|
+
try {
|
|
131
|
+
if (config.launchBarrierToken) {
|
|
132
|
+
await waitForStartupControl(startupProceedPath, config.launchBarrierToken, "proceed");
|
|
133
|
+
startupCommitted = true;
|
|
134
|
+
try {
|
|
135
|
+
fs.rmSync(startupProceedPath, { force: true });
|
|
136
|
+
} catch {
|
|
137
|
+
// Best effort after commit.
|
|
138
|
+
}
|
|
139
|
+
} else if (config.revivalLease) {
|
|
140
|
+
lease = acquireSessionLease(config.revivalLease);
|
|
141
|
+
config.revivalLeaseToken = lease.owner.token;
|
|
142
|
+
writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
|
|
143
|
+
await waitForStartupControl(startupAckPath, lease.owner.token, "ack");
|
|
144
|
+
writeAtomicJson(startupPath, { state: "acknowledged", token: lease.owner.token, pid: process.pid });
|
|
145
|
+
await waitForStartupControl(startupConfirmPath, lease.owner.token, "confirm");
|
|
146
|
+
writeAtomicJson(startupPath, { state: "confirmed", token: lease.owner.token, pid: process.pid });
|
|
147
|
+
await waitForStartupControl(startupProceedPath, lease.owner.token, "proceed");
|
|
148
|
+
startupCommitted = true;
|
|
149
|
+
for (const controlPath of [startupAckPath, startupConfirmPath, startupProceedPath]) {
|
|
150
|
+
try {
|
|
151
|
+
fs.rmSync(controlPath, { force: true });
|
|
152
|
+
} catch {
|
|
153
|
+
// Best effort after commit.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (lease) {
|
|
158
|
+
// Persist token identity before the heavy import so an import rejection
|
|
159
|
+
// still leaves the parent enough evidence to prove lease release.
|
|
160
|
+
const candidate = readProcessTerminalCandidate(config.asyncDir);
|
|
161
|
+
if (candidate) {
|
|
162
|
+
writeProcessTerminalCandidate(config.asyncDir, {
|
|
163
|
+
...candidate,
|
|
164
|
+
sessionFile: config.revivalLease?.sessionFile,
|
|
165
|
+
revivalLeaseToken: lease.owner.token,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const { loadExecutionModule, ...executionOptions } = options;
|
|
170
|
+
const testExecutionModule = process.env.PI_SUBAGENTS_TEST_RUNNER_EXECUTION_MODULE;
|
|
171
|
+
const execution = await (loadExecutionModule?.() ?? (testExecutionModule ? import(testExecutionModule) : import("./subagent-runner.ts")));
|
|
172
|
+
executionLoaded = true;
|
|
173
|
+
await execution.runConfiguredSubagentExecution(config, executionOptions);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (!startupCommitted) {
|
|
176
|
+
try {
|
|
177
|
+
writeAtomicJson(startupPath, { state: "error", pid: process.pid, error: error instanceof Error ? error.message : String(error) });
|
|
178
|
+
} catch {
|
|
179
|
+
// The parent will time out and terminate if startup evidence cannot be written.
|
|
180
|
+
}
|
|
181
|
+
} else if (!executionLoaded) {
|
|
182
|
+
try {
|
|
183
|
+
persistRunnerStartupFailure({
|
|
184
|
+
asyncDir: config.asyncDir,
|
|
185
|
+
runId: config.id,
|
|
186
|
+
runnerProcessInstanceId: config.runnerProcessInstanceId ?? "unknown-runner-instance",
|
|
187
|
+
message: `Subagent runner startup failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
188
|
+
...(config.sessionId ? { sessionId: config.sessionId } : {}),
|
|
189
|
+
...(config.completionOwnerId ? { completionOwnerId: config.completionOwnerId } : {}),
|
|
190
|
+
candidate: {
|
|
191
|
+
...(config.revivalLease?.sessionFile ? { sessionFile: config.revivalLease.sessionFile } : {}),
|
|
192
|
+
...(config.revivalLeaseToken ? { revivalLeaseToken: config.revivalLeaseToken } : {}),
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
} catch (persistenceError) {
|
|
196
|
+
console.error("Failed to persist runner startup failure:", persistenceError);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
throw error;
|
|
200
|
+
} finally {
|
|
201
|
+
process.off("exit", releaseOnExit);
|
|
202
|
+
if (lease) {
|
|
203
|
+
let acknowledged = false;
|
|
204
|
+
try {
|
|
205
|
+
acknowledged = lease.release();
|
|
206
|
+
} catch (error) {
|
|
207
|
+
console.error("Failed to release session revival lease:", error);
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
markProcessTerminalCandidateLeaseRelease(config.asyncDir, lease.owner.token, acknowledged);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
console.error("Failed to record session revival lease release:", error);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function startConfiguredSubagent(config: unknown): void {
|
|
219
|
+
runConfiguredSubagent(config).then(
|
|
220
|
+
() => process.exit(0),
|
|
221
|
+
(error) => {
|
|
222
|
+
console.error("Subagent runner error:", error);
|
|
223
|
+
process.exit(1);
|
|
224
|
+
},
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function monitorTestParent(): void {
|
|
229
|
+
const parentPid = Number(process.env.PI_SUBAGENTS_TEST_PARENT_PID);
|
|
230
|
+
if (!Number.isSafeInteger(parentPid) || parentPid <= 0 || parentPid === process.pid) {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const check = () => {
|
|
234
|
+
try {
|
|
235
|
+
process.kill(parentPid, 0);
|
|
236
|
+
} catch {
|
|
237
|
+
process.exit(1);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
check();
|
|
241
|
+
setInterval(check, 250).unref();
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const isRunnerEntrypoint = Boolean(process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href);
|
|
245
|
+
if (isRunnerEntrypoint) {
|
|
246
|
+
monitorTestParent();
|
|
247
|
+
const configArg = process.argv[2];
|
|
248
|
+
if (configArg) {
|
|
249
|
+
try {
|
|
250
|
+
const config = JSON.parse(fs.readFileSync(configArg, "utf-8")) as unknown;
|
|
251
|
+
try {
|
|
252
|
+
fs.unlinkSync(configArg);
|
|
253
|
+
} catch {
|
|
254
|
+
// Temp-config cleanup is best effort.
|
|
255
|
+
}
|
|
256
|
+
startConfiguredSubagent(config);
|
|
257
|
+
} catch (error) {
|
|
258
|
+
console.error("Subagent runner error:", error);
|
|
259
|
+
process.exit(1);
|
|
260
|
+
}
|
|
261
|
+
} else {
|
|
262
|
+
let input = "";
|
|
263
|
+
process.stdin.setEncoding("utf-8");
|
|
264
|
+
process.stdin.on("data", (chunk) => {
|
|
265
|
+
input += chunk;
|
|
266
|
+
});
|
|
267
|
+
process.stdin.on("end", () => {
|
|
268
|
+
try {
|
|
269
|
+
startConfiguredSubagent(JSON.parse(input) as unknown);
|
|
270
|
+
} catch (error) {
|
|
271
|
+
console.error("Subagent runner error:", error);
|
|
272
|
+
process.exit(1);
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|