@ferris1225/pi-subagents 6.0.5 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,9 +3,8 @@
3
3
  *
4
4
  * The process transport lives in cli-run.ts: each attempt runs Pi's own CLI in
5
5
  * `--mode rpc` with a session retained after settlement, and settles on
6
- * `agent_settled`. This module owns selected-to-main model handoff,
7
- * capability-clamped thinking, accounting, and result formatting around those
8
- * attempts.
6
+ * `agent_settled`. This module owns retained sessions and result handling.
7
+ * Worker failures return to main without starting a more expensive model.
9
8
  */
10
9
 
11
10
  import { createHash, randomUUID } from "node:crypto";
@@ -230,7 +229,7 @@ export function getResultOutput(result: SingleResult): string {
230
229
  return error || output || "(no output)";
231
230
  }
232
231
 
233
- /** Model handoff preserves useful history, but main or siblings may have edited
232
+ /** A continuation preserves useful history, but main or siblings may have edited
234
233
  * the workspace since the selected model last read it. */
235
234
  const RESUME_CONTINUATION_RULES =
236
235
  "Use the earlier session history as evidence. The current objective below takes precedence over earlier task requests; preserve earlier constraints unless it changes them. Reuse relevant completed work and checks. The workspace may have changed while this thread was inactive: before editing a file, re-read it unless you read it during this continuation. The current cwd is authoritative; do not reuse paths to an earlier temporary worktree. Finish with the result-only handoff your role requires.";
@@ -251,12 +250,6 @@ async function createSessionDir(root: string): Promise<string> {
251
250
  return dir;
252
251
  }
253
252
 
254
- function buildFallbackResumeReason(fromModel?: string): string {
255
- return fromModel
256
- ? `the selected model (${fromModel}) failed at the model/provider level, so the current main model is continuing`
257
- : "the selected model failed at the model/provider level, so the current main model is continuing";
258
- }
259
-
260
253
  export interface RunSingleOptions {
261
254
  defaultCwd: string;
262
255
  agent: AgentConfig;
@@ -264,8 +257,6 @@ export interface RunSingleOptions {
264
257
  task: string;
265
258
  cwd?: string;
266
259
  thinkingLevel?: ThinkingLevel;
267
- /** Resolve the effective level for each runtime model candidate. */
268
- thinkingLevelForModel?: (modelRef?: string) => ThinkingLevel;
269
260
  idleTimeoutMs?: number;
270
261
  sessionDir?: string;
271
262
  sessionId?: string;
@@ -276,13 +267,12 @@ export interface RunSingleOptions {
276
267
  scratchRoot: string;
277
268
  /** Plain-text prompt passed to Pi over stdin. */
278
269
  stdinText?: string;
279
- /** Refresh parent-derived tools immediately before every selected model and
280
- * selected-to-main fallback process is spawned. */
281
- resolveAgentForAttempt?: (agent: AgentConfig) => AgentConfig;
270
+ /** Refresh parent-derived tools immediately before the worker is spawned. */
271
+ resolveAgentBeforeLaunch?: (agent: AgentConfig) => AgentConfig;
282
272
  signal?: AbortSignal;
283
273
  onLive?: (event: SubagentLiveEvent) => void;
284
274
  env?: NodeJS.ProcessEnv;
285
- /** Stable logical-generation controller shared across model attempts. */
275
+ /** Stable logical-generation controller for startup, steering, and cancellation. */
286
276
  control?: RunControl;
287
277
  startupTimeoutMs?: number;
288
278
  }
@@ -344,18 +334,8 @@ async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult>
344
334
  return result;
345
335
  }
346
336
 
347
- /**
348
- * Run one logical generation on the selected model, then hand directly to the
349
- * current main model after any model/provider-level failure. A launch failure is returned to main without replaying an ambiguous prompt.
350
- * Both attempts resume the same retained Pi session.
351
- */
352
- export async function runSingleAgentWithMainFallback(
353
- options: RunSingleOptions,
354
- mainFallbackRef?: string,
355
- ): Promise<SingleResult> {
356
- const agent = options.agent;
357
- const launchedRef = agent.model;
358
-
337
+ /** Run one generation on the chosen worker, preserving its session for follow-ups. */
338
+ export async function runWorker(options: RunSingleOptions): Promise<SingleResult> {
359
339
  const sessionId = options.sessionId ?? randomUUID();
360
340
  const sessionDir = options.sessionDir ?? (await createSessionDir(options.sessionRoot));
361
341
  const baseOptions: RunSingleOptions = {
@@ -364,141 +344,37 @@ export async function runSingleAgentWithMainFallback(
364
344
  ? { stdinText: buildResumePrompt(options.task, "a follow-up was requested") }
365
345
  : {}),
366
346
  };
367
- if (!options.sessionDir) {
368
- // Surface the fresh session immediately so the dispatching thread can
369
- // persist a durable checkpoint before the child settles.
370
- try {
371
- options.onLive?.({ kind: "session", sessionId, sessionDir });
372
- } catch {
373
- /* never throw from event handling */
374
- }
347
+ try {
348
+ if (!options.sessionDir) options.onLive?.({ kind: "session", sessionId, sessionDir });
349
+ options.onLive?.({ kind: "model", model: options.agent.model, thinking: options.thinkingLevel });
350
+ } catch {
351
+ /* never throw from event handling */
375
352
  }
376
-
377
- const dispatchFailure = async (error: unknown): Promise<SingleResult> => {
353
+ let result: SingleResult;
354
+ try {
355
+ result = controlledDisposition(baseOptions) ?? await runSingleAgent({
356
+ ...baseOptions,
357
+ agent: options.resolveAgentBeforeLaunch?.(options.agent) ?? options.agent,
358
+ });
359
+ } catch (error) {
378
360
  const errorMessage = error instanceof Error ? error.message : String(error);
379
- const hasSession = sessionExists(sessionDir, sessionId);
380
- if (!hasSession && !options.sessionDir) {
381
- await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
382
- }
383
- return {
384
- agent: options.agentName,
385
- task: options.control?.getObjective() ?? options.task,
386
- exitCode: 1,
387
- messages: [],
388
- stderr: errorMessage,
389
- usage: emptyUsage(),
390
- model: options.agent.model,
391
- thinking: options.thinkingLevel,
392
- stopReason: "error",
393
- errorMessage,
394
- dispatchFailed: true,
395
- ...(hasSession || options.sessionDir ? { sessionId, sessionDir } : {}),
361
+ result = {
362
+ agent: options.agentName, task: options.task, exitCode: 1,
363
+ messages: [], stderr: errorMessage, usage: emptyUsage(),
364
+ model: options.agent.model, thinking: options.thinkingLevel,
365
+ stopReason: "error", errorMessage, dispatchFailed: true,
396
366
  };
397
- };
398
-
399
- const runAttempt = async (opts: RunSingleOptions): Promise<SingleResult> => {
400
- const immediate = controlledDisposition(opts);
401
- if (immediate) return immediate;
402
- try {
403
- const attemptOptions = opts.resolveAgentForAttempt ? { ...opts, agent: opts.resolveAgentForAttempt(opts.agent) } : opts;
404
- const result = await runSingleAgent(attemptOptions);
405
- return controlledDisposition(opts, result) ?? result;
406
- } catch (error) {
407
- const failed = await dispatchFailure(error);
408
- return controlledDisposition(opts, failed) ?? failed;
409
- }
410
- };
411
-
412
- const selectedRef = launchedRef?.trim() || undefined;
413
- const normalizedMainRef = mainFallbackRef?.trim() || undefined;
414
- const candidates: Array<{ agent: AgentConfig; ref?: string }> = [
415
- { agent, ref: selectedRef },
416
- ];
417
- if (normalizedMainRef && normalizedMainRef !== selectedRef) {
418
- candidates.push({ agent: { ...agent, model: normalizedMainRef }, ref: normalizedMainRef });
419
367
  }
420
-
421
- let fallbackUsed = false;
422
- let result: SingleResult | undefined;
423
- const priorFailedTools: NonNullable<SingleResult["failedTools"]> = [];
424
- const priorUsage = emptyUsage();
425
-
426
- const retainAttemptDiagnostics = (attempt: SingleResult): void => {
427
- priorFailedTools.push(...(attempt.failedTools ?? []));
428
- priorUsage.input += attempt.usage.input;
429
- priorUsage.output += attempt.usage.output;
430
- priorUsage.cacheRead += attempt.usage.cacheRead;
431
- priorUsage.cacheWrite += attempt.usage.cacheWrite;
432
- priorUsage.cost += attempt.usage.cost;
433
- priorUsage.turns += attempt.usage.turns;
434
- priorUsage.contextTokens = attempt.usage.contextTokens || priorUsage.contextTokens;
435
- };
436
-
437
- const finish = async (settled: SingleResult): Promise<SingleResult> => {
438
- if (priorFailedTools.length > 0) {
439
- settled.failedTools = [...priorFailedTools, ...(settled.failedTools ?? [])];
440
- }
441
- if (
442
- priorUsage.turns || priorUsage.input || priorUsage.output || priorUsage.cacheRead ||
443
- priorUsage.cacheWrite || priorUsage.cost || priorUsage.contextTokens
444
- ) {
445
- settled.usage = {
446
- input: priorUsage.input + settled.usage.input,
447
- output: priorUsage.output + settled.usage.output,
448
- cacheRead: priorUsage.cacheRead + settled.usage.cacheRead,
449
- cacheWrite: priorUsage.cacheWrite + settled.usage.cacheWrite,
450
- cost: priorUsage.cost + settled.usage.cost,
451
- turns: priorUsage.turns + settled.usage.turns,
452
- contextTokens: settled.usage.contextTokens || priorUsage.contextTokens,
453
- };
454
- }
455
- const persistedSession = sessionExists(sessionDir, sessionId);
456
- if (!settled.dispatchFailed || persistedSession || options.sessionDir) {
457
- settled.sessionId ??= sessionId;
458
- settled.sessionDir ??= sessionDir;
459
- } else {
460
- await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
461
- settled.sessionId = undefined;
462
- settled.sessionDir = undefined;
463
- }
464
- settled.task = options.control?.getObjective() ?? settled.task;
465
- if (fallbackUsed && launchedRef) settled.modelFallbackFrom = launchedRef;
466
- options.control?.markSettled();
467
- return settled;
468
- };
469
-
470
- for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
471
- const candidate = candidates[candidateIndex];
472
- fallbackUsed ||= candidateIndex > 0;
473
- const previousModel = result?.model ?? candidates[candidateIndex - 1]?.ref;
474
- const candidateThinking = options.thinkingLevelForModel?.(candidate.ref) ?? options.thinkingLevel;
475
- const candidateOptions: RunSingleOptions = {
476
- ...baseOptions,
477
- agent: candidate.agent,
478
- thinkingLevel: candidateThinking,
479
- ...(candidateIndex > 0
480
- ? {
481
- stdinText: buildResumePrompt(
482
- options.control?.getObjective() ?? options.task,
483
- buildFallbackResumeReason(previousModel),
484
- ),
485
- }
486
- : {}),
487
- };
488
- try {
489
- options.onLive?.({ kind: "model", model: candidate.ref, thinking: candidateThinking });
490
- } catch {
491
- /* never throw from event handling */
492
- }
493
-
494
- result = await runAttempt(candidateOptions);
495
- if (result.stopReason === "aborted") return finish(result);
496
- if (!isModelLevelFailure(result)) return finish(result);
497
- // Any model-level failure advances immediately to the sole fallback (the
498
- // current main model). Retain selected-attempt tool diagnostics and usage;
499
- // ordinary task/tool failures returned above without a handoff.
500
- if (candidateIndex < candidates.length - 1) retainAttemptDiagnostics(result);
368
+ result = controlledDisposition(baseOptions, result) ?? result;
369
+ if (!result.dispatchFailed || sessionExists(sessionDir, sessionId) || options.sessionDir) {
370
+ result.sessionId ??= sessionId;
371
+ result.sessionDir ??= sessionDir;
372
+ } else {
373
+ await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
374
+ result.sessionId = undefined;
375
+ result.sessionDir = undefined;
501
376
  }
502
-
503
- return finish(result!);
377
+ result.task = options.control?.getObjective() ?? result.task;
378
+ options.control?.markSettled();
379
+ return result;
504
380
  }
@@ -63,7 +63,7 @@ export const runCommand: CommandRunner = (command, args, options) =>
63
63
  () => terminateProcessTree(child, true, usePosixProcessGroup),
64
64
  GIT_COMMAND_KILL_GRACE_MS,
65
65
  );
66
- if (typeof forceKillTimer.unref === "function") forceKillTimer.unref();
66
+ forceKillTimer.unref();
67
67
  }
68
68
  };
69
69
  const fail = (error: Error): void => {
@@ -88,7 +88,7 @@ export const runCommand: CommandRunner = (command, args, options) =>
88
88
  () => fail(new Error(`Command timed out after ${options.timeoutMs}ms: ${command}`)),
89
89
  options.timeoutMs,
90
90
  );
91
- if (typeof timeout.unref === "function") timeout.unref();
91
+ timeout.unref();
92
92
  }
93
93
 
94
94
  child.stdout?.on("data", (chunk: Buffer | string) => append(stdout, chunk));
@@ -13,12 +13,10 @@ const RECOVERY_MANIFEST_FILE_NAME = "pi-subagents-recovery.json";
13
13
  const RECOVERY_MANIFEST_VERSION = 1;
14
14
 
15
15
  export interface RecoveryRecord {
16
- durableId?: string;
16
+ durableId: string;
17
17
  runId: number;
18
18
  createdAt: number;
19
19
  integrated: boolean;
20
- /** Legacy diagnostic metadata; cleanup authorization comes only from managed paths. */
21
- originalRoot?: string;
22
20
  worktreePath?: string;
23
21
  patchPath?: string;
24
22
  error?: string;
@@ -36,14 +34,14 @@ export function getRecoveryManifestPath(configPath: string): string {
36
34
  function normalizeRecord(value: unknown): RecoveryRecord | undefined {
37
35
  if (!value || typeof value !== "object") return undefined;
38
36
  const raw = value as Record<string, unknown>;
37
+ if (typeof raw.durableId !== "string" || !raw.durableId) throw new Error("Unsupported recovery record: durableId is required. Recovery artifacts were left untouched.");
39
38
  if (typeof raw.runId !== "number" || !Number.isInteger(raw.runId) || raw.runId < 1) return undefined;
40
39
  if (typeof raw.createdAt !== "number" || !Number.isFinite(raw.createdAt)) return undefined;
41
40
  return {
42
- ...(typeof raw.durableId === "string" && raw.durableId ? { durableId: raw.durableId } : {}),
41
+ durableId: raw.durableId,
43
42
  runId: raw.runId,
44
43
  createdAt: raw.createdAt,
45
44
  integrated: raw.integrated === true,
46
- ...(typeof raw.originalRoot === "string" && raw.originalRoot ? { originalRoot: raw.originalRoot } : {}),
47
45
  ...(typeof raw.worktreePath === "string" && raw.worktreePath ? { worktreePath: raw.worktreePath } : {}),
48
46
  ...(typeof raw.patchPath === "string" && raw.patchPath ? { patchPath: raw.patchPath } : {}),
49
47
  ...(typeof raw.error === "string" && raw.error ? { error: raw.error } : {}),
@@ -57,8 +55,8 @@ interface RecoveryManifestRead {
57
55
 
58
56
  async function readManifest(path: string): Promise<RecoveryManifestRead> {
59
57
  try {
60
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
61
- if (!Array.isArray(parsed?.records)) throw new Error(`Invalid recovery manifest: ${path}`);
58
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { version?: unknown; records?: unknown } | null;
59
+ if (parsed?.version !== RECOVERY_MANIFEST_VERSION || !Array.isArray(parsed.records)) throw new Error(`Invalid recovery manifest: ${path}`);
62
60
  return {
63
61
  sourceCount: parsed.records.length,
64
62
  records: parsed.records.flatMap((record) => {
@@ -96,21 +94,8 @@ export async function readRecoveryRecords(configPath: string): Promise<RecoveryR
96
94
  });
97
95
  }
98
96
 
99
- /** Move valid records from the previous agent-root manifest into the internal-state
100
- * root. Invalid legacy records are removed without touching their referenced paths. */
101
- export async function relocateRecoveryManifest(configPath: string): Promise<void> {
102
- const legacyPath = join(dirname(configPath), RECOVERY_MANIFEST_FILE_NAME);
103
- const currentPath = getRecoveryManifestPath(configPath);
104
- if (legacyPath === currentPath || !existsSync(legacyPath)) return;
105
- await withManifestMutation(legacyPath, async () => {
106
- const legacy = await readManifest(legacyPath);
107
- await persistRecoveryRecords(configPath, legacy.records);
108
- await rm(legacyPath, { force: true });
109
- });
110
- }
111
-
112
97
  function recoveryKey(record: RecoveryRecord): string {
113
- return `${record.durableId ?? record.runId}\0${record.worktreePath ?? ""}\0${record.patchPath ?? ""}\0${record.error ?? ""}`;
98
+ return `${record.durableId}\0${record.worktreePath ?? ""}\0${record.patchPath ?? ""}\0${record.error ?? ""}`;
114
99
  }
115
100
 
116
101
  async function writeManifest(path: string, records: readonly RecoveryRecord[]): Promise<void> {
@@ -155,15 +140,14 @@ export async function persistRecoveryRecords(
155
140
  export function recoveryRecordFromFinalization(
156
141
  runId: number,
157
142
  finalization: WorktreeFinalization,
143
+ durableId: string,
158
144
  now = Date.now(),
159
- durableId?: string,
160
145
  ): RecoveryRecord {
161
146
  return {
162
- ...(durableId ? { durableId } : {}),
147
+ durableId,
163
148
  runId,
164
149
  createdAt: now,
165
150
  integrated: finalization.integrated,
166
- ...(finalization.originalRoot ? { originalRoot: finalization.originalRoot } : {}),
167
151
  ...(finalization.worktreePath ? { worktreePath: finalization.worktreePath } : {}),
168
152
  ...(finalization.patchPath ? { patchPath: finalization.patchPath } : {}),
169
153
  ...(finalization.error ? { error: finalization.error } : {}),
@@ -27,7 +27,7 @@ import { join } from "node:path";
27
27
  export const TEMP_OWNER_FILE_NAME = "owner.json";
28
28
 
29
29
  /** Transient directories created under `<project>/tmp`: the child prompt
30
- * copies (`pi-subagents-*`), including policy-shim leftovers from older releases. The singular `pi-subagent-` prefixes below belong
30
+ * copies (`pi-subagents-*`). The singular `pi-subagent-` prefixes below belong
31
31
  * to the durable roots and are swept separately, under a reference guard. */
32
32
  const TEMP_DIR_PREFIXES = ["pi-subagents-"] as const;
33
33
 
@@ -15,17 +15,6 @@ const COMPLETION_MAX_WAIT_MS = 1_000;
15
15
 
16
16
  type TimerHandle = ReturnType<typeof setTimeout>;
17
17
 
18
- function unrefHandle(handle: TimerHandle): void {
19
- if (
20
- handle &&
21
- typeof handle === "object" &&
22
- "unref" in handle &&
23
- typeof (handle as { unref: unknown }).unref === "function"
24
- ) {
25
- (handle as { unref: () => void }).unref();
26
- }
27
- }
28
-
29
18
  export interface CompletionBatcherOptions<T> {
30
19
  emit: (items: T[]) => void;
31
20
  }
@@ -69,11 +58,11 @@ export function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>)
69
58
 
70
59
  if (debounceTimer !== null) clearTimeout(debounceTimer);
71
60
  debounceTimer = setTimeout(emitGroup, COMPLETION_DEBOUNCE_MS);
72
- unrefHandle(debounceTimer);
61
+ debounceTimer.unref();
73
62
 
74
63
  if (maxWaitTimer === null) {
75
64
  maxWaitTimer = setTimeout(emitGroup, COMPLETION_MAX_WAIT_MS);
76
- unrefHandle(maxWaitTimer);
65
+ maxWaitTimer.unref();
77
66
  }
78
67
  },
79
68
  flush: emitGroup,
@@ -13,14 +13,13 @@
13
13
  * through the same cross-process manifest lock as recovery records.
14
14
  */
15
15
 
16
- import { createHash, randomUUID } from "node:crypto";
16
+ import { randomUUID } from "node:crypto";
17
17
  import { replaceManifestFile, withManifestMutation } from "../isolation/manifest-mutation.ts";
18
18
  import { existsSync, type Dirent, readdirSync, statSync } from "node:fs";
19
19
  import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
20
20
  import { uptime } from "node:os";
21
21
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
22
22
  import type { UsageStats } from "../execution/run-control.ts";
23
- import { migrateStoredRecordRoles } from "../configuration/role-migration.ts";
24
23
  import type { SubagentThread } from "./runtime.ts";
25
24
  import { getResultOutput, isFailedResult, getProjectRoot, getSubagentsRoot, type SingleResult } from "../execution/spawn.ts";
26
25
  import { isManagedSessionDir, isManagedWorktreeLayout, samePath } from "../isolation/managed-paths.ts";
@@ -72,8 +71,8 @@ export interface ThreadResultSummary {
72
71
  }
73
72
 
74
73
  export interface ThreadRecord {
75
- /** Stable identity across windows and locally renumbered restores. Absent in legacy records. */
76
- durableId?: string;
74
+ /** Stable identity across windows and locally renumbered restores. */
75
+ durableId: string;
77
76
  runId: number;
78
77
  createdAt: number;
79
78
  updatedAt: number;
@@ -103,11 +102,7 @@ function currentBootId(now = Date.now()): number {
103
102
  return Math.round(now - uptime() * 1_000);
104
103
  }
105
104
 
106
- /** Whether a record's `childPids` can still name processes of this boot. Pids
107
- * are only unique within a boot: after a restart the same number belongs to
108
- * whatever claimed it, so restore must not signal them. Records written before
109
- * this field existed carry no boot id and count as unverifiable; leaving a
110
- * stray child alive is safer than killing an unrelated process tree. */
105
+ /** Only verified process identities from this boot can authorize signaling. */
111
106
  export function isCurrentBoot(record: ThreadRecord, now = Date.now()): boolean {
112
107
  if (record.bootId === undefined) return false;
113
108
  return Math.abs(record.bootId - currentBootId(now)) <= BOOT_ID_TOLERANCE_MS;
@@ -159,18 +154,20 @@ function normalizeResultSummary(value: unknown): ThreadResultSummary | undefined
159
154
  function normalizeRecord(value: unknown): ThreadRecord | undefined {
160
155
  if (!value || typeof value !== "object") return undefined;
161
156
  const raw = value as Record<string, unknown>;
157
+ if (typeof raw.durableId !== "string" || !raw.durableId) throw new Error("Unsupported thread record: durableId is required. Recovery artifacts were left untouched.");
162
158
  if (typeof raw.runId !== "number" || !Number.isInteger(raw.runId) || raw.runId < 1) return undefined;
163
159
  if (typeof raw.createdAt !== "number" || !Number.isFinite(raw.createdAt)) return undefined;
164
160
  if (typeof raw.updatedAt !== "number" || !Number.isFinite(raw.updatedAt)) return undefined;
165
161
  if (typeof raw.agentName !== "string" || !raw.agentName) return undefined;
166
162
  if (typeof raw.task !== "string" || !raw.task) return undefined;
167
163
  if (typeof raw.cwd !== "string" || !raw.cwd) return undefined;
164
+ if (typeof raw.executionCwd !== "string" || !raw.executionCwd) return undefined;
168
165
  if (raw.isolation !== "shared" && raw.isolation !== "worktree") return undefined;
169
166
  if (raw.state !== "parked" && raw.state !== "completed" && raw.state !== "failed") return undefined;
170
167
  const worktree = raw.worktree === undefined ? undefined : normalizeWorktreeSnapshot(raw.worktree);
171
168
  if (worktree === null) return undefined;
172
169
  return {
173
- ...(typeof raw.durableId === "string" && raw.durableId ? { durableId: raw.durableId } : {}),
170
+ durableId: raw.durableId,
174
171
  runId: raw.runId,
175
172
  createdAt: raw.createdAt,
176
173
  updatedAt: raw.updatedAt,
@@ -178,7 +175,7 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
178
175
  agentName: raw.agentName,
179
176
  task: raw.task,
180
177
  cwd: raw.cwd,
181
- executionCwd: typeof raw.executionCwd === "string" && raw.executionCwd ? raw.executionCwd : raw.cwd,
178
+ executionCwd: raw.executionCwd,
182
179
  ...(typeof raw.thinkingLevel === "string" && raw.thinkingLevel ? { thinkingLevel: raw.thinkingLevel } : {}),
183
180
  isolation: raw.isolation,
184
181
  state: raw.state,
@@ -196,19 +193,15 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
196
193
  }
197
194
 
198
195
  interface ThreadManifestRead {
199
- rolesMigrated?: boolean;
200
196
  sourceCount: number;
201
197
  records: ThreadRecord[];
202
198
  }
203
199
 
204
200
  async function readManifest(path: string): Promise<ThreadManifestRead> {
205
201
  try {
206
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
207
- if (!Array.isArray(parsed?.records)) throw new Error(`Invalid thread manifest: ${path}`);
208
- let rolesMigrated = false;
209
- for (const record of parsed.records) rolesMigrated = migrateStoredRecordRoles(record) || rolesMigrated;
202
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { version?: unknown; records?: unknown } | null;
203
+ if (parsed?.version !== THREADS_MANIFEST_VERSION || !Array.isArray(parsed.records)) throw new Error(`Invalid thread manifest: ${path}`);
210
204
  return {
211
- rolesMigrated,
212
205
  sourceCount: parsed.records.length,
213
206
  records: parsed.records.flatMap((record) => {
214
207
  const normalized = normalizeRecord(record);
@@ -287,15 +280,6 @@ export async function isThreadSourceAvailable(record: ThreadRecord): Promise<boo
287
280
  }
288
281
  }
289
282
 
290
- /** Legacy identities include immutable source/artifact metadata, so adopting a
291
- * record does not let a fresh run with the same display id overwrite it. */
292
- export function threadRecordIdentity(record: ThreadRecord): string {
293
- return record.durableId ?? `legacy-${createHash("sha256").update(JSON.stringify([
294
- record.cwd, record.runId, record.createdAt, record.ownerPid, record.bootId,
295
- record.sessionDir, record.worktree?.tempDir,
296
- ])).digest("hex")}`;
297
- }
298
-
299
283
  async function validatedManifestRecords(
300
284
  configPath: string,
301
285
  path: string,
@@ -325,7 +309,7 @@ export async function readThreadRecords(configPath: string): Promise<ThreadRecor
325
309
  .map((path) => withManifestMutation(path, async () => {
326
310
  const manifest = await readManifest(path);
327
311
  const validated = await validatedManifestRecords(configPath, path, manifest.records);
328
- if (manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
312
+ if (validated.length !== manifest.sourceCount) await writeManifest(path, validated);
329
313
  return validated;
330
314
  })),
331
315
  );
@@ -355,11 +339,10 @@ export async function upsertThreadRecord(configPath: string, record: ThreadRecor
355
339
  const path = getThreadsManifestPath(configPath, record.cwd);
356
340
  await withManifestMutation(path, async () => {
357
341
  const records = await readManifestRecords(path);
358
- const identity = threadRecordIdentity(record);
359
- const index = records.findIndex((candidate) => threadRecordIdentity(candidate) === identity);
342
+ const index = records.findIndex((candidate) => candidate.durableId === record.durableId);
360
343
  const merged: ThreadRecord = index === -1
361
- ? { ...record, durableId: identity }
362
- : { ...record, durableId: identity, createdAt: records[index]!.createdAt };
344
+ ? record
345
+ : { ...record, createdAt: records[index]!.createdAt };
363
346
  if (index === -1) records.push(merged);
364
347
  else records[index] = merged;
365
348
  await writeManifest(path, records);
@@ -370,7 +353,7 @@ export async function removeThreadRecord(configPath: string, identity: string, c
370
353
  const path = getThreadsManifestPath(configPath, cwd);
371
354
  await withManifestMutation(path, async () => {
372
355
  const records = await readManifestRecords(path);
373
- const next = records.filter((record) => threadRecordIdentity(record) !== identity);
356
+ const next = records.filter((record) => record.durableId !== identity);
374
357
  if (next.length === records.length) return;
375
358
  await writeManifest(path, next);
376
359
  });
@@ -423,7 +406,7 @@ export function threadRecordFromThread(
423
406
  elapsedMs: thread.elapsedMs,
424
407
  ...(thread.sessionId && thread.sessionDir ? { sessionId: thread.sessionId, sessionDir: thread.sessionDir } : {}),
425
408
  ...(worktree ? { worktree } : {}),
426
- childPids: thread.control?.getChildPids?.() ?? [],
409
+ childPids: thread.control.getChildPids(),
427
410
  ownerPid: process.pid,
428
411
  bootId: currentBootId(now),
429
412
  ...(thread.lastResult ? { resultSummary: summarizeResult(thread.lastResult) } : {}),
@@ -481,7 +464,7 @@ export async function pruneThreadRecords(
481
464
  const records = manifest.records;
482
465
  if (manifest.sourceCount === 0) return;
483
466
  const validity = await Promise.all(records.map((record) => validateThreadRecord(configPath, path, record)));
484
- let changed = Boolean(manifest.rolesMigrated) || manifest.sourceCount !== records.length || validity.some((valid) => !valid);
467
+ let changed = manifest.sourceCount !== records.length || validity.some((valid) => !valid);
485
468
  const kept: ThreadRecord[] = [];
486
469
  for (const [index, record] of records.entries()) {
487
470
  if (!validity[index]) continue;
@@ -136,7 +136,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
136
136
  finalizationCompletion,
137
137
  new Promise<undefined>((resolve) => {
138
138
  const timer = setTimeout(() => resolve(undefined), CONTROL_QUIESCE_TIMEOUT_MS);
139
- if (typeof timer.unref === "function") timer.unref();
139
+ timer.unref();
140
140
  }),
141
141
  ]);
142
142
  } catch {
@@ -158,7 +158,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
158
158
  ...(existsSync(worktree.worktreePath) ? { worktreePath: worktree.worktreePath } : {}),
159
159
  ...(existsSync(worktree.patchPath) ? { patchPath: worktree.patchPath } : {}),
160
160
  error: "subagent_stop timed out waiting for worktree integration; it continues in the background",
161
- }, Date.now(), thread.durableId),
161
+ }, thread.durableId!),
162
162
  ]).catch(() => undefined);
163
163
  pendingIntegration.push(`#${runId}`);
164
164
  }
@@ -22,7 +22,7 @@ import {
22
22
  RunControl,
23
23
  isFailedResult,
24
24
  isModelLevelFailure,
25
- runSingleAgentWithMainFallback,
25
+ runWorker,
26
26
  type SingleResult,
27
27
  type SubagentLiveEvent,
28
28
  } from "../execution/spawn.ts";
@@ -100,7 +100,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
100
100
  const originalCwd = resolve(cwd ?? runCtx.cwd);
101
101
  if (isolation === "worktree" && !isWriteCapableAgent(agent, toolInfos)) {
102
102
  return {
103
- ...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
103
+ ...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as worker.`),
104
104
  isolation,
105
105
  };
106
106
  }
@@ -131,6 +131,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
131
131
  let executionCwd = originalCwd;
132
132
  let worktreeGroup: string | undefined;
133
133
  const route = resolveDispatchModelRoute(agent, runConfig, runCtx);
134
+ if (route.error) return failedStartResult(agentName, task, route.error);
134
135
  const thinkingLevel = route.thinkingLevel;
135
136
  const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, isolation);
136
137
  runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
@@ -233,16 +234,16 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
233
234
  const launchAgent = worktree ? withWorktreeSystemPrompt(activeRoute.agent, worktree) : activeRoute.agent;
234
235
  let result: SingleResult;
235
236
  try {
236
- result = await runSingleAgentWithMainFallback(
237
+ if (activeRoute.error) throw new Error(activeRoute.error);
238
+ result = await runWorker(
237
239
  {
238
240
  defaultCwd: executionCwd,
239
241
  agent: launchAgent,
240
- resolveAgentForAttempt: resolveLiveAgentTools,
242
+ resolveAgentBeforeLaunch: resolveLiveAgentTools,
241
243
  agentName,
242
244
  task,
243
245
  cwd: executionCwd,
244
246
  thinkingLevel: activeRoute.thinkingLevel,
245
- thinkingLevelForModel: activeRoute.thinkingLevelForModel,
246
247
  signal: backgroundSignal,
247
248
  onLive,
248
249
  control,
@@ -251,7 +252,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
251
252
  ...(startOptions.resumeSession ?? {}),
252
253
  scratchRoot,
253
254
  },
254
- activeRoute.mainFallbackRef,
255
255
  );
256
256
  } catch (error) {
257
257
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -516,7 +516,7 @@ export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifec
516
516
  // Every retained finalization gets a durable recovery record, so the
517
517
  // artifacts stay findable even when the owning process dies next.
518
518
  void persistRecoveryRecords(runtime.configPath, [
519
- recoveryRecordFromFinalization(runId, finalization, Date.now(), thread.durableId),
519
+ recoveryRecordFromFinalization(runId, finalization, thread.durableId!),
520
520
  ]).catch(() => undefined);
521
521
  }
522
522
  return finalization;