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