@ashx-j/lunr-dev 0.2.40-dev.55.1 → 0.2.40-dev.58.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/dist/builtin-extensions/pi-subagents/src/runs/background/attempt-usage.d.ts +5 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/attempt-usage.js +31 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/child-stream.d.ts +65 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/child-stream.js +456 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/parallel-group-status.d.ts +42 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/parallel-group-status.js +79 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/run-log.d.ts +18 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/run-log.js +43 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-event-log.d.ts +3 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-event-log.js +70 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-single-step.d.ts +92 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-single-step.js +491 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-status.d.ts +64 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/runner-status.js +26 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts +1 -115
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +17 -1160
- package/dist/core/credential-files.d.ts +3 -2
- package/dist/core/credential-files.js +10 -4
- package/dist/core/permissions.d.ts +6 -0
- package/dist/core/permissions.js +6 -0
- package/dist/core/tool-call-hooks.js +3 -2
- package/dist/node-runtime/{acp-mode-CFYSYACH.js → acp-mode-5KZPFZBO.js} +2 -2
- package/dist/node-runtime/{agent-session-services-3ZHQJIKF.js → agent-session-services-KH5CIGC3.js} +5 -5
- package/dist/node-runtime/{builtin-extensions-YJ7F6GND.js → builtin-extensions-RZS4SMIS.js} +3 -3
- package/dist/node-runtime/{chunk-5HVA5ECB.js → chunk-AKQRASEH.js} +9 -9
- package/dist/node-runtime/{chunk-4ZEDT3YW.js → chunk-BJXBM6KD.js} +3 -3
- package/dist/node-runtime/{chunk-BNNBTBXY.js → chunk-EJMB4PAV.js} +3 -3
- package/dist/node-runtime/{chunk-HVXDYQNN.js → chunk-JI7AUY2T.js} +1 -1
- package/dist/node-runtime/{chunk-ITVBE3HR.js → chunk-JJTHGEUS.js} +5 -4
- package/dist/node-runtime/{chunk-3UQ7ZNLI.js → chunk-K24P7GMM.js} +7 -7
- package/dist/node-runtime/{chunk-KTCZH72R.js → chunk-LGRRFSE7.js} +3 -2
- package/dist/node-runtime/{chunk-7LCR56AK.js → chunk-NWYFKXP5.js} +1 -1
- package/dist/node-runtime/{chunk-SV42POA3.js → chunk-PGWSMQ4K.js} +1 -1
- package/dist/node-runtime/{chunk-YDMZHLBV.js → chunk-QX5I7QEW.js} +1 -1
- package/dist/node-runtime/{chunk-BNZXW77G.js → chunk-RXDLSXEC.js} +1 -1
- package/dist/node-runtime/{chunk-N574FRFF.js → chunk-TSZESZ6H.js} +2 -2
- package/dist/node-runtime/{chunk-CDILDA4F.js → chunk-U7MTVVT3.js} +2 -2
- package/dist/node-runtime/{chunk-G3PARFR4.js → chunk-UTZCCNFC.js} +5 -5
- package/dist/node-runtime/{chunk-U2LTTIWZ.js → chunk-WYJUGRVE.js} +1 -1
- package/dist/node-runtime/{chunk-7LNPTBQJ.js → chunk-XPKOWSYN.js} +6 -2
- package/dist/node-runtime/{chunk-2ZI6Q6JG.js → chunk-YFXGOLZ6.js} +1 -1
- package/dist/node-runtime/{command-H52R5R2G.js → command-6S6C62CX.js} +1 -1
- package/dist/node-runtime/{commands-7EETGZ7V.js → commands-GSZWAQJW.js} +5 -5
- package/dist/node-runtime/{commands-CV2JUYHM.js → commands-MM2TPV5I.js} +4 -4
- package/dist/node-runtime/{direct-tool-executor-DNZ2MS6Z.js → direct-tool-executor-WJLVHH7U.js} +6 -6
- package/dist/node-runtime/{gateway-OHPDCOOB.js → gateway-CWIWPUVC.js} +6 -6
- package/dist/node-runtime/index.js +10 -10
- package/dist/node-runtime/{init-G23PFPKF.js → init-P3RQ6EFK.js} +5 -5
- package/dist/node-runtime/{interactive-mode-7GX3UJFX.js → interactive-mode-2L5JMVKQ.js} +6 -6
- package/dist/node-runtime/{lunr-cron-SV2EXYKV.js → lunr-cron-LT3O64NO.js} +4 -4
- package/dist/node-runtime/main.js +7 -7
- package/dist/node-runtime/{mobile-commands-JQJU35OT.js → mobile-commands-PFXEWP2R.js} +3 -3
- package/dist/node-runtime/{pi-mcp-adapter-NKAL5CFR.js → pi-mcp-adapter-2OP5BBC6.js} +8 -8
- package/dist/node-runtime/{pi-subagents-WS6OU5MG.js → pi-subagents-G2T5XRAX.js} +6 -6
- package/dist/node-runtime/{print-mode-Y363FXY4.js → print-mode-S6ZUVPMU.js} +6 -6
- package/dist/node-runtime/{proxy-modes-EEYRUGQL.js → proxy-modes-RD2PQ6UH.js} +6 -6
- package/dist/node-runtime/rpc-entry.js +7 -7
- package/dist/node-runtime/{rpc-mode-ENVT7AXW.js → rpc-mode-C33WERBG.js} +3 -3
- package/dist/node-runtime/{src-Y3S2FIS5.js → src-J6FSKIFT.js} +1 -1
- package/dist/node-runtime/{subagent-executor-LPVOWPMG.js → subagent-executor-RTGKJ35C.js} +5 -5
- package/install-lock/package-lock.json +24 -24
- package/install-lock/package.json +2 -2
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1,1180 +1,37 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
1
|
import * as fs from "node:fs";
|
|
3
2
|
import * as path from "node:path";
|
|
4
3
|
import { fileURLToPath } from "node:url";
|
|
5
4
|
import { writeAtomicJson } from "../../shared/atomic-json.js";
|
|
6
|
-
import { createChildTranscriptWriter } from "../../shared/child-transcript.js";
|
|
7
5
|
import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, enqueueStepSteer, steerAcksDir, steerCapabilityPath, stepSteerInboxDir, watchAsyncControlInbox } from "./control-channel.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, injectSingleOutputInstruction, resolveSingleOutput } from "../shared/single-output.js";
|
|
11
|
-
import { DEFAULT_MAX_OUTPUT, SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, truncateOutput, getSubagentDepthEnv, } from "../../shared/types.js";
|
|
6
|
+
import { injectOutputPathSystemPrompt, injectSingleOutputInstruction } from "../shared/single-output.js";
|
|
7
|
+
import { DEFAULT_MAX_OUTPUT, SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, truncateOutput, } from "../../shared/types.js";
|
|
12
8
|
import { DEFAULT_CONTROL_CONFIG, buildControlEvent, deriveActivityState, claimControlNotification, formatControlIntercomMessage, formatControlNoticeMessage, } from "../shared/subagent-control.js";
|
|
13
9
|
import { isDynamicRunnerGroup, isParallelGroup, flattenSteps, mapConcurrent, aggregateParallelOutputs, MAX_PARALLEL_CONCURRENCY, DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore, } from "../shared/parallel-utils.js";
|
|
14
|
-
import { applyThinkingSuffix
|
|
15
|
-
import {
|
|
16
|
-
import { resolveChildExcludeTools } from "../shared/child-tools.js";
|
|
17
|
-
import { outputEntryFromAsyncResult, resolveOutputReferences, withChainHandoff } from "../shared/chain-outputs.js";
|
|
18
|
-
import { createStructuredOutputRuntime, readStructuredOutput } from "../shared/structured-output.js";
|
|
19
|
-
import { readChildToolDiagnosticError } from "../shared/tool-availability.js";
|
|
10
|
+
import { applyThinkingSuffix } from "../shared/pi-args.js";
|
|
11
|
+
import { outputEntryFromAsyncResult } from "../shared/chain-outputs.js";
|
|
20
12
|
import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.js";
|
|
21
13
|
import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.js";
|
|
22
|
-
import { formatModelAttemptNote, isRetryableModelFailure } from "../shared/model-fallback.js";
|
|
23
14
|
import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, updateSteeringTarget } from "./steering.js";
|
|
24
|
-
import {
|
|
25
|
-
import { detectSubagentError, extractTextFromContent, extractToolArgsPreview, getFinalOutput, readStatus } from "../../shared/utils.js";
|
|
26
|
-
import { evaluateCompletionMutationGuard } from "../shared/completion-guard.js";
|
|
15
|
+
import { extractTextFromContent, extractToolArgsPreview } from "../../shared/utils.js";
|
|
27
16
|
import { createMutatingFailureState, didMutatingToolFail, isMutatingTool, nextLongRunningTrigger, recordMutatingFailure, resetMutatingFailureState, resolveCurrentPath, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
|
|
28
|
-
import {
|
|
29
|
-
import { cleanupWorktrees, createWorktrees, diffWorktrees, findWorktreeTaskCwdConflict, formatWorktreeDiffSummary, formatWorktreeTaskCwdConflict, } from "../shared/worktree.js";
|
|
17
|
+
import { cleanupWorktrees, createWorktrees, findWorktreeTaskCwdConflict, formatWorktreeTaskCwdConflict, } from "../shared/worktree.js";
|
|
30
18
|
import { resolveEffectiveThinking } from "../../shared/model-info.js";
|
|
31
|
-
import { writeInitialProgressFile } from "../../shared/settings.js";
|
|
32
19
|
import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
|
|
33
|
-
import { acceptanceFailureMessage, aggregateAcceptanceReport,
|
|
34
|
-
import { waitForImportedAsyncRoot } from "./chain-root-attachment.js";
|
|
20
|
+
import { acceptanceFailureMessage, aggregateAcceptanceReport, evaluateAcceptance, resolveEffectiveAcceptance, stripAcceptanceReport } from "../shared/acceptance.js";
|
|
35
21
|
import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests } from "./chain-append.js";
|
|
36
|
-
import {
|
|
22
|
+
import { initialTurnBudgetState, shouldAbortForTurnBudget, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.js";
|
|
37
23
|
import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.js";
|
|
38
|
-
import { resolveWatchdogConfig } from "../../watchdog/settings.js";
|
|
39
|
-
import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, projectChildLifecycle } from "../shared/child-protocol.js";
|
|
40
|
-
import { createChildEventDecoder } from "../../../../../core/subagent-event-transport.js";
|
|
41
24
|
import { acquireSessionLease } from "../shared/session-lease.js";
|
|
42
|
-
import {
|
|
25
|
+
import { acceptChildWatchdogEvent, isChildWatchdogStatusEvent, } from "../../watchdog/child-status.js";
|
|
26
|
+
import { tokenUsageFromAttempts, emptyUsage } from "./attempt-usage.js";
|
|
27
|
+
import { isTerminalAssistantStop } from "./child-stream.js";
|
|
28
|
+
import { markParallelGroupSetupFailure, ensureParallelProgressFile, markParallelGroupRunning, prepareParallelTaskRun, appendParallelWorktreeSummary } from "./parallel-group-status.js";
|
|
29
|
+
import { writeRunLog } from "./run-log.js";
|
|
30
|
+
import { appendJsonl } from "./runner-event-log.js";
|
|
31
|
+
import { runSingleStep, combinedAbortSignal } from "./runner-single-step.js";
|
|
32
|
+
import { resolveAsyncStepTranscriptPath, appendRecentStepOutput, resetStepLiveDetail } from "./runner-status.js";
|
|
33
|
+
export { runSingleStep } from "./runner-single-step.js";
|
|
43
34
|
const ASYNC_INTERRUPT_SIGNAL = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
|
|
44
|
-
const DEFAULT_MAX_ASYNC_EVENTS_BYTES = 50 * 1024 * 1024;
|
|
45
|
-
const ASYNC_EVENTS_MAX_BYTES_ENV = "PI_SUBAGENT_ASYNC_EVENTS_MAX_BYTES";
|
|
46
|
-
const TRUNCATED_EVENT_TYPE = "subagent.events.truncated";
|
|
47
|
-
const TRUNCATION_MARKER_RESERVE_BYTES = 512;
|
|
48
|
-
const asyncEventLogStates = new Map();
|
|
49
|
-
function maxAsyncEventsBytes() {
|
|
50
|
-
const raw = process.env[ASYNC_EVENTS_MAX_BYTES_ENV];
|
|
51
|
-
if (!raw)
|
|
52
|
-
return DEFAULT_MAX_ASYNC_EVENTS_BYTES;
|
|
53
|
-
const parsed = Number(raw);
|
|
54
|
-
if (!Number.isFinite(parsed) || parsed < 0)
|
|
55
|
-
return DEFAULT_MAX_ASYNC_EVENTS_BYTES;
|
|
56
|
-
return Math.floor(parsed);
|
|
57
|
-
}
|
|
58
|
-
function eventLogState(filePath) {
|
|
59
|
-
let state = asyncEventLogStates.get(filePath);
|
|
60
|
-
if (state)
|
|
61
|
-
return state;
|
|
62
|
-
let bytes = 0;
|
|
63
|
-
try {
|
|
64
|
-
bytes = fs.statSync(filePath).size;
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
if (error.code !== "ENOENT") {
|
|
68
|
-
// Diagnostic event accounting is best-effort; writes below are also safe.
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
state = { bytes, diagnosticsTruncated: false };
|
|
72
|
-
asyncEventLogStates.set(filePath, state);
|
|
73
|
-
return state;
|
|
74
|
-
}
|
|
75
|
-
function appendJsonl(filePath, line) {
|
|
76
|
-
try {
|
|
77
|
-
appendRawJsonl(filePath, line);
|
|
78
|
-
const state = asyncEventLogStates.get(filePath);
|
|
79
|
-
if (state)
|
|
80
|
-
state.bytes += Buffer.byteLength(`${line}\n`, "utf-8");
|
|
81
|
-
}
|
|
82
|
-
catch {
|
|
83
|
-
// Async event logging is diagnostic and must not fail the run.
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
function appendDiagnosticJsonl(filePath, line, droppedEventType) {
|
|
87
|
-
if (!line.trim())
|
|
88
|
-
return;
|
|
89
|
-
const state = eventLogState(filePath);
|
|
90
|
-
if (state.diagnosticsTruncated)
|
|
91
|
-
return;
|
|
92
|
-
const maxBytes = maxAsyncEventsBytes();
|
|
93
|
-
const chunkBytes = Buffer.byteLength(`${line}\n`, "utf-8");
|
|
94
|
-
const diagnosticBudget = Math.max(0, maxBytes - TRUNCATION_MARKER_RESERVE_BYTES);
|
|
95
|
-
if (state.bytes + chunkBytes <= diagnosticBudget) {
|
|
96
|
-
appendJsonl(filePath, line);
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
|
-
const marker = JSON.stringify({
|
|
100
|
-
type: TRUNCATED_EVENT_TYPE,
|
|
101
|
-
ts: Date.now(),
|
|
102
|
-
maxBytes,
|
|
103
|
-
droppedEventType,
|
|
104
|
-
});
|
|
105
|
-
if (state.bytes + Buffer.byteLength(`${marker}\n`, "utf-8") <= maxBytes) {
|
|
106
|
-
appendJsonl(filePath, marker);
|
|
107
|
-
}
|
|
108
|
-
state.diagnosticsTruncated = true;
|
|
109
|
-
}
|
|
110
|
-
function shouldPersistChildEvent(event) {
|
|
111
|
-
return event.type !== "message_update";
|
|
112
|
-
}
|
|
113
|
-
function findLatestSessionFile(sessionDir) {
|
|
114
|
-
try {
|
|
115
|
-
const files = fs
|
|
116
|
-
.readdirSync(sessionDir)
|
|
117
|
-
.filter((f) => f.endsWith(".jsonl"))
|
|
118
|
-
.map((f) => path.join(sessionDir, f));
|
|
119
|
-
if (files.length === 0)
|
|
120
|
-
return null;
|
|
121
|
-
files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs || b.localeCompare(a));
|
|
122
|
-
return files[0] ?? null;
|
|
123
|
-
}
|
|
124
|
-
catch {
|
|
125
|
-
// Session lookup is optional metadata.
|
|
126
|
-
return null;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
function emptyUsage() {
|
|
130
|
-
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0, unknownRequests: 0, partialRequests: 0, unknownCosts: 0 };
|
|
131
|
-
}
|
|
132
|
-
function tokenUsageFromAttempts(attempts) {
|
|
133
|
-
if (!attempts?.some((attempt) => attempt.usage))
|
|
134
|
-
return null;
|
|
135
|
-
const usage = emptyUsage();
|
|
136
|
-
for (const attempt of attempts)
|
|
137
|
-
if (attempt.usage) {
|
|
138
|
-
for (const key of Object.keys(usage))
|
|
139
|
-
usage[key] += attempt.usage[key] ?? 0;
|
|
140
|
-
}
|
|
141
|
-
return tokenUsageFromUsage(usage);
|
|
142
|
-
}
|
|
143
|
-
function costSummaryFromAttempts(attempts) {
|
|
144
|
-
if (!attempts || attempts.length === 0)
|
|
145
|
-
return undefined;
|
|
146
|
-
let inputTokens = 0;
|
|
147
|
-
let outputTokens = 0;
|
|
148
|
-
let costUsd = 0;
|
|
149
|
-
for (const attempt of attempts) {
|
|
150
|
-
inputTokens += (attempt.usage?.input ?? 0) + (attempt.usage?.cacheRead ?? 0) + (attempt.usage?.cacheWrite ?? 0);
|
|
151
|
-
outputTokens += attempt.usage?.output ?? 0;
|
|
152
|
-
costUsd += attempt.usage?.cost ?? 0;
|
|
153
|
-
}
|
|
154
|
-
return inputTokens > 0 || outputTokens > 0 || costUsd > 0
|
|
155
|
-
? { inputTokens, outputTokens, costUsd }
|
|
156
|
-
: undefined;
|
|
157
|
-
}
|
|
158
|
-
function appendRecentStepOutput(step, lines) {
|
|
159
|
-
const nonEmpty = lines.filter((line) => line.trim());
|
|
160
|
-
if (nonEmpty.length === 0)
|
|
161
|
-
return;
|
|
162
|
-
step.recentOutput ??= [];
|
|
163
|
-
step.recentOutput.push(...nonEmpty);
|
|
164
|
-
if (step.recentOutput.length > 50) {
|
|
165
|
-
step.recentOutput.splice(0, step.recentOutput.length - 50);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
function isTerminalAssistantStop(message) {
|
|
169
|
-
const stopReason = message.stopReason;
|
|
170
|
-
const hasToolCall = Array.isArray(message.content)
|
|
171
|
-
&& message.content.some((part) => part.type === "toolCall");
|
|
172
|
-
return stopReason === "stop" && !hasToolCall;
|
|
173
|
-
}
|
|
174
|
-
function resetStepLiveDetail(step) {
|
|
175
|
-
step.currentTool = undefined;
|
|
176
|
-
step.currentToolArgs = undefined;
|
|
177
|
-
step.currentToolStartedAt = undefined;
|
|
178
|
-
step.currentPath = undefined;
|
|
179
|
-
step.recentTools = [];
|
|
180
|
-
step.recentOutput = [];
|
|
181
|
-
}
|
|
182
|
-
function runPiStreaming(args, cwd, outputFile, env, piPackageRoot, piArgv1, maxSubagentDepth, childEventContext, registerInterrupt, onChildEvent, transcriptWriter, registerTimeout, timeoutMessage, registerStop, stopMessage, registerTurnBudgetAbort, onWriterProcess) {
|
|
183
|
-
return new Promise((resolve) => {
|
|
184
|
-
onWriterProcess?.({ state: "spawning" });
|
|
185
|
-
const outputStream = fs.createWriteStream(outputFile, { flags: "w" });
|
|
186
|
-
const spawnEnv = { ...process.env, ...(env ?? {}), ...getSubagentDepthEnv(maxSubagentDepth) };
|
|
187
|
-
const spawnSpec = getPiSpawnCommand(args, {
|
|
188
|
-
...(piPackageRoot ? { piPackageRoot } : {}),
|
|
189
|
-
...(piArgv1 ? { argv1: piArgv1 } : {}),
|
|
190
|
-
});
|
|
191
|
-
const child = spawn(spawnSpec.command, spawnSpec.args, {
|
|
192
|
-
cwd,
|
|
193
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
194
|
-
env: spawnEnv,
|
|
195
|
-
windowsHide: true,
|
|
196
|
-
});
|
|
197
|
-
const stderrTail = createBoundedByteTail();
|
|
198
|
-
const rawStdoutTail = createBoundedByteTail();
|
|
199
|
-
const messages = [];
|
|
200
|
-
const usage = emptyUsage();
|
|
201
|
-
let model;
|
|
202
|
-
let writerRegistrationError;
|
|
203
|
-
if (typeof child.pid === "number") {
|
|
204
|
-
try {
|
|
205
|
-
onWriterProcess?.({ state: "running", pid: child.pid });
|
|
206
|
-
}
|
|
207
|
-
catch (writerError) {
|
|
208
|
-
writerRegistrationError = `Failed to record revived Pi writer ownership: ${writerError instanceof Error ? writerError.message : String(writerError)}`;
|
|
209
|
-
trySignalChild(child, "SIGKILL");
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
let error = writerRegistrationError;
|
|
213
|
-
let assistantError;
|
|
214
|
-
let interrupted = false;
|
|
215
|
-
let timedOut = false;
|
|
216
|
-
let stopped = false;
|
|
217
|
-
let turnBudgetExceeded = false;
|
|
218
|
-
let turnBudgetMessage;
|
|
219
|
-
let turnBudget;
|
|
220
|
-
let observedMutationAttempt = false;
|
|
221
|
-
const childWatchdogConfig = decodeChildWatchdogConfig(env?.[CHILD_WATCHDOG_CONFIG_ENV]);
|
|
222
|
-
let childWatchdogState;
|
|
223
|
-
let applyChildLifecycle = (_action) => { };
|
|
224
|
-
const updateChildWatchdogState = (snapshot) => {
|
|
225
|
-
childWatchdogState = snapshot;
|
|
226
|
-
};
|
|
227
|
-
const writeOutputLine = (line) => {
|
|
228
|
-
if (!line.trim())
|
|
229
|
-
return;
|
|
230
|
-
outputStream.write(`${line}\n`);
|
|
231
|
-
};
|
|
232
|
-
const writeOutputText = (text) => {
|
|
233
|
-
for (const line of text.split("\n")) {
|
|
234
|
-
writeOutputLine(line);
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
const appendChildEvent = (event) => {
|
|
238
|
-
if (!childEventContext)
|
|
239
|
-
return;
|
|
240
|
-
if (!shouldPersistChildEvent(event))
|
|
241
|
-
return;
|
|
242
|
-
appendDiagnosticJsonl(childEventContext.eventsPath, JSON.stringify({
|
|
243
|
-
...event,
|
|
244
|
-
subagentSource: "child",
|
|
245
|
-
subagentRunId: childEventContext.runId,
|
|
246
|
-
subagentStepIndex: childEventContext.stepIndex,
|
|
247
|
-
subagentAgent: childEventContext.agent,
|
|
248
|
-
observedAt: Date.now(),
|
|
249
|
-
}), typeof event.type === "string" ? event.type : undefined);
|
|
250
|
-
};
|
|
251
|
-
const appendChildLine = (type, line) => {
|
|
252
|
-
appendChildEvent({ type, line });
|
|
253
|
-
if (type === "subagent.child.stdout")
|
|
254
|
-
transcriptWriter?.writeStdoutLine(line);
|
|
255
|
-
else
|
|
256
|
-
transcriptWriter?.writeStderrLine(line);
|
|
257
|
-
};
|
|
258
|
-
const decodeChildEvent = createChildEventDecoder();
|
|
259
|
-
const processStdoutLine = (line) => {
|
|
260
|
-
if (!line.trim())
|
|
261
|
-
return;
|
|
262
|
-
let event;
|
|
263
|
-
try {
|
|
264
|
-
const assembled = decodeChildEvent(line);
|
|
265
|
-
if (assembled === undefined)
|
|
266
|
-
return;
|
|
267
|
-
event = JSON.parse(assembled);
|
|
268
|
-
}
|
|
269
|
-
catch {
|
|
270
|
-
rawStdoutTail.push(`${line}\n`);
|
|
271
|
-
writeOutputLine(line);
|
|
272
|
-
appendChildLine("subagent.child.stdout", line);
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
appendChildEvent(event);
|
|
276
|
-
transcriptWriter?.writeChildEvent(event);
|
|
277
|
-
if (event.type === "agent_settled")
|
|
278
|
-
agentSettledReceived = true;
|
|
279
|
-
applyChildLifecycle(projectChildLifecycle(event));
|
|
280
|
-
if (isChildWatchdogStatusEvent(event)) {
|
|
281
|
-
if (!childWatchdogConfig)
|
|
282
|
-
return;
|
|
283
|
-
const next = acceptChildWatchdogEvent({
|
|
284
|
-
current: childWatchdogState,
|
|
285
|
-
event,
|
|
286
|
-
runId: childEventContext?.runId,
|
|
287
|
-
agent: childEventContext?.agent,
|
|
288
|
-
childIndex: childEventContext?.stepIndex,
|
|
289
|
-
});
|
|
290
|
-
if (!next)
|
|
291
|
-
return;
|
|
292
|
-
updateChildWatchdogState(next);
|
|
293
|
-
onChildEvent?.(event);
|
|
294
|
-
if (childWatchdogIsActive(next)) {
|
|
295
|
-
if (finalDrainTimer) {
|
|
296
|
-
clearTimeout(finalDrainTimer);
|
|
297
|
-
finalDrainTimer = undefined;
|
|
298
|
-
}
|
|
299
|
-
if (finalHardKillTimer) {
|
|
300
|
-
clearTimeout(finalHardKillTimer);
|
|
301
|
-
finalHardKillTimer = undefined;
|
|
302
|
-
}
|
|
303
|
-
armWatchdogTail();
|
|
304
|
-
}
|
|
305
|
-
else {
|
|
306
|
-
clearWatchdogTailTimer();
|
|
307
|
-
if (cleanTerminalAssistantStopReceived || agentSettledReceived)
|
|
308
|
-
startFinalDrain();
|
|
309
|
-
}
|
|
310
|
-
return;
|
|
311
|
-
}
|
|
312
|
-
onChildEvent?.(event);
|
|
313
|
-
if (event.type === "tool_execution_start" && event.toolName) {
|
|
314
|
-
observedMutationAttempt = observedMutationAttempt || isMutatingTool(event.toolName, event.args);
|
|
315
|
-
const toolArgs = extractToolArgsPreview(event.args ?? {});
|
|
316
|
-
writeOutputLine(toolArgs ? `${event.toolName}: ${toolArgs}` : event.toolName);
|
|
317
|
-
return;
|
|
318
|
-
}
|
|
319
|
-
if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
|
|
320
|
-
messages.push(event.message);
|
|
321
|
-
const text = extractTextFromContent(event.message.content);
|
|
322
|
-
if (text)
|
|
323
|
-
writeOutputText(text);
|
|
324
|
-
if (event.type !== "message_end" || event.message.role !== "assistant")
|
|
325
|
-
return;
|
|
326
|
-
if (event.message.model)
|
|
327
|
-
model = event.message.model;
|
|
328
|
-
if (event.message.errorMessage)
|
|
329
|
-
assistantError = event.message.errorMessage;
|
|
330
|
-
const eventUsage = event.message.usage;
|
|
331
|
-
if (eventUsage) {
|
|
332
|
-
usage.turns++;
|
|
333
|
-
usage.input += eventUsage.input ?? eventUsage.inputTokens ?? 0;
|
|
334
|
-
usage.output += eventUsage.output ?? eventUsage.outputTokens ?? 0;
|
|
335
|
-
usage.cacheRead += eventUsage.cacheRead ?? 0;
|
|
336
|
-
usage.cacheWrite += eventUsage.cacheWrite ?? 0;
|
|
337
|
-
usage.cost += eventUsage.cost?.total ?? 0;
|
|
338
|
-
usage.unknownRequests += Number(eventUsage.measurement === "unknown");
|
|
339
|
-
usage.partialRequests += Number(eventUsage.measurement === "partial");
|
|
340
|
-
usage.unknownCosts += Number(eventUsage.costSource === "unknown");
|
|
341
|
-
}
|
|
342
|
-
if (isTerminalAssistantStop(event.message)) {
|
|
343
|
-
if (!event.message.errorMessage && extractTextFromContent(event.message.content).trim())
|
|
344
|
-
assistantError = undefined;
|
|
345
|
-
cleanTerminalAssistantStopReceived ||= !event.message.errorMessage;
|
|
346
|
-
applyChildLifecycle(projectChildLifecycle(event, true));
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
};
|
|
350
|
-
// Guard both cases that can leave the parent waiting on `close` forever:
|
|
351
|
-
// a lingering stdio holder after `exit`, or a child that never exits.
|
|
352
|
-
const FINAL_STOP_GRACE_MS = 1000;
|
|
353
|
-
const HARD_KILL_MS = 3000;
|
|
354
|
-
const TIMEOUT_HARD_KILL_MS = 3000;
|
|
355
|
-
let childExited = false;
|
|
356
|
-
let forcedTerminationSignal = false;
|
|
357
|
-
let cleanTerminalAssistantStopReceived = false;
|
|
358
|
-
let agentSettledReceived = false;
|
|
359
|
-
let finalDrainTimer;
|
|
360
|
-
let finalHardKillTimer;
|
|
361
|
-
let watchdogTailTimer;
|
|
362
|
-
let timeoutHardKillTimer;
|
|
363
|
-
let turnBudgetTerminationTimer;
|
|
364
|
-
let turnBudgetHardKillTimer;
|
|
365
|
-
let protocolHardKillTimer;
|
|
366
|
-
let protocolError;
|
|
367
|
-
let settled = false;
|
|
368
|
-
applyChildLifecycle = (action) => {
|
|
369
|
-
if (action === "cancel-drain") {
|
|
370
|
-
if (finalDrainTimer) {
|
|
371
|
-
clearTimeout(finalDrainTimer);
|
|
372
|
-
finalDrainTimer = undefined;
|
|
373
|
-
}
|
|
374
|
-
if (finalHardKillTimer) {
|
|
375
|
-
clearTimeout(finalHardKillTimer);
|
|
376
|
-
finalHardKillTimer = undefined;
|
|
377
|
-
}
|
|
378
|
-
clearWatchdogTailTimer();
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
381
|
-
if (action === "start-drain")
|
|
382
|
-
startFinalDrain();
|
|
383
|
-
};
|
|
384
|
-
const failProtocol = (limit) => {
|
|
385
|
-
if (protocolError)
|
|
386
|
-
return;
|
|
387
|
-
protocolError = limit;
|
|
388
|
-
error = formatProtocolOutputLimit(limit);
|
|
389
|
-
if (!childExited) {
|
|
390
|
-
trySignalChild(child, "SIGTERM");
|
|
391
|
-
protocolHardKillTimer = setTimeout(() => {
|
|
392
|
-
if (!settled)
|
|
393
|
-
trySignalChild(child, "SIGKILL");
|
|
394
|
-
}, 3000);
|
|
395
|
-
protocolHardKillTimer.unref?.();
|
|
396
|
-
}
|
|
397
|
-
};
|
|
398
|
-
const stdoutReader = createBoundedLineReader({ onLine: processStdoutLine, onLimit: failProtocol });
|
|
399
|
-
const stderrReader = createBoundedLineReader({
|
|
400
|
-
stream: "stderr",
|
|
401
|
-
maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
|
|
402
|
-
onLine: (line) => appendChildLine("subagent.child.stderr", line),
|
|
403
|
-
onLimit: (limit) => appendChildLine("subagent.child.stderr", formatProtocolOutputLimit(limit)),
|
|
404
|
-
});
|
|
405
|
-
const clearStdioGuard = attachPostExitStdioGuard(child, { idleMs: 2000, hardMs: 8000 });
|
|
406
|
-
child.stdout.on("data", (chunk) => stdoutReader.push(chunk));
|
|
407
|
-
child.stderr.on("data", (chunk) => {
|
|
408
|
-
stderrTail.push(chunk);
|
|
409
|
-
stderrReader.push(chunk);
|
|
410
|
-
outputStream.write(chunk);
|
|
411
|
-
});
|
|
412
|
-
registerInterrupt?.(() => {
|
|
413
|
-
if (settled || timedOut || stopped)
|
|
414
|
-
return;
|
|
415
|
-
interrupted = true;
|
|
416
|
-
if (!error)
|
|
417
|
-
error = "Interrupted. Waiting for explicit next action.";
|
|
418
|
-
trySignalChild(child, "SIGINT");
|
|
419
|
-
setTimeout(() => {
|
|
420
|
-
if (!settled && !timedOut && !stopped)
|
|
421
|
-
trySignalChild(child, "SIGTERM");
|
|
422
|
-
}, 1000).unref?.();
|
|
423
|
-
});
|
|
424
|
-
registerTimeout?.(() => {
|
|
425
|
-
if (settled || timedOut || stopped)
|
|
426
|
-
return;
|
|
427
|
-
timedOut = true;
|
|
428
|
-
interrupted = false;
|
|
429
|
-
error = timeoutMessage ?? "Subagent timed out.";
|
|
430
|
-
trySignalChild(child, "SIGTERM");
|
|
431
|
-
timeoutHardKillTimer = setTimeout(() => {
|
|
432
|
-
if (!settled)
|
|
433
|
-
trySignalChild(child, "SIGKILL");
|
|
434
|
-
}, TIMEOUT_HARD_KILL_MS);
|
|
435
|
-
timeoutHardKillTimer.unref?.();
|
|
436
|
-
});
|
|
437
|
-
registerStop?.(() => {
|
|
438
|
-
if (settled || timedOut || stopped)
|
|
439
|
-
return;
|
|
440
|
-
stopped = true;
|
|
441
|
-
interrupted = false;
|
|
442
|
-
error = stopMessage ?? "Subagent stopped by user.";
|
|
443
|
-
trySignalChild(child, "SIGTERM");
|
|
444
|
-
timeoutHardKillTimer = setTimeout(() => {
|
|
445
|
-
if (!settled)
|
|
446
|
-
trySignalChild(child, "SIGKILL");
|
|
447
|
-
}, TIMEOUT_HARD_KILL_MS);
|
|
448
|
-
timeoutHardKillTimer.unref?.();
|
|
449
|
-
});
|
|
450
|
-
registerTurnBudgetAbort?.((message, state) => {
|
|
451
|
-
if (settled || timedOut || stopped || turnBudgetExceeded)
|
|
452
|
-
return;
|
|
453
|
-
turnBudgetExceeded = true;
|
|
454
|
-
turnBudgetMessage = message;
|
|
455
|
-
turnBudget = state;
|
|
456
|
-
interrupted = false;
|
|
457
|
-
error = message;
|
|
458
|
-
trySignalChild(child, "SIGINT");
|
|
459
|
-
turnBudgetTerminationTimer = setTimeout(() => {
|
|
460
|
-
if (!settled && !timedOut && !stopped)
|
|
461
|
-
trySignalChild(child, "SIGTERM");
|
|
462
|
-
}, 1000);
|
|
463
|
-
turnBudgetTerminationTimer.unref?.();
|
|
464
|
-
turnBudgetHardKillTimer = setTimeout(() => {
|
|
465
|
-
if (!settled && !timedOut && !stopped)
|
|
466
|
-
trySignalChild(child, "SIGKILL");
|
|
467
|
-
}, 4000);
|
|
468
|
-
turnBudgetHardKillTimer.unref?.();
|
|
469
|
-
});
|
|
470
|
-
const clearDrainTimers = () => {
|
|
471
|
-
if (finalDrainTimer) {
|
|
472
|
-
clearTimeout(finalDrainTimer);
|
|
473
|
-
finalDrainTimer = undefined;
|
|
474
|
-
}
|
|
475
|
-
if (finalHardKillTimer) {
|
|
476
|
-
clearTimeout(finalHardKillTimer);
|
|
477
|
-
finalHardKillTimer = undefined;
|
|
478
|
-
}
|
|
479
|
-
clearWatchdogTailTimer();
|
|
480
|
-
if (timeoutHardKillTimer) {
|
|
481
|
-
clearTimeout(timeoutHardKillTimer);
|
|
482
|
-
timeoutHardKillTimer = undefined;
|
|
483
|
-
}
|
|
484
|
-
if (turnBudgetTerminationTimer) {
|
|
485
|
-
clearTimeout(turnBudgetTerminationTimer);
|
|
486
|
-
turnBudgetTerminationTimer = undefined;
|
|
487
|
-
}
|
|
488
|
-
if (turnBudgetHardKillTimer) {
|
|
489
|
-
clearTimeout(turnBudgetHardKillTimer);
|
|
490
|
-
turnBudgetHardKillTimer = undefined;
|
|
491
|
-
}
|
|
492
|
-
if (protocolHardKillTimer) {
|
|
493
|
-
clearTimeout(protocolHardKillTimer);
|
|
494
|
-
protocolHardKillTimer = undefined;
|
|
495
|
-
}
|
|
496
|
-
};
|
|
497
|
-
function startFinalDrain() {
|
|
498
|
-
if (childWatchdogIsActive(childWatchdogState)) {
|
|
499
|
-
armWatchdogTail();
|
|
500
|
-
return;
|
|
501
|
-
}
|
|
502
|
-
if (childExited || finalDrainTimer || settled)
|
|
503
|
-
return;
|
|
504
|
-
finalDrainTimer = setTimeout(() => {
|
|
505
|
-
if (settled)
|
|
506
|
-
return;
|
|
507
|
-
const termSent = trySignalChild(child, "SIGTERM");
|
|
508
|
-
if (!termSent)
|
|
509
|
-
return;
|
|
510
|
-
forcedTerminationSignal = true;
|
|
511
|
-
if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !error && !assistantError) {
|
|
512
|
-
error = `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;
|
|
513
|
-
}
|
|
514
|
-
finalHardKillTimer = setTimeout(() => {
|
|
515
|
-
if (settled)
|
|
516
|
-
return;
|
|
517
|
-
forcedTerminationSignal = trySignalChild(child, "SIGKILL") || forcedTerminationSignal;
|
|
518
|
-
}, HARD_KILL_MS);
|
|
519
|
-
finalHardKillTimer.unref?.();
|
|
520
|
-
}, FINAL_STOP_GRACE_MS);
|
|
521
|
-
finalDrainTimer.unref?.();
|
|
522
|
-
}
|
|
523
|
-
function clearWatchdogTailTimer() {
|
|
524
|
-
if (watchdogTailTimer) {
|
|
525
|
-
clearTimeout(watchdogTailTimer);
|
|
526
|
-
watchdogTailTimer = undefined;
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
function armWatchdogTail() {
|
|
530
|
-
if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || settled)
|
|
531
|
-
return;
|
|
532
|
-
watchdogTailTimer = setTimeout(() => {
|
|
533
|
-
watchdogTailTimer = undefined;
|
|
534
|
-
updateChildWatchdogState({
|
|
535
|
-
phase: "stale",
|
|
536
|
-
seq: (childWatchdogState?.seq ?? 0) + 1,
|
|
537
|
-
lastUpdate: Date.now(),
|
|
538
|
-
followUpPending: false,
|
|
539
|
-
reason: "child watchdog tail timeout",
|
|
540
|
-
timedOut: true,
|
|
541
|
-
});
|
|
542
|
-
startFinalDrain();
|
|
543
|
-
}, childWatchdogConfig?.watchdogTailTimeoutMs ?? 120_000);
|
|
544
|
-
watchdogTailTimer.unref?.();
|
|
545
|
-
}
|
|
546
|
-
child.on("exit", () => {
|
|
547
|
-
childExited = true;
|
|
548
|
-
clearDrainTimers();
|
|
549
|
-
});
|
|
550
|
-
child.on("close", (exitCode, signal) => {
|
|
551
|
-
settled = true;
|
|
552
|
-
try {
|
|
553
|
-
onWriterProcess?.({ state: "none" });
|
|
554
|
-
}
|
|
555
|
-
catch {
|
|
556
|
-
// The runner still owns and releases the lease during finalization.
|
|
557
|
-
}
|
|
558
|
-
registerInterrupt?.(undefined);
|
|
559
|
-
registerTimeout?.(undefined);
|
|
560
|
-
registerStop?.(undefined);
|
|
561
|
-
registerTurnBudgetAbort?.(undefined);
|
|
562
|
-
clearDrainTimers();
|
|
563
|
-
clearStdioGuard();
|
|
564
|
-
stdoutReader.end();
|
|
565
|
-
stderrReader.end();
|
|
566
|
-
outputStream.end();
|
|
567
|
-
const stderr = stderrTail.text();
|
|
568
|
-
const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
|
|
569
|
-
const finalError = error ?? assistantError;
|
|
570
|
-
const forcedDrainAfterFinalSuccess = forcedTerminationSignal && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !finalError;
|
|
571
|
-
resolve({
|
|
572
|
-
stderr,
|
|
573
|
-
exitCode: timedOut || stopped ? 1 : turnBudgetExceeded ? 1 : interrupted || forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (exitCode ?? 1) : exitCode,
|
|
574
|
-
messages,
|
|
575
|
-
usage,
|
|
576
|
-
model,
|
|
577
|
-
error: stopped ? (stopMessage ?? "Subagent stopped by user.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? turnBudgetMessage : interrupted || forcedDrainAfterFinalSuccess ? undefined : finalError,
|
|
578
|
-
protocolError,
|
|
579
|
-
finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage ?? "Subagent stopped by user." : timeoutMessage ?? "Subagent timed out.") : finalOutput,
|
|
580
|
-
interrupted,
|
|
581
|
-
timedOut,
|
|
582
|
-
stopped,
|
|
583
|
-
turnBudget,
|
|
584
|
-
turnBudgetExceeded,
|
|
585
|
-
wrapUpRequested: turnBudget?.outcome === "wrap-up-requested" || turnBudgetExceeded || undefined,
|
|
586
|
-
observedMutationAttempt,
|
|
587
|
-
watchdog: childWatchdogState,
|
|
588
|
-
});
|
|
589
|
-
});
|
|
590
|
-
child.on("error", (spawnError) => {
|
|
591
|
-
settled = true;
|
|
592
|
-
try {
|
|
593
|
-
onWriterProcess?.({ state: "none" });
|
|
594
|
-
}
|
|
595
|
-
catch {
|
|
596
|
-
// The runner still owns and releases the lease during finalization.
|
|
597
|
-
}
|
|
598
|
-
registerInterrupt?.(undefined);
|
|
599
|
-
registerTimeout?.(undefined);
|
|
600
|
-
registerStop?.(undefined);
|
|
601
|
-
registerTurnBudgetAbort?.(undefined);
|
|
602
|
-
clearDrainTimers();
|
|
603
|
-
clearStdioGuard();
|
|
604
|
-
stdoutReader.end();
|
|
605
|
-
stderrReader.end();
|
|
606
|
-
outputStream.end();
|
|
607
|
-
const stderr = stderrTail.text();
|
|
608
|
-
const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
|
|
609
|
-
const spawnErrorMessage = spawnError instanceof Error ? spawnError.message : String(spawnError);
|
|
610
|
-
resolve({ stderr, exitCode: 1, messages, usage, model, error: stopped ? (stopMessage ?? "Subagent stopped by user.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? turnBudgetMessage : error ?? assistantError ?? spawnErrorMessage, protocolError, finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage ?? "Subagent stopped by user." : timeoutMessage ?? "Subagent timed out.") : finalOutput, timedOut, stopped, turnBudget, turnBudgetExceeded, wrapUpRequested: turnBudget?.outcome === "wrap-up-requested" || turnBudgetExceeded || undefined, observedMutationAttempt, watchdog: childWatchdogState });
|
|
611
|
-
});
|
|
612
|
-
});
|
|
613
|
-
}
|
|
614
|
-
function formatDuration(ms) {
|
|
615
|
-
if (ms < 1000)
|
|
616
|
-
return `${ms}ms`;
|
|
617
|
-
if (ms < 60000)
|
|
618
|
-
return `${(ms / 1000).toFixed(1)}s`;
|
|
619
|
-
const minutes = Math.floor(ms / 60000);
|
|
620
|
-
const seconds = Math.floor((ms % 60000) / 1000);
|
|
621
|
-
return `${minutes}m${seconds}s`;
|
|
622
|
-
}
|
|
623
|
-
function writeRunLog(logPath, input) {
|
|
624
|
-
const lines = [];
|
|
625
|
-
lines.push(`# Subagent run ${input.id}`);
|
|
626
|
-
lines.push("");
|
|
627
|
-
lines.push(`- **Mode:** ${input.mode}`);
|
|
628
|
-
lines.push(`- **CWD:** ${input.cwd}`);
|
|
629
|
-
lines.push(`- **Started:** ${new Date(input.startedAt).toISOString()}`);
|
|
630
|
-
lines.push(`- **Ended:** ${new Date(input.endedAt).toISOString()}`);
|
|
631
|
-
lines.push(`- **Duration:** ${formatDuration(input.endedAt - input.startedAt)}`);
|
|
632
|
-
if (input.sessionFile)
|
|
633
|
-
lines.push(`- **Session:** ${input.sessionFile}`);
|
|
634
|
-
if (input.artifactsDir)
|
|
635
|
-
lines.push(`- **Artifacts:** ${input.artifactsDir}`);
|
|
636
|
-
lines.push("");
|
|
637
|
-
lines.push("## Steps");
|
|
638
|
-
lines.push("| Step | Agent | Status | Duration |");
|
|
639
|
-
lines.push("| --- | --- | --- | --- |");
|
|
640
|
-
input.steps.forEach((step, i) => {
|
|
641
|
-
const duration = step.durationMs !== undefined ? formatDuration(step.durationMs) : "-";
|
|
642
|
-
lines.push(`| ${i + 1} | ${step.agent} | ${step.status} | ${duration} |`);
|
|
643
|
-
});
|
|
644
|
-
lines.push("");
|
|
645
|
-
lines.push("## Summary");
|
|
646
|
-
if (input.truncated) {
|
|
647
|
-
lines.push("_Output truncated_");
|
|
648
|
-
lines.push("");
|
|
649
|
-
}
|
|
650
|
-
lines.push(input.summary.trim() || "(no output)");
|
|
651
|
-
lines.push("");
|
|
652
|
-
fs.writeFileSync(logPath, lines.join("\n"), "utf-8");
|
|
653
|
-
}
|
|
654
|
-
/** Run a single pi agent step, returning output and metadata */
|
|
655
|
-
export async function runSingleStep(step, ctx) {
|
|
656
|
-
if (step.importAsyncRoot) {
|
|
657
|
-
let importTimedOut = false;
|
|
658
|
-
let importStopped = false;
|
|
659
|
-
ctx.registerTimeout?.(() => {
|
|
660
|
-
importTimedOut = true;
|
|
661
|
-
let pid;
|
|
662
|
-
try {
|
|
663
|
-
pid = readStatus(step.importAsyncRoot.asyncDir)?.pid;
|
|
664
|
-
}
|
|
665
|
-
catch {
|
|
666
|
-
pid = undefined;
|
|
667
|
-
}
|
|
668
|
-
try {
|
|
669
|
-
deliverTimeoutRequest({ asyncDir: step.importAsyncRoot.asyncDir, pid, source: "ancestor-timeout" });
|
|
670
|
-
}
|
|
671
|
-
catch {
|
|
672
|
-
// The parent runner's own timeout result is authoritative for the attached step.
|
|
673
|
-
}
|
|
674
|
-
});
|
|
675
|
-
ctx.registerStop?.(() => {
|
|
676
|
-
importStopped = true;
|
|
677
|
-
let pid;
|
|
678
|
-
try {
|
|
679
|
-
pid = readStatus(step.importAsyncRoot.asyncDir)?.pid;
|
|
680
|
-
}
|
|
681
|
-
catch {
|
|
682
|
-
pid = undefined;
|
|
683
|
-
}
|
|
684
|
-
try {
|
|
685
|
-
deliverStopRequest({ asyncDir: step.importAsyncRoot.asyncDir, pid, source: "ancestor-stop" });
|
|
686
|
-
}
|
|
687
|
-
catch {
|
|
688
|
-
// The parent runner's own stopped result is authoritative for the attached step.
|
|
689
|
-
}
|
|
690
|
-
});
|
|
691
|
-
try {
|
|
692
|
-
const imported = await waitForImportedAsyncRoot(step.importAsyncRoot, {
|
|
693
|
-
shouldAbort: () => importTimedOut || importStopped || ctx.timeoutSignal?.aborted === true || ctx.stopSignal?.aborted === true || ctx.skipAcceptance?.() === true,
|
|
694
|
-
timeoutMessage: importStopped || ctx.stopSignal?.aborted === true ? ctx.stopMessage : ctx.timeoutMessage,
|
|
695
|
-
});
|
|
696
|
-
try {
|
|
697
|
-
fs.writeFileSync(ctx.outputFile, imported.output, "utf-8");
|
|
698
|
-
}
|
|
699
|
-
catch {
|
|
700
|
-
// Output files are observability only for imported roots.
|
|
701
|
-
}
|
|
702
|
-
const stopped = importStopped || imported.stopped === true || ctx.stopSignal?.aborted === true;
|
|
703
|
-
const timedOut = !stopped && (importTimedOut || imported.timedOut === true || ctx.timeoutSignal?.aborted === true || ctx.skipAcceptance?.() === true);
|
|
704
|
-
const message = stopped ? ctx.stopMessage ?? "Subagent stopped by user." : ctx.timeoutMessage ?? "Subagent timed out.";
|
|
705
|
-
return {
|
|
706
|
-
agent: imported.agent,
|
|
707
|
-
output: timedOut || stopped ? message : imported.output,
|
|
708
|
-
exitCode: timedOut || stopped ? 1 : imported.exitCode,
|
|
709
|
-
error: timedOut || stopped ? message : imported.error,
|
|
710
|
-
timedOut: timedOut ? true : undefined,
|
|
711
|
-
stopped: stopped ? true : undefined,
|
|
712
|
-
sessionFile: imported.sessionFile,
|
|
713
|
-
intercomTarget: imported.intercomTarget,
|
|
714
|
-
model: imported.model,
|
|
715
|
-
attemptedModels: imported.attemptedModels,
|
|
716
|
-
modelAttempts: imported.modelAttempts,
|
|
717
|
-
receiptUsage: imported.usage,
|
|
718
|
-
usageRequests: imported.usageRequests,
|
|
719
|
-
totalCost: imported.totalCost,
|
|
720
|
-
structuredOutput: timedOut || stopped ? undefined : imported.structuredOutput,
|
|
721
|
-
structuredOutputPath: timedOut || stopped ? undefined : imported.structuredOutputPath,
|
|
722
|
-
structuredOutputSchemaPath: timedOut || stopped ? undefined : imported.structuredOutputSchemaPath,
|
|
723
|
-
acceptance: timedOut || stopped ? undefined : imported.acceptance,
|
|
724
|
-
};
|
|
725
|
-
}
|
|
726
|
-
finally {
|
|
727
|
-
ctx.registerTimeout?.(undefined);
|
|
728
|
-
ctx.registerStop?.(undefined);
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
|
|
732
|
-
? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
|
|
733
|
-
: undefined);
|
|
734
|
-
const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
|
|
735
|
-
let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
|
|
736
|
-
if (ctx.outputs)
|
|
737
|
-
task = resolveOutputReferences(task, ctx.outputs);
|
|
738
|
-
const taskForCompletionGuard = step.completionTask ?? task;
|
|
739
|
-
if (step.effectiveAcceptance) {
|
|
740
|
-
const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance);
|
|
741
|
-
if (acceptancePrompt)
|
|
742
|
-
task = `${task}\n${acceptancePrompt}`;
|
|
743
|
-
}
|
|
744
|
-
task = withChainHandoff(task, ctx.handoffToNext === true);
|
|
745
|
-
const sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;
|
|
746
|
-
const sessionDir = step.sessionFile ? undefined : ctx.sessionDir;
|
|
747
|
-
let artifactPaths;
|
|
748
|
-
let transcriptWriter;
|
|
749
|
-
if (ctx.artifactsDir && ctx.artifactConfig?.enabled !== false) {
|
|
750
|
-
const index = ctx.flatStepCount > 1 ? ctx.flatIndex : undefined;
|
|
751
|
-
artifactPaths = getArtifactPaths(ctx.artifactsDir, ctx.id, step.agent, index);
|
|
752
|
-
ensureArtifactsDir(ctx.artifactsDir);
|
|
753
|
-
if (ctx.artifactConfig?.includeInput !== false) {
|
|
754
|
-
writeArtifact(artifactPaths.inputPath, `# Task for ${step.agent}\n\n${task}`);
|
|
755
|
-
}
|
|
756
|
-
if (ctx.artifactConfig?.includeTranscript !== false) {
|
|
757
|
-
transcriptWriter = createChildTranscriptWriter({
|
|
758
|
-
transcriptPath: artifactPaths.transcriptPath,
|
|
759
|
-
source: "async",
|
|
760
|
-
runId: ctx.id,
|
|
761
|
-
agent: step.agent,
|
|
762
|
-
childIndex: ctx.flatIndex,
|
|
763
|
-
cwd: step.cwd ?? ctx.cwd,
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
transcriptWriter?.writeInitialUserMessage(task);
|
|
768
|
-
const candidates = step.modelCandidates && step.modelCandidates.length > 0
|
|
769
|
-
? step.modelCandidates
|
|
770
|
-
: step.model
|
|
771
|
-
? [step.model]
|
|
772
|
-
: [undefined];
|
|
773
|
-
const attemptedModels = [];
|
|
774
|
-
const modelAttempts = [];
|
|
775
|
-
const priorRequestIds = new Set(parseSessionRequests(step.sessionFile ?? sessionDir).map((request) => request.id));
|
|
776
|
-
const attemptNotes = [];
|
|
777
|
-
const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
|
|
778
|
-
let finalResult;
|
|
779
|
-
let finalOutputSnapshot;
|
|
780
|
-
let completionGuardTriggeredFinal = false;
|
|
781
|
-
let turnBudget = ctx.turnBudget ? initialTurnBudgetState(ctx.turnBudget) : undefined;
|
|
782
|
-
let toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;
|
|
783
|
-
let toolBudgetBlocked = false;
|
|
784
|
-
for (let index = 0; index < candidates.length; index++) {
|
|
785
|
-
if (ctx.timeoutSignal?.aborted || ctx.skipAcceptance?.())
|
|
786
|
-
break;
|
|
787
|
-
const candidate = candidates[index];
|
|
788
|
-
ctx.onAttemptStart?.({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) });
|
|
789
|
-
const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
|
|
790
|
-
if (effectiveStructuredOutput) {
|
|
791
|
-
try {
|
|
792
|
-
if (fs.existsSync(effectiveStructuredOutput.outputPath))
|
|
793
|
-
fs.unlinkSync(effectiveStructuredOutput.outputPath);
|
|
794
|
-
}
|
|
795
|
-
catch {
|
|
796
|
-
// Missing/stale structured-output files are handled after the child exits.
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
const watchdogConfig = resolveWatchdogConfig(step.cwd ?? ctx.cwd);
|
|
800
|
-
const childWatchdog = watchdogConfig.ok
|
|
801
|
-
? resolveChildWatchdogConfig({
|
|
802
|
-
config: watchdogConfig.config,
|
|
803
|
-
agent: step.agent,
|
|
804
|
-
runId: ctx.id,
|
|
805
|
-
childIndex: ctx.flatIndex,
|
|
806
|
-
})
|
|
807
|
-
: undefined;
|
|
808
|
-
const parentPermissionMode = step.parentPermissionMode ?? snapshotParentPermissionMode(step.parentSessionId);
|
|
809
|
-
const childPermission = step.permissions === "read-only" || parentPermissionMode === "read-only" ? "read-only" : "full";
|
|
810
|
-
const excludeTools = resolveChildExcludeTools({
|
|
811
|
-
permissions: childPermission,
|
|
812
|
-
fanoutAuthorized: Array.isArray(step.tools) && step.tools.includes("subagent"),
|
|
813
|
-
});
|
|
814
|
-
const { args, env, tempDir, toolDiagnosticPath } = buildPiArgs({
|
|
815
|
-
parentSessionId: step.parentSessionId,
|
|
816
|
-
supervisorSessionId: ctx.supervisorSessionId,
|
|
817
|
-
baseArgs: ["--mode", "json", "-p"],
|
|
818
|
-
task,
|
|
819
|
-
sessionEnabled,
|
|
820
|
-
sessionDir,
|
|
821
|
-
sessionFile: step.sessionFile,
|
|
822
|
-
model: candidate,
|
|
823
|
-
inheritProjectContext: true,
|
|
824
|
-
inheritSkills: false,
|
|
825
|
-
requireReadTool: Boolean(step.skills?.length),
|
|
826
|
-
excludeTools,
|
|
827
|
-
childPermission,
|
|
828
|
-
childId: step.childId ?? step.agent,
|
|
829
|
-
childDescription: step.description ?? step.agent,
|
|
830
|
-
systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt && !step.systemPrompt.includes("You are `") ? step.systemPrompt : "", ctx.turnBudget) || undefined,
|
|
831
|
-
systemPromptMode: "append",
|
|
832
|
-
cwd: step.cwd ?? ctx.cwd,
|
|
833
|
-
promptFileStem: step.childId ?? step.agent,
|
|
834
|
-
intercomSessionName: ctx.childIntercomTarget,
|
|
835
|
-
orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
|
|
836
|
-
runId: ctx.id,
|
|
837
|
-
childAgentName: step.childId ?? step.agent,
|
|
838
|
-
childIndex: ctx.flatIndex,
|
|
839
|
-
parentEventSink: ctx.nestedRoute?.eventSink,
|
|
840
|
-
parentControlInbox: ctx.nestedRoute?.controlInbox,
|
|
841
|
-
parentRootRunId: ctx.nestedRoute?.rootRunId,
|
|
842
|
-
parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
|
|
843
|
-
steerInboxDir: ctx.steerInboxDir,
|
|
844
|
-
steerCapabilityPath: ctx.steerCapabilityPath,
|
|
845
|
-
steerAckDir: ctx.steerAckDir,
|
|
846
|
-
structuredOutput: effectiveStructuredOutput,
|
|
847
|
-
toolBudget: step.toolBudget,
|
|
848
|
-
childWatchdog,
|
|
849
|
-
waitToolEnabled: step.waitToolEnabled,
|
|
850
|
-
parentPermissionMode,
|
|
851
|
-
parentAutoReview: step.parentAutoReview,
|
|
852
|
-
});
|
|
853
|
-
const usageBeforeAttempt = parseSessionUsage(step.sessionFile ?? sessionDir);
|
|
854
|
-
const run = await runPiStreaming(args, step.cwd ?? ctx.cwd, ctx.outputFile, env, ctx.piPackageRoot, ctx.piArgv1, step.maxSubagentDepth, { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent }, ctx.registerInterrupt, ctx.onChildEvent, transcriptWriter, ctx.registerTimeout, ctx.timeoutMessage, ctx.registerStop, ctx.stopMessage, ctx.registerTurnBudgetAbort, ctx.onWriterProcess);
|
|
855
|
-
const persistedUsage = parseSessionUsage(step.sessionFile ?? sessionDir);
|
|
856
|
-
if (persistedUsage)
|
|
857
|
-
run.usage = sessionUsageDelta(persistedUsage, usageBeforeAttempt);
|
|
858
|
-
if (run.turnBudget)
|
|
859
|
-
turnBudget = run.turnBudget;
|
|
860
|
-
else if (ctx.turnBudget) {
|
|
861
|
-
const assistantMessages = run.messages.filter((message) => message.role === "assistant");
|
|
862
|
-
const turnCount = assistantMessages.length;
|
|
863
|
-
const lastAssistantMessage = assistantMessages.at(-1);
|
|
864
|
-
if (turnCount > 0 && turnCount < ctx.turnBudget.maxTurns) {
|
|
865
|
-
turnBudget = { ...ctx.turnBudget, outcome: "within-budget", turnCount };
|
|
866
|
-
}
|
|
867
|
-
else if (turnCount >= ctx.turnBudget.maxTurns) {
|
|
868
|
-
turnBudget = turnBudgetState(ctx.turnBudget, turnCount, shouldAbortForTurnBudget(ctx.turnBudget, turnCount, lastAssistantMessage ? isTerminalAssistantStop(lastAssistantMessage) : false));
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
const toolAvailabilityError = run.exitCode === 0 && !run.error
|
|
872
|
-
? readChildToolDiagnosticError(toolDiagnosticPath)
|
|
873
|
-
: undefined;
|
|
874
|
-
cleanupTempDir(tempDir);
|
|
875
|
-
const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError ? detectSubagentError(run.messages) : null;
|
|
876
|
-
const missingStructuredOutput = effectiveStructuredOutput
|
|
877
|
-
? !fs.existsSync(effectiveStructuredOutput.outputPath)
|
|
878
|
-
: false;
|
|
879
|
-
const emptyOutputError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !hiddenError?.hasError && !run.finalOutput.trim() && (!effectiveStructuredOutput || missingStructuredOutput)
|
|
880
|
-
? "Subagent produced no output (possible model cold-start or empty response)."
|
|
881
|
-
: undefined;
|
|
882
|
-
let structuredOutput;
|
|
883
|
-
let structuredError;
|
|
884
|
-
if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError && !hiddenError?.hasError && !emptyOutputError) {
|
|
885
|
-
const structured = readStructuredOutput({
|
|
886
|
-
schema: effectiveStructuredOutput.schema,
|
|
887
|
-
schemaPath: effectiveStructuredOutput.schemaPath,
|
|
888
|
-
outputPath: effectiveStructuredOutput.outputPath,
|
|
889
|
-
});
|
|
890
|
-
if (structured.error)
|
|
891
|
-
structuredError = structured.error;
|
|
892
|
-
else
|
|
893
|
-
structuredOutput = structured.value;
|
|
894
|
-
}
|
|
895
|
-
const completionGuard = run.exitCode === 0 && !run.error && !toolAvailabilityError && !hiddenError?.hasError && !emptyOutputError && step.completionGuard !== false
|
|
896
|
-
? evaluateCompletionMutationGuard({
|
|
897
|
-
permissions: childPermission,
|
|
898
|
-
task: taskForCompletionGuard,
|
|
899
|
-
messages: run.messages,
|
|
900
|
-
tools: step.tools,
|
|
901
|
-
mcpDirectTools: step.mcpDirectTools,
|
|
902
|
-
})
|
|
903
|
-
: undefined;
|
|
904
|
-
const completionGuardTriggered = completionGuard?.triggered === true && !run.observedMutationAttempt;
|
|
905
|
-
const completionGuardError = completionGuardTriggered
|
|
906
|
-
? "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes."
|
|
907
|
-
: undefined;
|
|
908
|
-
const effectiveExitCode = toolAvailabilityError || completionGuardTriggered || structuredError
|
|
909
|
-
? 1
|
|
910
|
-
: hiddenError?.hasError
|
|
911
|
-
? (hiddenError.exitCode ?? 1)
|
|
912
|
-
: emptyOutputError
|
|
913
|
-
? 1
|
|
914
|
-
: run.error && run.exitCode === 0
|
|
915
|
-
? 1
|
|
916
|
-
: run.exitCode;
|
|
917
|
-
const error = toolAvailabilityError
|
|
918
|
-
?? completionGuardError
|
|
919
|
-
?? structuredError
|
|
920
|
-
?? (hiddenError?.hasError
|
|
921
|
-
? hiddenError.details
|
|
922
|
-
? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
|
|
923
|
-
: `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
|
|
924
|
-
: emptyOutputError ?? (run.error || (run.exitCode !== 0 && run.stderr.trim() ? run.stderr.trim() : undefined)));
|
|
925
|
-
const attempt = {
|
|
926
|
-
model: candidate ?? run.model ?? step.model ?? "default",
|
|
927
|
-
success: effectiveExitCode === 0 && !error,
|
|
928
|
-
exitCode: effectiveExitCode,
|
|
929
|
-
error,
|
|
930
|
-
usage: run.usage,
|
|
931
|
-
};
|
|
932
|
-
modelAttempts.push(attempt);
|
|
933
|
-
if (candidate)
|
|
934
|
-
attemptedModels.push(candidate);
|
|
935
|
-
completionGuardTriggeredFinal = completionGuardTriggered;
|
|
936
|
-
finalOutputSnapshot = outputSnapshot;
|
|
937
|
-
if (step.toolBudget) {
|
|
938
|
-
const toolMessages = run.messages.filter((message) => message.role === "toolResult");
|
|
939
|
-
const blockedMessage = toolMessages.find((message) => extractTextFromContent(message.content).includes("Tool budget hard limit reached"));
|
|
940
|
-
toolBudgetBlocked = Boolean(blockedMessage);
|
|
941
|
-
toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? blockedMessage.toolName : undefined);
|
|
942
|
-
}
|
|
943
|
-
finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput };
|
|
944
|
-
if (run.turnBudgetExceeded)
|
|
945
|
-
break;
|
|
946
|
-
if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.())
|
|
947
|
-
break;
|
|
948
|
-
if (attempt.success || completionGuardTriggered)
|
|
949
|
-
break;
|
|
950
|
-
if (!isRetryableModelFailure(error) || index === candidates.length - 1)
|
|
951
|
-
break;
|
|
952
|
-
attemptNotes.push(formatModelAttemptNote(attempt, candidates[index + 1]));
|
|
953
|
-
}
|
|
954
|
-
const rawOutput = finalResult?.finalOutput ?? "";
|
|
955
|
-
const outputForPersistence = stripAcceptanceReport(rawOutput);
|
|
956
|
-
const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
|
|
957
|
-
? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot, ctx.sessionCwd ?? ctx.cwd)
|
|
958
|
-
: { fullOutput: outputForPersistence };
|
|
959
|
-
const output = stripAcceptanceReport(resolvedOutput.fullOutput);
|
|
960
|
-
const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, output) : undefined;
|
|
961
|
-
let outputForSummary = output;
|
|
962
|
-
if (attemptNotes.length > 0) {
|
|
963
|
-
outputForSummary = `${attemptNotes.join("\n")}\n\n${outputForSummary}`.trim();
|
|
964
|
-
}
|
|
965
|
-
if (finalResult?.stopped && !outputForSummary.trim()) {
|
|
966
|
-
outputForSummary = ctx.stopMessage ?? "Subagent stopped by user.";
|
|
967
|
-
}
|
|
968
|
-
else if (!finalResult?.timedOut && !finalResult?.stopped && finalResult?.turnBudgetExceeded && turnBudget) {
|
|
969
|
-
outputForSummary = formatTurnBudgetOutput(turnBudgetExceededMessage(turnBudget, turnBudget.turnCount), outputForSummary);
|
|
970
|
-
}
|
|
971
|
-
else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === "wrap-up-requested") {
|
|
972
|
-
const note = turnBudgetSoftNote(turnBudget, turnBudget.wrapUpRequestedAtTurn ?? turnBudget.turnCount);
|
|
973
|
-
outputForSummary = outputForSummary.trim() ? `${note}\n\n${outputForSummary}` : note;
|
|
974
|
-
}
|
|
975
|
-
const outputForAcceptance = rawOutput;
|
|
976
|
-
const childWrittenOutput = step.outputPath
|
|
977
|
-
? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)
|
|
978
|
-
: undefined;
|
|
979
|
-
const finalizedOutput = finalizeSingleOutput({
|
|
980
|
-
fullOutput: outputForSummary,
|
|
981
|
-
outputPath: step.outputPath,
|
|
982
|
-
outputMode: step.outputMode,
|
|
983
|
-
exitCode: finalResult?.exitCode ?? 1,
|
|
984
|
-
savedPath: resolvedOutput.savedPath,
|
|
985
|
-
outputReference,
|
|
986
|
-
saveError: resolvedOutput.saveError,
|
|
987
|
-
});
|
|
988
|
-
outputForSummary = finalizedOutput.displayOutput;
|
|
989
|
-
const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !finalResult?.turnBudgetExceeded && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
|
|
990
|
-
? await evaluateAcceptance({
|
|
991
|
-
acceptance: step.effectiveAcceptance,
|
|
992
|
-
output: outputForAcceptance,
|
|
993
|
-
fileOutput: childWrittenOutput !== undefined && step.outputPath
|
|
994
|
-
? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only" }
|
|
995
|
-
: undefined,
|
|
996
|
-
cwd: step.cwd ?? ctx.cwd,
|
|
997
|
-
signal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),
|
|
998
|
-
abortMessage: ctx.stopSignal?.aborted ? ctx.stopMessage ?? "Subagent stopped by user." : ctx.timeoutMessage ?? "Subagent timed out.",
|
|
999
|
-
})
|
|
1000
|
-
: undefined;
|
|
1001
|
-
const stoppedAfterAcceptance = finalResult?.stopped === true || ctx.stopSignal?.aborted === true;
|
|
1002
|
-
const timedOutAfterAcceptance = !stoppedAfterAcceptance && (finalResult?.timedOut === true || ctx.timeoutSignal?.aborted === true);
|
|
1003
|
-
const turnBudgetExceeded = finalResult?.turnBudgetExceeded === true;
|
|
1004
|
-
const effectiveAcceptance = step.effectiveAcceptance
|
|
1005
|
-
? stoppedAfterAcceptance
|
|
1006
|
-
? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." })
|
|
1007
|
-
: timedOutAfterAcceptance
|
|
1008
|
-
? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." })
|
|
1009
|
-
: turnBudgetExceeded
|
|
1010
|
-
? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." })
|
|
1011
|
-
: acceptance
|
|
1012
|
-
: undefined;
|
|
1013
|
-
const acceptanceFailure = effectiveAcceptance ? acceptanceFailureMessage(effectiveAcceptance) : undefined;
|
|
1014
|
-
const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !turnBudgetExceeded;
|
|
1015
|
-
const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
|
|
1016
|
-
const effectiveFinalError = stoppedAfterAcceptance
|
|
1017
|
-
? ctx.stopMessage ?? "Subagent stopped by user."
|
|
1018
|
-
: timedOutAfterAcceptance
|
|
1019
|
-
? ctx.timeoutMessage ?? "Subagent timed out."
|
|
1020
|
-
: turnBudgetExceeded
|
|
1021
|
-
? finalResult?.error ?? (turnBudget ? turnBudgetExceededMessage(turnBudget, turnBudget.turnCount) : "Subagent exceeded turn budget.")
|
|
1022
|
-
: acceptanceCanFailRun
|
|
1023
|
-
? (finalResult?.error ? `${finalResult.error}\n${acceptanceFailure}` : acceptanceFailure)
|
|
1024
|
-
: finalResult?.error;
|
|
1025
|
-
if (artifactPaths && ctx.artifactConfig?.enabled !== false) {
|
|
1026
|
-
if (ctx.artifactConfig?.includeOutput !== false) {
|
|
1027
|
-
writeArtifact(artifactPaths.outputPath, output);
|
|
1028
|
-
}
|
|
1029
|
-
if (ctx.artifactConfig?.includeMetadata !== false) {
|
|
1030
|
-
fs.writeFileSync(artifactPaths.metadataPath, JSON.stringify({
|
|
1031
|
-
runId: ctx.id,
|
|
1032
|
-
agent: step.agent,
|
|
1033
|
-
task,
|
|
1034
|
-
exitCode: effectiveFinalExitCode,
|
|
1035
|
-
model: finalResult?.model,
|
|
1036
|
-
attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
|
|
1037
|
-
modelAttempts,
|
|
1038
|
-
error: effectiveFinalError,
|
|
1039
|
-
acceptance: effectiveAcceptance,
|
|
1040
|
-
...(transcriptWriter ? { transcriptPath: artifactPaths.transcriptPath } : {}),
|
|
1041
|
-
transcriptError: transcriptWriter?.getError(),
|
|
1042
|
-
skills: step.skills,
|
|
1043
|
-
timestamp: Date.now(),
|
|
1044
|
-
}, null, 2), { encoding: "utf-8", mode: 0o600 });
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
const usageRequests = parseSessionRequests(step.sessionFile ?? sessionDir).filter((request) => Boolean(step.sessionFile) || !priorRequestIds.has(request.id));
|
|
1048
|
-
return {
|
|
1049
|
-
childId: step.childId,
|
|
1050
|
-
description: step.description,
|
|
1051
|
-
permissions: step.permissions,
|
|
1052
|
-
agent: step.agent,
|
|
1053
|
-
output: outputForSummary,
|
|
1054
|
-
exitCode: effectiveFinalExitCode,
|
|
1055
|
-
error: effectiveFinalError,
|
|
1056
|
-
protocolError: finalResult?.protocolError,
|
|
1057
|
-
sessionFile: step.sessionFile ?? (sessionDir ? findLatestSessionFile(sessionDir) ?? undefined : undefined),
|
|
1058
|
-
receiptUsage: step.sessionFile ? parseSessionUsage(step.sessionFile) ?? undefined : undefined,
|
|
1059
|
-
usageRequests: usageRequests.length > 0 ? usageRequests : undefined,
|
|
1060
|
-
intercomTarget: ctx.childIntercomTarget,
|
|
1061
|
-
model: finalResult?.model,
|
|
1062
|
-
attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
|
|
1063
|
-
modelAttempts,
|
|
1064
|
-
totalCost: costSummaryFromAttempts(modelAttempts),
|
|
1065
|
-
artifactPaths,
|
|
1066
|
-
transcriptPath: transcriptWriter ? artifactPaths?.transcriptPath : undefined,
|
|
1067
|
-
transcriptError: transcriptWriter?.getError(),
|
|
1068
|
-
interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? false : finalResult?.interrupted,
|
|
1069
|
-
timedOut: timedOutAfterAcceptance ? true : finalResult?.timedOut,
|
|
1070
|
-
stopped: stoppedAfterAcceptance ? true : finalResult?.stopped,
|
|
1071
|
-
turnBudget,
|
|
1072
|
-
turnBudgetExceeded: turnBudgetExceeded || undefined,
|
|
1073
|
-
wrapUpRequested: finalResult?.wrapUpRequested || turnBudget?.outcome === "wrap-up-requested" || turnBudgetExceeded || undefined,
|
|
1074
|
-
toolBudget,
|
|
1075
|
-
toolBudgetBlocked: toolBudgetBlocked || undefined,
|
|
1076
|
-
completionGuardTriggered: completionGuardTriggeredFinal,
|
|
1077
|
-
structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : finalResult?.structuredOutput,
|
|
1078
|
-
structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.outputPath,
|
|
1079
|
-
structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.schemaPath,
|
|
1080
|
-
acceptance: effectiveAcceptance,
|
|
1081
|
-
watchdog: finalResult?.watchdog,
|
|
1082
|
-
};
|
|
1083
|
-
}
|
|
1084
|
-
function markParallelGroupSetupFailure(input) {
|
|
1085
|
-
for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
|
|
1086
|
-
const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
|
|
1087
|
-
input.statusPayload.steps[flatTaskIndex].status = "failed";
|
|
1088
|
-
input.statusPayload.steps[flatTaskIndex].startedAt = input.failedAt;
|
|
1089
|
-
input.statusPayload.steps[flatTaskIndex].endedAt = input.failedAt;
|
|
1090
|
-
input.statusPayload.steps[flatTaskIndex].durationMs = 0;
|
|
1091
|
-
input.statusPayload.steps[flatTaskIndex].exitCode = 1;
|
|
1092
|
-
input.results.push({ agent: input.group.parallel[taskIndex].agent, output: input.setupError, success: false, exitCode: 1, sessionFile: input.group.parallel[taskIndex].sessionFile });
|
|
1093
|
-
}
|
|
1094
|
-
input.statusPayload.currentStep = input.groupStartFlatIndex;
|
|
1095
|
-
input.statusPayload.lastUpdate = input.failedAt;
|
|
1096
|
-
input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
|
|
1097
|
-
writeAtomicJson(input.statusPath, input.statusPayload);
|
|
1098
|
-
appendJsonl(input.eventsPath, JSON.stringify({
|
|
1099
|
-
type: "subagent.parallel.completed",
|
|
1100
|
-
ts: input.failedAt,
|
|
1101
|
-
runId: input.runId,
|
|
1102
|
-
stepIndex: input.stepIndex,
|
|
1103
|
-
success: false,
|
|
1104
|
-
}));
|
|
1105
|
-
}
|
|
1106
|
-
function markParallelGroupRunning(input) {
|
|
1107
|
-
for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
|
|
1108
|
-
const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
|
|
1109
|
-
input.statusPayload.steps[flatTaskIndex].status = "pending";
|
|
1110
|
-
input.statusPayload.steps[flatTaskIndex].startedAt = undefined;
|
|
1111
|
-
input.statusPayload.steps[flatTaskIndex].endedAt = undefined;
|
|
1112
|
-
input.statusPayload.steps[flatTaskIndex].durationMs = undefined;
|
|
1113
|
-
input.statusPayload.steps[flatTaskIndex].lastActivityAt = undefined;
|
|
1114
|
-
input.statusPayload.steps[flatTaskIndex].activityState = undefined;
|
|
1115
|
-
input.statusPayload.steps[flatTaskIndex].error = undefined;
|
|
1116
|
-
}
|
|
1117
|
-
input.statusPayload.currentStep = input.groupStartFlatIndex;
|
|
1118
|
-
input.statusPayload.activityState = undefined;
|
|
1119
|
-
input.statusPayload.lastActivityAt = input.groupStartTime;
|
|
1120
|
-
input.statusPayload.lastUpdate = input.groupStartTime;
|
|
1121
|
-
input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
|
|
1122
|
-
writeAtomicJson(input.statusPath, input.statusPayload);
|
|
1123
|
-
appendJsonl(input.eventsPath, JSON.stringify({
|
|
1124
|
-
type: "subagent.parallel.started",
|
|
1125
|
-
ts: input.groupStartTime,
|
|
1126
|
-
runId: input.runId,
|
|
1127
|
-
stepIndex: input.stepIndex,
|
|
1128
|
-
agents: input.group.parallel.map((task) => task.agent),
|
|
1129
|
-
count: input.group.parallel.length,
|
|
1130
|
-
}));
|
|
1131
|
-
}
|
|
1132
|
-
function prepareParallelTaskRun(task, cwd, worktreeSetup, taskIndex) {
|
|
1133
|
-
if (!worktreeSetup)
|
|
1134
|
-
return { taskForRun: task, taskCwd: cwd };
|
|
1135
|
-
return {
|
|
1136
|
-
taskForRun: { ...task, cwd: undefined },
|
|
1137
|
-
taskCwd: worktreeSetup.worktrees[taskIndex].agentCwd,
|
|
1138
|
-
};
|
|
1139
|
-
}
|
|
1140
|
-
function appendParallelWorktreeSummary(previousOutput, worktreeSetup, asyncDir, stepIndex, group) {
|
|
1141
|
-
if (!worktreeSetup)
|
|
1142
|
-
return previousOutput;
|
|
1143
|
-
const diffsDir = path.join(asyncDir, "worktree-diffs", `step-${stepIndex}`);
|
|
1144
|
-
const diffs = diffWorktrees(worktreeSetup, group.parallel.map((task) => task.agent), diffsDir);
|
|
1145
|
-
const diffSummary = formatWorktreeDiffSummary(diffs);
|
|
1146
|
-
if (!diffSummary)
|
|
1147
|
-
return previousOutput;
|
|
1148
|
-
return `${previousOutput}\n\n${diffSummary}`;
|
|
1149
|
-
}
|
|
1150
|
-
function ensureParallelProgressFile(cwd, group) {
|
|
1151
|
-
const progressPath = path.join(cwd, "progress.md");
|
|
1152
|
-
if (!group.parallel.some((task) => task.task.includes(`Update progress at: ${progressPath}`)))
|
|
1153
|
-
return;
|
|
1154
|
-
writeInitialProgressFile(cwd);
|
|
1155
|
-
}
|
|
1156
|
-
function resolveAsyncStepTranscriptPath(input) {
|
|
1157
|
-
if (!input.artifactsDir || input.artifactConfig?.enabled === false || input.artifactConfig?.includeTranscript === false)
|
|
1158
|
-
return undefined;
|
|
1159
|
-
return getArtifactPaths(input.artifactsDir, input.runId, input.agent, input.flatStepCount > 1 ? input.flatIndex : undefined).transcriptPath;
|
|
1160
|
-
}
|
|
1161
|
-
function combinedAbortSignal(signals) {
|
|
1162
|
-
const activeSignals = signals.filter((signal) => Boolean(signal));
|
|
1163
|
-
if (activeSignals.length === 0)
|
|
1164
|
-
return undefined;
|
|
1165
|
-
if (activeSignals.length === 1)
|
|
1166
|
-
return activeSignals[0];
|
|
1167
|
-
const controller = new AbortController();
|
|
1168
|
-
const abort = () => controller.abort();
|
|
1169
|
-
for (const signal of activeSignals) {
|
|
1170
|
-
if (signal.aborted) {
|
|
1171
|
-
abort();
|
|
1172
|
-
break;
|
|
1173
|
-
}
|
|
1174
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
1175
|
-
}
|
|
1176
|
-
return controller.signal;
|
|
1177
|
-
}
|
|
1178
35
|
async function runSubagent(config, onWriterProcess) {
|
|
1179
36
|
const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } = config;
|
|
1180
37
|
const globalSemaphore = new Semaphore(config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
|