@ferris1225/pi-subagents 6.0.4 → 7.0.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.
@@ -9,10 +9,10 @@
9
9
 
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { join, resolve } from "node:path";
12
- import { resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
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
18
  import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
@@ -22,12 +22,11 @@ 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";
29
29
  import {
30
- isWorktreeCapableAgent,
31
30
  persistThreadCheckpoint,
32
31
  projectResultsRoot,
33
32
  resolveDispatchModelRoute,
@@ -99,8 +98,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
99
98
  resolveAgentTools(candidate, runtime.getActiveTools(), runtime.getToolInfos());
100
99
  const agent = resolveLiveAgentTools(discoveredAgent);
101
100
  const originalCwd = resolve(cwd ?? runCtx.cwd);
102
- const quiet = startOptions.quiet === true;
103
- if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
101
+ if (isolation === "worktree" && !isWriteCapableAgent(agent, toolInfos)) {
104
102
  return {
105
103
  ...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
106
104
  isolation,
@@ -110,15 +108,18 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
110
108
  if (duplicate) {
111
109
  // A phase stays owned across reloads: an interrupted run keeps its claim
112
110
  // until it is retired, so "let it finish" is wrong advice for a parked
113
- // 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.
114
113
  const owner = duplicate.source;
115
- const remedy = owner.state === "parked" || owner.retired
116
- ? `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.`
117
- : owner.state === "completed"
118
- ? `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.`
119
- : owner.state === "failed"
120
- ? "Inspect the failure with subagent_status and finish the remaining work from its evidence. Do not repeat the same phase."
121
- : "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.";
122
123
  return failedStartResult(agentName, task,
123
124
  `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
124
125
  }
@@ -129,15 +130,11 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
129
130
  let worktree: WorktreeIsolation | undefined;
130
131
  let executionCwd = originalCwd;
131
132
  let worktreeGroup: string | undefined;
132
- const resolvedRoute = resolveDispatchModelRoute(agent, runConfig, runCtx);
133
- let route = isolation === "worktree"
134
- ? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
135
- : resolvedRoute;
133
+ const route = resolveDispatchModelRoute(agent, runConfig, runCtx);
134
+ if (route.error) return failedStartResult(agentName, task, route.error);
136
135
  const thinkingLevel = route.thinkingLevel;
137
- const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
138
- isolation,
139
- });
140
- if (!quiet) runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
136
+ const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, isolation);
137
+ runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
141
138
  const generation = 1;
142
139
  const pending: SingleResult = {
143
140
  ...queuedResult(route.agent, task, thinkingLevel),
@@ -188,7 +185,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
188
185
  runtime,
189
186
  runCtx,
190
187
  });
191
- if (isolation === "shared" || worktree) installCurrentLifecycle();
188
+ if (isolation === "shared") installCurrentLifecycle();
192
189
 
193
190
  const onLive = makeLiveHandler(runId, generation);
194
191
  const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
@@ -205,7 +202,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
205
202
  pending.isolation = "shared";
206
203
  delete pending.integrationStatus;
207
204
  pending.isolationNote = `Using the caller's directory: ${error.reason}; automatic worktree isolation is unavailable.`;
208
- route = resolvedRoute;
209
205
  monitor.setIsolation(runId, "shared");
210
206
  runCtx.ui.notify(`#${runId}: ${pending.isolationNote}`, "info");
211
207
  installCurrentLifecycle();
@@ -224,34 +220,30 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
224
220
  installCurrentLifecycle();
225
221
  }
226
222
  }
227
- // Independent runs start immediately; only worktree integration serializes.
228
- monitor.setWaitReason(runId, "starting");
229
223
  // Re-read model preferences after asynchronous worktree preparation.
230
224
  let activeRoute = route;
231
225
  const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
232
226
  try {
233
227
  const startConfig = await loadConfig(runtime.configPath);
234
- const resolvedStart = resolveDispatchModelRoute(agent, startConfig, runCtx);
235
- activeRoute = isolation === "worktree"
236
- ? { ...resolvedStart, agent: withWorktreeSystemPrompt(resolvedStart.agent) }
237
- : resolvedStart;
228
+ activeRoute = resolveDispatchModelRoute(agent, startConfig, runCtx);
238
229
  monitor.setModel(runId, activeRoute.agent.model);
239
230
  monitor.setThinking(runId, activeRoute.thinkingLevel);
240
231
  } catch {
241
232
  /* keep the dispatch-time route when fresh config is unavailable */
242
233
  }
234
+ const launchAgent = worktree ? withWorktreeSystemPrompt(activeRoute.agent, worktree) : activeRoute.agent;
243
235
  let result: SingleResult;
244
236
  try {
245
- result = await runSingleAgentWithMainFallback(
237
+ if (activeRoute.error) throw new Error(activeRoute.error);
238
+ result = await runWorker(
246
239
  {
247
240
  defaultCwd: executionCwd,
248
- agent: activeRoute.agent,
249
- resolveAgentForAttempt: resolveLiveAgentTools,
241
+ agent: launchAgent,
242
+ resolveAgentBeforeLaunch: resolveLiveAgentTools,
250
243
  agentName,
251
244
  task,
252
245
  cwd: executionCwd,
253
246
  thinkingLevel: activeRoute.thinkingLevel,
254
- thinkingLevelForModel: activeRoute.thinkingLevelForModel,
255
247
  signal: backgroundSignal,
256
248
  onLive,
257
249
  control,
@@ -260,7 +252,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
260
252
  ...(startOptions.resumeSession ?? {}),
261
253
  scratchRoot,
262
254
  },
263
- activeRoute.mainFallbackRef,
264
255
  );
265
256
  } catch (error) {
266
257
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -286,7 +277,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
286
277
  thread.sessionDir = result.sessionDir;
287
278
  thread.lastResult = result;
288
279
  runtime.retainSession(result);
289
- monitor.setModel(runId, result.model, result.modelFallbackFrom);
280
+ monitor.setModel(runId, result.model);
290
281
  monitor.setThinking(runId, result.thinking);
291
282
  // Checkpoint the session location durably: a crash or reload before
292
283
  // settlement still restores this thread with its retained context.
@@ -305,7 +296,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
305
296
  // aborted partial.
306
297
  if (backgroundSignal.aborted || !runtime.sessionActive) return;
307
298
 
308
- if (thread.retireOnSettle) runtime.retireThreadSession(thread);
309
299
  // Claim terminal settlement synchronously before the first slow await.
310
300
  // Shutdown therefore either wins while the child is still active, or is rejected
311
301
  // once settlement owns the generation. Destructive stop may supersede
@@ -339,30 +329,23 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
339
329
  const ownedController = thread.queueController;
340
330
  if (runtime.runControllers.get(runId) === ownedController) runtime.runControllers.delete(runId);
341
331
  thread.queueController = undefined;
342
- finishRun(
343
- runId,
344
- failed ? "failed" : "done",
345
- quiet || modelLevel || dispatchFailed ? { silent: true } : undefined,
346
- );
332
+ finishRun(runId, failed ? "failed" : "done", modelLevel || dispatchFailed ? { silent: true } : undefined);
347
333
  runtime.registerRunResult(runId, result);
348
- if (!quiet) {
349
- const block = formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
334
+ const completion: CompletionMessageItem = {
335
+ agent: result.agent,
336
+ block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
350
337
  resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? originalCwd),
351
- });
352
- const completion: CompletionMessageItem = {
353
- agent: result.agent,
354
- block: modelLevel ? `${block}\n\n${modelLevelTakeoverNote(result)}` : block,
355
- usage: result.usage,
356
- model: result.model,
357
- };
358
- if (modelLevel) {
359
- const detail = notifyDetail(result.errorMessage, "model unavailable or broken");
360
- runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
361
- } else if (dispatchFailed) {
362
- runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
363
- }
364
- 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");
365
347
  }
348
+ runtime.publishRunCompletion(runId, completion, failed);
366
349
  } finally {
367
350
  if (ownsSettlement()) thread.lifecycleOperation = undefined;
368
351
  }
@@ -433,13 +416,13 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
433
416
  runtime.runControllers.delete(runId);
434
417
  thread.queueController = undefined;
435
418
  if (!runtime.sessionActive || !ownsSettlement()) return;
436
- if (quiet) return;
437
419
  try {
438
420
  runCtx.ui.notify(`✗ ${crashed.agent} dispatch failed: ${notifyDetail(crashed.errorMessage, "dispatch crashed")}`, "error");
439
421
  runtime.publishRunCompletion(runId, {
440
422
  agent: crashed.agent,
441
423
  block: formatCompletionBlock(crashed, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, crashed.projectCwd ?? originalCwd) }),
442
424
  usage: crashed.usage,
425
+ model: crashed.model,
443
426
  }, true);
444
427
  } catch {
445
428
  /* a second delivery failure must not throw through the queue */
@@ -152,6 +152,7 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
152
152
  agent: record.agentName,
153
153
  block: `### Subagent restoration failed: #${record.runId} ${record.agentName}\n\n${reason}`,
154
154
  usage: failed.usage,
155
+ model: failed.model,
155
156
  }, true);
156
157
  continue;
157
158
  }
@@ -4,8 +4,8 @@ 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 { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
7
+ import type { AgentConfig } from "../delegation/agents.ts";
8
+ import type { SubagentsConfig, ThinkingLevel } from "../configuration/config.ts";
9
9
  import { removeThreadRecord, threadRecordFromThread, threadRecordIdentity, upsertThreadRecord } from "./durable.ts";
10
10
  import {
11
11
  availableModelsInScope,
@@ -17,7 +17,7 @@ import {
17
17
  } from "../configuration/models.ts";
18
18
  import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
19
19
  import { getProjectRoot, type SingleResult } from "../execution/spawn.ts";
20
- import { resolveRepositoryRoot, type IsolationMode } from "../isolation/worktree.ts";
20
+ import { resolveRepositoryRoot, type IsolationMode, type WorktreeIsolation } from "../isolation/worktree.ts";
21
21
 
22
22
  /** Control operations must never wait forever on a settling generation: the
23
23
  * queue task can legitimately spend minutes in worktree finalization (bounded
@@ -102,19 +102,14 @@ export function persistThreadCheckpoint(
102
102
  void write.catch(() => undefined);
103
103
  }
104
104
 
105
- const WORKTREE_ISOLATION_INSTRUCTIONS =
106
- "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.";
107
-
108
- export function withWorktreeSystemPrompt(agent: AgentConfig): AgentConfig {
109
- return {
110
- ...agent,
111
- systemPrompt: `${agent.systemPrompt.trimEnd()}\n\n${WORKTREE_ISOLATION_INSTRUCTIONS}`.trim(),
112
- };
113
- }
114
-
115
- /** Only write-capable agents can run in an isolated worktree. */
116
- export function isWorktreeCapableAgent(agent: AgentConfig, toolInfos?: readonly ToolMetadata[]): boolean {
117
- 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}` };
118
113
  }
119
114
 
120
115
  export interface DispatchEnvironment {
@@ -131,8 +126,6 @@ export interface StartBackgroundOptions {
131
126
  automaticIsolation?: boolean;
132
127
  /** Chosen by the tool call before the queue can start a fast child. */
133
128
  deliveryRoute?: "background" | "await";
134
- /** Suppress per-run completion messages and toasts when needed. */
135
- quiet?: boolean;
136
129
  }
137
130
 
138
131
  export type StartBackgroundInternal = (
@@ -150,9 +143,8 @@ export interface ThreadLifecycleDeps {
150
143
 
151
144
  interface DispatchModelRoute {
152
145
  agent: AgentConfig;
153
- mainFallbackRef?: string;
146
+ error?: string;
154
147
  thinkingLevel: ThinkingLevel;
155
- thinkingLevelForModel: (ref?: string) => ThinkingLevel;
156
148
  }
157
149
 
158
150
  export function resolveDispatchModelRoute(
@@ -163,25 +155,16 @@ export function resolveDispatchModelRoute(
163
155
  const availableModels = availableModelsInScope(ctx);
164
156
  const mainRef = currentModelRef(ctx);
165
157
  const route = resolveAgentModelRoute({
166
- selectedRef: config.agentModels[agent.name],
158
+ selectedRef: config.model,
167
159
  mainRef,
168
160
  availableRefs: availableModels.map(modelRef),
169
161
  });
170
- // A `/subagents-setup` override wins; otherwise the role default. No
171
- // per-call thinking.
172
- const preferred =
173
- config.agentThinkingLevels[agent.name] ?? roleThinkingLevel(agent.name);
174
- const thinkingLevelForModel = (ref?: string): ThinkingLevel => {
175
- const model = ref === mainRef && ctx.model
176
- ? ctx.model
177
- : findModelByRef(availableModels, ref);
178
- return resolveThinkingLevel(model, preferred);
179
- };
162
+ const model = route.primaryRef === mainRef && ctx.model
163
+ ? ctx.model : findModelByRef(availableModels, route.primaryRef);
180
164
  return {
181
165
  agent: { ...agent, model: route.primaryRef },
182
- mainFallbackRef: route.mainFallbackRef,
183
- thinkingLevel: thinkingLevelForModel(route.primaryRef),
184
- thinkingLevelForModel,
166
+ thinkingLevel: resolveThinkingLevel(model, config.thinking),
167
+ ...(route.unavailableSelectedRef ? { error: `Worker model ${route.unavailableSelectedRef} is unavailable in this session. Dispatch paused; restore availability or choose a worker with /subagents-setup. No main-model worker was started.` } : {}),
185
168
  };
186
169
  }
187
170
 
@@ -1,10 +1,9 @@
1
1
  /** Run inspection, steering, completed-run follow-ups, and destructive cancellation. */
2
2
 
3
- import { randomUUID } from "node:crypto";
4
3
  import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";
5
4
  import { basename, join } from "node:path";
6
5
  import type { Message } from "@earendil-works/pi-ai";
7
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
8
7
  import { Text } from "@earendil-works/pi-tui";
9
8
  import { Type } from "typebox";
10
9
  import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
@@ -17,12 +16,12 @@ import { cancelActiveWork } from "./cancellation.ts";
17
16
  import { stopThreads } from "./stop.ts";
18
17
  import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
19
18
  import { emptyUsage } from "../execution/run-control.ts";
20
- import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../presentation/monitor.ts";
19
+ import { formatDuration, formatTaskSummary, monitor } from "../presentation/monitor.ts";
21
20
  import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
22
21
  import { projectResultsRoot } from "./thread-shared.ts";
23
22
  import { getResultError } from "../execution/spawn.ts";
24
23
 
25
- function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
24
+ function renderFirstLine(result: { content?: unknown }, label: string, theme: Theme): Text {
26
25
  const parts = (result.content ?? []) as Array<{ type: string; text?: string }>;
27
26
  const text = parts
28
27
  .map((part) => (typeof part.text === "string" ? part.text : ""))
@@ -113,7 +112,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
113
112
  executionCwd: thread.executionCwd,
114
113
  taskSummary: formatTaskSummary(thread.task, 80, false),
115
114
  state,
116
- waitReason: state === "queued" ? live?.waitReason : undefined,
117
115
  activity: live?.activity,
118
116
  recentActivity: live?.recentActivity ?? [],
119
117
  lastSteering: thread.lastSteering,
@@ -140,7 +138,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
140
138
  const text = runs.length === 0
141
139
  ? params.id === undefined ? "No subagent runs in this parent session." : `No subagent run matches #${params.id}.`
142
140
  : runs.map((run) => {
143
- const wait = run.waitReason ? ` — ${runWaitLabel({ status: "queued", waitReason: run.waitReason })}` : "";
141
+ const wait = run.state === "queued" ? " — starting" : "";
144
142
  const lines = [`#${run.id} ${run.agent} · ${run.state} · ${formatDuration(run.elapsedMs)}${wait}`, ` task: ${run.taskSummary}`];
145
143
  if (run.isolationNote) lines.push(` isolation: ${run.isolationNote}`);
146
144
  if (run.lastSteering) lines.push(` last steering: ${run.lastSteering.disposition} · acknowledged ${formatDuration(Math.max(0, Date.now() - run.lastSteering.acknowledgedAt))} ago${run.lastSteering.requestId ? ` · request ${run.lastSteering.requestId}` : ""} · ${run.lastSteering.message}`);
@@ -191,13 +189,13 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
191
189
  pi.registerTool({
192
190
  name: "subagent_message",
193
191
  label: "Subagent Message",
194
- description: "Send a steering message to a running subagent, or continue a successfully completed run. Omit context or use \"auto\" to reuse its retained session when available and otherwise start from a bounded summary, reporting the fallback. Use \"session\" only when full history is required; missing history is an error. Use \"summary\" for a new next step with only the earlier objective, result, and touched files. Session copies preserve history and the provider cache key; summary runs have neither. Use wait:true to receive a completed-run follow-up in this call; one-shot print/JSON sessions wait by default. Steering waits for the child RPC acknowledgement and reports queued, handled by an input hook, or accepted with queue state unknown. Receipt is not proof of model execution; status retains the latest acknowledgement.",
192
+ description: "Steer a running subagent, or continue a successfully completed run with a new bounded step in the same role and workspace. Steering waits for the child's RPC acknowledgement and reports queued, handled by an input hook, or accepted with queue state unknown; receipt is not proof of model execution, and status retains the latest acknowledgement. A continuation chooses its history with the context parameter. Use wait:true to receive its result in this call; one-shot print/JSON sessions wait by default.",
195
193
  exposure: "model-only",
196
194
  executionMode: "parallel",
197
195
  parameters: Type.Object({
198
196
  id: Type.Integer({ minimum: 1, description: "Exact run id in this parent session." }),
199
197
  message: Type.String({ minLength: 1, pattern: "\\S", description: "Additional instruction or follow-up question." }),
200
- context: Type.Optional(Type.String({ enum: ["auto", "session", "summary"], description: "auto (default) uses the retained session when available, otherwise a bounded summary and reports the fallback. session requires the full retained history and fails if unavailable. summary always starts fresh with the earlier objective, result, and touched files; no history or cache reuse." })),
198
+ context: Type.Optional(Type.String({ enum: ["auto", "session", "summary"], description: "Completed-run history. auto (default): continue a copy of the retained session when available, otherwise start from a bounded summary and report the fallback. session: require the full history, reusing the provider cache key; fails when unavailable. summary: start fresh with only the earlier objective, result, and touched files." })),
201
199
  wait: WaitSchema,
202
200
  }),
203
201
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
@@ -259,7 +257,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
259
257
  if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while the follow-up was prepared.");
260
258
  const selectedContext = copyDir ? "session" : "summary";
261
259
  const task = copyDir
262
- ? `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`
260
+ ? `Follow-up to run #${thread.id}:\n${params.message}`
263
261
  : buildSummaryFollowUp(thread, params.message);
264
262
  const wait = params.wait ?? (ctx.hasUI === false);
265
263
  const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
@@ -351,15 +349,12 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
351
349
  }
352
350
 
353
351
  const { stopped, retainedIntegration, pendingIntegration, completionResults } = await stopThreads(runtime, targets);
354
- if (completionResults.length > 0) {
355
- runtime.sendCompletionGroup(completionResults.map((result) => ({
356
- agent: result.agent,
357
- block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
358
- triggerTurn: true,
359
- usage: result.usage,
360
- })));
361
- runtime.completionBatcher.flush();
362
- }
352
+ runtime.sendCompletionGroup(completionResults.map((result) => ({
353
+ agent: result.agent,
354
+ block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
355
+ usage: result.usage,
356
+ model: result.model,
357
+ })));
363
358
  return {
364
359
  content: [{
365
360
  type: "text",
@@ -1,34 +1,34 @@
1
- /** Session-start recovery, stale-model cleanup, and progress-surface installation. */
1
+ /** Session-start recovery, worker availability, and progress-surface installation. */
2
2
 
3
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { loadConfig, saveConfig } from "../configuration/config.ts";
5
- import { availableModelsInScope, filterUnavailableModelOverrides } from "../configuration/models.ts";
5
+ import { findModelByRef, modelRef } from "../configuration/models.ts";
6
6
  import { ensureDefaultConfig } from "../configuration/setup.ts";
7
7
  import { announceRecoveryRecords, relocateRecoveryManifest } from "../isolation/recovery.ts";
8
8
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
9
9
  import { installActiveRunsWidget } from "./widget.ts";
10
10
 
11
- /** Drop unavailable model overrides back to dynamic main-model routing. */
12
- async function removeUnavailableAgentModels(
13
- ctx: { ui: { notify: (message: string, kind: "info" | "warning" | "error") => void } } & Parameters<typeof availableModelsInScope>[0],
11
+ /** Preserve the worker choice during outages instead of spending main-model quota. */
12
+ async function checkWorkerModel(
13
+ ctx: Pick<ExtensionContext, "ui" | "modelRegistry">,
14
14
  runtime: SubagentRuntime,
15
15
  ): Promise<void> {
16
16
  try {
17
17
  const config = await loadConfig(runtime.configPath);
18
- const overrides = Object.entries(config.agentModels);
19
- if (overrides.length === 0) return;
20
- const { kept, dropped } = filterUnavailableModelOverrides(config.agentModels, availableModelsInScope(ctx));
21
- const rewritten = JSON.stringify(kept) !== JSON.stringify(config.agentModels);
22
- if (!rewritten && dropped.length === 0) return;
23
- await saveConfig({ ...config, agentModels: kept }, runtime.configPath);
24
- if (dropped.length === 0) return;
25
- const list = dropped.map(({ agent, ref }) => `${agent}: ${ref}`).join(", ");
18
+ if (!config.model) return;
19
+ const selected = findModelByRef(ctx.modelRegistry.getAvailable(), config.model);
20
+ const liveRef = selected ? modelRef(selected) : undefined;
21
+ if (liveRef === config.model) return;
22
+ if (liveRef) {
23
+ await saveConfig({ ...config, model: liveRef }, runtime.configPath);
24
+ return;
25
+ }
26
26
  ctx.ui.notify(
27
- `pi-subagents: removed stale agent model overrides that are no longer available (${list}). Those agents now use their role's default model route; run /subagents-setup to re-pick.`,
27
+ `pi-subagents: worker model ${config.model} is unavailable. Its setting is preserved and dispatch is paused. Restore availability or run /subagents-setup to choose another.`,
28
28
  "warning",
29
29
  );
30
30
  } catch {
31
- /* stale-model cleanup is non-fatal */
31
+ /* availability notices are non-fatal */
32
32
  }
33
33
  }
34
34
 
@@ -43,7 +43,7 @@ export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime
43
43
  // must not prevent the rest of the session UI from being installed.
44
44
  ctx.ui.notify(`pi-subagents: recovery inspection failed; continuing startup: ${error instanceof Error ? error.message : String(error)}`, "warning");
45
45
  }
46
- await removeUnavailableAgentModels(ctx, runtime);
46
+ await checkWorkerModel(ctx, runtime);
47
47
  // Bootstrap also runs on session_start; wait so this notice sees restored
48
48
  // threads instead of racing an empty list.
49
49
  await runtime.durableRestore;
@@ -4,15 +4,15 @@
4
4
  * and run-id matching.
5
5
  */
6
6
 
7
+ import { readFileSync } from "node:fs";
7
8
  import type { AgentConfig } from "../delegation/agents.ts";
8
9
  import { formatUsageCompact, runLabel, shrinkRunLabel } from "./monitor.ts";
9
10
  import { emptyUsage } from "../execution/run-control.ts";
10
11
  import {
11
- RESULT_LINE_MAX,
12
12
  getResultError,
13
13
  getResultOutput,
14
14
  isFailedResult,
15
- truncateResultOutput,
15
+ isModelLevelFailure,
16
16
  writeResultArtifact,
17
17
  type SingleResult,
18
18
  type UsageStats,
@@ -73,6 +73,34 @@ export interface CompletionFormatOptions {
73
73
  * tight enough to stay a hint rather than a second copy of the task. */
74
74
  const COMPLETION_LABEL_MAX = 24;
75
75
 
76
+ /** Characters of one full line in the inline budget of a completion block. */
77
+ export const RESULT_LINE_CHARS = 200;
78
+
79
+ /** The result's existing artifact when it already holds exactly this output.
80
+ * Results derived from a delivered one (a crash or stop wrapper) carry its path
81
+ * but different text, so they get their own file. */
82
+ function reusableArtifact(result: SingleResult, output: string): string | undefined {
83
+ if (!result.resultFile) return undefined;
84
+ try {
85
+ return readFileSync(result.resultFile, "utf8") === output ? result.resultFile : undefined;
86
+ } catch {
87
+ return undefined;
88
+ }
89
+ }
90
+
91
+ /** How an answer exceeds the inline budget of `maxLines` lines and the
92
+ * characters of that many full lines; undefined when it fits. Long prose lines
93
+ * fit, so only an oversized answer moves to its result file. */
94
+ function inlineOverflow(output: string, maxLines: number): string | undefined {
95
+ const lineCount = output.split("\n").length;
96
+ const maxChars = maxLines * RESULT_LINE_CHARS;
97
+ const overflow = [
98
+ lineCount > maxLines ? `${lineCount} lines` : undefined,
99
+ output.length > maxChars ? `${output.length} characters` : undefined,
100
+ ].filter(Boolean);
101
+ return overflow.length > 0 ? overflow.join(" · ") : undefined;
102
+ }
103
+
76
104
  export function formatCompletionBlock(
77
105
  result: SingleResult,
78
106
  maxResultLines: number,
@@ -83,17 +111,14 @@ export function formatCompletionBlock(
83
111
  const status = failed ? "failed" : "completed";
84
112
  const usage = formatUsage(result.usage);
85
113
  const output = getResultOutput(result);
86
- const { text, truncated, shownLines, totalLines, widthClipped } = truncateResultOutput(output, maxResultLines);
87
- const fallbackNote = result.modelFallbackFrom
88
- ? ` (selected model ${result.modelFallbackFrom} failed → main ${result.model ?? "dynamic default"})`
89
- : "";
114
+ const overflow = inlineOverflow(output, maxResultLines);
90
115
  const runNote = result.runId !== undefined ? ` · run #${result.runId}` : "";
91
116
  // A short task-derived label, not the task itself: the parent authored the
92
117
  // task and still has it in context, but a wide fan-out of same-agent runs
93
118
  // needs more than a run id to tell completions apart.
94
119
  const label = shrinkRunLabel(runLabel(result.task), COMPLETION_LABEL_MAX);
95
120
  const lines = [
96
- `### [${result.agent}${label ? `·${label}` : ""}] ${status}${usage ? ` (${usage})` : ""}${fallbackNote}${runNote}`,
121
+ `### [${result.agent}${label ? `·${label}` : ""}] ${status}${usage ? ` (${usage})` : ""}${runNote}`,
97
122
  "",
98
123
  ];
99
124
  if (result.isolation === "worktree") {
@@ -114,7 +139,7 @@ export function formatCompletionBlock(
114
139
  lines.push("");
115
140
  }
116
141
  if (result.isolationNote) lines.push(`Isolation: ${result.isolationNote}`, "");
117
- if (!truncated) lines.push(text);
142
+ if (!overflow) lines.push(output);
118
143
  // Failed-tool diagnostics ride along only when the run itself failed: they
119
144
  // explain the failure, while on a successful run a transient failed call
120
145
  // (no-match grep, rejected edit) is noise the agent already worked around.
@@ -125,31 +150,30 @@ export function formatCompletionBlock(
125
150
  ...failedTools.map((tool) => `- ${tool.toolName}: ${tool.error.trim() || "(no output)"}`),
126
151
  );
127
152
  }
128
- if (truncated) {
153
+ if (overflow) {
129
154
  // No inline copy at all: a truncated dump reads as complete while
130
155
  // hiding the rest, and the parent re-reads the full text from the file
131
156
  // anyway, paying for the same content twice. The notice only routes it.
132
- const artifact = options.resultRoot
133
- ? writeResultArtifact(output, result.agent, options.resultRoot)
134
- : "(result root unavailable)";
157
+ // Every delivery of the same result names one artifact.
158
+ const artifact = reusableArtifact(result, output)
159
+ ?? (options.resultRoot ? writeResultArtifact(output, result.agent, options.resultRoot) : "(result root unavailable)");
135
160
  if (options.resultRoot) result.resultFile = artifact;
136
- const loss = [
137
- shownLines < totalLines ? `${totalLines} lines` : undefined,
138
- widthClipped ? `lines wider than ${RESULT_LINE_MAX} characters` : undefined,
139
- ].filter(Boolean).join(" · ");
140
161
  lines.push(
141
162
  "",
142
- `⚠ The child's answer (${loss}) is not inlined here, so it is delivered exactly once. Read the complete result file \`${artifact}\`; it holds the full, untruncated output.`,
163
+ `⚠ The child's answer (${overflow}) is not inlined here, so it is delivered exactly once. Read the complete result file \`${artifact}\`; it holds the full, untruncated output.`,
143
164
  );
144
165
  }
166
+ if (failed && isModelLevelFailure(result)) lines.push("", modelLevelTakeoverNote(result));
167
+ if (!failed && result.agent === "artisan") {
168
+ lines.push("", "Review handoff: main. Worker completion is not review approval. Inspect the actual diff, affected callers, acceptance criteria, and check evidence. Send confirmed corrections to the owning worker with subagent_message; main owns acceptance and release.");
169
+ }
145
170
  return lines.join("\n");
146
171
  }
147
172
 
148
173
  /** A terminal model failure hands the unfinished task to main, not another run. */
149
- export function modelLevelTakeoverNote(result: SingleResult): string {
150
- const retry = result.modelFallbackFrom ? ", and the current main model also failed" : "";
174
+ function modelLevelTakeoverNote(result: SingleResult): string {
151
175
  const cause = getResultError(result) ?? "its model was unavailable or failed";
152
- return `The sub-agent could not complete this task: ${cause}${retry}. Earlier edits and any retained result/session artifacts remain available. Main must inspect that work and finish with its own tools; do not re-dispatch this phase.`;
176
+ return `The worker could not complete this task: ${cause}. No automatic model upgrade was attempted. Earlier edits and retained result/session artifacts remain available. Main must inspect that work and decide how to proceed; do not repeat this failed phase automatically.`;
153
177
  }
154
178
 
155
179
  /** Resolve a run-id request to actual ids: an exact numeric match always wins