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