@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,380 @@
1
+ /**
2
+ * output-file.ts — Streaming JSONL output file for agent transcripts.
3
+ *
4
+ * Creates a per-agent output file that streams conversation turns as JSONL,
5
+ * matching Claude Code's task output file format.
6
+ */
7
+
8
+ import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
9
+ import { appendFile } from "node:fs/promises";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { setImmediate as yieldToEventLoop } from "node:timers/promises";
13
+ import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
14
+ import { logSubagentIssue } from "./error-log.ts";
15
+ import { assistantDiagnosticContext, sanitizeDiagnosticText } from "./output-diagnostics.ts";
16
+
17
+ /**
18
+ * Project/global default for writing a subagent's `.output` transcript; a custom
19
+ * agent's `output_transcript` overrides it per agent.
20
+ *
21
+ * State lives here rather than in an index.ts closure because both spawn paths
22
+ * need it — the top-level Agent tool and the nested delegation tools. Same
23
+ * reason `scopeModels` lives in model-scope.ts: a setting only one path can read
24
+ * is a setting the other path silently ignores.
25
+ */
26
+ let outputTranscriptDefault = true;
27
+
28
+ export function getOutputTranscriptDefault(): boolean { return outputTranscriptDefault; }
29
+ export function setOutputTranscriptDefault(b: boolean): void { outputTranscriptDefault = b; }
30
+
31
+ /**
32
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
33
+ * - POSIX: "/home/user/project" → "home-user-project"
34
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
35
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
36
+ */
37
+ export function encodeCwd(cwd: string): string {
38
+ return cwd
39
+ .replace(/[/\\]/g, "-") // both separators → dash
40
+ .replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
41
+ .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
42
+ }
43
+
44
+ /**
45
+ * The per-session scratch directory, created if missing.
46
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
47
+ *
48
+ * Shared with the workflow tool, which persists each invocation's script here so
49
+ * iterating on one is edit-file-then-rerun — the same convention, one directory.
50
+ */
51
+ export function sessionTaskDir(cwd: string, sessionId: string): string {
52
+ const encoded = encodeCwd(cwd);
53
+ const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
54
+ mkdirSync(root, { recursive: true, mode: 0o700 });
55
+ // chmod is a no-op on Windows and throws on some Windows filesystems.
56
+ // On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
57
+ try {
58
+ chmodSync(root, 0o700);
59
+ } catch (err) {
60
+ if (process.platform !== "win32") throw err;
61
+ }
62
+ const dir = join(root, encoded, sessionId, "tasks");
63
+ mkdirSync(dir, { recursive: true });
64
+ return dir;
65
+ }
66
+
67
+ /** Create the output file path, ensuring the directory exists. */
68
+ export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
69
+ return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
70
+ }
71
+
72
+ /**
73
+ * Ensure a transcript file exists without disturbing what is already in it.
74
+ *
75
+ * A resume reuses the agent's existing transcript (same deterministic path), so
76
+ * it must never call `writeInitialEntry` — that truncates, discarding turns the
77
+ * completion notification still points the user at, and any history the session
78
+ * has since compacted away is gone for good. Appending nothing creates the file
79
+ * when this is the agent's first transcript and is a no-op when it is not.
80
+ */
81
+ export function ensureOutputFile(path: string): void {
82
+ try {
83
+ appendFileSync(path, "", "utf-8");
84
+ } catch { /* ignore — streaming writes are best-effort too */ }
85
+ }
86
+
87
+ /** Write the initial user prompt entry. */
88
+ export function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void {
89
+ const entry = {
90
+ isSidechain: true,
91
+ agentId,
92
+ type: "user",
93
+ message: { role: "user", content: prompt },
94
+ timestamp: new Date().toISOString(),
95
+ cwd,
96
+ };
97
+ writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
98
+ }
99
+
100
+ /**
101
+ * Lossless per-path output queues. Finalized lines are stringified at event
102
+ * time (snapshot semantics below) and appended by exactly one drain per file,
103
+ * so a resume subscribing a second stream to the same transcript queues behind
104
+ * the previous stream instead of interleaving. `pendingBytes` counts both
105
+ * queued and in-flight serialized bytes; appends are sliced into bounded
106
+ * batches, but a single oversized record is never split.
107
+ */
108
+ const OUTPUT_HIGH_WATER_BYTES = 1024 * 1024;
109
+ const OUTPUT_BATCH_BYTES = 256 * 1024;
110
+ const OUTPUT_BATCH_RECORDS = 64;
111
+
112
+ interface QueuedLine {
113
+ text: string;
114
+ bytes: number;
115
+ }
116
+
117
+ const CONSUMED_LINE: QueuedLine = { text: "", bytes: 0 };
118
+
119
+ interface DrainWaiter {
120
+ /** Resolve only once pending serialized bytes are strictly below this. */
121
+ below: number;
122
+ resolve: () => void;
123
+ }
124
+
125
+ interface PathQueue {
126
+ lines: QueuedLine[];
127
+ head: number;
128
+ pendingBytes: number;
129
+ draining: boolean;
130
+ waiters: Set<DrainWaiter>;
131
+ }
132
+
133
+ const outputQueues = new Map<string, PathQueue>();
134
+
135
+ function resolveWaiters(queue: PathQueue): void {
136
+ for (const waiter of [...queue.waiters]) {
137
+ if (queue.pendingBytes >= waiter.below) continue;
138
+ queue.waiters.delete(waiter);
139
+ waiter.resolve();
140
+ }
141
+ }
142
+
143
+ /** Wait until a path's accepted output falls below `below` bytes. No polling. */
144
+ function waitForOutput(path: string, below: number): Promise<void> {
145
+ const queue = outputQueues.get(path);
146
+ if (!queue || queue.pendingBytes < below) return Promise.resolve();
147
+ return new Promise<void>((resolve) => { queue.waiters.add({ below, resolve }); });
148
+ }
149
+
150
+ /**
151
+ * Write accepted records one batch at a time. Each append chunk is at most 256
152
+ * KiB or 64 records; the only exception is one larger indivisible record,
153
+ * which is written whole. Accounting is decremented in `finally`, so a failed
154
+ * best-effort write cannot strand pending bytes or waiters.
155
+ */
156
+ function drainQueue(path: string, queue: PathQueue): void {
157
+ if (queue.draining) return;
158
+ queue.draining = true;
159
+ void (async () => {
160
+ try {
161
+ while (queue.head < queue.lines.length) {
162
+ let records = 0;
163
+ let bytes = 0;
164
+ while (records < queue.lines.length - queue.head) {
165
+ const next = queue.lines[queue.head + records];
166
+ if (records > 0
167
+ && (records >= OUTPUT_BATCH_RECORDS || bytes + next.bytes > OUTPUT_BATCH_BYTES)) break;
168
+ bytes += next.bytes;
169
+ records += 1;
170
+ }
171
+ const end = queue.head + records;
172
+ const chunk = queue.lines.slice(queue.head, end);
173
+ // Release consumed payloads immediately; a long-lived busy path must not
174
+ // retain written strings. Compact geometrically instead of shifting the
175
+ // whole remaining queue for every bounded append (quadratic copying).
176
+ for (let index = queue.head; index < end; index++) queue.lines[index] = CONSUMED_LINE;
177
+ queue.head = end;
178
+ if (queue.head === queue.lines.length) {
179
+ queue.lines = [];
180
+ queue.head = 0;
181
+ } else if (queue.head >= OUTPUT_BATCH_RECORDS && queue.head * 2 >= queue.lines.length) {
182
+ queue.lines = queue.lines.slice(queue.head);
183
+ queue.head = 0;
184
+ }
185
+ try {
186
+ await appendFile(path, chunk.map(line => line.text).join(""), "utf-8");
187
+ } catch { /* best-effort file output; never write raw errors into the TUI */ }
188
+ finally {
189
+ queue.pendingBytes -= bytes;
190
+ resolveWaiters(queue);
191
+ }
192
+ }
193
+ } finally {
194
+ queue.draining = false;
195
+ if (queue.pendingBytes === 0 && queue.head === queue.lines.length) {
196
+ if (outputQueues.get(path) === queue) outputQueues.delete(path);
197
+ resolveWaiters(queue);
198
+ }
199
+ }
200
+ })();
201
+ }
202
+
203
+ function enqueueOutput(path: string, text: string): void {
204
+ let queue = outputQueues.get(path);
205
+ if (!queue) {
206
+ queue = { lines: [], head: 0, pendingBytes: 0, draining: false, waiters: new Set() };
207
+ outputQueues.set(path, queue);
208
+ }
209
+ const bytes = Buffer.byteLength(text, "utf-8");
210
+ queue.lines.push({ text, bytes });
211
+ queue.pendingBytes += bytes;
212
+ drainQueue(path, queue);
213
+ }
214
+
215
+ /**
216
+ * Wait until every queued write to one transcript file has landed. Resolves
217
+ * immediately when the file is idle; the stream cleanup function returns it
218
+ * so a caller can await the final flush.
219
+ */
220
+ export function drainOutputFile(path: string): Promise<void> {
221
+ return waitForOutput(path, 1);
222
+ }
223
+
224
+ /** Diagnostic only: serialized bytes accepted for a path but not yet written. */
225
+ export function pendingOutputBytes(path: string): number {
226
+ return outputQueues.get(path)?.pendingBytes ?? 0;
227
+ }
228
+
229
+ type OutputSession = Pick<AgentSession, "messages" | "retryAttempt" | "subscribe"> & {
230
+ agent?: Pick<AgentSession["agent"], "subscribe">;
231
+ };
232
+
233
+ /**
234
+ * Persist finalized events before retries can remove them from session.messages.
235
+ * Snapshot flushes also preserve eventless SDK additions (e.g. bashExecution).
236
+ * Lines are stringified at event time but written through an async per-file
237
+ * queue (see drainQueue). JSON serialization remains synchronous; disk waits
238
+ * and bounded producer checkpoints are asynchronous.
239
+ * A real Agent session also gets a producer listener registered after the
240
+ * session observer: it waits below the high-water mark at message_end and
241
+ * forces a drain at turn/run settlement, so slow disk stops the producer
242
+ * instead of growing an unbounded in-memory queue. Returns an idempotent final
243
+ * flush/unsubscribe that resolves once the flushed writes are on disk; never
244
+ * changes retry policy.
245
+ */
246
+ export function streamToOutputFile(
247
+ session: OutputSession,
248
+ path: string,
249
+ agentId: string,
250
+ cwd: string,
251
+ startIndex?: number,
252
+ // Best-effort label for the central error log. Only call sites that know the
253
+ // agent type pass it (the index.ts spawn paths); nested-tools.ts does not,
254
+ // so central-log records from that path carry agentId/session names only.
255
+ agentType?: string,
256
+ ): () => Promise<void> {
257
+ type Message = AgentSession["messages"][number];
258
+ const initial = session.messages;
259
+ // A resume supplies its pre-run boundary. Existing history on a reopened
260
+ // session is not new output either. Identity, not content/timestamp, keeps
261
+ // independent identical failures while deduplicating event + safety flush.
262
+ const seen = new WeakSet<Message>(initial.slice(0, startIndex ?? initial.length));
263
+ // writeInitialEntry already wrote the spawn prompt. New SDKs emit a system
264
+ // declaration first, so skipping array slot zero would duplicate the user.
265
+ let skipInitialUser = startIndex === undefined && !initial.some(msg => msg.role === "user");
266
+ let lastAssistant: ReturnType<typeof assistantDiagnosticContext> | undefined;
267
+ let closed = false;
268
+
269
+ // Lines are stringified at event time — messages are live SDK state, and a
270
+ // write must snapshot the finalized message, not a later mutation. enqueue
271
+ // adds the completed line to the shared per-path queue (one append in flight,
272
+ // bounded batches).
273
+ const append = (fields: Record<string, unknown>) => {
274
+ let line: string;
275
+ try {
276
+ line = JSON.stringify({
277
+ isSidechain: true, agentId, ...fields, timestamp: new Date().toISOString(), cwd,
278
+ }) + "\n";
279
+ } catch { /* best-effort file output; never write raw errors into the TUI */ return; }
280
+ enqueueOutput(path, line);
281
+ };
282
+
283
+ const capture = (msg: Message) => {
284
+ if (seen.has(msg) || (msg.role === "assistant" && msg.stopReason === "pending")) return;
285
+ seen.add(msg);
286
+ if (msg.role === "user" && skipInitialUser) {
287
+ skipInitialUser = false;
288
+ return;
289
+ }
290
+ append({
291
+ type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
292
+ // Keep normal content/usage intact. Don't duplicate a credential-bearing
293
+ // error in the regular row beside its sanitized diagnostic, or mutate SDK state.
294
+ message: msg.role === "assistant" && msg.errorMessage !== undefined
295
+ ? { ...msg, errorMessage: sanitizeDiagnosticText(msg.errorMessage) }
296
+ : msg,
297
+ });
298
+ if (msg.role === "assistant") {
299
+ lastAssistant = assistantDiagnosticContext(msg);
300
+ if (msg.stopReason === "error" || msg.stopReason === "aborted") {
301
+ const errorMessage = sanitizeDiagnosticText(msg.errorMessage);
302
+ append({ type: "diagnostic", diagnostic: {
303
+ event: msg.stopReason === "error" ? "assistant_error" : "assistant_aborted",
304
+ ...lastAssistant, errorMessage, attempt: session.retryAttempt,
305
+ } });
306
+ // Same event in the persistent cross-session aggregate (see error-log.ts).
307
+ logSubagentIssue({ kind: "attempt_error", agentId, agentType, ...lastAssistant,
308
+ errorMessage, attempt: session.retryAttempt });
309
+ }
310
+ }
311
+ };
312
+ const flush = () => { for (const msg of session.messages) capture(msg); };
313
+
314
+ // Observation snapshots happen synchronously in the session listener, before
315
+ // the producer listener below is registered. AgentSession installs its own
316
+ // agent listener in the constructor, so this is also the public observer order
317
+ // Agent.processEvents awaits.
318
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
319
+ if (closed) return;
320
+ if (event.type === "message_end") capture(event.message);
321
+ if (event.type === "auto_retry_start") {
322
+ const errorMessage = sanitizeDiagnosticText(event.errorMessage);
323
+ append({ type: "diagnostic", diagnostic: {
324
+ event: event.type, ...lastAssistant, attempt: event.attempt, maxAttempts: event.maxAttempts,
325
+ delayMs: event.delayMs, errorMessage,
326
+ } });
327
+ logSubagentIssue({ kind: "retry_start", agentId, agentType, ...lastAssistant,
328
+ attempt: event.attempt, maxAttempts: event.maxAttempts, delayMs: event.delayMs, errorMessage });
329
+ }
330
+ if (event.type === "auto_retry_end") {
331
+ const finalError = sanitizeDiagnosticText(event.finalError);
332
+ append({ type: "diagnostic", diagnostic: {
333
+ event: event.type, ...lastAssistant, attempt: event.attempt, success: event.success,
334
+ finalError,
335
+ } });
336
+ logSubagentIssue({ kind: "retry_end", agentId, agentType, ...lastAssistant,
337
+ attempt: event.attempt, success: event.success, finalError });
338
+ }
339
+ if (event.type === "turn_end" || event.type === "compaction_start") flush();
340
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
341
+ // Restored messages may be new objects. Mark the rebuilt history without
342
+ // writing it again; a subsequent overflow trim cannot strand this set.
343
+ for (const msg of session.messages) seen.add(msg);
344
+ }
345
+ });
346
+
347
+ // Attach after the observation subscription so capture (snapshot) precedes
348
+ // pressure. The producer hook is optional so legacy structural session
349
+ // doubles keep working; only the real SDK session supplies `session.agent`.
350
+ const producer = session.agent;
351
+ let finalizedSinceYield = 0;
352
+ const unsubscribeProducer = producer && typeof producer.subscribe === "function"
353
+ ? producer.subscribe(async (event) => {
354
+ if (closed) return;
355
+ if (event.type === "message_end") {
356
+ if (pendingOutputBytes(path) >= OUTPUT_HIGH_WATER_BYTES) {
357
+ await waitForOutput(path, OUTPUT_HIGH_WATER_BYTES);
358
+ finalizedSinceYield = 0;
359
+ } else if (++finalizedSinceYield >= OUTPUT_BATCH_RECORDS) {
360
+ // Awaiting already-resolved promises is not an event-loop yield.
361
+ // Small records also need periodic macrotask progress below HWM.
362
+ finalizedSinceYield = 0;
363
+ await yieldToEventLoop();
364
+ }
365
+ } else if (event.type === "turn_end" || event.type === "agent_end") {
366
+ await drainOutputFile(path);
367
+ finalizedSinceYield = 0;
368
+ }
369
+ })
370
+ : undefined;
371
+
372
+ return () => {
373
+ if (closed) return drainOutputFile(path);
374
+ closed = true;
375
+ unsubscribe();
376
+ unsubscribeProducer?.();
377
+ flush();
378
+ return drainOutputFile(path);
379
+ };
380
+ }
package/src/prompts.ts ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * prompts.ts — System prompt builder for agents.
3
+ */
4
+
5
+ import type { AgentConfig, EnvInfo } from "./types.ts";
6
+
7
+ /** Extra sections to inject into the system prompt (memory, skills, etc.). */
8
+ export interface PromptExtras {
9
+ /** Persistent memory content to inject (first 200 lines of MEMORY.md + instructions). */
10
+ memoryBlock?: string;
11
+ /**
12
+ * Built-in pin fallback notice (Explore/Plan pin named an unavailable
13
+ * provider, so the parent model is driving). Surfaced in the child's
14
+ * context so the substitution is visible, not silent.
15
+ */
16
+ pinFallbackNotice?: string;
17
+ /** Preloaded skill contents to inject. */
18
+ skillBlocks?: { name: string; content: string }[];
19
+ /**
20
+ * Parent directory the worktree copy was created from. Set only for
21
+ * `isolation: "worktree"` spawns — triggers the block that tells the agent
22
+ * to stay in the copy.
23
+ */
24
+ worktreeBase?: string;
25
+ /**
26
+ * Set only for a workflow's own children, and only when they have no
27
+ * `StructuredOutput` tool to answer through.
28
+ *
29
+ * A workflow child's final text is not read by a human — it is the value
30
+ * `agent()` resolves to, and the script interpolates it straight into the
31
+ * next stage's prompt. Without this, children answer the way every other
32
+ * subagent does (a report addressed to a reader), and the padding becomes
33
+ * input tokens for the stage downstream. Claude Code's `Workflow` tool
34
+ * documents this contract to the script-writing model; this is the end of it
35
+ * that makes the documentation true.
36
+ *
37
+ * Deliberately NOT applied to every subagent. In pi an ordinary agent's
38
+ * output IS read by a human — through FleetView, the conversation viewer and
39
+ * `get_subagent_result` — so terse raw data would be the wrong answer there.
40
+ */
41
+ workflowChild?: boolean;
42
+ }
43
+
44
+ /**
45
+ * Build the system prompt for an agent from its config.
46
+ *
47
+ * - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
48
+ * - "append" mode: parent system prompt + sub-agent context + env header + config.systemPrompt
49
+ * - "append" with empty systemPrompt: pure parent clone
50
+ *
51
+ * Both modes include an `<active_agent name="${config.name}"/>` tag so downstream
52
+ * extensions (e.g. permission/policy systems) can resolve per-agent policy
53
+ * inside the child session by parsing the system prompt. In replace mode the tag
54
+ * is prepended; in append mode it follows the shared inherited content so the
55
+ * parent prompt forms an identical, cacheable byte prefix with the parent
56
+ * session (the LLM's KV cache can then reuse those tokens across every spawn).
57
+ *
58
+ * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
59
+ * @param extras Optional extra sections to inject (memory, preloaded skills).
60
+ */
61
+ export function buildAgentPrompt(
62
+ config: AgentConfig,
63
+ cwd: string,
64
+ env: EnvInfo,
65
+ parentSystemPrompt?: string,
66
+ extras?: PromptExtras,
67
+ ): string {
68
+ const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
69
+
70
+ const envBlock = `# Environment
71
+ Working directory: ${cwd}
72
+ ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
73
+ Platform: ${env.platform}`;
74
+
75
+ // A worktree agent is told its cwd twice: by the env block above (the copy)
76
+ // and by whatever names the main checkout — the inherited parent prompt in
77
+ // append mode, or the task prompt in either mode. It follows the latter and
78
+ // works in the shared tree (#187), so resolve the contradiction explicitly.
79
+ const worktreeBlock = extras?.worktreeBase
80
+ ? `\n\n<worktree_isolation>
81
+ Your working directory is an isolated git worktree copy of ${extras.worktreeBase}.
82
+ Work only inside it — never in ${extras.worktreeBase}, even if other instructions name that path as your working directory.
83
+ </worktree_isolation>`
84
+ : "";
85
+
86
+ // The script, not a person, reads what this child returns — see
87
+ // `PromptExtras.workflowChild` for why only workflow children get this.
88
+ const workflowBlock = extras?.workflowChild
89
+ ? `\n\n<workflow_child>
90
+ Your final message IS the return value of this task. A workflow script captures it and passes it to the next stage; no person reads it.
91
+ Return only the answer, in exactly the shape the prompt asks for — no preamble, no summary of what you did, no offer to continue.
92
+ </workflow_child>`
93
+ : "";
94
+
95
+ // Build optional extras suffix
96
+ const extraSections: string[] = [];
97
+ if (extras?.pinFallbackNotice) {
98
+ extraSections.push(`NOTE: ${extras.pinFallbackNotice}`);
99
+ }
100
+ if (extras?.memoryBlock) {
101
+ extraSections.push(extras.memoryBlock);
102
+ }
103
+ if (extras?.skillBlocks?.length) {
104
+ for (const skill of extras.skillBlocks) {
105
+ extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
106
+ }
107
+ }
108
+ const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
109
+
110
+ if (config.promptMode === "append") {
111
+ const identity = parentSystemPrompt || genericBase;
112
+
113
+ const bridge = `<sub_agent_context>
114
+ You are operating as a sub-agent invoked to handle a specific task.
115
+ - Use the read tool instead of cat/head/tail
116
+ - Use the edit tool instead of sed/awk
117
+ - Use the write tool instead of echo/heredoc
118
+ - Use the find tool instead of bash find/ls for file search
119
+ - Use the grep tool instead of bash grep/rg for content search
120
+ - Make independent tool calls in parallel
121
+ - Use absolute file paths
122
+ - Do not use emojis
123
+ - Be concise but complete
124
+ </sub_agent_context>`;
125
+
126
+ const customSection = config.systemPrompt?.trim()
127
+ ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
128
+ : "";
129
+
130
+ // Place shared/stable content first so the LLM's KV cache can reuse the
131
+ // inherited prefix across all subagent invocations. The parent prompt is
132
+ // placed verbatim (no wrapper tag) so it forms an identical byte prefix
133
+ // with the parent session, maximising KV cache hits. The <active_agent>
134
+ // tag and env block vary per call and are placed after the cached prefix.
135
+ return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + worktreeBlock + workflowBlock + customSection + extrasSuffix;
136
+ }
137
+
138
+ // "replace" mode — env header + the config's full system prompt
139
+ const replaceHeader = `You are a pi coding agent sub-agent.
140
+ You have been invoked to handle a specific task autonomously.
141
+
142
+ ${envBlock}`;
143
+
144
+ return activeAgentTag + replaceHeader + worktreeBlock + workflowBlock + "\n\n" + config.systemPrompt + extrasSuffix;
145
+ }
146
+
147
+ /** Fallback base prompt when parent system prompt is unavailable in append mode. */
148
+ const genericBase = `# Role
149
+ You are a general-purpose coding agent for complex, multi-step tasks.
150
+ You have full access to read, write, edit files, and execute commands.
151
+ Do what has been asked; nothing more, nothing less.`;