@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
@@ -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,19 +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
- import {
25
- formatRetainedWorkflow,
26
- formatWorkflowStatus,
27
- readRetainedWorkflows,
28
- stopWorkflow,
29
- workflowStatus,
30
- } from "../workflow/engine.ts";
31
23
 
32
- function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
24
+ function renderFirstLine(result: { content?: unknown }, label: string, theme: Theme): Text {
33
25
  const parts = (result.content ?? []) as Array<{ type: string; text?: string }>;
34
26
  const text = parts
35
27
  .map((part) => (typeof part.text === "string" ? part.text : ""))
@@ -89,7 +81,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
89
81
  pi.registerTool({
90
82
  name: "subagent_status",
91
83
  label: "Subagent Status",
92
- description: "Inspect run or workflow ownership, progress, and failures. An exact run id also returns its retained result so completed work can be reused. Omit id to list runs. Results arrive automatically; do not poll.",
84
+ description: "Inspect run ownership, progress, and failures. An exact run id also returns its retained result so completed work can be reused. Omit id to list runs. Results arrive automatically; do not poll.",
93
85
  exposure: "model-only",
94
86
  executionMode: "parallel",
95
87
  annotations: {
@@ -100,9 +92,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
100
92
  },
101
93
  parameters: Type.Object({
102
94
  id: Type.Optional(Type.Integer({ minimum: 1, description: "Exact run id; omit to list all runs in this parent session." })),
103
- workflow: Type.Optional(Type.Integer({ minimum: 1, description: "Workflow graph id; omit to list every graph in this parent session." })),
104
95
  }),
105
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
96
+ async execute(_toolCallId, params) {
106
97
  await runtime.durableRestore;
107
98
  const threads = [...runtime.threads.values()]
108
99
  .filter((thread) => params.id === undefined || thread.id === params.id)
@@ -117,13 +108,10 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
117
108
  return {
118
109
  id: thread.id,
119
110
  agent: thread.agentName,
120
- phaseId: thread.phaseId,
121
111
  cwd: thread.cwd,
122
112
  executionCwd: thread.executionCwd,
123
- scope: thread.scope,
124
113
  taskSummary: formatTaskSummary(thread.task, 80, false),
125
114
  state,
126
- waitReason: state === "queued" ? live?.waitReason : undefined,
127
115
  activity: live?.activity,
128
116
  recentActivity: live?.recentActivity ?? [],
129
117
  lastSteering: thread.lastSteering,
@@ -150,10 +138,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
150
138
  const text = runs.length === 0
151
139
  ? params.id === undefined ? "No subagent runs in this parent session." : `No subagent run matches #${params.id}.`
152
140
  : runs.map((run) => {
153
- const wait = run.waitReason ? ` — ${runWaitLabel({ status: "queued", waitReason: run.waitReason })}` : "";
141
+ const wait = run.state === "queued" ? " — starting" : "";
154
142
  const lines = [`#${run.id} ${run.agent} · ${run.state} · ${formatDuration(run.elapsedMs)}${wait}`, ` task: ${run.taskSummary}`];
155
- if (run.phaseId) lines.push(` phase: ${run.phaseId}`);
156
- if (run.scope) lines.push(` scope: ${JSON.stringify(run.scope)}`);
157
143
  if (run.isolationNote) lines.push(` isolation: ${run.isolationNote}`);
158
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}`);
159
145
  if (run.followUpContext) lines.push(` follow-up: ${run.followUpContext}${run.followUpContext === "summary" ? " (retained session unavailable)" : " available"}`);
@@ -174,20 +160,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
174
160
  if (paths.length > 0) lines.push(` ${paths.join("\n ")}`);
175
161
  return lines.join("\n");
176
162
  }).join("\n");
177
- // Workflow graphs are reported beside individual runs: which nodes have
178
- // started, which one is waiting on a dependency, and what a graph that
179
- // outlived its session left behind.
180
- const workflowId = params.id === undefined ? params.workflow : undefined;
181
- const workflowRuns = [...runtime.workflows.values()]
182
- .filter((run) => workflowId === undefined || run.id === workflowId)
183
- .sort((left, right) => left.id - right.id);
184
- const retainedWorkflows = (await readRetainedWorkflows(runtime, ctx?.cwd ?? process.cwd()).catch(() => []))
185
- .filter((record) => workflowId === undefined || record.id === workflowId)
186
- .filter((record) => !workflowRuns.some((run) => run.id === record.id));
187
- const workflowSections = params.id === undefined ? [
188
- ...workflowRuns.map((run) => formatWorkflowStatus(run).join("\n")),
189
- ...retainedWorkflows.map((record) => formatRetainedWorkflow(record).join("\n")),
190
- ] : [];
191
163
  const selected = params.id === undefined ? undefined : runtime.threads.get(params.id);
192
164
  const retainedResult = selected ? runtime.settledRuns.get(selected.id) ?? selected.lastResult : undefined;
193
165
  const evidence = retainedResult && retainedResult.exitCode !== -1
@@ -195,21 +167,14 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
195
167
  ? `Read the retained result: ${retainedResult.resultFile}`
196
168
  : formatCompletionBlock(retainedResult, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, selected!.cwd) })
197
169
  : "";
198
- const sections = [text, ...workflowSections, evidence].filter((section) => section.trim().length > 0);
199
- const unknownWorkflow = workflowId !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
170
+ const sections = [text, evidence].filter((section) => section.trim().length > 0);
200
171
  return {
201
172
  content: [{
202
173
  type: "text",
203
- text: unknownWorkflow
204
- ? `No workflow graph matches #${params.workflow} in this parent session.`
205
- : sections.join("\n\n"),
174
+ text: sections.join("\n\n"),
206
175
  }],
207
- details: {
208
- runs,
209
- workflows: workflowRuns.map(workflowStatus),
210
- retainedWorkflows,
211
- },
212
- ...((params.id !== undefined && runs.length === 0) || unknownWorkflow ? { isError: true } : {}),
176
+ details: { runs },
177
+ ...(params.id !== undefined && runs.length === 0 ? { isError: true } : {}),
213
178
  };
214
179
  },
215
180
  renderCall(args, theme) {
@@ -224,13 +189,13 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
224
189
  pi.registerTool({
225
190
  name: "subagent_message",
226
191
  label: "Subagent Message",
227
- 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.",
228
193
  exposure: "model-only",
229
194
  executionMode: "parallel",
230
195
  parameters: Type.Object({
231
196
  id: Type.Integer({ minimum: 1, description: "Exact run id in this parent session." }),
232
197
  message: Type.String({ minLength: 1, pattern: "\\S", description: "Additional instruction or follow-up question." }),
233
- 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." })),
234
199
  wait: WaitSchema,
235
200
  }),
236
201
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
@@ -292,11 +257,10 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
292
257
  if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while the follow-up was prepared.");
293
258
  const selectedContext = copyDir ? "session" : "summary";
294
259
  const task = copyDir
295
- ? `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`
260
+ ? `Follow-up to run #${thread.id}:\n${params.message}`
296
261
  : buildSummaryFollowUp(thread, params.message);
297
262
  const wait = params.wait ?? (ctx.hasUI === false);
298
263
  const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
299
- phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
300
264
  deliveryRoute: wait ? "await" : "background",
301
265
  ...(copyDir ? { resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir } } : {}),
302
266
  });
@@ -343,17 +307,13 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
343
307
  description: "Run id or prefix to stop (see subagent dispatch output).",
344
308
  }),
345
309
  ),
346
- all: Type.Optional(Type.Boolean({ description: "Stop every active run and every running workflow (default false)." })),
347
- workflow: Type.Optional(Type.Integer({
348
- minimum: 1,
349
- description: "Stop this workflow graph: no dependent node starts and running nodes are cancelled.",
350
- })),
310
+ all: Type.Optional(Type.Boolean({ description: "Stop every active run (default false)." })),
351
311
  });
352
312
 
353
313
  pi.registerTool({
354
314
  name: "subagent_stop",
355
315
  label: "Subagent Stop",
356
- description: "Destructively stop and retire one run by id/prefix, one workflow by workflow id, or this session’s active runs and workflows with all: true. all takes precedence over id and workflow; id takes precedence over workflow. Other Pi sessions and projects are not targeted. Delivers partial results; stopped runs cannot resume.",
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.",
357
317
  exposure: "model-only",
358
318
  executionMode: "sequential",
359
319
  annotations: {
@@ -366,43 +326,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
366
326
 
367
327
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
368
328
  await runtime.durableRestore;
369
- // A graph stop owns its own lifecycle: dependents must not start, and the
370
- // graph's own summary reports what had already completed. Stopping the
371
- // nodes one by one first would let the runner dispatch the next layer.
372
- if (params.all !== true && !params.id?.trim() && params.workflow !== undefined) {
373
- const graph = runtime.workflows.get(params.workflow);
374
- if (!graph) {
375
- const known = [...runtime.workflows.keys()].map((id) => `#${id}`).join(", ");
376
- return {
377
- content: [{
378
- type: "text",
379
- text: `No workflow graph matches #${params.workflow}.${known ? ` Known graphs: ${known}.` : ""}`,
380
- }],
381
- details: {},
382
- };
383
- }
384
- const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
385
- return {
386
- content: [{
387
- type: "text",
388
- text: `Stopped workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? `; cancelled ${cancelled.map((id) => `#${id}`).join(", ")}` : "; no node had started"}. Its summary reports the completed work, and each node keeps its own run evidence.`,
389
- }],
390
- details: {},
391
- };
392
- }
393
- const graphStops: string[] = [];
394
- const graphStopPromises: Array<Promise<void>> = [];
395
- const graphRunIds = new Set<number>();
396
- if (params.all === true) {
397
- const graphs = [...runtime.workflows.values()].filter((graph) => graph.state === "running");
398
- for (const graph of graphs) for (const node of graph.nodes) { if (node.runId !== undefined) graphRunIds.add(node.runId); }
399
- graphStopPromises.push(...graphs.map(async (graph) => {
400
- const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
401
- graphStops.push(
402
- `workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? ` (${cancelled.length} node${cancelled.length === 1 ? "" : "s"} cancelled)` : ""}`,
403
- );
404
- }));
405
- }
406
329
  const candidateIds = params.all === true
407
330
  ? [...new Set([
408
331
  ...runtime.runControllers.keys(),
@@ -414,17 +337,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
414
337
  const targets = params.all === true
415
338
  ? candidateIds
416
339
  : params.id?.trim() ? matchRunIds(candidateIds, params.id.trim()) : [];
417
- const threadTargets = targets.filter((id) => !graphRunIds.has(id));
418
340
 
419
- if (threadTargets.length === 0) {
420
- await Promise.all(graphStopPromises);
341
+ if (targets.length === 0) {
421
342
  const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
422
- if (graphStops.length > 0) {
423
- return {
424
- content: [{ type: "text", text: `Stopped ${graphStops.length} workflow${graphStops.length === 1 ? "" : "s"}: ${graphStops.join(", ")}.` }],
425
- details: {},
426
- };
427
- }
428
343
  return {
429
344
  content: [{ type: "text", text: params.all === true
430
345
  ? "No active subagent runs to stop."
@@ -433,22 +348,17 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
433
348
  };
434
349
  }
435
350
 
436
- const stopping = stopThreads(runtime, threadTargets);
437
- await Promise.all(graphStopPromises);
438
- const { stopped, retainedIntegration, pendingIntegration, completionResults } = await stopping;
439
- if (completionResults.length > 0) {
440
- runtime.sendCompletionGroup(completionResults.filter((result) => !runtime.threads.get(result.runId!)?.workflow).map((result) => ({
441
- agent: result.agent,
442
- block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
443
- triggerTurn: true,
444
- usage: result.usage,
445
- })));
446
- runtime.completionBatcher.flush();
447
- }
351
+ const { stopped, retainedIntegration, pendingIntegration, completionResults } = await stopThreads(runtime, targets);
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
+ })));
448
358
  return {
449
359
  content: [{
450
360
  type: "text",
451
- text: `${graphStops.length > 0 ? `Stopped ${graphStops.length} workflow${graphStops.length === 1 ? "" : "s"}: ${graphStops.join(", ")}. ` : ""}Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
361
+ text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
452
362
  }],
453
363
  details: {},
454
364
  };
@@ -1,30 +1,32 @@
1
1
  /** Session-start recovery, stale-model cleanup, 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 { filterUnavailableModelOverrides } 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. */
11
+ /** Drop overrides that no authenticated model serves back to dynamic
12
+ * main-model routing. A session model scope only narrows this session's
13
+ * routing, so it never deletes a persisted override. */
12
14
  async function removeUnavailableAgentModels(
13
- ctx: { ui: { notify: (message: string, kind: "info" | "warning" | "error") => void } } & Parameters<typeof availableModelsInScope>[0],
15
+ ctx: Pick<ExtensionContext, "ui" | "modelRegistry">,
14
16
  runtime: SubagentRuntime,
15
17
  ): Promise<void> {
16
18
  try {
17
19
  const config = await loadConfig(runtime.configPath);
18
20
  const overrides = Object.entries(config.agentModels);
19
21
  if (overrides.length === 0) return;
20
- const { kept, dropped } = filterUnavailableModelOverrides(config.agentModels, availableModelsInScope(ctx));
22
+ const { kept, dropped } = filterUnavailableModelOverrides(config.agentModels, ctx.modelRegistry.getAvailable());
21
23
  const rewritten = JSON.stringify(kept) !== JSON.stringify(config.agentModels);
22
24
  if (!rewritten && dropped.length === 0) return;
23
25
  await saveConfig({ ...config, agentModels: kept }, runtime.configPath);
24
26
  if (dropped.length === 0) return;
25
27
  const list = dropped.map(({ agent, ref }) => `${agent}: ${ref}`).join(", ");
26
28
  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.`,
29
+ `pi-subagents: removed model overrides that are no longer available (${list}). Those roles now follow the main model; run /subagents-setup to choose another.`,
28
30
  "warning",
29
31
  );
30
32
  } catch {
@@ -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,7 +111,7 @@ 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);
114
+ const overflow = inlineOverflow(output, maxResultLines);
87
115
  const fallbackNote = result.modelFallbackFrom
88
116
  ? ` (selected model ${result.modelFallbackFrom} failed → main ${result.model ?? "dynamic default"})`
89
117
  : "";
@@ -114,7 +142,7 @@ export function formatCompletionBlock(
114
142
  lines.push("");
115
143
  }
116
144
  if (result.isolationNote) lines.push(`Isolation: ${result.isolationNote}`, "");
117
- if (!truncated) lines.push(text);
145
+ if (!overflow) lines.push(output);
118
146
  // Failed-tool diagnostics ride along only when the run itself failed: they
119
147
  // explain the failure, while on a successful run a transient failed call
120
148
  // (no-match grep, rejected edit) is noise the agent already worked around.
@@ -125,28 +153,25 @@ export function formatCompletionBlock(
125
153
  ...failedTools.map((tool) => `- ${tool.toolName}: ${tool.error.trim() || "(no output)"}`),
126
154
  );
127
155
  }
128
- if (truncated) {
156
+ if (overflow) {
129
157
  // No inline copy at all: a truncated dump reads as complete while
130
158
  // hiding the rest, and the parent re-reads the full text from the file
131
159
  // 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)";
160
+ // Every delivery of the same result names one artifact.
161
+ const artifact = reusableArtifact(result, output)
162
+ ?? (options.resultRoot ? writeResultArtifact(output, result.agent, options.resultRoot) : "(result root unavailable)");
135
163
  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
164
  lines.push(
141
165
  "",
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.`,
166
+ `⚠ 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
167
  );
144
168
  }
169
+ if (failed && isModelLevelFailure(result)) lines.push("", modelLevelTakeoverNote(result));
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 {
174
+ function modelLevelTakeoverNote(result: SingleResult): string {
150
175
  const retry = result.modelFallbackFrom ? ", and the current main model also failed" : "";
151
176
  const cause = getResultError(result) ?? "its model was unavailable or failed";
152
177
  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.`;