@ferris1225/pi-subagents 4.3.34 → 5.0.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 +32 -359
- package/README.md +130 -557
- package/index.ts +4 -2
- package/package.json +1 -1
- package/skills/workflow/SKILL.md +46 -29
- package/src/configuration/config.ts +4 -4
- package/src/configuration/setup.ts +88 -229
- package/src/configuration/ui.ts +107 -129
- package/src/delegation/builtin-agents.ts +9 -9
- package/src/delegation/dispatch.ts +9 -6
- package/src/delegation/prompt.ts +7 -8
- package/src/execution/cli-run.ts +364 -0
- package/src/execution/process-tree.ts +1 -1
- package/src/execution/{rpc-control.ts → run-control.ts} +15 -33
- package/src/execution/spawn.ts +33 -185
- package/src/isolation/temp-hygiene.ts +2 -3
- package/src/lifecycle/cancellation.ts +36 -0
- package/src/lifecycle/completion.ts +1 -1
- package/src/lifecycle/dispatch-core.ts +0 -1
- package/src/lifecycle/durable.ts +1 -1
- package/src/lifecycle/runtime.ts +42 -29
- package/src/lifecycle/stop.ts +175 -0
- package/src/lifecycle/thread-lifecycle.ts +11 -14
- package/src/lifecycle/thread-restore.ts +3 -3
- package/src/lifecycle/tools.ts +18 -173
- package/src/presentation/format.ts +2 -5
- package/src/presentation/monitor.ts +16 -1
- package/src/presentation/widget.ts +140 -175
- package/src/workflow/engine.ts +68 -34
- package/src/workflow/files.ts +10 -32
- package/src/workflow/plan.ts +61 -13
- package/src/workflow/state.ts +4 -3
- package/src/workflow/tool.ts +23 -12
- package/workflows/code-review.md +12 -7
- package/workflows/migration.md +14 -26
- package/workflows/research.md +6 -5
- package/src/execution/rpc-run.ts +0 -889
package/src/execution/rpc-run.ts
DELETED
|
@@ -1,889 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Persistent pi RPC child transport for one logical sub-agent generation.
|
|
3
|
-
*
|
|
4
|
-
* A child stays alive across prompt/abort operations and speaks
|
|
5
|
-
* strict LF-delimited JSONL. The process is terminated only after the logical
|
|
6
|
-
* run settles, is stopped, or fails. Session files remain owned by the parent
|
|
7
|
-
* runtime for in-run model fallback and manual recovery.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { spawn } from "node:child_process";
|
|
11
|
-
import { existsSync, readdirSync } from "node:fs";
|
|
12
|
-
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
13
|
-
import { basename, join } from "node:path";
|
|
14
|
-
import { StringDecoder } from "node:string_decoder";
|
|
15
|
-
import type { Message } from "@earendil-works/pi-ai";
|
|
16
|
-
import type { RpcCommand, RpcExtensionUIResponse, RpcResponse } from "@earendil-works/pi-coding-agent";
|
|
17
|
-
import { SUBAGENT_TOOL_NAMES, type AgentConfig } from "../delegation/agents.ts";
|
|
18
|
-
import type { ThinkingLevel } from "../configuration/config.ts";
|
|
19
|
-
import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
|
|
20
|
-
import { terminateProcessTree } from "./process-tree.ts";
|
|
21
|
-
import {
|
|
22
|
-
asPlainTextRpcPrompt,
|
|
23
|
-
emptyUsage,
|
|
24
|
-
RpcRunControl,
|
|
25
|
-
type AttemptControl,
|
|
26
|
-
type RpcControlPhase,
|
|
27
|
-
type RpcSingleResult,
|
|
28
|
-
type SubagentLiveEvent,
|
|
29
|
-
} from "./rpc-control.ts";
|
|
30
|
-
|
|
31
|
-
const DEPTH_ENV_VAR = "PI_SUBAGENT_DEPTH";
|
|
32
|
-
/** Every tool of an MCP server shares this prefix, whatever its exposure. */
|
|
33
|
-
const MCP_TOOL_PREFIX = "mcp__";
|
|
34
|
-
const SUBAGENT_KILL_GRACE_MS = 5_000;
|
|
35
|
-
/** ACK budget after the child is known to be reading RPC. */
|
|
36
|
-
const RPC_COMMAND_TIMEOUT_MS = 30_000;
|
|
37
|
-
|
|
38
|
-
/** clear_queue is stop-path hygiene ahead of the abort: give it its own short
|
|
39
|
-
* budget so a hung response cannot eat into the abort-settle window. */
|
|
40
|
-
const RPC_CLEAR_QUEUE_TIMEOUT_MS = 2_000;
|
|
41
|
-
/** Time allowed for the child to boot and answer get_state. */
|
|
42
|
-
const RPC_READY_TIMEOUT_MS = 60_000;
|
|
43
|
-
const RPC_ABORT_SETTLE_TIMEOUT_MS = 5_000;
|
|
44
|
-
/** Retained stderr tail. A chatty or crash-looping child must not grow parent
|
|
45
|
-
* memory without bound, and the tail carries the decisive diagnostic. */
|
|
46
|
-
export const RPC_STDERR_MAX_CHARS = 32_000;
|
|
47
|
-
|
|
48
|
-
/** Protocol events that prove the child reached the agent loop. */
|
|
49
|
-
const RPC_ACTIVITY_EVENTS = new Set([
|
|
50
|
-
"agent_start",
|
|
51
|
-
"agent_end",
|
|
52
|
-
"turn_start",
|
|
53
|
-
"turn_end",
|
|
54
|
-
"message_start",
|
|
55
|
-
"message_update",
|
|
56
|
-
"message_end",
|
|
57
|
-
"tool_execution_start",
|
|
58
|
-
"tool_execution_update",
|
|
59
|
-
"tool_execution_end",
|
|
60
|
-
"auto_retry_start",
|
|
61
|
-
"auto_retry_end",
|
|
62
|
-
"agent_settled",
|
|
63
|
-
]);
|
|
64
|
-
|
|
65
|
-
/** Append child stderr while keeping only the newest bounded tail. */
|
|
66
|
-
export function appendBoundedStderr(current: string, chunk: string, maxChars = RPC_STDERR_MAX_CHARS): string {
|
|
67
|
-
const next = current + chunk;
|
|
68
|
-
return next.length <= maxChars ? next : next.slice(next.length - maxChars);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export function isRpcCommandTimeoutError(message?: string): boolean {
|
|
72
|
-
return typeof message === "string" && message.includes("Timed out waiting for RPC response");
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export function currentSubagentDepth(env: NodeJS.ProcessEnv = process.env): number {
|
|
76
|
-
const raw = env[DEPTH_ENV_VAR];
|
|
77
|
-
const parsed = raw === undefined ? 0 : Number.parseInt(raw, 10);
|
|
78
|
-
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** Match pi's `<timestamp>Z_<id>.jsonl` session-file convention. */
|
|
82
|
-
export function sessionExists(sessionDir: string, sessionId: string): boolean {
|
|
83
|
-
try {
|
|
84
|
-
return readdirSync(sessionDir).some((file) => file.endsWith(`_${sessionId}.jsonl`));
|
|
85
|
-
} catch {
|
|
86
|
-
return false;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Resolve how to invoke the same pi build as the current process. */
|
|
91
|
-
function getPiInvocation(args: string[]): { command: string; args: string[] } {
|
|
92
|
-
const currentScript = process.argv[1];
|
|
93
|
-
const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
|
|
94
|
-
if (currentScript && !isBunVirtualScript && existsSync(currentScript)) {
|
|
95
|
-
return { command: process.execPath, args: [currentScript, ...args] };
|
|
96
|
-
}
|
|
97
|
-
const execName = basename(process.execPath).toLowerCase();
|
|
98
|
-
const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
|
|
99
|
-
if (!isGenericRuntime) return { command: process.execPath, args };
|
|
100
|
-
return { command: "pi", args };
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function extractToolErrorText(content: unknown): string {
|
|
104
|
-
const parts = Array.isArray(content) ? content : [];
|
|
105
|
-
const text = parts
|
|
106
|
-
.filter(
|
|
107
|
-
(part): part is { type: "text"; text: string } =>
|
|
108
|
-
typeof part === "object" &&
|
|
109
|
-
part !== null &&
|
|
110
|
-
(part as { type?: unknown }).type === "text" &&
|
|
111
|
-
typeof (part as { text?: unknown }).text === "string",
|
|
112
|
-
)
|
|
113
|
-
.map((part) => part.text)
|
|
114
|
-
.join("\n");
|
|
115
|
-
return text
|
|
116
|
-
.split("\n")
|
|
117
|
-
.map((line) => line.trim())
|
|
118
|
-
.filter(Boolean)
|
|
119
|
-
.slice(-3)
|
|
120
|
-
.map((line) => (line.length > 200 ? `${line.slice(0, 200)}…` : line))
|
|
121
|
-
.join("\n");
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
interface ChildRetryPolicyExtension {
|
|
125
|
-
dir: string;
|
|
126
|
-
filePath: string;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/** Child extension source. Pi 1.0 rejects `streamSimple` registrations that
|
|
130
|
-
* omit `api`, and only routes models whose api matches that field. The wrapper
|
|
131
|
-
* forwards the normalized transcript and request options, then forces
|
|
132
|
-
* provider retries off so the parent can hand off a failed child model. */
|
|
133
|
-
export function renderChildRetryPolicySource(modelRef?: string): string {
|
|
134
|
-
const slash = modelRef?.indexOf("/") ?? -1;
|
|
135
|
-
const selectedProvider = slash > 0 ? modelRef!.slice(0, slash) : undefined;
|
|
136
|
-
return `import { getApiProvider } from "@earendil-works/pi-ai/compat";\n`
|
|
137
|
-
+ `const selectedProvider = ${JSON.stringify(selectedProvider)};\n`
|
|
138
|
-
+ `let installedFor;\n`
|
|
139
|
-
+ `export default function noProviderRetries(pi) {\n`
|
|
140
|
-
+ ` pi.on("before_provider_request", (_event, ctx) => {\n`
|
|
141
|
-
+ ` const model = ctx.model;\n`
|
|
142
|
-
+ ` const providerId = model?.provider ?? selectedProvider;\n`
|
|
143
|
-
+ ` const api = model?.api;\n`
|
|
144
|
-
+ ` if (!providerId || !api) return;\n`
|
|
145
|
-
+ ` const key = providerId + "\\0" + api;\n`
|
|
146
|
-
+ ` if (installedFor === key) return;\n`
|
|
147
|
-
+ ` pi.registerProvider(providerId, {\n`
|
|
148
|
-
+ ` api,\n`
|
|
149
|
-
+ ` streamSimple(requestModel, context, options) {\n`
|
|
150
|
-
+ ` const implementation = getApiProvider(requestModel.api);\n`
|
|
151
|
-
+ ` if (!implementation) throw new Error(\`No API stream implementation is registered for \${requestModel.api}.\`);\n`
|
|
152
|
-
+ ` return implementation.streamSimple(requestModel, context, { ...options, maxRetries: 0 });\n`
|
|
153
|
-
+ ` },\n`
|
|
154
|
-
+ ` });\n`
|
|
155
|
-
+ ` installedFor = key;\n`
|
|
156
|
-
+ ` });\n`
|
|
157
|
-
+ `}\n`;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** Build a child-only Pi extension that replaces the selected provider's
|
|
161
|
-
* stream adapter with its registered API implementation while forcing
|
|
162
|
-
* maxRetries=0. It uses Pi's public extension and pi-ai compatibility APIs, so
|
|
163
|
-
* it works in Node and standalone/Bun builds without touching user settings. */
|
|
164
|
-
async function writeChildRetryPolicyExtension(
|
|
165
|
-
scratchRoot: string,
|
|
166
|
-
modelRef?: string,
|
|
167
|
-
): Promise<ChildRetryPolicyExtension> {
|
|
168
|
-
await mkdir(scratchRoot, { recursive: true });
|
|
169
|
-
const dir = await mkdtemp(join(scratchRoot, "pi-subagents-policy-"));
|
|
170
|
-
writeTempOwnerMarker(dir);
|
|
171
|
-
const filePath = join(dir, "no-provider-retries.mjs");
|
|
172
|
-
const source = renderChildRetryPolicySource(modelRef);
|
|
173
|
-
try {
|
|
174
|
-
await writeFile(filePath, source, "utf8");
|
|
175
|
-
return { dir, filePath };
|
|
176
|
-
} catch (error) {
|
|
177
|
-
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
178
|
-
throw error;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/** Hand the agent body to the child as a file rather than inline argv text.
|
|
183
|
-
* `--append-system-prompt` takes either, but a system prompt is unbounded — a
|
|
184
|
-
* role can carry a whole spec — while Windows caps a command line at
|
|
185
|
-
* 32767 characters, so inlining turns a long agent into an opaque spawn failure.
|
|
186
|
-
* The file lives in the run's scratch dir and is removed when the attempt ends. */
|
|
187
|
-
async function writePromptToTempFile(
|
|
188
|
-
scratchRoot: string,
|
|
189
|
-
agentName: string,
|
|
190
|
-
prompt: string,
|
|
191
|
-
): Promise<{ dir: string; filePath: string }> {
|
|
192
|
-
await mkdir(scratchRoot, { recursive: true });
|
|
193
|
-
const dir = await mkdtemp(join(scratchRoot, "pi-subagents-"));
|
|
194
|
-
writeTempOwnerMarker(dir);
|
|
195
|
-
const safeName = agentName.replace(/[^\w.-]+/g, "_");
|
|
196
|
-
const filePath = join(dir, `prompt-${safeName}.md`);
|
|
197
|
-
try {
|
|
198
|
-
await writeFile(filePath, prompt, "utf8");
|
|
199
|
-
return { dir, filePath };
|
|
200
|
-
} catch (error) {
|
|
201
|
-
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
202
|
-
throw error;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
interface RpcSessionUsage {
|
|
207
|
-
input: number;
|
|
208
|
-
output: number;
|
|
209
|
-
cacheRead: number;
|
|
210
|
-
cacheWrite: number;
|
|
211
|
-
cost: number;
|
|
212
|
-
contextTokens: number;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function sessionUsage(data: unknown): RpcSessionUsage | undefined {
|
|
216
|
-
if (!data || typeof data !== "object") return undefined;
|
|
217
|
-
const value = data as { tokens?: Record<string, unknown>; cost?: unknown; contextUsage?: { tokens?: unknown } };
|
|
218
|
-
if (!value.tokens || typeof value.tokens !== "object") return undefined;
|
|
219
|
-
const number = (candidate: unknown): number =>
|
|
220
|
-
typeof candidate === "number" && Number.isFinite(candidate) ? candidate : 0;
|
|
221
|
-
return {
|
|
222
|
-
input: number(value.tokens.input),
|
|
223
|
-
output: number(value.tokens.output),
|
|
224
|
-
cacheRead: number(value.tokens.cacheRead),
|
|
225
|
-
cacheWrite: number(value.tokens.cacheWrite),
|
|
226
|
-
cost: number(value.cost),
|
|
227
|
-
contextTokens: number(value.contextUsage?.tokens),
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
function applySessionUsageDelta(result: RpcSingleResult, before: RpcSessionUsage, after: RpcSessionUsage): void {
|
|
232
|
-
result.usage.input = Math.max(0, after.input - before.input);
|
|
233
|
-
result.usage.output = Math.max(0, after.output - before.output);
|
|
234
|
-
result.usage.cacheRead = Math.max(0, after.cacheRead - before.cacheRead);
|
|
235
|
-
result.usage.cacheWrite = Math.max(0, after.cacheWrite - before.cacheWrite);
|
|
236
|
-
result.usage.cost = Math.max(0, after.cost - before.cost);
|
|
237
|
-
result.usage.contextTokens = after.contextTokens;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
class RpcCommandRejectedError extends Error {
|
|
241
|
-
constructor(message: string) {
|
|
242
|
-
super(message);
|
|
243
|
-
this.name = "RpcCommandRejectedError";
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
interface PendingRequest {
|
|
248
|
-
resolve: (response: RpcResponse) => void;
|
|
249
|
-
reject: (error: Error) => void;
|
|
250
|
-
timer?: ReturnType<typeof setTimeout>;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
interface Deferred<T> {
|
|
254
|
-
promise: Promise<T>;
|
|
255
|
-
resolve(value: T): void;
|
|
256
|
-
reject(error: Error): void;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
function deferred<T>(): Deferred<T> {
|
|
260
|
-
let resolve!: (value: T) => void;
|
|
261
|
-
let reject!: (error: Error) => void;
|
|
262
|
-
const promise = new Promise<T>((res, rej) => {
|
|
263
|
-
resolve = res;
|
|
264
|
-
reject = rej;
|
|
265
|
-
});
|
|
266
|
-
return { promise, resolve, reject };
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
export interface RunRpcAttemptOptions {
|
|
270
|
-
defaultCwd: string;
|
|
271
|
-
agent: AgentConfig;
|
|
272
|
-
agentName: string;
|
|
273
|
-
task: string;
|
|
274
|
-
cwd?: string;
|
|
275
|
-
thinkingLevel: ThinkingLevel;
|
|
276
|
-
idleTimeoutMs: number;
|
|
277
|
-
sessionDir?: string;
|
|
278
|
-
sessionId?: string;
|
|
279
|
-
/** Transient scratch root (child prompt files, retry-policy extension):
|
|
280
|
-
* the project-scoped tmp directory, never the OS temp directory. */
|
|
281
|
-
scratchRoot: string;
|
|
282
|
-
prompt: string;
|
|
283
|
-
signal?: AbortSignal;
|
|
284
|
-
onLive?: (event: SubagentLiveEvent) => void;
|
|
285
|
-
env?: NodeJS.ProcessEnv;
|
|
286
|
-
control?: RpcRunControl;
|
|
287
|
-
rpcReadyTimeoutMs?: number;
|
|
288
|
-
rpcCommandTimeoutMs?: number;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
export interface ChildLaunchOptions {
|
|
292
|
-
agent: Pick<AgentConfig, "model" | "tools">;
|
|
293
|
-
thinkingLevel: ThinkingLevel;
|
|
294
|
-
sessionDir?: string;
|
|
295
|
-
sessionId?: string;
|
|
296
|
-
/** The session directory already holds the session being resumed. */
|
|
297
|
-
resumeExistingSession?: boolean;
|
|
298
|
-
/** Appended system prompt file, when the role carries one. */
|
|
299
|
-
promptPath?: string;
|
|
300
|
-
retryPolicyPath: string;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/** Command line for one child attempt.
|
|
304
|
-
*
|
|
305
|
-
* An explicit role list is a strict intersection of the parent's tools, but pi
|
|
306
|
-
* keeps MCP tools unless a `--tools` entry names one, so a list that names none
|
|
307
|
-
* has to exclude them by pattern. Scout depends on that: its read-only boundary
|
|
308
|
-
* must not leak an MCP writer. */
|
|
309
|
-
export function buildChildLaunchArgs(options: ChildLaunchOptions): string[] {
|
|
310
|
-
const { agent, thinkingLevel } = options;
|
|
311
|
-
const excludedTools: string[] = [...SUBAGENT_TOOL_NAMES];
|
|
312
|
-
const args: string[] = ["--mode", "rpc"];
|
|
313
|
-
if (options.sessionDir && options.sessionId) {
|
|
314
|
-
args.push("--session-dir", options.sessionDir);
|
|
315
|
-
args.push(options.resumeExistingSession ? "--session" : "--session-id", options.sessionId);
|
|
316
|
-
} else {
|
|
317
|
-
args.push("--no-session");
|
|
318
|
-
}
|
|
319
|
-
if (agent.model) args.push("--model", agent.model);
|
|
320
|
-
args.push("--thinking", thinkingLevel);
|
|
321
|
-
if (agent.tools) {
|
|
322
|
-
if (agent.tools.length > 0) {
|
|
323
|
-
args.push("--tools", agent.tools.join(","));
|
|
324
|
-
if (!agent.tools.some((tool) => tool.startsWith(MCP_TOOL_PREFIX))) excludedTools.push(`${MCP_TOOL_PREFIX}*`);
|
|
325
|
-
} else {
|
|
326
|
-
args.push("--no-tools");
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
args.push("--exclude-tools", excludedTools.join(","));
|
|
330
|
-
if (options.promptPath) args.push("--append-system-prompt", options.promptPath);
|
|
331
|
-
args.push("--extension", options.retryPolicyPath);
|
|
332
|
-
return args;
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
/** Run one persistent RPC child until a stable `agent_settled` or control action. */
|
|
336
|
-
export async function runRpcAgentAttempt(options: RunRpcAttemptOptions): Promise<RpcSingleResult> {
|
|
337
|
-
const { agent, agentName, task, thinkingLevel, idleTimeoutMs, signal, onLive, control } = options;
|
|
338
|
-
let tmpPromptDir: string | null = null;
|
|
339
|
-
let tmpPromptPath: string | null = null;
|
|
340
|
-
if (agent.systemPrompt.trim()) {
|
|
341
|
-
const tmp = await writePromptToTempFile(options.scratchRoot, agent.name, agent.systemPrompt);
|
|
342
|
-
tmpPromptDir = tmp.dir;
|
|
343
|
-
tmpPromptPath = tmp.filePath;
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
let retryPolicy: ChildRetryPolicyExtension;
|
|
347
|
-
let args: string[];
|
|
348
|
-
try {
|
|
349
|
-
retryPolicy = await writeChildRetryPolicyExtension(options.scratchRoot, agent.model);
|
|
350
|
-
args = buildChildLaunchArgs({
|
|
351
|
-
agent,
|
|
352
|
-
thinkingLevel,
|
|
353
|
-
sessionDir: options.sessionDir,
|
|
354
|
-
sessionId: options.sessionId,
|
|
355
|
-
resumeExistingSession: Boolean(
|
|
356
|
-
options.sessionDir && options.sessionId && sessionExists(options.sessionDir, options.sessionId),
|
|
357
|
-
),
|
|
358
|
-
promptPath: tmpPromptPath ?? undefined,
|
|
359
|
-
retryPolicyPath: retryPolicy.filePath,
|
|
360
|
-
});
|
|
361
|
-
} catch (error) {
|
|
362
|
-
if (tmpPromptDir) await rm(tmpPromptDir, { recursive: true, force: true }).catch(() => undefined);
|
|
363
|
-
throw error;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
const result: RpcSingleResult = {
|
|
367
|
-
agent: agentName,
|
|
368
|
-
task,
|
|
369
|
-
exitCode: 0,
|
|
370
|
-
messages: [],
|
|
371
|
-
stderr: "",
|
|
372
|
-
usage: emptyUsage(),
|
|
373
|
-
model: agent.model,
|
|
374
|
-
thinking: thinkingLevel,
|
|
375
|
-
sessionId: options.sessionId,
|
|
376
|
-
sessionDir: options.sessionDir,
|
|
377
|
-
};
|
|
378
|
-
|
|
379
|
-
const childDepth = currentSubagentDepth(options.env) + 1;
|
|
380
|
-
const childEnv: NodeJS.ProcessEnv = {
|
|
381
|
-
...(options.env ?? process.env),
|
|
382
|
-
[DEPTH_ENV_VAR]: String(childDepth),
|
|
383
|
-
};
|
|
384
|
-
const invocation = getPiInvocation(args);
|
|
385
|
-
const usePosixProcessGroup = process.platform !== "win32";
|
|
386
|
-
const proc = spawn(invocation.command, invocation.args, {
|
|
387
|
-
cwd: options.cwd ?? options.defaultCwd,
|
|
388
|
-
shell: false,
|
|
389
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
390
|
-
env: childEnv,
|
|
391
|
-
detached: usePosixProcessGroup,
|
|
392
|
-
});
|
|
393
|
-
|
|
394
|
-
const attemptToken = control?.beginAttempt();
|
|
395
|
-
let closed = false;
|
|
396
|
-
let finished = false;
|
|
397
|
-
let requestId = 0;
|
|
398
|
-
let stdoutBuffer = "";
|
|
399
|
-
let lastActivityAt = Date.now();
|
|
400
|
-
let idleTimer: ReturnType<typeof setInterval> | undefined;
|
|
401
|
-
let forceKillTimer: ReturnType<typeof setTimeout> | undefined;
|
|
402
|
-
let terminationRequested = false;
|
|
403
|
-
let abortHandler: (() => void) | undefined;
|
|
404
|
-
let abortSettlement: Deferred<void> | undefined;
|
|
405
|
-
let droppedQueuedCount = 0;
|
|
406
|
-
let initialPromptResolved = false;
|
|
407
|
-
let usageBaseline: RpcSessionUsage | undefined;
|
|
408
|
-
let usageSettlementStarted = false;
|
|
409
|
-
const initialPrompt = deferred<{ accepted: boolean; error?: Error }>();
|
|
410
|
-
const pendingRequests = new Map<string, PendingRequest>();
|
|
411
|
-
const outcome = deferred<void>();
|
|
412
|
-
const processClosed = deferred<void>();
|
|
413
|
-
const stdoutDecoder = new StringDecoder("utf8");
|
|
414
|
-
const stderrDecoder = new StringDecoder("utf8");
|
|
415
|
-
|
|
416
|
-
const emit = (event: SubagentLiveEvent): void => {
|
|
417
|
-
try {
|
|
418
|
-
onLive?.(event);
|
|
419
|
-
} catch {
|
|
420
|
-
/* live observers must never break protocol handling */
|
|
421
|
-
}
|
|
422
|
-
};
|
|
423
|
-
|
|
424
|
-
const setAttemptPhase = (phase: RpcControlPhase): void => {
|
|
425
|
-
if (attemptToken !== undefined) control?.updateAttemptPhase(attemptToken, phase);
|
|
426
|
-
if (phase === "running" || phase === "interrupting") {
|
|
427
|
-
emit({ kind: "status", status: phase });
|
|
428
|
-
}
|
|
429
|
-
};
|
|
430
|
-
|
|
431
|
-
const rejectPending = (error: Error): void => {
|
|
432
|
-
for (const request of pendingRequests.values()) {
|
|
433
|
-
if (request.timer) clearTimeout(request.timer);
|
|
434
|
-
request.reject(error);
|
|
435
|
-
}
|
|
436
|
-
pendingRequests.clear();
|
|
437
|
-
};
|
|
438
|
-
|
|
439
|
-
const finish = (): void => {
|
|
440
|
-
if (finished) return;
|
|
441
|
-
finished = true;
|
|
442
|
-
if (idleTimer) clearInterval(idleTimer);
|
|
443
|
-
if (signal && abortHandler) signal.removeEventListener("abort", abortHandler);
|
|
444
|
-
outcome.resolve();
|
|
445
|
-
};
|
|
446
|
-
|
|
447
|
-
const resolveInitialPrompt = (accepted: boolean, error?: Error): void => {
|
|
448
|
-
if (initialPromptResolved) return;
|
|
449
|
-
initialPromptResolved = true;
|
|
450
|
-
if (accepted) result.rpcPromptAccepted = true;
|
|
451
|
-
initialPrompt.resolve({ accepted, error });
|
|
452
|
-
};
|
|
453
|
-
|
|
454
|
-
const settleRun = (): void => {
|
|
455
|
-
const failed = result.stopReason === "error" || result.stopReason === "aborted";
|
|
456
|
-
result.exitCode = failed ? 1 : 0;
|
|
457
|
-
// RPC settlement only means model transport is quiescent. Dispatch may still
|
|
458
|
-
// be applying an isolated worktree, so it alone publishes the terminal live
|
|
459
|
-
// status after filesystem finalization completes.
|
|
460
|
-
finish();
|
|
461
|
-
};
|
|
462
|
-
|
|
463
|
-
const terminate = (force = false): void => {
|
|
464
|
-
if (closed) return;
|
|
465
|
-
// Failure paths and the final cleanup each request a graceful stop; one
|
|
466
|
-
// signal (one taskkill on Windows) plus the hard-kill timer is enough.
|
|
467
|
-
if (!force && terminationRequested) return;
|
|
468
|
-
terminationRequested = true;
|
|
469
|
-
terminateProcessTree(proc, force, usePosixProcessGroup);
|
|
470
|
-
if (!force && !forceKillTimer) {
|
|
471
|
-
forceKillTimer = setTimeout(() => {
|
|
472
|
-
if (!closed) terminateProcessTree(proc, true, usePosixProcessGroup);
|
|
473
|
-
}, SUBAGENT_KILL_GRACE_MS);
|
|
474
|
-
}
|
|
475
|
-
};
|
|
476
|
-
|
|
477
|
-
const readyTimeoutMs = options.rpcReadyTimeoutMs ?? RPC_READY_TIMEOUT_MS;
|
|
478
|
-
const commandTimeoutMs = options.rpcCommandTimeoutMs ?? RPC_COMMAND_TIMEOUT_MS;
|
|
479
|
-
|
|
480
|
-
const writeLine = (value: RpcCommand | RpcExtensionUIResponse): Promise<void> =>
|
|
481
|
-
new Promise((resolve, reject) => {
|
|
482
|
-
if (!proc.stdin || proc.stdin.destroyed || !proc.stdin.writable) {
|
|
483
|
-
reject(new Error("Subagent RPC stdin is not writable."));
|
|
484
|
-
return;
|
|
485
|
-
}
|
|
486
|
-
// JSON strings may contain U+2028/U+2029. Only the final ASCII LF frames a
|
|
487
|
-
// record; never use a generic line reader on the receiving side.
|
|
488
|
-
proc.stdin.write(`${JSON.stringify(value)}\n`, "utf8", (error) => {
|
|
489
|
-
if (error) reject(error);
|
|
490
|
-
else resolve();
|
|
491
|
-
});
|
|
492
|
-
});
|
|
493
|
-
|
|
494
|
-
const send = async <T extends RpcCommand>(
|
|
495
|
-
command: T,
|
|
496
|
-
timeoutMs = commandTimeoutMs,
|
|
497
|
-
): Promise<Extract<RpcResponse, { command: T["type"]; success: true }>> => {
|
|
498
|
-
if (finished || closed) throw new Error("Subagent RPC process is no longer active.");
|
|
499
|
-
const id = `req_${++requestId}`;
|
|
500
|
-
const payload = { ...command, id };
|
|
501
|
-
return new Promise<RpcResponse>((resolve, reject) => {
|
|
502
|
-
const pending: PendingRequest = { resolve, reject };
|
|
503
|
-
pending.timer = setTimeout(() => {
|
|
504
|
-
pendingRequests.delete(id);
|
|
505
|
-
reject(new Error(`Timed out waiting for RPC response to ${String(command.type)}.`));
|
|
506
|
-
}, timeoutMs);
|
|
507
|
-
if (typeof pending.timer.unref === "function") pending.timer.unref();
|
|
508
|
-
pendingRequests.set(id, pending);
|
|
509
|
-
void writeLine(payload).catch((error) => {
|
|
510
|
-
if (!pendingRequests.has(id)) return;
|
|
511
|
-
pendingRequests.delete(id);
|
|
512
|
-
if (pending.timer) clearTimeout(pending.timer);
|
|
513
|
-
reject(error instanceof Error ? error : new Error(String(error)));
|
|
514
|
-
});
|
|
515
|
-
}).then((response) => {
|
|
516
|
-
if (!response.success) {
|
|
517
|
-
throw new RpcCommandRejectedError(response.error || `RPC ${response.command} failed.`);
|
|
518
|
-
}
|
|
519
|
-
return response as Extract<RpcResponse, { command: T["type"]; success: true }>;
|
|
520
|
-
});
|
|
521
|
-
};
|
|
522
|
-
|
|
523
|
-
const settleRunWithUsage = async (): Promise<void> => {
|
|
524
|
-
if (usageSettlementStarted) return;
|
|
525
|
-
usageSettlementStarted = true;
|
|
526
|
-
try {
|
|
527
|
-
if (usageBaseline) {
|
|
528
|
-
const response = await send({ type: "get_session_stats" });
|
|
529
|
-
const finalUsage = sessionUsage(response.data);
|
|
530
|
-
if (finalUsage) applySessionUsageDelta(result, usageBaseline, finalUsage);
|
|
531
|
-
if (finalUsage) emit({ kind: "usage", usage: { ...result.usage }, model: result.model });
|
|
532
|
-
}
|
|
533
|
-
} catch {
|
|
534
|
-
/* message events remain the generation-safe accounting fallback */
|
|
535
|
-
} finally {
|
|
536
|
-
settleRun();
|
|
537
|
-
}
|
|
538
|
-
};
|
|
539
|
-
|
|
540
|
-
const waitForAbortSettlement = (): Deferred<void> => {
|
|
541
|
-
if (abortSettlement) throw new Error("Another RPC abort transition is already in progress.");
|
|
542
|
-
abortSettlement = deferred<void>();
|
|
543
|
-
return abortSettlement;
|
|
544
|
-
};
|
|
545
|
-
|
|
546
|
-
const abortAcceptedPrompt = async (): Promise<boolean> => {
|
|
547
|
-
const acceptance = await initialPrompt.promise;
|
|
548
|
-
if (!acceptance.accepted) return false;
|
|
549
|
-
// Pi continues queued messages after an abort. Drop them first so stale
|
|
550
|
-
// queue entries cannot revive a stopped run. Best-effort: an
|
|
551
|
-
// older child rejects the command and a hung child falls through to
|
|
552
|
-
// the bounded abort below.
|
|
553
|
-
try {
|
|
554
|
-
const cleared = await send({ type: "clear_queue" }, RPC_CLEAR_QUEUE_TIMEOUT_MS);
|
|
555
|
-
const data = cleared.data as { steering?: unknown; followUp?: unknown } | undefined;
|
|
556
|
-
droppedQueuedCount =
|
|
557
|
-
(Array.isArray(data?.steering) ? data.steering.length : 0) +
|
|
558
|
-
(Array.isArray(data?.followUp) ? data.followUp.length : 0);
|
|
559
|
-
} catch {
|
|
560
|
-
/* abort below is the authoritative stop */
|
|
561
|
-
}
|
|
562
|
-
const stable = waitForAbortSettlement();
|
|
563
|
-
try {
|
|
564
|
-
await Promise.all([send({ type: "abort" }), stable.promise]);
|
|
565
|
-
return true;
|
|
566
|
-
} catch (error) {
|
|
567
|
-
if (abortSettlement === stable) {
|
|
568
|
-
abortSettlement = undefined;
|
|
569
|
-
stable.resolve();
|
|
570
|
-
}
|
|
571
|
-
throw error;
|
|
572
|
-
}
|
|
573
|
-
};
|
|
574
|
-
|
|
575
|
-
const attemptControl: AttemptControl = {
|
|
576
|
-
async stop(reason = "Subagent was aborted"): Promise<void> {
|
|
577
|
-
if (finished) {
|
|
578
|
-
if (!closed) await processClosed.promise;
|
|
579
|
-
return;
|
|
580
|
-
}
|
|
581
|
-
setAttemptPhase("interrupting");
|
|
582
|
-
if (!initialPromptResolved) {
|
|
583
|
-
const stopped = new Error(reason);
|
|
584
|
-
resolveInitialPrompt(false, stopped);
|
|
585
|
-
rejectPending(stopped);
|
|
586
|
-
}
|
|
587
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
588
|
-
const timeout = new Promise<boolean>((resolve) => {
|
|
589
|
-
timer = setTimeout(() => resolve(false), RPC_ABORT_SETTLE_TIMEOUT_MS);
|
|
590
|
-
if (typeof timer.unref === "function") timer.unref();
|
|
591
|
-
});
|
|
592
|
-
try {
|
|
593
|
-
await Promise.race([abortAcceptedPrompt(), timeout]);
|
|
594
|
-
} catch {
|
|
595
|
-
/* process termination below is the bounded fallback */
|
|
596
|
-
} finally {
|
|
597
|
-
if (timer) clearTimeout(timer);
|
|
598
|
-
}
|
|
599
|
-
if (abortSettlement) {
|
|
600
|
-
const stable = abortSettlement;
|
|
601
|
-
abortSettlement = undefined;
|
|
602
|
-
stable.resolve();
|
|
603
|
-
}
|
|
604
|
-
result.exitCode = 1;
|
|
605
|
-
result.stopReason = "aborted";
|
|
606
|
-
result.errorMessage =
|
|
607
|
-
droppedQueuedCount > 0
|
|
608
|
-
? `${reason} — dropped ${droppedQueuedCount} queued steering/follow-up message${droppedQueuedCount === 1 ? "" : "s"}`
|
|
609
|
-
: reason;
|
|
610
|
-
finish();
|
|
611
|
-
// Even when RPC abort/settle times out, give Pi SIGTERM first so its
|
|
612
|
-
// shutdown handler can reap detached tool process groups. terminate()
|
|
613
|
-
// retains the hard-kill timer as the bounded fallback.
|
|
614
|
-
terminate(false);
|
|
615
|
-
if (!closed) await processClosed.promise;
|
|
616
|
-
},
|
|
617
|
-
};
|
|
618
|
-
|
|
619
|
-
if (attemptToken !== undefined) control?.attach(attemptToken, attemptControl);
|
|
620
|
-
if (proc.pid !== undefined) control?.noteChildPid(proc.pid);
|
|
621
|
-
control?.markStarting();
|
|
622
|
-
|
|
623
|
-
const processLine = (rawLine: string): void => {
|
|
624
|
-
let line = rawLine;
|
|
625
|
-
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
626
|
-
if (!line.trim()) return;
|
|
627
|
-
let event: any;
|
|
628
|
-
try {
|
|
629
|
-
event = JSON.parse(line);
|
|
630
|
-
} catch {
|
|
631
|
-
return;
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
if (event.type === "response" && typeof event.id === "string") {
|
|
635
|
-
const pending = pendingRequests.get(event.id);
|
|
636
|
-
if (pending) {
|
|
637
|
-
pendingRequests.delete(event.id);
|
|
638
|
-
clearTimeout(pending.timer);
|
|
639
|
-
pending.resolve(event as RpcResponse);
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
if (finished) return;
|
|
644
|
-
|
|
645
|
-
if (RPC_ACTIVITY_EVENTS.has(event.type)) result.rpcActivity = true;
|
|
646
|
-
|
|
647
|
-
// Let Pi's outer turn retry run. Grok/xAI long streams commonly drop with
|
|
648
|
-
// a retryable `terminated` mid-turn; aborting that retry was misread as
|
|
649
|
-
// "model unavailable" and handed a still-working model back to the parent.
|
|
650
|
-
// After retries exhaust, dispatch still classifies a settled model-level
|
|
651
|
-
// failure and hands off.
|
|
652
|
-
|
|
653
|
-
// Child RPC mode exposes extension dialogs. Sub-agents are non-interactive:
|
|
654
|
-
// cancel blocking dialogs so an unrelated child extension cannot deadlock.
|
|
655
|
-
if (
|
|
656
|
-
event.type === "extension_ui_request" &&
|
|
657
|
-
typeof event.id === "string" &&
|
|
658
|
-
["select", "confirm", "input", "editor"].includes(event.method)
|
|
659
|
-
) {
|
|
660
|
-
void writeLine({ type: "extension_ui_response", id: event.id, cancelled: true }).catch(() => undefined);
|
|
661
|
-
return;
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
if (event.type === "agent_start") {
|
|
665
|
-
resolveInitialPrompt(true);
|
|
666
|
-
// Also publishes the live "running" status.
|
|
667
|
-
setAttemptPhase("running");
|
|
668
|
-
}
|
|
669
|
-
if (event.type === "turn_start") {
|
|
670
|
-
setAttemptPhase("running");
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
if (event.type === "message_update") {
|
|
674
|
-
const type = event.assistantMessageEvent?.type;
|
|
675
|
-
if (type === "thinking_delta" || type === "text_delta") {
|
|
676
|
-
emit({ kind: type === "thinking_delta" ? "thinking" : "text" });
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
if (event.type === "tool_execution_start") {
|
|
681
|
-
emit({
|
|
682
|
-
kind: "tool_start",
|
|
683
|
-
...(typeof event.toolCallId === "string" ? { toolCallId: event.toolCallId } : {}),
|
|
684
|
-
toolName: event.toolName ?? "unknown",
|
|
685
|
-
args: event.args,
|
|
686
|
-
});
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
if (event.type === "tool_execution_end") {
|
|
690
|
-
emit({
|
|
691
|
-
kind: "tool_end",
|
|
692
|
-
...(typeof event.toolCallId === "string" ? { toolCallId: event.toolCallId } : {}),
|
|
693
|
-
toolName: event.toolName ?? "unknown",
|
|
694
|
-
isError: Boolean(event.isError),
|
|
695
|
-
});
|
|
696
|
-
if (event.isError) {
|
|
697
|
-
(result.failedTools ??= []).push({
|
|
698
|
-
toolName: event.toolName ?? "unknown",
|
|
699
|
-
error: extractToolErrorText(event.result?.content),
|
|
700
|
-
});
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
if (event.type === "message_end" && event.message) {
|
|
705
|
-
const message = event.message as Message;
|
|
706
|
-
result.messages.push(message);
|
|
707
|
-
if (message.role === "assistant") {
|
|
708
|
-
result.usage.turns++;
|
|
709
|
-
const usage = (message as any).usage;
|
|
710
|
-
if (usage) {
|
|
711
|
-
result.usage.input += usage.input || 0;
|
|
712
|
-
result.usage.output += usage.output || 0;
|
|
713
|
-
result.usage.cacheRead += usage.cacheRead || 0;
|
|
714
|
-
result.usage.cacheWrite += usage.cacheWrite || 0;
|
|
715
|
-
result.usage.cost += usage.cost?.total || 0;
|
|
716
|
-
result.usage.contextTokens = usage.totalTokens || 0;
|
|
717
|
-
}
|
|
718
|
-
if (!result.model && (message as any).model) result.model = (message as any).model;
|
|
719
|
-
result.stopReason = message.stopReason;
|
|
720
|
-
result.errorMessage = message.errorMessage;
|
|
721
|
-
}
|
|
722
|
-
emit({ kind: "usage", usage: { ...result.usage }, model: result.model });
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
if (event.type === "agent_settled") {
|
|
726
|
-
if (abortSettlement) {
|
|
727
|
-
const stable = abortSettlement;
|
|
728
|
-
abortSettlement = undefined;
|
|
729
|
-
stable.resolve();
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
void settleRunWithUsage();
|
|
733
|
-
}
|
|
734
|
-
};
|
|
735
|
-
|
|
736
|
-
proc.stdout?.on("data", (chunk: Buffer | string) => {
|
|
737
|
-
lastActivityAt = Date.now();
|
|
738
|
-
stdoutBuffer += typeof chunk === "string" ? chunk : stdoutDecoder.write(chunk);
|
|
739
|
-
// Scan with a cursor and cut the buffer once per chunk: streaming
|
|
740
|
-
// message_update records are large, and re-slicing per line is quadratic.
|
|
741
|
-
let start = 0;
|
|
742
|
-
for (let lf = stdoutBuffer.indexOf("\n"); lf !== -1; lf = stdoutBuffer.indexOf("\n", start)) {
|
|
743
|
-
processLine(stdoutBuffer.slice(start, lf));
|
|
744
|
-
start = lf + 1;
|
|
745
|
-
}
|
|
746
|
-
if (start > 0) stdoutBuffer = stdoutBuffer.slice(start);
|
|
747
|
-
});
|
|
748
|
-
|
|
749
|
-
proc.stderr?.on("data", (chunk: Buffer | string) => {
|
|
750
|
-
result.stderr = appendBoundedStderr(result.stderr, typeof chunk === "string" ? chunk : stderrDecoder.write(chunk));
|
|
751
|
-
});
|
|
752
|
-
|
|
753
|
-
proc.stdin?.on("error", (error) => {
|
|
754
|
-
if (finished) return;
|
|
755
|
-
resolveInitialPrompt(false, error);
|
|
756
|
-
result.exitCode = 1;
|
|
757
|
-
result.stopReason = "error";
|
|
758
|
-
result.errorMessage ??= `Subagent RPC stdin failed: ${error.message}`;
|
|
759
|
-
result.dispatchFailed = true;
|
|
760
|
-
finish();
|
|
761
|
-
terminate();
|
|
762
|
-
});
|
|
763
|
-
|
|
764
|
-
proc.once("error", (error) => {
|
|
765
|
-
if (finished) return;
|
|
766
|
-
resolveInitialPrompt(false, error);
|
|
767
|
-
result.exitCode = 1;
|
|
768
|
-
result.stopReason = "error";
|
|
769
|
-
result.errorMessage ??= `Failed to start the sub-agent process: ${error.message}`;
|
|
770
|
-
result.dispatchFailed = true;
|
|
771
|
-
finish();
|
|
772
|
-
});
|
|
773
|
-
|
|
774
|
-
proc.once("close", (code, exitSignal) => {
|
|
775
|
-
closed = true;
|
|
776
|
-
const disposition = exitSignal ? `signal=${exitSignal}` : `code=${code}`;
|
|
777
|
-
resolveInitialPrompt(false, new Error(`Subagent RPC process exited before the initial prompt was accepted (${disposition}).`));
|
|
778
|
-
if (forceKillTimer) clearTimeout(forceKillTimer);
|
|
779
|
-
stdoutBuffer += stdoutDecoder.end();
|
|
780
|
-
result.stderr = appendBoundedStderr(result.stderr, stderrDecoder.end());
|
|
781
|
-
if (stdoutBuffer.length > 0) processLine(stdoutBuffer);
|
|
782
|
-
const exitError = new Error(
|
|
783
|
-
`Subagent RPC process exited before settling (${disposition}).${result.stderr ? ` ${result.stderr.trim()}` : ""}`,
|
|
784
|
-
);
|
|
785
|
-
rejectPending(exitError);
|
|
786
|
-
if (abortSettlement) {
|
|
787
|
-
abortSettlement.reject(exitError);
|
|
788
|
-
abortSettlement = undefined;
|
|
789
|
-
}
|
|
790
|
-
if (!finished && !usageSettlementStarted) {
|
|
791
|
-
const silentStartupExit = !result.rpcPromptDispatched && !result.rpcActivity
|
|
792
|
-
&& result.messages.length === 0 && !result.stderr.trim() && !result.errorMessage?.trim();
|
|
793
|
-
result.exitCode = code === 0 ? 1 : (code ?? 1);
|
|
794
|
-
result.stopReason = signal?.aborted ? "aborted" : "error";
|
|
795
|
-
if (signal?.aborted) {
|
|
796
|
-
result.errorMessage ||= "Subagent was aborted";
|
|
797
|
-
} else {
|
|
798
|
-
result.errorMessage = result.errorMessage?.trim()
|
|
799
|
-
? `${result.errorMessage}\n${exitError.message}` : exitError.message;
|
|
800
|
-
if (silentStartupExit) result.rpcStartupFailed = true;
|
|
801
|
-
else result.dispatchFailed = true;
|
|
802
|
-
}
|
|
803
|
-
finish();
|
|
804
|
-
}
|
|
805
|
-
processClosed.resolve();
|
|
806
|
-
});
|
|
807
|
-
|
|
808
|
-
if (idleTimeoutMs > 0) {
|
|
809
|
-
const checkInterval = Math.max(1, Math.min(10_000, Math.floor(idleTimeoutMs / 3)));
|
|
810
|
-
idleTimer = setInterval(() => {
|
|
811
|
-
if (finished || closed) return;
|
|
812
|
-
if (Date.now() - lastActivityAt >= idleTimeoutMs) {
|
|
813
|
-
result.exitCode = 1;
|
|
814
|
-
result.stopReason = "error";
|
|
815
|
-
result.errorMessage = `Subagent idle timeout: no activity for ${Math.ceil(idleTimeoutMs / 1000)} seconds.`;
|
|
816
|
-
finish();
|
|
817
|
-
terminate();
|
|
818
|
-
}
|
|
819
|
-
}, checkInterval);
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
if (signal) {
|
|
823
|
-
abortHandler = () => {
|
|
824
|
-
const stopping = control
|
|
825
|
-
? control.stop("Subagent was aborted")
|
|
826
|
-
: attemptControl.stop("Subagent was aborted");
|
|
827
|
-
void stopping.catch(() => undefined);
|
|
828
|
-
};
|
|
829
|
-
if (signal.aborted) abortHandler();
|
|
830
|
-
else signal.addEventListener("abort", abortHandler, { once: true });
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
try {
|
|
834
|
-
if (control?.isStopRequested()) {
|
|
835
|
-
resolveInitialPrompt(false, new Error("Run was stopped before its initial prompt."));
|
|
836
|
-
await attemptControl.stop();
|
|
837
|
-
} else {
|
|
838
|
-
const failBeforePrompt = (error: Error, startup: boolean): void => {
|
|
839
|
-
resolveInitialPrompt(false, error);
|
|
840
|
-
if (finished) return;
|
|
841
|
-
result.exitCode = 1;
|
|
842
|
-
result.stopReason = "error";
|
|
843
|
-
result.errorMessage = error.message;
|
|
844
|
-
if (startup) result.rpcStartupFailed = true;
|
|
845
|
-
else if (error instanceof RpcCommandRejectedError) result.rpcPromptRejected = true;
|
|
846
|
-
finish();
|
|
847
|
-
terminate();
|
|
848
|
-
};
|
|
849
|
-
try {
|
|
850
|
-
await send({ type: "get_state" }, readyTimeoutMs);
|
|
851
|
-
try {
|
|
852
|
-
usageBaseline = sessionUsage((await send({ type: "get_session_stats" })).data);
|
|
853
|
-
} catch {
|
|
854
|
-
/* older or degraded RPC children fall back to message usage */
|
|
855
|
-
}
|
|
856
|
-
} catch (error) {
|
|
857
|
-
const handshakeError = error instanceof Error ? error : new Error(String(error));
|
|
858
|
-
if (!control?.isStopRequested()) {
|
|
859
|
-
failBeforePrompt(handshakeError, true);
|
|
860
|
-
} else {
|
|
861
|
-
resolveInitialPrompt(false, handshakeError);
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
if (!finished && !initialPromptResolved && !control?.isStopRequested()) {
|
|
865
|
-
// Pi starts the agent immediately after prompt preflight, before its
|
|
866
|
-
// success response necessarily reaches stdout. From this point on, a
|
|
867
|
-
// missing ACK is ambiguous and must never be recovered by replay.
|
|
868
|
-
result.rpcPromptDispatched = true;
|
|
869
|
-
void send({ type: "prompt", message: asPlainTextRpcPrompt(options.prompt) }).then(
|
|
870
|
-
() => resolveInitialPrompt(true),
|
|
871
|
-
(error) => {
|
|
872
|
-
const promptError = error instanceof Error ? error : new Error(String(error));
|
|
873
|
-
failBeforePrompt(promptError, false);
|
|
874
|
-
},
|
|
875
|
-
);
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
await outcome.promise;
|
|
879
|
-
terminate();
|
|
880
|
-
if (!closed) await processClosed.promise;
|
|
881
|
-
return result;
|
|
882
|
-
} finally {
|
|
883
|
-
if (attemptToken !== undefined) control?.detach(attemptToken);
|
|
884
|
-
// Recursive removal: the directory also holds the temp-hygiene owner marker,
|
|
885
|
-
// so an empty-directory removal always fails and leaks one dir per dispatch.
|
|
886
|
-
if (tmpPromptDir) await rm(tmpPromptDir, { recursive: true, force: true }).catch(() => undefined);
|
|
887
|
-
await rm(retryPolicy.dir, { recursive: true, force: true }).catch(() => undefined);
|
|
888
|
-
}
|
|
889
|
-
}
|