@diousk/pi-subagents-fast 0.20.0

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