@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.6

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