@esso0428/pi-subagents 0.17.5 → 0.17.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/README.md +1 -1
  4. package/dist/abortable.d.ts +13 -0
  5. package/dist/abortable.d.ts.map +1 -0
  6. package/dist/abortable.js +43 -0
  7. package/dist/abortable.js.map +1 -0
  8. package/dist/agent-color.d.ts +36 -0
  9. package/dist/agent-color.d.ts.map +1 -0
  10. package/dist/agent-color.js +124 -0
  11. package/dist/agent-color.js.map +1 -0
  12. package/dist/agent-file-toggle.d.ts +126 -0
  13. package/dist/agent-file-toggle.d.ts.map +1 -0
  14. package/dist/agent-file-toggle.js +259 -0
  15. package/dist/agent-file-toggle.js.map +1 -0
  16. package/dist/agent-history.d.ts +4 -0
  17. package/dist/agent-history.d.ts.map +1 -1
  18. package/dist/agent-history.js +47 -1
  19. package/dist/agent-history.js.map +1 -1
  20. package/dist/agent-manager.d.ts +370 -56
  21. package/dist/agent-manager.d.ts.map +1 -1
  22. package/dist/agent-manager.js +1123 -409
  23. package/dist/agent-manager.js.map +1 -1
  24. package/dist/agent-runner.d.ts +100 -10
  25. package/dist/agent-runner.d.ts.map +1 -1
  26. package/dist/agent-runner.js +166 -21
  27. package/dist/agent-runner.js.map +1 -1
  28. package/dist/agent-types.d.ts +57 -5
  29. package/dist/agent-types.d.ts.map +1 -1
  30. package/dist/agent-types.js +164 -32
  31. package/dist/agent-types.js.map +1 -1
  32. package/dist/child-context.d.ts +3 -0
  33. package/dist/child-context.d.ts.map +1 -0
  34. package/dist/child-context.js +13 -0
  35. package/dist/child-context.js.map +1 -0
  36. package/dist/cross-extension-rpc.d.ts +23 -3
  37. package/dist/cross-extension-rpc.d.ts.map +1 -1
  38. package/dist/cross-extension-rpc.js +79 -17
  39. package/dist/cross-extension-rpc.js.map +1 -1
  40. package/dist/custom-agents.d.ts +38 -1
  41. package/dist/custom-agents.d.ts.map +1 -1
  42. package/dist/custom-agents.js +164 -12
  43. package/dist/custom-agents.js.map +1 -1
  44. package/dist/index.d.ts +34 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +1908 -495
  47. package/dist/index.js.map +1 -1
  48. package/dist/invocation-config.d.ts +87 -2
  49. package/dist/invocation-config.d.ts.map +1 -1
  50. package/dist/invocation-config.js +71 -3
  51. package/dist/invocation-config.js.map +1 -1
  52. package/dist/mention-clone.d.ts +88 -0
  53. package/dist/mention-clone.d.ts.map +1 -0
  54. package/dist/mention-clone.js +154 -0
  55. package/dist/mention-clone.js.map +1 -0
  56. package/dist/mention.d.ts +82 -0
  57. package/dist/mention.d.ts.map +1 -0
  58. package/dist/mention.js +132 -0
  59. package/dist/mention.js.map +1 -0
  60. package/dist/model-resolver.d.ts +17 -0
  61. package/dist/model-resolver.d.ts.map +1 -1
  62. package/dist/model-resolver.js +15 -0
  63. package/dist/model-resolver.js.map +1 -1
  64. package/dist/model-scope.d.ts +50 -0
  65. package/dist/model-scope.d.ts.map +1 -0
  66. package/dist/model-scope.js +49 -0
  67. package/dist/model-scope.js.map +1 -0
  68. package/dist/nested-tools.d.ts +57 -0
  69. package/dist/nested-tools.d.ts.map +1 -0
  70. package/dist/nested-tools.js +301 -0
  71. package/dist/nested-tools.js.map +1 -0
  72. package/dist/output-file.d.ts +22 -3
  73. package/dist/output-file.d.ts.map +1 -1
  74. package/dist/output-file.js +58 -7
  75. package/dist/output-file.js.map +1 -1
  76. package/dist/prompts.d.ts +23 -0
  77. package/dist/prompts.d.ts.map +1 -1
  78. package/dist/prompts.js +20 -2
  79. package/dist/prompts.js.map +1 -1
  80. package/dist/schedule.d.ts.map +1 -1
  81. package/dist/schedule.js +36 -15
  82. package/dist/schedule.js.map +1 -1
  83. package/dist/settings.d.ts +228 -2
  84. package/dist/settings.d.ts.map +1 -1
  85. package/dist/settings.js +94 -0
  86. package/dist/settings.js.map +1 -1
  87. package/dist/status-note.d.ts +49 -1
  88. package/dist/status-note.d.ts.map +1 -1
  89. package/dist/status-note.js +62 -1
  90. package/dist/status-note.js.map +1 -1
  91. package/dist/structured-output.d.ts +62 -0
  92. package/dist/structured-output.d.ts.map +1 -0
  93. package/dist/structured-output.js +113 -0
  94. package/dist/structured-output.js.map +1 -0
  95. package/dist/types.d.ts +176 -10
  96. package/dist/types.d.ts.map +1 -1
  97. package/dist/ui/agent-mention.d.ts +83 -0
  98. package/dist/ui/agent-mention.d.ts.map +1 -0
  99. package/dist/ui/agent-mention.js +188 -0
  100. package/dist/ui/agent-mention.js.map +1 -0
  101. package/dist/ui/agent-widget.d.ts +96 -75
  102. package/dist/ui/agent-widget.d.ts.map +1 -1
  103. package/dist/ui/agent-widget.js +397 -420
  104. package/dist/ui/agent-widget.js.map +1 -1
  105. package/dist/ui/conversation-blocks.d.ts.map +1 -1
  106. package/dist/ui/conversation-blocks.js +6 -0
  107. package/dist/ui/conversation-blocks.js.map +1 -1
  108. package/dist/ui/conversation-timeline.d.ts +10 -2
  109. package/dist/ui/conversation-timeline.d.ts.map +1 -1
  110. package/dist/ui/conversation-timeline.js +130 -23
  111. package/dist/ui/conversation-timeline.js.map +1 -1
  112. package/dist/ui/conversation-viewer.d.ts +20 -5
  113. package/dist/ui/conversation-viewer.d.ts.map +1 -1
  114. package/dist/ui/conversation-viewer.js +274 -73
  115. package/dist/ui/conversation-viewer.js.map +1 -1
  116. package/dist/ui/fleet-list.d.ts +198 -0
  117. package/dist/ui/fleet-list.d.ts.map +1 -0
  118. package/dist/ui/fleet-list.js +487 -0
  119. package/dist/ui/fleet-list.js.map +1 -0
  120. package/dist/ui/schedule-menu.d.ts.map +1 -1
  121. package/dist/ui/schedule-menu.js +6 -7
  122. package/dist/ui/schedule-menu.js.map +1 -1
  123. package/dist/ui/select-item.d.ts +28 -0
  124. package/dist/ui/select-item.d.ts.map +1 -0
  125. package/dist/ui/select-item.js +35 -0
  126. package/dist/ui/select-item.js.map +1 -0
  127. package/dist/ui/workflow-card.d.ts +176 -0
  128. package/dist/ui/workflow-card.d.ts.map +1 -0
  129. package/dist/ui/workflow-card.js +333 -0
  130. package/dist/ui/workflow-card.js.map +1 -0
  131. package/dist/ui/workflow-dialog.d.ts +306 -0
  132. package/dist/ui/workflow-dialog.d.ts.map +1 -0
  133. package/dist/ui/workflow-dialog.js +844 -0
  134. package/dist/ui/workflow-dialog.js.map +1 -0
  135. package/dist/ui/workflow-menu.d.ts +61 -0
  136. package/dist/ui/workflow-menu.d.ts.map +1 -0
  137. package/dist/ui/workflow-menu.js +148 -0
  138. package/dist/ui/workflow-menu.js.map +1 -0
  139. package/dist/usage.d.ts +86 -1
  140. package/dist/usage.d.ts.map +1 -1
  141. package/dist/usage.js +72 -1
  142. package/dist/usage.js.map +1 -1
  143. package/dist/workflow/collisions.d.ts +96 -0
  144. package/dist/workflow/collisions.d.ts.map +1 -0
  145. package/dist/workflow/collisions.js +89 -0
  146. package/dist/workflow/collisions.js.map +1 -0
  147. package/dist/workflow/entry.d.ts +33 -0
  148. package/dist/workflow/entry.d.ts.map +1 -0
  149. package/dist/workflow/entry.js +30 -0
  150. package/dist/workflow/entry.js.map +1 -0
  151. package/dist/workflow/host.d.ts +63 -0
  152. package/dist/workflow/host.d.ts.map +1 -0
  153. package/dist/workflow/host.js +363 -0
  154. package/dist/workflow/host.js.map +1 -0
  155. package/dist/workflow/journal.d.ts +98 -0
  156. package/dist/workflow/journal.d.ts.map +1 -0
  157. package/dist/workflow/journal.js +121 -0
  158. package/dist/workflow/journal.js.map +1 -0
  159. package/dist/workflow/json-schema.d.ts +52 -0
  160. package/dist/workflow/json-schema.d.ts.map +1 -0
  161. package/dist/workflow/json-schema.js +112 -0
  162. package/dist/workflow/json-schema.js.map +1 -0
  163. package/dist/workflow/meta.d.ts +68 -0
  164. package/dist/workflow/meta.d.ts.map +1 -0
  165. package/dist/workflow/meta.js +318 -0
  166. package/dist/workflow/meta.js.map +1 -0
  167. package/dist/workflow/progress.d.ts +225 -0
  168. package/dist/workflow/progress.d.ts.map +1 -0
  169. package/dist/workflow/progress.js +362 -0
  170. package/dist/workflow/progress.js.map +1 -0
  171. package/dist/workflow/runtime.d.ts +335 -0
  172. package/dist/workflow/runtime.d.ts.map +1 -0
  173. package/dist/workflow/runtime.js +831 -0
  174. package/dist/workflow/runtime.js.map +1 -0
  175. package/dist/workflow/saved.d.ts +91 -0
  176. package/dist/workflow/saved.d.ts.map +1 -0
  177. package/dist/workflow/saved.js +204 -0
  178. package/dist/workflow/saved.js.map +1 -0
  179. package/dist/workflow/task.d.ts +137 -0
  180. package/dist/workflow/task.d.ts.map +1 -0
  181. package/dist/workflow/task.js +208 -0
  182. package/dist/workflow/task.js.map +1 -0
  183. package/dist/workflow/tool-description.d.ts +39 -0
  184. package/dist/workflow/tool-description.d.ts.map +1 -0
  185. package/dist/workflow/tool-description.js +200 -0
  186. package/dist/workflow/tool-description.js.map +1 -0
  187. package/dist/workflow/worker-source.d.ts +48 -0
  188. package/dist/workflow/worker-source.d.ts.map +1 -0
  189. package/dist/workflow/worker-source.js +779 -0
  190. package/dist/workflow/worker-source.js.map +1 -0
  191. package/dist/worktree.d.ts +10 -3
  192. package/dist/worktree.d.ts.map +1 -1
  193. package/dist/worktree.js +58 -54
  194. package/dist/worktree.js.map +1 -1
  195. package/dist/xml.d.ts +11 -0
  196. package/dist/xml.d.ts.map +1 -0
  197. package/dist/xml.js +13 -0
  198. package/dist/xml.js.map +1 -0
  199. package/docs/rpc.md +183 -0
  200. package/docs/superpowers/plans/2026-09-30-conversation-viewer-scrollbar.md +216 -0
  201. package/docs/superpowers/plans/2026-09-30-upstream-event-workflow-partial-history.md +195 -0
  202. package/docs/superpowers/specs/2026-09-30-conversation-viewer-scrollbar-design.md +82 -0
  203. package/docs/superpowers/specs/2026-09-30-upstream-event-workflow-partial-history-design.md +49 -0
  204. package/docs/workflows.md +437 -0
  205. package/examples/agent-tool-description.md +7 -7
  206. package/examples/workflows/compose.js +51 -0
  207. package/examples/workflows/fan-out-audit.js +47 -0
  208. package/examples/workflows/gated-fix.js +60 -0
  209. package/examples/workflows/lib/count-child.js +27 -0
  210. package/examples/workflows/review-panel.js +63 -0
  211. package/examples/workflows/structured-findings.js +78 -0
  212. package/package.json +1 -1
  213. package/src/abortable.ts +43 -0
  214. package/src/agent-color.ts +161 -0
  215. package/src/agent-file-toggle.ts +269 -0
  216. package/src/agent-history.ts +54 -2
  217. package/src/agent-manager.ts +1263 -402
  218. package/src/agent-runner.ts +251 -27
  219. package/src/agent-types.ts +188 -32
  220. package/src/child-context.ts +15 -0
  221. package/src/cross-extension-rpc.ts +96 -20
  222. package/src/custom-agents.ts +170 -13
  223. package/src/index.ts +2024 -537
  224. package/src/invocation-config.ts +118 -3
  225. package/src/mention-clone.ts +196 -0
  226. package/src/mention.ts +141 -0
  227. package/src/model-resolver.ts +18 -0
  228. package/src/model-scope.ts +70 -0
  229. package/src/nested-tools.ts +424 -0
  230. package/src/output-file.ts +61 -6
  231. package/src/prompts.ts +45 -2
  232. package/src/schedule.ts +35 -14
  233. package/src/settings.ts +312 -2
  234. package/src/status-note.ts +66 -1
  235. package/src/structured-output.ts +130 -0
  236. package/src/types.ts +177 -10
  237. package/src/ui/agent-mention.ts +216 -0
  238. package/src/ui/agent-widget.ts +389 -441
  239. package/src/ui/conversation-blocks.ts +6 -0
  240. package/src/ui/conversation-timeline.ts +139 -25
  241. package/src/ui/conversation-viewer.ts +284 -69
  242. package/src/ui/fleet-list.ts +558 -0
  243. package/src/ui/schedule-menu.ts +9 -8
  244. package/src/ui/select-item.ts +45 -0
  245. package/src/ui/workflow-card.ts +470 -0
  246. package/src/ui/workflow-dialog.ts +1115 -0
  247. package/src/ui/workflow-menu.ts +193 -0
  248. package/src/usage.ts +109 -2
  249. package/src/workflow/collisions.ts +123 -0
  250. package/src/workflow/entry.ts +47 -0
  251. package/src/workflow/host.ts +403 -0
  252. package/src/workflow/journal.ts +164 -0
  253. package/src/workflow/json-schema.ts +128 -0
  254. package/src/workflow/meta.ts +325 -0
  255. package/src/workflow/progress.ts +550 -0
  256. package/src/workflow/runtime.ts +1219 -0
  257. package/src/workflow/saved.ts +217 -0
  258. package/src/workflow/task.ts +302 -0
  259. package/src/workflow/tool-description.ts +200 -0
  260. package/src/workflow/worker-source.ts +781 -0
  261. package/src/worktree.ts +69 -55
  262. package/src/xml.ts +13 -0
  263. package/vitest.config.ts +0 -18
@@ -0,0 +1,424 @@
1
+ import type { Model } from "@earendil-works/pi-ai";
2
+ import {
3
+ type AgentSession,
4
+ defineTool,
5
+ type ExtensionAPI,
6
+ type ExtensionContext,
7
+ type ToolDefinition,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { Type } from "@sinclair/typebox";
10
+ import { abortable } from "./abortable.js";
11
+ import {
12
+ buildAgentRegistry,
13
+ getAgentConfigIn,
14
+ getAvailableTypesIn,
15
+ resolveEnabledTypeIn,
16
+ resolveTypeIn,
17
+ } from "./agent-types.js";
18
+ import { loadCustomAgents } from "./custom-agents.js";
19
+ import { isolationParam, resolveAgentInvocationConfig } from "./invocation-config.js";
20
+ import { resolveModel } from "./model-resolver.js";
21
+ import { checkModelScope } from "./model-scope.js";
22
+ import {
23
+ createOutputFilePath,
24
+ getOutputTranscriptDefault,
25
+ streamToOutputFile,
26
+ writeInitialEntry,
27
+ } from "./output-file.js";
28
+ import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
29
+ import type {
30
+ AgentConfig,
31
+ AgentInvocation,
32
+ AgentRecord,
33
+ IsolationMode,
34
+ ThinkingLevel,
35
+ } from "./types.js";
36
+ import { addUsage } from "./usage.js";
37
+ import { isWorktreeIsolationEnabled } from "./worktree.js";
38
+
39
+ /**
40
+ * Hard ceiling on nesting for every branch: main session = 0, its subagents = 1,
41
+ * their children = 2. `0`/`1` disables nesting entirely. Set from
42
+ * `subagents.json` (`maxSubagentDepth`). Read when a subagent session is built,
43
+ * so a change applies to sessions started after it.
44
+ */
45
+ let maxSubagentDepth = 2;
46
+
47
+ export function getMaxSubagentDepth(): number { return maxSubagentDepth; }
48
+ export function setMaxSubagentDepth(n: number): void { maxSubagentDepth = Math.max(0, Math.floor(n)); }
49
+
50
+ const NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"] as const;
51
+
52
+ interface NestedSpawnOptions {
53
+ description: string;
54
+ model?: Model<any>;
55
+ maxTurns?: number;
56
+ isolated?: boolean;
57
+ inheritContext?: boolean;
58
+ thinkingLevel?: ThinkingLevel;
59
+ isBackground?: boolean;
60
+ isolation?: IsolationMode;
61
+ outputTranscript?: boolean;
62
+ invocation?: AgentInvocation;
63
+ signal?: AbortSignal;
64
+ onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
65
+ onSessionCreated?: (session: AgentSession) => void;
66
+ depth: number;
67
+ parentAgentId: string;
68
+ maxSubagentDepth: number;
69
+ configCwd?: string;
70
+ rootSessionId?: string;
71
+ }
72
+
73
+ export interface NestedAgentManager {
74
+ spawn(
75
+ pi: ExtensionAPI,
76
+ ctx: ExtensionContext,
77
+ type: string,
78
+ prompt: string,
79
+ options: NestedSpawnOptions,
80
+ ): string;
81
+ /** Resolves once the spawned agent is running; rejects on a startup failure. */
82
+ awaitStartup(id: string): Promise<void>;
83
+ spawnAndWait(
84
+ pi: ExtensionAPI,
85
+ ctx: ExtensionContext,
86
+ type: string,
87
+ prompt: string,
88
+ options: Omit<NestedSpawnOptions, "isBackground">,
89
+ /** Fires synchronously after spawn, before the session exists — where the transcript is attached. */
90
+ onSpawned?: (id: string) => void,
91
+ ): Promise<{ id: string; record: AgentRecord }>;
92
+ getRecord(id: string): AgentRecord | undefined;
93
+ resume(id: string, prompt: string, signal?: AbortSignal): Promise<AgentRecord | undefined>;
94
+ }
95
+
96
+ export interface NestedToolContext {
97
+ manager: NestedAgentManager;
98
+ pi: ExtensionAPI;
99
+ parentAgentId: string;
100
+ depth: number;
101
+ maxSubagentDepth: number;
102
+ /** "all" = any enabled agent; string[] = only those types. Never empty. */
103
+ allowedSubagents: "all" | string[];
104
+ /** Root used for agent/config discovery; may differ from the agent's working directory. */
105
+ configCwd: string;
106
+ }
107
+
108
+ function textResult(text: string, isError = false) {
109
+ return { content: [{ type: "text" as const, text }], isError, details: {} };
110
+ }
111
+
112
+ function ownsRecord(record: AgentRecord | undefined, parentAgentId: string): record is AgentRecord {
113
+ return record?.parentAgentId === parentAgentId;
114
+ }
115
+
116
+ /**
117
+ * How the caller received this record, which decides the outcome wording.
118
+ *
119
+ * - "inline": a foreground spawn or a resume. The full output is in this very
120
+ * result and no agent id was handed back, so the note must say there is
121
+ * nothing left to fetch — otherwise the parent invents an id, calls
122
+ * `get_subagent_result`, and hits "not owned by this parent" (#174, the same
123
+ * trap the top-level foreground path fell into).
124
+ * - "fetched": `get_subagent_result` on a background child. The parent holds a
125
+ * valid id and can poll again, so the background wording applies.
126
+ */
127
+ type ResultPosition = "inline" | "fetched";
128
+
129
+ function formatRecord(record: AgentRecord, position: ResultPosition): string {
130
+ if (record.status === "error") {
131
+ return `Agent failed: ${record.error ?? "unknown error"}${partialOutputSuffix(record)}`;
132
+ }
133
+ if (record.status === "queued" || record.status === "running") {
134
+ return `Agent ${record.id} is ${record.status}.`;
135
+ }
136
+ // A truncated run must not read as a finished one. The top-level path carries
137
+ // this in its result headline; a nested result has no headline, so the note
138
+ // leads — appended, it would look like part of the child's own output.
139
+ const text = record.result?.trim() || record.error?.trim() || "No output.";
140
+ const note = position === "inline"
141
+ ? getForegroundOutcomeNote(record.status)
142
+ : getStatusNote(record.status);
143
+ return note ? `Nested agent${note}.\n\n${text}` : text;
144
+ }
145
+
146
+ /** Build child-safe orchestration tools scoped to one parent agent instance. */
147
+ export function createNestedSubagentTools(context: NestedToolContext): ToolDefinition[] {
148
+ // Agents resolve from a registry built for THIS branch's config root (under
149
+ // worktree isolation, the copy). Never via registerAgents — that is
150
+ // process-global state shared with the main session and every other agent.
151
+ const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd));
152
+ const allowedTypesIn = (registry: Map<string, AgentConfig>): Set<string> | undefined =>
153
+ context.allowedSubagents === "all"
154
+ ? undefined
155
+ : new Set(context.allowedSubagents.map(name => resolveTypeIn(registry, name) ?? name));
156
+ const availableIn = (registry: Map<string, AgentConfig>): string[] => {
157
+ const allowed = allowedTypesIn(registry);
158
+ return getAvailableTypesIn(registry).filter(name => allowed === undefined || allowed.has(name));
159
+ };
160
+
161
+ const agentTool = defineTool({
162
+ name: NESTED_TOOL_NAMES[0],
163
+ label: "Agent",
164
+ description:
165
+ "Launch a child-safe nested subagent for bounded delegated work. " +
166
+ "Only use agent types allowed by this parent agent; nesting is depth-limited.",
167
+ parameters: Type.Object({
168
+ prompt: Type.String({ description: "Self-contained task for the nested agent." }),
169
+ description: Type.String({ description: "Short 3-5 word task description." }),
170
+ subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
171
+ model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
172
+ thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
173
+ max_turns: Type.Optional(Type.Number({ minimum: 1 })),
174
+ run_in_background: Type.Optional(
175
+ Type.Boolean({
176
+ 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.",
177
+ }),
178
+ ),
179
+ resume: Type.Optional(Type.String({ description: "Resume a nested agent owned by this parent." })),
180
+ isolated: Type.Optional(Type.Boolean()),
181
+ inherit_context: Type.Optional(Type.Boolean()),
182
+ ...isolationParam(isWorktreeIsolationEnabled()),
183
+ }),
184
+ execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
185
+ if (params.resume) {
186
+ const existing = context.manager.getRecord(params.resume);
187
+ if (!ownsRecord(existing, context.parentAgentId)) {
188
+ return textResult(`Nested agent not found or not owned by this parent: "${params.resume}".`, true);
189
+ }
190
+ const resumed = await context.manager.resume(params.resume, params.prompt, signal);
191
+ return resumed
192
+ ? textResult(formatRecord(resumed, "inline"), resumed.status === "error")
193
+ : textResult(`Failed to resume nested agent "${params.resume}".`, true);
194
+ }
195
+
196
+ if (context.depth >= context.maxSubagentDepth) {
197
+ return textResult(
198
+ `Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`,
199
+ true,
200
+ );
201
+ }
202
+
203
+ // Reloaded per call so new agent files are picked up without a restart.
204
+ const registry = loadRegistry();
205
+ const rawType = params.subagent_type;
206
+ // Strict resolve, never the fallback policy: a project-level
207
+ // `fallbackSubagent` must not hand a nested caller an agent its allowlist
208
+ // never named. The list stays allowlist-filtered so a typo can't enumerate
209
+ // agents this parent may not reach.
210
+ const resolvedType = resolveEnabledTypeIn(registry, rawType);
211
+ if (resolvedType === undefined) {
212
+ return textResult(
213
+ `Unknown or disabled nested agent type: "${rawType}". Allowed: ${availableIn(registry).join(", ") || "none"}.`,
214
+ true,
215
+ );
216
+ }
217
+ const allowed = allowedTypesIn(registry);
218
+ if (allowed !== undefined && !allowed.has(resolvedType)) {
219
+ return textResult(
220
+ `Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`,
221
+ true,
222
+ );
223
+ }
224
+
225
+ const config = getAgentConfigIn(registry, resolvedType);
226
+ // Foreground regardless of `backgroundByDefault` — see the reasoning on
227
+ // ResolveOptions. An explicit `true` here still opts in.
228
+ const invocation = resolveAgentInvocationConfig(config, params, {
229
+ worktreeAllowed: isWorktreeIsolationEnabled(),
230
+ defaultRunInBackground: false,
231
+ });
232
+ let model = ctx.model;
233
+ if (invocation.modelInput) {
234
+ const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
235
+ if (typeof resolvedModel === "string") {
236
+ if (invocation.modelFromParams) return textResult(resolvedModel, true);
237
+ } else {
238
+ model = resolvedModel;
239
+ }
240
+ }
241
+
242
+ // Same scopeModels policy as the top-level Agent tool — a nested spawn
243
+ // must not escape the allowlist. A "warn" verdict proceeds silently:
244
+ // child sessions have no UI surface to toast to.
245
+ const scopeVerdict = checkModelScope({
246
+ model,
247
+ cwd: context.configCwd,
248
+ modelRegistry: ctx.modelRegistry,
249
+ callerSupplied: invocation.modelFromParams,
250
+ agentLabel: config?.displayName ?? resolvedType,
251
+ modelInput: invocation.modelInput,
252
+ });
253
+ if (scopeVerdict.kind === "error") return textResult(scopeVerdict.message, true);
254
+
255
+ // The whole branch shares the root session's transcript directory; read it
256
+ // off the owning parent rather than this child session's own id.
257
+ const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId;
258
+ const childDepth = context.depth + 1;
259
+ const options: NestedSpawnOptions = {
260
+ description: params.description,
261
+ model,
262
+ maxTurns: invocation.maxTurns,
263
+ isolated: invocation.isolated,
264
+ inheritContext: invocation.inheritContext,
265
+ thinkingLevel: invocation.thinking,
266
+ isolation: invocation.isolation,
267
+ outputTranscript: config?.outputTranscript ?? getOutputTranscriptDefault(),
268
+ invocation: {
269
+ thinking: invocation.thinking,
270
+ maxTurns: invocation.maxTurns,
271
+ isolated: invocation.isolated,
272
+ inheritContext: invocation.inheritContext,
273
+ runInBackground: invocation.runInBackground,
274
+ isolation: invocation.isolation,
275
+ },
276
+ // Nested children are hidden from every reporting surface, so their spend
277
+ // would otherwise be unattributable. Fold it into every ancestor's record:
278
+ // the top-level one appears in lifecycle events, completion notifications,
279
+ // and `/agents`, and those all read `lifetimeUsage`. The whole chain is
280
+ // walked, not just the immediate parent — a spawn callback only fires for
281
+ // that child's OWN turns, so stopping at one level would hide a
282
+ // great-grandchild from the only record anyone can see. (The live
283
+ // widget/fleet counters read their own per-agent activity tracker, which
284
+ // still sees only the top-level agent's own turns.)
285
+ onAssistantUsage: (usage) => {
286
+ for (let id: string | undefined = context.parentAgentId; id !== undefined; ) {
287
+ const ancestor = context.manager.getRecord(id);
288
+ if (!ancestor) break;
289
+ addUsage(ancestor.lifetimeUsage, usage);
290
+ id = ancestor.parentAgentId;
291
+ }
292
+ },
293
+ depth: childDepth,
294
+ parentAgentId: context.parentAgentId,
295
+ maxSubagentDepth: context.maxSubagentDepth,
296
+ configCwd: context.configCwd,
297
+ rootSessionId,
298
+ };
299
+
300
+ // Transcript wiring, same gate as the top-level path: the child's
301
+ // `output_transcript` frontmatter wins, else the project default. Without
302
+ // it a nested run leaves no artifact but the string it returned — the
303
+ // parent's own transcript records the call and the answer, never the tool
304
+ // calls in between, which is exactly what a misbehaving child needs to
305
+ // explain itself. Filed under the ROOT session and this branch's config
306
+ // root, so a nested transcript lands in the same `tasks/` directory as its
307
+ // ancestors' rather than in a directory of its own.
308
+ const transcriptSessionId =
309
+ rootSessionId !== undefined && (config?.outputTranscript ?? getOutputTranscriptDefault())
310
+ ? rootSessionId
311
+ : undefined;
312
+ let childId: string | undefined;
313
+ const attachTranscript = (id: string): void => {
314
+ childId = id;
315
+ if (transcriptSessionId === undefined) return;
316
+ const rec = context.manager.getRecord(id);
317
+ if (!rec) return;
318
+ rec.outputFile = createOutputFilePath(context.configCwd, id, transcriptSessionId);
319
+ writeInitialEntry(rec.outputFile, id, params.prompt, ctx.cwd);
320
+ };
321
+ options.onSessionCreated = (session) => {
322
+ const rec = childId === undefined ? undefined : context.manager.getRecord(childId);
323
+ if (rec?.outputFile && childId !== undefined) {
324
+ rec.outputCleanup = streamToOutputFile(session, rec.outputFile, childId, ctx.cwd, undefined);
325
+ }
326
+ };
327
+
328
+ // `ctx` is forwarded to the manager unmodified, never captured at tool-build
329
+ // time: each AgentSession builds its own ExtensionRunner from that session's
330
+ // cwd/sessionManager/modelRegistry, so this is the CHILD's context. Capturing
331
+ // one earlier would silently give a grandchild the wrong worktree base, the
332
+ // wrong conversation under inherit_context, and the wrong inherited model.
333
+ //
334
+ // spawn() throws on strict worktree-isolation failure and cwd validation —
335
+ // report it as a tool error, like the top-level Agent tool does, instead of
336
+ // letting it escape into the child's turn.
337
+ try {
338
+ if (invocation.runInBackground) {
339
+ const id = context.manager.spawn(context.pi, ctx, resolvedType, params.prompt, {
340
+ ...options,
341
+ isBackground: true,
342
+ });
343
+ // Synchronous, before the event loop yields — onSessionCreated fires
344
+ // asynchronously inside runAgent, so the file is attached in time.
345
+ attachTranscript(id);
346
+ // Worktree isolation starts the agent asynchronously; surface its
347
+ // failure as a tool error, like the synchronous throw used to.
348
+ await context.manager.awaitStartup(id);
349
+ return textResult(`Nested agent started in background. Agent ID: ${id}`);
350
+ }
351
+
352
+ const { record } = await context.manager.spawnAndWait(
353
+ context.pi,
354
+ ctx,
355
+ resolvedType,
356
+ params.prompt,
357
+ { ...options, signal },
358
+ attachTranscript,
359
+ );
360
+ return textResult(formatRecord(record, "inline"), record.status === "error");
361
+ } catch (err) {
362
+ return textResult(err instanceof Error ? err.message : String(err), true);
363
+ }
364
+ },
365
+ });
366
+
367
+ const resultTool = defineTool({
368
+ name: NESTED_TOOL_NAMES[1],
369
+ label: "Get Nested Agent Result",
370
+ description: "Check or wait for a background nested agent owned by this parent.",
371
+ parameters: Type.Object({
372
+ agent_id: Type.String(),
373
+ wait: Type.Optional(Type.Boolean()),
374
+ }),
375
+ execute: async (_toolCallId, params, signal) => {
376
+ const record = context.manager.getRecord(params.agent_id);
377
+ if (!ownsRecord(record, context.parentAgentId)) {
378
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
379
+ }
380
+ // Wait for completion if requested. Cancellation (e.g. the parent's tool
381
+ // call is aborted) stops only this wait; the nested child keeps running and
382
+ // stays unconsumed. Queued records have no promise until the manager starts
383
+ // them, so poll — abortably — until they leave the queue, then await.
384
+ if (params.wait && (record.status === "queued" || record.status === "running")) {
385
+ while (record.status === "queued") {
386
+ await abortable(new Promise<void>(resolve => setTimeout(resolve, 250)), signal);
387
+ }
388
+ if (record.promise) await abortable(record.promise, signal);
389
+ }
390
+ return textResult(formatRecord(record, "fetched"), record.status === "error");
391
+ },
392
+ });
393
+
394
+ const steerTool = defineTool({
395
+ name: NESTED_TOOL_NAMES[2],
396
+ label: "Steer Nested Agent",
397
+ description: "Send guidance to a running nested agent owned by this parent.",
398
+ parameters: Type.Object({
399
+ agent_id: Type.String(),
400
+ message: Type.String(),
401
+ }),
402
+ execute: async (_toolCallId, params) => {
403
+ const record = context.manager.getRecord(params.agent_id);
404
+ if (!ownsRecord(record, context.parentAgentId) || record.status !== "running") {
405
+ return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
406
+ }
407
+ // Session not ready yet — queue the steer. The manager flushes pending
408
+ // steers when the session is created (same contract as the top-level tool).
409
+ if (!record.session) {
410
+ if (!record.pendingSteers) record.pendingSteers = [];
411
+ record.pendingSteers.push(params.message);
412
+ return textResult(`Steering message queued for nested agent ${params.agent_id}.`);
413
+ }
414
+ try {
415
+ await record.session.steer(params.message);
416
+ } catch (err) {
417
+ return textResult(`Failed to steer nested agent: ${err instanceof Error ? err.message : String(err)}`, true);
418
+ }
419
+ return textResult(`Steering message sent to nested agent ${params.agent_id}.`);
420
+ },
421
+ });
422
+
423
+ return [agentTool, resultTool, steerTool];
424
+ }
@@ -10,6 +10,20 @@ import { tmpdir } from "node:os";
10
10
  import { join } from "node:path";
11
11
  import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
12
12
 
13
+ /**
14
+ * Project/global default for writing a subagent's `.output` transcript; a custom
15
+ * agent's `output_transcript` overrides it per agent.
16
+ *
17
+ * State lives here rather than in an index.ts closure because both spawn paths
18
+ * need it — the top-level Agent tool and the nested delegation tools. Same
19
+ * reason `scopeModels` lives in model-scope.ts: a setting only one path can read
20
+ * is a setting the other path silently ignores.
21
+ */
22
+ let outputTranscriptDefault = true;
23
+
24
+ export function getOutputTranscriptDefault(): boolean { return outputTranscriptDefault; }
25
+ export function setOutputTranscriptDefault(b: boolean): void { outputTranscriptDefault = b; }
26
+
13
27
  /**
14
28
  * Encode a cwd path as a filesystem-safe directory name. Handles:
15
29
  * - POSIX: "/home/user/project" → "home-user-project"
@@ -23,9 +37,14 @@ export function encodeCwd(cwd: string): string {
23
37
  .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
24
38
  }
25
39
 
26
- /** Create the output file path, ensuring the directory exists.
27
- * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
28
- export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
40
+ /**
41
+ * The per-session scratch directory, created if missing.
42
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
43
+ *
44
+ * Shared with the workflow tool, which persists each invocation's script here so
45
+ * iterating on one is edit-file-then-rerun — the same convention, one directory.
46
+ */
47
+ export function sessionTaskDir(cwd: string, sessionId: string): string {
29
48
  const encoded = encodeCwd(cwd);
30
49
  const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
31
50
  mkdirSync(root, { recursive: true, mode: 0o700 });
@@ -38,7 +57,27 @@ export function createOutputFilePath(cwd: string, agentId: string, sessionId: st
38
57
  }
39
58
  const dir = join(root, encoded, sessionId, "tasks");
40
59
  mkdirSync(dir, { recursive: true });
41
- return join(dir, `${agentId}.output`);
60
+ return dir;
61
+ }
62
+
63
+ /** Create the output file path, ensuring the directory exists. */
64
+ export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
65
+ return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
66
+ }
67
+
68
+ /**
69
+ * Ensure a transcript file exists without disturbing what is already in it.
70
+ *
71
+ * A resume reuses the agent's existing transcript (same deterministic path), so
72
+ * it must never call `writeInitialEntry` — that truncates, discarding turns the
73
+ * completion notification still points the user at, and any history the session
74
+ * has since compacted away is gone for good. Appending nothing creates the file
75
+ * when this is the agent's first transcript and is a no-op when it is not.
76
+ */
77
+ export function ensureOutputFile(path: string): void {
78
+ try {
79
+ appendFileSync(path, "", "utf-8");
80
+ } catch { /* ignore — streaming writes are best-effort too */ }
42
81
  }
43
82
 
44
83
  /** Write the initial user prompt entry. */
@@ -63,9 +102,24 @@ export function streamToOutputFile(
63
102
  path: string,
64
103
  agentId: string,
65
104
  cwd: string,
105
+ startIndexOrHistoryPath?: number | string,
66
106
  historyPath?: string,
67
107
  ): () => void {
68
- let writtenCount = 1; // initial user prompt already written
108
+ // Keep the fork's historical five-argument form (historyPath as the fifth
109
+ // argument) while accepting upstream's six-argument resume form
110
+ // (startIndex, historyPath). This matters because scheduler/RPC/workflow
111
+ // callers use the ordinary spawn form, whereas resume starts after an
112
+ // existing in-memory message prefix.
113
+ const startIndex = typeof startIndexOrHistoryPath === "number" ? startIndexOrHistoryPath : undefined;
114
+ const durableHistoryPath = typeof startIndexOrHistoryPath === "string"
115
+ ? startIndexOrHistoryPath
116
+ : historyPath;
117
+ // Index of the first message this stream is responsible for. A spawn writes
118
+ // messages[0] as the initial prompt entry, so it starts at 1. A resume hands
119
+ // in the session's length as of just before the run: the session already
120
+ // holds every prior turn, and re-emitting those would duplicate history that
121
+ // is already in the file.
122
+ let writtenCount = startIndex ?? 1;
69
123
 
70
124
  const flush = () => {
71
125
  const messages = session.messages;
@@ -80,7 +134,8 @@ export function streamToOutputFile(
80
134
  cwd,
81
135
  };
82
136
  const entryJson = JSON.stringify(entry) + "\n";
83
- for (const target of historyPath && historyPath !== path ? [path, historyPath] : [path]) {
137
+ const targets = durableHistoryPath && durableHistoryPath !== path ? [path, durableHistoryPath] : [path];
138
+ for (const target of targets) {
84
139
  try {
85
140
  appendFileSync(target, entryJson, "utf-8");
86
141
  } catch { /* ignore write errors */ }
package/src/prompts.ts CHANGED
@@ -10,6 +10,29 @@ export interface PromptExtras {
10
10
  memoryBlock?: string;
11
11
  /** Preloaded skill contents to inject. */
12
12
  skillBlocks?: { name: string; content: string }[];
13
+ /**
14
+ * Parent directory the worktree copy was created from. Set only for
15
+ * `isolation: "worktree"` spawns — triggers the block that tells the agent
16
+ * to stay in the copy.
17
+ */
18
+ worktreeBase?: string;
19
+ /**
20
+ * Set only for a workflow's own children, and only when they have no
21
+ * `StructuredOutput` tool to answer through.
22
+ *
23
+ * A workflow child's final text is not read by a human — it is the value
24
+ * `agent()` resolves to, and the script interpolates it straight into the
25
+ * next stage's prompt. Without this, children answer the way every other
26
+ * subagent does (a report addressed to a reader), and the padding becomes
27
+ * input tokens for the stage downstream. Claude Code's `Workflow` tool
28
+ * documents this contract to the script-writing model; this is the end of it
29
+ * that makes the documentation true.
30
+ *
31
+ * Deliberately NOT applied to every subagent. In pi an ordinary agent's
32
+ * output IS read by a human — through FleetView, the conversation viewer and
33
+ * `get_subagent_result` — so terse raw data would be the wrong answer there.
34
+ */
35
+ workflowChild?: boolean;
13
36
  }
14
37
 
15
38
  /**
@@ -43,6 +66,26 @@ Working directory: ${cwd}
43
66
  ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
44
67
  Platform: ${env.platform}`;
45
68
 
69
+ // A worktree agent is told its cwd twice: by the env block above (the copy)
70
+ // and by whatever names the main checkout — the inherited parent prompt in
71
+ // append mode, or the task prompt in either mode. It follows the latter and
72
+ // works in the shared tree (#187), so resolve the contradiction explicitly.
73
+ const worktreeBlock = extras?.worktreeBase
74
+ ? `\n\n<worktree_isolation>
75
+ Your working directory is an isolated git worktree copy of ${extras.worktreeBase}.
76
+ Work only inside it — never in ${extras.worktreeBase}, even if other instructions name that path as your working directory.
77
+ </worktree_isolation>`
78
+ : "";
79
+
80
+ // The script, not a person, reads what this child returns — see
81
+ // `PromptExtras.workflowChild` for why only workflow children get this.
82
+ const workflowBlock = extras?.workflowChild
83
+ ? `\n\n<workflow_child>
84
+ 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.
85
+ Return only the answer, in exactly the shape the prompt asks for — no preamble, no summary of what you did, no offer to continue.
86
+ </workflow_child>`
87
+ : "";
88
+
46
89
  // Build optional extras suffix
47
90
  const extraSections: string[] = [];
48
91
  if (extras?.memoryBlock) {
@@ -80,7 +123,7 @@ You are operating as a sub-agent invoked to handle a specific task.
80
123
  // placed verbatim (no wrapper tag) so it forms an identical byte prefix
81
124
  // with the parent session, maximising KV cache hits. The <active_agent>
82
125
  // tag and env block vary per call and are placed after the cached prefix.
83
- return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + customSection + extrasSuffix;
126
+ return identity + "\n\n" + bridge + "\n\n" + activeAgentTag + envBlock + worktreeBlock + workflowBlock + customSection + extrasSuffix;
84
127
  }
85
128
 
86
129
  // "replace" mode — env header + the config's full system prompt
@@ -89,7 +132,7 @@ You have been invoked to handle a specific task autonomously.
89
132
 
90
133
  ${envBlock}`;
91
134
 
92
- return activeAgentTag + replaceHeader + "\n\n" + config.systemPrompt + extrasSuffix;
135
+ return activeAgentTag + replaceHeader + worktreeBlock + workflowBlock + "\n\n" + config.systemPrompt + extrasSuffix;
93
136
  }
94
137
 
95
138
  /** Fallback base prompt when parent system prompt is unavailable in append mode. */