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