opensec-pi-subagents 0.19.1

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