pi-subagents 0.83.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 (206) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-5YIITCPD.js → chunk-3UZ5FVVJ.js} +322 -110
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-YXFJVCOL.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-AHIFYGR3.js → chunk-DV2NCNPR.js} +22 -11
  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-MABL3FUM.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-UFL7IYCW.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-NPIYWVOD.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-C7JMPU5F.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-UUP372DR.js → chunk-JWYG26RE.js} +223 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-VLFZIN6D.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-ZVOAMTUQ.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-RNIZLSEA.js → chunk-LGMILZNE.js} +323 -18
  21. package/bundle/{chunk-UYK5MZWE.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-IPGZMQXV.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-QP5ZWNIS.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-F5DBXJ2G.js → chunk-WOVMHDES.js} +234 -182
  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 +1 -1
  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 +8 -9
  78. package/src/runs/background/async-execution.js +77 -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.d.ts +1 -0
  83. package/src/runs/background/async-retention.js +22 -11
  84. package/src/runs/background/auto-drain.js +2 -1
  85. package/src/runs/background/boot-id.d.ts +1 -3
  86. package/src/runs/background/boot-id.js +1 -3
  87. package/src/runs/background/completion-batcher.d.ts +3 -4
  88. package/src/runs/background/completion-batcher.js +2 -3
  89. package/src/runs/background/control-channel.d.ts +0 -6
  90. package/src/runs/background/control-channel.js +0 -6
  91. package/src/runs/background/fleet-view.js +2 -3
  92. package/src/runs/background/notify.d.ts +0 -2
  93. package/src/runs/background/notify.js +0 -2
  94. package/src/runs/background/result-watcher.d.ts +1 -0
  95. package/src/runs/background/result-watcher.js +59 -29
  96. package/src/runs/background/resume-guidance.js +4 -2
  97. package/src/runs/background/retained-children.js +2 -1
  98. package/src/runs/background/run-child-session.d.ts +2 -1
  99. package/src/runs/background/run-child-session.js +10 -2
  100. package/src/runs/background/run-status.js +4 -3
  101. package/src/runs/background/scheduled-runs.d.ts +3 -1
  102. package/src/runs/background/scheduled-runs.js +13 -16
  103. package/src/runs/background/subagent-runner.d.ts +2 -4
  104. package/src/runs/background/subagent-runner.js +10 -6
  105. package/src/runs/background/subagent-wait.js +12 -15
  106. package/src/runs/background/wait-config.d.ts +2 -0
  107. package/src/runs/background/wait-config.js +17 -3
  108. package/src/runs/background/wait-tool.js +4 -2
  109. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  110. package/src/runs/background/workflow-terminal-proof.js +0 -1
  111. package/src/runs/foreground/execution.d.ts +0 -3
  112. package/src/runs/foreground/execution.js +17 -9
  113. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  114. package/src/runs/foreground/subagent-executor.js +112 -26
  115. package/src/runs/shared/child-commands.js +15 -2
  116. package/src/runs/shared/child-hooks.d.ts +1 -7
  117. package/src/runs/shared/child-hooks.js +13 -5
  118. package/src/runs/shared/child-launch.js +6 -2
  119. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  120. package/src/runs/shared/child-session.d.ts +3 -1
  121. package/src/runs/shared/child-session.js +22 -2
  122. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  123. package/src/runs/shared/child-tool-plan.js +0 -1
  124. package/src/runs/shared/claude-code-adapter.js +11 -0
  125. package/src/runs/shared/external-cli-runner.js +26 -6
  126. package/src/runs/shared/herdr-connection.js +2 -1
  127. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  128. package/src/runs/shared/herdr-pane-host.js +17 -1
  129. package/src/runs/shared/herdr-placed-run.js +48 -22
  130. package/src/runs/shared/lane-metadata.d.ts +0 -1
  131. package/src/runs/shared/lane-metadata.js +0 -1
  132. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  133. package/src/runs/shared/model-resolution-diagnostic.d.ts +11 -1
  134. package/src/runs/shared/model-resolution-diagnostic.js +25 -0
  135. package/src/runs/shared/model-resolution.d.ts +2 -2
  136. package/src/runs/shared/model-resolution.js +7 -1
  137. package/src/runs/shared/model-scope.d.ts +1 -5
  138. package/src/runs/shared/model-scope.js +1 -5
  139. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  140. package/src/runs/shared/mutation-evidence.js +52 -7
  141. package/src/runs/shared/nested-events.d.ts +1 -0
  142. package/src/runs/shared/nested-events.js +1 -1
  143. package/src/runs/shared/parallel-utils.d.ts +2 -1
  144. package/src/runs/shared/permissions.js +5 -3
  145. package/src/runs/shared/placement-host.d.ts +5 -1
  146. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  147. package/src/runs/shared/rex-pane-host.js +0 -2
  148. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  149. package/src/runs/shared/run-launch-folder.js +21 -0
  150. package/src/runs/shared/runner-launcher.d.ts +12 -1
  151. package/src/runs/shared/runner-launcher.js +16 -0
  152. package/src/runs/shared/single-output.d.ts +3 -3
  153. package/src/runs/shared/single-output.js +5 -3
  154. package/src/runs/shared/structured-output.d.ts +8 -0
  155. package/src/runs/shared/structured-output.js +30 -2
  156. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  157. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  158. package/src/runs/shared/tool-timeout.js +2 -1
  159. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  160. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  161. package/src/runs/shared/worktree.d.ts +3 -0
  162. package/src/runs/shared/worktree.js +20 -0
  163. package/src/shared/capacity-resilient-json.d.ts +1 -1
  164. package/src/shared/child-cache-retention.d.ts +1 -2
  165. package/src/shared/child-cache-retention.js +1 -2
  166. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  167. package/src/shared/fleet-transcript-reader.js +333 -0
  168. package/src/shared/formatters.d.ts +0 -18
  169. package/src/shared/formatters.js +0 -18
  170. package/src/shared/session-succession.d.ts +16 -1
  171. package/src/shared/session-succession.js +41 -2
  172. package/src/shared/session-warnings.d.ts +7 -0
  173. package/src/shared/session-warnings.js +26 -0
  174. package/src/shared/settings.d.ts +0 -23
  175. package/src/shared/settings.js +3 -35
  176. package/src/shared/types.d.ts +28 -11
  177. package/src/shared/types.js +0 -12
  178. package/src/shared/utils.d.ts +0 -14
  179. package/src/shared/utils.js +0 -22
  180. package/src/shared/wait-tool-name.d.ts +8 -0
  181. package/src/shared/wait-tool-name.js +13 -0
  182. package/src/slash/slash-commands.js +2 -1
  183. package/src/slash/subagent-cost.d.ts +3 -2
  184. package/src/slash/subagent-cost.js +22 -3
  185. package/src/slash/subagents-admin.js +0 -1
  186. package/src/tui/fleet-status.d.ts +0 -5
  187. package/src/tui/fleet-status.js +4 -24
  188. package/src/tui/fleet-transcript.d.ts +1 -44
  189. package/src/tui/fleet-transcript.js +1 -327
  190. package/src/tui/fleet.js +6 -4
  191. package/src/tui/render.d.ts +0 -9
  192. package/src/tui/render.js +81 -47
  193. package/src/tui/subagent-messages.js +3 -2
  194. package/src/watchdog/register-child.d.ts +2 -3
  195. package/src/watchdog/register-child.js +2 -3
  196. package/src/watchdog/turn-delta.js +2 -1
  197. package/src/workflows/scripted-workflow.js +243 -20
  198. package/src/workflows/workflow-launch-record.d.ts +15 -6
  199. package/src/workflows/workflow-launch-record.js +30 -12
  200. package/src/workflows/workflow-resume-claim.js +2 -2
  201. package/src/workflows/workflow-resume.d.ts +1 -1
  202. package/src/workflows/workflow-resume.js +11 -8
  203. package/src/workflows/workflow-script-worker.d.ts +13 -0
  204. package/src/workflows/workflow-script-worker.js +79 -0
  205. package/workflow-script-process.cjs +36 -0
  206. package/workflow-script-worker.cjs +453 -176
@@ -0,0 +1,333 @@
1
+ /**
2
+ * Fleet transcript reading: trusted-path validation, tail reads, and JSONL
3
+ * parsing into display events. Pure data layer — no TUI imports — so both the
4
+ * engine (run status) and the TUI (fleet view) can share one parser.
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { safeTerminalText as safeDisplayText } from "./display-text.js";
9
+ import { isTrustedRecordedSessionFile } from "./session-file-trust.js";
10
+ const DEFAULT_MAX_RECORDS = 240;
11
+ const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
12
+ const MAX_MESSAGE_CHARS = 64 * 1024;
13
+ function sanitizeJsonDisplayValue(value) {
14
+ if (typeof value === "string") {
15
+ const safe = safeDisplayText(value);
16
+ return { value: safe, changed: safe !== value };
17
+ }
18
+ if (Array.isArray(value)) {
19
+ const sanitized = value.map(sanitizeJsonDisplayValue);
20
+ return {
21
+ value: sanitized.map((entry) => entry.value),
22
+ changed: sanitized.some((entry) => entry.changed),
23
+ };
24
+ }
25
+ if (value && typeof value === "object") {
26
+ let changed = false;
27
+ const sanitized = Object.create(null);
28
+ for (const [key, nested] of Object.entries(value)) {
29
+ const safeKey = safeDisplayText(key);
30
+ const safeValue = sanitizeJsonDisplayValue(nested);
31
+ sanitized[safeKey] = safeValue.value;
32
+ changed ||= safeKey !== key || safeValue.changed;
33
+ }
34
+ return { value: changed ? sanitized : value, changed };
35
+ }
36
+ return { value, changed: false };
37
+ }
38
+ function safeToolArgsPayload(payload) {
39
+ try {
40
+ const sanitized = sanitizeJsonDisplayValue(JSON.parse(payload));
41
+ return sanitized.changed ? JSON.stringify(sanitized.value) : safeDisplayText(payload);
42
+ }
43
+ catch {
44
+ return safeDisplayText(payload);
45
+ }
46
+ }
47
+ export function objectValue(value) {
48
+ return value && typeof value === "object" && !Array.isArray(value)
49
+ ? value
50
+ : undefined;
51
+ }
52
+ function stringValue(value) {
53
+ return typeof value === "string" && value.trim() ? value : undefined;
54
+ }
55
+ function numberValue(value) {
56
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
57
+ }
58
+ function pathWithin(base, candidate) {
59
+ const resolvedBase = path.resolve(base);
60
+ const resolvedCandidate = path.resolve(candidate);
61
+ return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
62
+ }
63
+ function errorMessage(error) {
64
+ return error instanceof Error ? error.message : String(error);
65
+ }
66
+ function isNotFoundError(error) {
67
+ return Boolean(objectValue(error)?.code === "ENOENT");
68
+ }
69
+ function validateTranscriptPath(filePath, trustedRoots, trustedFiles = [], trustedFileRoot) {
70
+ if (trustedRoots.length === 0 && (!trustedFileRoot || trustedFiles.length === 0))
71
+ return { warning: `Transcript preview has no trusted root: ${filePath}` };
72
+ const resolvedPath = path.resolve(filePath);
73
+ const recordedCandidate = trustedFileRoot
74
+ && pathWithin(trustedFileRoot, resolvedPath)
75
+ && trustedFiles.some((file) => path.resolve(file) === resolvedPath);
76
+ if (!trustedRoots.some((root) => pathWithin(root, resolvedPath)) && !recordedCandidate) {
77
+ return { warning: `Transcript is outside trusted roots: ${filePath}` };
78
+ }
79
+ let stat;
80
+ try {
81
+ stat = fs.lstatSync(resolvedPath);
82
+ }
83
+ catch (error) {
84
+ if (isNotFoundError(error))
85
+ return {};
86
+ return { warning: `Transcript could not be inspected: ${errorMessage(error)}` };
87
+ }
88
+ if (stat.isSymbolicLink())
89
+ return { warning: `Transcript preview refused a symlink: ${filePath}` };
90
+ if (!stat.isFile())
91
+ return { warning: `Transcript path is not a file: ${filePath}` };
92
+ try {
93
+ const realPath = fs.realpathSync(resolvedPath);
94
+ const realRoots = trustedRoots
95
+ .filter((root) => fs.existsSync(root))
96
+ .map((root) => fs.realpathSync(root));
97
+ if (!realRoots.some((root) => pathWithin(root, realPath)) && !isTrustedRecordedSessionFile(realPath, trustedFiles, trustedFileRoot)) {
98
+ return { warning: `Transcript resolves outside trusted roots: ${filePath}` };
99
+ }
100
+ return { resolvedPath: realPath };
101
+ }
102
+ catch (error) {
103
+ return { warning: `Transcript path could not be resolved: ${errorMessage(error)}` };
104
+ }
105
+ }
106
+ function isCompleteRecord(line) {
107
+ if (!line?.trim())
108
+ return false;
109
+ try {
110
+ return objectValue(JSON.parse(line)) !== undefined;
111
+ }
112
+ catch {
113
+ return false;
114
+ }
115
+ }
116
+ function readTailLines(filePath, maxBytes) {
117
+ let fd;
118
+ try {
119
+ const noFollow = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
120
+ fd = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);
121
+ const stat = fs.fstatSync(fd);
122
+ if (!stat.isFile())
123
+ return { lines: [], truncated: false, warning: `Transcript path is not a file: ${filePath}` };
124
+ if (stat.size === 0)
125
+ return { lines: [], truncated: false };
126
+ const bytesToRead = Math.min(stat.size, maxBytes);
127
+ const start = stat.size - bytesToRead;
128
+ const buffer = Buffer.alloc(bytesToRead);
129
+ const bytesRead = fs.readSync(fd, buffer, 0, bytesToRead, start);
130
+ const content = buffer.subarray(0, bytesRead).toString("utf-8");
131
+ const endsWithNewline = content.endsWith("\n");
132
+ let lines = content.split(/\r?\n/);
133
+ if (start > 0 && lines.length > 0)
134
+ lines = lines.slice(1);
135
+ if (lines.at(-1) === "")
136
+ lines = lines.slice(0, -1);
137
+ else if (!endsWithNewline && !isCompleteRecord(lines.at(-1)))
138
+ lines = lines.slice(0, -1);
139
+ return { lines, truncated: start > 0 };
140
+ }
141
+ catch (error) {
142
+ return { lines: [], truncated: false, warning: `Transcript could not be read: ${errorMessage(error)}` };
143
+ }
144
+ finally {
145
+ if (fd !== undefined)
146
+ fs.closeSync(fd);
147
+ }
148
+ }
149
+ function clipMessage(text) {
150
+ if (text.length <= MAX_MESSAGE_CHARS)
151
+ return text;
152
+ return `${text.slice(0, MAX_MESSAGE_CHARS)}\n\n… message truncated`;
153
+ }
154
+ export function safeTranscriptEvent(event) {
155
+ if (event.kind === "assistant") {
156
+ return {
157
+ ...event,
158
+ text: safeDisplayText(event.text),
159
+ ...(event.model ? { model: safeDisplayText(event.model) } : {}),
160
+ };
161
+ }
162
+ if (event.kind === "user" || event.kind === "notice") {
163
+ return { ...event, text: safeDisplayText(event.text) };
164
+ }
165
+ return {
166
+ ...event,
167
+ name: safeDisplayText(event.name),
168
+ ...(event.args !== undefined ? { args: safeDisplayText(event.args) } : {}),
169
+ ...(event.argsPayload !== undefined ? { argsPayload: safeToolArgsPayload(event.argsPayload) } : {}),
170
+ ...(event.output !== undefined ? { output: safeDisplayText(event.output) } : {}),
171
+ ...(event.error !== undefined ? { error: safeDisplayText(event.error) } : {}),
172
+ };
173
+ }
174
+ function findTool(events, toolCallId, name) {
175
+ if (toolCallId) {
176
+ for (let index = events.length - 1; index >= 0; index--) {
177
+ const event = events[index];
178
+ if (event?.kind === "tool" && event.toolCallId === toolCallId)
179
+ return event;
180
+ }
181
+ return undefined;
182
+ }
183
+ for (let index = events.length - 1; index >= 0; index--) {
184
+ const event = events[index];
185
+ if (event?.kind !== "tool")
186
+ continue;
187
+ const tool = event;
188
+ if ((!name || tool.name === name) && !tool.resultSeen)
189
+ return tool;
190
+ }
191
+ return undefined;
192
+ }
193
+ function appendTextEvent(events, kind, text, metadata) {
194
+ const clipped = clipMessage(text.trim());
195
+ if (!clipped)
196
+ return;
197
+ const previous = events.at(-1);
198
+ if (previous?.kind === kind && previous.text === clipped)
199
+ return;
200
+ events.push({ kind, text: clipped, ...metadata });
201
+ }
202
+ function parseTranscriptLines(lines, conversationStarted = false) {
203
+ const events = [];
204
+ let malformed = 0;
205
+ let explicitTruncation = false;
206
+ let assistantSeen = conversationStarted;
207
+ for (const line of lines) {
208
+ if (!line.trim())
209
+ continue;
210
+ let record;
211
+ try {
212
+ record = objectValue(JSON.parse(line));
213
+ }
214
+ catch {
215
+ malformed++;
216
+ continue;
217
+ }
218
+ if (!record) {
219
+ malformed++;
220
+ continue;
221
+ }
222
+ const recordType = stringValue(record.recordType);
223
+ const timestamp = numberValue(record.ts);
224
+ if (recordType === "truncated") {
225
+ explicitTruncation = true;
226
+ continue;
227
+ }
228
+ if (recordType === "tool_start") {
229
+ const name = stringValue(record.toolName) ?? "tool";
230
+ events.push({
231
+ kind: "tool",
232
+ ...(stringValue(record.toolCallId) ? { toolCallId: stringValue(record.toolCallId) } : {}),
233
+ name,
234
+ ...(stringValue(record.argsPreview) ? { args: stringValue(record.argsPreview) } : {}),
235
+ ...(stringValue(record.argsPayload) ? { argsPayload: stringValue(record.argsPayload) } : {}),
236
+ status: "running",
237
+ ...(timestamp !== undefined ? { timestamp, startedAt: timestamp } : {}),
238
+ });
239
+ continue;
240
+ }
241
+ if (recordType === "tool_end") {
242
+ const tool = findTool(events, stringValue(record.toolCallId), stringValue(record.toolName));
243
+ if (tool && !tool.resultSeen)
244
+ tool.status = record.isError === true ? "error" : "complete";
245
+ if (tool && timestamp !== undefined && tool.endedAt === undefined)
246
+ tool.endedAt = timestamp;
247
+ continue;
248
+ }
249
+ if (recordType === "stderr") {
250
+ const text = stringValue(record.text);
251
+ if (text)
252
+ events.push({ kind: "notice", text: clipMessage(text), tone: "error", ...(timestamp !== undefined ? { timestamp } : {}) });
253
+ continue;
254
+ }
255
+ if (recordType !== "message")
256
+ continue;
257
+ const message = objectValue(record.message);
258
+ const role = stringValue(record.role) ?? stringValue(message?.role);
259
+ const text = stringValue(record.text) ?? stringValue(message?.text) ?? stringValue(message?.content);
260
+ if (role === "toolResult" || role === "tool_result") {
261
+ const toolCallId = stringValue(record.toolCallId) ?? stringValue(message?.toolCallId);
262
+ const name = stringValue(record.toolName) ?? stringValue(message?.toolName) ?? "tool";
263
+ const failed = record.isError === true || message?.isError === true;
264
+ let tool = findTool(events, toolCallId, name);
265
+ if (!tool) {
266
+ tool = {
267
+ kind: "tool",
268
+ ...(toolCallId ? { toolCallId } : {}),
269
+ name,
270
+ status: failed ? "error" : "complete",
271
+ ...(timestamp !== undefined ? { timestamp } : {}),
272
+ };
273
+ events.push(tool);
274
+ }
275
+ if (!tool.resultSeen) {
276
+ tool.resultSeen = true;
277
+ tool.status = failed ? "error" : "complete";
278
+ if (timestamp !== undefined && tool.endedAt === undefined)
279
+ tool.endedAt = timestamp;
280
+ if (text && (!failed || tool.output === undefined)) {
281
+ tool.output = clipMessage(text);
282
+ tool.outputTruncated = record.outputTruncated === true || text.includes("… payload truncated") || text.includes("[Showing lines");
283
+ }
284
+ if (failed && text)
285
+ tool.error = clipMessage(text.split(/\r?\n/).find((candidate) => candidate.trim()) ?? text);
286
+ }
287
+ continue;
288
+ }
289
+ if (role === "assistant") {
290
+ assistantSeen = true;
291
+ // The transcript writer records the assistant message's provider-local id, which can itself contain a slash.
292
+ const rawModel = stringValue(record.model) ?? stringValue(message?.model);
293
+ const provider = stringValue(message?.provider);
294
+ const model = rawModel && provider ? `${provider}/${rawModel}` : rawModel;
295
+ if (text)
296
+ appendTextEvent(events, "assistant", text, {
297
+ ...(model ? { model } : {}),
298
+ ...(timestamp !== undefined ? { timestamp } : {}),
299
+ });
300
+ continue;
301
+ }
302
+ if (role === "user" && assistantSeen && text) {
303
+ appendTextEvent(events, "user", text, timestamp !== undefined ? { timestamp } : {});
304
+ }
305
+ }
306
+ for (const event of events) {
307
+ if (event.kind === "tool")
308
+ delete event.resultSeen;
309
+ }
310
+ return { events: events.map(safeTranscriptEvent), malformed, explicitTruncation };
311
+ }
312
+ export function readFleetTranscript(filePath, options) {
313
+ const validated = validateTranscriptPath(filePath, options.trustedRoots, options.trustedFiles, options.trustedFileRoot);
314
+ if (!validated.resolvedPath) {
315
+ return { path: filePath, events: [], truncated: false, readFailed: true, ...(validated.warning ? { warning: safeDisplayText(validated.warning) } : {}) };
316
+ }
317
+ const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
318
+ const tail = readTailLines(validated.resolvedPath, Math.max(1024, options.maxBytes ?? DEFAULT_MAX_BYTES));
319
+ const recordsOmitted = tail.truncated || tail.lines.length > maxRecords;
320
+ const selectedLines = tail.lines.slice(-maxRecords);
321
+ const parsed = parseTranscriptLines(selectedLines, recordsOmitted);
322
+ const warnings = [
323
+ tail.warning,
324
+ parsed.malformed > 0 ? `Skipped ${parsed.malformed} malformed transcript record${parsed.malformed === 1 ? "" : "s"}.` : undefined,
325
+ ].filter((value) => Boolean(value));
326
+ return {
327
+ path: filePath,
328
+ events: parsed.events,
329
+ truncated: tail.truncated || tail.lines.length > maxRecords || parsed.explicitTruncation,
330
+ ...(tail.warning ? { readFailed: true } : {}),
331
+ ...(warnings.length ? { warning: safeDisplayText(warnings.join(" ")) } : {}),
332
+ };
333
+ }
@@ -1,33 +1,15 @@
1
- /**
2
- * Formatting utilities for display output
3
- */
4
1
  import type { Usage, SingleResult, TokenUsage } from "./types.ts";
5
2
  import type { ChainStep } from "./settings.ts";
6
- /**
7
- * Format token count for compact display.
8
- */
9
3
  export declare function formatTokens(n: number): string;
10
4
  export declare function formatTokenUsage(usage: TokenUsage, legacyLabel?: string): string;
11
5
  export declare function formatContextUsage(usage: Pick<TokenUsage, "window" | "windowPeak">, contextLimit: number): string | undefined;
12
6
  export declare function formatModelThinking(model?: string, thinking?: string): string;
13
- /**
14
- * Format usage statistics into a compact string
15
- */
16
7
  export declare function formatUsage(u: Usage, model?: string): string;
17
- /**
18
- * Format duration in human-readable form
19
- */
20
8
  export declare function formatDuration(ms: number): string;
21
- /**
22
- * Build a summary string for a completed/failed chain
23
- */
24
9
  export declare function buildChainSummary(steps: ChainStep[], results: SingleResult[], chainDir: string, status: "completed" | "failed", failedStep?: {
25
10
  index: number;
26
11
  error: string;
27
12
  }): string;
28
- /**
29
- * Format a tool call for display
30
- */
31
13
  export declare function formatToolCall(name: string, args: Record<string, unknown>, expanded?: boolean): string;
32
14
  /**
33
15
  * Shorten a path by replacing home directory with ~
@@ -1,14 +1,8 @@
1
- /**
2
- * Formatting utilities for display output
3
- */
4
1
  import * as fs from "node:fs";
5
2
  import * as path from "node:path";
6
3
  import { isDynamicParallelStep, isParallelStep } from "./settings.js";
7
4
  import { previewDisplayText, sanitizeDisplayText } from "./display-text.js";
8
5
  import { splitKnownThinkingSuffix, THINKING_LEVELS } from "./model-info.js";
9
- /**
10
- * Format token count for compact display.
11
- */
12
6
  export function formatTokens(n) {
13
7
  if (n < 1000)
14
8
  return String(n);
@@ -37,9 +31,6 @@ export function formatModelThinking(model, thinking) {
37
31
  const displayThinking = parsed?.thinkingSuffix ? parsed.thinkingSuffix.slice(1) : explicitThinking;
38
32
  return [displayModel, displayThinking ? `thinking ${displayThinking}` : undefined].filter(Boolean).join(" · ");
39
33
  }
40
- /**
41
- * Format usage statistics into a compact string
42
- */
43
34
  export function formatUsage(u, model) {
44
35
  const parts = [];
45
36
  if (u.turns)
@@ -58,9 +49,6 @@ export function formatUsage(u, model) {
58
49
  parts.push(model);
59
50
  return parts.join(" ");
60
51
  }
61
- /**
62
- * Format duration in human-readable form
63
- */
64
52
  export function formatDuration(ms) {
65
53
  if (ms < 1000)
66
54
  return `${ms}ms`;
@@ -68,9 +56,6 @@ export function formatDuration(ms) {
68
56
  return `${(ms / 1000).toFixed(1)}s`;
69
57
  return `${Math.floor(ms / 60000)}m${Math.floor((ms % 60000) / 1000)}s`;
70
58
  }
71
- /**
72
- * Build a summary string for a completed/failed chain
73
- */
74
59
  export function buildChainSummary(steps, results, chainDir, status, failedStep) {
75
60
  const stepNames = steps
76
61
  .map((step) => (isParallelStep(step) ? `parallel[${step.parallel.length}]` : isDynamicParallelStep(step) ? `expand:${step.parallel.agent}` : step.agent))
@@ -101,9 +86,6 @@ export function buildChainSummary(steps, results, chainDir, status, failedStep)
101
86
  📁 Artifacts: ${chainDir}`;
102
87
  }
103
88
  }
104
- /**
105
- * Format a tool call for display
106
- */
107
89
  export function formatToolCall(name, args, expanded = false) {
108
90
  switch (name) {
109
91
  case "bash": {
@@ -1,4 +1,19 @@
1
- /** Records that sessionId replaced previousSessionId in this process, inheriting its chain. */
1
+ /**
2
+ * The operator switched away from sessionId and chose to leave its work there: its successor inherits nothing, and
3
+ * sessionId keeps its own chain when it is reopened. The mark lasts until sessionId shuts down again without it,
4
+ * so a repeated start of the same replacement (RPC rebind) sees it too.
5
+ */
6
+ export declare function keepSessionWork(sessionId: string): void;
7
+ /** sessionId shut down without leaving its work there, so whoever replaces it next inherits as usual. */
8
+ export declare function releaseSessionWork(sessionId: string): void;
9
+ /** Records that sessionId replaced previousSessionId in this process, inheriting its chain unless its work was kept there. */
2
10
  export declare function recordSessionReplacement(sessionId: string, previousSessionId: string): void;
11
+ /**
12
+ * A session starting in this process is live again, so no other session inherits its runs any more.
13
+ * pi-web keeps a forked-from session listed and can reopen it while its fork is still live.
14
+ * A startup replaces no session, so the session also drops what it inherited before: whoever
15
+ * replaced it took those runs over and keeps them.
16
+ */
17
+ export declare function recordSessionStart(sessionId: string, startup: boolean): void;
3
18
  /** Sessions this process replaced on the way to sessionId, newest first; their runs belong to sessionId. */
4
19
  export declare function inheritedSessionIds(sessionId: string): readonly string[];
@@ -3,21 +3,60 @@ const SUCCESSION_KEY = Symbol.for("pi-subagents.session-succession");
3
3
  const MAX_INHERITED_SESSIONS = 8;
4
4
  // A long-lived host (pi-web) can replace sessions for days; keep only the most recent ones.
5
5
  const MAX_RECORDED_SESSIONS = 64;
6
+ const KEPT_WORK_KEY = Symbol.for("pi-subagents.sessions-keeping-work");
6
7
  function successions() {
7
8
  const runtime = globalThis;
8
9
  runtime[SUCCESSION_KEY] ??= new Map();
9
10
  return runtime[SUCCESSION_KEY];
10
11
  }
11
- /** Records that sessionId replaced previousSessionId in this process, inheriting its chain. */
12
+ function keptWork() {
13
+ const runtime = globalThis;
14
+ runtime[KEPT_WORK_KEY] ??= new Set();
15
+ return runtime[KEPT_WORK_KEY];
16
+ }
17
+ /**
18
+ * The operator switched away from sessionId and chose to leave its work there: its successor inherits nothing, and
19
+ * sessionId keeps its own chain when it is reopened. The mark lasts until sessionId shuts down again without it,
20
+ * so a repeated start of the same replacement (RPC rebind) sees it too.
21
+ */
22
+ export function keepSessionWork(sessionId) {
23
+ keptWork().delete(sessionId);
24
+ keptWork().add(sessionId);
25
+ while (keptWork().size > MAX_RECORDED_SESSIONS)
26
+ keptWork().delete(keptWork().values().next().value);
27
+ }
28
+ /** sessionId shut down without leaving its work there, so whoever replaces it next inherits as usual. */
29
+ export function releaseSessionWork(sessionId) {
30
+ keptWork().delete(sessionId);
31
+ }
32
+ /** Records that sessionId replaced previousSessionId in this process, inheriting its chain unless its work was kept there. */
12
33
  export function recordSessionReplacement(sessionId, previousSessionId) {
34
+ const inherited = keptWork().has(previousSessionId) ? [] : [previousSessionId, ...(successions().get(previousSessionId) ?? [])];
35
+ const own = keptWork().has(sessionId) ? successions().get(sessionId) ?? [] : [];
13
36
  // Resuming back and forth can revisit a session: keep the chain distinct and free of sessionId
14
37
  // itself, so the bound holds real predecessors and discovery never scans one session twice.
15
- const chain = [...new Set([previousSessionId, ...(successions().get(previousSessionId) ?? [])])].filter((id) => id !== sessionId);
38
+ const chain = [...new Set([...inherited, ...own])].filter((id) => id !== sessionId);
16
39
  successions().delete(sessionId);
17
40
  successions().set(sessionId, chain.slice(0, MAX_INHERITED_SESSIONS));
18
41
  while (successions().size > MAX_RECORDED_SESSIONS)
19
42
  successions().delete(successions().keys().next().value);
20
43
  }
44
+ /**
45
+ * A session starting in this process is live again, so no other session inherits its runs any more.
46
+ * pi-web keeps a forked-from session listed and can reopen it while its fork is still live.
47
+ * A startup replaces no session, so the session also drops what it inherited before: whoever
48
+ * replaced it took those runs over and keeps them.
49
+ */
50
+ export function recordSessionStart(sessionId, startup) {
51
+ if (startup) {
52
+ successions().delete(sessionId);
53
+ keptWork().delete(sessionId);
54
+ }
55
+ for (const [id, chain] of successions()) {
56
+ if (chain.includes(sessionId))
57
+ successions().set(id, chain.filter((inherited) => inherited !== sessionId));
58
+ }
59
+ }
21
60
  /** Sessions this process replaced on the way to sessionId, newest first; their runs belong to sessionId. */
22
61
  export function inheritedSessionIds(sessionId) {
23
62
  return successions().get(sessionId) ?? [];
@@ -0,0 +1,7 @@
1
+ import type { SubagentState } from "./types.ts";
2
+ /**
3
+ * Reports a warning once per extension runtime and key. Console output while the TUI owns the terminal is drawn
4
+ * over the editor, so a session with a UI gets a TUI warning; a headless session gets the line on stderr.
5
+ * Pass `key` when the message varies between occurrences (for example, an elapsed time).
6
+ */
7
+ export declare function reportSessionWarning(state: SubagentState, message: string, key?: string): void;
@@ -0,0 +1,26 @@
1
+ import { withCachedUiContext } from "./extension-context.js";
2
+ const reportedWarnings = new WeakMap();
3
+ /**
4
+ * Reports a warning once per extension runtime and key. Console output while the TUI owns the terminal is drawn
5
+ * over the editor, so a session with a UI gets a TUI warning; a headless session gets the line on stderr.
6
+ * Pass `key` when the message varies between occurrences (for example, an elapsed time).
7
+ */
8
+ export function reportSessionWarning(state, message, key = message) {
9
+ let reported = reportedWarnings.get(state);
10
+ if (!reported)
11
+ reportedWarnings.set(state, reported = new Set());
12
+ if (reported.has(key))
13
+ return;
14
+ reported.add(key);
15
+ const text = `[pi-subagents] ${message}`;
16
+ const cached = state.lastUiContext;
17
+ const notified = withCachedUiContext(cached, () => {
18
+ if (state.lastUiContext === cached)
19
+ state.lastUiContext = null;
20
+ }, (ctx) => {
21
+ ctx.ui.notify(text, "warning");
22
+ return true;
23
+ });
24
+ if (!notified)
25
+ console.warn(text);
26
+ }
@@ -1,12 +1,8 @@
1
- /**
2
- * Chain behavior, template resolution, and directory management
3
- */
4
1
  import { type AgentConfig, type AgentScope, type UnknownAgentDiagnosticContext } from "../agents/agents.ts";
5
2
  import { type OutputOverrideInput, type ResolvedStepBehavior } from "../runs/shared/child-launch-plan.ts";
6
3
  import { type AcceptanceInput, type AgentContract, type ChainGateLayer, type JsonSchemaObject, type OutputMode, type ToolBudgetConfig } from "./types.ts";
7
4
  export { planChildLaunch, resolveStepBehavior, resolveTaskTextForFileUpdatePolicy, suppressProgressForReadOnlyTask, taskDisallowsFileUpdates, } from "../runs/shared/child-launch-plan.ts";
8
5
  export type { ChildLaunchPlan, ChildLaunchPlanInput, OutputOverrideInput, ResolvedStepBehavior, StepOverrides } from "../runs/shared/child-launch-plan.ts";
9
- /** Sequential step: single agent execution */
10
6
  export interface SequentialStep {
11
7
  agent: string;
12
8
  task?: string;
@@ -30,7 +26,6 @@ export interface SequentialStep {
30
26
  /** Internal workflow child isolation; public workflow scripts supply this on runs.run. */
31
27
  worktree?: boolean;
32
28
  }
33
- /** Parallel task item within a parallel step */
34
29
  export interface ParallelTaskItem {
35
30
  agent: string;
36
31
  task?: string;
@@ -80,7 +75,6 @@ export interface DynamicParallelStep {
80
75
  agentContract?: AgentContract;
81
76
  gateOn?: ChainGateLayer;
82
77
  }
83
- /** Parallel step: multiple agents running concurrently */
84
78
  export interface ParallelStep {
85
79
  parallel: ParallelTaskItem[];
86
80
  concurrency?: number;
@@ -91,21 +85,15 @@ export interface ParallelStep {
91
85
  agentContract?: AgentContract;
92
86
  gateOn?: ChainGateLayer;
93
87
  }
94
- /** Union type for chain steps */
95
88
  export type ChainStep = SequentialStep | ParallelStep | DynamicParallelStep;
96
89
  export declare function isParallelStep(step: ChainStep): step is ParallelStep;
97
90
  export declare function isDynamicParallelStep(step: ChainStep): step is DynamicParallelStep;
98
- /** Get all agent names in a step (single for sequential, multiple for parallel) */
99
91
  export declare function getStepAgents(step: ChainStep): string[];
100
92
  export declare function createChainDir(runId: string, baseDir?: string): string;
101
93
  export declare function removeChainDir(chainDir: string): void;
102
94
  export declare function cleanupOldChainDirs(): void;
103
95
  /** Resolved templates for a chain - string for sequential, string[] for parallel */
104
96
  export type ResolvedTemplates = (string | string[])[];
105
- /**
106
- * Resolve templates for a chain with parallel step support.
107
- * Returns string for sequential steps, string[] for parallel steps.
108
- */
109
97
  export declare function resolveChainTemplates(steps: ChainStep[]): ResolvedTemplates;
110
98
  /**
111
99
  * Expand a leading `~`/`~/` to the user's home directory. Other forms (relative,
@@ -119,28 +107,17 @@ export declare function expandHomePath(filePath: string): string;
119
107
  export declare function resolveChainPath(filePath: string, chainDir: string): string;
120
108
  export declare function resolveExistingReadInstructionPaths(reads: readonly string[], instructionCwd: string, existenceCwd?: string): string[];
121
109
  export declare function resolveExistingReadPaths(reads: readonly string[], cwd: string): string[];
122
- /**
123
- * Build chain instructions from resolved behavior.
124
- * These are appended to the task to tell the agent what to read/write.
125
- */
126
110
  export declare function writeInitialProgressFile(progressDir: string): void;
127
111
  export declare function buildChainInstructions(behavior: ResolvedStepBehavior, chainDir: string, isFirstProgressAgent: boolean, previousSummary?: string, readExistenceDir?: string): {
128
112
  prefix: string;
129
113
  suffix: string;
130
114
  };
131
- /**
132
- * Resolve behaviors for all tasks in a parallel step.
133
- * Creates namespaced output paths to avoid collisions.
134
- */
135
115
  /** Exact discovery context, or explicit input for defensive fallback discovery. */
136
116
  export type ParallelBehaviorDiagnostics = UnknownAgentDiagnosticContext | {
137
117
  cwd: string;
138
118
  scope?: AgentScope;
139
119
  };
140
120
  export declare function resolveParallelBehaviors(tasks: ParallelTaskItem[], agentConfigs: AgentConfig[], stepIndex: number, chainSkills?: string[], diagnostics?: ParallelBehaviorDiagnostics): ResolvedStepBehavior[];
141
- /**
142
- * Create subdirectories for parallel step outputs
143
- */
144
121
  export declare function createParallelDirs(chainDir: string, stepIndex: number, taskCount: number, agentNames: string[]): void;
145
122
  export type { ParallelTaskResult } from "../runs/shared/parallel-utils.ts";
146
123
  export { aggregateParallelOutputs } from "../runs/shared/parallel-utils.ts";