@timmyjl12/pi-subagents 0.0.0-stage → 0.20.0

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