@ferris1225/pi-subagents 6.0.3 → 6.0.5

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +83 -200
  3. package/index.ts +8 -13
  4. package/package.json +1 -1
  5. package/src/configuration/config.ts +2 -6
  6. package/src/configuration/role-migration.ts +3 -14
  7. package/src/configuration/setup.ts +66 -57
  8. package/src/configuration/ui.ts +335 -64
  9. package/src/delegation/agents.ts +5 -6
  10. package/src/delegation/builtin-agents.ts +10 -31
  11. package/src/delegation/dispatch.ts +52 -165
  12. package/src/delegation/prompt.ts +29 -82
  13. package/src/execution/background.ts +2 -2
  14. package/src/execution/run-control.ts +1 -1
  15. package/src/execution/spawn.ts +2 -30
  16. package/src/isolation/worktree.ts +0 -14
  17. package/src/lifecycle/cancellation.ts +4 -8
  18. package/src/lifecycle/completion.ts +9 -21
  19. package/src/lifecycle/dispatch-core.ts +7 -7
  20. package/src/lifecycle/durable.ts +5 -29
  21. package/src/lifecycle/runtime.ts +11 -63
  22. package/src/lifecycle/stop.ts +1 -2
  23. package/src/lifecycle/thread-lifecycle.ts +38 -83
  24. package/src/lifecycle/thread-restore.ts +1 -3
  25. package/src/lifecycle/thread-shared.ts +10 -27
  26. package/src/lifecycle/tools.ts +24 -114
  27. package/src/presentation/announcements.ts +8 -6
  28. package/src/presentation/format.ts +39 -14
  29. package/src/presentation/monitor.ts +697 -758
  30. package/src/presentation/widget.ts +34 -142
  31. package/src/delegation/ownership.ts +0 -98
  32. package/src/delegation/phase-scope.ts +0 -186
  33. package/src/workflow/acceptance.ts +0 -67
  34. package/src/workflow/durable.ts +0 -228
  35. package/src/workflow/engine.ts +0 -816
  36. package/src/workflow/plan.ts +0 -409
  37. package/src/workflow/state.ts +0 -55
  38. package/src/workflow/templates.ts +0 -156
  39. package/src/workflow/tool.ts +0 -254
@@ -9,9 +9,6 @@
9
9
  */
10
10
 
11
11
  import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
12
- import { findDuplicateDispatch } from "../delegation/prompt.ts";
13
- import { pendingWorkflowLeases } from "../delegation/ownership.ts";
14
- import type { PhaseScope } from "../delegation/phase-scope.ts";
15
12
  import { rmSync } from "node:fs";
16
13
  import { BackgroundTaskQueue } from "../execution/background.ts";
17
14
  import {
@@ -23,11 +20,10 @@ import {
23
20
  } from "./completion.ts";
24
21
  import { type ThinkingLevel } from "../configuration/config.ts";
25
22
  import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
26
- import { isRunActiveStatus, monitor, type RunWorkflowTag } from "../presentation/monitor.ts";
23
+ import { isRunActiveStatus, monitor } from "../presentation/monitor.ts";
27
24
  import type { RunControl, SteeringReceipt } from "../execution/run-control.ts";
28
25
  import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
29
26
  import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
30
- import type { WorkflowRun } from "../workflow/state.ts";
31
27
 
32
28
  export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "completed" | "failed" | "stopped";
33
29
 
@@ -40,18 +36,11 @@ export interface SubagentThread {
40
36
  generation: number;
41
37
  agentName: string;
42
38
  task: string;
43
- phaseId?: string;
44
- scope?: PhaseScope;
45
- /** Capability snapshot used by declared-scope admission, including after restore. */
46
- writeCapable?: boolean;
47
- /** Live graph membership; graph summaries own delivery for these runs. */
48
- workflow?: RunWorkflowTag;
49
39
  /** Caller-facing cwd in the original worktree. */
50
40
  cwd: string;
51
41
  /** Actual child cwd (the equivalent path inside an isolated worktree). */
52
42
  executionCwd: string;
53
43
  thinkingLevel?: ThinkingLevel;
54
- requestedThinkingLevel?: ThinkingLevel;
55
44
  isolation: IsolationMode;
56
45
  worktree?: WorktreeIsolation;
57
46
  /** Original durable evidence retained when its worktree handle is unavailable. */
@@ -71,8 +60,7 @@ export interface SubagentThread {
71
60
  elapsedMs: number;
72
61
  /** Terminal or interrupted partial result; independent of the transient monitor row. */
73
62
  lastResult?: SingleResult;
74
- /** A destructive stop retires context even if the active child settles later. */
75
- retireOnSettle?: boolean;
63
+ /** Retired by a destructive stop: its session is deleted and it cannot be continued. */
76
64
  retired?: boolean;
77
65
  /** All owners finalize under the same original-repository lane. */
78
66
  finalizeIsolation: (generation: number, result?: SingleResult) => Promise<WorktreeFinalization | undefined>;
@@ -95,7 +83,7 @@ export interface SubagentRuntime {
95
83
  suppressCompletions: boolean;
96
84
  discardCompletions: () => void;
97
85
  /** Record cancellation for the next user turn without waking the parent. */
98
- recordCancellation: (runIds: number[], workflowIds: number[]) => void;
86
+ recordCancellation: (runIds: number[]) => void;
99
87
  /** Resolves when the load-time durable restore pass has finished. Everything
100
88
  * that answers "which threads exist" awaits it — the lookup tools, a fresh
101
89
  * dispatch before it allocates a run id, and the restored-thread notice — so
@@ -127,18 +115,7 @@ export interface SubagentRuntime {
127
115
  registerRunResult: (runId: number, result: SingleResult) => void;
128
116
  /** Logical threads outlive process attempts and completed generations. */
129
117
  threads: Map<number, SubagentThread>;
130
- /** Explicit main edit/write calls hold their paths until tool_execution_end. */
131
- mainWrites: Map<string, { toolName: string; scope: PhaseScope }>;
132
- /** Workflow graphs started in this parent session, live and settled. */
133
- workflows: Map<number, WorkflowRun>;
134
- /** Stable mapping from persisted identities to this window's display ids. */
135
- workflowRecordIds: Map<string, number>;
136
- /** Allocate a graph id that no retained or live workflow record owns. */
137
- reserveWorkflowId: () => number;
138
- /** Raise the graph-id allocator above an id restored from a durable record. */
139
- ensureWorkflowIdAbove: (id: number) => void;
140
- /** Session-teardown tasks that must run before runtime state is released
141
- * (persisting a graph's shape, for example). */
118
+ /** Session-teardown tasks that must run before runtime state is released. */
142
119
  shutdownHooks: Array<() => Promise<void> | void>;
143
120
  /** Every session directory retained for this parent session. */
144
121
  sessionDirs: Set<string>;
@@ -148,22 +125,8 @@ export interface SubagentRuntime {
148
125
  shutdown: () => Promise<void>;
149
126
  }
150
127
 
151
- /** Pending nodes reserve their phases before they allocate ordinary run ids. */
152
- export function findPendingWorkflowPhase(
153
- runtime: Pick<SubagentRuntime, "workflows">,
154
- task: string,
155
- cwd: string,
156
- phaseId?: string,
157
- excludeWorkflowId?: number,
158
- ): { workflowId: number; nodeId: string; agent: string } | undefined {
159
- const duplicate = findDuplicateDispatch(pendingWorkflowLeases(runtime, excludeWorkflowId), task, cwd, phaseId);
160
- const owner = duplicate?.source;
161
- return owner?.workflow ? { workflowId: owner.workflow.workflowId, nodeId: owner.workflow.nodeId, agent: owner.agentName } : undefined;
162
- }
163
-
164
128
  export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
165
129
  const backgroundQueue = new BackgroundTaskQueue();
166
- let nextWorkflowId = 1;
167
130
  // Compaction reads the whole history, summarizes it, and replaces it. A
168
131
  // completion injected into that window can be swallowed by the summary,
169
132
  // silently losing a result a child spent minutes producing — so delivery is
@@ -179,16 +142,14 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
179
142
  getToolInfos: () => pi.getAllTools(),
180
143
  sessionActive: true,
181
144
  suppressCompletions: false,
182
- recordCancellation: (runIds, workflowIds) => {
183
- const targets = [
184
- ...(runIds.length ? ["runs " + runIds.map((id) => `#${id}`).join(", ")] : []),
185
- ...(workflowIds.length ? ["workflows " + workflowIds.map((id) => `#${id}`).join(", ")] : []),
186
- ].join("; ");
145
+ recordCancellation: (runIds) => {
146
+ if (!runIds.length) return;
147
+ const targets = "runs " + runIds.map((id) => `#${id}`).join(", ");
187
148
  pi.sendMessage({
188
149
  customType: "subagent-cancelled",
189
150
  content: `Parent cancellation stopped ${targets}. These runs are already cancelled; no further subagent_stop is needed. Do not restart cancelled work unless the user requests it. Partial edits and retained integration artifacts may remain; inspect them only if continuing the task.`,
190
151
  display: true,
191
- details: { runIds, workflowIds },
152
+ details: { runIds },
192
153
  }, { deliverAs: "nextTurn", triggerTurn: false });
193
154
  },
194
155
  discardCompletions: () => {
@@ -219,7 +180,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
219
180
  id: run.id,
220
181
  agent: run.agent,
221
182
  label: run.label,
222
- ...(run.status === "queued" && run.waitReason ? { wait: run.waitReason } : {}),
183
+ ...(run.status === "queued" ? { starting: true } : {}),
223
184
  }));
224
185
  const message = {
225
186
  customType: "subagent-result",
@@ -255,13 +216,6 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
255
216
  settledRuns: new Map<number, SingleResult>(),
256
217
  settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
257
218
  threads: new Map<number, SubagentThread>(),
258
- mainWrites: new Map(),
259
- workflows: new Map<number, WorkflowRun>(),
260
- workflowRecordIds: new Map(),
261
- reserveWorkflowId: () => nextWorkflowId++,
262
- ensureWorkflowIdAbove: (id) => {
263
- if (id >= nextWorkflowId) nextWorkflowId = id + 1;
264
- },
265
219
  shutdownHooks: [],
266
220
  sessionDirs: new Set<string>(),
267
221
  retainSession: (result) => {
@@ -315,10 +269,9 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
315
269
  continue;
316
270
  }
317
271
  if (thread.lifecycleOperation === "settle") continue;
272
+ // Unlike subagent_stop, shutdown interrupts to the last checkpoint and
273
+ // preserves session/worktree artifacts for manual recovery.
318
274
  thread.lifecycleOperation = "stop";
319
- // Deliberately NOT retireOnSettle: shutdown interrupts to the last
320
- // checkpoint and preserves session/worktree artifacts for manual recovery.
321
- thread.retireOnSettle = false;
322
275
  if (liveStates.has(thread.state)) thread.state = "stopped";
323
276
  }
324
277
  runtime.completionBatcher.dispose();
@@ -382,8 +335,6 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
382
335
  /* best-effort; the state-root sweep catches leftovers later */
383
336
  }
384
337
  }
385
- // Let owners persist their own last state (a workflow's shape) while the
386
- // threads it refers to still exist.
387
338
  for (const hook of runtime.shutdownHooks) {
388
339
  try {
389
340
  await hook();
@@ -399,9 +350,6 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
399
350
  // manifest; the next process re-registers them at restore.
400
351
  runtime.sessionDirs.clear();
401
352
  runtime.threads.clear();
402
- runtime.mainWrites.clear();
403
- runtime.workflows.clear();
404
- runtime.workflowRecordIds.clear();
405
353
  runtime.shutdownHooks = [];
406
354
  monitor.clear();
407
355
  },
@@ -35,7 +35,6 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
35
35
  const stopVersion = ++thread.lifecycleVersion;
36
36
  thread.lifecycleOperation = "stop";
37
37
  thread.retired = true;
38
- thread.retireOnSettle = true;
39
38
  thread.state = "stopped";
40
39
  const completion = thread.generationCompletion;
41
40
  let releaseQuiescence!: () => void;
@@ -60,7 +59,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
60
59
  // Interrupt every claimed generation before awaiting any one of them.
61
60
  // An isolated stop may need the repository lane for final integration;
62
61
  // cancelling all holders first prevents stop-all from waiting behind a
63
- // later shared workflow that this same operation has not interrupted yet.
62
+ // later run that this same operation has not interrupted yet.
64
63
  const interruptionPromises = claimed.map(({ thread, stopMessage, controller }) => {
65
64
  const stopping = thread.control.stop(stopMessage).catch(() => undefined);
66
65
  runtime.backgroundQueue.cancel(controller);
@@ -12,13 +12,11 @@ import { join, resolve } from "node:path";
12
12
  import { isWriteCapableAgent, resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
13
13
  import type { CompletionMessageItem } from "./completion.ts";
14
14
  import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
15
- import { dispatchFailedResult, failedStartResult, formatCompletionBlock, modelLevelTakeoverNote, queuedResult } from "../presentation/format.ts";
15
+ import { dispatchFailedResult, failedStartResult, formatCompletionBlock, queuedResult } from "../presentation/format.ts";
16
16
  import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
17
17
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
18
- import { normalizePhaseId, normalizePhaseScope } from "../delegation/phase-scope.ts";
19
- import { findRuntimeWriterConflict } from "../delegation/ownership.ts";
20
18
  import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
21
- import { findPendingWorkflowPhase, type SubagentRuntime, type SubagentThread, type ThreadState } from "./runtime.ts";
19
+ import { type SubagentRuntime, type SubagentThread, type ThreadState } from "./runtime.ts";
22
20
  import {
23
21
  getProjectRoot,
24
22
  RunControl,
@@ -29,7 +27,6 @@ import {
29
27
  type SubagentLiveEvent,
30
28
  } from "../execution/spawn.ts";
31
29
  import {
32
- isWorktreeCapableAgent,
33
30
  persistThreadCheckpoint,
34
31
  projectResultsRoot,
35
32
  resolveDispatchModelRoute,
@@ -101,50 +98,31 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
101
98
  resolveAgentTools(candidate, runtime.getActiveTools(), runtime.getToolInfos());
102
99
  const agent = resolveLiveAgentTools(discoveredAgent);
103
100
  const originalCwd = resolve(cwd ?? runCtx.cwd);
104
- let phaseId: string | undefined;
105
- let scope: ReturnType<typeof normalizePhaseScope>;
106
- try {
107
- phaseId = normalizePhaseId(startOptions.phaseId);
108
- scope = normalizePhaseScope(startOptions.scope, originalCwd);
109
- } catch (error) {
110
- return failedStartResult(agentName, task, error instanceof Error ? error.message : String(error));
111
- }
112
- const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent, toolInfos);
113
- // A workflow node is an ordinary managed run whose reporting belongs to
114
- // the graph: it settles into the graph's single summary instead of
115
- // waking the parent once per node.
116
- const quiet = startOptions.quiet === true;
117
- if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
101
+ if (isolation === "worktree" && !isWriteCapableAgent(agent, toolInfos)) {
118
102
  return {
119
103
  ...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
120
104
  isolation,
121
105
  };
122
106
  }
123
- const pendingOwner = findPendingWorkflowPhase(runtime, task, originalCwd, phaseId, startOptions.workflow?.workflowId);
124
- if (pendingOwner) return failedStartResult(agentName, task, `Workflow #${pendingOwner.workflowId} node "${pendingOwner.nodeId}" already owns this pending phase. Inspect the graph with subagent_status; main handles follow-up work.`);
125
- const duplicate = findDuplicateDispatch(runtime.threads.values(), task, originalCwd, phaseId);
107
+ const duplicate = findDuplicateDispatch(runtime.threads.values(), task, originalCwd);
126
108
  if (duplicate) {
127
109
  // A phase stays owned across reloads: an interrupted run keeps its claim
128
110
  // until it is retired, so "let it finish" is wrong advice for a parked
129
- // owner and leaves the caller with no way forward.
111
+ // owner and leaves the caller with no way forward. A retired owner is
112
+ // still releasing its child or worktree after subagent_stop.
130
113
  const owner = duplicate.source;
131
- const remedy = owner.state === "parked" || owner.retired
132
- ? `That interrupted run keeps the phase claimed. Inspect its retained result with subagent_status and finish from that evidence. Retire it with subagent_stop({ id: "${owner.id}" }) only if discarding its retained session is intended; then the phase can be reused. Changing only phaseId cannot bypass equal-task ownership.`
133
- : owner.state === "completed"
134
- ? `Reuse its result via subagent_status({ id: ${owner.id} }); use subagent_message({ id: ${owner.id}, message: "<bounded next step>" }) for additional work. A new deliverable needs its own brief and phaseId.`
135
- : owner.state === "failed"
136
- ? "Inspect the failure with subagent_status and finish the remaining work from its evidence. Do not repeat the same phase."
137
- : "Do not redispatch it; let it finish or steer it with subagent_message. Its result returns automatically; then continue the task.";
114
+ const remedy = owner.retired
115
+ ? "It is still stopping; dispatch the phase again after the stop finishes."
116
+ : owner.state === "parked"
117
+ ? `That interrupted run keeps the phase claimed. Inspect its retained result with subagent_status and finish from that evidence. Retire it with subagent_stop({ id: "${owner.id}" }) only if discarding its retained session is intended; then the phase can be reused.`
118
+ : owner.state === "completed"
119
+ ? `Reuse its result via subagent_status({ id: ${owner.id} }); use subagent_message({ id: ${owner.id}, message: "<bounded next step>" }) for additional work. A new deliverable needs its own brief.`
120
+ : owner.state === "failed"
121
+ ? "Inspect the failure with subagent_status and finish the remaining work from its evidence. Do not repeat the same phase."
122
+ : "Do not redispatch it; let it finish or steer it with subagent_message. Its result returns automatically; then continue the task.";
138
123
  return failedStartResult(agentName, task,
139
124
  `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
140
125
  }
141
- if (writeCapable && scope) {
142
- const conflict = findRuntimeWriterConflict(runtime, scope, { excludeWorkflowId: startOptions.workflow?.workflowId });
143
- if (conflict) {
144
- return failedStartResult(agentName, task,
145
- `Declared writer scope ${conflict.overlap.left} overlaps ${conflict.owner} scope ${conflict.overlap.right}; no run was started.`);
146
- }
147
- }
148
126
  const projectRoot = getProjectRoot(runtime.configPath, originalCwd);
149
127
  const sessionsRoot = join(projectRoot, "sessions");
150
128
  const worktreesRoot = join(projectRoot, "worktrees");
@@ -152,16 +130,10 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
152
130
  let worktree: WorktreeIsolation | undefined;
153
131
  let executionCwd = originalCwd;
154
132
  let worktreeGroup: string | undefined;
155
- const resolvedRoute = resolveDispatchModelRoute(agent, runConfig, runCtx);
156
- let route = isolation === "worktree"
157
- ? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
158
- : resolvedRoute;
133
+ const route = resolveDispatchModelRoute(agent, runConfig, runCtx);
159
134
  const thinkingLevel = route.thinkingLevel;
160
- const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
161
- isolation,
162
- ...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
163
- });
164
- if (!quiet) runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
135
+ const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, isolation);
136
+ runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
165
137
  const generation = 1;
166
138
  const pending: SingleResult = {
167
139
  ...queuedResult(route.agent, task, thinkingLevel),
@@ -194,10 +166,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
194
166
  generation,
195
167
  agentName: agent.name,
196
168
  task,
197
- phaseId,
198
- scope,
199
- writeCapable,
200
- ...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
201
169
  cwd: originalCwd,
202
170
  executionCwd,
203
171
  thinkingLevel,
@@ -216,7 +184,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
216
184
  runtime,
217
185
  runCtx,
218
186
  });
219
- if (isolation === "shared" || worktree) installCurrentLifecycle();
187
+ if (isolation === "shared") installCurrentLifecycle();
220
188
 
221
189
  const onLive = makeLiveHandler(runId, generation);
222
190
  const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
@@ -233,7 +201,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
233
201
  pending.isolation = "shared";
234
202
  delete pending.integrationStatus;
235
203
  pending.isolationNote = `Using the caller's directory: ${error.reason}; automatic worktree isolation is unavailable.`;
236
- route = resolvedRoute;
237
204
  monitor.setIsolation(runId, "shared");
238
205
  runCtx.ui.notify(`#${runId}: ${pending.isolationNote}`, "info");
239
206
  installCurrentLifecycle();
@@ -252,28 +219,24 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
252
219
  installCurrentLifecycle();
253
220
  }
254
221
  }
255
- // Independent runs start immediately; only worktree integration serializes.
256
- monitor.setWaitReason(runId, "starting");
257
222
  // Re-read model preferences after asynchronous worktree preparation.
258
223
  let activeRoute = route;
259
224
  const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
260
225
  try {
261
226
  const startConfig = await loadConfig(runtime.configPath);
262
- const resolvedStart = resolveDispatchModelRoute(agent, startConfig, runCtx);
263
- activeRoute = isolation === "worktree"
264
- ? { ...resolvedStart, agent: withWorktreeSystemPrompt(resolvedStart.agent) }
265
- : resolvedStart;
227
+ activeRoute = resolveDispatchModelRoute(agent, startConfig, runCtx);
266
228
  monitor.setModel(runId, activeRoute.agent.model);
267
229
  monitor.setThinking(runId, activeRoute.thinkingLevel);
268
230
  } catch {
269
231
  /* keep the dispatch-time route when fresh config is unavailable */
270
232
  }
233
+ const launchAgent = worktree ? withWorktreeSystemPrompt(activeRoute.agent, worktree) : activeRoute.agent;
271
234
  let result: SingleResult;
272
235
  try {
273
236
  result = await runSingleAgentWithMainFallback(
274
237
  {
275
238
  defaultCwd: executionCwd,
276
- agent: activeRoute.agent,
239
+ agent: launchAgent,
277
240
  resolveAgentForAttempt: resolveLiveAgentTools,
278
241
  agentName,
279
242
  task,
@@ -314,7 +277,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
314
277
  thread.sessionDir = result.sessionDir;
315
278
  thread.lastResult = result;
316
279
  runtime.retainSession(result);
317
- monitor.setModel(runId, result.model, result.modelFallbackFrom);
280
+ monitor.setModel(runId, result.model);
318
281
  monitor.setThinking(runId, result.thinking);
319
282
  // Checkpoint the session location durably: a crash or reload before
320
283
  // settlement still restores this thread with its retained context.
@@ -333,7 +296,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
333
296
  // aborted partial.
334
297
  if (backgroundSignal.aborted || !runtime.sessionActive) return;
335
298
 
336
- if (thread.retireOnSettle) runtime.retireThreadSession(thread);
337
299
  // Claim terminal settlement synchronously before the first slow await.
338
300
  // Shutdown therefore either wins while the child is still active, or is rejected
339
301
  // once settlement owns the generation. Destructive stop may supersede
@@ -367,30 +329,23 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
367
329
  const ownedController = thread.queueController;
368
330
  if (runtime.runControllers.get(runId) === ownedController) runtime.runControllers.delete(runId);
369
331
  thread.queueController = undefined;
370
- finishRun(
371
- runId,
372
- failed ? "failed" : "done",
373
- quiet || modelLevel || dispatchFailed ? { silent: true } : undefined,
374
- );
332
+ finishRun(runId, failed ? "failed" : "done", modelLevel || dispatchFailed ? { silent: true } : undefined);
375
333
  runtime.registerRunResult(runId, result);
376
- if (!quiet) {
377
- const block = formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
334
+ const completion: CompletionMessageItem = {
335
+ agent: result.agent,
336
+ block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
378
337
  resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? originalCwd),
379
- });
380
- const completion: CompletionMessageItem = {
381
- agent: result.agent,
382
- block: modelLevel ? `${block}\n\n${modelLevelTakeoverNote(result)}` : block,
383
- usage: result.usage,
384
- model: result.model,
385
- };
386
- if (modelLevel) {
387
- const detail = notifyDetail(result.errorMessage, "model unavailable or broken");
388
- runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
389
- } else if (dispatchFailed) {
390
- runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
391
- }
392
- runtime.publishRunCompletion(runId, completion, failed);
338
+ }),
339
+ usage: result.usage,
340
+ model: result.model,
341
+ };
342
+ if (modelLevel) {
343
+ const detail = notifyDetail(result.errorMessage, "model unavailable or broken");
344
+ runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
345
+ } else if (dispatchFailed) {
346
+ runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
393
347
  }
348
+ runtime.publishRunCompletion(runId, completion, failed);
394
349
  } finally {
395
350
  if (ownsSettlement()) thread.lifecycleOperation = undefined;
396
351
  }
@@ -461,13 +416,13 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
461
416
  runtime.runControllers.delete(runId);
462
417
  thread.queueController = undefined;
463
418
  if (!runtime.sessionActive || !ownsSettlement()) return;
464
- if (quiet) return;
465
419
  try {
466
420
  runCtx.ui.notify(`✗ ${crashed.agent} dispatch failed: ${notifyDetail(crashed.errorMessage, "dispatch crashed")}`, "error");
467
421
  runtime.publishRunCompletion(runId, {
468
422
  agent: crashed.agent,
469
423
  block: formatCompletionBlock(crashed, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, crashed.projectCwd ?? originalCwd) }),
470
424
  usage: crashed.usage,
425
+ model: crashed.model,
471
426
  }, true);
472
427
  } catch {
473
428
  /* a second delivery failure must not throw through the queue */
@@ -53,9 +53,6 @@ function createRestoredThread(
53
53
  generation: record.generation,
54
54
  agentName: record.agentName,
55
55
  task: record.task,
56
- phaseId: record.phaseId,
57
- scope: record.scope,
58
- writeCapable: record.writeCapable ?? record.agentName !== "scout",
59
56
  cwd: record.cwd,
60
57
  executionCwd: record.executionCwd,
61
58
  ...(record.thinkingLevel ? { thinkingLevel: record.thinkingLevel as ThinkingLevel } : {}),
@@ -155,6 +152,7 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
155
152
  agent: record.agentName,
156
153
  block: `### Subagent restoration failed: #${record.runId} ${record.agentName}\n\n${reason}`,
157
154
  usage: failed.usage,
155
+ model: failed.model,
158
156
  }, true);
159
157
  continue;
160
158
  }
@@ -4,8 +4,7 @@ import { utimesSync } from "node:fs";
4
4
  import { realpath } from "node:fs/promises";
5
5
  import { join, resolve } from "node:path";
6
6
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
- import { isWriteCapableAgent, type AgentConfig, type ToolMetadata } from "../delegation/agents.ts";
8
- import type { PhaseScope } from "../delegation/phase-scope.ts";
7
+ import type { AgentConfig } from "../delegation/agents.ts";
9
8
  import { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
10
9
  import { removeThreadRecord, threadRecordFromThread, threadRecordIdentity, upsertThreadRecord } from "./durable.ts";
11
10
  import {
@@ -16,10 +15,9 @@ import {
16
15
  resolveAgentModelRoute,
17
16
  resolveThinkingLevel,
18
17
  } from "../configuration/models.ts";
19
- import type { RunWorkflowTag } from "../presentation/monitor.ts";
20
18
  import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
21
19
  import { getProjectRoot, type SingleResult } from "../execution/spawn.ts";
22
- import { resolveRepositoryRoot, type IsolationMode } from "../isolation/worktree.ts";
20
+ import { resolveRepositoryRoot, type IsolationMode, type WorktreeIsolation } from "../isolation/worktree.ts";
23
21
 
24
22
  /** Control operations must never wait forever on a settling generation: the
25
23
  * queue task can legitimately spend minutes in worktree finalization (bounded
@@ -104,19 +102,14 @@ export function persistThreadCheckpoint(
104
102
  void write.catch(() => undefined);
105
103
  }
106
104
 
107
- const WORKTREE_ISOLATION_INSTRUCTIONS =
108
- "You are running in a temporary detached Git worktree. Work only in the current cwd; interpret paths from the brief relative to this checkout. Do not write to the original checkout, create another worktree, or copy/apply changes back manually. The runtime will merge your tracked, deleted, and untracked changes after you finish.";
109
-
110
- export function withWorktreeSystemPrompt(agent: AgentConfig): AgentConfig {
111
- return {
112
- ...agent,
113
- systemPrompt: `${agent.systemPrompt.trimEnd()}\n\n${WORKTREE_ISOLATION_INSTRUCTIONS}`.trim(),
114
- };
115
- }
116
-
117
- /** Only write-capable agents can run in an isolated worktree. */
118
- export function isWorktreeCapableAgent(agent: AgentConfig, toolInfos?: readonly ToolMetadata[]): boolean {
119
- return isWriteCapableAgent(agent, toolInfos);
105
+ /** Briefs name paths in the caller's checkout. Naming both roots lets an
106
+ * isolated child map them into its worktree instead of editing the original. */
107
+ export function withWorktreeSystemPrompt(
108
+ agent: AgentConfig,
109
+ worktree: Pick<WorktreeIsolation, "originalRoot" | "worktreePath">,
110
+ ): AgentConfig {
111
+ const instructions = `You are running in a temporary detached Git worktree at ${worktree.worktreePath}, a snapshot of the original checkout ${worktree.originalRoot}. Work only inside this worktree: map every brief path under the original checkout to the same relative path here. Do not write to the original checkout, create another worktree, or copy/apply changes back manually. The runtime merges your tracked, deleted, and untracked changes after you finish.`;
112
+ return { ...agent, systemPrompt: `${agent.systemPrompt.trimEnd()}\n\n${instructions}` };
120
113
  }
121
114
 
122
115
  export interface DispatchEnvironment {
@@ -129,20 +122,10 @@ export interface DispatchEnvironment {
129
122
  export interface StartBackgroundOptions {
130
123
  /** A private copy of a settled session used for a follow-up run. */
131
124
  resumeSession?: { sessionId: string; sessionDir: string };
132
- phaseId?: string;
133
- scope?: PhaseScope;
134
- /** A false hint cannot downgrade a live write-capable role. */
135
- writeCapable?: boolean;
136
125
  /** Omitted public isolation may fall back only when no Git baseline exists. */
137
126
  automaticIsolation?: boolean;
138
127
  /** Chosen by the tool call before the queue can start a fast child. */
139
128
  deliveryRoute?: "background" | "await";
140
- /** A workflow node reports through its graph's single summary: no per-run
141
- * completion message and no per-run toast, so a wide graph cannot flood the
142
- * parent with one wake-up per node. */
143
- quiet?: boolean;
144
- /** Graph membership rendered by the widget and node status rows. */
145
- workflow?: RunWorkflowTag;
146
129
  }
147
130
 
148
131
  export type StartBackgroundInternal = (