@ferris1225/pi-subagents 0.32.2 → 1.0.1
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/README.md +45 -22
- package/agents/reviewer.md +2 -0
- package/package.json +2 -2
- package/src/agents.ts +2 -7
- package/src/announcements.ts +62 -0
- package/src/completion.ts +7 -36
- package/src/config.ts +327 -364
- package/src/dispatch.ts +1682 -1878
- package/src/fixloop.ts +0 -16
- package/src/format.ts +4 -8
- package/src/index.ts +8 -9
- package/src/models.ts +17 -39
- package/src/monitor.ts +64 -175
- package/src/rpc-run.ts +2 -41
- package/src/runtime.ts +272 -285
- package/src/session-fork.ts +0 -4
- package/src/setup.ts +4 -4
- package/src/spawn.ts +542 -562
- package/src/tools.ts +706 -748
- package/src/ui.ts +3 -7
- package/src/widget.ts +90 -178
- package/src/worktree.ts +1 -1
- package/src/inspector-panel.ts +0 -363
- package/src/inspector.ts +0 -369
- package/src/trajectory.ts +0 -503
package/src/spawn.ts
CHANGED
|
@@ -1,562 +1,542 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sub-agent result handling and resilient RPC launch orchestration.
|
|
3
|
-
*
|
|
4
|
-
* The process transport itself lives in rpc-run.ts. Each attempt starts pi in
|
|
5
|
-
* persistent `--mode rpc`, sends commands over strict LF-delimited JSONL, and
|
|
6
|
-
* settles only on `agent_settled`. This module preserves the existing startup
|
|
7
|
-
* retry, same-model retry, model fallback, accounting, and result formatting
|
|
8
|
-
* contracts around those attempts.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { randomUUID } from "node:crypto";
|
|
12
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
13
|
-
import { mkdtemp, rm } from "node:fs/promises";
|
|
14
|
-
import { tmpdir } from "node:os";
|
|
15
|
-
import { basename, join } from "node:path";
|
|
16
|
-
import type { Message } from "@earendil-works/pi-ai";
|
|
17
|
-
import type { AgentConfig } from "./agents.ts";
|
|
18
|
-
import { DEFAULT_THINKING_LEVEL, type ThinkingLevel } from "./config.ts";
|
|
19
|
-
import {
|
|
20
|
-
currentSubagentDepth,
|
|
21
|
-
DEPTH_ENV_VAR,
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
type
|
|
30
|
-
type
|
|
31
|
-
type UsageStats,
|
|
32
|
-
} from "./rpc-run.ts";
|
|
33
|
-
|
|
34
|
-
export {
|
|
35
|
-
currentSubagentDepth,
|
|
36
|
-
DEPTH_ENV_VAR,
|
|
37
|
-
extractToolErrorText,
|
|
38
|
-
getPiInvocation,
|
|
39
|
-
RpcRunControl,
|
|
40
|
-
sessionExists,
|
|
41
|
-
SUBAGENT_KILL_GRACE_MS,
|
|
42
|
-
};
|
|
43
|
-
export type { SubagentLiveEvent,
|
|
44
|
-
|
|
45
|
-
export const SUBAGENT_THINKING_LEVEL: ThinkingLevel = DEFAULT_THINKING_LEVEL;
|
|
46
|
-
/** 0 disables the watchdog; dispatch supplies the configured timeout. */
|
|
47
|
-
export const SUBAGENT_DEFAULT_IDLE_TIMEOUT_MS = 0;
|
|
48
|
-
export const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500] as const;
|
|
49
|
-
export const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
|
|
50
|
-
export const SUBAGENT_RUN_LEVEL_RETRY_DELAYS_MS = [2_000, 4_000, 8_000, 16_000, 30_000] as const;
|
|
51
|
-
|
|
52
|
-
export interface SingleResult extends RpcSingleResult {}
|
|
53
|
-
|
|
54
|
-
export interface SubagentDetails {
|
|
55
|
-
mode: "single" | "parallel";
|
|
56
|
-
results: SingleResult[];
|
|
57
|
-
background?: boolean;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function getFinalOutput(messages: Message[]): string {
|
|
61
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
62
|
-
const msg = messages[i];
|
|
63
|
-
if (msg.role === "assistant") {
|
|
64
|
-
for (const part of msg.content) {
|
|
65
|
-
if (part.type === "text") return part.text;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return "";
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Only the last standalone reviewer verdict line counts. */
|
|
73
|
-
export function reviewVerdict(output: string): "pass" | "fail" | undefined {
|
|
74
|
-
const lines = output.split("\n");
|
|
75
|
-
for (let index = lines.length - 1; index >= 0; index--) {
|
|
76
|
-
const match = /^\s*VERDICT:\s*REVIEW_(PASS|FAIL)\s*$/i.exec(lines[index]);
|
|
77
|
-
if (match) return match[1].toUpperCase() === "PASS" ? "pass" : "fail";
|
|
78
|
-
}
|
|
79
|
-
return undefined;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export const RESULT_LINE_MAX = 200;
|
|
83
|
-
|
|
84
|
-
export interface TruncatedOutput {
|
|
85
|
-
text: string;
|
|
86
|
-
truncated: boolean;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export function truncateResultOutput(output: string, maxLines: number): TruncatedOutput {
|
|
90
|
-
const lines = output.split("\n");
|
|
91
|
-
if (lines.length <= maxLines && lines.every((line) => line.length <= RESULT_LINE_MAX)) {
|
|
92
|
-
return { text: output, truncated: false };
|
|
93
|
-
}
|
|
94
|
-
const kept = lines.slice(0, maxLines).map((line) =>
|
|
95
|
-
line.length > RESULT_LINE_MAX ? `${line.slice(0, RESULT_LINE_MAX)}…` : line,
|
|
96
|
-
);
|
|
97
|
-
return { text: kept.join("\n"), truncated: true };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export function writeResultArtifact(output: string, agentName: string, cwd?: string): string {
|
|
101
|
-
const projectSlug = cwd ? basename(cwd).replace(/[^\w.-]+/g, "_") || "default" : "default";
|
|
102
|
-
const dir = join(tmpdir(), "pi-subagents-results", projectSlug);
|
|
103
|
-
mkdirSync(dir, { recursive: true });
|
|
104
|
-
const safeName = agentName.replace(/[^\w.-]+/g, "_");
|
|
105
|
-
const unique = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
106
|
-
const filePath = join(dir, `${unique}-${safeName}.md`);
|
|
107
|
-
writeFileSync(filePath, output, "utf8");
|
|
108
|
-
return filePath;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export function isFailedResult(result: SingleResult): boolean {
|
|
112
|
-
if (result.parked) return false;
|
|
113
|
-
return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function lastAssistantMessage(messages: Message[]): Extract<Message, { role: "assistant" }> | undefined {
|
|
117
|
-
for (let index = messages.length - 1; index >= 0; index--) {
|
|
118
|
-
const message = messages[index];
|
|
119
|
-
if (message.role === "assistant") return message;
|
|
120
|
-
}
|
|
121
|
-
return undefined;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function assistantText(message: Extract<Message, { role: "assistant" }>): string {
|
|
125
|
-
return message.content
|
|
126
|
-
.filter((part): part is Extract<(typeof message.content)[number], { type: "text" }> => part.type === "text")
|
|
127
|
-
.map((part) => part.text)
|
|
128
|
-
.join("");
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export function isModelLevelFailure(result: SingleResult): boolean {
|
|
132
|
-
if (!isFailedResult(result)) return false;
|
|
133
|
-
if (result.stopReason === "aborted") return false;
|
|
134
|
-
if (result.dispatchFailed) return false;
|
|
135
|
-
if (result.integrationStatus === "retained") return false;
|
|
136
|
-
if (result.errorMessage?.includes("idle timeout")) return true;
|
|
137
|
-
if (result.rpcPromptRejected) return true;
|
|
138
|
-
|
|
139
|
-
// Classification belongs to the final assistant turn, not the whole attempt.
|
|
140
|
-
// Earlier useful text or failed tool calls are retained session history and
|
|
141
|
-
// must not hide a later provider error (for example a second-turn 503).
|
|
142
|
-
const finalAssistant = lastAssistantMessage(result.messages);
|
|
143
|
-
if (finalAssistant) {
|
|
144
|
-
if (finalAssistant.stopReason !== "error") return false;
|
|
145
|
-
if (assistantText(finalAssistant).trim()) return false;
|
|
146
|
-
return Boolean(
|
|
147
|
-
finalAssistant.errorMessage?.trim() ||
|
|
148
|
-
result.errorMessage?.trim() ||
|
|
149
|
-
result.stderr.trim() ||
|
|
150
|
-
finalAssistant.content.length === 0
|
|
151
|
-
);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
if ((result.failedTools?.length ?? 0) > 0) return false;
|
|
155
|
-
return Boolean(result.errorMessage?.trim()) || result.stderr.trim().length > 0;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const TERMINAL_MODEL_ERROR_PATTERN =
|
|
159
|
-
/insufficient_quota|quota\s+exceeded|exceeded[^.\n]{0,40}quota|out\s+of\s+budget|billing|usage\s+limit|usage_limit|gousagelimiterror|freeusagelimiterror|monthly\s+usage\s+limit\s+reached|available\s+balance|invalid\s+(?:api\s+)?key|incorrect\s+api\s+key|unauthori[sz]ed|\b401\b|\b403\b|forbidden|permission\s+denied/i;
|
|
160
|
-
const PERMANENT_MODEL_CANDIDATE_ERROR_PATTERN =
|
|
161
|
-
/model[_ -]?not[_ -]?found|no\s+models?\s+(?:found|matched)|(?:model|provider)[^.\n]{0,80}(?:not\s+found|unknown|does\s+not\s+exist|unsupported|invalid)|(?:not\s+found|unknown|unsupported|invalid)[^.\n]{0,40}(?:model|provider)|\b404\b/i;
|
|
162
|
-
|
|
163
|
-
export function isTerminalModelError(result: SingleResult): boolean {
|
|
164
|
-
const message = result.errorMessage?.trim();
|
|
165
|
-
if (message) return TERMINAL_MODEL_ERROR_PATTERN.test(message);
|
|
166
|
-
const stderr = result.stderr.trim();
|
|
167
|
-
return stderr.length > 0 && TERMINAL_MODEL_ERROR_PATTERN.test(stderr);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** A permanent failure of this model/provider reference (stale id, unknown
|
|
171
|
-
* provider, 404 config route). Skip same-candidate backoff, but keep advancing
|
|
172
|
-
* through backup and current-main candidates. */
|
|
173
|
-
export function isPermanentModelCandidateError(result: SingleResult): boolean {
|
|
174
|
-
const message = result.errorMessage?.trim();
|
|
175
|
-
if (message) return PERMANENT_MODEL_CANDIDATE_ERROR_PATTERN.test(message);
|
|
176
|
-
const stderr = result.stderr.trim();
|
|
177
|
-
return stderr.length > 0 && PERMANENT_MODEL_CANDIDATE_ERROR_PATTERN.test(stderr);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
export function isRetryableStartupFailure(result: SingleResult, durationMs: number): boolean {
|
|
181
|
-
if (result.exitCode === 0) return false;
|
|
182
|
-
if (result.stopReason === "aborted") return false;
|
|
183
|
-
if (result.dispatchFailed) return false;
|
|
184
|
-
if (result.errorMessage?.includes("idle timeout")) return false;
|
|
185
|
-
if (getFinalOutput(result.messages)) return false;
|
|
186
|
-
if (result.messages.length > 0) return false;
|
|
187
|
-
const usage = result.usage;
|
|
188
|
-
if (usage.turns || usage.input || usage.output || usage.cacheRead || usage.cacheWrite || usage.cost) return false;
|
|
189
|
-
if (durationMs > MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS) return false;
|
|
190
|
-
if (result.stderr.trim().length > 0) return false;
|
|
191
|
-
if (result.errorMessage && result.errorMessage.trim().length > 0) return false;
|
|
192
|
-
return true;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
export function formatStartupRetryExhaustedError(model: string, attempts: number): string {
|
|
196
|
-
return `Subagent failed to start after ${attempts} attempt${attempts === 1 ? "" : "s"} on ${model}: the child exited before any model, tool, output, or usage activity. This is typically a concurrent pi startup race (several sub-agents starting at once). Retry the dispatch, or temporarily lower maxConcurrency in /subagents-setup.`;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
export async function waitForStartupRetry(delayMs: number, signal?: AbortSignal): Promise<boolean> {
|
|
200
|
-
if (delayMs <= 0) return !signal?.aborted;
|
|
201
|
-
if (!signal) {
|
|
202
|
-
return new Promise<boolean>((resolve) => {
|
|
203
|
-
const timer = setTimeout(() => resolve(true), delayMs);
|
|
204
|
-
if (typeof timer.unref === "function") timer.unref();
|
|
205
|
-
});
|
|
206
|
-
}
|
|
207
|
-
if (signal.aborted) return false;
|
|
208
|
-
return new Promise<boolean>((resolve) => {
|
|
209
|
-
let settled = false;
|
|
210
|
-
const finish = (shouldRetry: boolean): void => {
|
|
211
|
-
if (settled) return;
|
|
212
|
-
settled = true;
|
|
213
|
-
clearTimeout(timer);
|
|
214
|
-
signal.removeEventListener("abort", onAbort);
|
|
215
|
-
resolve(shouldRetry);
|
|
216
|
-
};
|
|
217
|
-
const onAbort = (): void => finish(false);
|
|
218
|
-
const timer = setTimeout(() => finish(true), delayMs);
|
|
219
|
-
if (typeof timer.unref === "function") timer.unref();
|
|
220
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async function waitForControlledRetry(
|
|
225
|
-
delayMs: number,
|
|
226
|
-
signal: AbortSignal | undefined,
|
|
227
|
-
control: RpcRunControl | undefined,
|
|
228
|
-
): Promise<boolean> {
|
|
229
|
-
let remaining = delayMs;
|
|
230
|
-
while (remaining > 0) {
|
|
231
|
-
if (control?.isParkRequested() || control?.isStopRequested()) return false;
|
|
232
|
-
const slice = Math.min(remaining, 50);
|
|
233
|
-
if (!(await waitForStartupRetry(slice, signal))) return false;
|
|
234
|
-
remaining -= slice;
|
|
235
|
-
}
|
|
236
|
-
return !signal?.aborted && !control?.isParkRequested() && !control?.isStopRequested();
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
export function getResultOutput(result: SingleResult): string {
|
|
240
|
-
if (isFailedResult(result)) {
|
|
241
|
-
const error = result.errorMessage || result.stderr;
|
|
242
|
-
const partial = getFinalOutput(result.messages);
|
|
243
|
-
if (error && partial) return `${error}\n\n--- Partial output ---\n${partial}`;
|
|
244
|
-
return error || partial || "(no output)";
|
|
245
|
-
}
|
|
246
|
-
return getFinalOutput(result.messages) || "(no output)";
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
export function buildResumePrompt(task: string, reason: string): string {
|
|
250
|
-
return `You are resuming an earlier sub-agent session after ${reason}. Your earlier work — searches, reads, edits, and reasoning — is preserved in this session's history above; review it before acting. Original task: ${task}. Pick up exactly where you left off and finish it. Do NOT redo searches, reads, or edits you already completed unless a step clearly failed. Continue now.`;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
export function buildFallbackResumeReason(fromModel?: string): string {
|
|
254
|
-
return fromModel
|
|
255
|
-
? `the previous model (${fromModel}) failed at the model/provider level, so the next model in its configured pool is continuing`
|
|
256
|
-
: "the previous model failed at the model/provider level, so the next model in its configured pool is continuing";
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
export interface RunSingleOptions {
|
|
260
|
-
defaultCwd: string;
|
|
261
|
-
agent: AgentConfig
|
|
262
|
-
agentName: string;
|
|
263
|
-
task: string;
|
|
264
|
-
cwd?: string;
|
|
265
|
-
thinkingLevel?: ThinkingLevel;
|
|
266
|
-
idleTimeoutMs?: number;
|
|
267
|
-
startupRetryDelaysMs?: readonly number[];
|
|
268
|
-
runLevelRetryDelaysMs?: readonly number[];
|
|
269
|
-
sessionDir?: string;
|
|
270
|
-
sessionId?: string;
|
|
271
|
-
/** Initial RPC prompt. Kept under the old name to limit caller churn. */
|
|
272
|
-
stdinText?: string;
|
|
273
|
-
signal?: AbortSignal;
|
|
274
|
-
onLive?: (event: SubagentLiveEvent) => void;
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
result.
|
|
304
|
-
result.
|
|
305
|
-
result.
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
if (
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
if (
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
return
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
let
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
const
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
return controlledDisposition(baseOptions, result) ?? result;
|
|
544
|
-
}
|
|
545
|
-
result = await runWithStartupRetry(retryOptions);
|
|
546
|
-
modelRetries++;
|
|
547
|
-
if (result.parked || result.stopReason === "aborted") return result;
|
|
548
|
-
if (
|
|
549
|
-
!isModelLevelFailure(result) ||
|
|
550
|
-
isTerminalModelError(result) ||
|
|
551
|
-
isPermanentModelCandidateError(result)
|
|
552
|
-
) break;
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
if (!isModelLevelFailure(result)) return finish(result);
|
|
557
|
-
// Transient exhaustion plus terminal/permanent candidate errors advance
|
|
558
|
-
// to the next configured candidate. Ordinary task/tool failures returned above.
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
return finish(result ?? (await dispatchFailure("No model candidate was attempted.")));
|
|
562
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Sub-agent result handling and resilient RPC launch orchestration.
|
|
3
|
+
*
|
|
4
|
+
* The process transport itself lives in rpc-run.ts. Each attempt starts pi in
|
|
5
|
+
* persistent `--mode rpc`, sends commands over strict LF-delimited JSONL, and
|
|
6
|
+
* settles only on `agent_settled`. This module preserves the existing startup
|
|
7
|
+
* retry, same-model retry, model fallback, accounting, and result formatting
|
|
8
|
+
* contracts around those attempts.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { basename, join } from "node:path";
|
|
16
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
17
|
+
import type { AgentConfig } from "./agents.ts";
|
|
18
|
+
import { DEFAULT_THINKING_LEVEL, type ThinkingLevel } from "./config.ts";
|
|
19
|
+
import {
|
|
20
|
+
currentSubagentDepth,
|
|
21
|
+
DEPTH_ENV_VAR,
|
|
22
|
+
emptyUsage,
|
|
23
|
+
extractToolErrorText,
|
|
24
|
+
getPiInvocation,
|
|
25
|
+
RpcRunControl,
|
|
26
|
+
runRpcAgentAttempt,
|
|
27
|
+
sessionExists,
|
|
28
|
+
SUBAGENT_KILL_GRACE_MS,
|
|
29
|
+
type RpcSingleResult,
|
|
30
|
+
type SubagentLiveEvent,
|
|
31
|
+
type UsageStats,
|
|
32
|
+
} from "./rpc-run.ts";
|
|
33
|
+
|
|
34
|
+
export {
|
|
35
|
+
currentSubagentDepth,
|
|
36
|
+
DEPTH_ENV_VAR,
|
|
37
|
+
extractToolErrorText,
|
|
38
|
+
getPiInvocation,
|
|
39
|
+
RpcRunControl,
|
|
40
|
+
sessionExists,
|
|
41
|
+
SUBAGENT_KILL_GRACE_MS,
|
|
42
|
+
};
|
|
43
|
+
export type { SubagentLiveEvent, UsageStats };
|
|
44
|
+
|
|
45
|
+
export const SUBAGENT_THINKING_LEVEL: ThinkingLevel = DEFAULT_THINKING_LEVEL;
|
|
46
|
+
/** 0 disables the watchdog; dispatch supplies the configured timeout. */
|
|
47
|
+
export const SUBAGENT_DEFAULT_IDLE_TIMEOUT_MS = 0;
|
|
48
|
+
export const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500] as const;
|
|
49
|
+
export const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
|
|
50
|
+
export const SUBAGENT_RUN_LEVEL_RETRY_DELAYS_MS = [2_000, 4_000, 8_000, 16_000, 30_000] as const;
|
|
51
|
+
|
|
52
|
+
export interface SingleResult extends RpcSingleResult {}
|
|
53
|
+
|
|
54
|
+
export interface SubagentDetails {
|
|
55
|
+
mode: "single" | "parallel";
|
|
56
|
+
results: SingleResult[];
|
|
57
|
+
background?: boolean;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function getFinalOutput(messages: Message[]): string {
|
|
61
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
62
|
+
const msg = messages[i];
|
|
63
|
+
if (msg.role === "assistant") {
|
|
64
|
+
for (const part of msg.content) {
|
|
65
|
+
if (part.type === "text") return part.text;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return "";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Only the last standalone reviewer verdict line counts. */
|
|
73
|
+
export function reviewVerdict(output: string): "pass" | "fail" | undefined {
|
|
74
|
+
const lines = output.split("\n");
|
|
75
|
+
for (let index = lines.length - 1; index >= 0; index--) {
|
|
76
|
+
const match = /^\s*VERDICT:\s*REVIEW_(PASS|FAIL)\s*$/i.exec(lines[index]);
|
|
77
|
+
if (match) return match[1].toUpperCase() === "PASS" ? "pass" : "fail";
|
|
78
|
+
}
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export const RESULT_LINE_MAX = 200;
|
|
83
|
+
|
|
84
|
+
export interface TruncatedOutput {
|
|
85
|
+
text: string;
|
|
86
|
+
truncated: boolean;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function truncateResultOutput(output: string, maxLines: number): TruncatedOutput {
|
|
90
|
+
const lines = output.split("\n");
|
|
91
|
+
if (lines.length <= maxLines && lines.every((line) => line.length <= RESULT_LINE_MAX)) {
|
|
92
|
+
return { text: output, truncated: false };
|
|
93
|
+
}
|
|
94
|
+
const kept = lines.slice(0, maxLines).map((line) =>
|
|
95
|
+
line.length > RESULT_LINE_MAX ? `${line.slice(0, RESULT_LINE_MAX)}…` : line,
|
|
96
|
+
);
|
|
97
|
+
return { text: kept.join("\n"), truncated: true };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function writeResultArtifact(output: string, agentName: string, cwd?: string): string {
|
|
101
|
+
const projectSlug = cwd ? basename(cwd).replace(/[^\w.-]+/g, "_") || "default" : "default";
|
|
102
|
+
const dir = join(tmpdir(), "pi-subagents-results", projectSlug);
|
|
103
|
+
mkdirSync(dir, { recursive: true });
|
|
104
|
+
const safeName = agentName.replace(/[^\w.-]+/g, "_");
|
|
105
|
+
const unique = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
106
|
+
const filePath = join(dir, `${unique}-${safeName}.md`);
|
|
107
|
+
writeFileSync(filePath, output, "utf8");
|
|
108
|
+
return filePath;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function isFailedResult(result: SingleResult): boolean {
|
|
112
|
+
if (result.parked) return false;
|
|
113
|
+
return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function lastAssistantMessage(messages: Message[]): Extract<Message, { role: "assistant" }> | undefined {
|
|
117
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
118
|
+
const message = messages[index];
|
|
119
|
+
if (message.role === "assistant") return message;
|
|
120
|
+
}
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function assistantText(message: Extract<Message, { role: "assistant" }>): string {
|
|
125
|
+
return message.content
|
|
126
|
+
.filter((part): part is Extract<(typeof message.content)[number], { type: "text" }> => part.type === "text")
|
|
127
|
+
.map((part) => part.text)
|
|
128
|
+
.join("");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function isModelLevelFailure(result: SingleResult): boolean {
|
|
132
|
+
if (!isFailedResult(result)) return false;
|
|
133
|
+
if (result.stopReason === "aborted") return false;
|
|
134
|
+
if (result.dispatchFailed) return false;
|
|
135
|
+
if (result.integrationStatus === "retained") return false;
|
|
136
|
+
if (result.errorMessage?.includes("idle timeout")) return true;
|
|
137
|
+
if (result.rpcPromptRejected) return true;
|
|
138
|
+
|
|
139
|
+
// Classification belongs to the final assistant turn, not the whole attempt.
|
|
140
|
+
// Earlier useful text or failed tool calls are retained session history and
|
|
141
|
+
// must not hide a later provider error (for example a second-turn 503).
|
|
142
|
+
const finalAssistant = lastAssistantMessage(result.messages);
|
|
143
|
+
if (finalAssistant) {
|
|
144
|
+
if (finalAssistant.stopReason !== "error") return false;
|
|
145
|
+
if (assistantText(finalAssistant).trim()) return false;
|
|
146
|
+
return Boolean(
|
|
147
|
+
finalAssistant.errorMessage?.trim() ||
|
|
148
|
+
result.errorMessage?.trim() ||
|
|
149
|
+
result.stderr.trim() ||
|
|
150
|
+
finalAssistant.content.length === 0
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if ((result.failedTools?.length ?? 0) > 0) return false;
|
|
155
|
+
return Boolean(result.errorMessage?.trim()) || result.stderr.trim().length > 0;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const TERMINAL_MODEL_ERROR_PATTERN =
|
|
159
|
+
/insufficient_quota|quota\s+exceeded|exceeded[^.\n]{0,40}quota|out\s+of\s+budget|billing|usage\s+limit|usage_limit|gousagelimiterror|freeusagelimiterror|monthly\s+usage\s+limit\s+reached|available\s+balance|invalid\s+(?:api\s+)?key|incorrect\s+api\s+key|unauthori[sz]ed|\b401\b|\b403\b|forbidden|permission\s+denied/i;
|
|
160
|
+
const PERMANENT_MODEL_CANDIDATE_ERROR_PATTERN =
|
|
161
|
+
/model[_ -]?not[_ -]?found|no\s+models?\s+(?:found|matched)|(?:model|provider)[^.\n]{0,80}(?:not\s+found|unknown|does\s+not\s+exist|unsupported|invalid)|(?:not\s+found|unknown|unsupported|invalid)[^.\n]{0,40}(?:model|provider)|\b404\b/i;
|
|
162
|
+
|
|
163
|
+
export function isTerminalModelError(result: SingleResult): boolean {
|
|
164
|
+
const message = result.errorMessage?.trim();
|
|
165
|
+
if (message) return TERMINAL_MODEL_ERROR_PATTERN.test(message);
|
|
166
|
+
const stderr = result.stderr.trim();
|
|
167
|
+
return stderr.length > 0 && TERMINAL_MODEL_ERROR_PATTERN.test(stderr);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A permanent failure of this model/provider reference (stale id, unknown
|
|
171
|
+
* provider, 404 config route). Skip same-candidate backoff, but keep advancing
|
|
172
|
+
* through backup and current-main candidates. */
|
|
173
|
+
export function isPermanentModelCandidateError(result: SingleResult): boolean {
|
|
174
|
+
const message = result.errorMessage?.trim();
|
|
175
|
+
if (message) return PERMANENT_MODEL_CANDIDATE_ERROR_PATTERN.test(message);
|
|
176
|
+
const stderr = result.stderr.trim();
|
|
177
|
+
return stderr.length > 0 && PERMANENT_MODEL_CANDIDATE_ERROR_PATTERN.test(stderr);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function isRetryableStartupFailure(result: SingleResult, durationMs: number): boolean {
|
|
181
|
+
if (result.exitCode === 0) return false;
|
|
182
|
+
if (result.stopReason === "aborted") return false;
|
|
183
|
+
if (result.dispatchFailed) return false;
|
|
184
|
+
if (result.errorMessage?.includes("idle timeout")) return false;
|
|
185
|
+
if (getFinalOutput(result.messages)) return false;
|
|
186
|
+
if (result.messages.length > 0) return false;
|
|
187
|
+
const usage = result.usage;
|
|
188
|
+
if (usage.turns || usage.input || usage.output || usage.cacheRead || usage.cacheWrite || usage.cost) return false;
|
|
189
|
+
if (durationMs > MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS) return false;
|
|
190
|
+
if (result.stderr.trim().length > 0) return false;
|
|
191
|
+
if (result.errorMessage && result.errorMessage.trim().length > 0) return false;
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function formatStartupRetryExhaustedError(model: string, attempts: number): string {
|
|
196
|
+
return `Subagent failed to start after ${attempts} attempt${attempts === 1 ? "" : "s"} on ${model}: the child exited before any model, tool, output, or usage activity. This is typically a concurrent pi startup race (several sub-agents starting at once). Retry the dispatch, or temporarily lower maxConcurrency in /subagents-setup.`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function waitForStartupRetry(delayMs: number, signal?: AbortSignal): Promise<boolean> {
|
|
200
|
+
if (delayMs <= 0) return !signal?.aborted;
|
|
201
|
+
if (!signal) {
|
|
202
|
+
return new Promise<boolean>((resolve) => {
|
|
203
|
+
const timer = setTimeout(() => resolve(true), delayMs);
|
|
204
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
if (signal.aborted) return false;
|
|
208
|
+
return new Promise<boolean>((resolve) => {
|
|
209
|
+
let settled = false;
|
|
210
|
+
const finish = (shouldRetry: boolean): void => {
|
|
211
|
+
if (settled) return;
|
|
212
|
+
settled = true;
|
|
213
|
+
clearTimeout(timer);
|
|
214
|
+
signal.removeEventListener("abort", onAbort);
|
|
215
|
+
resolve(shouldRetry);
|
|
216
|
+
};
|
|
217
|
+
const onAbort = (): void => finish(false);
|
|
218
|
+
const timer = setTimeout(() => finish(true), delayMs);
|
|
219
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
220
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function waitForControlledRetry(
|
|
225
|
+
delayMs: number,
|
|
226
|
+
signal: AbortSignal | undefined,
|
|
227
|
+
control: RpcRunControl | undefined,
|
|
228
|
+
): Promise<boolean> {
|
|
229
|
+
let remaining = delayMs;
|
|
230
|
+
while (remaining > 0) {
|
|
231
|
+
if (control?.isParkRequested() || control?.isStopRequested()) return false;
|
|
232
|
+
const slice = Math.min(remaining, 50);
|
|
233
|
+
if (!(await waitForStartupRetry(slice, signal))) return false;
|
|
234
|
+
remaining -= slice;
|
|
235
|
+
}
|
|
236
|
+
return !signal?.aborted && !control?.isParkRequested() && !control?.isStopRequested();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function getResultOutput(result: SingleResult): string {
|
|
240
|
+
if (isFailedResult(result)) {
|
|
241
|
+
const error = result.errorMessage || result.stderr;
|
|
242
|
+
const partial = getFinalOutput(result.messages);
|
|
243
|
+
if (error && partial) return `${error}\n\n--- Partial output ---\n${partial}`;
|
|
244
|
+
return error || partial || "(no output)";
|
|
245
|
+
}
|
|
246
|
+
return getFinalOutput(result.messages) || "(no output)";
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export function buildResumePrompt(task: string, reason: string): string {
|
|
250
|
+
return `You are resuming an earlier sub-agent session after ${reason}. Your earlier work — searches, reads, edits, and reasoning — is preserved in this session's history above; review it before acting. Original task: ${task}. Pick up exactly where you left off and finish it. Do NOT redo searches, reads, or edits you already completed unless a step clearly failed. Continue now.`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function buildFallbackResumeReason(fromModel?: string): string {
|
|
254
|
+
return fromModel
|
|
255
|
+
? `the previous model (${fromModel}) failed at the model/provider level, so the next model in its configured pool is continuing`
|
|
256
|
+
: "the previous model failed at the model/provider level, so the next model in its configured pool is continuing";
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export interface RunSingleOptions {
|
|
260
|
+
defaultCwd: string;
|
|
261
|
+
agent: AgentConfig;
|
|
262
|
+
agentName: string;
|
|
263
|
+
task: string;
|
|
264
|
+
cwd?: string;
|
|
265
|
+
thinkingLevel?: ThinkingLevel;
|
|
266
|
+
idleTimeoutMs?: number;
|
|
267
|
+
startupRetryDelaysMs?: readonly number[];
|
|
268
|
+
runLevelRetryDelaysMs?: readonly number[];
|
|
269
|
+
sessionDir?: string;
|
|
270
|
+
sessionId?: string;
|
|
271
|
+
/** Initial RPC prompt. Kept under the old name to limit caller churn. */
|
|
272
|
+
stdinText?: string;
|
|
273
|
+
signal?: AbortSignal;
|
|
274
|
+
onLive?: (event: SubagentLiveEvent) => void;
|
|
275
|
+
makeDetails: (results: SingleResult[]) => SubagentDetails;
|
|
276
|
+
env?: NodeJS.ProcessEnv;
|
|
277
|
+
/** Stable logical-generation controller shared across retry attempts. */
|
|
278
|
+
control?: RpcRunControl;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function controlledDisposition(options: RunSingleOptions, base?: SingleResult): SingleResult | undefined {
|
|
282
|
+
const control = options.control;
|
|
283
|
+
if (!control?.isParkRequested() && !control?.isStopRequested()) return undefined;
|
|
284
|
+
const result: SingleResult = base ?? {
|
|
285
|
+
agent: options.agentName,
|
|
286
|
+
task: control.getObjective(),
|
|
287
|
+
exitCode: 0,
|
|
288
|
+
messages: [],
|
|
289
|
+
stderr: "",
|
|
290
|
+
usage: emptyUsage(),
|
|
291
|
+
model: options.agent.model,
|
|
292
|
+
thinking: options.thinkingLevel,
|
|
293
|
+
sessionId: options.sessionId,
|
|
294
|
+
sessionDir: options.sessionDir,
|
|
295
|
+
};
|
|
296
|
+
result.task = control.getObjective();
|
|
297
|
+
if (control.isParkRequested()) {
|
|
298
|
+
result.parked = true;
|
|
299
|
+
result.exitCode = 0;
|
|
300
|
+
result.stopReason = undefined;
|
|
301
|
+
result.errorMessage = undefined;
|
|
302
|
+
} else {
|
|
303
|
+
result.parked = undefined;
|
|
304
|
+
result.exitCode = 1;
|
|
305
|
+
result.stopReason = "aborted";
|
|
306
|
+
result.errorMessage = control.getStopMessage();
|
|
307
|
+
}
|
|
308
|
+
return result;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Spawn one RPC attempt and wait for stable settlement. */
|
|
312
|
+
export async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult> {
|
|
313
|
+
const {
|
|
314
|
+
agent,
|
|
315
|
+
agentName,
|
|
316
|
+
thinkingLevel = SUBAGENT_THINKING_LEVEL,
|
|
317
|
+
idleTimeoutMs = SUBAGENT_DEFAULT_IDLE_TIMEOUT_MS,
|
|
318
|
+
control,
|
|
319
|
+
} = options;
|
|
320
|
+
const disposition = controlledDisposition(options);
|
|
321
|
+
if (disposition) return disposition;
|
|
322
|
+
const objective = control?.getObjective() ?? options.task;
|
|
323
|
+
let prompt = options.stdinText ?? `Task: ${objective}`;
|
|
324
|
+
if (control && objective !== options.task) {
|
|
325
|
+
prompt = options.sessionDir && sessionExists(options.sessionDir, options.sessionId ?? "")
|
|
326
|
+
? `Abandon the previous objective. New objective: ${objective}`
|
|
327
|
+
: `Task: ${objective}`;
|
|
328
|
+
}
|
|
329
|
+
const result = await runRpcAgentAttempt({
|
|
330
|
+
defaultCwd: options.defaultCwd,
|
|
331
|
+
agent,
|
|
332
|
+
agentName,
|
|
333
|
+
task: objective,
|
|
334
|
+
cwd: options.cwd,
|
|
335
|
+
thinkingLevel,
|
|
336
|
+
idleTimeoutMs,
|
|
337
|
+
sessionDir: options.sessionDir,
|
|
338
|
+
sessionId: options.sessionId,
|
|
339
|
+
prompt,
|
|
340
|
+
signal: options.signal,
|
|
341
|
+
onLive: options.onLive,
|
|
342
|
+
env: options.env,
|
|
343
|
+
control,
|
|
344
|
+
});
|
|
345
|
+
result.task = control?.getObjective() ?? result.task;
|
|
346
|
+
return result;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Run one logical generation across an ordered model pool. Every candidate gets
|
|
351
|
+
* startup retries plus same-model retries for transient provider failures;
|
|
352
|
+
* terminal model errors skip those retries and advance immediately. All
|
|
353
|
+
* candidates resume the same retained pi session.
|
|
354
|
+
*/
|
|
355
|
+
export async function runSingleAgentWithModelFallback(
|
|
356
|
+
options: RunSingleOptions,
|
|
357
|
+
fallbackModelRefs: readonly string[] = [],
|
|
358
|
+
): Promise<SingleResult> {
|
|
359
|
+
const agent = options.agent;
|
|
360
|
+
const launchedRef = agent?.model;
|
|
361
|
+
const startupDelays = options.startupRetryDelaysMs ?? SUBAGENT_STARTUP_RETRY_DELAYS_MS;
|
|
362
|
+
const runDelays = options.runLevelRetryDelaysMs ?? SUBAGENT_RUN_LEVEL_RETRY_DELAYS_MS;
|
|
363
|
+
|
|
364
|
+
const sessionId = options.sessionId ?? randomUUID();
|
|
365
|
+
const sessionDir = options.sessionDir ?? (await mkdtemp(join(tmpdir(), "pi-subagent-session-")));
|
|
366
|
+
const baseOptions: RunSingleOptions = { ...options, sessionDir, sessionId };
|
|
367
|
+
|
|
368
|
+
const dispatchFailure = async (error: unknown): Promise<SingleResult> => {
|
|
369
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
370
|
+
const hasSession = sessionExists(sessionDir, sessionId);
|
|
371
|
+
if (!hasSession && !options.sessionDir) {
|
|
372
|
+
await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
|
|
373
|
+
}
|
|
374
|
+
return {
|
|
375
|
+
agent: options.agentName,
|
|
376
|
+
task: options.control?.getObjective() ?? options.task,
|
|
377
|
+
exitCode: 1,
|
|
378
|
+
messages: [],
|
|
379
|
+
stderr: errorMessage,
|
|
380
|
+
usage: emptyUsage(),
|
|
381
|
+
model: options.agent.model,
|
|
382
|
+
thinking: options.thinkingLevel,
|
|
383
|
+
stopReason: "error",
|
|
384
|
+
errorMessage,
|
|
385
|
+
dispatchFailed: true,
|
|
386
|
+
...(hasSession || options.sessionDir ? { sessionId, sessionDir } : {}),
|
|
387
|
+
};
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
const runWithStartupRetry = async (opts: RunSingleOptions): Promise<SingleResult> => {
|
|
391
|
+
let lastResult: SingleResult;
|
|
392
|
+
let retries = 0;
|
|
393
|
+
for (let attempt = 0; ; attempt++) {
|
|
394
|
+
const immediate = controlledDisposition(opts);
|
|
395
|
+
if (immediate) {
|
|
396
|
+
if (immediate.parked && !options.sessionDir && !sessionExists(sessionDir, sessionId)) {
|
|
397
|
+
await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
|
|
398
|
+
immediate.sessionId = undefined;
|
|
399
|
+
immediate.sessionDir = undefined;
|
|
400
|
+
}
|
|
401
|
+
return immediate;
|
|
402
|
+
}
|
|
403
|
+
const start = Date.now();
|
|
404
|
+
try {
|
|
405
|
+
lastResult = await runSingleAgent(opts);
|
|
406
|
+
} catch (error) {
|
|
407
|
+
const failed = await dispatchFailure(error);
|
|
408
|
+
return controlledDisposition(opts, failed) ?? failed;
|
|
409
|
+
}
|
|
410
|
+
const durationMs = Date.now() - start;
|
|
411
|
+
const controlled = controlledDisposition(opts, lastResult);
|
|
412
|
+
if (controlled) return controlled;
|
|
413
|
+
if (lastResult.parked || lastResult.stopReason === "aborted") return lastResult;
|
|
414
|
+
if (!isRetryableStartupFailure(lastResult, durationMs)) {
|
|
415
|
+
if (retries > 0 && !isFailedResult(lastResult)) lastResult.startupRetries = retries;
|
|
416
|
+
return lastResult;
|
|
417
|
+
}
|
|
418
|
+
const delay = startupDelays[attempt];
|
|
419
|
+
if (delay === undefined) {
|
|
420
|
+
lastResult.errorMessage = formatStartupRetryExhaustedError(
|
|
421
|
+
lastResult.model ?? opts.agent.model ?? "default",
|
|
422
|
+
attempt + 1,
|
|
423
|
+
);
|
|
424
|
+
lastResult.stopReason ??= "error";
|
|
425
|
+
lastResult.dispatchFailed = true;
|
|
426
|
+
return lastResult;
|
|
427
|
+
}
|
|
428
|
+
opts.control?.markRetrying();
|
|
429
|
+
try {
|
|
430
|
+
opts.onLive?.({ kind: "status", status: "running" });
|
|
431
|
+
} catch {
|
|
432
|
+
/* never throw from event handling */
|
|
433
|
+
}
|
|
434
|
+
if (!(await waitForControlledRetry(delay, opts.signal, opts.control))) {
|
|
435
|
+
return controlledDisposition(opts, lastResult) ?? lastResult;
|
|
436
|
+
}
|
|
437
|
+
retries++;
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
const fallbackRefs: string[] = [];
|
|
442
|
+
const seenRefs = new Set<string>();
|
|
443
|
+
if (launchedRef?.trim()) seenRefs.add(launchedRef.trim());
|
|
444
|
+
for (const candidate of fallbackModelRefs) {
|
|
445
|
+
const ref = candidate.trim();
|
|
446
|
+
if (!ref || seenRefs.has(ref)) continue;
|
|
447
|
+
seenRefs.add(ref);
|
|
448
|
+
fallbackRefs.push(ref);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const candidates: Array<{ agent: AgentConfig; ref?: string }> = [
|
|
452
|
+
{ agent, ref: launchedRef?.trim() || undefined },
|
|
453
|
+
];
|
|
454
|
+
for (const ref of fallbackRefs) candidates.push({ agent: { ...agent, model: ref }, ref });
|
|
455
|
+
|
|
456
|
+
let modelRetries = 0;
|
|
457
|
+
let fallbackUsed = false;
|
|
458
|
+
let result: SingleResult | undefined;
|
|
459
|
+
|
|
460
|
+
const finish = async (settled: SingleResult): Promise<SingleResult> => {
|
|
461
|
+
const persistedSession = sessionExists(sessionDir, sessionId);
|
|
462
|
+
if (!settled.dispatchFailed || persistedSession || options.sessionDir) {
|
|
463
|
+
settled.sessionId ??= sessionId;
|
|
464
|
+
settled.sessionDir ??= sessionDir;
|
|
465
|
+
} else {
|
|
466
|
+
await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
|
|
467
|
+
settled.sessionId = undefined;
|
|
468
|
+
settled.sessionDir = undefined;
|
|
469
|
+
}
|
|
470
|
+
settled.task = options.control?.getObjective() ?? settled.task;
|
|
471
|
+
if (fallbackUsed && launchedRef) settled.modelFallbackFrom = launchedRef;
|
|
472
|
+
settled.modelRetries = modelRetries;
|
|
473
|
+
options.control?.markSettled();
|
|
474
|
+
return settled;
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
|
|
478
|
+
const candidate = candidates[candidateIndex];
|
|
479
|
+
fallbackUsed ||= candidateIndex > 0;
|
|
480
|
+
const previousModel = result?.model ?? candidates[candidateIndex - 1]?.ref;
|
|
481
|
+
const candidateOptions: RunSingleOptions = {
|
|
482
|
+
...baseOptions,
|
|
483
|
+
agent: candidate.agent,
|
|
484
|
+
...(candidateIndex > 0
|
|
485
|
+
? {
|
|
486
|
+
stdinText: buildResumePrompt(
|
|
487
|
+
options.control?.getObjective() ?? options.task,
|
|
488
|
+
buildFallbackResumeReason(previousModel),
|
|
489
|
+
),
|
|
490
|
+
}
|
|
491
|
+
: {}),
|
|
492
|
+
};
|
|
493
|
+
try {
|
|
494
|
+
options.onLive?.({
|
|
495
|
+
kind: "model",
|
|
496
|
+
model: candidate.ref,
|
|
497
|
+
...(candidateIndex > 0 && launchedRef ? { fallbackFrom: launchedRef } : {}),
|
|
498
|
+
});
|
|
499
|
+
} catch {
|
|
500
|
+
/* never throw from event handling */
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
result = await runWithStartupRetry(candidateOptions);
|
|
504
|
+
if (result.parked || result.stopReason === "aborted") return result;
|
|
505
|
+
if (!isModelLevelFailure(result)) return finish(result);
|
|
506
|
+
|
|
507
|
+
if (!isTerminalModelError(result) && !isPermanentModelCandidateError(result)) {
|
|
508
|
+
const retryOptions: RunSingleOptions = {
|
|
509
|
+
...candidateOptions,
|
|
510
|
+
stdinText: buildResumePrompt(
|
|
511
|
+
options.control?.getObjective() ?? options.task,
|
|
512
|
+
"a transient provider error on the same model",
|
|
513
|
+
),
|
|
514
|
+
};
|
|
515
|
+
for (const delay of runDelays) {
|
|
516
|
+
baseOptions.control?.markRetrying();
|
|
517
|
+
try {
|
|
518
|
+
options.onLive?.({ kind: "status", status: "running" });
|
|
519
|
+
} catch {
|
|
520
|
+
/* never throw from event handling */
|
|
521
|
+
}
|
|
522
|
+
if (!(await waitForControlledRetry(delay, options.signal, options.control))) {
|
|
523
|
+
return controlledDisposition(baseOptions, result) ?? result;
|
|
524
|
+
}
|
|
525
|
+
result = await runWithStartupRetry(retryOptions);
|
|
526
|
+
modelRetries++;
|
|
527
|
+
if (result.parked || result.stopReason === "aborted") return result;
|
|
528
|
+
if (
|
|
529
|
+
!isModelLevelFailure(result) ||
|
|
530
|
+
isTerminalModelError(result) ||
|
|
531
|
+
isPermanentModelCandidateError(result)
|
|
532
|
+
) break;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
if (!isModelLevelFailure(result)) return finish(result);
|
|
537
|
+
// Transient exhaustion plus terminal/permanent candidate errors advance
|
|
538
|
+
// to the next configured candidate. Ordinary task/tool failures returned above.
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
return finish(result!);
|
|
542
|
+
}
|