@diousk/pi-subagents-fast 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 (183) hide show
  1. package/CHANGELOG.md +808 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1034 -0
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +125 -0
  11. package/dist/agent-file-toggle.js +260 -0
  12. package/dist/agent-manager.d.ts +472 -0
  13. package/dist/agent-manager.js +1338 -0
  14. package/dist/agent-runner.d.ts +312 -0
  15. package/dist/agent-runner.js +1034 -0
  16. package/dist/agent-types.d.ts +119 -0
  17. package/dist/agent-types.js +286 -0
  18. package/dist/child-context.d.ts +2 -0
  19. package/dist/child-context.js +12 -0
  20. package/dist/context.d.ts +12 -0
  21. package/dist/context.js +56 -0
  22. package/dist/cross-extension-rpc.d.ts +66 -0
  23. package/dist/cross-extension-rpc.js +138 -0
  24. package/dist/custom-agents.d.ts +54 -0
  25. package/dist/custom-agents.js +316 -0
  26. package/dist/default-agents.d.ts +7 -0
  27. package/dist/default-agents.js +122 -0
  28. package/dist/enabled-models.d.ts +49 -0
  29. package/dist/enabled-models.js +145 -0
  30. package/dist/env.d.ts +6 -0
  31. package/dist/env.js +28 -0
  32. package/dist/group-join.d.ts +32 -0
  33. package/dist/group-join.js +116 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +3682 -0
  36. package/dist/invocation-config.d.ts +107 -0
  37. package/dist/invocation-config.js +83 -0
  38. package/dist/memory.d.ts +53 -0
  39. package/dist/memory.js +165 -0
  40. package/dist/mention-clone.d.ts +87 -0
  41. package/dist/mention-clone.js +153 -0
  42. package/dist/mention.d.ts +81 -0
  43. package/dist/mention.js +131 -0
  44. package/dist/model-resolver.d.ts +36 -0
  45. package/dist/model-resolver.js +95 -0
  46. package/dist/model-scope.d.ts +49 -0
  47. package/dist/model-scope.js +48 -0
  48. package/dist/nested-tools.d.ts +55 -0
  49. package/dist/nested-tools.js +299 -0
  50. package/dist/output-file.d.ts +43 -0
  51. package/dist/output-file.js +142 -0
  52. package/dist/prompts.d.ts +55 -0
  53. package/dist/prompts.js +91 -0
  54. package/dist/schedule-store.d.ts +38 -0
  55. package/dist/schedule-store.js +155 -0
  56. package/dist/schedule.d.ts +109 -0
  57. package/dist/schedule.js +359 -0
  58. package/dist/settings.d.ts +360 -0
  59. package/dist/settings.js +251 -0
  60. package/dist/skill-loader.d.ts +24 -0
  61. package/dist/skill-loader.js +93 -0
  62. package/dist/status-note.d.ts +61 -0
  63. package/dist/status-note.js +85 -0
  64. package/dist/structured-output.d.ts +61 -0
  65. package/dist/structured-output.js +112 -0
  66. package/dist/types.d.ts +371 -0
  67. package/dist/types.js +5 -0
  68. package/dist/ui/agent-mention.d.ts +82 -0
  69. package/dist/ui/agent-mention.js +187 -0
  70. package/dist/ui/agent-widget.d.ts +219 -0
  71. package/dist/ui/agent-widget.js +592 -0
  72. package/dist/ui/conversation-viewer.d.ts +120 -0
  73. package/dist/ui/conversation-viewer.js +578 -0
  74. package/dist/ui/fleet-list.d.ts +195 -0
  75. package/dist/ui/fleet-list.js +471 -0
  76. package/dist/ui/schedule-menu.d.ts +16 -0
  77. package/dist/ui/schedule-menu.js +94 -0
  78. package/dist/ui/select-item.d.ts +27 -0
  79. package/dist/ui/select-item.js +34 -0
  80. package/dist/ui/viewer-keys.d.ts +20 -0
  81. package/dist/ui/viewer-keys.js +17 -0
  82. package/dist/ui/workflow-card.d.ts +175 -0
  83. package/dist/ui/workflow-card.js +332 -0
  84. package/dist/ui/workflow-dialog.d.ts +305 -0
  85. package/dist/ui/workflow-dialog.js +843 -0
  86. package/dist/ui/workflow-menu.d.ts +60 -0
  87. package/dist/ui/workflow-menu.js +147 -0
  88. package/dist/usage.d.ts +135 -0
  89. package/dist/usage.js +120 -0
  90. package/dist/workflow/collisions.d.ts +95 -0
  91. package/dist/workflow/collisions.js +88 -0
  92. package/dist/workflow/entry.d.ts +32 -0
  93. package/dist/workflow/entry.js +29 -0
  94. package/dist/workflow/host.d.ts +62 -0
  95. package/dist/workflow/host.js +362 -0
  96. package/dist/workflow/journal.d.ts +97 -0
  97. package/dist/workflow/journal.js +120 -0
  98. package/dist/workflow/json-schema.d.ts +51 -0
  99. package/dist/workflow/json-schema.js +111 -0
  100. package/dist/workflow/meta.d.ts +67 -0
  101. package/dist/workflow/meta.js +317 -0
  102. package/dist/workflow/progress.d.ts +224 -0
  103. package/dist/workflow/progress.js +361 -0
  104. package/dist/workflow/runtime.d.ts +334 -0
  105. package/dist/workflow/runtime.js +830 -0
  106. package/dist/workflow/saved.d.ts +90 -0
  107. package/dist/workflow/saved.js +203 -0
  108. package/dist/workflow/task.d.ts +136 -0
  109. package/dist/workflow/task.js +207 -0
  110. package/dist/workflow/tool-description.d.ts +38 -0
  111. package/dist/workflow/tool-description.js +199 -0
  112. package/dist/workflow/worker-source.d.ts +47 -0
  113. package/dist/workflow/worker-source.js +778 -0
  114. package/dist/worktree.d.ts +52 -0
  115. package/dist/worktree.js +164 -0
  116. package/dist/xml.d.ts +10 -0
  117. package/dist/xml.js +12 -0
  118. package/docs/rpc.md +183 -0
  119. package/docs/workflows.md +437 -0
  120. package/examples/agent-tool-description.md +42 -0
  121. package/examples/workflows/compose.js +51 -0
  122. package/examples/workflows/fan-out-audit.js +47 -0
  123. package/examples/workflows/gated-fix.js +60 -0
  124. package/examples/workflows/lib/count-child.js +27 -0
  125. package/examples/workflows/review-panel.js +63 -0
  126. package/examples/workflows/structured-findings.js +78 -0
  127. package/package.json +68 -0
  128. package/src/abortable.ts +43 -0
  129. package/src/agent-color.ts +161 -0
  130. package/src/agent-file-toggle.ts +270 -0
  131. package/src/agent-manager.ts +1581 -0
  132. package/src/agent-runner.ts +1286 -0
  133. package/src/agent-types.ts +346 -0
  134. package/src/child-context.ts +15 -0
  135. package/src/context.ts +58 -0
  136. package/src/cross-extension-rpc.ts +198 -0
  137. package/src/custom-agents.ts +333 -0
  138. package/src/default-agents.ts +126 -0
  139. package/src/enabled-models.ts +180 -0
  140. package/src/env.ts +33 -0
  141. package/src/group-join.ts +141 -0
  142. package/src/index.ts +3991 -0
  143. package/src/invocation-config.ts +155 -0
  144. package/src/memory.ts +179 -0
  145. package/src/mention-clone.ts +196 -0
  146. package/src/mention.ts +141 -0
  147. package/src/model-resolver.ts +118 -0
  148. package/src/model-scope.ts +70 -0
  149. package/src/nested-tools.ts +422 -0
  150. package/src/output-file.ts +155 -0
  151. package/src/prompts.ts +142 -0
  152. package/src/schedule-store.ts +153 -0
  153. package/src/schedule.ts +386 -0
  154. package/src/settings.ts +587 -0
  155. package/src/skill-loader.ts +102 -0
  156. package/src/status-note.ts +90 -0
  157. package/src/structured-output.ts +130 -0
  158. package/src/types.ts +384 -0
  159. package/src/ui/agent-mention.ts +216 -0
  160. package/src/ui/agent-widget.ts +664 -0
  161. package/src/ui/conversation-viewer.ts +589 -0
  162. package/src/ui/fleet-list.ts +543 -0
  163. package/src/ui/schedule-menu.ts +105 -0
  164. package/src/ui/select-item.ts +45 -0
  165. package/src/ui/viewer-keys.ts +39 -0
  166. package/src/ui/workflow-card.ts +470 -0
  167. package/src/ui/workflow-dialog.ts +1115 -0
  168. package/src/ui/workflow-menu.ts +193 -0
  169. package/src/usage.ts +167 -0
  170. package/src/workflow/collisions.ts +123 -0
  171. package/src/workflow/entry.ts +47 -0
  172. package/src/workflow/host.ts +403 -0
  173. package/src/workflow/journal.ts +164 -0
  174. package/src/workflow/json-schema.ts +128 -0
  175. package/src/workflow/meta.ts +325 -0
  176. package/src/workflow/progress.ts +550 -0
  177. package/src/workflow/runtime.ts +1219 -0
  178. package/src/workflow/saved.ts +217 -0
  179. package/src/workflow/task.ts +302 -0
  180. package/src/workflow/tool-description.ts +200 -0
  181. package/src/workflow/worker-source.ts +781 -0
  182. package/src/worktree.ts +205 -0
  183. package/src/xml.ts +13 -0
@@ -0,0 +1,299 @@
1
+ import { defineTool, } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "@sinclair/typebox";
3
+ import { abortable } from "./abortable.js";
4
+ import { buildAgentRegistry, getAgentConfigIn, getAvailableTypesIn, resolveEnabledTypeIn, resolveTypeIn, } from "./agent-types.js";
5
+ import { loadCustomAgents } from "./custom-agents.js";
6
+ import { isolationParam, resolveAgentInvocationConfig } from "./invocation-config.js";
7
+ import { resolveModel } from "./model-resolver.js";
8
+ import { checkModelScope } from "./model-scope.js";
9
+ import { createOutputFilePath, getOutputTranscriptDefault, streamToOutputFile, writeInitialEntry, } from "./output-file.js";
10
+ import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
11
+ import { addUsage } from "./usage.js";
12
+ import { isWorktreeIsolationEnabled } from "./worktree.js";
13
+ /**
14
+ * Hard ceiling on nesting for every branch: main session = 0, its subagents = 1,
15
+ * their children = 2. `0`/`1` disables nesting entirely. Set from
16
+ * `subagents.json` (`maxSubagentDepth`). Read when a subagent session is built,
17
+ * so a change applies to sessions started after it.
18
+ */
19
+ let maxSubagentDepth = 2;
20
+ export function getMaxSubagentDepth() { return maxSubagentDepth; }
21
+ export function setMaxSubagentDepth(n) { maxSubagentDepth = Math.max(0, Math.floor(n)); }
22
+ const NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"];
23
+ function textResult(text, isError = false) {
24
+ return { content: [{ type: "text", text }], isError, details: {} };
25
+ }
26
+ function ownsRecord(record, parentAgentId) {
27
+ return record?.parentAgentId === parentAgentId;
28
+ }
29
+ function formatRecord(record, position) {
30
+ if (record.status === "error") {
31
+ return `Agent failed: ${record.error ?? "unknown error"}${partialOutputSuffix(record)}`;
32
+ }
33
+ if (record.status === "queued" || record.status === "running") {
34
+ return `Agent ${record.id} is ${record.status}.`;
35
+ }
36
+ // A truncated run must not read as a finished one. The top-level path carries
37
+ // this in its result headline; a nested result has no headline, so the note
38
+ // leads — appended, it would look like part of the child's own output.
39
+ const text = record.result?.trim() || record.error?.trim() || "No output.";
40
+ const note = position === "inline"
41
+ ? getForegroundOutcomeNote(record.status)
42
+ : getStatusNote(record.status);
43
+ return note ? `Nested agent${note}.\n\n${text}` : text;
44
+ }
45
+ /** Build child-safe orchestration tools scoped to one parent agent instance. */
46
+ export function createNestedSubagentTools(context) {
47
+ // Agents resolve from a registry built for THIS branch's config root (under
48
+ // worktree isolation, the copy). Never via registerAgents — that is
49
+ // process-global state shared with the main session and every other agent.
50
+ const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd));
51
+ const allowedTypesIn = (registry) => context.allowedSubagents === "all"
52
+ ? undefined
53
+ : new Set(context.allowedSubagents.map(name => resolveTypeIn(registry, name) ?? name));
54
+ const availableIn = (registry) => {
55
+ const allowed = allowedTypesIn(registry);
56
+ return getAvailableTypesIn(registry).filter(name => allowed === undefined || allowed.has(name));
57
+ };
58
+ const agentTool = defineTool({
59
+ name: NESTED_TOOL_NAMES[0],
60
+ label: "Agent",
61
+ description: "Launch a child-safe nested subagent for bounded delegated work. " +
62
+ "Only use agent types allowed by this parent agent; nesting is depth-limited.",
63
+ parameters: Type.Object({
64
+ prompt: Type.String({ description: "Self-contained task for the nested agent." }),
65
+ description: Type.String({ description: "Short 3-5 word task description." }),
66
+ subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
67
+ model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
68
+ thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
69
+ max_turns: Type.Optional(Type.Number({ minimum: 1 })),
70
+ run_in_background: Type.Optional(Type.Boolean({
71
+ description: "Defaults to false for nested spawns — the call blocks and returns the child's result inline. Set true only for work you will collect later with get_subagent_result; a detached child is stopped when you finish.",
72
+ })),
73
+ resume: Type.Optional(Type.String({ description: "Resume a nested agent owned by this parent." })),
74
+ isolated: Type.Optional(Type.Boolean()),
75
+ inherit_context: Type.Optional(Type.Boolean()),
76
+ ...isolationParam(isWorktreeIsolationEnabled()),
77
+ }),
78
+ execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
79
+ if (params.resume) {
80
+ const existing = context.manager.getRecord(params.resume);
81
+ if (!ownsRecord(existing, context.parentAgentId)) {
82
+ return textResult(`Nested agent not found or not owned by this parent: "${params.resume}".`, true);
83
+ }
84
+ const resumed = await context.manager.resume(params.resume, params.prompt, signal);
85
+ return resumed
86
+ ? textResult(formatRecord(resumed, "inline"), resumed.status === "error")
87
+ : textResult(`Failed to resume nested agent "${params.resume}".`, true);
88
+ }
89
+ if (context.depth >= context.maxSubagentDepth) {
90
+ return textResult(`Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`, true);
91
+ }
92
+ // Reloaded per call so new agent files are picked up without a restart.
93
+ const registry = loadRegistry();
94
+ const rawType = params.subagent_type;
95
+ // Strict resolve, never the fallback policy: a project-level
96
+ // `fallbackSubagent` must not hand a nested caller an agent its allowlist
97
+ // never named. The list stays allowlist-filtered so a typo can't enumerate
98
+ // agents this parent may not reach.
99
+ const resolvedType = resolveEnabledTypeIn(registry, rawType);
100
+ if (resolvedType === undefined) {
101
+ return textResult(`Unknown or disabled nested agent type: "${rawType}". Allowed: ${availableIn(registry).join(", ") || "none"}.`, true);
102
+ }
103
+ const allowed = allowedTypesIn(registry);
104
+ if (allowed !== undefined && !allowed.has(resolvedType)) {
105
+ return textResult(`Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`, true);
106
+ }
107
+ const config = getAgentConfigIn(registry, resolvedType);
108
+ // Foreground regardless of `backgroundByDefault` — see the reasoning on
109
+ // ResolveOptions. An explicit `true` here still opts in.
110
+ const invocation = resolveAgentInvocationConfig(config, params, {
111
+ worktreeAllowed: isWorktreeIsolationEnabled(),
112
+ defaultRunInBackground: false,
113
+ });
114
+ let model = ctx.model;
115
+ if (invocation.modelInput) {
116
+ const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
117
+ if (typeof resolvedModel === "string") {
118
+ if (invocation.modelFromParams)
119
+ return textResult(resolvedModel, true);
120
+ }
121
+ else {
122
+ model = resolvedModel;
123
+ }
124
+ }
125
+ // Same scopeModels policy as the top-level Agent tool — a nested spawn
126
+ // must not escape the allowlist. A "warn" verdict proceeds silently:
127
+ // child sessions have no UI surface to toast to.
128
+ const scopeVerdict = checkModelScope({
129
+ model,
130
+ cwd: context.configCwd,
131
+ modelRegistry: ctx.modelRegistry,
132
+ callerSupplied: invocation.modelFromParams,
133
+ agentLabel: config?.displayName ?? resolvedType,
134
+ modelInput: invocation.modelInput,
135
+ });
136
+ if (scopeVerdict.kind === "error")
137
+ return textResult(scopeVerdict.message, true);
138
+ // The whole branch shares the root session's transcript directory; read it
139
+ // off the owning parent rather than this child session's own id.
140
+ const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId;
141
+ const childDepth = context.depth + 1;
142
+ const options = {
143
+ description: params.description,
144
+ model,
145
+ maxTurns: invocation.maxTurns,
146
+ isolated: invocation.isolated,
147
+ inheritContext: invocation.inheritContext,
148
+ thinkingLevel: invocation.thinking,
149
+ isolation: invocation.isolation,
150
+ invocation: {
151
+ thinking: invocation.thinking,
152
+ maxTurns: invocation.maxTurns,
153
+ isolated: invocation.isolated,
154
+ inheritContext: invocation.inheritContext,
155
+ runInBackground: invocation.runInBackground,
156
+ isolation: invocation.isolation,
157
+ },
158
+ // Nested children are hidden from every reporting surface, so their spend
159
+ // would otherwise be unattributable. Fold it into every ancestor's record:
160
+ // the top-level one appears in lifecycle events, completion notifications,
161
+ // and `/agents`, and those all read `lifetimeUsage`. The whole chain is
162
+ // walked, not just the immediate parent — a spawn callback only fires for
163
+ // that child's OWN turns, so stopping at one level would hide a
164
+ // great-grandchild from the only record anyone can see. (The live
165
+ // widget/fleet counters read their own per-agent activity tracker, which
166
+ // still sees only the top-level agent's own turns.)
167
+ onAssistantUsage: (usage) => {
168
+ for (let id = context.parentAgentId; id !== undefined;) {
169
+ const ancestor = context.manager.getRecord(id);
170
+ if (!ancestor)
171
+ break;
172
+ addUsage(ancestor.lifetimeUsage, usage);
173
+ id = ancestor.parentAgentId;
174
+ }
175
+ },
176
+ depth: childDepth,
177
+ parentAgentId: context.parentAgentId,
178
+ maxSubagentDepth: context.maxSubagentDepth,
179
+ configCwd: context.configCwd,
180
+ rootSessionId,
181
+ };
182
+ // Transcript wiring, same gate as the top-level path: the child's
183
+ // `output_transcript` frontmatter wins, else the project default. Without
184
+ // it a nested run leaves no artifact but the string it returned — the
185
+ // parent's own transcript records the call and the answer, never the tool
186
+ // calls in between, which is exactly what a misbehaving child needs to
187
+ // explain itself. Filed under the ROOT session and this branch's config
188
+ // root, so a nested transcript lands in the same `tasks/` directory as its
189
+ // ancestors' rather than in a directory of its own.
190
+ const transcriptSessionId = rootSessionId !== undefined && (config?.outputTranscript ?? getOutputTranscriptDefault())
191
+ ? rootSessionId
192
+ : undefined;
193
+ let childId;
194
+ const attachTranscript = (id) => {
195
+ childId = id;
196
+ if (transcriptSessionId === undefined)
197
+ return;
198
+ const rec = context.manager.getRecord(id);
199
+ if (!rec)
200
+ return;
201
+ rec.outputFile = createOutputFilePath(context.configCwd, id, transcriptSessionId);
202
+ writeInitialEntry(rec.outputFile, id, params.prompt, ctx.cwd);
203
+ };
204
+ options.onSessionCreated = (session) => {
205
+ const rec = childId === undefined ? undefined : context.manager.getRecord(childId);
206
+ if (rec?.outputFile && childId !== undefined) {
207
+ rec.outputCleanup = streamToOutputFile(session, rec.outputFile, childId, ctx.cwd);
208
+ }
209
+ };
210
+ // `ctx` is forwarded to the manager unmodified, never captured at tool-build
211
+ // time: each AgentSession builds its own ExtensionRunner from that session's
212
+ // cwd/sessionManager/modelRegistry, so this is the CHILD's context. Capturing
213
+ // one earlier would silently give a grandchild the wrong worktree base, the
214
+ // wrong conversation under inherit_context, and the wrong inherited model.
215
+ //
216
+ // spawn() throws on strict worktree-isolation failure and cwd validation —
217
+ // report it as a tool error, like the top-level Agent tool does, instead of
218
+ // letting it escape into the child's turn.
219
+ try {
220
+ if (invocation.runInBackground) {
221
+ const id = context.manager.spawn(context.pi, ctx, resolvedType, params.prompt, {
222
+ ...options,
223
+ isBackground: true,
224
+ });
225
+ // Synchronous, before the event loop yields — onSessionCreated fires
226
+ // asynchronously inside runAgent, so the file is attached in time.
227
+ attachTranscript(id);
228
+ // Worktree isolation starts the agent asynchronously; surface its
229
+ // failure as a tool error, like the synchronous throw used to.
230
+ await context.manager.awaitStartup(id);
231
+ return textResult(`Nested agent started in background. Agent ID: ${id}`);
232
+ }
233
+ const { record } = await context.manager.spawnAndWait(context.pi, ctx, resolvedType, params.prompt, { ...options, signal }, attachTranscript);
234
+ return textResult(formatRecord(record, "inline"), record.status === "error");
235
+ }
236
+ catch (err) {
237
+ return textResult(err instanceof Error ? err.message : String(err), true);
238
+ }
239
+ },
240
+ });
241
+ const resultTool = defineTool({
242
+ name: NESTED_TOOL_NAMES[1],
243
+ label: "Get Nested Agent Result",
244
+ description: "Check or wait for a background nested agent owned by this parent.",
245
+ parameters: Type.Object({
246
+ agent_id: Type.String(),
247
+ wait: Type.Optional(Type.Boolean()),
248
+ }),
249
+ execute: async (_toolCallId, params, signal) => {
250
+ const record = context.manager.getRecord(params.agent_id);
251
+ if (!ownsRecord(record, context.parentAgentId)) {
252
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
253
+ }
254
+ // Wait for completion if requested. Cancellation (e.g. the parent's tool
255
+ // call is aborted) stops only this wait; the nested child keeps running and
256
+ // stays unconsumed. Queued records have no promise until the manager starts
257
+ // them, so poll — abortably — until they leave the queue, then await.
258
+ if (params.wait && (record.status === "queued" || record.status === "running")) {
259
+ while (record.status === "queued") {
260
+ await abortable(new Promise(resolve => setTimeout(resolve, 250)), signal);
261
+ }
262
+ if (record.promise)
263
+ await abortable(record.promise, signal);
264
+ }
265
+ return textResult(formatRecord(record, "fetched"), record.status === "error");
266
+ },
267
+ });
268
+ const steerTool = defineTool({
269
+ name: NESTED_TOOL_NAMES[2],
270
+ label: "Steer Nested Agent",
271
+ description: "Send guidance to a running nested agent owned by this parent.",
272
+ parameters: Type.Object({
273
+ agent_id: Type.String(),
274
+ message: Type.String(),
275
+ }),
276
+ execute: async (_toolCallId, params) => {
277
+ const record = context.manager.getRecord(params.agent_id);
278
+ if (!ownsRecord(record, context.parentAgentId) || record.status !== "running") {
279
+ return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
280
+ }
281
+ // Session not ready yet — queue the steer. The manager flushes pending
282
+ // steers when the session is created (same contract as the top-level tool).
283
+ if (!record.session) {
284
+ if (!record.pendingSteers)
285
+ record.pendingSteers = [];
286
+ record.pendingSteers.push(params.message);
287
+ return textResult(`Steering message queued for nested agent ${params.agent_id}.`);
288
+ }
289
+ try {
290
+ await record.session.steer(params.message);
291
+ }
292
+ catch (err) {
293
+ return textResult(`Failed to steer nested agent: ${err instanceof Error ? err.message : String(err)}`, true);
294
+ }
295
+ return textResult(`Steering message sent to nested agent ${params.agent_id}.`);
296
+ },
297
+ });
298
+ return [agentTool, resultTool, steerTool];
299
+ }
@@ -0,0 +1,43 @@
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 type { AgentSession } from "@earendil-works/pi-coding-agent";
8
+ export declare function getOutputTranscriptDefault(): boolean;
9
+ export declare function setOutputTranscriptDefault(b: boolean): void;
10
+ /**
11
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
12
+ * - POSIX: "/home/user/project" → "home-user-project"
13
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
14
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
15
+ */
16
+ export declare function encodeCwd(cwd: string): string;
17
+ /**
18
+ * The per-session scratch directory, created if missing.
19
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
20
+ *
21
+ * Shared with the workflow tool, which persists each invocation's script here so
22
+ * iterating on one is edit-file-then-rerun — the same convention, one directory.
23
+ */
24
+ export declare function sessionTaskDir(cwd: string, sessionId: string): string;
25
+ /** Create the output file path, ensuring the directory exists. */
26
+ export declare function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string;
27
+ /**
28
+ * Ensure a transcript file exists without disturbing what is already in it.
29
+ *
30
+ * A resume reuses the agent's existing transcript (same deterministic path), so
31
+ * it must never call `writeInitialEntry` — that truncates, discarding turns the
32
+ * completion notification still points the user at, and any history the session
33
+ * has since compacted away is gone for good. Appending nothing creates the file
34
+ * when this is the agent's first transcript and is a no-op when it is not.
35
+ */
36
+ export declare function ensureOutputFile(path: string): void;
37
+ /** Write the initial user prompt entry. */
38
+ export declare function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void;
39
+ /**
40
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
41
+ * Returns a cleanup function that does a final flush and unsubscribes.
42
+ */
43
+ export declare function streamToOutputFile(session: AgentSession, path: string, agentId: string, cwd: string, startIndex?: number): () => void;
@@ -0,0 +1,142 @@
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 { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ /**
11
+ * Project/global default for writing a subagent's `.output` transcript; a custom
12
+ * agent's `output_transcript` overrides it per agent.
13
+ *
14
+ * State lives here rather than in an index.ts closure because both spawn paths
15
+ * need it — the top-level Agent tool and the nested delegation tools. Same
16
+ * reason `scopeModels` lives in model-scope.ts: a setting only one path can read
17
+ * is a setting the other path silently ignores.
18
+ */
19
+ let outputTranscriptDefault = true;
20
+ export function getOutputTranscriptDefault() { return outputTranscriptDefault; }
21
+ export function setOutputTranscriptDefault(b) { outputTranscriptDefault = b; }
22
+ /**
23
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
24
+ * - POSIX: "/home/user/project" → "home-user-project"
25
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
26
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
27
+ */
28
+ export function encodeCwd(cwd) {
29
+ return cwd
30
+ .replace(/[/\\]/g, "-") // both separators → dash
31
+ .replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
32
+ .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
33
+ }
34
+ /**
35
+ * The per-session scratch directory, created if missing.
36
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
37
+ *
38
+ * Shared with the workflow tool, which persists each invocation's script here so
39
+ * iterating on one is edit-file-then-rerun — the same convention, one directory.
40
+ */
41
+ export function sessionTaskDir(cwd, sessionId) {
42
+ const encoded = encodeCwd(cwd);
43
+ const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
44
+ mkdirSync(root, { recursive: true, mode: 0o700 });
45
+ // chmod is a no-op on Windows and throws on some Windows filesystems.
46
+ // On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
47
+ try {
48
+ chmodSync(root, 0o700);
49
+ }
50
+ catch (err) {
51
+ if (process.platform !== "win32")
52
+ throw err;
53
+ }
54
+ const dir = join(root, encoded, sessionId, "tasks");
55
+ mkdirSync(dir, { recursive: true });
56
+ return dir;
57
+ }
58
+ /** Create the output file path, ensuring the directory exists. */
59
+ export function createOutputFilePath(cwd, agentId, sessionId) {
60
+ return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
61
+ }
62
+ /**
63
+ * Ensure a transcript file exists without disturbing what is already in it.
64
+ *
65
+ * A resume reuses the agent's existing transcript (same deterministic path), so
66
+ * it must never call `writeInitialEntry` — that truncates, discarding turns the
67
+ * completion notification still points the user at, and any history the session
68
+ * has since compacted away is gone for good. Appending nothing creates the file
69
+ * when this is the agent's first transcript and is a no-op when it is not.
70
+ */
71
+ export function ensureOutputFile(path) {
72
+ try {
73
+ appendFileSync(path, "", "utf-8");
74
+ }
75
+ catch { /* ignore — streaming writes are best-effort too */ }
76
+ }
77
+ /** Write the initial user prompt entry. */
78
+ export function writeInitialEntry(path, agentId, prompt, cwd) {
79
+ const entry = {
80
+ isSidechain: true,
81
+ agentId,
82
+ type: "user",
83
+ message: { role: "user", content: prompt },
84
+ timestamp: new Date().toISOString(),
85
+ cwd,
86
+ };
87
+ writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
88
+ }
89
+ /**
90
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
91
+ * Returns a cleanup function that does a final flush and unsubscribes.
92
+ */
93
+ export function streamToOutputFile(session, path, agentId, cwd, startIndex) {
94
+ // Index of the first message this stream is responsible for. A spawn writes
95
+ // messages[0] as the initial prompt entry, so it starts at 1. A resume hands
96
+ // in the session's length as of just before the run: the session already
97
+ // holds every prior turn, and re-emitting those would duplicate history that
98
+ // is already in the file.
99
+ let writtenCount = startIndex ?? 1;
100
+ const flush = () => {
101
+ const messages = session.messages;
102
+ while (writtenCount < messages.length) {
103
+ const msg = messages[writtenCount];
104
+ const entry = {
105
+ isSidechain: true,
106
+ agentId,
107
+ type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
108
+ message: msg,
109
+ timestamp: new Date().toISOString(),
110
+ cwd,
111
+ };
112
+ try {
113
+ appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
114
+ }
115
+ catch { /* ignore write errors */ }
116
+ writtenCount++;
117
+ }
118
+ };
119
+ const unsubscribe = session.subscribe((event) => {
120
+ if (event.type === "turn_end")
121
+ flush();
122
+ // Compaction replaces session.messages with a shorter, summarized array,
123
+ // leaving writtenCount past the new end — without re-anchoring, the flush
124
+ // loop would never match again and streaming would halt for good (#145).
125
+ // Flush before it runs so any not-yet-flushed tail still reaches the file,
126
+ // then re-anchor to the rebuilt array once it lands. The re-anchor is
127
+ // deferred a microtask because on the overflow-retry path pi trims the
128
+ // trailing error assistant message AFTER emitting compaction_end —
129
+ // anchoring synchronously would sit one past the trimmed array and skip
130
+ // the first post-compaction message. Aborted/failed compactions leave
131
+ // session.messages untouched, so only successful ones re-anchor.
132
+ if (event.type === "compaction_start")
133
+ flush();
134
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
135
+ queueMicrotask(() => { writtenCount = session.messages.length; });
136
+ }
137
+ });
138
+ return () => {
139
+ flush();
140
+ unsubscribe();
141
+ };
142
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * prompts.ts — System prompt builder for agents.
3
+ */
4
+ import type { AgentConfig, EnvInfo } from "./types.js";
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
+ /** Preloaded skill contents to inject. */
10
+ skillBlocks?: {
11
+ name: string;
12
+ content: string;
13
+ }[];
14
+ /**
15
+ * Parent directory the worktree copy was created from. Set only for
16
+ * `isolation: "worktree"` spawns — triggers the block that tells the agent
17
+ * to stay in the copy.
18
+ */
19
+ worktreeBase?: string;
20
+ /**
21
+ * Set only for a workflow's own children, and only when they have no
22
+ * `StructuredOutput` tool to answer through.
23
+ *
24
+ * A workflow child's final text is not read by a human — it is the value
25
+ * `agent()` resolves to, and the script interpolates it straight into the
26
+ * next stage's prompt. Without this, children answer the way every other
27
+ * subagent does (a report addressed to a reader), and the padding becomes
28
+ * input tokens for the stage downstream. Claude Code's `Workflow` tool
29
+ * documents this contract to the script-writing model; this is the end of it
30
+ * that makes the documentation true.
31
+ *
32
+ * Deliberately NOT applied to every subagent. In pi an ordinary agent's
33
+ * output IS read by a human — through FleetView, the conversation viewer and
34
+ * `get_subagent_result` — so terse raw data would be the wrong answer there.
35
+ */
36
+ workflowChild?: boolean;
37
+ }
38
+ /**
39
+ * Build the system prompt for an agent from its config.
40
+ *
41
+ * - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
42
+ * - "append" mode: parent system prompt + sub-agent context + env header + config.systemPrompt
43
+ * - "append" with empty systemPrompt: pure parent clone
44
+ *
45
+ * Both modes include an `<active_agent name="${config.name}"/>` tag so downstream
46
+ * extensions (e.g. permission/policy systems) can resolve per-agent policy
47
+ * inside the child session by parsing the system prompt. In replace mode the tag
48
+ * is prepended; in append mode it follows the shared inherited content so the
49
+ * parent prompt forms an identical, cacheable byte prefix with the parent
50
+ * session (the LLM's KV cache can then reuse those tokens across every spawn).
51
+ *
52
+ * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
53
+ * @param extras Optional extra sections to inject (memory, preloaded skills).
54
+ */
55
+ export declare function buildAgentPrompt(config: AgentConfig, cwd: string, env: EnvInfo, parentSystemPrompt?: string, extras?: PromptExtras): string;
@@ -0,0 +1,91 @@
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?.memoryBlock) {
48
+ extraSections.push(extras.memoryBlock);
49
+ }
50
+ if (extras?.skillBlocks?.length) {
51
+ for (const skill of extras.skillBlocks) {
52
+ extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
53
+ }
54
+ }
55
+ const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
56
+ if (config.promptMode === "append") {
57
+ const identity = parentSystemPrompt || genericBase;
58
+ const bridge = `<sub_agent_context>
59
+ You are operating as a sub-agent invoked to handle a specific task.
60
+ - Use the read tool instead of cat/head/tail
61
+ - Use the edit tool instead of sed/awk
62
+ - Use the write tool instead of echo/heredoc
63
+ - Use the find tool instead of bash find/ls for file search
64
+ - Use the grep tool instead of bash grep/rg for content search
65
+ - Make independent tool calls in parallel
66
+ - Use absolute file paths
67
+ - Do not use emojis
68
+ - Be concise but complete
69
+ </sub_agent_context>`;
70
+ const customSection = config.systemPrompt?.trim()
71
+ ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
72
+ : "";
73
+ // Place shared/stable content first so the LLM's KV cache can reuse the
74
+ // inherited prefix across all subagent invocations. The parent prompt is
75
+ // placed verbatim (no wrapper tag) so it forms an identical byte prefix
76
+ // with the parent session, maximising KV cache hits. The <active_agent>
77
+ // tag and env block vary per call and are placed after the cached prefix.
78
+ return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + worktreeBlock + workflowBlock + customSection + extrasSuffix;
79
+ }
80
+ // "replace" mode — env header + the config's full system prompt
81
+ const replaceHeader = `You are a pi coding agent sub-agent.
82
+ You have been invoked to handle a specific task autonomously.
83
+
84
+ ${envBlock}`;
85
+ return activeAgentTag + replaceHeader + worktreeBlock + workflowBlock + "\n\n" + config.systemPrompt + extrasSuffix;
86
+ }
87
+ /** Fallback base prompt when parent system prompt is unavailable in append mode. */
88
+ const genericBase = `# Role
89
+ You are a general-purpose coding agent for complex, multi-step tasks.
90
+ You have full access to read, write, edit files, and execute commands.
91
+ Do what has been asked; nothing more, nothing less.`;