@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,1286 @@
1
+ /**
2
+ * agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
3
+ */
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
8
+ import type { Model } from "@earendil-works/pi-ai";
9
+ import type { ExtensionContext, LoadExtensionsResult } from "@earendil-works/pi-coding-agent";
10
+ import {
11
+ type AgentSession,
12
+ type AgentSessionEvent,
13
+ createAgentSession,
14
+ DefaultResourceLoader,
15
+ type ExtensionAPI,
16
+ getAgentDir,
17
+ SessionManager,
18
+ SettingsManager,
19
+ } from "@earendil-works/pi-coding-agent";
20
+ import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
21
+ import { runInChildSessionContext } from "./child-context.js";
22
+ import { buildParentContext, extractText } from "./context.js";
23
+ import { DEFAULT_AGENTS } from "./default-agents.js";
24
+ import { detectEnv } from "./env.js";
25
+ import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
26
+ import { createNestedSubagentTools, getMaxSubagentDepth, type NestedAgentManager } from "./nested-tools.js";
27
+ import { buildAgentPrompt, type PromptExtras } from "./prompts.js";
28
+ import { preloadSkills } from "./skill-loader.js";
29
+ import { createStructuredCapture, createStructuredOutputTool, structuredRetryPrompt } from "./structured-output.js";
30
+ import type { ServiceTier, SubagentType, ThinkingLevel } from "./types.js";
31
+ import type { LifetimeUsage } from "./usage.js";
32
+ import type { CompiledSchema } from "./workflow/json-schema.js";
33
+
34
+ /**
35
+ * Tool names registered by THIS extension. Single source of truth so the
36
+ * registration sites (index.ts) and the subagent exclusion list below can't
37
+ * drift apart. These are our own tools, not pi built-ins, so they can't be
38
+ * derived from pi — but they only need defining once.
39
+ */
40
+ export const SUBAGENT_TOOL_NAMES = {
41
+ AGENT: "Agent",
42
+ WORKFLOW: "SubagentWorkflow",
43
+ GET_RESULT: "get_subagent_result",
44
+ STEER: "steer_subagent",
45
+ } as const;
46
+
47
+ /** Names of tools registered by this extension that subagents must NOT inherit. */
48
+ const EXCLUDED_TOOL_NAMES: string[] = Object.values(SUBAGENT_TOOL_NAMES);
49
+
50
+ /** APIs whose request payloads support OpenAI service tiers. */
51
+ const SERVICE_TIER_APIS = new Set(["openai-codex-responses", "openai-responses"]);
52
+
53
+ /** Whether an API accepts the OpenAI `service_tier` request field. */
54
+ export function isServiceTierApi(api: string | undefined): boolean {
55
+ return api !== undefined && SERVICE_TIER_APIS.has(api);
56
+ }
57
+
58
+ function isObjectPayload(payload: unknown): payload is Record<string, unknown> {
59
+ return typeof payload === "object" && payload !== null && !Array.isArray(payload);
60
+ }
61
+
62
+ /**
63
+ * Add a custom agent's service tier to compatible provider requests.
64
+ *
65
+ * The existing payload hook belongs to pi's extension lifecycle, so it must be
66
+ * called first and its replacement preserved. An undefined replacement means
67
+ * "keep the original payload" in pi-ai's callback contract.
68
+ */
69
+ export function installServiceTierPayload(
70
+ session: Pick<AgentSession, "agent">,
71
+ serviceTier: ServiceTier | undefined,
72
+ ): void {
73
+ if (serviceTier === undefined) return;
74
+
75
+ const priorOnPayload = session.agent.onPayload;
76
+ session.agent.onPayload = async (payload, requestModel) => {
77
+ const replacement = priorOnPayload
78
+ ? await priorOnPayload(payload, requestModel)
79
+ : undefined;
80
+ const effectivePayload = replacement === undefined ? payload : replacement;
81
+
82
+ if (!isServiceTierApi(requestModel.api) || !isObjectPayload(effectivePayload)) {
83
+ return effectivePayload;
84
+ }
85
+ return { ...effectivePayload, service_tier: serviceTier };
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Canonical name of an extension for `extensions: [...]` allowlist matching.
91
+ * Lowercased — extension names match case-insensitively so `extensions: [Mcp]`
92
+ * resolves the same as `[mcp]`. Tool names within `ext:foo/bar` are not affected.
93
+ * Directory extensions (`foo/index.ts`) resolve to the parent directory name;
94
+ * single-file extensions to the basename minus `.ts`/`.js`.
95
+ */
96
+ export function extensionCanonicalName(extPath: string): string {
97
+ const base = basename(extPath);
98
+ const name = base === "index.ts" || base === "index.js"
99
+ ? basename(dirname(extPath))
100
+ : base.replace(/\.(ts|js)$/, "");
101
+ return name.toLowerCase();
102
+ }
103
+
104
+ /**
105
+ * The unscoped, lowercased npm short name of the pi package that DECLARES
106
+ * `extPath` as an extension entry — or undefined if the entry doesn't belong to
107
+ * such a package.
108
+ *
109
+ * Climbs from the entry's directory looking for the package that owns it, and
110
+ * stays strictly within that package's tree by stopping at two structural
111
+ * boundaries — no hardcoded depth:
112
+ * - the FIRST `package.json` found (the package root); the entry's own
113
+ * manifest always sits at the root, above the entry, below any node_modules.
114
+ * - a `node_modules` directory: a package never spans one (it's where OTHER
115
+ * packages live), so reaching it means we've climbed out of the package —
116
+ * stop before reading a consumer's or parent package's manifest.
117
+ * The name is then taken only when that root's `pi.extensions` manifest actually
118
+ * lists this entry. That "declares this entry" check is deliberate: our own test
119
+ * fixtures live under this repo, whose root manifest declares `./src/index.ts`
120
+ * as `@tintinweb/pi-subagents`, so a looser rule would misattribute every
121
+ * co-located file to `pi-subagents`.
122
+ */
123
+ function extensionPackageName(extPath: string): string | undefined {
124
+ const entry = resolve(extPath);
125
+ let dir = dirname(extPath);
126
+ for (;;) {
127
+ // Climbing into node_modules means we've left the owning package's tree.
128
+ if (basename(dir) === "node_modules") return undefined;
129
+ let pkg: { name?: unknown; pi?: { extensions?: unknown } };
130
+ try {
131
+ pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
132
+ } catch {
133
+ const parent = dirname(dir);
134
+ if (parent === dir) return undefined; // walked to the filesystem root
135
+ dir = parent;
136
+ continue;
137
+ }
138
+ // First package.json wins — it's the package root; decide here.
139
+ const entries = pkg.pi?.extensions;
140
+ if (
141
+ typeof pkg.name === "string" &&
142
+ Array.isArray(entries) &&
143
+ entries.some((e) => typeof e === "string" && resolve(dir, e) === entry)
144
+ ) {
145
+ const short = pkg.name.startsWith("@") ? pkg.name.slice(pkg.name.indexOf("/") + 1) : pkg.name;
146
+ return short.toLowerCase();
147
+ }
148
+ return undefined;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * All names an extension answers to for allowlist matching (lowercased): its
154
+ * path-derived {@link extensionCanonicalName} plus, when a pi package manifest
155
+ * declares this entry, that package's unscoped short name (`@scope/foo` → `foo`).
156
+ * #143: an extension installed via `pi.extensions: ["./src/index.ts"]` would
157
+ * otherwise only ever match as `src` (the source directory), never by its
158
+ * package name. The path-derived name is preserved, so it keeps matching too.
159
+ */
160
+ export function extensionCanonicalNames(extPath: string): string[] {
161
+ const canonical = extensionCanonicalName(extPath);
162
+ const pkg = extensionPackageName(extPath);
163
+ return pkg && pkg !== canonical ? [canonical, pkg] : [canonical];
164
+ }
165
+
166
+ /**
167
+ * Classify `extensions: string[]` frontmatter entries for the loader-level filter.
168
+ *
169
+ * An entry is a PATH iff it contains a path separator or starts with `~`; otherwise
170
+ * it is a NAME. `"*"` sets the wildcard flag (keep all default-discovered extensions).
171
+ *
172
+ * Path entries are resolved (`~` expanded, made absolute against `cwd`) into `paths`
173
+ * — and their canonical name is also added to `names`. The loader override matches
174
+ * everything by canonical name, so path-loaded extensions are matched via their name
175
+ * rather than their post-staging `Extension.path`.
176
+ */
177
+ export function parseExtensionsSpec(
178
+ entries: string[],
179
+ cwd: string,
180
+ ): { names: Set<string>; paths: string[]; wildcard: boolean } {
181
+ const names = new Set<string>();
182
+ const paths: string[] = [];
183
+ let wildcard = false;
184
+ for (const entry of entries) {
185
+ if (!entry) continue;
186
+ if (entry === "*") {
187
+ wildcard = true;
188
+ continue;
189
+ }
190
+ const isPathEntry = entry.includes("/") || entry.includes("\\") || entry.startsWith("~");
191
+ if (!isPathEntry) {
192
+ names.add(entry.toLowerCase());
193
+ continue;
194
+ }
195
+ let p = entry;
196
+ if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
197
+ p = homedir() + p.slice(1);
198
+ }
199
+ const abs = isAbsolute(p) ? p : resolve(cwd, p);
200
+ paths.push(abs);
201
+ names.add(extensionCanonicalName(abs));
202
+ }
203
+ return { names, paths, wildcard };
204
+ }
205
+
206
+ /**
207
+ * Parse raw `ext:` selector strings (from the `tools:` CSV) into the set of
208
+ * extension names to keep loaded and a per-extension tool-narrowing map.
209
+ *
210
+ * `ext:foo` → `extNames` has `foo`, no narrowing entry (all of foo's tools).
211
+ * `ext:foo/bar` → `extNames` has `foo`, `narrowing.foo` has `bar` (only `bar`).
212
+ * A name lands in `narrowing` only when a `/tool` form is seen, so a bare
213
+ * `ext:foo` alongside `ext:foo/bar` leaves narrowing in effect (narrowing wins).
214
+ * The split is on the first `/`; extension canonical names never contain `/`.
215
+ */
216
+ export function parseExtSelectors(entries: string[]): {
217
+ extNames: Set<string>;
218
+ narrowing: Map<string, Set<string>>;
219
+ } {
220
+ const extNames = new Set<string>();
221
+ const narrowing = new Map<string, Set<string>>();
222
+ for (const raw of entries) {
223
+ if (!raw) continue;
224
+ const body = raw.slice("ext:".length);
225
+ const slash = body.indexOf("/");
226
+ // Extension name matches case-insensitively (matches the loader-side canonical
227
+ // name). Tool names are case-preserved — they're matched against pi-mono's
228
+ // registered identifiers, which are case-sensitive.
229
+ const name = (slash === -1 ? body : body.slice(0, slash)).trim().toLowerCase();
230
+ if (!name) continue;
231
+ extNames.add(name);
232
+ if (slash === -1) continue;
233
+ const tool = body.slice(slash + 1).trim();
234
+ if (!tool) continue;
235
+ let set = narrowing.get(name);
236
+ if (!set) {
237
+ set = new Set();
238
+ narrowing.set(name, set);
239
+ }
240
+ set.add(tool);
241
+ }
242
+ return { extNames, narrowing };
243
+ }
244
+
245
+ /**
246
+ * Keep a subagent's tool scope correct as extensions register tools over time.
247
+ *
248
+ * Extensions may call `registerTool` long after load — pi-mcp from `session_start`,
249
+ * context-mode from `before_agent_start` — so scope has to be re-derived rather than
250
+ * snapshotted. `registerTool` writes into the very `extension.tools` maps this reads,
251
+ * so `inScope()` sees late arrivals on the next call.
252
+ *
253
+ * Two enforcement points, because neither covers the whole picture:
254
+ *
255
+ * - `turn_end` re-narrows the ACTIVE set. pi emits `turn_end` immediately before
256
+ * `prepareNextTurn` re-snapshots `agent.state.tools`, and session listeners run
257
+ * synchronously, so the narrow lands in time for turns 2..N.
258
+ * - `beforeToolCall` blocks out-of-scope calls. Turn 1 cannot be narrowed at all:
259
+ * `before_agent_start` fires INSIDE `prompt()` and may widen the tool set, but
260
+ * `createContextSnapshot()` freezes that turn's tools immediately after — there
261
+ * is no hook in between. A call-time check is the only correct guard there.
262
+ *
263
+ * Both are installed on the session and deliberately NOT unsubscribed: they must
264
+ * outlive the `runAgent` call so resumed/steered turns stay scoped. pi's `dispose()`
265
+ * clears `_eventListeners`, so they die with the session rather than leaking.
266
+ *
267
+ * Only meaningful when extensions are loaded — under `noExtensions`/`isolated` the
268
+ * static `allowedToolNames` allowlist already gates the registry itself.
269
+ */
270
+ export function installExtensionToolScope(
271
+ session: AgentSession,
272
+ ctx: {
273
+ loader: DefaultResourceLoader;
274
+ toolNames: string[];
275
+ disallowedSet: Set<string> | undefined;
276
+ extNames: Set<string>;
277
+ narrowing: Map<string, Set<string>>;
278
+ /**
279
+ * Injected `customTools` to keep active regardless of the built-in list.
280
+ *
281
+ * Two kinds arrive here and they are blocked for different reasons: opt-in
282
+ * nested-delegation tools share EXCLUDED_TOOL_NAMES' names, and
283
+ * StructuredOutput is simply not a built-in, so neither survives a `keep`
284
+ * seeded from `toolNames`.
285
+ */
286
+ readmitToolNames: Set<string>;
287
+ },
288
+ ): void {
289
+ const { loader, toolNames, disallowedSet, extNames, narrowing, readmitToolNames } = ctx;
290
+
291
+ // The names allowed right now. Mirrors the `ext:` opt-in flip: when any `ext:`
292
+ // selector is present, extension tools become an explicit allowlist — a loaded
293
+ // extension not named by a selector contributes nothing (its handlers still ran),
294
+ // and `ext:foo/bar` narrows `foo` to just `bar`.
295
+ const inScope = (): Set<string> => {
296
+ const keep = new Set(toolNames.filter((t) => !disallowedSet?.has(t)));
297
+ const optInActive = extNames.size > 0;
298
+ for (const extension of loader.getExtensions().extensions) {
299
+ const canons = extensionCanonicalNames(extension.path);
300
+ if (optInActive && !canons.some((c) => extNames.has(c))) continue;
301
+ // First alias that carries a narrowing set — a user won't narrow one
302
+ // extension under two different names, so first-match is correct.
303
+ const narrowed = canons.map((c) => narrowing.get(c)).find(Boolean);
304
+ for (const name of extension.tools.keys()) {
305
+ if (narrowed && !narrowed.has(name)) continue;
306
+ if (disallowedSet?.has(name)) continue;
307
+ keep.add(name);
308
+ }
309
+ }
310
+ for (const name of EXCLUDED_TOOL_NAMES) keep.delete(name);
311
+ // Injected tools are legitimately active for this agent — re-admit them so
312
+ // the renarrow keeps them in the active set and beforeToolCall doesn't
313
+ // block them. Already vetted against `disallowed_tools` by the caller,
314
+ // which is the only place that knows which kind may be taken back.
315
+ for (const name of readmitToolNames) keep.add(name);
316
+ return keep;
317
+ };
318
+
319
+ const renarrow = () => {
320
+ const allowed = inScope();
321
+ const next = session.getAllTools().map((t) => t.name).filter((n) => allowed.has(n));
322
+ const current = session.getActiveToolNames();
323
+ // setActiveToolsByName unconditionally rebuilds the system prompt, so skip
324
+ // the no-op that steady-state turns would otherwise pay for every turn.
325
+ if (next.length !== current.length || next.some((n, i) => n !== current[i])) {
326
+ session.setActiveToolsByName(next);
327
+ }
328
+ };
329
+
330
+ // Activate what registered during session_start (eager MCP servers); pi would
331
+ // otherwise leave only its four default built-ins active at turn 1.
332
+ renarrow();
333
+
334
+ session.subscribe((event: AgentSessionEvent) => {
335
+ if (event.type === "turn_end") renarrow();
336
+ });
337
+
338
+ const priorBeforeToolCall = session.agent.beforeToolCall;
339
+ session.agent.beforeToolCall = async (context, signal) => {
340
+ if (!inScope().has(context.toolCall.name)) {
341
+ return {
342
+ block: true,
343
+ reason: `Tool "${context.toolCall.name}" is not available to this subagent.`,
344
+ };
345
+ }
346
+ return priorBeforeToolCall?.(context, signal);
347
+ };
348
+ }
349
+
350
+ /** Default max turns. undefined = unlimited (no turn limit). */
351
+ let defaultMaxTurns: number | undefined;
352
+
353
+ /** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
354
+ export function normalizeMaxTurns(n: number | undefined): number | undefined {
355
+ if (n == null || n === 0) return undefined;
356
+ return Math.max(1, n);
357
+ }
358
+
359
+ /** Get the default max turns value. undefined = unlimited. */
360
+ export function getDefaultMaxTurns(): number | undefined { return defaultMaxTurns; }
361
+ /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
362
+ export function setDefaultMaxTurns(n: number | undefined): void { defaultMaxTurns = normalizeMaxTurns(n); }
363
+
364
+ /**
365
+ * The turn limit a run of `type` will actually enforce: an explicit value if the
366
+ * caller supplied one, else the agent's own `max_turns`, else the project
367
+ * default. `undefined` = unlimited.
368
+ *
369
+ * Exported because the widget's turn counter (`↻3≤20`) has to predict this
370
+ * before the run starts, and a second copy of the expression would drift from
371
+ * the one below that enforces it.
372
+ */
373
+ export function resolveEffectiveMaxTurns(type: string, explicit?: number): number | undefined {
374
+ return normalizeMaxTurns(explicit ?? getAgentConfig(type)?.maxTurns ?? defaultMaxTurns);
375
+ }
376
+
377
+ /**
378
+ * Project default for `persist_session`, from the `rememberAgents` setting.
379
+ * On by default: a persisted session is what lets `@handle` reopen an agent's
380
+ * conversation after its record has been evicted, which is the whole point of
381
+ * addressing an agent by a name that outlives one run. Per-agent frontmatter
382
+ * still overrides it in both directions.
383
+ */
384
+ let rememberAgents = true;
385
+
386
+ /** Whether subagent sessions are persisted by default. */
387
+ export function getRememberAgents(): boolean { return rememberAgents; }
388
+ /** Set whether subagent sessions are persisted by default. */
389
+ export function setRememberAgents(b: boolean): void { rememberAgents = b; }
390
+
391
+ /** Additional turns allowed after the soft limit steer message. */
392
+ let graceTurns = 5;
393
+
394
+ /** Get the grace turns value. */
395
+ export function getGraceTurns(): number { return graceTurns; }
396
+ /** Set the grace turns value (minimum 1). */
397
+ export function setGraceTurns(n: number): void { graceTurns = Math.max(1, n); }
398
+
399
+ /**
400
+ * Try to find the right model for an agent type.
401
+ * Priority: explicit option > config.model > parent model.
402
+ */
403
+ export function resolveDefaultModel(
404
+ parentModel: Model<any> | undefined,
405
+ registry: { find(provider: string, modelId: string): Model<any> | undefined; getAvailable?(): Model<any>[] },
406
+ configModel?: string,
407
+ ): Model<any> | undefined {
408
+ if (configModel) {
409
+ const slashIdx = configModel.indexOf("/");
410
+ if (slashIdx !== -1) {
411
+ const provider = configModel.slice(0, slashIdx);
412
+ const modelId = configModel.slice(slashIdx + 1);
413
+
414
+ // Build a set of available model keys for fast lookup
415
+ const available = registry.getAvailable?.();
416
+ const availableKeys = available
417
+ ? new Set(available.map((m: any) => `${m.provider}/${m.id}`))
418
+ : undefined;
419
+ const isAvailable = (p: string, id: string) =>
420
+ !availableKeys || availableKeys.has(`${p}/${id}`);
421
+
422
+ const found = registry.find(provider, modelId);
423
+ if (found && isAvailable(provider, modelId)) return found;
424
+ }
425
+ }
426
+
427
+ return parentModel;
428
+ }
429
+
430
+ /** Info about a tool event in the subagent. */
431
+ export interface ToolActivity {
432
+ type: "start" | "end";
433
+ toolName: string;
434
+ }
435
+
436
+ export interface RunOptions {
437
+ /** ExtensionAPI instance — used for pi.exec() instead of execSync. */
438
+ pi: ExtensionAPI;
439
+ /** Manager-assigned id; suffixes session name to disambiguate parallel spawns (e.g. `Explore#a1b2c3d4`). */
440
+ agentId?: string;
441
+ model?: Model<any>;
442
+ maxTurns?: number;
443
+ signal?: AbortSignal;
444
+ isolated?: boolean;
445
+ inheritContext?: boolean;
446
+ thinkingLevel?: ThinkingLevel;
447
+ /**
448
+ * Reopen this pi session file rather than starting an empty conversation.
449
+ * `createAgentSession` seeds itself from whatever its SessionManager holds,
450
+ * so pointing it at an existing file rehydrates that agent's history and the
451
+ * prompt continues it. Everything else — tools, model, system prompt, turn
452
+ * caps — is still resolved from the agent type, so the continuation runs
453
+ * under the type's *current* definition, not the one the original run used.
454
+ */
455
+ resumeSessionFile?: string;
456
+ /**
457
+ * True when another agent spawned this one. Only top-level agents get a
458
+ * handle, so only they can be reopened by name — which is the whole reason
459
+ * `rememberAgents` persists a session at all. A nested run's transcript would
460
+ * be unreachable by anything, so it stays in memory unless its own
461
+ * frontmatter asks otherwise.
462
+ */
463
+ nested?: boolean;
464
+ /**
465
+ * True when a workflow run spawned this agent. Its final text is the value
466
+ * `agent()` resolves to rather than a report a person reads, and the prompt
467
+ * says so — but only when `structuredOutput` is unset, since that child
468
+ * already has a `StructuredOutput` tool to answer through and two competing
469
+ * "this is how you return your answer" instructions is worse than one.
470
+ */
471
+ workflow?: boolean;
472
+ /** Override working directory (e.g. for worktree isolation). */
473
+ cwd?: string;
474
+ /**
475
+ * Directory the worktree copy was created from. Set only when `cwd` points
476
+ * into a worktree — the prompt then tells the agent to stay in the copy
477
+ * instead of following the inherited parent prompt back to the main tree.
478
+ */
479
+ worktreeBase?: string;
480
+ /**
481
+ * Where .pi config is discovered (project extensions, skills, pi settings,
482
+ * agent memory). Default: same as the working directory. The manager sets
483
+ * this to the parent session's cwd when `SpawnOptions.cwd` points the
484
+ * working directory elsewhere — the agent works *there* but carries the
485
+ * parent project's config (the target's `.pi` extensions never execute).
486
+ *
487
+ * WARNING for future callers: if you pass `cwd` pointing at a directory the
488
+ * user didn't open, you almost certainly must pass `configCwd` too —
489
+ * omitting it makes the target's `.pi` extensions execute in this process.
490
+ * (Worktree isolation is the one intentional exception: its copy IS the
491
+ * parent's repo, so config resolving inside it is correct.)
492
+ */
493
+ configCwd?: string;
494
+ /** Called on tool start/end with activity info. */
495
+ onToolActivity?: (activity: ToolActivity) => void;
496
+ /** Called on streaming text deltas from the assistant response. */
497
+ onTextDelta?: (delta: string, fullText: string) => void;
498
+ onSessionCreated?: (session: AgentSession) => void;
499
+ /** Called at the end of each agentic turn with the cumulative count. */
500
+ onTurnEnd?: (turnCount: number) => void;
501
+ /**
502
+ * Called once per assistant message_end with that message's usage delta.
503
+ * Lets callers maintain a lifetime accumulator that survives compaction
504
+ * (which replaces session.state.messages and resets stats-derived sums).
505
+ *
506
+ * `cost` is pi's own `usage.cost.total` for that message — priced from the
507
+ * model's rates, so it is 0 (not missing) for a model pi has no pricing for.
508
+ * We never price anything ourselves; every dollar figure this extension shows
509
+ * or reports traces back to this field.
510
+ */
511
+ onAssistantUsage?: (usage: LifetimeUsage) => void;
512
+ /**
513
+ * Called when the session successfully compacts. `tokensBefore` is upstream's
514
+ * pre-compaction context size estimate. Aborted compactions don't fire.
515
+ */
516
+ onCompaction?: (info: { reason: "manual" | "threshold" | "overflow"; tokensBefore: number }) => void;
517
+ /**
518
+ * Make this child report through a `StructuredOutput` tool built from this
519
+ * schema, and put the validated payload on {@link RunResult.structuredJson}.
520
+ *
521
+ * Already compiled by the caller, so a schema this runtime cannot validate
522
+ * fails at the call that wrote it rather than inside the child.
523
+ */
524
+ structuredOutput?: CompiledSchema;
525
+ /** Runtime bridge for opt-in child-safe nested delegation. */
526
+ nestedRuntime?: {
527
+ manager: NestedAgentManager;
528
+ parentAgentId: string;
529
+ depth: number;
530
+ maxSubagentDepth?: number;
531
+ };
532
+ }
533
+
534
+ export interface RunResult {
535
+ responseText: string;
536
+ session: AgentSession;
537
+ /** True if the agent was hard-aborted (max_turns + grace exceeded). */
538
+ aborted: boolean;
539
+ /** True if the agent was steered to wrap up (hit soft turn limit) but finished in time. */
540
+ steered: boolean;
541
+ /**
542
+ * A failure message for the run's FINAL assistant turn, when that turn failed:
543
+ * a provider error (stopReason "error"), or a "length" stop that produced no
544
+ * text (a silent max-token death). pi resolves an exhausted-retries failure
545
+ * normally instead of rejecting, so without this the manager would report such
546
+ * a run as completed — with an empty result, or worse, an earlier turn's text
547
+ * presented as the answer (#144). Undefined for a clean stop, or a "length"
548
+ * stop that produced text (a legitimate truncated answer).
549
+ */
550
+ failure?: string;
551
+ /**
552
+ * The validated `StructuredOutput` payload as canonical JSON, when the caller
553
+ * asked for a schema and the child produced one.
554
+ *
555
+ * Deliberately not folded into {@link responseText}: `record.result` picks up
556
+ * a worktree branch note on the way out, which would leave the caller with
557
+ * unparseable JSON, and merging the two would make "produced structured
558
+ * output" indistinguishable from "happened to answer in JSON".
559
+ */
560
+ structuredJson?: string;
561
+ /** Whether the extra structured-output prompt had to be sent. */
562
+ structuredRetried?: boolean;
563
+ }
564
+
565
+ /**
566
+ * Subscribe to a session and collect the last assistant message text.
567
+ * Returns an object with a `getText()` getter and an `unsubscribe` function.
568
+ */
569
+ function collectResponseText(session: AgentSession) {
570
+ let text = "";
571
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
572
+ // message_start also fires for user and toolResult messages — resetting on
573
+ // those would wipe assistant text already collected. Reset only when a new
574
+ // ASSISTANT message begins, so getText() is the last assistant message's text.
575
+ if (event.type === "message_start" && event.message.role === "assistant") {
576
+ text = "";
577
+ }
578
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
579
+ text += event.assistantMessageEvent.delta;
580
+ }
581
+ });
582
+ return { getText: () => text, unsubscribe };
583
+ }
584
+
585
+ /**
586
+ * Get the last non-empty assistant text produced during THIS invocation.
587
+ * `startIndex` is the message count captured before the prompt, so the walk-back
588
+ * never crosses into a previous turn: on a resume whose new turn failed empty,
589
+ * this returns "" instead of the prior turn's answer (#144). Defaults to 0 (a
590
+ * fresh spawn, where the whole history belongs to this run).
591
+ */
592
+ function getLastAssistantText(session: AgentSession, startIndex = 0): string {
593
+ for (let i = session.messages.length - 1; i >= startIndex; i--) {
594
+ const msg = session.messages[i];
595
+ if (msg.role !== "assistant") continue;
596
+ const text = extractText(msg.content).trim();
597
+ if (text) return text;
598
+ }
599
+ return "";
600
+ }
601
+
602
+ /**
603
+ * Error message of THIS invocation's final assistant message, when that turn
604
+ * failed. Two failure shapes, both keyed off how the final turn STOPPED:
605
+ * - stopReason "error": a provider failure pi resolved instead of rejecting
606
+ * (any text; partial output is surfaced separately).
607
+ * - stopReason "length" with NO text: a silent max-token death — the run hit
608
+ * the output-token ceiling before writing anything, which would otherwise
609
+ * land as a "completed" run with an empty result (the #144 symptom).
610
+ * Everything else completes: a clean "stop"/"toolUse" final, and — crucially — a
611
+ * "length" stop that DID produce text (a legitimate truncated-but-useful answer).
612
+ * "aborted" is handled by the manager's abort flag / "stopped" guard, not here.
613
+ * Bounded by `startIndex` (like the text fallback) so a resume that produced no
614
+ * assistant message of its own never inherits a PRIOR turn's stop reason.
615
+ */
616
+ function finalTurnError(session: AgentSession, startIndex = 0): string | undefined {
617
+ for (let i = session.messages.length - 1; i >= startIndex; i--) {
618
+ const msg = session.messages[i];
619
+ if (msg.role !== "assistant") continue;
620
+ if (msg.stopReason === "error") {
621
+ return (msg as { errorMessage?: string }).errorMessage?.trim() || "provider error with no output";
622
+ }
623
+ if (msg.stopReason === "length" && !extractText(msg.content).trim()) {
624
+ return "run hit the output token limit before producing any text";
625
+ }
626
+ return undefined;
627
+ }
628
+ return undefined;
629
+ }
630
+
631
+ /**
632
+ * Wire an AbortSignal to abort a session.
633
+ * Returns a cleanup function to remove the listener.
634
+ */
635
+ function forwardAbortSignal(session: AgentSession, signal?: AbortSignal): () => void {
636
+ if (!signal) return () => {};
637
+ const onAbort = () => session.abort();
638
+ signal.addEventListener("abort", onAbort, { once: true });
639
+ return () => signal.removeEventListener("abort", onAbort);
640
+ }
641
+
642
+ function resolveConfiguredSessionDir(sessionDir: string | undefined, cwd: string): string | undefined {
643
+ if (!sessionDir) return undefined;
644
+ if (sessionDir === "~" || sessionDir.startsWith("~/")) return resolve(homedir(), sessionDir.slice(2));
645
+ if (isAbsolute(sessionDir)) return sessionDir;
646
+ return resolve(cwd, sessionDir);
647
+ }
648
+
649
+ export async function runAgent(
650
+ ctx: ExtensionContext,
651
+ type: SubagentType,
652
+ prompt: string,
653
+ options: RunOptions,
654
+ ): Promise<RunResult> {
655
+ const config = getConfig(type);
656
+ const agentConfig = getAgentConfig(type);
657
+
658
+ // Resolve working directory: worktree override > parent cwd
659
+ const effectiveCwd = options.cwd ?? ctx.cwd;
660
+ // Filesystem work happens in effectiveCwd; config discovery in configCwd.
661
+ // They differ only for SpawnOptions.cwd spawns (config stays with the parent).
662
+ const configCwd = options.configCwd ?? effectiveCwd;
663
+
664
+ const env = await detectEnv(options.pi, effectiveCwd);
665
+
666
+ // Get parent system prompt for append-mode agents
667
+ const parentSystemPrompt = ctx.getSystemPrompt();
668
+
669
+ // Build prompt extras (memory, skill preloading)
670
+ const extras: PromptExtras = {};
671
+ if (options.worktreeBase) extras.worktreeBase = options.worktreeBase;
672
+ if (options.workflow && !options.structuredOutput) extras.workflowChild = true;
673
+
674
+ // Resolve extensions/skills: isolated overrides to false
675
+ const extensions = options.isolated ? false : config.extensions;
676
+ // Nulling excludes under isolated also suppresses the orphaned-exclude warning —
677
+ // isolation is an intentional override, not a misconfiguration.
678
+ const excludeExtensions = options.isolated ? undefined : config.excludeExtensions;
679
+ const skills = options.isolated ? false : config.skills;
680
+
681
+ // Skill preloading: when skills is string[], preload their content into prompt
682
+ if (Array.isArray(skills)) {
683
+ const loaded = preloadSkills(skills, configCwd);
684
+ if (loaded.length > 0) {
685
+ extras.skillBlocks = loaded;
686
+ }
687
+ }
688
+
689
+ let toolNames = getToolNamesForType(type);
690
+
691
+ // Persistent memory: detect write capability and branch accordingly.
692
+ // Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
693
+ if (agentConfig?.memory) {
694
+ const existingNames = new Set(toolNames);
695
+ const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
696
+ const effectivelyHas = (name: string) => existingNames.has(name) && !denied?.has(name);
697
+ const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
698
+
699
+ if (hasWriteTools) {
700
+ // Read-write memory: add any missing memory tool names (read/write/edit)
701
+ const extraNames = getMemoryToolNames(existingNames);
702
+ if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames];
703
+ extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
704
+ } else {
705
+ // Read-only memory: only add read tool name, use read-only prompt
706
+ const extraNames = getReadOnlyMemoryToolNames(existingNames);
707
+ if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames];
708
+ extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
709
+ }
710
+ }
711
+
712
+ // Build system prompt from agent config
713
+ let systemPrompt: string;
714
+ if (agentConfig) {
715
+ systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras);
716
+ } else {
717
+ // Unknown type fallback: spread the canonical general-purpose config (defensive —
718
+ // unreachable in practice since index.ts resolves unknown types before calling runAgent).
719
+ const fallback = DEFAULT_AGENTS.get("general-purpose");
720
+ if (!fallback) throw new Error(`No fallback config available for unknown type "${type}"`);
721
+ systemPrompt = buildAgentPrompt({ ...fallback, name: type }, effectiveCwd, env, parentSystemPrompt, extras);
722
+ }
723
+
724
+ // When skills is string[], we've already preloaded them into the prompt.
725
+ // Still pass noSkills: true since we don't need the skill loader to load them again.
726
+ const noSkills = skills === false || Array.isArray(skills);
727
+
728
+ const agentDir = getAgentDir();
729
+
730
+ // Extension loading:
731
+ // - true → all default-discovered extensions
732
+ // - false → none (noExtensions)
733
+ // - string[] → loader-level allowlist. Bare names keep the matching
734
+ // default-discovered extension; path entries load that extension fresh;
735
+ // "*" keeps all default-discovered extensions. Excluded extensions never
736
+ // bind handlers or register tools (their factory still runs once).
737
+ //
738
+ // Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md — upstream's
739
+ // buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
740
+ // would defeat prompt_mode: replace and isolated: true. Parent context, if
741
+ // wanted, reaches the subagent via prompt_mode: append (parentSystemPrompt
742
+ // is embedded in systemPromptOverride) or inherit_context (conversation).
743
+ // `ext:` selectors from the `tools:` CSV narrow which extension tools surface to
744
+ // the LLM. They do NOT control loading — `extensions:` is the sole authority for
745
+ // which extensions load. `ext:foo` against an extension that `extensions:` excluded
746
+ // is an orphan and warns after reload. `isolated` means no extension tools at all.
747
+ const { extNames, narrowing } = parseExtSelectors(
748
+ options.isolated ? [] : (agentConfig?.extSelectors ?? []),
749
+ );
750
+ const noExtensions = extensions === false;
751
+
752
+ const extensionsSpec = Array.isArray(extensions)
753
+ ? parseExtensionsSpec(extensions, configCwd)
754
+ : undefined;
755
+ const keepNames = extensionsSpec?.names ?? new Set<string>();
756
+ // `exclude_extensions:` is a denylist applied AFTER the include set — exclude wins.
757
+ // Plain canonical names only (case-insensitive). Note: excluded extensions'
758
+ // factories still run once during reload() (see comment above) — exclusion
759
+ // suppresses handler binding and tool registration; it is not a sandbox.
760
+ const excludeNames = new Set((excludeExtensions ?? []).map((n) => n.toLowerCase()));
761
+ const hasExcludes = excludeNames.size > 0;
762
+ // The override filters loaded extensions down to `keepNames` minus `excludeNames`.
763
+ // It's only needed when we're neither loading everything without excludes
764
+ // (`extensions: true` or a `"*"` wildcard) nor nothing (`noExtensions`).
765
+ const loadAll = extensions === true || extensionsSpec?.wildcard === true;
766
+ const additionalExtensionPaths = extensionsSpec?.paths.length ? extensionsSpec.paths : undefined;
767
+ // Pre-filter discovered set, captured by the override — the exclude-typo warning
768
+ // must compare against this, not the surviving set (absence from survivors is
769
+ // an exclude *succeeding*).
770
+ let discoveredNames: Set<string> | undefined;
771
+ const extensionsOverride: ((base: LoadExtensionsResult) => LoadExtensionsResult) | undefined =
772
+ noExtensions || (loadAll && !hasExcludes)
773
+ ? undefined
774
+ : (base) => {
775
+ discoveredNames = new Set(base.extensions.flatMap((e) => extensionCanonicalNames(e.path)));
776
+ return {
777
+ ...base,
778
+ extensions: base.extensions.filter((e) => {
779
+ const canons = extensionCanonicalNames(e.path);
780
+ if (canons.some((n) => excludeNames.has(n))) return false; // exclude wins
781
+ return loadAll || canons.some((n) => keepNames.has(n));
782
+ }),
783
+ };
784
+ };
785
+
786
+ const loader = new DefaultResourceLoader({
787
+ cwd: configCwd,
788
+ agentDir,
789
+ noExtensions,
790
+ additionalExtensionPaths,
791
+ extensionsOverride,
792
+ noSkills,
793
+ noPromptTemplates: true,
794
+ noThemes: true,
795
+ noContextFiles: true,
796
+ systemPromptOverride: () => systemPrompt,
797
+ appendSystemPromptOverride: () => [],
798
+ });
799
+ await runInChildSessionContext(() => loader.reload());
800
+
801
+ // Plain entries in `tools:` are expected to be built-in names (extension tools
802
+ // go through `ext:`), so an unknown name there is unambiguously a typo. Previously
803
+ // this produced a silently broken agent (#75) — pi-mono accepted the bogus name
804
+ // into the allowlist, then dropped it at registration with no signal back.
805
+ if (agentConfig?.builtinToolNames?.length) {
806
+ const knownBuiltins = new Set(BUILTIN_TOOL_NAMES);
807
+ for (const name of agentConfig.builtinToolNames) {
808
+ if (!knownBuiltins.has(name)) {
809
+ options.onToolActivity?.({
810
+ type: "end",
811
+ toolName: `tools-error:tool "${name}" requested by agent "${type}" is not a known built-in`,
812
+ });
813
+ }
814
+ }
815
+ }
816
+
817
+ // A subagent spawns mid-task, so a bad `extensions:`/`ext:` entry warns rather
818
+ // than aborts. Two distinct misconfigurations to catch:
819
+ // - `extensions: [foo]` but no extension named foo was discovered (typo or
820
+ // path that failed to load — path entries fold their canonical name into
821
+ // `keepNames`, so this covers them too).
822
+ // - `tools: ext:foo` but foo isn't in the loaded set (because `extensions:`
823
+ // didn't include it). Since v0.9, `ext:` no longer pulls extensions in;
824
+ // loading is `extensions:`-authoritative.
825
+ // An exclude_extensions: alongside extensions: false is contradictory — nothing
826
+ // loads, so there is nothing to exclude.
827
+ if (hasExcludes && noExtensions) {
828
+ options.onToolActivity?.({
829
+ type: "end",
830
+ toolName: `extension-error:exclude_extensions has no effect for agent "${type}" — extensions: false loads nothing`,
831
+ });
832
+ }
833
+ // Exclude typo check: compares against the PRE-filter discovered set (an excluded
834
+ // name absent from the surviving set is the exclude working as intended). Also
835
+ // flags path-like and "*" entries — excludes are plain names only.
836
+ if (hasExcludes && discoveredNames) {
837
+ for (const name of excludeNames) {
838
+ if (!discoveredNames.has(name)) {
839
+ options.onToolActivity?.({
840
+ type: "end",
841
+ toolName: `extension-error:exclude_extensions: "${name}" for agent "${type}" did not match any discovered extension`,
842
+ });
843
+ }
844
+ }
845
+ }
846
+ if (keepNames.size > 0 || extNames.size > 0) {
847
+ const survivingNames = new Set(
848
+ loader.getExtensions().extensions.flatMap((e) => extensionCanonicalNames(e.path)),
849
+ );
850
+ for (const name of keepNames) {
851
+ if (!survivingNames.has(name)) {
852
+ options.onToolActivity?.({
853
+ type: "end",
854
+ toolName: excludeNames.has(name)
855
+ ? `extension-error:extension "${name}" is in both extensions: and exclude_extensions: for agent "${type}" — exclude wins`
856
+ : `extension-error:extension "${name}" requested by agent "${type}" was not loaded`,
857
+ });
858
+ }
859
+ }
860
+ for (const name of extNames) {
861
+ if (!survivingNames.has(name)) {
862
+ options.onToolActivity?.({
863
+ type: "end",
864
+ toolName: `extension-error:ext:${name} referenced by agent "${type}" but extension "${name}" is not loaded (check extensions:/exclude_extensions:)`,
865
+ });
866
+ }
867
+ }
868
+ }
869
+
870
+ // Resolve model: explicit option > config.model > parent model
871
+ const model = options.model ?? resolveDefaultModel(
872
+ ctx.model, ctx.modelRegistry, agentConfig?.model,
873
+ );
874
+
875
+ // Resolve thinking level: explicit option > agent config > undefined (inherit)
876
+ const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
877
+
878
+ const disallowedSet = agentConfig?.disallowedTools
879
+ ? new Set(agentConfig.disallowedTools)
880
+ : undefined;
881
+
882
+ // Nested delegation tools (opt-in, ownership-scoped). Empty unless the agent
883
+ // set `allowed_subagents` and a nestedRuntime was provided — and never when
884
+ // isolated. Their names collide with EXCLUDED_TOOL_NAMES by design, so the
885
+ // scoping below re-admits them explicitly (registry deny + active-set narrow).
886
+ const effectiveMaxDepth = options.nestedRuntime?.maxSubagentDepth ?? getMaxSubagentDepth();
887
+ // At (or past) the cap this agent can never spawn, so it can never own a child
888
+ // to fetch from or steer either — inject nothing rather than three tools whose
889
+ // every call is an error. This is also what makes `maxSubagentDepth` 0/1 mean
890
+ // "nesting off" instead of "nesting always fails".
891
+ const nestedRuntime = options.nestedRuntime && options.nestedRuntime.depth < effectiveMaxDepth
892
+ ? options.nestedRuntime
893
+ : undefined;
894
+ const nestedTools = agentConfig?.allowedSubagents && nestedRuntime && !options.isolated
895
+ ? createNestedSubagentTools({
896
+ manager: nestedRuntime.manager,
897
+ pi: options.pi,
898
+ parentAgentId: nestedRuntime.parentAgentId,
899
+ depth: nestedRuntime.depth,
900
+ maxSubagentDepth: effectiveMaxDepth,
901
+ allowedSubagents: agentConfig.allowedSubagents,
902
+ configCwd,
903
+ })
904
+ : [];
905
+ const nestedToolNames = new Set(nestedTools.map(tool => tool.name));
906
+
907
+ // The `agent({ schema })` contract: this child reports its answer by calling
908
+ // StructuredOutput, and `structuredJson` below is what the caller reads. The
909
+ // schema was already compiled by whoever asked for it, so a bad one failed
910
+ // before any of this ran.
911
+ const structuredCapture = options.structuredOutput ? createStructuredCapture() : undefined;
912
+ const structuredTools = options.structuredOutput && structuredCapture
913
+ ? [createStructuredOutputTool(options.structuredOutput, structuredCapture)]
914
+ : [];
915
+ const structuredToolNames = new Set(structuredTools.map(tool => tool.name));
916
+ // Re-admitted together at every gate below. Kept as one set so a new injected
917
+ // tool cannot be added to some of the three gates and forgotten at the rest.
918
+ //
919
+ // `disallowed_tools` is applied HERE rather than at the gates, because the two
920
+ // kinds answer to it differently: a nested delegation tool is an opt-in the
921
+ // agent's own frontmatter can take back, while StructuredOutput exists only
922
+ // because this call asked for a schema — removing it would make the request
923
+ // unsatisfiable by construction rather than merely restricted.
924
+ const readmitToolNames = new Set([
925
+ ...[...nestedToolNames].filter(name => !disallowedSet?.has(name)),
926
+ ...structuredToolNames,
927
+ ]);
928
+
929
+ // ─── Tool scoping ───────────────────────────────────────────────────────
930
+ //
931
+ // Some extensions register their tools ASYNCHRONOUSLY, long after the
932
+ // `loader.reload()` above: pi-mcp calls registerTool from `session_start`
933
+ // (once its MCP servers connect), context-mode from `before_agent_start`.
934
+ // That is deliberate on their part — eagerly spawning an MCP bridge during
935
+ // extension discovery orphans child processes on pi's non-agent code paths
936
+ // (--help, config, trust probing).
937
+ //
938
+ // So the tool set cannot be snapshotted here. pi's `allowedToolNames` gates
939
+ // tool *registration* (`_refreshToolRegistry`'s `isAllowedTool`), not merely
940
+ // the active set, and is frozen at construction — a name absent from the
941
+ // snapshot is dropped forever, even once the tool actually registers (#125).
942
+ //
943
+ // Whenever extensions are in play we therefore:
944
+ // - leave `allowedToolNames` unset, so pi's live gate admits tools whenever
945
+ // they register;
946
+ // - express the name-stable, permanent part of the scope (our own
947
+ // orchestration tools, built-ins the agent didn't ask for, and
948
+ // `disallowedTools`) as `excludeTools`, which pi re-applies on every
949
+ // registry refresh;
950
+ // - enforce `ext:` narrowing on the ACTIVE set via the live `inScope()`
951
+ // predicate installed after bind — the active set is what the LLM sees,
952
+ // so a registry tool that is never activated is invisible and uncallable.
953
+ //
954
+ // `noExtensions`/`isolated` keeps the historical static allowlist: nothing
955
+ // async can appear there, and a hard registry gate is the correct boundary.
956
+ const builtinToolNameSet = new Set(toolNames);
957
+
958
+ let sessionTools: string[] | undefined;
959
+ let sessionExcludeTools: string[] | undefined;
960
+ if (noExtensions) {
961
+ // Strict allowlist: built-ins the agent asked for, plus any opt-in nested
962
+ // tools (whose names would otherwise be dropped as EXCLUDED_TOOL_NAMES).
963
+ sessionTools = [
964
+ ...toolNames.filter(
965
+ (t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t),
966
+ ),
967
+ ...[...nestedToolNames].filter((t) => !disallowedSet?.has(t)),
968
+ // Not filtered through `disallowedSet`, unlike the nested tools above:
969
+ // the caller asked for a schema, and removing the only tool that can
970
+ // satisfy it would make the request unsatisfiable by construction rather
971
+ // than merely restricted.
972
+ ...structuredToolNames,
973
+ ];
974
+ } else {
975
+ // Deny the orchestration tools EXCEPT the nested ones this agent opted into —
976
+ // those are injected as customTools and must survive the registry gate.
977
+ const denyTools = new Set<string>(
978
+ EXCLUDED_TOOL_NAMES.filter((t) => !nestedToolNames.has(t)),
979
+ );
980
+ // Keep only the built-ins the agent asked for — deny the rest.
981
+ for (const name of BUILTIN_TOOL_NAMES) {
982
+ if (!builtinToolNameSet.has(name)) denyTools.add(name);
983
+ }
984
+ if (disallowedSet) {
985
+ // disallowed_tools wins even over an opt-in nested tool of the same name.
986
+ // Not over StructuredOutput, though — see the allowlist branch above.
987
+ for (const name of disallowedSet) {
988
+ if (!structuredToolNames.has(name)) denyTools.add(name);
989
+ }
990
+ }
991
+ sessionExcludeTools = [...denyTools];
992
+ }
993
+
994
+ const settingsManager = SettingsManager.create(configCwd, agentDir);
995
+ const configuredSessionDir = resolveConfiguredSessionDir(agentConfig?.sessionDir, effectiveCwd);
996
+ const defaultSessionDir = process.env.PI_CODING_AGENT_SESSION_DIR ?? settingsManager.getSessionDir?.();
997
+ // Frontmatter wins when it says anything; otherwise the project default,
998
+ // which `rememberAgents` supplies for top-level agents only. Same precedence
999
+ // as `outputTranscript`.
1000
+ const persistSession = agentConfig?.persistSession ?? (options.nested ? false : rememberAgents);
1001
+ const sessionManager = options.resumeSessionFile
1002
+ // Reopening an existing conversation: the file already carries its own
1003
+ // header (cwd, parent) and history, so none of the create-time options
1004
+ // apply. `sessionDir` still matters for a later /new or /branch off it.
1005
+ ? SessionManager.open(options.resumeSessionFile, configuredSessionDir ?? defaultSessionDir)
1006
+ : persistSession
1007
+ ? SessionManager.create(effectiveCwd, configuredSessionDir ?? defaultSessionDir, {
1008
+ // Optional metadata — it only nests the subagent under its spawner in
1009
+ // `/resume`. Until `rememberAgents` this ran solely for the rare
1010
+ // `persist_session: true` agent; now it runs for every spawn, so a
1011
+ // context without a session manager (a bare programmatic ctx) must
1012
+ // still persist rather than take the whole spawn down.
1013
+ parentSession: ctx.sessionManager?.getSessionFile?.(),
1014
+ })
1015
+ : SessionManager.inMemory(effectiveCwd);
1016
+
1017
+ // Pi 0.80.8 replaced createAgentSession's modelRegistry option with
1018
+ // modelRuntime, but ExtensionContext still exposes only the registry facade.
1019
+ // Pass both so the full supported Pi range retains the parent's providers.
1020
+ const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: unknown }).runtime;
1021
+ const sessionOpts: Parameters<typeof createAgentSession>[0] & {
1022
+ modelRegistry: ExtensionContext["modelRegistry"];
1023
+ modelRuntime?: unknown;
1024
+ } = {
1025
+ cwd: effectiveCwd,
1026
+ agentDir,
1027
+ sessionManager,
1028
+ settingsManager,
1029
+ modelRegistry: ctx.modelRegistry,
1030
+ // `as never` is what keeps this assignable across the supported Pi range:
1031
+ // pre-0.80.8 the field exists only via the `modelRuntime?: unknown` shim
1032
+ // above, while newer Pi types it as `ModelRuntime` — a shape an opaque
1033
+ // `unknown` read off the private facade field can never satisfy.
1034
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime as never }),
1035
+ model,
1036
+ tools: sessionTools,
1037
+ customTools: [...nestedTools, ...structuredTools],
1038
+ resourceLoader: loader,
1039
+ };
1040
+ if (sessionExcludeTools) {
1041
+ sessionOpts.excludeTools = sessionExcludeTools;
1042
+ }
1043
+ if (thinkingLevel) {
1044
+ sessionOpts.thinkingLevel = thinkingLevel;
1045
+ }
1046
+
1047
+ const { session } = await runInChildSessionContext(() => createAgentSession(sessionOpts));
1048
+
1049
+ const baseSessionName = agentConfig?.name ?? type;
1050
+ session.setSessionName(
1051
+ options.agentId ? `${baseSessionName}#${options.agentId.slice(0, 8)}` : baseSessionName,
1052
+ );
1053
+
1054
+ // Bind extensions so that session_start fires and extensions can initialize
1055
+ // (e.g. loading credentials, setting up state). Tool gating already happened
1056
+ // at session construction via the `tools:` allowlist above — no separate
1057
+ // post-bind filter is needed. All ExtensionBindings fields are optional.
1058
+ await session.bindExtensions({
1059
+ onError: (err) => {
1060
+ options.onToolActivity?.({
1061
+ type: "end",
1062
+ toolName: `extension-error:${err.extensionPath}`,
1063
+ });
1064
+ },
1065
+ });
1066
+
1067
+ installServiceTierPayload(session, agentConfig?.serviceTier);
1068
+
1069
+ // With `allowedToolNames` unset, the registry is scoped by `excludeTools` but
1070
+ // the ACTIVE set still needs managing: pi activates only its four default
1071
+ // built-ins at turn 1, and `ext:` narrowing has no registry-level expression
1072
+ // (we can't deny the name of a tool that hasn't registered yet). Both are
1073
+ // handled below by re-deriving scope from the loader's live extension maps —
1074
+ // `registerTool` writes into those same maps, so late arrivals are judged too.
1075
+ if (!noExtensions) {
1076
+ installExtensionToolScope(session, {
1077
+ loader,
1078
+ toolNames,
1079
+ disallowedSet,
1080
+ extNames,
1081
+ narrowing,
1082
+ readmitToolNames,
1083
+ });
1084
+ }
1085
+
1086
+ options.onSessionCreated?.(session);
1087
+
1088
+ // Track turns for graceful max_turns enforcement
1089
+ let turnCount = 0;
1090
+ const maxTurns = resolveEffectiveMaxTurns(type, options.maxTurns);
1091
+ let softLimitReached = false;
1092
+ let aborted = false;
1093
+
1094
+ let currentMessageText = "";
1095
+ const unsubTurns = session.subscribe((event: AgentSessionEvent) => {
1096
+ if (event.type === "turn_end") {
1097
+ turnCount++;
1098
+ options.onTurnEnd?.(turnCount);
1099
+ if (maxTurns != null) {
1100
+ if (!softLimitReached && turnCount >= maxTurns) {
1101
+ softLimitReached = true;
1102
+ session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
1103
+ } else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
1104
+ aborted = true;
1105
+ session.abort();
1106
+ }
1107
+ }
1108
+ }
1109
+ if (event.type === "message_start") {
1110
+ currentMessageText = "";
1111
+ }
1112
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
1113
+ currentMessageText += event.assistantMessageEvent.delta;
1114
+ options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
1115
+ }
1116
+ if (event.type === "tool_execution_start") {
1117
+ options.onToolActivity?.({ type: "start", toolName: event.toolName });
1118
+ }
1119
+ if (event.type === "tool_execution_end") {
1120
+ options.onToolActivity?.({ type: "end", toolName: event.toolName });
1121
+ }
1122
+ if (event.type === "message_end" && event.message.role === "assistant") {
1123
+ const u = (event.message as any).usage;
1124
+ if (u) options.onAssistantUsage?.({
1125
+ input: u.input ?? 0,
1126
+ output: u.output ?? 0,
1127
+ cacheWrite: u.cacheWrite ?? 0,
1128
+ cacheRead: u.cacheRead ?? 0,
1129
+ cost: u.cost?.total ?? 0,
1130
+ });
1131
+ }
1132
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
1133
+ options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
1134
+ }
1135
+ });
1136
+
1137
+ const collector = collectResponseText(session);
1138
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
1139
+
1140
+ // Build the effective prompt: optionally prepend parent context
1141
+ let effectivePrompt = prompt;
1142
+ if (options.inheritContext) {
1143
+ const parentContext = buildParentContext(ctx);
1144
+ if (parentContext) {
1145
+ effectivePrompt = parentContext + prompt;
1146
+ }
1147
+ }
1148
+
1149
+ // Boundary for the history fallback: only assistant text produced from here
1150
+ // on counts as this run's output (a fresh session, so usually 0).
1151
+ const startLen = session.messages.length;
1152
+ let structuredRetried = false;
1153
+ try {
1154
+ await session.prompt(effectivePrompt);
1155
+
1156
+ // One more prompt when a schema was asked for and nothing usable came back
1157
+ // — the model answered in prose, or only ever called the tool invalidly.
1158
+ // Inside this `try`, so the turn tracking, the text collector and above all
1159
+ // the abort forwarding are still live: torn down first, a retry would be
1160
+ // unkillable.
1161
+ if (structuredCapture !== undefined && structuredCapture.json === undefined
1162
+ && !aborted && options.signal?.aborted !== true) {
1163
+ structuredRetried = true;
1164
+ await session.prompt(structuredRetryPrompt(structuredCapture));
1165
+ }
1166
+ } finally {
1167
+ unsubTurns();
1168
+ collector.unsubscribe();
1169
+ cleanupAbort();
1170
+ }
1171
+
1172
+ const responseText = collector.getText().trim() || getLastAssistantText(session, startLen);
1173
+ // A child asked for structured output that never gave any has failed, however
1174
+ // articulate its prose was. Reported through `failure` so it travels the same
1175
+ // path as a provider error rather than arriving as a successful empty answer.
1176
+ const structuredFailure = structuredCapture !== undefined && structuredCapture.json === undefined
1177
+ ? structuredCapture.lastError !== undefined
1178
+ ? `The agent's StructuredOutput call did not match the required schema: ${structuredCapture.lastError}`
1179
+ : "The agent did not report its answer through StructuredOutput."
1180
+ : undefined;
1181
+ return {
1182
+ responseText,
1183
+ session,
1184
+ aborted,
1185
+ steered: softLimitReached,
1186
+ failure: finalTurnError(session, startLen) ?? structuredFailure,
1187
+ ...(structuredCapture?.json !== undefined ? { structuredJson: structuredCapture.json } : {}),
1188
+ ...(structuredRetried ? { structuredRetried } : {}),
1189
+ };
1190
+ }
1191
+
1192
+ /**
1193
+ * Send a new prompt to an existing session (resume).
1194
+ */
1195
+ export async function resumeAgent(
1196
+ session: AgentSession,
1197
+ prompt: string,
1198
+ options: {
1199
+ onToolActivity?: (activity: ToolActivity) => void;
1200
+ onAssistantUsage?: (usage: LifetimeUsage) => void;
1201
+ onCompaction?: (info: { reason: "manual" | "threshold" | "overflow"; tokensBefore: number }) => void;
1202
+ signal?: AbortSignal;
1203
+ } = {},
1204
+ ): Promise<{ text: string; failure?: string }> {
1205
+ // Boundary for the history fallback: the session already holds prior turns,
1206
+ // so only assistant text produced by THIS resume prompt counts as its output
1207
+ // — a failed resume must not surface the previous turn's answer (#144).
1208
+ const startLen = session.messages.length;
1209
+ const collector = collectResponseText(session);
1210
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
1211
+
1212
+ const unsubEvents = (options.onToolActivity || options.onAssistantUsage || options.onCompaction)
1213
+ ? session.subscribe((event: AgentSessionEvent) => {
1214
+ if (event.type === "tool_execution_start") options.onToolActivity?.({ type: "start", toolName: event.toolName });
1215
+ if (event.type === "tool_execution_end") options.onToolActivity?.({ type: "end", toolName: event.toolName });
1216
+ if (event.type === "message_end" && event.message.role === "assistant") {
1217
+ const u = (event.message as any).usage;
1218
+ if (u) options.onAssistantUsage?.({
1219
+ input: u.input ?? 0,
1220
+ output: u.output ?? 0,
1221
+ cacheWrite: u.cacheWrite ?? 0,
1222
+ cacheRead: u.cacheRead ?? 0,
1223
+ cost: u.cost?.total ?? 0,
1224
+ });
1225
+ }
1226
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
1227
+ options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
1228
+ }
1229
+ })
1230
+ : () => {};
1231
+
1232
+ try {
1233
+ await session.prompt(prompt);
1234
+ } finally {
1235
+ collector.unsubscribe();
1236
+ unsubEvents();
1237
+ cleanupAbort();
1238
+ }
1239
+
1240
+ return {
1241
+ text: collector.getText().trim() || getLastAssistantText(session, startLen),
1242
+ failure: finalTurnError(session, startLen),
1243
+ };
1244
+ }
1245
+
1246
+ /**
1247
+ * Send a steering message to a running subagent.
1248
+ * The message will interrupt the agent after its current tool execution.
1249
+ */
1250
+ export async function steerAgent(
1251
+ session: AgentSession,
1252
+ message: string,
1253
+ ): Promise<void> {
1254
+ await session.steer(message);
1255
+ }
1256
+
1257
+ /**
1258
+ * Get the subagent's conversation messages as formatted text.
1259
+ */
1260
+ export function getAgentConversation(session: AgentSession): string {
1261
+ const parts: string[] = [];
1262
+
1263
+ for (const msg of session.messages) {
1264
+ if (msg.role === "user") {
1265
+ const text = typeof msg.content === "string"
1266
+ ? msg.content
1267
+ : extractText(msg.content);
1268
+ if (text.trim()) parts.push(`[User]: ${text.trim()}`);
1269
+ } else if (msg.role === "assistant") {
1270
+ const textParts: string[] = [];
1271
+ const toolCalls: string[] = [];
1272
+ for (const c of msg.content) {
1273
+ if (c.type === "text" && c.text) textParts.push(c.text);
1274
+ else if (c.type === "toolCall") toolCalls.push(` Tool: ${(c as any).name ?? (c as any).toolName ?? "unknown"}`);
1275
+ }
1276
+ if (textParts.length > 0) parts.push(`[Assistant]: ${textParts.join("\n")}`);
1277
+ if (toolCalls.length > 0) parts.push(`[Tool Calls]:\n${toolCalls.join("\n")}`);
1278
+ } else if (msg.role === "toolResult") {
1279
+ const text = extractText(msg.content);
1280
+ const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text;
1281
+ parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`);
1282
+ }
1283
+ }
1284
+
1285
+ return parts.join("\n\n");
1286
+ }