@vicary/pi-subagents 0.84.0-1 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  5. package/bundle/{chunk-4MDR6V46.js → chunk-A7VJ5XXE.js} +190 -1177
  6. package/bundle/{chunk-LGLEH7B6.js → chunk-B3OOJJA6.js} +231 -182
  7. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-T44HVL5U.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/{chunk-F4AMYP5N.js → chunk-HS4WPO6B.js} +15 -6
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-4NIY3BE6.js → chunk-JHBQ7N2L.js} +2 -2
  14. package/bundle/{chunk-HKJLSMXV.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  16. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  17. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  18. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  19. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  20. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  21. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  22. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  23. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  24. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  25. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  26. package/bundle/{chunk-67ENPDDA.js → chunk-QZL2ZZPM.js} +22 -11
  27. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  28. package/bundle/chunk-T5V5BRCL.js +1067 -0
  29. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  30. package/bundle/{chunk-TE4LHYHN.js → chunk-VEZMZDTW.js} +209 -93
  31. package/bundle/{chunk-X2MXCSA5.js → chunk-YZBCREP5.js} +310 -101
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +2 -2
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +5 -9
  78. package/src/runs/background/async-execution.js +62 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.js +6 -1
  83. package/src/runs/background/auto-drain.js +2 -1
  84. package/src/runs/background/boot-id.d.ts +1 -3
  85. package/src/runs/background/boot-id.js +1 -3
  86. package/src/runs/background/completion-batcher.d.ts +3 -4
  87. package/src/runs/background/completion-batcher.js +2 -3
  88. package/src/runs/background/control-channel.d.ts +0 -6
  89. package/src/runs/background/control-channel.js +0 -6
  90. package/src/runs/background/fleet-view.js +2 -3
  91. package/src/runs/background/notify.d.ts +0 -2
  92. package/src/runs/background/notify.js +0 -2
  93. package/src/runs/background/result-watcher.d.ts +1 -0
  94. package/src/runs/background/result-watcher.js +59 -29
  95. package/src/runs/background/resume-guidance.js +4 -2
  96. package/src/runs/background/retained-children.js +2 -1
  97. package/src/runs/background/run-child-session.d.ts +0 -1
  98. package/src/runs/background/run-child-session.js +1 -1
  99. package/src/runs/background/run-status.js +4 -3
  100. package/src/runs/background/scheduled-runs.d.ts +3 -1
  101. package/src/runs/background/scheduled-runs.js +13 -16
  102. package/src/runs/background/subagent-runner.d.ts +2 -4
  103. package/src/runs/background/subagent-runner.js +9 -6
  104. package/src/runs/background/subagent-wait.js +12 -15
  105. package/src/runs/background/wait-config.d.ts +2 -0
  106. package/src/runs/background/wait-config.js +17 -3
  107. package/src/runs/background/wait-tool.js +4 -2
  108. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  109. package/src/runs/background/workflow-terminal-proof.js +0 -1
  110. package/src/runs/foreground/execution.d.ts +0 -3
  111. package/src/runs/foreground/execution.js +17 -9
  112. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  113. package/src/runs/foreground/subagent-executor.js +107 -26
  114. package/src/runs/shared/child-commands.js +15 -2
  115. package/src/runs/shared/child-hooks.d.ts +1 -7
  116. package/src/runs/shared/child-hooks.js +13 -5
  117. package/src/runs/shared/child-launch.js +6 -2
  118. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  119. package/src/runs/shared/child-session.d.ts +1 -1
  120. package/src/runs/shared/child-session.js +21 -2
  121. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  122. package/src/runs/shared/child-tool-plan.js +0 -1
  123. package/src/runs/shared/claude-code-adapter.js +11 -0
  124. package/src/runs/shared/external-cli-runner.js +26 -6
  125. package/src/runs/shared/herdr-connection.js +2 -1
  126. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  127. package/src/runs/shared/herdr-pane-host.js +17 -1
  128. package/src/runs/shared/herdr-placed-run.js +48 -22
  129. package/src/runs/shared/lane-metadata.d.ts +0 -1
  130. package/src/runs/shared/lane-metadata.js +0 -1
  131. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  132. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  133. package/src/runs/shared/model-resolution.d.ts +2 -2
  134. package/src/runs/shared/model-resolution.js +7 -1
  135. package/src/runs/shared/model-scope.d.ts +1 -5
  136. package/src/runs/shared/model-scope.js +1 -5
  137. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  138. package/src/runs/shared/mutation-evidence.js +52 -7
  139. package/src/runs/shared/nested-events.d.ts +1 -0
  140. package/src/runs/shared/nested-events.js +1 -1
  141. package/src/runs/shared/parallel-utils.d.ts +0 -1
  142. package/src/runs/shared/permissions.js +5 -3
  143. package/src/runs/shared/placement-host.d.ts +5 -1
  144. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  145. package/src/runs/shared/rex-pane-host.js +0 -2
  146. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  147. package/src/runs/shared/run-launch-folder.js +21 -0
  148. package/src/runs/shared/runner-launcher.d.ts +12 -1
  149. package/src/runs/shared/runner-launcher.js +16 -0
  150. package/src/runs/shared/single-output.d.ts +3 -3
  151. package/src/runs/shared/single-output.js +5 -3
  152. package/src/runs/shared/structured-output.d.ts +8 -0
  153. package/src/runs/shared/structured-output.js +30 -2
  154. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  155. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  156. package/src/runs/shared/tool-timeout.js +2 -1
  157. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  158. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  159. package/src/runs/shared/worktree.d.ts +3 -0
  160. package/src/runs/shared/worktree.js +20 -0
  161. package/src/shared/capacity-resilient-json.d.ts +1 -1
  162. package/src/shared/child-cache-retention.d.ts +1 -2
  163. package/src/shared/child-cache-retention.js +1 -2
  164. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  165. package/src/shared/fleet-transcript-reader.js +333 -0
  166. package/src/shared/formatters.d.ts +0 -18
  167. package/src/shared/formatters.js +0 -18
  168. package/src/shared/session-succession.d.ts +16 -1
  169. package/src/shared/session-succession.js +41 -2
  170. package/src/shared/session-warnings.d.ts +7 -0
  171. package/src/shared/session-warnings.js +26 -0
  172. package/src/shared/settings.d.ts +0 -23
  173. package/src/shared/settings.js +3 -35
  174. package/src/shared/types.d.ts +28 -11
  175. package/src/shared/types.js +0 -12
  176. package/src/shared/utils.d.ts +0 -14
  177. package/src/shared/utils.js +0 -22
  178. package/src/shared/wait-tool-name.d.ts +8 -0
  179. package/src/shared/wait-tool-name.js +13 -0
  180. package/src/slash/slash-commands.js +2 -1
  181. package/src/slash/subagent-cost.d.ts +3 -2
  182. package/src/slash/subagent-cost.js +22 -3
  183. package/src/slash/subagents-admin.js +0 -1
  184. package/src/tui/fleet-status.d.ts +0 -5
  185. package/src/tui/fleet-status.js +4 -24
  186. package/src/tui/fleet-transcript.d.ts +1 -44
  187. package/src/tui/fleet-transcript.js +1 -327
  188. package/src/tui/fleet.js +6 -4
  189. package/src/tui/render.d.ts +0 -9
  190. package/src/tui/render.js +81 -47
  191. package/src/tui/subagent-messages.js +3 -2
  192. package/src/watchdog/register-child.d.ts +2 -3
  193. package/src/watchdog/register-child.js +2 -3
  194. package/src/watchdog/turn-delta.js +2 -1
  195. package/src/workflows/scripted-workflow.js +241 -20
  196. package/src/workflows/workflow-launch-record.d.ts +15 -6
  197. package/src/workflows/workflow-launch-record.js +30 -12
  198. package/src/workflows/workflow-resume-claim.js +2 -2
  199. package/src/workflows/workflow-resume.d.ts +1 -1
  200. package/src/workflows/workflow-resume.js +11 -8
  201. package/src/workflows/workflow-script-worker.d.ts +13 -0
  202. package/src/workflows/workflow-script-worker.js +79 -0
  203. package/workflow-script-process.cjs +36 -0
  204. package/workflow-script-worker.cjs +4 -1
@@ -1,334 +1,8 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
1
  import { getLanguageFromPath, highlightCode } from "@earendil-works/pi-coding-agent";
4
2
  import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
5
3
  import { safeTerminalText as safeDisplayText } from "../shared/display-text.js";
6
- import { isTrustedRecordedSessionFile } from "../shared/session-file-trust.js";
7
- const DEFAULT_MAX_RECORDS = 240;
8
- const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
9
- const MAX_MESSAGE_CHARS = 64 * 1024;
4
+ import { objectValue, safeTranscriptEvent } from "../shared/fleet-transcript-reader.js";
10
5
  const TOOL_PREVIEW_LINES = 7;
11
- function sanitizeJsonDisplayValue(value) {
12
- if (typeof value === "string") {
13
- const safe = safeDisplayText(value);
14
- return { value: safe, changed: safe !== value };
15
- }
16
- if (Array.isArray(value)) {
17
- const sanitized = value.map(sanitizeJsonDisplayValue);
18
- return {
19
- value: sanitized.map((entry) => entry.value),
20
- changed: sanitized.some((entry) => entry.changed),
21
- };
22
- }
23
- if (value && typeof value === "object") {
24
- let changed = false;
25
- const sanitized = Object.create(null);
26
- for (const [key, nested] of Object.entries(value)) {
27
- const safeKey = safeDisplayText(key);
28
- const safeValue = sanitizeJsonDisplayValue(nested);
29
- sanitized[safeKey] = safeValue.value;
30
- changed ||= safeKey !== key || safeValue.changed;
31
- }
32
- return { value: changed ? sanitized : value, changed };
33
- }
34
- return { value, changed: false };
35
- }
36
- function safeToolArgsPayload(payload) {
37
- try {
38
- const sanitized = sanitizeJsonDisplayValue(JSON.parse(payload));
39
- return sanitized.changed ? JSON.stringify(sanitized.value) : safeDisplayText(payload);
40
- }
41
- catch {
42
- return safeDisplayText(payload);
43
- }
44
- }
45
- function objectValue(value) {
46
- return value && typeof value === "object" && !Array.isArray(value)
47
- ? value
48
- : undefined;
49
- }
50
- function stringValue(value) {
51
- return typeof value === "string" && value.trim() ? value : undefined;
52
- }
53
- function numberValue(value) {
54
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
55
- }
56
- function pathWithin(base, candidate) {
57
- const resolvedBase = path.resolve(base);
58
- const resolvedCandidate = path.resolve(candidate);
59
- return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
60
- }
61
- function errorMessage(error) {
62
- return error instanceof Error ? error.message : String(error);
63
- }
64
- function isNotFoundError(error) {
65
- return Boolean(objectValue(error)?.code === "ENOENT");
66
- }
67
- function validateTranscriptPath(filePath, trustedRoots, trustedFiles = [], trustedFileRoot) {
68
- if (trustedRoots.length === 0 && (!trustedFileRoot || trustedFiles.length === 0))
69
- return { warning: `Transcript preview has no trusted root: ${filePath}` };
70
- const resolvedPath = path.resolve(filePath);
71
- const recordedCandidate = trustedFileRoot
72
- && pathWithin(trustedFileRoot, resolvedPath)
73
- && trustedFiles.some((file) => path.resolve(file) === resolvedPath);
74
- if (!trustedRoots.some((root) => pathWithin(root, resolvedPath)) && !recordedCandidate) {
75
- return { warning: `Transcript is outside trusted roots: ${filePath}` };
76
- }
77
- let stat;
78
- try {
79
- stat = fs.lstatSync(resolvedPath);
80
- }
81
- catch (error) {
82
- if (isNotFoundError(error))
83
- return {};
84
- return { warning: `Transcript could not be inspected: ${errorMessage(error)}` };
85
- }
86
- if (stat.isSymbolicLink())
87
- return { warning: `Transcript preview refused a symlink: ${filePath}` };
88
- if (!stat.isFile())
89
- return { warning: `Transcript path is not a file: ${filePath}` };
90
- try {
91
- const realPath = fs.realpathSync(resolvedPath);
92
- const realRoots = trustedRoots
93
- .filter((root) => fs.existsSync(root))
94
- .map((root) => fs.realpathSync(root));
95
- if (!realRoots.some((root) => pathWithin(root, realPath)) && !isTrustedRecordedSessionFile(realPath, trustedFiles, trustedFileRoot)) {
96
- return { warning: `Transcript resolves outside trusted roots: ${filePath}` };
97
- }
98
- return { resolvedPath: realPath };
99
- }
100
- catch (error) {
101
- return { warning: `Transcript path could not be resolved: ${errorMessage(error)}` };
102
- }
103
- }
104
- function isCompleteRecord(line) {
105
- if (!line?.trim())
106
- return false;
107
- try {
108
- return objectValue(JSON.parse(line)) !== undefined;
109
- }
110
- catch {
111
- return false;
112
- }
113
- }
114
- function readTailLines(filePath, maxBytes) {
115
- let fd;
116
- try {
117
- const noFollow = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
118
- fd = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);
119
- const stat = fs.fstatSync(fd);
120
- if (!stat.isFile())
121
- return { lines: [], truncated: false, warning: `Transcript path is not a file: ${filePath}` };
122
- if (stat.size === 0)
123
- return { lines: [], truncated: false };
124
- const bytesToRead = Math.min(stat.size, maxBytes);
125
- const start = stat.size - bytesToRead;
126
- const buffer = Buffer.alloc(bytesToRead);
127
- const bytesRead = fs.readSync(fd, buffer, 0, bytesToRead, start);
128
- const content = buffer.subarray(0, bytesRead).toString("utf-8");
129
- const endsWithNewline = content.endsWith("\n");
130
- let lines = content.split(/\r?\n/);
131
- if (start > 0 && lines.length > 0)
132
- lines = lines.slice(1);
133
- if (lines.at(-1) === "")
134
- lines = lines.slice(0, -1);
135
- else if (!endsWithNewline && !isCompleteRecord(lines.at(-1)))
136
- lines = lines.slice(0, -1);
137
- return { lines, truncated: start > 0 };
138
- }
139
- catch (error) {
140
- return { lines: [], truncated: false, warning: `Transcript could not be read: ${errorMessage(error)}` };
141
- }
142
- finally {
143
- if (fd !== undefined)
144
- fs.closeSync(fd);
145
- }
146
- }
147
- function clipMessage(text) {
148
- if (text.length <= MAX_MESSAGE_CHARS)
149
- return text;
150
- return `${text.slice(0, MAX_MESSAGE_CHARS)}\n\n… message truncated`;
151
- }
152
- function safeTranscriptEvent(event) {
153
- if (event.kind === "assistant") {
154
- return {
155
- ...event,
156
- text: safeDisplayText(event.text),
157
- ...(event.model ? { model: safeDisplayText(event.model) } : {}),
158
- };
159
- }
160
- if (event.kind === "user" || event.kind === "notice") {
161
- return { ...event, text: safeDisplayText(event.text) };
162
- }
163
- return {
164
- ...event,
165
- name: safeDisplayText(event.name),
166
- ...(event.args !== undefined ? { args: safeDisplayText(event.args) } : {}),
167
- ...(event.argsPayload !== undefined ? { argsPayload: safeToolArgsPayload(event.argsPayload) } : {}),
168
- ...(event.output !== undefined ? { output: safeDisplayText(event.output) } : {}),
169
- ...(event.error !== undefined ? { error: safeDisplayText(event.error) } : {}),
170
- };
171
- }
172
- function findTool(events, toolCallId, name) {
173
- if (toolCallId) {
174
- for (let index = events.length - 1; index >= 0; index--) {
175
- const event = events[index];
176
- if (event?.kind === "tool" && event.toolCallId === toolCallId)
177
- return event;
178
- }
179
- return undefined;
180
- }
181
- for (let index = events.length - 1; index >= 0; index--) {
182
- const event = events[index];
183
- if (event?.kind !== "tool")
184
- continue;
185
- const tool = event;
186
- if ((!name || tool.name === name) && !tool.resultSeen)
187
- return tool;
188
- }
189
- return undefined;
190
- }
191
- function appendTextEvent(events, kind, text, metadata) {
192
- const clipped = clipMessage(text.trim());
193
- if (!clipped)
194
- return;
195
- const previous = events.at(-1);
196
- if (previous?.kind === kind && previous.text === clipped)
197
- return;
198
- events.push({ kind, text: clipped, ...metadata });
199
- }
200
- function parseTranscriptLines(lines, conversationStarted = false) {
201
- const events = [];
202
- let malformed = 0;
203
- let explicitTruncation = false;
204
- let assistantSeen = conversationStarted;
205
- for (const line of lines) {
206
- if (!line.trim())
207
- continue;
208
- let record;
209
- try {
210
- record = objectValue(JSON.parse(line));
211
- }
212
- catch {
213
- malformed++;
214
- continue;
215
- }
216
- if (!record) {
217
- malformed++;
218
- continue;
219
- }
220
- const recordType = stringValue(record.recordType);
221
- const timestamp = numberValue(record.ts);
222
- if (recordType === "truncated") {
223
- explicitTruncation = true;
224
- continue;
225
- }
226
- if (recordType === "tool_start") {
227
- const name = stringValue(record.toolName) ?? "tool";
228
- events.push({
229
- kind: "tool",
230
- ...(stringValue(record.toolCallId) ? { toolCallId: stringValue(record.toolCallId) } : {}),
231
- name,
232
- ...(stringValue(record.argsPreview) ? { args: stringValue(record.argsPreview) } : {}),
233
- ...(stringValue(record.argsPayload) ? { argsPayload: stringValue(record.argsPayload) } : {}),
234
- status: "running",
235
- ...(timestamp !== undefined ? { timestamp, startedAt: timestamp } : {}),
236
- });
237
- continue;
238
- }
239
- if (recordType === "tool_end") {
240
- const tool = findTool(events, stringValue(record.toolCallId), stringValue(record.toolName));
241
- if (tool && !tool.resultSeen)
242
- tool.status = record.isError === true ? "error" : "complete";
243
- if (tool && timestamp !== undefined && tool.endedAt === undefined)
244
- tool.endedAt = timestamp;
245
- continue;
246
- }
247
- if (recordType === "stderr") {
248
- const text = stringValue(record.text);
249
- if (text)
250
- events.push({ kind: "notice", text: clipMessage(text), tone: "error", ...(timestamp !== undefined ? { timestamp } : {}) });
251
- continue;
252
- }
253
- if (recordType !== "message")
254
- continue;
255
- const message = objectValue(record.message);
256
- const role = stringValue(record.role) ?? stringValue(message?.role);
257
- const text = stringValue(record.text) ?? stringValue(message?.text) ?? stringValue(message?.content);
258
- if (role === "toolResult" || role === "tool_result") {
259
- const toolCallId = stringValue(record.toolCallId) ?? stringValue(message?.toolCallId);
260
- const name = stringValue(record.toolName) ?? stringValue(message?.toolName) ?? "tool";
261
- const failed = record.isError === true || message?.isError === true;
262
- let tool = findTool(events, toolCallId, name);
263
- if (!tool) {
264
- tool = {
265
- kind: "tool",
266
- ...(toolCallId ? { toolCallId } : {}),
267
- name,
268
- status: failed ? "error" : "complete",
269
- ...(timestamp !== undefined ? { timestamp } : {}),
270
- };
271
- events.push(tool);
272
- }
273
- if (!tool.resultSeen) {
274
- tool.resultSeen = true;
275
- tool.status = failed ? "error" : "complete";
276
- if (timestamp !== undefined && tool.endedAt === undefined)
277
- tool.endedAt = timestamp;
278
- if (text && (!failed || tool.output === undefined)) {
279
- tool.output = clipMessage(text);
280
- tool.outputTruncated = record.outputTruncated === true || text.includes("… payload truncated") || text.includes("[Showing lines");
281
- }
282
- if (failed && text)
283
- tool.error = clipMessage(text.split(/\r?\n/).find((candidate) => candidate.trim()) ?? text);
284
- }
285
- continue;
286
- }
287
- if (role === "assistant") {
288
- assistantSeen = true;
289
- // The transcript writer records the assistant message's provider-local id, which can itself contain a slash.
290
- const rawModel = stringValue(record.model) ?? stringValue(message?.model);
291
- const provider = stringValue(message?.provider);
292
- const model = rawModel && provider ? `${provider}/${rawModel}` : rawModel;
293
- if (text)
294
- appendTextEvent(events, "assistant", text, {
295
- ...(model ? { model } : {}),
296
- ...(timestamp !== undefined ? { timestamp } : {}),
297
- });
298
- continue;
299
- }
300
- if (role === "user" && assistantSeen && text) {
301
- appendTextEvent(events, "user", text, timestamp !== undefined ? { timestamp } : {});
302
- }
303
- }
304
- for (const event of events) {
305
- if (event.kind === "tool")
306
- delete event.resultSeen;
307
- }
308
- return { events: events.map(safeTranscriptEvent), malformed, explicitTruncation };
309
- }
310
- export function readFleetTranscript(filePath, options) {
311
- const validated = validateTranscriptPath(filePath, options.trustedRoots, options.trustedFiles, options.trustedFileRoot);
312
- if (!validated.resolvedPath) {
313
- return { path: filePath, events: [], truncated: false, readFailed: true, ...(validated.warning ? { warning: safeDisplayText(validated.warning) } : {}) };
314
- }
315
- const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
316
- const tail = readTailLines(validated.resolvedPath, Math.max(1024, options.maxBytes ?? DEFAULT_MAX_BYTES));
317
- const recordsOmitted = tail.truncated || tail.lines.length > maxRecords;
318
- const selectedLines = tail.lines.slice(-maxRecords);
319
- const parsed = parseTranscriptLines(selectedLines, recordsOmitted);
320
- const warnings = [
321
- tail.warning,
322
- parsed.malformed > 0 ? `Skipped ${parsed.malformed} malformed transcript record${parsed.malformed === 1 ? "" : "s"}.` : undefined,
323
- ].filter((value) => Boolean(value));
324
- return {
325
- path: filePath,
326
- events: parsed.events,
327
- truncated: tail.truncated || tail.lines.length > maxRecords || parsed.explicitTruncation,
328
- ...(tail.warning ? { readFailed: true } : {}),
329
- ...(warnings.length ? { warning: safeDisplayText(warnings.join(" ")) } : {}),
330
- };
331
- }
332
6
  function statusGlyph(event, theme) {
333
7
  if (event.status === "running")
334
8
  return theme.fg("warning", "●");
package/src/tui/fleet.js CHANGED
@@ -17,9 +17,11 @@ import { stopAsyncRun } from "../runs/foreground/async-stop-action.js";
17
17
  import { resolveWorkflowForegroundSteeringTarget, steerWorkflowForegroundTarget } from "../runs/foreground/workflow-foreground-steering.js";
18
18
  import { contextModeBadge, contextModeLabel } from "../runs/shared/context-mode.js";
19
19
  import { foregroundChildStateLabel } from "../runs/foreground/foreground-history.js";
20
- import { FLEET_STATUS_WIDGET_KEY, reportFleetWarning } from "./fleet-status.js";
20
+ import { FLEET_STATUS_WIDGET_KEY } from "./fleet-status.js";
21
+ import { reportSessionWarning } from "../shared/session-warnings.js";
21
22
  import { stepTaskSummary } from "./render.js";
22
- import { readFleetTranscript, renderFleetTranscript } from "./fleet-transcript.js";
23
+ import { renderFleetTranscript } from "./fleet-transcript.js";
24
+ import { readFleetTranscript } from "../shared/fleet-transcript-reader.js";
23
25
  import { runningTone } from "./running-tone.js";
24
26
  import { childThinkingLevel } from "../shared/model-info.js";
25
27
  import { handleInspectorAction } from "../inspectors/actions.js";
@@ -222,7 +224,7 @@ export function collectFleetSnapshot(state, options = {}) {
222
224
  entryLimit: MAX_FLEET_HISTORY_CANDIDATES,
223
225
  resultsDir: options.resultsDir ?? DIRS.results,
224
226
  reconcile: false,
225
- onCorruptStatus: (warning) => reportFleetWarning(state, warning),
227
+ onCorruptStatus: (warning) => reportSessionWarning(state, warning),
226
228
  }).filter((run) => !trackedIds.has(run.id));
227
229
  runs = [...trackedRuns, ...history];
228
230
  }
@@ -238,7 +240,7 @@ export function collectFleetSnapshot(state, options = {}) {
238
240
  }
239
241
  if (state.currentSessionId) {
240
242
  try {
241
- for (const run of snapshotExternalRuns(state.currentSessionId, { ignoreMalformed: true, onMalformedRecord: (message) => reportFleetWarning(state, `Removed ${message}`) })) {
243
+ for (const run of snapshotExternalRuns(state.currentSessionId, { ignoreMalformed: true, onMalformedRecord: (message) => reportSessionWarning(state, `Removed ${message}`) })) {
242
244
  items.push({
243
245
  key: `external:${run.id}`,
244
246
  kind: "external",
@@ -1,6 +1,3 @@
1
- /**
2
- * Rendering functions for subagent results
3
- */
4
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
2
  import { type ExtensionContext } from "@earendil-works/pi-coding-agent";
6
3
  import { type Component } from "@earendil-works/pi-tui";
@@ -50,16 +47,10 @@ export declare function inlineWorkflowRenderKey(job: AsyncJobState, children: As
50
47
  /** Presentation-only coverage from the mounted inline Fleet roster, never configuration. */
51
48
  export declare function setInlineWorkflowCoverage(ui: ExtensionContext["ui"], coverage: ReadonlyMap<string, string>): void;
52
49
  export declare function buildWidgetLines(jobs: AsyncJobState[], theme: Theme, width?: number, expanded?: boolean, frame?: number): string[];
53
- /**
54
- * Render the async jobs widget
55
- */
56
50
  export declare function renderWidget(ctx: ExtensionContext, jobs: AsyncJobState[], initiallyCollapsed?: boolean, layout?: AsyncWidgetLayout): void;
57
51
  export declare function renderSubagentSummary(result: AgentToolResult<Details>, options: {
58
52
  isPartial?: boolean;
59
53
  }, theme: Theme): Component;
60
- /**
61
- * Render a subagent result
62
- */
63
54
  export declare function renderSubagentResult(result: AgentToolResult<Details>, options: {
64
55
  expanded: boolean;
65
56
  }, theme: Theme, frame?: number, rendererConfig?: MainWindowRendererConfig, foregroundDetachShortcut?: string): Component;
package/src/tui/render.js CHANGED
@@ -1,6 +1,3 @@
1
- /**
2
- * Rendering functions for subagent results
3
- */
4
1
  import * as path from "node:path";
5
2
  import { createHash } from "node:crypto";
6
3
  import { getMarkdownTheme, keyText } from "@earendil-works/pi-coding-agent";
@@ -729,6 +726,31 @@ function visibleWorkflowRows(rows) {
729
726
  hiddenRows: rows.length - selected.size,
730
727
  };
731
728
  }
729
+ /**
730
+ * Lines for at most `cap` rows: every unfinished row plus the newest finished ones, in order, with the
731
+ * older finished rows folded into one line, because live widgets list rows oldest first. When unfinished
732
+ * rows alone fill `cap`, only they are returned, possibly more than `cap`.
733
+ */
734
+ function foldEarlierDoneLines(rows, cap, line, foldLine) {
735
+ if (rows.length <= cap)
736
+ return rows.map(line);
737
+ const unfinished = rows.filter((row) => row.state !== "complete");
738
+ if (unfinished.length >= cap)
739
+ return unfinished.map(line);
740
+ // rows.length > cap, so at least two rows fold into the one line.
741
+ const hidden = rows.length - cap + 1;
742
+ const lines = [];
743
+ let skipped = 0;
744
+ for (const row of rows) {
745
+ if (skipped < hidden && row.state === "complete") {
746
+ if (++skipped === hidden)
747
+ lines.push(foldLine(hidden));
748
+ continue;
749
+ }
750
+ lines.push(line(row));
751
+ }
752
+ return lines;
753
+ }
732
754
  function snapshotNowForProgress(progress) {
733
755
  if (progress.currentToolStartedAt !== undefined && progress.durationMs !== undefined)
734
756
  return progress.currentToolStartedAt + progress.durationMs;
@@ -1258,6 +1280,7 @@ function workflowChecklistItemLine(item, theme, indent, frame, includeError) {
1258
1280
  return `${indent}${workflowChecklistGlyph(item, theme, frame)} ${theme.bold(identity || item.key)}${context}${state}${details ? ` ${theme.fg("dim", `· ${details}`)}` : ""}`;
1259
1281
  }
1260
1282
  const COLLAPSED_WORKFLOW_PHASE_LIMIT = 4;
1283
+ const EXPANDED_WIDGET_DONE_ITEMS = 4;
1261
1284
  function workflowChecklistWidgetLines(checklist, theme, indent, expanded, frame, options = {}) {
1262
1285
  if (!checklist?.total)
1263
1286
  return [];
@@ -1266,6 +1289,12 @@ function workflowChecklistWidgetLines(checklist, theme, indent, expanded, frame,
1266
1289
  const includeBottleneckOutput = options.includeBottleneckOutput ?? expanded;
1267
1290
  const includeItemErrors = options.includeItemErrors ?? true;
1268
1291
  const lines = includeSummary ? [`${indent}${theme.fg("dim", `Checklist ${formatWorkflowChecklistSummary(checklist)}`)}`] : [];
1292
+ const bottleneck = formatWorkflowChecklistBottleneck(checklist.bottleneck, { includeOutput: includeBottleneckOutput, includeError: !expanded });
1293
+ const tone = checklist.bottleneck?.state === "blocked" || checklist.bottleneck?.state === "failed" ? "error" : checklist.bottleneck?.state === "running" ? "accent" : "warning";
1294
+ const bottleneckLine = bottleneck ? `${indent}${theme.fg(tone, `bottleneck · ${bottleneck}`)}` : undefined;
1295
+ const liveExpanded = expanded && options.liveWidget === true;
1296
+ if (liveExpanded && bottleneckLine)
1297
+ lines.push(bottleneckLine);
1269
1298
  const phases = !limitPhases || checklist.phases.length <= COLLAPSED_WORKFLOW_PHASE_LIMIT
1270
1299
  ? checklist.phases
1271
1300
  : checklist.phases
@@ -1287,16 +1316,14 @@ function workflowChecklistWidgetLines(checklist, theme, indent, expanded, frame,
1287
1316
  }, theme, frame);
1288
1317
  lines.push(`${indent}${glyph} ${theme.bold(formatWorkflowChecklistPhase(phase))}`);
1289
1318
  if (expanded) {
1290
- for (const item of [...phase.items].sort((left, right) => workflowChecklistItemPriority(left.state) - workflowChecklistItemPriority(right.state))) {
1291
- lines.push(workflowChecklistItemLine(item, theme, `${indent} `, frame, includeItemErrors || item.kind === "host"));
1292
- }
1319
+ const items = [...phase.items].sort((left, right) => workflowChecklistItemPriority(left.state) - workflowChecklistItemPriority(right.state));
1320
+ const line = (item) => workflowChecklistItemLine(item, theme, `${indent} `, frame, includeItemErrors || item.kind === "host");
1321
+ const cap = liveExpanded ? items.filter((item) => item.state !== "complete").length + EXPANDED_WIDGET_DONE_ITEMS + 1 : items.length;
1322
+ lines.push(...foldEarlierDoneLines(items, cap, line, (hidden) => `${indent} ${theme.fg("dim", `… ${hidden} earlier done`)}`));
1293
1323
  }
1294
1324
  }
1295
- const bottleneck = formatWorkflowChecklistBottleneck(checklist.bottleneck, { includeOutput: includeBottleneckOutput, includeError: !expanded });
1296
- if (bottleneck) {
1297
- const tone = checklist.bottleneck?.state === "blocked" || checklist.bottleneck?.state === "failed" ? "error" : checklist.bottleneck?.state === "running" ? "accent" : "warning";
1298
- lines.push(`${indent}${theme.fg(tone, `bottleneck · ${bottleneck}`)}`);
1299
- }
1325
+ if (!liveExpanded && bottleneckLine)
1326
+ lines.push(bottleneckLine);
1300
1327
  return lines;
1301
1328
  }
1302
1329
  function compactWorkflowLaneState(items) {
@@ -1473,24 +1500,25 @@ function compactWorkflowHeaderLine(job, theme, width) {
1473
1500
  return full;
1474
1501
  return `${theme.fg("toolTitle", themeBold(theme, `async workflow ${label}`))} ${theme.fg("dim", "· background")}`;
1475
1502
  }
1476
- function compactWorkflowWidgetBodyLines(job, theme, frame, projection) {
1503
+ /** `lineBudget` is the room left for these lines; older done lanes fold so the newest and active ones fit. */
1504
+ function compactWorkflowWidgetBodyLines(job, theme, frame, projection, lineBudget) {
1477
1505
  const rows = compactWorkflowLaneRows(job, projection.checklist);
1478
1506
  const lines = [` ${compactWorkflowStats(job, rows, theme, projection)}`];
1479
1507
  if (projection.inlineFleetCovered)
1480
1508
  return [...lines, ` ${theme.fg("dim", "Workflow children shown in Fleet roster")}`];
1509
+ const bottleneck = compactWorkflowBottleneck(rows, job);
1510
+ const hint = job.status === "running" || rows.some((row) => row.state === "running");
1481
1511
  if (rows.length) {
1482
- for (const row of rows) {
1483
- if (!projection.materializedKeys?.has(row.key))
1484
- lines.push(compactWorkflowLaneLine(row, theme, " ", frame));
1485
- }
1512
+ const shown = rows.filter((row) => !projection.materializedKeys?.has(row.key));
1513
+ const cap = lineBudget === undefined ? shown.length : Math.max(1, lineBudget - lines.length - Number(Boolean(bottleneck)) - Number(hint));
1514
+ lines.push(...foldEarlierDoneLines(shown, cap, (row) => compactWorkflowLaneLine(row, theme, " ", frame), (hidden) => ` ${theme.fg("dim", `… ${hidden} earlier done`)}`));
1486
1515
  }
1487
1516
  else {
1488
1517
  lines.push(` ${theme.fg("dim", "◦ waiting for workflow lanes")}`);
1489
1518
  }
1490
- const bottleneck = compactWorkflowBottleneck(rows, job);
1491
1519
  if (bottleneck)
1492
1520
  lines.push(` ${theme.fg(bottleneck.tone, `bottleneck · ${bottleneck.text}`)}`);
1493
- if (job.status === "running" || rows.some((row) => row.state === "running"))
1521
+ if (hint)
1494
1522
  lines.push(` ${theme.fg("accent", workflowDetailHintText())}`);
1495
1523
  return lines;
1496
1524
  }
@@ -2296,7 +2324,7 @@ function foregroundStyleWidgetDetails(job, theme, expanded, width, frame, projec
2296
2324
  const lane = projectAsyncLane(job, laneStepForJob(job, steps));
2297
2325
  return [
2298
2326
  ...(expanded ? workflowPreflightLines(job) : []),
2299
- ...workflowChecklistWidgetLines(checklist, theme, " ", expanded, frame),
2327
+ ...workflowChecklistWidgetLines(checklist, theme, " ", expanded, frame, { liveWidget: true }),
2300
2328
  ...(lane ? formatLaneProjectionLines(lane, theme, " ") : []),
2301
2329
  ...hostStepWidgetLines(job, theme, " "),
2302
2330
  ` ${theme.fg("dim", `⎿ ${widgetActivity(job)}`)}`,
@@ -2307,7 +2335,7 @@ function foregroundStyleWidgetDetails(job, theme, expanded, width, frame, projec
2307
2335
  return widgetChainDetails(job, theme, expanded, width, frame);
2308
2336
  const lines = [
2309
2337
  ...(expanded ? workflowPreflightLines(job) : []),
2310
- ...workflowChecklistWidgetLines(checklist, theme, " ", expanded, frame, { includeItemErrors: !expanded }),
2338
+ ...workflowChecklistWidgetLines(checklist, theme, " ", expanded, frame, { includeItemErrors: !expanded, liveWidget: true }),
2311
2339
  ];
2312
2340
  const group = activeParallelWidgetGroup(job);
2313
2341
  if (group) {
@@ -2339,9 +2367,10 @@ function foregroundStyleWidgetDetails(job, theme, expanded, width, frame, projec
2339
2367
  }
2340
2368
  return lines;
2341
2369
  }
2342
- function buildSingleWidgetLines(job, theme, width, expanded, frame, projection = buildWorkflowWidgetProjection(job)) {
2370
+ /** `reservedLines` are lines the caller renders after these, such as materialized workflow children. */
2371
+ function buildSingleWidgetLines(job, theme, width, expanded, frame, projection = buildWorkflowWidgetProjection(job), reservedLines = 0) {
2343
2372
  if ((!expanded || projection.inlineFleetCovered) && job.mode === "workflow")
2344
- return [compactWorkflowHeaderLine(job, theme, width), ...compactWorkflowWidgetBodyLines(job, theme, frame, projection)].map((line) => truncLine(line, width));
2373
+ return [compactWorkflowHeaderLine(job, theme, width), ...compactWorkflowWidgetBodyLines(job, theme, frame, projection, widgetLineBudget(expanded) - 1 - reservedLines)].map((line) => truncLine(line, width));
2345
2374
  const stats = widgetStats(job, theme, projection, !expanded);
2346
2375
  const count = job.mode === "workflow"
2347
2376
  ? projection.checklist?.total ?? projection.stageProgress?.total ?? job.stepsTotal ?? job.agents?.length ?? job.steps?.length
@@ -2632,10 +2661,9 @@ function buildProgressiveWidgetLines(jobs, theme, width, lockedRows, previousKey
2632
2661
  lines.push(progressiveJobLine(job, theme, width, frame, projection, laneRows));
2633
2662
  if (!laneRows || projection.inlineFleetCovered)
2634
2663
  continue;
2635
- const shownLanes = laneRows.slice(0, Math.max(0, spareRows));
2636
- for (const row of shownLanes)
2637
- lines.push(truncLine(compactWorkflowLaneLine(row, theme, " ", frame), width));
2638
- spareRows -= shownLanes.length;
2664
+ const laneLines = foldEarlierDoneLines(laneRows, spareRows, (row) => truncLine(compactWorkflowLaneLine(row, theme, " ", frame), width), (hidden) => truncLine(` ${theme.fg("dim", `… ${hidden} earlier done`)}`, width)).slice(0, spareRows);
2665
+ lines.push(...laneLines);
2666
+ spareRows -= laneLines.length;
2639
2667
  }
2640
2668
  if (hiddenJobs.length > 0 && lines.length < rowCount)
2641
2669
  lines.push(progressiveHiddenLine(hiddenJobs, theme, width));
@@ -2653,11 +2681,12 @@ function paddedWidgetLine(line, width) {
2653
2681
  const text = ` ${truncLine(line, width - 2)} `;
2654
2682
  return `${text}${" ".repeat(Math.max(0, width - visibleWidth(text)))}`;
2655
2683
  }
2684
+ function widgetLineBudget(expanded) {
2685
+ const rows = currentTerminalRows();
2686
+ return expanded ? Math.max(12, Math.min(24, Math.floor(rows * 0.55))) : collapsedWidgetLineBudget(rows);
2687
+ }
2656
2688
  function fitWidgetLineBudget(lines, theme, width, expanded) {
2657
- const rows = process.stdout.rows || 30;
2658
- const budget = expanded
2659
- ? Math.max(12, Math.min(24, Math.floor(rows * 0.55)))
2660
- : collapsedWidgetLineBudget(rows);
2689
+ const budget = widgetLineBudget(expanded);
2661
2690
  if (lines.length <= budget)
2662
2691
  return lines;
2663
2692
  const visibleLines = Math.max(1, budget - 1);
@@ -2908,11 +2937,10 @@ function buildWidgetComponent(jobs, ui, initiallyCollapsed = false, layout) {
2908
2937
  function buildWidgetLinesWithProjection(jobs, theme, width = getTermWidth(), expanded = false, frame, projectionFor = workflowWidgetProjectionLookup()) {
2909
2938
  if (jobs.length === 0)
2910
2939
  return [];
2911
- if (jobs.length === 1)
2912
- return [
2913
- ...buildSingleWidgetLines(jobs[0], theme, width, expanded, frame, projectionFor(jobs[0])),
2914
- ...materializedWidgetChildLines(jobs[0], theme, width, expanded, frame, projectionFor).map((line) => truncLine(line, width)),
2915
- ];
2940
+ if (jobs.length === 1) {
2941
+ const childLines = materializedWidgetChildLines(jobs[0], theme, width, expanded, frame, projectionFor).map((line) => truncLine(line, width));
2942
+ return [...buildSingleWidgetLines(jobs[0], theme, width, expanded, frame, projectionFor(jobs[0]), childLines.length), ...childLines];
2943
+ }
2916
2944
  const running = jobs.filter((job) => job.status === "running");
2917
2945
  const queued = jobs.filter((job) => job.status === "queued");
2918
2946
  const finished = jobs.filter((job) => job.status !== "running" && job.status !== "queued");
@@ -2926,27 +2954,29 @@ function buildWidgetLinesWithProjection(jobs, theme, width = getTermWidth(), exp
2926
2954
  let hiddenFinished = 0;
2927
2955
  let queuedSummaryShown = false;
2928
2956
  let slots = MAX_WIDGET_JOBS;
2957
+ const compactCards = [];
2929
2958
  const appendJob = (job) => {
2930
2959
  const projection = projectionFor(job);
2931
2960
  const compactWorkflow = (!expanded || projection.inlineFleetCovered) && job.mode === "workflow";
2932
2961
  const stats = compactWorkflow ? "" : widgetStats(job, theme, projection, !expanded);
2933
2962
  const details = compactWorkflow
2934
- ? [
2935
- ...compactWorkflowWidgetBodyLines(job, theme, frame, projection),
2936
- ]
2963
+ ? compactWorkflowWidgetBodyLines(job, theme, frame, projection)
2937
2964
  : [
2938
2965
  ` ${theme.fg("dim", `⎿ ${widgetActivity(job)}`)}`,
2939
2966
  ...widgetLaneDetailLines(job, theme, projection),
2940
- ...workflowChecklistWidgetLines(widgetChecklistWithoutMaterializedChildren(projection), theme, " ", expanded, frame, { includeItemErrors: !expanded || !job.steps?.length }),
2967
+ ...workflowChecklistWidgetLines(widgetChecklistWithoutMaterializedChildren(projection), theme, " ", expanded, frame, { includeItemErrors: !expanded || !job.steps?.length, liveWidget: true }),
2941
2968
  ...widgetParallelAgentDetails(job, theme, expanded, width, frame),
2942
2969
  ];
2943
- items.push([
2970
+ const item = [
2944
2971
  compactWorkflow
2945
2972
  ? compactWorkflowHeaderLine(job, theme, width)
2946
2973
  : `${widgetStatusGlyph(job, theme, frame)} ${themeBold(theme, widgetJobName(job))}${contextModeBadge(theme, job.context)}${stats ? ` ${theme.fg("dim", "·")} ${stats}` : ""}`,
2947
2974
  ...details,
2948
2975
  ...materializedWidgetChildLines(job, theme, width, expanded, frame, projectionFor),
2949
- ]);
2976
+ ];
2977
+ items.push(item);
2978
+ if (compactWorkflow)
2979
+ compactCards.push({ item, job, projection, bodyLength: details.length });
2950
2980
  };
2951
2981
  for (const job of running) {
2952
2982
  if (slots <= 0) {
@@ -2981,6 +3011,16 @@ function buildWidgetLinesWithProjection(jobs, theme, width = getTermWidth(), exp
2981
3011
  parts.push(`${hiddenFinished} finished`);
2982
3012
  items.push([theme.fg("dim", `+${hiddenTotal} more (${parts.join(", ")})`)]);
2983
3013
  }
3014
+ // Fold the oldest done lanes of compact workflow cards by the overflow, so later cards and
3015
+ // materialized children stay inside the line budget.
3016
+ let overflow = 1 + items.reduce((sum, item) => sum + item.length, 0) - widgetLineBudget(expanded);
3017
+ for (const card of compactCards) {
3018
+ if (overflow <= 0)
3019
+ break;
3020
+ const body = compactWorkflowWidgetBodyLines(card.job, theme, frame, card.projection, card.bodyLength - overflow);
3021
+ card.item.splice(1, card.bodyLength, ...body);
3022
+ overflow -= card.bodyLength - body.length;
3023
+ }
2984
3024
  for (let i = 0; i < items.length; i++) {
2985
3025
  const item = items[i];
2986
3026
  const last = i === items.length - 1;
@@ -2997,9 +3037,6 @@ export function buildWidgetLines(jobs, theme, width = getTermWidth(), expanded =
2997
3037
  const { roots, projectionFor } = widgetJobTree(jobs, Date.now());
2998
3038
  return buildWidgetLinesWithProjection(roots, theme, width, expanded, frame, projectionFor);
2999
3039
  }
3000
- /**
3001
- * Render the async jobs widget
3002
- */
3003
3040
  export function renderWidget(ctx, jobs, initiallyCollapsed = false, layout = "adaptive") {
3004
3041
  // Advance round tracking on every widget update, including the empty-jobs
3005
3042
  // cleanup path below, which never reaches container.render.
@@ -3382,9 +3419,6 @@ export function renderSubagentSummary(result, options, theme) {
3382
3419
  : details?.mode || "subagent";
3383
3420
  return new Text(truncLine(`${glyph} ${theme.fg("toolTitle", theme.bold(label))} ${theme.fg("dim", "·")} ${theme.fg(state === "failed" ? "error" : state === "completed" ? "success" : state === "running" ? "accent" : "warning", state)}`, getTermWidth() - 4), 0, 0);
3384
3421
  }
3385
- /**
3386
- * Render a subagent result
3387
- */
3388
3422
  export function renderSubagentResult(result, options, theme, frame, rendererConfig, foregroundDetachShortcut) {
3389
3423
  const layout = resolveMainWindowRenderLayout(rendererConfig);
3390
3424
  const compact = (component) => capCompactMainWindowResult(component, layout, theme, !options.expanded);