@timmyjl12/pi-subagents 0.0.0-stage → 0.20.0

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