@clanker-code/pi-subagents 0.10.5

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 (130) hide show
  1. package/.plans/PLAN-next-changes.md +183 -0
  2. package/.plans/README.md +14 -0
  3. package/AGENTS.md +31 -0
  4. package/CHANGELOG.md +583 -0
  5. package/CLAUDE.md +1 -0
  6. package/LICENSE +21 -0
  7. package/README.md +630 -0
  8. package/RELEASE.md +39 -0
  9. package/dist/abort-resend.d.ts +35 -0
  10. package/dist/abort-resend.js +71 -0
  11. package/dist/agent-details.d.ts +17 -0
  12. package/dist/agent-details.js +22 -0
  13. package/dist/agent-manager.d.ts +132 -0
  14. package/dist/agent-manager.js +493 -0
  15. package/dist/agent-runner.d.ts +165 -0
  16. package/dist/agent-runner.js +732 -0
  17. package/dist/agent-tool-description.d.ts +9 -0
  18. package/dist/agent-tool-description.js +147 -0
  19. package/dist/agent-types.d.ts +60 -0
  20. package/dist/agent-types.js +157 -0
  21. package/dist/context.d.ts +12 -0
  22. package/dist/context.js +56 -0
  23. package/dist/cross-extension-rpc.d.ts +46 -0
  24. package/dist/cross-extension-rpc.js +76 -0
  25. package/dist/custom-agents.d.ts +14 -0
  26. package/dist/custom-agents.js +149 -0
  27. package/dist/default-agents.d.ts +7 -0
  28. package/dist/default-agents.js +119 -0
  29. package/dist/enabled-models.d.ts +49 -0
  30. package/dist/enabled-models.js +145 -0
  31. package/dist/env.d.ts +6 -0
  32. package/dist/env.js +28 -0
  33. package/dist/group-join.d.ts +32 -0
  34. package/dist/group-join.js +116 -0
  35. package/dist/index.d.ts +36 -0
  36. package/dist/index.js +1918 -0
  37. package/dist/invocation-config.d.ts +25 -0
  38. package/dist/invocation-config.js +19 -0
  39. package/dist/memory.d.ts +49 -0
  40. package/dist/memory.js +151 -0
  41. package/dist/model-resolver.d.ts +19 -0
  42. package/dist/model-resolver.js +62 -0
  43. package/dist/notifications.d.ts +6 -0
  44. package/dist/notifications.js +107 -0
  45. package/dist/output-file.d.ts +24 -0
  46. package/dist/output-file.js +86 -0
  47. package/dist/peek.d.ts +37 -0
  48. package/dist/peek.js +121 -0
  49. package/dist/prompts.d.ts +40 -0
  50. package/dist/prompts.js +95 -0
  51. package/dist/schedule-store.d.ts +38 -0
  52. package/dist/schedule-store.js +155 -0
  53. package/dist/schedule.d.ts +109 -0
  54. package/dist/schedule.js +338 -0
  55. package/dist/settings.d.ts +135 -0
  56. package/dist/settings.js +168 -0
  57. package/dist/skill-loader.d.ts +24 -0
  58. package/dist/skill-loader.js +93 -0
  59. package/dist/status-note.d.ts +13 -0
  60. package/dist/status-note.js +24 -0
  61. package/dist/types.d.ts +184 -0
  62. package/dist/types.js +7 -0
  63. package/dist/ui/agent-tool-rendering.d.ts +34 -0
  64. package/dist/ui/agent-tool-rendering.js +154 -0
  65. package/dist/ui/agent-widget-tree.d.ts +33 -0
  66. package/dist/ui/agent-widget-tree.js +130 -0
  67. package/dist/ui/agent-widget.d.ts +156 -0
  68. package/dist/ui/agent-widget.js +408 -0
  69. package/dist/ui/conversation-viewer.d.ts +47 -0
  70. package/dist/ui/conversation-viewer.js +290 -0
  71. package/dist/ui/menu-select.d.ts +20 -0
  72. package/dist/ui/menu-select.js +46 -0
  73. package/dist/ui/schedule-menu.d.ts +16 -0
  74. package/dist/ui/schedule-menu.js +99 -0
  75. package/dist/ui/viewer-keys.d.ts +20 -0
  76. package/dist/ui/viewer-keys.js +17 -0
  77. package/dist/usage.d.ts +50 -0
  78. package/dist/usage.js +49 -0
  79. package/dist/wait.d.ts +10 -0
  80. package/dist/wait.js +37 -0
  81. package/dist/worktree.d.ts +45 -0
  82. package/dist/worktree.js +160 -0
  83. package/docs/design/default-extension-tool-exposure.md +56 -0
  84. package/docs/superpowers/plans/2026-06-19-recursive-subagent-widget.md +600 -0
  85. package/docs/superpowers/specs/2026-06-19-recursive-subagent-widget-design.md +189 -0
  86. package/examples/agent-tool-description.md +45 -0
  87. package/package.json +56 -0
  88. package/reviews/proposal-structured-output-schema.md +135 -0
  89. package/reviews/recursive-subagent-widget-preview-rev2.png +0 -0
  90. package/reviews/recursive-subagent-widget-preview.html +137 -0
  91. package/reviews/recursive-subagent-widget-preview.png +0 -0
  92. package/reviews/subagent-features-comparison.md +350 -0
  93. package/src/abort-resend.ts +75 -0
  94. package/src/agent-details.ts +31 -0
  95. package/src/agent-manager.ts +596 -0
  96. package/src/agent-runner.ts +872 -0
  97. package/src/agent-tool-description.ts +163 -0
  98. package/src/agent-types.ts +189 -0
  99. package/src/context.ts +58 -0
  100. package/src/cross-extension-rpc.ts +122 -0
  101. package/src/custom-agents.ts +160 -0
  102. package/src/default-agents.ts +123 -0
  103. package/src/enabled-models.ts +180 -0
  104. package/src/env.ts +33 -0
  105. package/src/group-join.ts +141 -0
  106. package/src/index.ts +2115 -0
  107. package/src/invocation-config.ts +42 -0
  108. package/src/memory.ts +165 -0
  109. package/src/model-resolver.ts +81 -0
  110. package/src/notifications.ts +120 -0
  111. package/src/output-file.ts +96 -0
  112. package/src/peek.ts +155 -0
  113. package/src/prompts.ts +129 -0
  114. package/src/schedule-store.ts +153 -0
  115. package/src/schedule.ts +365 -0
  116. package/src/settings.ts +289 -0
  117. package/src/skill-loader.ts +102 -0
  118. package/src/status-note.ts +25 -0
  119. package/src/types.ts +195 -0
  120. package/src/ui/agent-tool-rendering.ts +175 -0
  121. package/src/ui/agent-widget-tree.ts +169 -0
  122. package/src/ui/agent-widget.ts +497 -0
  123. package/src/ui/conversation-viewer.ts +297 -0
  124. package/src/ui/menu-select.ts +68 -0
  125. package/src/ui/schedule-menu.ts +105 -0
  126. package/src/ui/viewer-keys.ts +39 -0
  127. package/src/usage.ts +60 -0
  128. package/src/wait.ts +44 -0
  129. package/src/worktree.ts +191 -0
  130. package/vitest.config.ts +25 -0
@@ -0,0 +1,732 @@
1
+ /**
2
+ * agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
3
+ */
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
+ import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
+ import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
9
+ import { buildParentContext, extractText } from "./context.js";
10
+ import { DEFAULT_AGENTS } from "./default-agents.js";
11
+ import { detectEnv } from "./env.js";
12
+ import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
13
+ import { buildAgentPrompt } from "./prompts.js";
14
+ import { preloadSkills } from "./skill-loader.js";
15
+ import { MAX_RECURSIVE_DEPTH } from "./types.js";
16
+ /**
17
+ * Tool names registered by THIS extension. Single source of truth so the
18
+ * registration sites (index.ts) and the subagent exclusion list below can't
19
+ * drift apart. These are our own tools, not pi built-ins, so they can't be
20
+ * derived from pi — but they only need defining once.
21
+ */
22
+ export const SUBAGENT_TOOL_NAMES = {
23
+ AGENT: "Agent",
24
+ GET_RESULT: "get_subagent_result",
25
+ STEER: "steer_subagent",
26
+ LIST_MODELS: "list_models",
27
+ };
28
+ /**
29
+ * Names of tools registered by this extension that are GATED by recursive depth.
30
+ * Subset of SUBAGENT_TOOL_NAMES — only the tools that can spawn or address
31
+ * further subagents. Read-only / introspection tools like `list_models` are
32
+ * available at every depth so an agent can still ask questions about the
33
+ * environment even when it can't delegate.
34
+ */
35
+ const RECURSIVE_TOOL_NAMES = [
36
+ SUBAGENT_TOOL_NAMES.AGENT,
37
+ SUBAGENT_TOOL_NAMES.GET_RESULT,
38
+ SUBAGENT_TOOL_NAMES.STEER,
39
+ ];
40
+ const EXTENSION_DEPTH_KEY = Symbol.for("pi-subagents:extension-depth");
41
+ const AUTO_EXPOSE_EXTENSION_NAMES = new Set(["pi-c2c"]);
42
+ let extensionDepthLoadChain = Promise.resolve();
43
+ const packageNameCache = new Map();
44
+ function getLoadingExtensionDepth() {
45
+ const value = globalThis[EXTENSION_DEPTH_KEY];
46
+ if (typeof value === "number" && Number.isFinite(value))
47
+ return value;
48
+ if (value && typeof value.depth === "number" && Number.isFinite(value.depth))
49
+ return value.depth;
50
+ return 0;
51
+ }
52
+ function getLoadingExtensionAgentId() {
53
+ const value = globalThis[EXTENSION_DEPTH_KEY];
54
+ return value && typeof value.agentId === "string" ? value.agentId : undefined;
55
+ }
56
+ async function withLoadingExtensionDepth(depth, agentId, fn) {
57
+ const previous = extensionDepthLoadChain;
58
+ let release;
59
+ extensionDepthLoadChain = new Promise((resolve) => {
60
+ release = resolve;
61
+ });
62
+ await previous;
63
+ try {
64
+ const g = globalThis;
65
+ const prev = g[EXTENSION_DEPTH_KEY];
66
+ g[EXTENSION_DEPTH_KEY] = { depth, agentId };
67
+ try {
68
+ return await fn();
69
+ }
70
+ finally {
71
+ if (prev === undefined)
72
+ delete g[EXTENSION_DEPTH_KEY];
73
+ else
74
+ g[EXTENSION_DEPTH_KEY] = prev;
75
+ }
76
+ }
77
+ finally {
78
+ release();
79
+ }
80
+ }
81
+ export function getCurrentExtensionDepth() {
82
+ return getLoadingExtensionDepth();
83
+ }
84
+ export function getCurrentExtensionAgentId() {
85
+ return getLoadingExtensionAgentId();
86
+ }
87
+ /**
88
+ * Canonical name of an extension for `extensions: [...]` allowlist matching.
89
+ * Lowercased — extension names match case-insensitively so `extensions: [Mcp]`
90
+ * resolves the same as `[mcp]`. Tool names within `ext:foo/bar` are not affected.
91
+ * Directory extensions (`foo/index.ts`) resolve to the parent directory name;
92
+ * single-file extensions to the basename minus `.ts`/`.js`.
93
+ */
94
+ export function extensionCanonicalName(extPath) {
95
+ const base = basename(extPath);
96
+ const name = base === "index.ts" || base === "index.js"
97
+ ? basename(dirname(extPath))
98
+ : base.replace(/\.(ts|js)$/, "");
99
+ return name.toLowerCase();
100
+ }
101
+ function packageNameCandidates(name) {
102
+ const lower = name.toLowerCase();
103
+ const slash = lower.lastIndexOf("/");
104
+ return slash === -1 ? [lower] : [lower, lower.slice(slash + 1)];
105
+ }
106
+ function extensionMatchNames(extPath) {
107
+ const names = new Set([extensionCanonicalName(extPath)]);
108
+ const packageNames = packageNameCache.get(extPath);
109
+ if (packageNames) {
110
+ for (const name of packageNames)
111
+ names.add(name);
112
+ return names;
113
+ }
114
+ const found = [];
115
+ let dir = dirname(extPath);
116
+ while (dir && dir !== dirname(dir)) {
117
+ const packageJson = join(dir, "package.json");
118
+ if (existsSync(packageJson)) {
119
+ try {
120
+ const parsed = JSON.parse(readFileSync(packageJson, "utf8"));
121
+ if (typeof parsed.name === "string" && parsed.name.trim()) {
122
+ found.push(...packageNameCandidates(parsed.name.trim()));
123
+ }
124
+ }
125
+ catch {
126
+ // Ignore malformed package metadata; path-based canonicalization remains.
127
+ }
128
+ break;
129
+ }
130
+ dir = dirname(dir);
131
+ }
132
+ packageNameCache.set(extPath, found);
133
+ for (const name of found)
134
+ names.add(name);
135
+ return names;
136
+ }
137
+ function extensionMatchesName(extPath, names) {
138
+ if (names.size === 0)
139
+ return false;
140
+ for (const candidate of extensionMatchNames(extPath)) {
141
+ if (names.has(candidate))
142
+ return true;
143
+ }
144
+ return false;
145
+ }
146
+ function extensionMatchingSelector(extPath, selectors) {
147
+ for (const candidate of extensionMatchNames(extPath)) {
148
+ if (selectors.has(candidate))
149
+ return candidate;
150
+ }
151
+ return undefined;
152
+ }
153
+ /**
154
+ * Classify `extensions: string[]` frontmatter entries for the loader-level filter.
155
+ *
156
+ * An entry is a PATH iff it contains a path separator or starts with `~`; otherwise
157
+ * it is a NAME. `"*"` sets the wildcard flag (keep all default-discovered extensions).
158
+ *
159
+ * Path entries are resolved (`~` expanded, made absolute against `cwd`) into `paths`
160
+ * — and their canonical name is also added to `names`. The loader override matches
161
+ * everything by canonical name, so path-loaded extensions are matched via their name
162
+ * rather than their post-staging `Extension.path`.
163
+ */
164
+ export function parseExtensionsSpec(entries, cwd) {
165
+ const names = new Set();
166
+ const paths = [];
167
+ let wildcard = false;
168
+ for (const entry of entries) {
169
+ if (!entry)
170
+ continue;
171
+ if (entry === "*") {
172
+ wildcard = true;
173
+ continue;
174
+ }
175
+ const isPathEntry = entry.includes("/") || entry.includes("\\") || entry.startsWith("~");
176
+ if (!isPathEntry) {
177
+ names.add(entry.toLowerCase());
178
+ continue;
179
+ }
180
+ let p = entry;
181
+ if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
182
+ p = homedir() + p.slice(1);
183
+ }
184
+ const abs = isAbsolute(p) ? p : resolve(cwd, p);
185
+ paths.push(abs);
186
+ names.add(extensionCanonicalName(abs));
187
+ }
188
+ return { names, paths, wildcard };
189
+ }
190
+ /**
191
+ * Parse raw `ext:` selector strings (from the `tools:` CSV) into the set of
192
+ * extension names to keep loaded and a per-extension tool-narrowing map.
193
+ *
194
+ * `ext:foo` → `extNames` has `foo`, no narrowing entry (all of foo's tools).
195
+ * `ext:foo/bar` → `extNames` has `foo`, `narrowing.foo` has `bar` (only `bar`).
196
+ * A name lands in `narrowing` only when a `/tool` form is seen, so a bare
197
+ * `ext:foo` alongside `ext:foo/bar` leaves narrowing in effect (narrowing wins).
198
+ * The split is on the first `/`; extension canonical names never contain `/`.
199
+ */
200
+ export function parseExtSelectors(entries) {
201
+ const extNames = new Set();
202
+ const narrowing = new Map();
203
+ for (const raw of entries) {
204
+ if (!raw)
205
+ continue;
206
+ const body = raw.slice("ext:".length);
207
+ const slash = body.indexOf("/");
208
+ // Extension name matches case-insensitively (matches the loader-side canonical
209
+ // name). Tool names are case-preserved — they're matched against pi-mono's
210
+ // registered identifiers, which are case-sensitive.
211
+ const name = (slash === -1 ? body : body.slice(0, slash)).trim().toLowerCase();
212
+ if (!name)
213
+ continue;
214
+ extNames.add(name);
215
+ if (slash === -1)
216
+ continue;
217
+ const tool = body.slice(slash + 1).trim();
218
+ if (!tool)
219
+ continue;
220
+ let set = narrowing.get(name);
221
+ if (!set) {
222
+ set = new Set();
223
+ narrowing.set(name, set);
224
+ }
225
+ set.add(tool);
226
+ }
227
+ return { extNames, narrowing };
228
+ }
229
+ /** Default max turns. undefined = unlimited (no turn limit). */
230
+ let defaultMaxTurns;
231
+ /** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
232
+ export function normalizeMaxTurns(n) {
233
+ if (n == null || n === 0)
234
+ return undefined;
235
+ return Math.max(1, n);
236
+ }
237
+ /** Get the default max turns value. undefined = unlimited. */
238
+ export function getDefaultMaxTurns() { return defaultMaxTurns; }
239
+ /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
240
+ export function setDefaultMaxTurns(n) { defaultMaxTurns = normalizeMaxTurns(n); }
241
+ /** Additional turns allowed after the soft limit steer message. */
242
+ let graceTurns = 5;
243
+ /** Get the grace turns value. */
244
+ export function getGraceTurns() { return graceTurns; }
245
+ /** Set the grace turns value (minimum 1). */
246
+ export function setGraceTurns(n) { graceTurns = Math.max(1, n); }
247
+ /**
248
+ * Try to find the right model for an agent type.
249
+ * Priority: explicit option > config.model > parent model.
250
+ */
251
+ function resolveDefaultModel(parentModel, registry, configModel) {
252
+ if (configModel) {
253
+ const slashIdx = configModel.indexOf("/");
254
+ if (slashIdx !== -1) {
255
+ const provider = configModel.slice(0, slashIdx);
256
+ const modelId = configModel.slice(slashIdx + 1);
257
+ // Build a set of available model keys for fast lookup
258
+ const available = registry.getAvailable?.();
259
+ const availableKeys = available
260
+ ? new Set(available.map((m) => `${m.provider}/${m.id}`))
261
+ : undefined;
262
+ const isAvailable = (p, id) => !availableKeys || availableKeys.has(`${p}/${id}`);
263
+ const found = registry.find(provider, modelId);
264
+ if (found && isAvailable(provider, modelId))
265
+ return found;
266
+ }
267
+ }
268
+ return parentModel;
269
+ }
270
+ /**
271
+ * Subscribe to a session and collect the last assistant message text.
272
+ * Returns an object with a `getText()` getter and an `unsubscribe` function.
273
+ */
274
+ function collectResponseText(session) {
275
+ let text = "";
276
+ const unsubscribe = session.subscribe((event) => {
277
+ if (event.type === "message_start") {
278
+ text = "";
279
+ }
280
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
281
+ text += event.assistantMessageEvent.delta;
282
+ }
283
+ });
284
+ return { getText: () => text, unsubscribe };
285
+ }
286
+ /** Get the last assistant text from the completed session history. */
287
+ function getLastAssistantText(session) {
288
+ for (let i = session.messages.length - 1; i >= 0; i--) {
289
+ const msg = session.messages[i];
290
+ if (msg.role !== "assistant")
291
+ continue;
292
+ const text = extractText(msg.content).trim();
293
+ if (text)
294
+ return text;
295
+ }
296
+ return "";
297
+ }
298
+ /**
299
+ * Wire an AbortSignal to abort a session.
300
+ * Returns a cleanup function to remove the listener.
301
+ */
302
+ function forwardAbortSignal(session, signal) {
303
+ if (!signal)
304
+ return () => { };
305
+ const onAbort = () => session.abort();
306
+ signal.addEventListener("abort", onAbort, { once: true });
307
+ return () => signal.removeEventListener("abort", onAbort);
308
+ }
309
+ export async function runAgent(ctx, type, prompt, options) {
310
+ const config = getConfig(type);
311
+ const agentConfig = getAgentConfig(type);
312
+ // Resolve working directory: worktree override > parent cwd
313
+ const effectiveCwd = options.cwd ?? ctx.cwd;
314
+ // Filesystem work happens in effectiveCwd; config discovery in configCwd.
315
+ // They differ only for SpawnOptions.cwd spawns (config stays with the parent).
316
+ const configCwd = options.configCwd ?? effectiveCwd;
317
+ const env = await detectEnv(options.pi, effectiveCwd);
318
+ // Get parent system prompt for append-mode agents
319
+ const parentSystemPrompt = ctx.getSystemPrompt();
320
+ // Build prompt extras (memory, skill preloading)
321
+ const depth = options.depth ?? 1;
322
+ const extras = {
323
+ agentId: options.agentId,
324
+ parentAgentId: options.parentAgentId,
325
+ depth,
326
+ maxDepth: MAX_RECURSIVE_DEPTH,
327
+ };
328
+ // Resolve extensions/skills: isolated overrides to false
329
+ const extensions = options.isolated ? false : config.extensions;
330
+ // Nulling excludes under isolated also suppresses the orphaned-exclude warning —
331
+ // isolation is an intentional override, not a misconfiguration.
332
+ const excludeExtensions = options.isolated ? undefined : config.excludeExtensions;
333
+ const skills = options.isolated ? false : config.skills;
334
+ // Skill preloading: when skills is string[], preload their content into prompt
335
+ if (Array.isArray(skills)) {
336
+ const loaded = preloadSkills(skills, configCwd);
337
+ if (loaded.length > 0) {
338
+ extras.skillBlocks = loaded;
339
+ }
340
+ }
341
+ let toolNames = getToolNamesForType(type);
342
+ // Persistent memory: detect write capability and branch accordingly.
343
+ // Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
344
+ if (agentConfig?.memory) {
345
+ const existingNames = new Set(toolNames);
346
+ const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
347
+ const effectivelyHas = (name) => existingNames.has(name) && !denied?.has(name);
348
+ const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
349
+ if (hasWriteTools) {
350
+ // Read-write memory: add any missing memory tool names (read/write/edit)
351
+ const extraNames = getMemoryToolNames(existingNames);
352
+ if (extraNames.length > 0)
353
+ toolNames = [...toolNames, ...extraNames];
354
+ extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
355
+ }
356
+ else {
357
+ // Read-only memory: only add read tool name, use read-only prompt
358
+ const extraNames = getReadOnlyMemoryToolNames(existingNames);
359
+ if (extraNames.length > 0)
360
+ toolNames = [...toolNames, ...extraNames];
361
+ extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, configCwd);
362
+ }
363
+ }
364
+ // Build system prompt from agent config
365
+ let systemPrompt;
366
+ if (agentConfig) {
367
+ systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras);
368
+ }
369
+ else {
370
+ // Unknown type fallback: spread the canonical general-purpose config (defensive —
371
+ // unreachable in practice since index.ts resolves unknown types before calling runAgent).
372
+ const fallback = DEFAULT_AGENTS.get("general-purpose");
373
+ if (!fallback)
374
+ throw new Error(`No fallback config available for unknown type "${type}"`);
375
+ systemPrompt = buildAgentPrompt({ ...fallback, name: type }, effectiveCwd, env, parentSystemPrompt, extras);
376
+ }
377
+ // When skills is string[], we've already preloaded them into the prompt.
378
+ // Still pass noSkills: true since we don't need the skill loader to load them again.
379
+ const noSkills = skills === false || Array.isArray(skills);
380
+ const agentDir = getAgentDir();
381
+ // Extension loading:
382
+ // - true → all default-discovered extensions
383
+ // - false → none (noExtensions)
384
+ // - string[] → loader-level allowlist. Bare names keep the matching
385
+ // default-discovered extension; path entries load that extension fresh;
386
+ // "*" keeps all default-discovered extensions. Excluded extensions never
387
+ // bind handlers or register tools (their factory still runs once).
388
+ //
389
+ // Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md — upstream's
390
+ // buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
391
+ // would defeat prompt_mode: replace and isolated: true. Parent context, if
392
+ // wanted, reaches the subagent via prompt_mode: append (parentSystemPrompt
393
+ // is embedded in systemPromptOverride) or inherit_context (conversation).
394
+ // `ext:` selectors from the `tools:` CSV narrow which extension tools surface to
395
+ // the LLM. They do NOT control loading — `extensions:` is the sole authority for
396
+ // which extensions load. `ext:foo` against an extension that `extensions:` excluded
397
+ // is an orphan and warns after reload. `isolated` means no extension tools at all.
398
+ const { extNames, narrowing } = parseExtSelectors(options.isolated ? [] : (agentConfig?.extSelectors ?? []));
399
+ const noExtensions = extensions === false;
400
+ const extensionsSpec = Array.isArray(extensions)
401
+ ? parseExtensionsSpec(extensions, configCwd)
402
+ : undefined;
403
+ const keepNames = extensionsSpec?.names ?? new Set();
404
+ // `exclude_extensions:` is a denylist applied AFTER the include set — exclude wins.
405
+ // Plain canonical names only (case-insensitive). Note: excluded extensions'
406
+ // factories still run once during reload() (see comment above) — exclusion
407
+ // suppresses handler binding and tool registration; it is not a sandbox.
408
+ const excludeNames = new Set((excludeExtensions ?? []).map((n) => n.toLowerCase()));
409
+ const hasExcludes = excludeNames.size > 0;
410
+ // The override filters loaded extensions down to `keepNames` minus `excludeNames`.
411
+ // It's only needed when we're neither loading everything without excludes
412
+ // (`extensions: true` or a `"*"` wildcard) nor nothing (`noExtensions`).
413
+ const loadAll = extensions === true || extensionsSpec?.wildcard === true;
414
+ const additionalExtensionPaths = extensionsSpec?.paths.length ? extensionsSpec.paths : undefined;
415
+ // Pre-filter discovered set, captured by the override — the exclude-typo warning
416
+ // must compare against this, not the surviving set (absence from survivors is
417
+ // an exclude *succeeding*).
418
+ let discoveredNames;
419
+ const extensionsOverride = noExtensions || (loadAll && !hasExcludes)
420
+ ? undefined
421
+ : (base) => {
422
+ discoveredNames = new Set(base.extensions.flatMap((e) => Array.from(extensionMatchNames(e.path))));
423
+ return {
424
+ ...base,
425
+ extensions: base.extensions.filter((e) => {
426
+ if (extensionMatchesName(e.path, excludeNames))
427
+ return false; // exclude wins
428
+ return loadAll || extensionMatchesName(e.path, keepNames);
429
+ }),
430
+ };
431
+ };
432
+ const loader = new DefaultResourceLoader({
433
+ cwd: configCwd,
434
+ agentDir,
435
+ noExtensions,
436
+ additionalExtensionPaths,
437
+ extensionsOverride,
438
+ noSkills,
439
+ noPromptTemplates: true,
440
+ noThemes: true,
441
+ noContextFiles: true,
442
+ systemPromptOverride: () => systemPrompt,
443
+ appendSystemPromptOverride: () => [],
444
+ });
445
+ await withLoadingExtensionDepth(depth, options.agentId, () => loader.reload());
446
+ // Plain entries in `tools:` are expected to be built-in names (extension tools
447
+ // go through `ext:`), so an unknown name there is unambiguously a typo. Previously
448
+ // this produced a silently broken agent (#75) — pi-mono accepted the bogus name
449
+ // into the allowlist, then dropped it at registration with no signal back.
450
+ if (agentConfig?.builtinToolNames?.length) {
451
+ const knownBuiltins = new Set(BUILTIN_TOOL_NAMES);
452
+ for (const name of agentConfig.builtinToolNames) {
453
+ if (!knownBuiltins.has(name)) {
454
+ options.onToolActivity?.({
455
+ type: "end",
456
+ toolName: `tools-error:tool "${name}" requested by agent "${type}" is not a known built-in`,
457
+ });
458
+ }
459
+ }
460
+ }
461
+ // A subagent spawns mid-task, so a bad `extensions:`/`ext:` entry warns rather
462
+ // than aborts. Two distinct misconfigurations to catch:
463
+ // - `extensions: [foo]` but no extension named foo was discovered (typo or
464
+ // path that failed to load — path entries fold their canonical name into
465
+ // `keepNames`, so this covers them too).
466
+ // - `tools: ext:foo` but foo isn't in the loaded set (because `extensions:`
467
+ // didn't include it). Since v0.9, `ext:` no longer pulls extensions in;
468
+ // loading is `extensions:`-authoritative.
469
+ // An exclude_extensions: alongside extensions: false is contradictory — nothing
470
+ // loads, so there is nothing to exclude.
471
+ if (hasExcludes && noExtensions) {
472
+ options.onToolActivity?.({
473
+ type: "end",
474
+ toolName: `extension-error:exclude_extensions has no effect for agent "${type}" — extensions: false loads nothing`,
475
+ });
476
+ }
477
+ // Exclude typo check: compares against the PRE-filter discovered set (an excluded
478
+ // name absent from the surviving set is the exclude working as intended). Also
479
+ // flags path-like and "*" entries — excludes are plain names only.
480
+ if (hasExcludes && discoveredNames) {
481
+ for (const name of excludeNames) {
482
+ if (!discoveredNames.has(name)) {
483
+ options.onToolActivity?.({
484
+ type: "end",
485
+ toolName: `extension-error:exclude_extensions: "${name}" for agent "${type}" did not match any discovered extension`,
486
+ });
487
+ }
488
+ }
489
+ }
490
+ if (keepNames.size > 0 || extNames.size > 0) {
491
+ const survivingNames = new Set(loader.getExtensions().extensions.flatMap((e) => Array.from(extensionMatchNames(e.path))));
492
+ for (const name of keepNames) {
493
+ if (!survivingNames.has(name)) {
494
+ options.onToolActivity?.({
495
+ type: "end",
496
+ toolName: excludeNames.has(name)
497
+ ? `extension-error:extension "${name}" is in both extensions: and exclude_extensions: for agent "${type}" — exclude wins`
498
+ : `extension-error:extension "${name}" requested by agent "${type}" was not loaded`,
499
+ });
500
+ }
501
+ }
502
+ for (const name of extNames) {
503
+ if (!survivingNames.has(name)) {
504
+ options.onToolActivity?.({
505
+ type: "end",
506
+ toolName: `extension-error:ext:${name} referenced by agent "${type}" but extension "${name}" is not loaded (check extensions:/exclude_extensions:)`,
507
+ });
508
+ }
509
+ }
510
+ }
511
+ // Resolve model: explicit option > config.model > parent model
512
+ const model = options.model ?? resolveDefaultModel(ctx.model, ctx.modelRegistry, agentConfig?.model);
513
+ // Resolve thinking level: explicit option > agent config > undefined (inherit)
514
+ const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
515
+ const disallowedSet = agentConfig?.disallowedTools
516
+ ? new Set(agentConfig.disallowedTools)
517
+ : undefined;
518
+ // Enumerate extension-registered tool names from the loaded resource loader.
519
+ // Extensions populate `extension.tools` during `loader.reload()` and the set
520
+ // is stable afterwards — `bindExtensions` does not register new tools.
521
+ //
522
+ // Opt-in flip: when any `ext:` selector is present, extension tools become an
523
+ // explicit allowlist — a loaded extension not named by a selector contributes
524
+ // no tools (its handlers still ran), and `ext:foo/bar` narrows `foo` to `bar`.
525
+ const extensionToolNames = [];
526
+ if (!noExtensions) {
527
+ const optInActive = extNames.size > 0;
528
+ for (const extension of loader.getExtensions().extensions) {
529
+ const selectorName = extensionMatchingSelector(extension.path, extNames);
530
+ const autoExpose = extensionMatchesName(extension.path, AUTO_EXPOSE_EXTENSION_NAMES);
531
+ if (optInActive && !selectorName && !autoExpose)
532
+ continue;
533
+ const narrowed = selectorName ? narrowing.get(selectorName) : undefined;
534
+ for (const toolName of extension.tools.keys()) {
535
+ if (!autoExpose && narrowed && !narrowed.has(toolName))
536
+ continue;
537
+ extensionToolNames.push(toolName);
538
+ }
539
+ }
540
+ }
541
+ // Build the master tool allowlist applied at session construction.
542
+ // pi-mono's `allowedToolNames` gates BOTH registration and the initial active
543
+ // set, so listing the exact final set here means the session is correctly
544
+ // scoped from the first instant — no post-construction narrowing required.
545
+ const builtinToolNameSet = new Set(toolNames);
546
+ const allowedTools = [...toolNames, ...extensionToolNames].filter((t) => {
547
+ if (RECURSIVE_TOOL_NAMES.includes(t) && depth >= MAX_RECURSIVE_DEPTH)
548
+ return false;
549
+ if (disallowedSet?.has(t))
550
+ return false;
551
+ if (builtinToolNameSet.has(t))
552
+ return true;
553
+ // Reached only for extension tools. The extension set was already filtered
554
+ // at the loader (extensionsOverride / noExtensions) and at enumeration
555
+ // (`ext:` opt-in flip), so any extension tool in `extensionToolNames` is allowed.
556
+ return !noExtensions;
557
+ });
558
+ const sessionOpts = {
559
+ cwd: effectiveCwd,
560
+ agentDir,
561
+ sessionManager: SessionManager.inMemory(effectiveCwd),
562
+ settingsManager: SettingsManager.create(configCwd, agentDir),
563
+ modelRegistry: ctx.modelRegistry,
564
+ model,
565
+ tools: allowedTools,
566
+ resourceLoader: loader,
567
+ };
568
+ if (thinkingLevel) {
569
+ sessionOpts.thinkingLevel = thinkingLevel;
570
+ }
571
+ const { session } = await createAgentSession(sessionOpts);
572
+ const baseSessionName = agentConfig?.name ?? type;
573
+ session.setSessionName(options.agentId ? `${baseSessionName}#${options.agentId.slice(0, 8)}` : baseSessionName);
574
+ // Bind extensions so that session_start fires and extensions can initialize
575
+ // (e.g. loading credentials, setting up state). Tool gating already happened
576
+ // at session construction via the `tools:` allowlist above — no separate
577
+ // post-bind filter is needed. All ExtensionBindings fields are optional.
578
+ await session.bindExtensions({
579
+ onError: (err) => {
580
+ options.onToolActivity?.({
581
+ type: "end",
582
+ toolName: `extension-error:${err.extensionPath}`,
583
+ });
584
+ },
585
+ });
586
+ options.onSessionCreated?.(session);
587
+ // Track turns for graceful max_turns enforcement
588
+ let turnCount = 0;
589
+ const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
590
+ let softLimitReached = false;
591
+ let aborted = false;
592
+ let currentMessageText = "";
593
+ const unsubTurns = session.subscribe((event) => {
594
+ if (event.type === "turn_end") {
595
+ turnCount++;
596
+ options.onTurnEnd?.(turnCount);
597
+ if (maxTurns != null) {
598
+ if (!softLimitReached && turnCount >= maxTurns) {
599
+ softLimitReached = true;
600
+ session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
601
+ }
602
+ else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
603
+ aborted = true;
604
+ session.abort();
605
+ }
606
+ }
607
+ }
608
+ if (event.type === "message_start") {
609
+ currentMessageText = "";
610
+ }
611
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
612
+ currentMessageText += event.assistantMessageEvent.delta;
613
+ options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
614
+ }
615
+ if (event.type === "tool_execution_start") {
616
+ options.onToolActivity?.({ type: "start", toolName: event.toolName });
617
+ }
618
+ if (event.type === "tool_execution_end") {
619
+ options.onToolActivity?.({ type: "end", toolName: event.toolName });
620
+ }
621
+ if (event.type === "message_end" && event.message.role === "assistant") {
622
+ const u = event.message.usage;
623
+ if (u)
624
+ options.onAssistantUsage?.({
625
+ input: u.input ?? 0,
626
+ output: u.output ?? 0,
627
+ cacheWrite: u.cacheWrite ?? 0,
628
+ });
629
+ }
630
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
631
+ options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
632
+ }
633
+ });
634
+ const collector = collectResponseText(session);
635
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
636
+ // Build the effective prompt: optionally prepend parent context
637
+ let effectivePrompt = prompt;
638
+ if (options.inheritContext) {
639
+ const parentContext = buildParentContext(ctx);
640
+ if (parentContext) {
641
+ effectivePrompt = parentContext + prompt;
642
+ }
643
+ }
644
+ try {
645
+ await session.prompt(effectivePrompt);
646
+ }
647
+ finally {
648
+ unsubTurns();
649
+ collector.unsubscribe();
650
+ cleanupAbort();
651
+ }
652
+ const responseText = collector.getText().trim() || getLastAssistantText(session);
653
+ return { responseText, session, aborted, steered: softLimitReached };
654
+ }
655
+ /**
656
+ * Send a new prompt to an existing session (resume).
657
+ */
658
+ export async function resumeAgent(session, prompt, options = {}) {
659
+ const collector = collectResponseText(session);
660
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
661
+ const unsubEvents = (options.onToolActivity || options.onAssistantUsage || options.onCompaction)
662
+ ? session.subscribe((event) => {
663
+ if (event.type === "tool_execution_start")
664
+ options.onToolActivity?.({ type: "start", toolName: event.toolName });
665
+ if (event.type === "tool_execution_end")
666
+ options.onToolActivity?.({ type: "end", toolName: event.toolName });
667
+ if (event.type === "message_end" && event.message.role === "assistant") {
668
+ const u = event.message.usage;
669
+ if (u)
670
+ options.onAssistantUsage?.({
671
+ input: u.input ?? 0,
672
+ output: u.output ?? 0,
673
+ cacheWrite: u.cacheWrite ?? 0,
674
+ });
675
+ }
676
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
677
+ options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
678
+ }
679
+ })
680
+ : () => { };
681
+ try {
682
+ await session.prompt(prompt);
683
+ }
684
+ finally {
685
+ collector.unsubscribe();
686
+ unsubEvents();
687
+ cleanupAbort();
688
+ }
689
+ return collector.getText().trim() || getLastAssistantText(session);
690
+ }
691
+ /**
692
+ * Send a steering message to a running subagent.
693
+ * The message will interrupt the agent after its current tool execution.
694
+ */
695
+ export async function steerAgent(session, message) {
696
+ await session.steer(message);
697
+ }
698
+ /**
699
+ * Get the subagent's conversation messages as formatted text.
700
+ */
701
+ export function getAgentConversation(session) {
702
+ const parts = [];
703
+ for (const msg of session.messages) {
704
+ if (msg.role === "user") {
705
+ const text = typeof msg.content === "string"
706
+ ? msg.content
707
+ : extractText(msg.content);
708
+ if (text.trim())
709
+ parts.push(`[User]: ${text.trim()}`);
710
+ }
711
+ else if (msg.role === "assistant") {
712
+ const textParts = [];
713
+ const toolCalls = [];
714
+ for (const c of msg.content) {
715
+ if (c.type === "text" && c.text)
716
+ textParts.push(c.text);
717
+ else if (c.type === "toolCall")
718
+ toolCalls.push(` Tool: ${c.name ?? c.toolName ?? "unknown"}`);
719
+ }
720
+ if (textParts.length > 0)
721
+ parts.push(`[Assistant]: ${textParts.join("\n")}`);
722
+ if (toolCalls.length > 0)
723
+ parts.push(`[Tool Calls]:\n${toolCalls.join("\n")}`);
724
+ }
725
+ else if (msg.role === "toolResult") {
726
+ const text = extractText(msg.content);
727
+ const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text;
728
+ parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`);
729
+ }
730
+ }
731
+ return parts.join("\n\n");
732
+ }