@xzzpig/pi-subagents 0.24.1 → 0.25.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 (263) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-ZWXU5SPQ.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-6BJUEES3.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-SLNMBXLL.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-LMGQAJ3O.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-Y6H2G6KX.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-TGLFTQWJ.js → chunk-YWXILP5N.js} +5 -4
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +12 -0
  49. package/node_modules/@xzzpig/pi-components/README.md +94 -0
  50. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.d.ts +186 -0
  51. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.js +693 -0
  52. package/node_modules/@xzzpig/pi-components/package.json +5 -1
  53. package/package.json +4 -4
  54. package/skills/pi-subagents/SKILL.md +15 -6
  55. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  56. package/src/agents/agent-management.d.ts +1 -0
  57. package/src/agents/agent-management.js +46 -18
  58. package/src/agents/agent-memory.d.ts +1 -4
  59. package/src/agents/agent-memory.js +1 -4
  60. package/src/agents/agent-serializer.d.ts +2 -0
  61. package/src/agents/agent-serializer.js +1 -1
  62. package/src/agents/agents.d.ts +2 -3
  63. package/src/agents/agents.js +46 -20
  64. package/src/agents/frontmatter.js +1 -8
  65. package/src/agents/global-npm-root.d.ts +1 -0
  66. package/src/agents/global-npm-root.js +11 -3
  67. package/src/agents/skills.d.ts +0 -3
  68. package/src/agents/skills.js +0 -3
  69. package/src/api/preflight.d.ts +3 -1
  70. package/src/api/preflight.js +2 -0
  71. package/src/extension/config.d.ts +1 -0
  72. package/src/extension/config.js +13 -1
  73. package/src/extension/herdr-pi-bridge.js +10 -2
  74. package/src/extension/index.d.ts +0 -13
  75. package/src/extension/index.js +51 -37
  76. package/src/extension/public-execution.d.ts +1 -0
  77. package/src/extension/public-execution.js +4 -0
  78. package/src/extension/reply-workflow-script.js +24 -4
  79. package/src/extension/schemas.d.ts +12 -3
  80. package/src/extension/schemas.js +7 -3
  81. package/src/extension/session-switch.d.ts +25 -0
  82. package/src/extension/session-switch.js +138 -0
  83. package/src/extension/subagent-guide.d.ts +1 -1
  84. package/src/extension/subagent-guide.js +1 -1
  85. package/src/extension/subagent-launch-tool.d.ts +25 -0
  86. package/src/extension/subagent-launch-tool.js +48 -0
  87. package/src/extension/tool-activation.js +55 -15
  88. package/src/extension/tool-description.d.ts +1 -1
  89. package/src/extension/tool-description.js +14 -8
  90. package/src/inspectors/herdr/actions.d.ts +0 -1
  91. package/src/inspectors/herdr/actions.js +0 -1
  92. package/src/inspectors/session-roots-codec.d.ts +0 -1
  93. package/src/inspectors/session-roots-codec.js +0 -1
  94. package/src/inspectors/tmux/actions.d.ts +0 -1
  95. package/src/inspectors/tmux/actions.js +0 -1
  96. package/src/integrations/herdr-status.js +3 -8
  97. package/src/intercom/native-supervisor-channel.js +65 -9
  98. package/src/runs/background/async-execution.d.ts +7 -10
  99. package/src/runs/background/async-execution.js +66 -29
  100. package/src/runs/background/async-job-tracker.js +12 -0
  101. package/src/runs/background/async-resume.d.ts +2 -1
  102. package/src/runs/background/async-resume.js +114 -40
  103. package/src/runs/background/async-retention.d.ts +0 -2
  104. package/src/runs/background/async-retention.js +17 -6
  105. package/src/runs/background/async-status.d.ts +2 -0
  106. package/src/runs/background/async-status.js +4 -0
  107. package/src/runs/background/auto-drain.js +2 -1
  108. package/src/runs/background/boot-id.d.ts +1 -3
  109. package/src/runs/background/boot-id.js +1 -3
  110. package/src/runs/background/completion-batcher.d.ts +3 -4
  111. package/src/runs/background/completion-batcher.js +2 -3
  112. package/src/runs/background/control-channel.d.ts +0 -6
  113. package/src/runs/background/control-channel.js +0 -6
  114. package/src/runs/background/fleet-view.js +2 -3
  115. package/src/runs/background/notify.d.ts +0 -2
  116. package/src/runs/background/notify.js +0 -2
  117. package/src/runs/background/result-watcher.d.ts +1 -0
  118. package/src/runs/background/result-watcher.js +59 -29
  119. package/src/runs/background/resume-guidance.js +4 -2
  120. package/src/runs/background/retained-children.js +2 -1
  121. package/src/runs/background/run-child-session.d.ts +2 -3
  122. package/src/runs/background/run-child-session.js +5 -8
  123. package/src/runs/background/run-status.js +9 -7
  124. package/src/runs/background/runner-aliases.js +15 -0
  125. package/src/runs/background/scheduled-runs.d.ts +3 -1
  126. package/src/runs/background/scheduled-runs.js +13 -16
  127. package/src/runs/background/steering.d.ts +2 -11
  128. package/src/runs/background/steering.js +11 -6
  129. package/src/runs/background/subagent-runner.d.ts +2 -6
  130. package/src/runs/background/subagent-runner.js +88 -70
  131. package/src/runs/background/subagent-wait.js +12 -15
  132. package/src/runs/background/wait-config.d.ts +2 -0
  133. package/src/runs/background/wait-config.js +17 -3
  134. package/src/runs/background/wait-subscriptions.js +124 -12
  135. package/src/runs/background/wait-tool.js +4 -2
  136. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  137. package/src/runs/background/workflow-terminal-proof.js +0 -1
  138. package/src/runs/foreground/async-steering-action.js +24 -9
  139. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  140. package/src/runs/foreground/async-stop-action.js +9 -1
  141. package/src/runs/foreground/execution.d.ts +0 -3
  142. package/src/runs/foreground/execution.js +56 -24
  143. package/src/runs/foreground/prompt-audit.js +1 -0
  144. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  145. package/src/runs/foreground/subagent-executor.js +164 -49
  146. package/src/runs/shared/acceptance.js +69 -26
  147. package/src/runs/shared/async-status-projection.d.ts +2 -0
  148. package/src/runs/shared/async-status-projection.js +10 -0
  149. package/src/runs/shared/child-commands.js +15 -2
  150. package/src/runs/shared/child-hooks.d.ts +1 -7
  151. package/src/runs/shared/child-hooks.js +13 -5
  152. package/src/runs/shared/child-launch.js +6 -2
  153. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  154. package/src/runs/shared/child-session.d.ts +6 -5
  155. package/src/runs/shared/child-session.js +85 -38
  156. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  157. package/src/runs/shared/child-tool-plan.js +0 -1
  158. package/src/runs/shared/claude-code-adapter.js +11 -0
  159. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  160. package/src/runs/shared/external-cli-contract.js +18 -13
  161. package/src/runs/shared/external-cli-runner.js +26 -6
  162. package/src/runs/shared/herdr-connection.js +2 -1
  163. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  164. package/src/runs/shared/herdr-pane-host.js +17 -1
  165. package/src/runs/shared/herdr-placed-run.js +51 -24
  166. package/src/runs/shared/lane-metadata.d.ts +0 -1
  167. package/src/runs/shared/lane-metadata.js +0 -1
  168. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  169. package/src/runs/shared/mcp-config-sources.js +1 -1
  170. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  171. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  172. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  173. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  174. package/src/runs/shared/model-resolution.d.ts +20 -5
  175. package/src/runs/shared/model-resolution.js +55 -50
  176. package/src/runs/shared/model-scope.d.ts +1 -5
  177. package/src/runs/shared/model-scope.js +1 -5
  178. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  179. package/src/runs/shared/mutation-evidence.js +52 -7
  180. package/src/runs/shared/nested-events.d.ts +1 -0
  181. package/src/runs/shared/nested-events.js +1 -1
  182. package/src/runs/shared/parallel-utils.d.ts +0 -1
  183. package/src/runs/shared/permissions.js +5 -3
  184. package/src/runs/shared/placement-host.d.ts +5 -1
  185. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  186. package/src/runs/shared/rex-pane-host.js +0 -2
  187. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  188. package/src/runs/shared/run-launch-folder.js +21 -0
  189. package/src/runs/shared/runner-launcher.d.ts +12 -1
  190. package/src/runs/shared/runner-launcher.js +16 -0
  191. package/src/runs/shared/single-output.d.ts +3 -3
  192. package/src/runs/shared/single-output.js +5 -3
  193. package/src/runs/shared/structured-output.d.ts +8 -0
  194. package/src/runs/shared/structured-output.js +40 -5
  195. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  196. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  197. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  198. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  199. package/src/runs/shared/tool-timeout.js +2 -1
  200. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  201. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  202. package/src/runs/shared/worktree.d.ts +3 -0
  203. package/src/runs/shared/worktree.js +20 -0
  204. package/src/shared/artifacts.d.ts +1 -0
  205. package/src/shared/artifacts.js +132 -22
  206. package/src/shared/capacity-resilient-json.d.ts +1 -1
  207. package/src/shared/child-cache-retention.d.ts +1 -2
  208. package/src/shared/child-cache-retention.js +1 -2
  209. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  210. package/src/shared/fleet-transcript-reader.js +333 -0
  211. package/src/shared/formatters.d.ts +0 -18
  212. package/src/shared/formatters.js +0 -18
  213. package/src/shared/pruned-fork.js +2 -2
  214. package/src/shared/reported-progress.d.ts +1 -0
  215. package/src/shared/reported-progress.js +12 -0
  216. package/src/shared/session-succession.d.ts +16 -1
  217. package/src/shared/session-succession.js +41 -2
  218. package/src/shared/session-warnings.d.ts +7 -0
  219. package/src/shared/session-warnings.js +26 -0
  220. package/src/shared/settings.d.ts +0 -23
  221. package/src/shared/settings.js +3 -35
  222. package/src/shared/status-format.d.ts +1 -0
  223. package/src/shared/status-format.js +1 -1
  224. package/src/shared/types.d.ts +108 -59
  225. package/src/shared/types.js +0 -12
  226. package/src/shared/utils.d.ts +3 -15
  227. package/src/shared/utils.js +4 -22
  228. package/src/shared/wait-tool-name.d.ts +8 -0
  229. package/src/shared/wait-tool-name.js +13 -0
  230. package/src/slash/slash-commands.js +2 -1
  231. package/src/slash/subagent-cost.d.ts +3 -2
  232. package/src/slash/subagent-cost.js +22 -3
  233. package/src/slash/subagents-admin.js +0 -1
  234. package/src/tui/fleet-status.d.ts +0 -5
  235. package/src/tui/fleet-status.js +4 -24
  236. package/src/tui/fleet.js +6 -4
  237. package/src/tui/render.d.ts +0 -9
  238. package/src/tui/render.js +194 -68
  239. package/src/tui/subagent-messages.js +3 -2
  240. package/src/watchdog/model-selection.js +2 -2
  241. package/src/watchdog/permission-arbiter.js +1 -0
  242. package/src/watchdog/register-child.d.ts +2 -3
  243. package/src/watchdog/register-child.js +2 -3
  244. package/src/watchdog/review.d.ts +0 -5
  245. package/src/watchdog/review.js +4 -3
  246. package/src/watchdog/turn-delta.js +2 -1
  247. package/src/workflows/scripted-workflow.d.ts +2 -0
  248. package/src/workflows/scripted-workflow.js +344 -59
  249. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  250. package/src/workflows/structured-workflow-scripts.js +32 -11
  251. package/src/workflows/workflow-launch-record.d.ts +15 -6
  252. package/src/workflows/workflow-launch-record.js +30 -12
  253. package/src/workflows/workflow-receipt.js +36 -53
  254. package/src/workflows/workflow-resources.js +4 -4
  255. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  256. package/src/workflows/workflow-resume-claim.js +3 -3
  257. package/src/workflows/workflow-resume.d.ts +1 -1
  258. package/src/workflows/workflow-resume.js +13 -8
  259. package/src/workflows/workflow-script-worker.d.ts +13 -0
  260. package/src/workflows/workflow-script-worker.js +81 -0
  261. package/workflow-script-process.cjs +36 -0
  262. package/workflow-script-worker.cjs +4 -1
  263. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -0,0 +1,51 @@
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
+ export type FleetTranscriptEvent = {
7
+ kind: "assistant";
8
+ text: string;
9
+ model?: string;
10
+ timestamp?: number;
11
+ } | {
12
+ kind: "user";
13
+ text: string;
14
+ timestamp?: number;
15
+ } | {
16
+ kind: "tool";
17
+ toolCallId?: string;
18
+ name: string;
19
+ args?: string;
20
+ argsPayload?: string;
21
+ output?: string;
22
+ outputTruncated?: boolean;
23
+ status: "running" | "complete" | "error";
24
+ error?: string;
25
+ startedAt?: number;
26
+ endedAt?: number;
27
+ timestamp?: number;
28
+ } | {
29
+ kind: "notice";
30
+ text: string;
31
+ tone: "muted" | "warning" | "error";
32
+ timestamp?: number;
33
+ };
34
+ export interface FleetTranscript {
35
+ path: string;
36
+ events: FleetTranscriptEvent[];
37
+ truncated: boolean;
38
+ warning?: string;
39
+ /** The path was refused or the file could not be read, as opposed to a read that only skipped records. */
40
+ readFailed?: true;
41
+ }
42
+ export interface FleetTranscriptReadOptions {
43
+ trustedRoots: string[];
44
+ trustedFiles?: string[];
45
+ trustedFileRoot?: string;
46
+ maxRecords?: number;
47
+ maxBytes?: number;
48
+ }
49
+ export declare function objectValue(value: unknown): Record<string, unknown> | undefined;
50
+ export declare function safeTranscriptEvent(event: FleetTranscriptEvent): FleetTranscriptEvent;
51
+ export declare function readFleetTranscript(filePath: string, options: FleetTranscriptReadOptions): FleetTranscript;
@@ -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": {
@@ -2,7 +2,7 @@ import { Buffer } from "node:buffer";
2
2
  import { createHash } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
4
  import * as path from "node:path";
5
- import { resolveModelCandidate } from "../runs/shared/model-resolution.js";
5
+ import { knownModelProviders, resolveModelCandidate } from "../runs/shared/model-resolution.js";
6
6
  import { splitKnownThinkingSuffix, toModelInfo } from "./model-info.js";
7
7
  import { opencodeSessionHeaders } from "./opencode-session-headers.js";
8
8
  const MAX_INHERITED_SESSION_BYTES = 64 * 1024;
@@ -392,7 +392,7 @@ export async function createPrunedForkSessionWriter(ctx, config, signal) {
392
392
  if (!config.model?.trim())
393
393
  throw new Error("Pruned fork context requires config.forkContext.model.");
394
394
  const available = ctx.modelRegistry.getAvailable();
395
- const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider);
395
+ const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider, knownModelProviders(ctx.modelRegistry));
396
396
  if (!resolved)
397
397
  throw new Error(`Pruned fork model '${config.model}' did not match exactly one available model.`);
398
398
  const { baseModel } = splitKnownThinkingSuffix(resolved);
@@ -0,0 +1 @@
1
+ export declare function extractReportedProgress(toolName: string, args: unknown): string | undefined;
@@ -0,0 +1,12 @@
1
+ import { sanitizeDisplayText } from "./display-text.js";
2
+ const MAX_REPORTED_PROGRESS_LENGTH = 512;
3
+ export function extractReportedProgress(toolName, args) {
4
+ if (toolName !== "contact_supervisor" || typeof args !== "object" || args === null)
5
+ return undefined;
6
+ const call = args;
7
+ if (call.reason !== "progress_update" || typeof call.message !== "string")
8
+ return undefined;
9
+ const firstLine = call.message.split(/\r?\n/, 1)[0] ?? "";
10
+ const sanitized = sanitizeDisplayText(firstLine).replace(/^(?:progress|update):\s*/i, "");
11
+ return sanitized ? sanitized.slice(0, MAX_REPORTED_PROGRESS_LENGTH) : undefined;
12
+ }
@@ -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
+ }