@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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 (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  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 +18 -0
  9. package/dist/active-agents-prompt.js +34 -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 +123 -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 +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,258 @@
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 type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
13
+ import { logSubagentIssue } from "./error-log.js";
14
+ import { assistantDiagnosticContext, sanitizeDiagnosticText } from "./output-diagnostics.js";
15
+
16
+ /**
17
+ * Project/global default for writing a subagent's `.output` transcript; a custom
18
+ * agent's `output_transcript` overrides it per agent.
19
+ *
20
+ * State lives here rather than in an index.ts closure because both spawn paths
21
+ * need it — the top-level Agent tool and the nested delegation tools. Same
22
+ * reason `scopeModels` lives in model-scope.ts: a setting only one path can read
23
+ * is a setting the other path silently ignores.
24
+ */
25
+ let outputTranscriptDefault = true;
26
+
27
+ export function getOutputTranscriptDefault(): boolean { return outputTranscriptDefault; }
28
+ export function setOutputTranscriptDefault(b: boolean): void { outputTranscriptDefault = b; }
29
+
30
+ /**
31
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
32
+ * - POSIX: "/home/user/project" → "home-user-project"
33
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
34
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
35
+ */
36
+ export function encodeCwd(cwd: string): string {
37
+ return cwd
38
+ .replace(/[/\\]/g, "-") // both separators → dash
39
+ .replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
40
+ .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
41
+ }
42
+
43
+ /**
44
+ * The per-session scratch directory, created if missing.
45
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
46
+ *
47
+ * Shared with the workflow tool, which persists each invocation's script here so
48
+ * iterating on one is edit-file-then-rerun — the same convention, one directory.
49
+ */
50
+ export function sessionTaskDir(cwd: string, sessionId: string): string {
51
+ const encoded = encodeCwd(cwd);
52
+ const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
53
+ mkdirSync(root, { recursive: true, mode: 0o700 });
54
+ // chmod is a no-op on Windows and throws on some Windows filesystems.
55
+ // On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
56
+ try {
57
+ chmodSync(root, 0o700);
58
+ } catch (err) {
59
+ if (process.platform !== "win32") throw err;
60
+ }
61
+ const dir = join(root, encoded, sessionId, "tasks");
62
+ mkdirSync(dir, { recursive: true });
63
+ return dir;
64
+ }
65
+
66
+ /** Create the output file path, ensuring the directory exists. */
67
+ export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
68
+ return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
69
+ }
70
+
71
+ /**
72
+ * Ensure a transcript file exists without disturbing what is already in it.
73
+ *
74
+ * A resume reuses the agent's existing transcript (same deterministic path), so
75
+ * it must never call `writeInitialEntry` — that truncates, discarding turns the
76
+ * completion notification still points the user at, and any history the session
77
+ * has since compacted away is gone for good. Appending nothing creates the file
78
+ * when this is the agent's first transcript and is a no-op when it is not.
79
+ */
80
+ export function ensureOutputFile(path: string): void {
81
+ try {
82
+ appendFileSync(path, "", "utf-8");
83
+ } catch { /* ignore — streaming writes are best-effort too */ }
84
+ }
85
+
86
+ /** Write the initial user prompt entry. */
87
+ export function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void {
88
+ const entry = {
89
+ isSidechain: true,
90
+ agentId,
91
+ type: "user",
92
+ message: { role: "user", content: prompt },
93
+ timestamp: new Date().toISOString(),
94
+ cwd,
95
+ };
96
+ writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
97
+ }
98
+
99
+ /**
100
+ * Serialized write chains for transcript files: at most one in-flight append
101
+ * per file. A drain coalesces everything queued while it writes — a burst of
102
+ * finalized messages costs one append syscall per batch, not per message — and
103
+ * a resume subscribing a second stream to the same transcript chains after the
104
+ * previous stream's pending writes instead of interleaving with them.
105
+ */
106
+ const writeChains = new Map<string, Promise<void>>();
107
+
108
+ function chainWrite(path: string, run: () => Promise<void>): Promise<void> {
109
+ const chained = (writeChains.get(path) ?? Promise.resolve()).then(run);
110
+ writeChains.set(path, chained);
111
+ void chained.finally(() => {
112
+ if (writeChains.get(path) === chained) writeChains.delete(path);
113
+ });
114
+ return chained;
115
+ }
116
+
117
+ /**
118
+ * Wait until every queued write to one transcript file has landed. Resolves
119
+ * immediately when the file is idle; the stream cleanup function returns it
120
+ * so a caller can await the final flush.
121
+ */
122
+ export function drainOutputFile(path: string): Promise<void> {
123
+ return writeChains.get(path) ?? Promise.resolve();
124
+ }
125
+
126
+ /**
127
+ * Persist finalized events before retries can remove them from session.messages.
128
+ * Snapshot flushes also preserve eventless SDK additions (e.g. bashExecution).
129
+ * Lines are stringified at event time but written through an async per-file
130
+ * queue (see chainWrite), so message-sized JSON work never blocks the loop.
131
+ * Returns an idempotent final flush/unsubscribe that resolves once the flushed
132
+ * writes are on disk; never changes retry policy.
133
+ */
134
+ export function streamToOutputFile(
135
+ session: AgentSession,
136
+ path: string,
137
+ agentId: string,
138
+ cwd: string,
139
+ startIndex?: number,
140
+ // Best-effort label for the central error log. Only call sites that know the
141
+ // agent type pass it (the index.ts spawn paths); nested-tools.ts does not,
142
+ // so central-log records from that path carry agentId/session names only.
143
+ agentType?: string,
144
+ ): () => void {
145
+ type Message = AgentSession["messages"][number];
146
+ const initial = session.messages;
147
+ // A resume supplies its pre-run boundary. Existing history on a reopened
148
+ // session is not new output either. Identity, not content/timestamp, keeps
149
+ // independent identical failures while deduplicating event + safety flush.
150
+ const seen = new WeakSet<Message>(initial.slice(0, startIndex ?? initial.length));
151
+ // writeInitialEntry already wrote the spawn prompt. New SDKs emit a system
152
+ // declaration first, so skipping array slot zero would duplicate the user.
153
+ let skipInitialUser = startIndex === undefined && !initial.some(msg => msg.role === "user");
154
+ let lastAssistant: ReturnType<typeof assistantDiagnosticContext> | undefined;
155
+ let closed = false;
156
+
157
+ // Queued lines are stringified at event time — messages are live SDK state,
158
+ // and a write must snapshot the finalized message, not a later mutation. The
159
+ // drain coalesces everything queued while a write is in flight.
160
+ let batch: string[] = [];
161
+ let draining = false;
162
+
163
+ const drain = async (): Promise<void> => {
164
+ try {
165
+ while (batch.length > 0) {
166
+ const chunk = batch;
167
+ batch = [];
168
+ try {
169
+ await appendFile(path, chunk.join(""), "utf-8");
170
+ } catch { /* best-effort file output; never write raw errors into the TUI */ }
171
+ }
172
+ } finally {
173
+ draining = false;
174
+ }
175
+ };
176
+
177
+ const append = (fields: Record<string, unknown>) => {
178
+ let line: string;
179
+ try {
180
+ line = JSON.stringify({
181
+ isSidechain: true, agentId, ...fields, timestamp: new Date().toISOString(), cwd,
182
+ }) + "\n";
183
+ } catch { /* best-effort file output; never write raw errors into the TUI */ return; }
184
+ batch.push(line);
185
+ if (!draining) {
186
+ draining = true;
187
+ void chainWrite(path, drain);
188
+ }
189
+ };
190
+
191
+ const capture = (msg: Message) => {
192
+ if (seen.has(msg) || (msg.role === "assistant" && msg.stopReason === "pending")) return;
193
+ seen.add(msg);
194
+ if (msg.role === "user" && skipInitialUser) {
195
+ skipInitialUser = false;
196
+ return;
197
+ }
198
+ append({
199
+ type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
200
+ // Keep normal content/usage intact. Don't duplicate a credential-bearing
201
+ // error in the regular row beside its sanitized diagnostic, or mutate SDK state.
202
+ message: msg.role === "assistant" && msg.errorMessage !== undefined
203
+ ? { ...msg, errorMessage: sanitizeDiagnosticText(msg.errorMessage) }
204
+ : msg,
205
+ });
206
+ if (msg.role === "assistant") {
207
+ lastAssistant = assistantDiagnosticContext(msg);
208
+ if (msg.stopReason === "error" || msg.stopReason === "aborted") {
209
+ const errorMessage = sanitizeDiagnosticText(msg.errorMessage);
210
+ append({ type: "diagnostic", diagnostic: {
211
+ event: msg.stopReason === "error" ? "assistant_error" : "assistant_aborted",
212
+ ...lastAssistant, errorMessage, attempt: session.retryAttempt,
213
+ } });
214
+ // Same event in the persistent cross-session aggregate (see error-log.ts).
215
+ logSubagentIssue({ kind: "attempt_error", agentId, agentType, ...lastAssistant,
216
+ errorMessage, attempt: session.retryAttempt });
217
+ }
218
+ }
219
+ };
220
+ const flush = () => { for (const msg of session.messages) capture(msg); };
221
+
222
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
223
+ if (closed) return;
224
+ if (event.type === "message_end") capture(event.message);
225
+ if (event.type === "auto_retry_start") {
226
+ const errorMessage = sanitizeDiagnosticText(event.errorMessage);
227
+ append({ type: "diagnostic", diagnostic: {
228
+ event: event.type, ...lastAssistant, attempt: event.attempt, maxAttempts: event.maxAttempts,
229
+ delayMs: event.delayMs, errorMessage,
230
+ } });
231
+ logSubagentIssue({ kind: "retry_start", agentId, agentType, ...lastAssistant,
232
+ attempt: event.attempt, maxAttempts: event.maxAttempts, delayMs: event.delayMs, errorMessage });
233
+ }
234
+ if (event.type === "auto_retry_end") {
235
+ const finalError = sanitizeDiagnosticText(event.finalError);
236
+ append({ type: "diagnostic", diagnostic: {
237
+ event: event.type, ...lastAssistant, attempt: event.attempt, success: event.success,
238
+ finalError,
239
+ } });
240
+ logSubagentIssue({ kind: "retry_end", agentId, agentType, ...lastAssistant,
241
+ attempt: event.attempt, success: event.success, finalError });
242
+ }
243
+ if (event.type === "turn_end" || event.type === "compaction_start") flush();
244
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
245
+ // Restored messages may be new objects. Mark the rebuilt history without
246
+ // writing it again; a subsequent overflow trim cannot strand this set.
247
+ for (const msg of session.messages) seen.add(msg);
248
+ }
249
+ });
250
+
251
+ return () => {
252
+ if (closed) return drainOutputFile(path);
253
+ closed = true;
254
+ unsubscribe();
255
+ flush();
256
+ return drainOutputFile(path);
257
+ };
258
+ }
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.js";
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.`;