@ferris1225/pi-subagents 2.0.2 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -6
- package/package.json +1 -1
- package/src/announcements.ts +70 -70
- package/src/dispatch.ts +24 -996
- package/src/format.ts +177 -177
- package/src/index.ts +3 -2
- package/src/rpc-run.ts +1125 -1059
- package/src/spawn.ts +13 -1
- package/src/thread-lifecycle.ts +1061 -0
- package/src/widget.ts +144 -144
- package/src/worktree.ts +687 -687
|
@@ -0,0 +1,1061 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stable logical-thread generation lifecycle for background sub-agents.
|
|
3
|
+
*
|
|
4
|
+
* Dispatch owns the public tool contract and auto-fix policy; this module owns
|
|
5
|
+
* one thread generation end to end: worktree setup/finalization, queue/process
|
|
6
|
+
* ownership, retained-session resume/fork, and guarded terminal publication.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { rm } from "node:fs/promises";
|
|
12
|
+
import { resolve } from "node:path";
|
|
13
|
+
import { discoverAgents, type AgentConfig } from "./agents.ts";
|
|
14
|
+
import { completionTriggersTurn, type CompletionMessageItem } from "./completion.ts";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_THINKING_LEVEL,
|
|
17
|
+
loadConfig,
|
|
18
|
+
type SubagentsConfig,
|
|
19
|
+
type ThinkingLevel,
|
|
20
|
+
} from "./config.ts";
|
|
21
|
+
import {
|
|
22
|
+
dispatchFailedResult,
|
|
23
|
+
failedStartResult,
|
|
24
|
+
formatCompletionBlock,
|
|
25
|
+
modelLevelTakeoverNote,
|
|
26
|
+
queuedResult,
|
|
27
|
+
} from "./format.ts";
|
|
28
|
+
import { shouldTriggerFixLoop } from "./fixloop.ts";
|
|
29
|
+
import {
|
|
30
|
+
availableModelsInScope,
|
|
31
|
+
currentModelRef,
|
|
32
|
+
findModelByRef,
|
|
33
|
+
modelRef,
|
|
34
|
+
resolveAgentModelRoute,
|
|
35
|
+
resolveThinkingLevel,
|
|
36
|
+
} from "./models.ts";
|
|
37
|
+
import { monitor } from "./monitor.ts";
|
|
38
|
+
import { persistRecoveryRecords, recoveryRecordFromFinalization } from "./recovery.ts";
|
|
39
|
+
import type { SubagentRuntime, SubagentThread, ThreadState } from "./runtime.ts";
|
|
40
|
+
import { forkRetainedSession } from "./session-fork.ts";
|
|
41
|
+
import {
|
|
42
|
+
buildResumePrompt,
|
|
43
|
+
RpcRunControl,
|
|
44
|
+
isFailedResult,
|
|
45
|
+
isModelLevelFailure,
|
|
46
|
+
runSingleAgentWithMainFallback,
|
|
47
|
+
type SingleResult,
|
|
48
|
+
type SubagentDetails,
|
|
49
|
+
type SubagentLiveEvent,
|
|
50
|
+
} from "./spawn.ts";
|
|
51
|
+
import {
|
|
52
|
+
createWorktreeIsolation,
|
|
53
|
+
type IsolationMode,
|
|
54
|
+
type WorktreeFinalization,
|
|
55
|
+
type WorktreeIsolation,
|
|
56
|
+
} from "./worktree.ts";
|
|
57
|
+
|
|
58
|
+
export const FORK_CONTINUATION_PROMPT =
|
|
59
|
+
"Continue from the retained context above. Review the prior work, then take the most useful next step toward completing the existing objective without repeating completed work.";
|
|
60
|
+
|
|
61
|
+
const WORKTREE_ISOLATION_INSTRUCTIONS =
|
|
62
|
+
"You are running in a temporary detached Git worktree. Work only in the current cwd; do not create another worktree or manually copy/apply changes to the original checkout. The parent dispatcher will integrate your tracked, deleted, and untracked changes when this thread finally settles.";
|
|
63
|
+
|
|
64
|
+
function withWorktreeSystemPrompt(agent: AgentConfig): AgentConfig {
|
|
65
|
+
return {
|
|
66
|
+
...agent,
|
|
67
|
+
systemPrompt: `${agent.systemPrompt.trimEnd()}\n\n${WORKTREE_ISOLATION_INSTRUCTIONS}`.trim(),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function isWorktreeCapableAgent(agent: AgentConfig): boolean {
|
|
72
|
+
if (agent.name === "explore" || agent.name === "reviewer") return false;
|
|
73
|
+
if (agent.name === "worker") return true;
|
|
74
|
+
if (!agent.tools) return true;
|
|
75
|
+
return agent.tools.includes("edit") || agent.tools.includes("write");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface DispatchEnvironment {
|
|
79
|
+
ctx: ExtensionContext;
|
|
80
|
+
config: SubagentsConfig;
|
|
81
|
+
agents: AgentConfig[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface DispatchModelRoute {
|
|
85
|
+
agent: AgentConfig;
|
|
86
|
+
mainFallbackRef?: string;
|
|
87
|
+
thinkingLevel: ThinkingLevel;
|
|
88
|
+
thinkingLevelForModel: (ref?: string) => ThinkingLevel;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function resolveDispatchModelRoute(
|
|
92
|
+
agent: AgentConfig,
|
|
93
|
+
config: SubagentsConfig,
|
|
94
|
+
ctx: ExtensionContext,
|
|
95
|
+
vision: boolean,
|
|
96
|
+
): DispatchModelRoute {
|
|
97
|
+
const availableModels = availableModelsInScope(ctx);
|
|
98
|
+
const mainRef = currentModelRef(ctx);
|
|
99
|
+
const route = resolveAgentModelRoute({
|
|
100
|
+
selectedRef: vision ? config.visionModel : config.agentModels[agent.name],
|
|
101
|
+
mainRef,
|
|
102
|
+
declaredDefaultRef: agent.model,
|
|
103
|
+
availableRefs: availableModels.map(modelRef),
|
|
104
|
+
});
|
|
105
|
+
const preferred = config.agentThinkingLevels[agent.name] ?? agent.thinking ?? DEFAULT_THINKING_LEVEL;
|
|
106
|
+
const thinkingLevelForModel = (ref?: string): ThinkingLevel => {
|
|
107
|
+
const model = ref === mainRef && ctx.model
|
|
108
|
+
? ctx.model
|
|
109
|
+
: findModelByRef(availableModels, ref);
|
|
110
|
+
return resolveThinkingLevel(model, preferred);
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
agent: { ...agent, model: route.primaryRef },
|
|
114
|
+
mainFallbackRef: route.mainFallbackRef,
|
|
115
|
+
thinkingLevel: thinkingLevelForModel(route.primaryRef),
|
|
116
|
+
thinkingLevelForModel,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface BackgroundDispatcherOptions extends DispatchEnvironment {
|
|
121
|
+
runtime: SubagentRuntime;
|
|
122
|
+
finishRun: (
|
|
123
|
+
runId: number,
|
|
124
|
+
status: "done" | "failed",
|
|
125
|
+
opts?: { silent?: boolean },
|
|
126
|
+
) => void;
|
|
127
|
+
makeLiveHandler: (
|
|
128
|
+
runId: number,
|
|
129
|
+
generation?: number,
|
|
130
|
+
) => (event: SubagentLiveEvent) => void;
|
|
131
|
+
makeDetails: (
|
|
132
|
+
mode: "single" | "parallel",
|
|
133
|
+
background?: boolean,
|
|
134
|
+
) => (results: SingleResult[]) => SubagentDetails;
|
|
135
|
+
startFixLoop: (
|
|
136
|
+
initialReviewerResult: SingleResult,
|
|
137
|
+
parentGroupId: string,
|
|
138
|
+
parentRunId: number,
|
|
139
|
+
executionCwd: string,
|
|
140
|
+
vision?: boolean,
|
|
141
|
+
) => void;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
type BackgroundStarter = (
|
|
145
|
+
agentName: string,
|
|
146
|
+
task: string,
|
|
147
|
+
cwd: string | undefined,
|
|
148
|
+
vision?: boolean,
|
|
149
|
+
isolation?: IsolationMode,
|
|
150
|
+
) => Promise<SingleResult>;
|
|
151
|
+
|
|
152
|
+
export function createBackgroundDispatcher(options: BackgroundDispatcherOptions): BackgroundStarter {
|
|
153
|
+
const {
|
|
154
|
+
runtime,
|
|
155
|
+
ctx,
|
|
156
|
+
config,
|
|
157
|
+
agents,
|
|
158
|
+
finishRun,
|
|
159
|
+
makeLiveHandler,
|
|
160
|
+
makeDetails,
|
|
161
|
+
startFixLoop,
|
|
162
|
+
} = options;
|
|
163
|
+
interface SessionSeed {
|
|
164
|
+
sessionId?: string;
|
|
165
|
+
sessionDir?: string;
|
|
166
|
+
prompt?: string;
|
|
167
|
+
worktree?: WorktreeIsolation;
|
|
168
|
+
forkedFromRunId?: number;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
interface ResumeReservation {
|
|
172
|
+
version: number;
|
|
173
|
+
generation: number;
|
|
174
|
+
sessionId?: string;
|
|
175
|
+
sessionDir?: string;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const ownsResumeReservation = (
|
|
179
|
+
thread: SubagentThread,
|
|
180
|
+
reservation: ResumeReservation,
|
|
181
|
+
): boolean =>
|
|
182
|
+
runtime.sessionActive &&
|
|
183
|
+
runtime.threads.get(thread.id) === thread &&
|
|
184
|
+
!thread.retired &&
|
|
185
|
+
thread.lifecycleOperation === "resume" &&
|
|
186
|
+
thread.lifecycleVersion === reservation.version &&
|
|
187
|
+
thread.generation === reservation.generation &&
|
|
188
|
+
thread.sessionId === reservation.sessionId &&
|
|
189
|
+
thread.sessionDir === reservation.sessionDir;
|
|
190
|
+
|
|
191
|
+
const beginPreflight = (): (() => void) => {
|
|
192
|
+
let resolvePreflight!: () => void;
|
|
193
|
+
const preflight = new Promise<void>((resolve) => {
|
|
194
|
+
resolvePreflight = resolve;
|
|
195
|
+
});
|
|
196
|
+
runtime.preflightOperations.add(preflight);
|
|
197
|
+
return () => {
|
|
198
|
+
runtime.preflightOperations.delete(preflight);
|
|
199
|
+
resolvePreflight();
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const startBackground = async (
|
|
204
|
+
agentName: string,
|
|
205
|
+
task: string,
|
|
206
|
+
cwd: string | undefined,
|
|
207
|
+
vision = false,
|
|
208
|
+
isolation: IsolationMode = "shared",
|
|
209
|
+
existingThread?: SubagentThread,
|
|
210
|
+
newObjectiveOnResume = false,
|
|
211
|
+
environment?: DispatchEnvironment,
|
|
212
|
+
seed?: SessionSeed,
|
|
213
|
+
resumeReservation?: ResumeReservation,
|
|
214
|
+
): Promise<SingleResult> => {
|
|
215
|
+
if (!runtime.sessionActive) {
|
|
216
|
+
return failedStartResult(agentName, task, "Parent session shut down before this subagent generation could start.");
|
|
217
|
+
}
|
|
218
|
+
if (existingThread && (!resumeReservation || !ownsResumeReservation(existingThread, resumeReservation))) {
|
|
219
|
+
return failedStartResult(agentName, task, `Run #${existingThread.id} changed while resume was preparing; no new generation was started.`);
|
|
220
|
+
}
|
|
221
|
+
const runCtx = environment?.ctx ?? ctx;
|
|
222
|
+
const runConfig = environment?.config ?? config;
|
|
223
|
+
const runAgents = environment?.agents ?? agents;
|
|
224
|
+
const agent = runAgents.find((candidate) => candidate.name === agentName);
|
|
225
|
+
if (!agent) return failedStartResult(agentName, task, `Unknown agent: "${agentName}".`);
|
|
226
|
+
if (isolation === "worktree" && !isWorktreeCapableAgent(agent)) {
|
|
227
|
+
return {
|
|
228
|
+
...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as worker or cleaner.`),
|
|
229
|
+
isolation,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const originalCwd = resolve(cwd ?? runCtx.cwd);
|
|
234
|
+
const previousWorktree = existingThread?.worktree;
|
|
235
|
+
let worktree = seed?.worktree ?? previousWorktree;
|
|
236
|
+
if (isolation === "worktree") {
|
|
237
|
+
if (worktree && worktree.state !== "active") {
|
|
238
|
+
return {
|
|
239
|
+
...failedStartResult(agentName, task, `Run #${existingThread?.id ?? "?"} has no active continuation worktree.`),
|
|
240
|
+
isolation,
|
|
241
|
+
integrationStatus: worktree.state === "finalizing" ? "pending" : worktree.state,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
if (!worktree) {
|
|
245
|
+
try {
|
|
246
|
+
worktree = await createWorktreeIsolation(originalCwd);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
return {
|
|
249
|
+
...failedStartResult(agentName, task, error instanceof Error ? error.message : String(error)),
|
|
250
|
+
isolation,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const executionCwd = worktree?.cwd ?? originalCwd;
|
|
256
|
+
const resolvedRoute = resolveDispatchModelRoute(agent, runConfig, runCtx, vision);
|
|
257
|
+
// Isolation is a persistent system-level invariant, not a one-shot task
|
|
258
|
+
// prefix: queued retargets, live retargets, resumes, and main-model
|
|
259
|
+
// handoffs all keep the same worktree boundary.
|
|
260
|
+
const route = isolation === "worktree"
|
|
261
|
+
? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
|
|
262
|
+
: resolvedRoute;
|
|
263
|
+
const thinkingLevel = route.thinkingLevel;
|
|
264
|
+
const priorTask = existingThread?.task;
|
|
265
|
+
const priorSessionId = seed?.sessionId ?? existingThread?.sessionId;
|
|
266
|
+
const priorSessionDir = seed?.sessionDir ?? existingThread?.sessionDir;
|
|
267
|
+
if (existingThread && resumeReservation && !ownsResumeReservation(existingThread, resumeReservation)) {
|
|
268
|
+
return failedStartResult(agentName, task, `Run #${existingThread.id} changed while resume was preparing; no new generation was started.`);
|
|
269
|
+
}
|
|
270
|
+
const runId = existingThread?.id ?? monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
271
|
+
isolation,
|
|
272
|
+
...(seed?.forkedFromRunId !== undefined ? { forkedFromRunId: seed.forkedFromRunId } : {}),
|
|
273
|
+
});
|
|
274
|
+
const generation = (existingThread?.generation ?? 0) + 1;
|
|
275
|
+
const pending: SingleResult = {
|
|
276
|
+
...queuedResult(route.agent, task, thinkingLevel),
|
|
277
|
+
runId,
|
|
278
|
+
projectCwd: originalCwd,
|
|
279
|
+
isolation,
|
|
280
|
+
...(isolation === "worktree" ? { integrationStatus: "pending" as const } : {}),
|
|
281
|
+
...(seed?.sessionId && seed.sessionDir
|
|
282
|
+
? { sessionId: seed.sessionId, sessionDir: seed.sessionDir }
|
|
283
|
+
: {}),
|
|
284
|
+
...(seed?.forkedFromRunId !== undefined ? { forkedFromRunId: seed.forkedFromRunId } : {}),
|
|
285
|
+
};
|
|
286
|
+
if (existingThread) {
|
|
287
|
+
monitor.restartRun(runId, agent.name, task, route.agent.model, thinkingLevel, isolation);
|
|
288
|
+
runtime.settledRuns.delete(runId);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
let thread!: SubagentThread;
|
|
292
|
+
const control = new RpcRunControl(task, generation, (phase) => {
|
|
293
|
+
if (runtime.threads.get(runId)?.generation !== generation || phase === "settled") return;
|
|
294
|
+
const state: ThreadState =
|
|
295
|
+
phase === "queued" || phase === "starting"
|
|
296
|
+
? "queued"
|
|
297
|
+
: phase === "steering"
|
|
298
|
+
? "steering"
|
|
299
|
+
: phase === "interrupting"
|
|
300
|
+
? "interrupting"
|
|
301
|
+
: phase === "parked"
|
|
302
|
+
? "parked"
|
|
303
|
+
: phase === "stopped"
|
|
304
|
+
? "stopped"
|
|
305
|
+
: "running";
|
|
306
|
+
thread.state = state;
|
|
307
|
+
if (state === "queued") monitor.setStatus(runId, "queued");
|
|
308
|
+
else if (state === "steering") monitor.setStatus(runId, "steering");
|
|
309
|
+
else if (state === "interrupting") monitor.setStatus(runId, "interrupting");
|
|
310
|
+
else if (state === "parked") monitor.setStatus(runId, "parked");
|
|
311
|
+
else if (state === "running") monitor.setStatus(runId, "running");
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
if (existingThread) {
|
|
316
|
+
thread = existingThread;
|
|
317
|
+
thread.generation = generation;
|
|
318
|
+
thread.agentName = agent.name;
|
|
319
|
+
thread.task = task;
|
|
320
|
+
thread.cwd = originalCwd;
|
|
321
|
+
thread.executionCwd = executionCwd;
|
|
322
|
+
thread.vision = vision;
|
|
323
|
+
thread.thinkingLevel = thinkingLevel;
|
|
324
|
+
thread.isolation = isolation;
|
|
325
|
+
thread.worktree = worktree;
|
|
326
|
+
thread.state = "queued";
|
|
327
|
+
thread.control = control;
|
|
328
|
+
// A newly admitted generation owns no output yet. Keeping the prior
|
|
329
|
+
// generation here would make a queued stop publish stale task,
|
|
330
|
+
// session metadata as this generation's partial.
|
|
331
|
+
thread.lastResult = undefined;
|
|
332
|
+
if (seed?.sessionId && seed.sessionDir) {
|
|
333
|
+
thread.sessionId = seed.sessionId;
|
|
334
|
+
thread.sessionDir = seed.sessionDir;
|
|
335
|
+
}
|
|
336
|
+
thread.retireOnSettle = false;
|
|
337
|
+
thread.isolationFailureNotified = false;
|
|
338
|
+
} else {
|
|
339
|
+
thread = {
|
|
340
|
+
id: runId,
|
|
341
|
+
generation,
|
|
342
|
+
agentName: agent.name,
|
|
343
|
+
task,
|
|
344
|
+
cwd: originalCwd,
|
|
345
|
+
executionCwd,
|
|
346
|
+
vision,
|
|
347
|
+
thinkingLevel,
|
|
348
|
+
isolation,
|
|
349
|
+
worktree,
|
|
350
|
+
state: "queued",
|
|
351
|
+
control,
|
|
352
|
+
generationCompletion: Promise.resolve(),
|
|
353
|
+
lifecycleVersion: 0,
|
|
354
|
+
sessionId: seed?.sessionId,
|
|
355
|
+
sessionDir: seed?.sessionDir,
|
|
356
|
+
forkedFromRunId: seed?.forkedFromRunId,
|
|
357
|
+
forkChildRunIds: [],
|
|
358
|
+
park: async () => {
|
|
359
|
+
throw new Error("Thread park was not initialized.");
|
|
360
|
+
},
|
|
361
|
+
resume: async () => failedStartResult(agent.name, task, "Thread resume was not initialized."),
|
|
362
|
+
fork: async () => failedStartResult(agent.name, task, "Thread fork was not initialized."),
|
|
363
|
+
finalizeIsolation: async () => undefined,
|
|
364
|
+
};
|
|
365
|
+
runtime.threads.set(runId, thread);
|
|
366
|
+
}
|
|
367
|
+
thread.notifyIsolationFailure = (finalization) => {
|
|
368
|
+
const paths = [finalization.worktreePath, finalization.patchPath].filter(Boolean).join(" · ");
|
|
369
|
+
runCtx.ui.notify(
|
|
370
|
+
`✗ ${agent.name} worktree ${finalization.integrated ? "cleanup" : "integration"} failed${paths ? ` · retained ${paths}` : ""}: ${finalization.error ?? "unknown Git integration error"}`,
|
|
371
|
+
"error",
|
|
372
|
+
);
|
|
373
|
+
};
|
|
374
|
+
thread.finalizeIsolation = async (
|
|
375
|
+
expectedGeneration: number,
|
|
376
|
+
result?: SingleResult,
|
|
377
|
+
): Promise<WorktreeFinalization | undefined> => {
|
|
378
|
+
if (thread.isolation !== "worktree" || !thread.worktree) return undefined;
|
|
379
|
+
if (thread.generation !== expectedGeneration) return undefined;
|
|
380
|
+
const finalization = await thread.worktree.finalize();
|
|
381
|
+
monitor.setIsolation(runId, "worktree", finalization.status);
|
|
382
|
+
if (result) {
|
|
383
|
+
result.runId = runId;
|
|
384
|
+
result.isolation = "worktree";
|
|
385
|
+
result.integrationStatus = finalization.status;
|
|
386
|
+
result.integrationApplied = finalization.integrated;
|
|
387
|
+
result.integrationError = finalization.error;
|
|
388
|
+
result.integrationWorktreePath = finalization.worktreePath;
|
|
389
|
+
result.integrationPatchPath = finalization.patchPath;
|
|
390
|
+
result.forkedFromRunId = thread.forkedFromRunId;
|
|
391
|
+
result.forkChildRunIds = [...thread.forkChildRunIds];
|
|
392
|
+
if (finalization.status === "retained") {
|
|
393
|
+
const retained = [
|
|
394
|
+
finalization.worktreePath ? `worktree ${finalization.worktreePath}` : undefined,
|
|
395
|
+
finalization.patchPath ? `patch ${finalization.patchPath}` : undefined,
|
|
396
|
+
].filter(Boolean).join(", ");
|
|
397
|
+
const integrationMessage = finalization.integrated
|
|
398
|
+
? `Worktree changes were applied, but cleanup failed${retained ? `; retained ${retained}` : ""}: ${finalization.error ?? "unknown Git cleanup error"}`
|
|
399
|
+
: `Worktree integration failed${retained ? `; retained ${retained}` : ""}: ${finalization.error ?? "unknown Git integration error"}`;
|
|
400
|
+
result.exitCode = 1;
|
|
401
|
+
result.stopReason = "error";
|
|
402
|
+
result.errorMessage = result.errorMessage
|
|
403
|
+
? `${result.errorMessage}\n${integrationMessage}`
|
|
404
|
+
: integrationMessage;
|
|
405
|
+
result.stderr = result.stderr ? `${result.stderr.trimEnd()}\n${integrationMessage}` : integrationMessage;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (finalization.status === "retained") {
|
|
409
|
+
if (!thread.isolationFailureNotified) {
|
|
410
|
+
thread.isolationFailureNotified = true;
|
|
411
|
+
try {
|
|
412
|
+
thread.notifyIsolationFailure?.(finalization);
|
|
413
|
+
} catch {
|
|
414
|
+
/* notification failures do not hide retained artifacts */
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return finalization;
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
const cleanupTrackedSessionDir = async (sessionDir: string, action: string): Promise<void> => {
|
|
422
|
+
try {
|
|
423
|
+
await rm(sessionDir, { recursive: true, force: true });
|
|
424
|
+
runtime.sessionDirs.delete(sessionDir);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
// Keep ownership so shutdown can retry; losing the path here leaks a
|
|
427
|
+
// cloned session containing retained model context on Windows locks.
|
|
428
|
+
try {
|
|
429
|
+
runCtx.ui.notify(
|
|
430
|
+
`✗ ${action}; retained ${sessionDir} for shutdown cleanup: ${error instanceof Error ? error.message : String(error)}`,
|
|
431
|
+
"error",
|
|
432
|
+
);
|
|
433
|
+
} catch {
|
|
434
|
+
/* cleanup ownership remains tracked even if the UI is unavailable */
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
const discardUnusedWorktree = async (candidate: WorktreeIsolation | undefined): Promise<void> => {
|
|
440
|
+
if (!candidate) return;
|
|
441
|
+
try {
|
|
442
|
+
await candidate.discard();
|
|
443
|
+
} catch (error) {
|
|
444
|
+
const retainedPath = existsSync(candidate.worktreePath)
|
|
445
|
+
? candidate.worktreePath
|
|
446
|
+
: existsSync(candidate.tempDir)
|
|
447
|
+
? candidate.tempDir
|
|
448
|
+
: undefined;
|
|
449
|
+
const finalization: WorktreeFinalization = {
|
|
450
|
+
status: "retained",
|
|
451
|
+
integrated: false,
|
|
452
|
+
hadChanges: false,
|
|
453
|
+
...(retainedPath ? { worktreePath: retainedPath } : {}),
|
|
454
|
+
...(existsSync(candidate.patchPath) ? { patchPath: candidate.patchPath } : {}),
|
|
455
|
+
error: `Discarding unused continuation failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
456
|
+
};
|
|
457
|
+
await persistRecoveryRecords(runtime.configPath, [
|
|
458
|
+
recoveryRecordFromFinalization(runId, finalization),
|
|
459
|
+
]).catch(() => undefined);
|
|
460
|
+
try {
|
|
461
|
+
thread.notifyIsolationFailure?.(finalization);
|
|
462
|
+
} catch {
|
|
463
|
+
/* parent UI may already be shutting down */
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
const createContinuationWorktree = async (
|
|
469
|
+
source: WorktreeIsolation,
|
|
470
|
+
seedIsIntegrated: boolean,
|
|
471
|
+
): Promise<WorktreeIsolation> => {
|
|
472
|
+
if (source.state === "finalizing") {
|
|
473
|
+
throw new Error(`Run #${runId}'s worktree is still finalizing.`);
|
|
474
|
+
}
|
|
475
|
+
const seedCheckpoint = await source.snapshotCheckpoint();
|
|
476
|
+
return createWorktreeIsolation(thread.cwd, {
|
|
477
|
+
seedCheckpoint,
|
|
478
|
+
seedIsIntegrated,
|
|
479
|
+
});
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
thread.park = async (): Promise<"queued" | "active"> => {
|
|
483
|
+
if (thread.retired) throw new Error(`Run #${runId} was retired by subagent_stop.`);
|
|
484
|
+
if (thread.lifecycleOperation) throw new Error(`Run #${runId} is already handling ${thread.lifecycleOperation}.`);
|
|
485
|
+
if (thread.state === "parked") return "active";
|
|
486
|
+
const phase = thread.control.getPhase();
|
|
487
|
+
const queued = thread.state === "queued" && phase === "queued";
|
|
488
|
+
if (
|
|
489
|
+
!queued &&
|
|
490
|
+
((phase === "settled" && thread.state !== "running") ||
|
|
491
|
+
!["starting", "running", "steering", "interrupting", "retrying", "settled"].includes(phase))
|
|
492
|
+
) {
|
|
493
|
+
throw new Error(`Run #${runId} is ${thread.state}; only active work can be parked.`);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const version = ++thread.lifecycleVersion;
|
|
497
|
+
const generation = thread.generation;
|
|
498
|
+
const completion = thread.generationCompletion;
|
|
499
|
+
const controller = thread.queueController;
|
|
500
|
+
thread.lifecycleOperation = "park";
|
|
501
|
+
try {
|
|
502
|
+
if (queued) {
|
|
503
|
+
thread.control.parkPending();
|
|
504
|
+
runtime.backgroundQueue.cancel(controller);
|
|
505
|
+
} else {
|
|
506
|
+
await thread.control.park();
|
|
507
|
+
// Auto-fix orchestration has no live RPC attempt once its parent
|
|
508
|
+
// review settled, so cancel its queue owner explicitly.
|
|
509
|
+
if (phase === "settled") runtime.backgroundQueue.cancel(controller);
|
|
510
|
+
}
|
|
511
|
+
await completion;
|
|
512
|
+
if (
|
|
513
|
+
thread.generation !== generation ||
|
|
514
|
+
thread.lifecycleVersion !== version ||
|
|
515
|
+
thread.lifecycleOperation !== "park"
|
|
516
|
+
) {
|
|
517
|
+
throw new Error(`Run #${runId} changed while parking.`);
|
|
518
|
+
}
|
|
519
|
+
thread.state = "parked";
|
|
520
|
+
thread.queueController = undefined;
|
|
521
|
+
runtime.runControllers.delete(runId);
|
|
522
|
+
monitor.setStatus(runId, "parked");
|
|
523
|
+
return queued ? "queued" : "active";
|
|
524
|
+
} finally {
|
|
525
|
+
if (thread.lifecycleVersion === version && thread.lifecycleOperation === "park") {
|
|
526
|
+
thread.lifecycleOperation = undefined;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
thread.resume = async (objective?: string, resumeCtx?: ExtensionContext): Promise<SingleResult> => {
|
|
532
|
+
const requestedObjective = objective?.trim();
|
|
533
|
+
if (!runtime.sessionActive || runtime.threads.get(runId) !== thread) {
|
|
534
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} belongs to a parent session that has shut down.`);
|
|
535
|
+
}
|
|
536
|
+
if (objective !== undefined && !requestedObjective) {
|
|
537
|
+
return failedStartResult(thread.agentName, thread.task, "resume objective must be non-blank when provided.");
|
|
538
|
+
}
|
|
539
|
+
if (thread.retired) return failedStartResult(thread.agentName, thread.task, `Run #${runId} was retired by subagent_stop.`);
|
|
540
|
+
if (thread.lifecycleOperation) {
|
|
541
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} is already ${thread.lifecycleOperation === "resume" ? "resuming" : "being forked"}.`);
|
|
542
|
+
}
|
|
543
|
+
if (!["parked", "completed", "failed"].includes(thread.state)) {
|
|
544
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} is ${thread.state}; it must be parked or settled before resume.`);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// Lifecycle CAS: claim synchronously before the first await, then cancel
|
|
548
|
+
// and fully quiesce any superseded queue/process before cloning or
|
|
549
|
+
// reusing its session. A second resume/fork sees this claim immediately.
|
|
550
|
+
const previousState = thread.state;
|
|
551
|
+
const previousSessionId = thread.sessionId;
|
|
552
|
+
const previousSessionDir = thread.sessionDir;
|
|
553
|
+
const previousExecutionCwd = thread.executionCwd;
|
|
554
|
+
const reservation: ResumeReservation = {
|
|
555
|
+
version: ++thread.lifecycleVersion,
|
|
556
|
+
generation: thread.generation,
|
|
557
|
+
sessionId: previousSessionId,
|
|
558
|
+
sessionDir: previousSessionDir,
|
|
559
|
+
};
|
|
560
|
+
thread.lifecycleOperation = "resume";
|
|
561
|
+
thread.state = "resuming";
|
|
562
|
+
const finishPreflight = beginPreflight();
|
|
563
|
+
const supersededController = thread.queueController;
|
|
564
|
+
runtime.backgroundQueue.cancel(supersededController);
|
|
565
|
+
runtime.runControllers.delete(runId);
|
|
566
|
+
|
|
567
|
+
let continuationWorktree: WorktreeIsolation | undefined;
|
|
568
|
+
let clonedSession: Awaited<ReturnType<typeof forkRetainedSession>> | undefined;
|
|
569
|
+
try {
|
|
570
|
+
await thread.generationCompletion;
|
|
571
|
+
if (!ownsResumeReservation(thread, reservation)) {
|
|
572
|
+
return failedStartResult(
|
|
573
|
+
thread.agentName,
|
|
574
|
+
thread.task,
|
|
575
|
+
thread.retired
|
|
576
|
+
? `Run #${runId} was retired by subagent_stop; no new generation was started.`
|
|
577
|
+
: `Run #${runId} changed while resume was preparing; no new generation was started.`,
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
thread.state = "resuming";
|
|
581
|
+
const currentCtx = resumeCtx ?? runCtx;
|
|
582
|
+
let seed: SessionSeed | undefined;
|
|
583
|
+
if (thread.isolation === "worktree" && thread.worktree?.state !== "active") {
|
|
584
|
+
if (!thread.worktree) throw new Error(`Run #${runId} has no isolated worktree checkpoint.`);
|
|
585
|
+
const seedAlreadyIntegrated =
|
|
586
|
+
thread.worktree.state === "integrated" ||
|
|
587
|
+
thread.worktree.state === "no_changes" ||
|
|
588
|
+
thread.lastResult?.integrationApplied === true;
|
|
589
|
+
continuationWorktree = await createContinuationWorktree(thread.worktree, seedAlreadyIntegrated);
|
|
590
|
+
if (!ownsResumeReservation(thread, reservation)) {
|
|
591
|
+
throw new Error(`Run #${runId} changed while its continuation worktree was being created.`);
|
|
592
|
+
}
|
|
593
|
+
seed = { worktree: continuationWorktree };
|
|
594
|
+
if (previousSessionId && previousSessionDir) {
|
|
595
|
+
clonedSession = await forkRetainedSession({
|
|
596
|
+
cwd: previousExecutionCwd,
|
|
597
|
+
targetCwd: continuationWorktree.cwd,
|
|
598
|
+
sessionDir: previousSessionDir,
|
|
599
|
+
sessionId: previousSessionId,
|
|
600
|
+
});
|
|
601
|
+
runtime.sessionDirs.add(clonedSession.sessionDir);
|
|
602
|
+
if (!ownsResumeReservation(thread, reservation)) {
|
|
603
|
+
throw new Error(`Run #${runId} changed while its retained session was being cloned.`);
|
|
604
|
+
}
|
|
605
|
+
seed.sessionId = clonedSession.sessionId;
|
|
606
|
+
seed.sessionDir = clonedSession.sessionDir;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const currentConfig = await loadConfig(runtime.configPath);
|
|
611
|
+
if (!ownsResumeReservation(thread, reservation)) {
|
|
612
|
+
throw new Error(`Run #${runId} changed while resume configuration was loading.`);
|
|
613
|
+
}
|
|
614
|
+
runtime.backgroundQueue.setConcurrency(currentConfig.maxConcurrency);
|
|
615
|
+
const currentAgents = discoverAgents(currentCtx.cwd, {
|
|
616
|
+
scope: currentConfig.agentScope,
|
|
617
|
+
enabledNames: currentConfig.enabledAgents,
|
|
618
|
+
projectTrusted: currentCtx.isProjectTrusted?.() === true,
|
|
619
|
+
}).agents;
|
|
620
|
+
const nextTask = requestedObjective ?? thread.task;
|
|
621
|
+
const pending = await startBackground(
|
|
622
|
+
thread.agentName,
|
|
623
|
+
nextTask,
|
|
624
|
+
thread.cwd,
|
|
625
|
+
thread.vision,
|
|
626
|
+
thread.isolation,
|
|
627
|
+
thread,
|
|
628
|
+
objective !== undefined,
|
|
629
|
+
{
|
|
630
|
+
ctx: currentCtx,
|
|
631
|
+
config: currentConfig,
|
|
632
|
+
agents: currentAgents,
|
|
633
|
+
},
|
|
634
|
+
seed,
|
|
635
|
+
reservation,
|
|
636
|
+
);
|
|
637
|
+
if (pending.exitCode !== -1) {
|
|
638
|
+
if (clonedSession) {
|
|
639
|
+
await cleanupTrackedSessionDir(
|
|
640
|
+
clonedSession.sessionDir,
|
|
641
|
+
`Could not discard failed resume session clone for run #${runId}`,
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
await discardUnusedWorktree(continuationWorktree);
|
|
645
|
+
if (ownsResumeReservation(thread, reservation)) thread.state = previousState;
|
|
646
|
+
return pending;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// The cloned branch replaces the removed-worktree session for this
|
|
650
|
+
// logical id. Keep an undeletable old dir in runtime cleanup if needed.
|
|
651
|
+
if (clonedSession && previousSessionDir && previousSessionDir !== clonedSession.sessionDir) {
|
|
652
|
+
try {
|
|
653
|
+
await rm(previousSessionDir, { recursive: true, force: true });
|
|
654
|
+
runtime.sessionDirs.delete(previousSessionDir);
|
|
655
|
+
} catch {
|
|
656
|
+
/* shutdown retries cleanup of the old retained branch */
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
return pending;
|
|
660
|
+
} catch (error) {
|
|
661
|
+
if (clonedSession) {
|
|
662
|
+
await cleanupTrackedSessionDir(
|
|
663
|
+
clonedSession.sessionDir,
|
|
664
|
+
`Could not discard interrupted resume session clone for run #${runId}`,
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
await discardUnusedWorktree(continuationWorktree);
|
|
668
|
+
if (ownsResumeReservation(thread, reservation)) {
|
|
669
|
+
thread.state = previousState;
|
|
670
|
+
thread.sessionId = previousSessionId;
|
|
671
|
+
thread.sessionDir = previousSessionDir;
|
|
672
|
+
thread.executionCwd = previousExecutionCwd;
|
|
673
|
+
}
|
|
674
|
+
return failedStartResult(
|
|
675
|
+
thread.agentName,
|
|
676
|
+
requestedObjective ?? thread.task,
|
|
677
|
+
`Could not resume run #${runId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
678
|
+
);
|
|
679
|
+
} finally {
|
|
680
|
+
finishPreflight();
|
|
681
|
+
if (
|
|
682
|
+
thread.lifecycleOperation === "resume" &&
|
|
683
|
+
thread.lifecycleVersion === reservation.version
|
|
684
|
+
) {
|
|
685
|
+
thread.lifecycleOperation = undefined;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
thread.fork = async (objective?: string, forkCtx?: ExtensionContext): Promise<SingleResult> => {
|
|
691
|
+
const forkObjective = objective?.trim();
|
|
692
|
+
if (!runtime.sessionActive || runtime.threads.get(runId) !== thread) {
|
|
693
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} belongs to a parent session that has shut down.`);
|
|
694
|
+
}
|
|
695
|
+
if (objective !== undefined && !forkObjective) {
|
|
696
|
+
return failedStartResult(thread.agentName, thread.task, "fork objective must be non-blank when provided.");
|
|
697
|
+
}
|
|
698
|
+
if (thread.retired || thread.state === "stopped") {
|
|
699
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} was retired by subagent_stop and cannot be forked.`);
|
|
700
|
+
}
|
|
701
|
+
if (thread.lifecycleOperation) {
|
|
702
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} is already ${thread.lifecycleOperation === "resume" ? "resuming" : "being forked"}.`);
|
|
703
|
+
}
|
|
704
|
+
if (thread.state === "queued" && !thread.sessionId) {
|
|
705
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} is queued and has no retained session to fork.`);
|
|
706
|
+
}
|
|
707
|
+
if (["queued", "running", "steering", "interrupting"].includes(thread.state)) {
|
|
708
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} is active; park it first with subagent_control { action: "park", id: ${runId} }, then fork the stable session.`);
|
|
709
|
+
}
|
|
710
|
+
if (!["parked", "completed", "failed"].includes(thread.state)) {
|
|
711
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} is ${thread.state} and has no forkable retained checkpoint.`);
|
|
712
|
+
}
|
|
713
|
+
if (!thread.sessionId || !thread.sessionDir) {
|
|
714
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} has no retained session to fork (it may have been parked before starting).`);
|
|
715
|
+
}
|
|
716
|
+
if (thread.isolation === "worktree") {
|
|
717
|
+
const worktreeState = thread.worktree?.state;
|
|
718
|
+
const seedIntegrated =
|
|
719
|
+
worktreeState === "integrated" ||
|
|
720
|
+
worktreeState === "no_changes" ||
|
|
721
|
+
thread.lastResult?.integrationApplied === true;
|
|
722
|
+
if (!seedIntegrated) {
|
|
723
|
+
return failedStartResult(
|
|
724
|
+
thread.agentName,
|
|
725
|
+
thread.task,
|
|
726
|
+
`Run #${runId}'s isolated checkpoint has not been integrated. Resume and settle it before forking so its seed is applied exactly once.`,
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// Same lifecycle CAS as resume: a concurrent resume/fork cannot consume
|
|
732
|
+
// or clone this session while the branch copy is in progress.
|
|
733
|
+
const forkVersion = ++thread.lifecycleVersion;
|
|
734
|
+
const forkGeneration = thread.generation;
|
|
735
|
+
const forkSessionId = thread.sessionId;
|
|
736
|
+
const forkSessionDir = thread.sessionDir;
|
|
737
|
+
const ownsFork = (): boolean =>
|
|
738
|
+
runtime.sessionActive &&
|
|
739
|
+
runtime.threads.get(runId) === thread &&
|
|
740
|
+
!thread.retired &&
|
|
741
|
+
thread.lifecycleOperation === "fork" &&
|
|
742
|
+
thread.lifecycleVersion === forkVersion &&
|
|
743
|
+
thread.generation === forkGeneration &&
|
|
744
|
+
thread.sessionId === forkSessionId &&
|
|
745
|
+
thread.sessionDir === forkSessionDir;
|
|
746
|
+
thread.lifecycleOperation = "fork";
|
|
747
|
+
const finishPreflight = beginPreflight();
|
|
748
|
+
let childWorktree: WorktreeIsolation | undefined;
|
|
749
|
+
let forkedSession: Awaited<ReturnType<typeof forkRetainedSession>> | undefined;
|
|
750
|
+
try {
|
|
751
|
+
await thread.generationCompletion;
|
|
752
|
+
if (!ownsFork()) {
|
|
753
|
+
return failedStartResult(thread.agentName, thread.task, `Run #${runId} changed while fork was preparing; no child was started.`);
|
|
754
|
+
}
|
|
755
|
+
const currentCtx = forkCtx ?? runCtx;
|
|
756
|
+
if (thread.isolation === "worktree") {
|
|
757
|
+
if (!thread.worktree) throw new Error(`Run #${runId} has no isolated worktree checkpoint.`);
|
|
758
|
+
const seedAlreadyIntegrated =
|
|
759
|
+
thread.worktree.state === "integrated" ||
|
|
760
|
+
thread.worktree.state === "no_changes" ||
|
|
761
|
+
thread.lastResult?.integrationApplied === true;
|
|
762
|
+
childWorktree = await createContinuationWorktree(thread.worktree, seedAlreadyIntegrated);
|
|
763
|
+
if (!ownsFork()) throw new Error(`Run #${runId} changed while its fork worktree was being created.`);
|
|
764
|
+
}
|
|
765
|
+
forkedSession = await forkRetainedSession({
|
|
766
|
+
cwd: thread.executionCwd,
|
|
767
|
+
targetCwd: childWorktree?.cwd ?? thread.cwd,
|
|
768
|
+
sessionDir: thread.sessionDir,
|
|
769
|
+
sessionId: thread.sessionId,
|
|
770
|
+
});
|
|
771
|
+
runtime.sessionDirs.add(forkedSession.sessionDir);
|
|
772
|
+
if (!ownsFork()) throw new Error(`Run #${runId} changed while its retained session was being forked.`);
|
|
773
|
+
const currentConfig = await loadConfig(runtime.configPath);
|
|
774
|
+
if (!ownsFork()) throw new Error(`Run #${runId} changed while fork configuration was loading.`);
|
|
775
|
+
runtime.backgroundQueue.setConcurrency(currentConfig.maxConcurrency);
|
|
776
|
+
const currentAgents = discoverAgents(currentCtx.cwd, {
|
|
777
|
+
scope: currentConfig.agentScope,
|
|
778
|
+
enabledNames: currentConfig.enabledAgents,
|
|
779
|
+
projectTrusted: currentCtx.isProjectTrusted?.() === true,
|
|
780
|
+
}).agents;
|
|
781
|
+
if (!ownsFork()) throw new Error(`Run #${runId} changed while fork was preparing; no child was started.`);
|
|
782
|
+
const childTask = forkObjective ?? thread.task;
|
|
783
|
+
const child = await startBackground(
|
|
784
|
+
thread.agentName,
|
|
785
|
+
childTask,
|
|
786
|
+
thread.cwd,
|
|
787
|
+
thread.vision,
|
|
788
|
+
thread.isolation,
|
|
789
|
+
undefined,
|
|
790
|
+
false,
|
|
791
|
+
{
|
|
792
|
+
ctx: currentCtx,
|
|
793
|
+
config: currentConfig,
|
|
794
|
+
agents: currentAgents,
|
|
795
|
+
},
|
|
796
|
+
{
|
|
797
|
+
sessionId: forkedSession.sessionId,
|
|
798
|
+
sessionDir: forkedSession.sessionDir,
|
|
799
|
+
prompt: forkObjective ?? FORK_CONTINUATION_PROMPT,
|
|
800
|
+
worktree: childWorktree,
|
|
801
|
+
forkedFromRunId: runId,
|
|
802
|
+
},
|
|
803
|
+
);
|
|
804
|
+
if (child.exitCode !== -1 || child.runId === undefined) {
|
|
805
|
+
await cleanupTrackedSessionDir(
|
|
806
|
+
forkedSession.sessionDir,
|
|
807
|
+
`Could not discard failed fork session clone for run #${runId}`,
|
|
808
|
+
);
|
|
809
|
+
await discardUnusedWorktree(childWorktree);
|
|
810
|
+
return child;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// Once the independent child is enqueued it remains valid even if the
|
|
814
|
+
// source is retired; just skip source-side relationship mutation.
|
|
815
|
+
if (!ownsFork()) return child;
|
|
816
|
+
const childRunId = child.runId;
|
|
817
|
+
if (!thread.forkChildRunIds.includes(childRunId)) thread.forkChildRunIds.push(childRunId);
|
|
818
|
+
const childThread = runtime.threads.get(childRunId);
|
|
819
|
+
if (childThread) childThread.forkedFromRunId = runId;
|
|
820
|
+
monitor.setForkRelation(runId, childRunId);
|
|
821
|
+
const sourceResult = runtime.settledRuns.get(runId) ?? thread.lastResult;
|
|
822
|
+
if (sourceResult) sourceResult.forkChildRunIds = [...thread.forkChildRunIds];
|
|
823
|
+
return child;
|
|
824
|
+
} catch (error) {
|
|
825
|
+
if (forkedSession) {
|
|
826
|
+
await cleanupTrackedSessionDir(
|
|
827
|
+
forkedSession.sessionDir,
|
|
828
|
+
`Could not discard interrupted fork session clone for run #${runId}`,
|
|
829
|
+
);
|
|
830
|
+
}
|
|
831
|
+
await discardUnusedWorktree(childWorktree);
|
|
832
|
+
return failedStartResult(
|
|
833
|
+
thread.agentName,
|
|
834
|
+
forkObjective ?? thread.task,
|
|
835
|
+
`Could not fork retained session for run #${runId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
836
|
+
);
|
|
837
|
+
} finally {
|
|
838
|
+
finishPreflight();
|
|
839
|
+
if (thread.lifecycleVersion === forkVersion && thread.lifecycleOperation === "fork") {
|
|
840
|
+
thread.lifecycleOperation = undefined;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
|
|
845
|
+
const onLive = makeLiveHandler(runId, generation);
|
|
846
|
+
const queueController = runtime.backgroundQueue.enqueue(
|
|
847
|
+
async (backgroundSignal) => {
|
|
848
|
+
if (runtime.threads.get(runId)?.generation !== generation) return;
|
|
849
|
+
let result: SingleResult;
|
|
850
|
+
try {
|
|
851
|
+
result = await runSingleAgentWithMainFallback(
|
|
852
|
+
{
|
|
853
|
+
defaultCwd: executionCwd,
|
|
854
|
+
agent: route.agent,
|
|
855
|
+
agentName,
|
|
856
|
+
task,
|
|
857
|
+
cwd: executionCwd,
|
|
858
|
+
thinkingLevel,
|
|
859
|
+
thinkingLevelForModel: route.thinkingLevelForModel,
|
|
860
|
+
signal: backgroundSignal,
|
|
861
|
+
onLive,
|
|
862
|
+
control,
|
|
863
|
+
makeDetails: makeDetails("single", true),
|
|
864
|
+
idleTimeoutMs: runConfig.idleTimeoutSec * 1000,
|
|
865
|
+
...(priorSessionId && priorSessionDir
|
|
866
|
+
? {
|
|
867
|
+
sessionId: priorSessionId,
|
|
868
|
+
sessionDir: priorSessionDir,
|
|
869
|
+
stdinText: seed?.prompt ?? (newObjectiveOnResume
|
|
870
|
+
? task
|
|
871
|
+
: buildResumePrompt(priorTask ?? task, "the retained thread was resumed")),
|
|
872
|
+
}
|
|
873
|
+
: {}),
|
|
874
|
+
},
|
|
875
|
+
route.mainFallbackRef,
|
|
876
|
+
);
|
|
877
|
+
} catch (error) {
|
|
878
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
879
|
+
result = {
|
|
880
|
+
...pending,
|
|
881
|
+
task: control.getObjective(),
|
|
882
|
+
exitCode: 1,
|
|
883
|
+
stderr: errorMessage,
|
|
884
|
+
stopReason: backgroundSignal.aborted ? "aborted" : "error",
|
|
885
|
+
errorMessage,
|
|
886
|
+
dispatchFailed: true,
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// A stale process/generation may finish after a park/resume race. It owns
|
|
891
|
+
// no monitor mutation, result registration, or completion delivery.
|
|
892
|
+
if (runtime.threads.get(runId)?.generation !== generation) return;
|
|
893
|
+
result.runId = runId;
|
|
894
|
+
result.projectCwd = originalCwd;
|
|
895
|
+
result.isolation = isolation;
|
|
896
|
+
result.forkedFromRunId = thread.forkedFromRunId;
|
|
897
|
+
result.forkChildRunIds = [...thread.forkChildRunIds];
|
|
898
|
+
thread.queueController = undefined;
|
|
899
|
+
runtime.runControllers.delete(runId);
|
|
900
|
+
thread.task = result.task;
|
|
901
|
+
thread.sessionId = result.sessionId;
|
|
902
|
+
thread.sessionDir = result.sessionDir;
|
|
903
|
+
thread.lastResult = result;
|
|
904
|
+
runtime.retainSession(result);
|
|
905
|
+
monitor.setModel(runId, result.model, result.modelFallbackFrom);
|
|
906
|
+
monitor.setThinking(runId, result.thinking);
|
|
907
|
+
|
|
908
|
+
// Destructive stop owns publication once it has synchronously claimed
|
|
909
|
+
// the lifecycle. Leave the partial result/session on the thread; the
|
|
910
|
+
// stop path waits for this queue task, finalizes isolation, and emits
|
|
911
|
+
// exactly one aborted result.
|
|
912
|
+
if (thread.lifecycleOperation === "stop") return;
|
|
913
|
+
|
|
914
|
+
if (result.parked) {
|
|
915
|
+
thread.state = "parked";
|
|
916
|
+
monitor.setStatus(runId, "parked");
|
|
917
|
+
runtime.settledRuns.delete(runId);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
if (thread.retireOnSettle) runtime.retireThreadSession(thread);
|
|
922
|
+
const wantsFixLoop = shouldTriggerFixLoop(result, runConfig);
|
|
923
|
+
if (wantsFixLoop && isolation === "shared" && runtime.sessionActive) {
|
|
924
|
+
thread.state = "running";
|
|
925
|
+
// The review being done does not mean the logical run is over:
|
|
926
|
+
// the same row now represents the chain until it resolves.
|
|
927
|
+
monitor.setStatus(runId, "running");
|
|
928
|
+
monitor.setActivity(runId, "auto-fix chain running");
|
|
929
|
+
startFixLoop(result, `fix-${runId}`, runId, thread.executionCwd, vision);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
// Claim terminal settlement synchronously before the first slow await.
|
|
933
|
+
// Park therefore either wins while RPC is still active, or is rejected
|
|
934
|
+
// once settlement owns the generation. Destructive stop may supersede
|
|
935
|
+
// this reservation; publication is revalidated after Git finalization.
|
|
936
|
+
const settlementVersion = ++thread.lifecycleVersion;
|
|
937
|
+
thread.lifecycleOperation = "settle";
|
|
938
|
+
const ownsSettlement = (): boolean =>
|
|
939
|
+
runtime.threads.get(runId) === thread &&
|
|
940
|
+
thread.generation === generation &&
|
|
941
|
+
thread.lifecycleVersion === settlementVersion &&
|
|
942
|
+
thread.lifecycleOperation === "settle" &&
|
|
943
|
+
!thread.retired;
|
|
944
|
+
try {
|
|
945
|
+
// Worktree isolation is rejected for reviewers, the only role that can
|
|
946
|
+
// trigger auto-fix. Keep that invariant explicit: an isolated result is
|
|
947
|
+
// finalized once here and can never start a chain that would integrate
|
|
948
|
+
// the same worktree early.
|
|
949
|
+
await thread.finalizeIsolation(generation, result);
|
|
950
|
+
if (!ownsSettlement()) return;
|
|
951
|
+
|
|
952
|
+
const failed = isFailedResult(result);
|
|
953
|
+
thread.state = failed ? "failed" : "completed";
|
|
954
|
+
// Stamp the terminal monitor state before projecting it. This gives every
|
|
955
|
+
// path a fixed endedAt even when the row is removed immediately.
|
|
956
|
+
monitor.setStatus(runId, failed ? "failed" : "done");
|
|
957
|
+
if (!runtime.sessionActive || !ownsSettlement()) return;
|
|
958
|
+
|
|
959
|
+
const modelLevel = failed && isModelLevelFailure(result);
|
|
960
|
+
const dispatchFailed = result.dispatchFailed === true;
|
|
961
|
+
finishRun(runId, failed ? "failed" : "done", modelLevel || dispatchFailed ? { silent: true } : undefined);
|
|
962
|
+
runtime.registerRunResult(runId, result);
|
|
963
|
+
const completion: CompletionMessageItem = {
|
|
964
|
+
agent: result.agent,
|
|
965
|
+
block: modelLevel
|
|
966
|
+
? `${formatCompletionBlock(result, runConfig.maxResultLines, result.projectCwd ?? originalCwd)}\n\n${modelLevelTakeoverNote(result, { runId })}`
|
|
967
|
+
: formatCompletionBlock(result, runConfig.maxResultLines, result.projectCwd ?? originalCwd),
|
|
968
|
+
triggerTurn: completionTriggersTurn(result, runConfig.notifyOnReviewPass),
|
|
969
|
+
};
|
|
970
|
+
if (modelLevel) {
|
|
971
|
+
const detail = result.errorMessage?.trim() || "model unavailable or broken";
|
|
972
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
|
|
973
|
+
} else if (dispatchFailed) {
|
|
974
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${result.errorMessage ?? "dispatch crashed"}`, "error");
|
|
975
|
+
}
|
|
976
|
+
if (failed) {
|
|
977
|
+
runtime.sendCompletionGroup([completion]);
|
|
978
|
+
runtime.completionBatcher.flush();
|
|
979
|
+
} else {
|
|
980
|
+
runtime.completionBatcher.push(completion);
|
|
981
|
+
}
|
|
982
|
+
} finally {
|
|
983
|
+
if (ownsSettlement()) thread.lifecycleOperation = undefined;
|
|
984
|
+
}
|
|
985
|
+
},
|
|
986
|
+
() => {
|
|
987
|
+
if (runtime.threads.get(runId)?.generation !== generation) return;
|
|
988
|
+
// Queued park/stop owns publication and may still be finalizing an
|
|
989
|
+
// isolated worktree. Do not expose a terminal monitor state before
|
|
990
|
+
// that owner records the checkpoint or aborted result.
|
|
991
|
+
if (thread.lifecycleOperation === "park" || thread.lifecycleOperation === "stop") return;
|
|
992
|
+
runtime.runControllers.delete(runId);
|
|
993
|
+
thread.queueController = undefined;
|
|
994
|
+
if (thread.state === "parked") {
|
|
995
|
+
monitor.setStatus(runId, "parked");
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
thread.state = "stopped";
|
|
999
|
+
monitor.setStatus(runId, "failed");
|
|
1000
|
+
if (!runtime.sessionActive) {
|
|
1001
|
+
monitor.removeRun(runId);
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
finishRun(runId, "failed");
|
|
1005
|
+
},
|
|
1006
|
+
async (error) => {
|
|
1007
|
+
if (runtime.threads.get(runId)?.generation !== generation) return;
|
|
1008
|
+
// Queue-level crashes use the same settlement reservation as ordinary
|
|
1009
|
+
// results. A concurrent destructive stop may supersede it while slow
|
|
1010
|
+
// worktree finalization is running, in which case stop publishes once.
|
|
1011
|
+
if (thread.lifecycleOperation === "stop") return;
|
|
1012
|
+
const settlementVersion = ++thread.lifecycleVersion;
|
|
1013
|
+
thread.lifecycleOperation = "settle";
|
|
1014
|
+
const ownsSettlement = (): boolean =>
|
|
1015
|
+
runtime.threads.get(runId) === thread &&
|
|
1016
|
+
thread.generation === generation &&
|
|
1017
|
+
thread.lifecycleVersion === settlementVersion &&
|
|
1018
|
+
thread.lifecycleOperation === "settle" &&
|
|
1019
|
+
!thread.retired;
|
|
1020
|
+
try {
|
|
1021
|
+
const crashed: SingleResult = {
|
|
1022
|
+
...dispatchFailedResult(route.agent, control.getObjective(), error, thinkingLevel),
|
|
1023
|
+
runId,
|
|
1024
|
+
isolation,
|
|
1025
|
+
forkedFromRunId: thread.forkedFromRunId,
|
|
1026
|
+
};
|
|
1027
|
+
await thread.finalizeIsolation(generation, crashed);
|
|
1028
|
+
if (!ownsSettlement()) return;
|
|
1029
|
+
thread.state = "failed";
|
|
1030
|
+
monitor.setStatus(runId, "failed");
|
|
1031
|
+
finishRun(runId, "failed", { silent: true });
|
|
1032
|
+
runtime.registerRunResult(runId, crashed);
|
|
1033
|
+
runtime.runControllers.delete(runId);
|
|
1034
|
+
thread.queueController = undefined;
|
|
1035
|
+
if (!runtime.sessionActive || !ownsSettlement()) return;
|
|
1036
|
+
try {
|
|
1037
|
+
runCtx.ui.notify(`✗ ${agent.name} dispatch failed: ${crashed.errorMessage}`, "error");
|
|
1038
|
+
runtime.sendCompletionGroup([
|
|
1039
|
+
{
|
|
1040
|
+
agent: agent.name,
|
|
1041
|
+
block: formatCompletionBlock(crashed, runConfig.maxResultLines, crashed.projectCwd ?? originalCwd),
|
|
1042
|
+
triggerTurn: true,
|
|
1043
|
+
},
|
|
1044
|
+
]);
|
|
1045
|
+
runtime.completionBatcher.flush();
|
|
1046
|
+
} catch {
|
|
1047
|
+
/* a second delivery failure must not throw through the queue */
|
|
1048
|
+
}
|
|
1049
|
+
} finally {
|
|
1050
|
+
if (ownsSettlement()) thread.lifecycleOperation = undefined;
|
|
1051
|
+
}
|
|
1052
|
+
},
|
|
1053
|
+
);
|
|
1054
|
+
thread.queueController = queueController;
|
|
1055
|
+
thread.generationCompletion = runtime.backgroundQueue.waitForTask(queueController);
|
|
1056
|
+
runtime.runControllers.set(runId, queueController);
|
|
1057
|
+
return pending;
|
|
1058
|
+
};
|
|
1059
|
+
|
|
1060
|
+
return startBackground;
|
|
1061
|
+
}
|