@ferris1225/pi-subagents 7.0.0 → 7.0.2

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.
@@ -14,7 +14,7 @@ import type { CompletionMessageItem } from "./completion.ts";
14
14
  import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
15
15
  import { dispatchFailedResult, failedStartResult, formatCompletionBlock, queuedResult } from "../presentation/format.ts";
16
16
  import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
17
- import { findDuplicateDispatch } from "../delegation/prompt.ts";
17
+ import { duplicateDispatchRemedy, findDuplicateDispatch } from "../delegation/prompt.ts";
18
18
  import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
19
19
  import { type SubagentRuntime, type SubagentThread, type ThreadState } from "./runtime.ts";
20
20
  import {
@@ -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
  }
@@ -111,17 +111,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
111
111
  // owner and leaves the caller with no way forward. A retired owner is
112
112
  // still releasing its child or worktree after subagent_stop.
113
113
  const owner = duplicate.source;
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.";
123
114
  return failedStartResult(agentName, task,
124
- `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
115
+ `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${duplicateDispatchRemedy(owner)}`);
125
116
  }
126
117
  const projectRoot = getProjectRoot(runtime.configPath, originalCwd);
127
118
  const sessionsRoot = join(projectRoot, "sessions");
@@ -350,24 +341,11 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
350
341
  if (ownsSettlement()) thread.lifecycleOperation = undefined;
351
342
  }
352
343
  };
344
+ // No await separates the sessionActive check above from this enqueue, and
345
+ // only shutdown stops the queue after clearing sessionActive, so the
346
+ // queue always accepts this task.
353
347
  const queueController = runtime.backgroundQueue.enqueue(
354
348
  runGeneration,
355
- () => {
356
- if (runtime.threads.get(runId)?.generation !== generation) return;
357
- // A destructive stop owns publication and may still be finalizing an
358
- // isolated worktree. Do not expose a
359
- // terminal monitor state before that owner records its outcome.
360
- if (thread.lifecycleOperation === "stop") return;
361
- runtime.runControllers.delete(runId);
362
- thread.queueController = undefined;
363
- thread.state = "stopped";
364
- monitor.setStatus(runId, "failed");
365
- if (!runtime.sessionActive) {
366
- monitor.removeRun(runId);
367
- return;
368
- }
369
- finishRun(runId, "failed");
370
- },
371
349
  async (error) => {
372
350
  if (runtime.threads.get(runId)?.generation !== generation) return;
373
351
  // Queue-level crashes use the same settlement reservation as ordinary
@@ -516,7 +494,7 @@ export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifec
516
494
  // Every retained finalization gets a durable recovery record, so the
517
495
  // artifacts stay findable even when the owning process dies next.
518
496
  void persistRecoveryRecords(runtime.configPath, [
519
- recoveryRecordFromFinalization(runId, finalization, Date.now(), thread.durableId),
497
+ recoveryRecordFromFinalization(runId, finalization, thread.durableId!),
520
498
  ]).catch(() => undefined);
521
499
  }
522
500
  return finalization;
@@ -11,7 +11,6 @@ import {
11
11
  readThreadRecords,
12
12
  removeThreadRecord,
13
13
  restoredResultFromSummary,
14
- threadRecordIdentity,
15
14
  type ThreadRecord,
16
15
  } from "./durable.ts";
17
16
  import { monitor } from "../presentation/monitor.ts";
@@ -38,7 +37,7 @@ import { installThreadLifecycle } from "./thread-lifecycle.ts";
38
37
  async function discardRestoredRecord(runtime: SubagentRuntime, record: ThreadRecord): Promise<void> {
39
38
  await discardRecordArtifacts(record);
40
39
  if (record.sessionDir) runtime.sessionDirs.delete(record.sessionDir);
41
- await removeThreadRecord(runtime.configPath, threadRecordIdentity(record), record.cwd).catch(() => undefined);
40
+ await removeThreadRecord(runtime.configPath, record.durableId, record.cwd).catch(() => undefined);
42
41
  }
43
42
 
44
43
  function createRestoredThread(
@@ -48,7 +47,7 @@ function createRestoredThread(
48
47
  state: ThreadState,
49
48
  ): SubagentThread {
50
49
  const thread: SubagentThread = {
51
- durableId: threadRecordIdentity(record),
50
+ durableId: record.durableId,
52
51
  id: record.runId,
53
52
  generation: record.generation,
54
53
  agentName: record.agentName,
@@ -66,6 +65,7 @@ function createRestoredThread(
66
65
  sessionId: record.sessionId,
67
66
  sessionDir: record.sessionDir,
68
67
  lastResult: restoredResultFromSummary(record),
68
+ restoredUpdatedAt: record.updatedAt,
69
69
  finalizeIsolation: async () => undefined,
70
70
  };
71
71
  installThreadLifecycle(thread, { runtime });
@@ -80,15 +80,14 @@ function belongsToSessionProject(configPath: string, cwd: string, record: Thread
80
80
  * Other projects' parked threads stay on disk for their own window; this process
81
81
  * must not restore them or kill their children. Records with a live owner or
82
82
  * child are left alone; missing session files do not discard isolated
83
- * edits. Already-settled records from older versions are removed with their
84
- * managed artifacts. */
83
+ * edits. Settled records are removed with their managed artifacts. */
85
84
  export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: string): Promise<number[]> {
86
85
  const records = await readThreadRecords(runtime.configPath);
87
86
  const restoredIds: number[] = [];
88
87
  const localRecords = records.filter((record) => belongsToSessionProject(runtime.configPath, cwd, record));
89
88
  for (const record of localRecords) monitor.ensureNextIdAbove(record.runId);
90
89
  for (let record of localRecords) {
91
- const identity = threadRecordIdentity(record);
90
+ const identity = record.durableId;
92
91
  if ([...runtime.threads.values()].some((thread) => thread.durableId === identity)) continue;
93
92
  // Another Pi window may own this checkpoint, and PID reuse means a live
94
93
  // recorded child is not proof of ownership. Never kill either on restore.
@@ -5,8 +5,8 @@ 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
7
  import type { AgentConfig } from "../delegation/agents.ts";
8
- import type { SubagentsConfig, ThinkingLevel } from "../configuration/config.ts";
9
- import { removeThreadRecord, threadRecordFromThread, threadRecordIdentity, upsertThreadRecord } from "./durable.ts";
8
+ import { BUILTIN_AGENT_NAMES, type AgentName, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
9
+ import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord } from "./durable.ts";
10
10
  import {
11
11
  availableModelsInScope,
12
12
  currentModelRef,
@@ -32,7 +32,7 @@ export function quiesced(promise: Promise<unknown>, timeoutMs: number = CONTROL_
32
32
  promise.then(() => true, () => true),
33
33
  new Promise<boolean>((resolve) => {
34
34
  const timer = setTimeout(() => resolve(false), timeoutMs);
35
- if (typeof timer.unref === "function") timer.unref();
35
+ timer.unref();
36
36
  }),
37
37
  ]);
38
38
  }
@@ -98,7 +98,7 @@ export function persistThreadCheckpoint(
98
98
  const record = threadRecordFromThread(thread, state);
99
99
  const write = state === "parked"
100
100
  ? upsertThreadRecord(runtime.configPath, record)
101
- : removeThreadRecord(runtime.configPath, threadRecordIdentity(record), thread.cwd);
101
+ : removeThreadRecord(runtime.configPath, record.durableId, thread.cwd);
102
102
  void write.catch(() => undefined);
103
103
  }
104
104
 
@@ -152,10 +152,12 @@ export function resolveDispatchModelRoute(
152
152
  config: SubagentsConfig,
153
153
  ctx: ExtensionContext,
154
154
  ): DispatchModelRoute {
155
+ if (!(BUILTIN_AGENT_NAMES as readonly string[]).includes(agent.name)) throw new Error(`Unknown subagent role: ${agent.name}`);
156
+ const settings = config[agent.name as AgentName];
155
157
  const availableModels = availableModelsInScope(ctx);
156
158
  const mainRef = currentModelRef(ctx);
157
159
  const route = resolveAgentModelRoute({
158
- selectedRef: config.model,
160
+ selectedRef: settings.model,
159
161
  mainRef,
160
162
  availableRefs: availableModels.map(modelRef),
161
163
  });
@@ -163,8 +165,8 @@ export function resolveDispatchModelRoute(
163
165
  ? ctx.model : findModelByRef(availableModels, route.primaryRef);
164
166
  return {
165
167
  agent: { ...agent, model: route.primaryRef },
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.` } : {}),
168
+ thinkingLevel: resolveThinkingLevel(model, settings.thinking),
169
+ ...(route.unavailableSelectedRef ? { error: `${agent.name} model ${route.unavailableSelectedRef} is unavailable in this session. Dispatch paused; restore availability or choose another model with /subagents-setup. No main-model worker was started.` } : {}),
168
170
  };
169
171
  }
170
172
 
@@ -14,7 +14,7 @@ import type { DispatchCore } from "./dispatch-core.ts";
14
14
  import { awaitRunResults, WaitSchema } from "./await-results.ts";
15
15
  import { cancelActiveWork } from "./cancellation.ts";
16
16
  import { stopThreads } from "./stop.ts";
17
- import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
17
+ import { formatCompletionBlock } from "../presentation/format.ts";
18
18
  import { emptyUsage } from "../execution/run-control.ts";
19
19
  import { formatDuration, formatTaskSummary, monitor } from "../presentation/monitor.ts";
20
20
  import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
@@ -189,7 +189,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
189
189
  pi.registerTool({
190
190
  name: "subagent_message",
191
191
  label: "Subagent Message",
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.",
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 or handled by an input hook; 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.",
193
193
  exposure: "model-only",
194
194
  executionMode: "parallel",
195
195
  parameters: Type.Object({
@@ -210,9 +210,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
210
210
  thread.lastSteering = { ...receipt, message: formatTaskSummary(params.message, 160, false) };
211
211
  const status = receipt.disposition === "queued"
212
212
  ? `Received by #${thread.id} · queued for the next steering boundary. Model execution is not yet confirmed.`
213
- : receipt.disposition === "handled"
214
- ? `Received by #${thread.id} · handled by an input hook. Delivery to the model is not confirmed.`
215
- : `Accepted by #${thread.id} · queue state unconfirmed. Model execution is not yet confirmed.`;
213
+ : `Received by #${thread.id} · handled by an input hook. Delivery to the model is not confirmed.`;
216
214
  monitor.setActivity(thread.id, `steering ${receipt.disposition}`);
217
215
  return {
218
216
  content: [{ type: "text" as const, text: `${status}${receipt.requestId ? `\nChild RPC acknowledgement: ${receipt.requestId}` : ""}` }],
@@ -224,7 +222,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
224
222
  const state = thread.state === "parked" ? "interrupted" : thread.state;
225
223
  const terminal = !thread.lifecycleOperation && ["parked", "failed", "stopped"].includes(thread.state);
226
224
  return fail(`Run #${thread.id} is ${state}; ${terminal
227
- ? "inspect retained results with subagent_status and handle unfinished work in main. This run cannot be continued with subagent_message."
225
+ ? "this run cannot be continued with subagent_message. Inspect retained results with subagent_status, then dispatch a corrected brief with subagent or finish the unfinished work in main."
228
226
  : "messages require a running or successfully completed run. Results arrive automatically."}`);
229
227
  }
230
228
  if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
@@ -298,13 +296,20 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
298
296
  },
299
297
  });
300
298
 
299
+ function parseExactRunId(raw: string | undefined): number | undefined {
300
+ const cleaned = raw?.trim().replace(/^#/u, "").trim() ?? "";
301
+ if (!/^[1-9]\d*$/u.test(cleaned)) return undefined;
302
+ const parsed = Number(cleaned);
303
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
304
+ }
305
+
301
306
  // Cancel one or more active runs: aborts the queue controller, which
302
307
  // terminates the child and delivers an aborted result (with whatever partial
303
308
  // output it produced) so the main agent always knows the run stopped.
304
309
  const SubagentStopParams = Type.Object({
305
310
  id: Type.Optional(
306
311
  Type.String({
307
- description: "Run id or prefix to stop (see subagent dispatch output).",
312
+ description: "Run id to stop.",
308
313
  }),
309
314
  ),
310
315
  all: Type.Optional(Type.Boolean({ description: "Stop every active run (default false)." })),
@@ -313,7 +318,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
313
318
  pi.registerTool({
314
319
  name: "subagent_stop",
315
320
  label: "Subagent Stop",
316
- description: "Destructively stop and retire one run by id/prefix, or this session’s active runs with all: true. all takes precedence over id. Other Pi sessions and projects are not targeted. Delivers partial results; stopped runs cannot resume.",
321
+ description: "Destructively stop and retire one run by id, or this session’s active runs with all: true. all takes precedence over id. Other Pi sessions and projects are not targeted. Delivers partial results; stopped runs cannot resume.",
317
322
  exposure: "model-only",
318
323
  executionMode: "sequential",
319
324
  annotations: {
@@ -334,9 +339,10 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
334
339
  .map((thread) => thread.id),
335
340
  ])]
336
341
  : [...runtime.threads.keys()];
342
+ const requestedId = params.all === true ? undefined : parseExactRunId(params.id);
337
343
  const targets = params.all === true
338
344
  ? candidateIds
339
- : params.id?.trim() ? matchRunIds(candidateIds, params.id.trim()) : [];
345
+ : requestedId !== undefined && candidateIds.includes(requestedId) ? [requestedId] : [];
340
346
 
341
347
  if (targets.length === 0) {
342
348
  const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
@@ -1,32 +1,42 @@
1
1
  /** Session-start recovery, worker availability, and progress-surface installation. */
2
2
 
3
3
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
- import { loadConfig, saveConfig } from "../configuration/config.ts";
5
- import { findModelByRef, modelRef } from "../configuration/models.ts";
4
+ import { BUILTIN_AGENT_NAMES, errorMessage, loadConfig } from "../configuration/config.ts";
5
+ import { availableModelsInScope, findModelByRef } from "../configuration/models.ts";
6
6
  import { ensureDefaultConfig } from "../configuration/setup.ts";
7
- import { announceRecoveryRecords, relocateRecoveryManifest } from "../isolation/recovery.ts";
7
+ import { announceRecoveryRecords } from "../isolation/recovery.ts";
8
8
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
9
9
  import { installActiveRunsWidget } from "./widget.ts";
10
10
 
11
11
  /** Preserve the worker choice during outages instead of spending main-model quota. */
12
12
  async function checkWorkerModel(
13
- ctx: Pick<ExtensionContext, "ui" | "modelRegistry">,
13
+ ctx: Pick<ExtensionContext, "ui" | "modelRegistry"> & Partial<Pick<ExtensionContext, "model" | "scopedModels">>,
14
14
  runtime: SubagentRuntime,
15
15
  ): Promise<void> {
16
+ let config;
16
17
  try {
17
- const config = await loadConfig(runtime.configPath);
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
- }
18
+ config = await loadConfig(runtime.configPath);
19
+ } catch (error) {
26
20
  ctx.ui.notify(
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.`,
21
+ `pi-subagents: ${errorMessage(error)} Dispatch is paused until the settings file is repaired.`,
28
22
  "warning",
29
23
  );
24
+ return;
25
+ }
26
+ try {
27
+ const models = availableModelsInScope({
28
+ model: ctx.model,
29
+ modelRegistry: ctx.modelRegistry,
30
+ scopedModels: ctx.scopedModels ?? [],
31
+ });
32
+ for (const role of BUILTIN_AGENT_NAMES) {
33
+ const ref = config[role].model;
34
+ if (!ref || findModelByRef(models, ref)) continue;
35
+ ctx.ui.notify(
36
+ `pi-subagents: ${role} model ${ref} is unavailable. Its setting is preserved and dispatch is paused for this role. Restore availability or run /subagents-setup to choose another.`,
37
+ "warning",
38
+ );
39
+ }
30
40
  } catch {
31
41
  /* availability notices are non-fatal */
32
42
  }
@@ -36,7 +46,6 @@ export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime
36
46
  pi.on("session_start", async (_event, ctx) => {
37
47
  await ensureDefaultConfig(ctx, runtime.configPath);
38
48
  try {
39
- await relocateRecoveryManifest(runtime.configPath);
40
49
  await announceRecoveryRecords(runtime.configPath, ctx);
41
50
  } catch (error) {
42
51
  // Recovery readers must fail closed for cleanup, but a failed notice
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * Pure formatting/result helpers shared by the subagent tool and completion
3
- * delivery: usage rendering, completion blocks, synthetic result constructors,
4
- * and run-id matching.
3
+ * delivery: usage rendering, completion blocks, and synthetic result constructors.
5
4
  */
6
5
 
7
6
  import { readFileSync } from "node:fs";
@@ -101,6 +100,17 @@ function inlineOverflow(output: string, maxLines: number): string | undefined {
101
100
  return overflow.length > 0 ? overflow.join(" · ") : undefined;
102
101
  }
103
102
 
103
+ /** Bounded head of an oversized output for inline fallback when no artifact file
104
+ * is available: at most `maxLines` lines and `maxLines * RESULT_LINE_CHARS` chars. */
105
+ function truncateHead(output: string, maxLines: number): string {
106
+ const lineLimit = Math.max(0, maxLines);
107
+ if (lineLimit === 0) return "";
108
+ const charLimit = lineLimit * RESULT_LINE_CHARS;
109
+ let head = output.split("\n").slice(0, lineLimit).join("\n");
110
+ if (head.length > charLimit) head = head.slice(0, charLimit);
111
+ return head;
112
+ }
113
+
104
114
  export function formatCompletionBlock(
105
115
  result: SingleResult,
106
116
  maxResultLines: number,
@@ -151,20 +161,45 @@ export function formatCompletionBlock(
151
161
  );
152
162
  }
153
163
  if (overflow) {
154
- // No inline copy at all: a truncated dump reads as complete while
155
- // hiding the rest, and the parent re-reads the full text from the file
156
- // anyway, paying for the same content twice. The notice only routes it.
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)");
160
- if (options.resultRoot) result.resultFile = artifact;
161
- lines.push(
162
- "",
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.`,
164
- );
164
+ // No inline copy when the full output is saved to a file: a truncated
165
+ // dump reads as complete while hiding the rest, and the parent re-reads
166
+ // the full text from the file anyway. Fall back to a bounded head only
167
+ // when the artifact cannot be written or no result root is available.
168
+ let artifact = reusableArtifact(result, output);
169
+ let saveFailure: string | undefined;
170
+ if (!artifact) {
171
+ if (!options.resultRoot) {
172
+ saveFailure = "result root unavailable";
173
+ } else {
174
+ try {
175
+ artifact = writeResultArtifact(output, result.agent, options.resultRoot);
176
+ result.resultFile = artifact;
177
+ } catch (error) {
178
+ saveFailure = error instanceof Error ? error.message : String(error);
179
+ }
180
+ }
181
+ }
182
+ if (artifact) {
183
+ if (options.resultRoot) result.resultFile = artifact;
184
+ lines.push(
185
+ "",
186
+ `⚠ 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.`,
187
+ );
188
+ } else {
189
+ delete result.resultFile;
190
+ const head = truncateHead(output, maxResultLines);
191
+ if (head) {
192
+ if (lines[lines.length - 1] !== "") lines.push("");
193
+ lines.push(head);
194
+ }
195
+ lines.push(
196
+ "",
197
+ `⚠ The child's answer (${overflow}) was truncated above because the full result could not be saved (${saveFailure ?? "unknown error"}).`,
198
+ );
199
+ }
165
200
  }
166
201
  if (failed && isModelLevelFailure(result)) lines.push("", modelLevelTakeoverNote(result));
167
- if (!failed && result.agent === "artisan") {
202
+ if (!failed && result.agent === "worker") {
168
203
  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
204
  }
170
205
  return lines.join("\n");
@@ -173,15 +208,6 @@ export function formatCompletionBlock(
173
208
  /** A terminal model failure hands the unfinished task to main, not another run. */
174
209
  function modelLevelTakeoverNote(result: SingleResult): string {
175
210
  const cause = getResultError(result) ?? "its model was unavailable or failed";
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.`;
177
- }
178
-
179
- /** Resolve a run-id request to actual ids: an exact numeric match always wins
180
- * (so "1" never fans out to 10, 11, …); only when no exact match exists does a
181
- * prefix match run, as a convenience for partial ids. Keeps single-digit lookups
182
- * from returning — or, for subagent_stop, acting on — a whole prefix family. */
183
- export function matchRunIds(ids: number[], requested: string): number[] {
184
- const exact = ids.filter((id) => String(id) === requested);
185
- if (exact.length > 0) return exact;
186
- return ids.filter((id) => String(id).startsWith(requested));
211
+ const role = result.agent || "subagent";
212
+ return `The ${role} 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.`;
187
213
  }
@@ -161,7 +161,7 @@ function tailGraphemes(segments: string[], maxWidth: number): string {
161
161
  * One-line task preview, capped by `maxWidth` display columns (default 80).
162
162
  * `keysOnly` (default): extracted key fragments (paths, quoted phrases,
163
163
  * symbols) are shown bare — the agent name is already displayed next to the
164
- * task line, so templated prose ("scout: trace how ...") adds nothing.
164
+ * task line, so templated prose ("researcher: trace how ...") adds nothing.
165
165
  * `keysOnly: false` keeps the prose as `head…tail` (used for completion
166
166
  * messages, where the Task line is the reader's only context).
167
167
  * Grapheme-safe — CJK, ZWJ emoji and combining sequences are never split.
@@ -303,13 +303,8 @@ export function formatDuration(ms: number): string {
303
303
  }
304
304
 
305
305
  function elapsedMilliseconds(run: RunView, now: number = Date.now()): number {
306
- let elapsed = run.elapsedMs ?? 0;
306
+ let elapsed = run.elapsedMs;
307
307
  if (run.activeSince !== undefined) elapsed += Math.max(0, now - run.activeSince);
308
- // Keep formatting tolerant of older/synthetic RunView values that predate
309
- // segmented timing and carry only startedAt/endedAt.
310
- if (elapsed === 0 && run.startedAt !== undefined && run.activeSince === undefined) {
311
- elapsed = Math.max(0, (run.endedAt ?? now) - run.startedAt);
312
- }
313
308
  return elapsed;
314
309
  }
315
310