@xzzpig/pi-subagents 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -1,12 +1,13 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import { snapshotBackgroundWork } from "../../api/background-work.ts";
3
- import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
3
+ import type { Details, SubagentState } from "../../shared/types.ts";
4
4
  import { listAsyncRuns } from "./async-status.ts";
5
- import { waitForSubagents, type SubagentWaitDeps, type SubagentWaitParams, type WaitEventBus } from "./subagent-wait.ts";
5
+ import type { ReadonlyDrainObservation } from "../shared/readonly-drain-observation.ts";
6
+ import { waitForSubagents, waitRunScopes, type SubagentWaitDeps, type SubagentWaitParams, type WaitEventBus } from "./subagent-wait.ts";
6
7
 
7
8
  export const DEFAULT_AUTO_DRAIN_TIMEOUT_MS = 30 * 60 * 1000;
8
9
 
9
- export interface AutoDrainDeps {
10
+ export interface AutoDrainDeps extends Pick<SubagentWaitDeps, "asyncDirRoot" | "resultsDir" | "nestedRootRunId"> {
10
11
  state: SubagentState;
11
12
  events?: WaitEventBus;
12
13
  timeoutMs?: number;
@@ -17,52 +18,75 @@ export interface AutoDrainDeps {
17
18
  deps: SubagentWaitDeps,
18
19
  ) => Promise<AgentToolResult<Details>>;
19
20
  hasWork?: (sessionId: string, nowMs: number) => boolean;
21
+ hasPendingSupervisorRequest?: () => boolean;
20
22
  }
21
23
 
22
24
  function resultText(value: AgentToolResult<Details>): string {
23
25
  return value.content.map((part) => part.type === "text" ? part.text : "").join(" ").trim();
24
26
  }
25
27
 
26
- function hasOutstandingWork(sessionId: string, nowMs: number): boolean {
27
- const asyncRuns = listAsyncRuns(DIRS.async, {
28
+ function hasOutstandingWork(deps: AutoDrainDeps, sessionId: string, nowMs: number, observation?: ReadonlyDrainObservation): boolean {
29
+ const asyncRuns = waitRunScopes(deps).flatMap(({ asyncDirRoot, resultsDir }) => listAsyncRuns(asyncDirRoot, {
28
30
  states: ["queued", "running"],
29
31
  sessionId,
30
- resultsDir: DIRS.results,
32
+ resultsDir,
31
33
  now: () => nowMs,
32
- });
33
- return asyncRuns.length > 0 || snapshotBackgroundWork(sessionId, nowMs).items.length > 0;
34
+ includeNested: false,
35
+ }, observation?.status));
36
+ const detachedForeground = [...(deps.state.foregroundRuns?.values() ?? [])].some((run) =>
37
+ run.sessionId === sessionId && run.children.some((child) => child.status === "detached")
38
+ );
39
+ return asyncRuns.length > 0 || snapshotBackgroundWork(sessionId, nowMs).items.length > 0 || detachedForeground;
34
40
  }
35
41
 
36
42
  /** Drain all work owned by the current headless session, including work added while draining. */
37
- export async function drainOutstandingWork(deps: AutoDrainDeps): Promise<void> {
43
+ export async function drainOutstandingWork(deps: AutoDrainDeps, observation?: ReadonlyDrainObservation): Promise<void> {
38
44
  const sessionId = deps.state.currentSessionId;
39
- if (!sessionId) throw new Error("Cannot auto-drain background work without an active session identity.");
40
- const now = deps.now ?? Date.now;
41
- const timeoutMs = deps.timeoutMs ?? DEFAULT_AUTO_DRAIN_TIMEOUT_MS;
42
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Auto-drain timeoutMs must be a positive finite number.");
43
- const deadlineAt = now() + timeoutMs;
44
- const hasWork = deps.hasWork ?? hasOutstandingWork;
45
- const wait = deps.wait ?? waitForSubagents;
45
+ observation?.begin(sessionId, !deps.hasWork && !deps.wait && !deps.now && !deps.hasPendingSupervisorRequest);
46
+ try {
47
+ if (!sessionId) throw new Error("Cannot auto-drain background work without an active session identity.");
48
+ const now = deps.now ?? Date.now;
49
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_AUTO_DRAIN_TIMEOUT_MS;
50
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Auto-drain timeoutMs must be a positive finite number.");
51
+ const deadlineAt = now() + timeoutMs;
52
+ const hasWork = deps.hasWork ?? ((id: string, time: number) => hasOutstandingWork(deps, id, time, observation));
53
+ const wait = deps.wait ?? waitForSubagents;
46
54
 
47
- while (hasWork(sessionId, now())) {
48
- const remainingMs = deadlineAt - now();
49
- if (remainingMs <= 0) {
50
- throw new Error(`Auto-drain timed out after ${timeoutMs}ms with background work still active in session '${sessionId}'.`);
51
- }
52
- const waitResult = await wait(
53
- { all: true, timeoutMs: remainingMs },
54
- undefined,
55
- {
56
- state: deps.state,
57
- events: deps.events,
58
- now,
59
- stopOnAttention: false,
60
- failOnFailedRuns: true,
61
- failOnAttention: true,
62
- },
63
- );
64
- if (waitResult.isError) {
65
- throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || "bg_wait returned an error without details"}.`);
55
+ while (true) {
56
+ if (deps.state.currentSessionId !== sessionId) throw new Error("Auto-drain stopped because the active session changed.");
57
+ if (deps.hasPendingSupervisorRequest?.()) break;
58
+ const work = hasWork(sessionId, now());
59
+ observation?.predicate(work);
60
+ if (!work) break;
61
+ const remainingMs = deadlineAt - now();
62
+ if (remainingMs <= 0) {
63
+ throw new Error(`Auto-drain timed out after ${timeoutMs}ms with background work still active in session '${sessionId}'.`);
64
+ }
65
+ const waitResult = await wait(
66
+ { all: true, timeoutMs: remainingMs },
67
+ undefined,
68
+ {
69
+ state: deps.state,
70
+ asyncDirRoot: deps.asyncDirRoot,
71
+ resultsDir: deps.resultsDir,
72
+ nestedRootRunId: deps.nestedRootRunId,
73
+ events: deps.events,
74
+ now,
75
+ stopOnAttention: false,
76
+ failOnFailedRuns: true,
77
+ failOnAttention: true,
78
+ hasPendingSupervisorRequest: deps.hasPendingSupervisorRequest,
79
+ },
80
+ );
81
+ if (waitResult.isError) {
82
+ throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || "bg_wait returned an error without details"}.`);
83
+ }
84
+ if (waitResult.details.wait?.reason === "supervisor_request") break;
85
+ if (deps.hasPendingSupervisorRequest?.()) break;
66
86
  }
87
+ observation?.complete();
88
+ } catch (error) {
89
+ observation?.deny();
90
+ throw error;
67
91
  }
68
92
  }
@@ -0,0 +1,38 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as sdk from "@earendil-works/pi-coding-agent";
4
+ import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.ts";
5
+ import { runConfiguredSubagent, type SubagentRunConfig } from "./subagent-runner.ts";
6
+ import { getAgentDir } from "../../shared/utils.ts";
7
+
8
+ /**
9
+ * Pi's extension loader supplies the embedded SDK. Bare Bun/Node cannot replace
10
+ * it: an apparent import success can be an auto-installed, different SDK.
11
+ * Await the configured runner inside extension initialization so the outer Pi
12
+ * session/RPC loop never starts. Exit only after shared disposal/lease release.
13
+ * Derived from xz-dev's PR #2049, commit 910807bfefcf9ee41d73fa25ec86dcd75ab8f4b2.
14
+ */
15
+ export default async function runBinaryBootstrap(): Promise<never> {
16
+ const configPath = process.env.PI_SUBAGENT_RUNNER_CONFIG;
17
+ delete process.env.PI_SUBAGENT_RUNNER_CONFIG;
18
+ try {
19
+ if (!configPath || !path.isAbsolute(configPath)) throw new Error("Missing absolute PI_SUBAGENT_RUNNER_CONFIG path");
20
+ const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as SubagentRunConfig;
21
+ if (!config || typeof config.id !== "string" || typeof config.asyncDir !== "string" || !Array.isArray(config.steps)) {
22
+ throw new Error("Invalid binary runner configuration");
23
+ }
24
+ try {
25
+ fs.unlinkSync(configPath);
26
+ } catch {
27
+ // Temp-config cleanup is best effort, as in the Node entrypoint.
28
+ }
29
+ // Pi applies httpIdleTimeoutMs to its dispatcher only after extension
30
+ // factories return; this factory never does, so install the runner's own.
31
+ installRunnerHttpDispatcher({ agentDir: getAgentDir(), cwd: process.cwd() });
32
+ await runConfiguredSubagent(config, { loadPiCodingAgent: async () => sdk });
33
+ process.exit(0);
34
+ } catch (error) {
35
+ console.error("Subagent binary runner error:", error);
36
+ process.exit(1);
37
+ }
38
+ }
@@ -177,7 +177,7 @@ function statusStepForTask(task: RunnerSubagentStep): StatusStep {
177
177
  model: task.model,
178
178
  ...(task.contextLimit !== undefined ? { contextLimit: task.contextLimit } : {}),
179
179
  thinking: task.thinking,
180
- attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
180
+ requestedModel: task.requestedModel,
181
181
  recentTools: [],
182
182
  recentOutput: [],
183
183
  };
@@ -1,7 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { resultFilePath, resultPayloadPathForSessionRun } from "./result-files.ts";
4
- import type { AcceptanceLedger, ArtifactPaths, AsyncStatus, CostSummary, EffectsProjection, ExecutionProjection, ModelAttempt, Usage } from "../../shared/types.ts";
4
+ import type { AcceptanceLedger, ArtifactPaths, AsyncStatus, CostSummary, EffectsProjection, ExecutionProjection, Usage } from "../../shared/types.ts";
5
5
  import { readStatus } from "../../shared/utils.ts";
6
6
 
7
7
  export interface ImportedAsyncRoot {
@@ -13,6 +13,7 @@ export interface ImportedAsyncRoot {
13
13
 
14
14
  export interface ImportedAsyncRootResult {
15
15
  agent: string;
16
+ importedPublication?: { sessionId?: string; toolCallId?: string };
16
17
  /** Human-readable display name for the child session, when derived at launch. */
17
18
  sessionName?: string;
18
19
  output: string;
@@ -22,8 +23,7 @@ export interface ImportedAsyncRootResult {
22
23
  sessionFile?: string;
23
24
  intercomTarget?: string;
24
25
  model?: string;
25
- attemptedModels?: string[];
26
- modelAttempts?: ModelAttempt[];
26
+ requestedModel?: string;
27
27
  contextOverflow?: boolean;
28
28
  totalCost?: CostSummary;
29
29
  usage?: Usage;
@@ -32,6 +32,7 @@ export interface ImportedAsyncRootResult {
32
32
  structuredOutputSchemaPath?: string;
33
33
  acceptance?: AcceptanceLedger;
34
34
  artifactPaths?: ArtifactPaths;
35
+ savedOutputPath?: string;
35
36
  outputSaveError?: string;
36
37
  transcriptPath?: string;
37
38
  transcriptError?: string;
@@ -42,6 +43,8 @@ export interface ImportedAsyncRootResult {
42
43
  }
43
44
 
44
45
  interface AsyncResultFile {
46
+ sessionId?: string;
47
+ toolCallId?: string;
45
48
  state?: string;
46
49
  success?: boolean;
47
50
  summary?: string;
@@ -61,8 +64,7 @@ interface AsyncResultFile {
61
64
  sessionFile?: string;
62
65
  intercomTarget?: string;
63
66
  model?: string;
64
- attemptedModels?: string[];
65
- modelAttempts?: ModelAttempt[];
67
+ requestedModel?: string;
66
68
  contextOverflow?: boolean;
67
69
  totalCost?: CostSummary;
68
70
  usage?: Usage;
@@ -71,6 +73,7 @@ interface AsyncResultFile {
71
73
  structuredOutputSchemaPath?: string;
72
74
  acceptance?: AcceptanceLedger;
73
75
  artifactPaths?: ArtifactPaths;
76
+ savedOutputPath?: string;
74
77
  outputSaveError?: string;
75
78
  transcriptPath?: string;
76
79
  transcriptError?: string;
@@ -80,23 +83,6 @@ interface AsyncResultFile {
80
83
  const TERMINAL_STATES = new Set(["complete", "failed", "partial", "paused", "stopped"]);
81
84
  const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "partial", "paused", "stopped"]);
82
85
 
83
- function usageFromAttempts(attempts: ModelAttempt[] | undefined): Usage | undefined {
84
- if (!attempts?.length) return undefined;
85
- const usage: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
86
- for (const attempt of attempts) {
87
- if (!attempt.usage) continue;
88
- usage.input += attempt.usage.input;
89
- usage.output += attempt.usage.output;
90
- usage.cacheRead += attempt.usage.cacheRead;
91
- usage.cacheWrite += attempt.usage.cacheWrite;
92
- usage.cost += attempt.usage.cost;
93
- usage.turns += attempt.usage.turns;
94
- }
95
- return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
96
- ? usage
97
- : undefined;
98
- }
99
-
100
86
  function readResultFile(resultPath: string): AsyncResultFile | undefined {
101
87
  try {
102
88
  return JSON.parse(fs.readFileSync(resultPath, "utf-8")) as AsyncResultFile;
@@ -121,6 +107,11 @@ function selectedStatusStep(status: AsyncStatus | null, index: number): NonNulla
121
107
 
122
108
  function isTerminalStatus(status: AsyncStatus | null, index: number): boolean {
123
109
  if (!status) return false;
110
+ // A workflow-owned single runner publishes its result after completing its
111
+ // step. Keep that window open while root process proof is absent or pending;
112
+ // explicit terminal/unavailable proof retains the existing step fallback.
113
+ if (status.mode === "single" && status.parentWorkflowRunId
114
+ && (!status.processTerminal || status.processTerminal.state === "pending")) return TERMINAL_STATES.has(status.state);
124
115
  const step = selectedStatusStep(status, index);
125
116
  if (step && TERMINAL_STEP_STATUSES.has(step.status)) return true;
126
117
  return TERMINAL_STATES.has(status.state);
@@ -146,7 +137,6 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
146
137
  const execution = step?.execution ?? (partialStatus
147
138
  ? { status: "partial" as const, success: false, exitCode: 1, error: message }
148
139
  : undefined);
149
- const usage = usageFromAttempts(step?.modelAttempts);
150
140
  return {
151
141
  agent,
152
142
  output: message,
@@ -158,11 +148,9 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
158
148
  ...(step?.sessionName ? { sessionName: step.sessionName } : {}),
159
149
  ...(step?.sessionFile ?? status.sessionFile ? { sessionFile: step?.sessionFile ?? status.sessionFile } : {}),
160
150
  ...(step?.model ? { model: step.model } : {}),
161
- ...(step?.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
162
- ...(step?.modelAttempts ? { modelAttempts: step.modelAttempts } : {}),
151
+ ...(step?.requestedModel ? { requestedModel: step.requestedModel } : {}),
163
152
  ...(step?.contextOverflow ? { contextOverflow: true } : {}),
164
153
  ...(step?.totalCost ? { totalCost: step.totalCost } : {}),
165
- ...(usage ? { usage } : {}),
166
154
  ...(step?.structuredOutput !== undefined ? { structuredOutput: step.structuredOutput } : {}),
167
155
  ...(step?.structuredOutputPath ? { structuredOutputPath: step.structuredOutputPath } : {}),
168
156
  ...(step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: step.structuredOutputSchemaPath } : {}),
@@ -175,7 +163,6 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
175
163
 
176
164
  function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string): ImportedAsyncRootResult {
177
165
  const step = selectedStatusStep(status, root.index);
178
- const usage = usageFromAttempts(step?.modelAttempts);
179
166
  return {
180
167
  agent: step?.agent ?? status?.steps?.[root.index]?.agent ?? "subagent",
181
168
  output: message,
@@ -186,11 +173,9 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
186
173
  ...(step?.sessionName ? { sessionName: step.sessionName } : {}),
187
174
  ...(step?.sessionFile ?? status?.sessionFile ? { sessionFile: step?.sessionFile ?? status?.sessionFile } : {}),
188
175
  ...(step?.model ? { model: step.model } : {}),
189
- ...(step?.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
190
- ...(step?.modelAttempts ? { modelAttempts: step.modelAttempts } : {}),
176
+ ...(step?.requestedModel ? { requestedModel: step.requestedModel } : {}),
191
177
  ...(step?.contextOverflow ? { contextOverflow: true } : {}),
192
178
  ...(step?.totalCost ? { totalCost: step.totalCost } : {}),
193
- ...(usage ? { usage } : {}),
194
179
  ...(step?.transcriptPath ? { transcriptPath: step.transcriptPath } : {}),
195
180
  };
196
181
  }
@@ -206,9 +191,13 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
206
191
  const success = state === "complete" && !timedOut && !stopped;
207
192
  const error = child?.error ?? (success ? undefined : stopped ? "Subagent stopped by user." : result.error ?? result.summary ?? status?.error ?? `Attached async root ${root.runId} did not complete successfully.`);
208
193
  const execution = state ? { status: state === "complete" ? "completed" as const : state, success, exitCode: success ? 0 : 1, ...(error ? { error } : {}) } : undefined;
209
- const usage = child?.usage ?? usageFromAttempts(step?.modelAttempts);
194
+ const usage = child?.usage;
210
195
  return {
211
196
  agent,
197
+ importedPublication: {
198
+ ...(typeof result.sessionId === "string" ? { sessionId: result.sessionId } : {}),
199
+ ...(typeof result.toolCallId === "string" ? { toolCallId: result.toolCallId } : {}),
200
+ },
212
201
  output: success ? output : (output || error || ""),
213
202
  success,
214
203
  exitCode: success ? 0 : 1,
@@ -219,8 +208,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
219
208
  ...(child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile ? { sessionFile: child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile } : {}),
220
209
  ...(child?.intercomTarget ? { intercomTarget: child.intercomTarget } : {}),
221
210
  ...(child?.model ?? step?.model ? { model: child?.model ?? step?.model } : {}),
222
- ...(child?.attemptedModels ?? step?.attemptedModels ? { attemptedModels: child?.attemptedModels ?? step?.attemptedModels } : {}),
223
- ...(child?.modelAttempts ?? step?.modelAttempts ? { modelAttempts: child?.modelAttempts ?? step?.modelAttempts } : {}),
211
+ ...(child?.requestedModel ?? step?.requestedModel ? { requestedModel: child?.requestedModel ?? step?.requestedModel } : {}),
224
212
  ...(child?.contextOverflow || step?.contextOverflow ? { contextOverflow: true } : {}),
225
213
  ...(child?.totalCost ?? step?.totalCost ? { totalCost: child?.totalCost ?? step?.totalCost } : {}),
226
214
  ...(usage ? { usage } : {}),
@@ -229,6 +217,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
229
217
  ...(child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath } : {}),
230
218
  ...(child?.acceptance ?? step?.acceptance ? { acceptance: child?.acceptance ?? step?.acceptance } : {}),
231
219
  ...(child?.artifactPaths ? { artifactPaths: child.artifactPaths } : {}),
220
+ ...(child?.savedOutputPath ? { savedOutputPath: child.savedOutputPath } : {}),
232
221
  ...(child?.outputSaveError ? { outputSaveError: child.outputSaveError } : {}),
233
222
  ...(child?.transcriptPath ?? step?.transcriptPath ? { transcriptPath: child?.transcriptPath ?? step?.transcriptPath } : {}),
234
223
  ...(child?.transcriptError ? { transcriptError: child.transcriptError } : {}),
@@ -275,28 +275,36 @@ function parseSteerRequest(raw: unknown): SteerRequest | undefined {
275
275
  };
276
276
  }
277
277
 
278
- export function consumeSteerRequestsFromDir(dir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs): SteerRequest[] {
279
- if (!fsImpl.existsSync(dir)) return [];
278
+ export function consumeSteerRequestsFromDir(dir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs, onError: (error: unknown) => void = () => {}): SteerRequest[] {
280
279
  let entries: string[];
281
280
  try {
282
281
  entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort();
283
- } catch {
282
+ } catch (error) {
284
283
  // Leave requests in place so the periodic poll can retry the scan.
284
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") onError(error);
285
285
  return [];
286
286
  }
287
287
  const requests: SteerRequest[] = [];
288
288
  for (const entry of entries) {
289
289
  const requestPath = path.join(dir, entry);
290
290
  let parsed: SteerRequest | undefined;
291
+ let text: string;
292
+ try {
293
+ text = fsImpl.readFileSync(requestPath, "utf-8");
294
+ } catch (error) {
295
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") onError(error);
296
+ continue;
297
+ }
291
298
  try {
292
- parsed = parseSteerRequest(JSON.parse(fsImpl.readFileSync(requestPath, "utf-8")));
299
+ parsed = parseSteerRequest(JSON.parse(text));
293
300
  } catch {
294
301
  parsed = undefined;
295
302
  }
296
303
  try {
297
304
  fsImpl.rmSync(requestPath, { recursive: true });
298
- } catch {
305
+ } catch (error) {
299
306
  // Already removed by a concurrent check — do not execute it twice.
307
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") onError(error);
300
308
  continue;
301
309
  }
302
310
  if (parsed) requests.push(parsed);
@@ -304,8 +312,8 @@ export function consumeSteerRequestsFromDir(dir: string, fsImpl: Pick<typeof fs,
304
312
  return requests.sort((left, right) => left.ts - right.ts || left.id.localeCompare(right.id));
305
313
  }
306
314
 
307
- export function consumeSteerRequests(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs): SteerRequest[] {
308
- return consumeSteerRequestsFromDir(steerRequestsDir(asyncDir), fsImpl);
315
+ export function consumeSteerRequests(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs, onError?: (error: unknown) => void): SteerRequest[] {
316
+ return consumeSteerRequestsFromDir(steerRequestsDir(asyncDir), fsImpl, onError);
309
317
  }
310
318
 
311
319
  export function queueRevivalBrief(asyncDir: string, request: SteerRequest): string {
@@ -387,17 +395,26 @@ function parseStopRequest(raw: unknown): StopRequest | undefined {
387
395
  function consumeStopRequestFile(
388
396
  requestPath: string,
389
397
  fsImpl: Pick<typeof fs, "rmSync" | "readFileSync">,
398
+ onError?: (error: unknown) => void,
390
399
  ): StopRequest | undefined {
400
+ let text: string;
401
+ try {
402
+ text = fsImpl.readFileSync(requestPath, "utf-8");
403
+ } catch (error) {
404
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) onError?.(error);
405
+ return undefined;
406
+ }
391
407
  let request: StopRequest | undefined;
392
408
  try {
393
- request = parseStopRequest(JSON.parse(fsImpl.readFileSync(requestPath, "utf-8")));
409
+ request = parseStopRequest(JSON.parse(text));
394
410
  } catch {
395
411
  request = undefined;
396
412
  }
397
413
  try {
398
414
  fsImpl.rmSync(requestPath, { force: true, recursive: true });
399
- } catch {
400
- // Already removed by a concurrent check — do not execute it twice.
415
+ } catch (error) {
416
+ // Execute only after successful removal.
417
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) onError?.(error);
401
418
  return undefined;
402
419
  }
403
420
  return request;
@@ -406,6 +423,7 @@ function consumeStopRequestFile(
406
423
  export function consumeStopRequestPayloads(
407
424
  asyncDir: string,
408
425
  fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs,
426
+ onError?: (error: unknown) => void,
409
427
  ): StopRequest[] {
410
428
  const dir = stopRequestsDir(asyncDir);
411
429
  const requests: StopRequest[] = [];
@@ -413,18 +431,19 @@ export function consumeStopRequestPayloads(
413
431
  let entries: string[];
414
432
  try {
415
433
  entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort();
416
- } catch {
434
+ } catch (error) {
435
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) onError?.(error);
417
436
  entries = [];
418
437
  }
419
438
  for (const entry of entries) {
420
- const request = consumeStopRequestFile(path.join(dir, entry), fsImpl);
439
+ const request = consumeStopRequestFile(path.join(dir, entry), fsImpl, onError);
421
440
  if (request) requests.push(request);
422
441
  }
423
442
  }
424
443
 
425
444
  const legacyPath = stopRequestPath(asyncDir);
426
445
  if (fsImpl.existsSync(legacyPath)) {
427
- const request = consumeStopRequestFile(legacyPath, fsImpl);
446
+ const request = consumeStopRequestFile(legacyPath, fsImpl, onError);
428
447
  if (request) requests.push(request);
429
448
  }
430
449
  return requests.sort((left, right) => (left.ts ?? 0) - (right.ts ?? 0));
@@ -470,19 +489,21 @@ export function deliverStopRequest(input: {
470
489
  requestAsyncStop(input.asyncDir, { ...(input.source ? { source: input.source } : {}), ...(input.targetIndex !== undefined ? { targetIndex: input.targetIndex } : {}), ...(input.childId ? { childId: input.childId } : {}) }, { now: input.now });
471
490
  }
472
491
 
492
+
473
493
  /**
474
- * Runner side: watch the control inbox and route interrupt requests into
475
- * `onInterrupt`. Uses `fs.watch` when available and starts interval polling
494
+ * Active owner: watch and consume only kinds with installed handlers.
495
+ * Uses `fs.watch` when available and starts interval polling
476
496
  * only when native watching is unavailable or fails. Fires once per distinct
477
497
  * request. Returns a disposer.
478
498
  */
479
499
  export function watchAsyncControlInbox(
480
500
  asyncDir: string,
481
501
  opts: {
482
- onInterrupt: () => void;
502
+ onInterrupt?: () => void;
483
503
  onTimeout?: () => void;
484
504
  onStop?: (request: StopRequest) => void;
485
505
  onSteer?: (request: SteerRequest) => void;
506
+ onError?: (error: unknown, phase: "install" | "scan" | "callback", request?: SteerRequest) => void;
486
507
  pollIntervalMs?: number;
487
508
  safetyPollIntervalMs?: number;
488
509
  platform?: NodeJS.Platform;
@@ -493,22 +514,44 @@ export function watchAsyncControlInbox(
493
514
  const fsImpl = opts.fs ?? fs;
494
515
  const timers = opts.timers ?? { setInterval, clearInterval };
495
516
  const dir = controlInboxDir(asyncDir);
517
+ const report = (error: unknown, phase: "install" | "scan" | "callback", request?: SteerRequest): void => {
518
+ try {
519
+ if (opts.onError) opts.onError(error, phase, request);
520
+ else console.error(`Control inbox ${phase} failed:`, error);
521
+ } catch (reportError) {
522
+ console.error("Control inbox error reporter failed:", reportError);
523
+ }
524
+ };
525
+ const dirs = [
526
+ ...(opts.onInterrupt || opts.onTimeout || opts.onStop ? [dir] : []),
527
+ ...(opts.onStop ? [stopRequestsDir(asyncDir)] : []),
528
+ ...(opts.onSteer ? [steerRequestsDir(asyncDir)] : []),
529
+ ];
530
+ if (dirs.length === 0) return () => {};
496
531
  try {
497
- fsImpl.mkdirSync(dir, { recursive: true });
498
- } catch {
499
- // Best effort — the poll/watch below tolerates a missing dir.
532
+ for (const target of dirs) fsImpl.mkdirSync(target, { recursive: true });
533
+ } catch (error) {
534
+ report(error, "install");
500
535
  }
501
536
 
502
537
  let disposed = false;
503
538
  const check = (): void => {
504
539
  if (disposed) return;
505
540
  try {
506
- for (const stopRequest of consumeStopRequestPayloads(asyncDir, fsImpl)) opts.onStop?.(stopRequest);
507
- if (consumeTimeoutRequest(asyncDir, fsImpl)) opts.onTimeout?.();
508
- if (consumeInterruptRequest(asyncDir, fsImpl)) opts.onInterrupt();
509
- for (const request of consumeSteerRequests(asyncDir, fsImpl)) opts.onSteer?.(request);
510
- } catch {
511
- // Never let inbox errors crash the runner.
541
+ if (opts.onStop) for (const request of consumeStopRequestPayloads(asyncDir, fsImpl, (error) => report(error, "scan"))) {
542
+ try { opts.onStop(request); } catch (error) { report(error, "callback"); }
543
+ }
544
+ if (opts.onTimeout && consumeTimeoutRequest(asyncDir, fsImpl)) {
545
+ try { opts.onTimeout(); } catch (error) { report(error, "callback"); }
546
+ }
547
+ if (opts.onInterrupt && consumeInterruptRequest(asyncDir, fsImpl)) {
548
+ try { opts.onInterrupt(); } catch (error) { report(error, "callback"); }
549
+ }
550
+ if (opts.onSteer) for (const request of consumeSteerRequestsFromDir(steerRequestsDir(asyncDir), fsImpl, (error) => report(error, "scan"))) {
551
+ try { opts.onSteer(request); } catch (error) { report(error, "callback", request); }
552
+ }
553
+ } catch (error) {
554
+ report(error, "scan");
512
555
  }
513
556
  };
514
557
 
@@ -516,40 +559,31 @@ export function watchAsyncControlInbox(
516
559
  check();
517
560
 
518
561
  const watchers: fs.FSWatcher[] = [];
519
- const watchedDirs = new Set<string>();
520
562
  let interval: ReturnType<typeof setInterval> | undefined;
521
563
  let safetyInterval: ReturnType<typeof setInterval> | undefined;
522
564
  const startPolling = (): void => {
523
565
  if (interval || disposed) return;
566
+ if (safetyInterval) { timers.clearInterval(safetyInterval); safetyInterval = undefined; }
524
567
  interval = timers.setInterval(check, opts.pollIntervalMs ?? POLL_INTERVAL_MS);
525
568
  interval.unref?.();
526
569
  };
527
- const startSafetyPolling = (): void => {
528
- if (safetyInterval || disposed) return;
529
- safetyInterval = timers.setInterval(check, opts.safetyPollIntervalMs ?? CONTROL_SAFETY_POLL_INTERVAL_MS);
530
- safetyInterval.unref?.();
531
- };
532
- const watchDir = (target: string, create = false): void => {
533
- if (disposed || watchedDirs.has(target)) return;
534
- if (create) fsImpl.mkdirSync(target, { recursive: true });
535
- const watcher = fsImpl.watch(resolveWatchPath(target, fsImpl.realpathSync.native), () => check());
536
- watcher.on?.("error", startPolling);
537
- watchers.push(watcher);
538
- watchedDirs.add(target);
539
- };
540
570
  try {
541
571
  if (shouldUseNativeFsWatch("runner-control-inbox", opts.platform)) {
542
- watchDir(dir);
543
- watchDir(stopRequestsDir(asyncDir), true);
544
- watchDir(steerRequestsDir(asyncDir), true);
545
- startSafetyPolling();
572
+ for (const target of dirs) {
573
+ const watcher = fsImpl.watch(resolveWatchPath(target, fsImpl.realpathSync.native), check);
574
+ watcher.on?.("error", startPolling);
575
+ watchers.push(watcher);
576
+ }
577
+ if (!interval) {
578
+ safetyInterval = timers.setInterval(check, opts.safetyPollIntervalMs ?? CONTROL_SAFETY_POLL_INTERVAL_MS);
579
+ safetyInterval.unref?.();
580
+ }
546
581
  } else {
547
582
  startPolling();
548
583
  }
549
584
  } catch {
550
585
  startPolling();
551
586
  }
552
-
553
587
  return () => {
554
588
  if (disposed) return;
555
589
  disposed = true;
@@ -1,7 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
- import { safeTerminalText } from "../../shared/display-text.ts";
4
+ import { safeTerminalText, truncateDisplayText } from "../../shared/display-text.ts";
5
5
  import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.ts";
6
6
  import { formatActivityLabel } from "../../shared/status-format.ts";
7
7
  import {
@@ -23,6 +23,10 @@ import { isTrustedRecordedSessionFile } from "../../shared/session-file-trust.ts
23
23
  const DEFAULT_TRANSCRIPT_LINES = 80;
24
24
  const MAX_TRANSCRIPT_LINES = 500;
25
25
  const TRANSCRIPT_TAIL_BYTES = 256 * 1024;
26
+ const MAX_TRANSCRIPT_LINE_CHARS = 2000;
27
+ const MAX_TRANSCRIPT_BODY_BYTES = 32 * 1024;
28
+ const TRANSCRIPT_LINE_OMISSION = "… [content omitted]";
29
+ const TRANSCRIPT_BODY_OMISSION = " … [earlier lines omitted]";
26
30
 
27
31
  type ForegroundControl = SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never;
28
32
  type ForegroundRun = NonNullable<SubagentState["foregroundRuns"]> extends Map<string, infer T> ? T : never;
@@ -494,7 +498,31 @@ function appendTranscriptBody(lines: string[], sourceLabel: string, sourceLines:
494
498
  lines.push(" (no transcript lines available yet)");
495
499
  return;
496
500
  }
497
- for (const line of sourceLines) lines.push(` ${line}`);
501
+ // Bound the rendered body, not the raw input: terminal escaping can expand it.
502
+ // Keep line prefixes (roles/tool names), then prefer whole recent lines. The
503
+ // byte budget includes indentation, separators and omission markers, but not
504
+ // the source label, run metadata, warnings or artifact paths above the body.
505
+ const body: string[] = [];
506
+ let bytes = 0;
507
+ for (let index = sourceLines.length - 1; index >= 0; index--) {
508
+ // Preserve assembled-line binary detection (including indentation). A
509
+ // binary placeholder replaces the whole line and must not be reindented.
510
+ const safe = safeTerminalText(` ${sourceLines[index]!}`);
511
+ const lineLimit = MAX_TRANSCRIPT_LINE_CHARS + 2;
512
+ const line = safe.length <= lineLimit
513
+ ? safe
514
+ : truncateDisplayText(safe, lineLimit - TRANSCRIPT_LINE_OMISSION.length) + TRANSCRIPT_LINE_OMISSION;
515
+ const size = Buffer.byteLength(line) + 1;
516
+ if (bytes + size > MAX_TRANSCRIPT_BODY_BYTES) {
517
+ const markerBytes = Buffer.byteLength(TRANSCRIPT_BODY_OMISSION) + 1;
518
+ while (bytes + markerBytes > MAX_TRANSCRIPT_BODY_BYTES) bytes -= Buffer.byteLength(body.pop()!) + 1;
519
+ body.push(TRANSCRIPT_BODY_OMISSION);
520
+ break;
521
+ }
522
+ body.push(line);
523
+ bytes += size;
524
+ }
525
+ lines.push(...body.reverse());
498
526
  }
499
527
 
500
528
  export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string, options: TranscriptOptions = {}): string {