@gotgenes/pi-subagents 1.0.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 (86) hide show
  1. package/.markdownlint-cli2.yaml +19 -0
  2. package/.prettierignore +5 -0
  3. package/.release-please-manifest.json +3 -0
  4. package/AGENTS.md +85 -0
  5. package/CHANGELOG.md +495 -0
  6. package/LICENSE +21 -0
  7. package/README.md +528 -0
  8. package/dist/agent-manager.d.ts +108 -0
  9. package/dist/agent-manager.js +390 -0
  10. package/dist/agent-runner.d.ts +93 -0
  11. package/dist/agent-runner.js +428 -0
  12. package/dist/agent-types.d.ts +48 -0
  13. package/dist/agent-types.js +136 -0
  14. package/dist/context.d.ts +12 -0
  15. package/dist/context.js +56 -0
  16. package/dist/cross-extension-rpc.d.ts +46 -0
  17. package/dist/cross-extension-rpc.js +54 -0
  18. package/dist/custom-agents.d.ts +14 -0
  19. package/dist/custom-agents.js +127 -0
  20. package/dist/default-agents.d.ts +7 -0
  21. package/dist/default-agents.js +119 -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 +13 -0
  27. package/dist/index.js +1731 -0
  28. package/dist/invocation-config.d.ts +22 -0
  29. package/dist/invocation-config.js +15 -0
  30. package/dist/memory.d.ts +49 -0
  31. package/dist/memory.js +151 -0
  32. package/dist/model-resolver.d.ts +19 -0
  33. package/dist/model-resolver.js +62 -0
  34. package/dist/output-file.d.ts +24 -0
  35. package/dist/output-file.js +86 -0
  36. package/dist/prompts.d.ts +29 -0
  37. package/dist/prompts.js +72 -0
  38. package/dist/schedule-store.d.ts +36 -0
  39. package/dist/schedule-store.js +144 -0
  40. package/dist/schedule.d.ts +109 -0
  41. package/dist/schedule.js +338 -0
  42. package/dist/settings.d.ts +66 -0
  43. package/dist/settings.js +130 -0
  44. package/dist/skill-loader.d.ts +24 -0
  45. package/dist/skill-loader.js +93 -0
  46. package/dist/types.d.ts +164 -0
  47. package/dist/types.js +5 -0
  48. package/dist/ui/agent-widget.d.ts +134 -0
  49. package/dist/ui/agent-widget.js +451 -0
  50. package/dist/ui/conversation-viewer.d.ts +35 -0
  51. package/dist/ui/conversation-viewer.js +252 -0
  52. package/dist/ui/schedule-menu.d.ts +16 -0
  53. package/dist/ui/schedule-menu.js +95 -0
  54. package/dist/usage.d.ts +50 -0
  55. package/dist/usage.js +49 -0
  56. package/dist/worktree.d.ts +36 -0
  57. package/dist/worktree.js +139 -0
  58. package/docs/decisions/0001-deferred-patches.md +75 -0
  59. package/package.json +68 -0
  60. package/prek.toml +24 -0
  61. package/release-please-config.json +22 -0
  62. package/src/agent-manager.ts +482 -0
  63. package/src/agent-runner.ts +625 -0
  64. package/src/agent-types.ts +164 -0
  65. package/src/context.ts +58 -0
  66. package/src/cross-extension-rpc.ts +95 -0
  67. package/src/custom-agents.ts +136 -0
  68. package/src/default-agents.ts +123 -0
  69. package/src/env.ts +33 -0
  70. package/src/group-join.ts +141 -0
  71. package/src/index.ts +1894 -0
  72. package/src/invocation-config.ts +40 -0
  73. package/src/memory.ts +165 -0
  74. package/src/model-resolver.ts +81 -0
  75. package/src/output-file.ts +96 -0
  76. package/src/prompts.ts +105 -0
  77. package/src/schedule-store.ts +143 -0
  78. package/src/schedule.ts +365 -0
  79. package/src/settings.ts +186 -0
  80. package/src/skill-loader.ts +102 -0
  81. package/src/types.ts +176 -0
  82. package/src/ui/agent-widget.ts +533 -0
  83. package/src/ui/conversation-viewer.ts +261 -0
  84. package/src/ui/schedule-menu.ts +104 -0
  85. package/src/usage.ts +60 -0
  86. package/src/worktree.ts +162 -0
@@ -0,0 +1,625 @@
1
+ /**
2
+ * agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
3
+ */
4
+
5
+ import type { Model } from "@earendil-works/pi-ai";
6
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
+ import {
8
+ type AgentSession,
9
+ type AgentSessionEvent,
10
+ createAgentSession,
11
+ DefaultResourceLoader,
12
+ type ExtensionAPI,
13
+ getAgentDir,
14
+ SessionManager,
15
+ SettingsManager,
16
+ } from "@earendil-works/pi-coding-agent";
17
+ import {
18
+ getAgentConfig,
19
+ getConfig,
20
+ getMemoryToolNames,
21
+ getReadOnlyMemoryToolNames,
22
+ getToolNamesForType,
23
+ } from "./agent-types.js";
24
+ import { buildParentContext, extractText } from "./context.js";
25
+ import { DEFAULT_AGENTS } from "./default-agents.js";
26
+ import { detectEnv } from "./env.js";
27
+ import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
28
+ import { buildAgentPrompt, type PromptExtras } from "./prompts.js";
29
+ import { preloadSkills } from "./skill-loader.js";
30
+ import type { SubagentType, ThinkingLevel } from "./types.js";
31
+
32
+ /** Names of tools registered by this extension that subagents must NOT inherit. */
33
+ const EXCLUDED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"];
34
+
35
+ /**
36
+ * Filter the session's active tool names according to extension/denylist rules.
37
+ *
38
+ * Run twice — once before `bindExtensions` (filters built-in tools) and once after
39
+ * (filters extension-registered tools, which only join the active set during
40
+ * `bindExtensions`). Extracting this keeps the two callsites consistent and makes
41
+ * the post-bind re-filter trivial.
42
+ *
43
+ * @param activeTools Names currently active on the session.
44
+ * @param toolNames The built-in tool name allowlist for this agent type.
45
+ * @param extensions Agent config `extensions` field: false | true | string[] (allowlist).
46
+ * @param disallowedSet Optional denylist from agent config.
47
+ */
48
+ function filterActiveTools(
49
+ activeTools: string[],
50
+ toolNames: string[],
51
+ extensions: boolean | string[],
52
+ disallowedSet: Set<string> | undefined,
53
+ ): string[] {
54
+ if (extensions === false) {
55
+ // Extensions disabled: only apply the denylist to built-in tools.
56
+ if (!disallowedSet) return activeTools;
57
+ return activeTools.filter((t) => !disallowedSet.has(t));
58
+ }
59
+ const builtinToolNameSet = new Set(toolNames);
60
+ return activeTools.filter((t) => {
61
+ if (EXCLUDED_TOOL_NAMES.includes(t)) return false;
62
+ if (disallowedSet?.has(t)) return false;
63
+ if (builtinToolNameSet.has(t)) return true;
64
+ if (Array.isArray(extensions)) {
65
+ return extensions.some((ext) => t.startsWith(ext) || t.includes(ext));
66
+ }
67
+ return true;
68
+ });
69
+ }
70
+
71
+ /** Default max turns. undefined = unlimited (no turn limit). */
72
+ let defaultMaxTurns: number | undefined;
73
+
74
+ /** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
75
+ export function normalizeMaxTurns(n: number | undefined): number | undefined {
76
+ if (n == null || n === 0) return undefined;
77
+ return Math.max(1, n);
78
+ }
79
+
80
+ /** Get the default max turns value. undefined = unlimited. */
81
+ export function getDefaultMaxTurns(): number | undefined {
82
+ return defaultMaxTurns;
83
+ }
84
+ /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
85
+ export function setDefaultMaxTurns(n: number | undefined): void {
86
+ defaultMaxTurns = normalizeMaxTurns(n);
87
+ }
88
+
89
+ /** Additional turns allowed after the soft limit steer message. */
90
+ let graceTurns = 5;
91
+
92
+ /** Get the grace turns value. */
93
+ export function getGraceTurns(): number {
94
+ return graceTurns;
95
+ }
96
+ /** Set the grace turns value (minimum 1). */
97
+ export function setGraceTurns(n: number): void {
98
+ graceTurns = Math.max(1, n);
99
+ }
100
+
101
+ /**
102
+ * Try to find the right model for an agent type.
103
+ * Priority: explicit option > config.model > parent model.
104
+ */
105
+ function resolveDefaultModel(
106
+ parentModel: Model<any> | undefined,
107
+ registry: {
108
+ find(provider: string, modelId: string): Model<any> | undefined;
109
+ getAvailable?(): Model<any>[];
110
+ },
111
+ configModel?: string,
112
+ ): Model<any> | undefined {
113
+ if (configModel) {
114
+ const slashIdx = configModel.indexOf("/");
115
+ if (slashIdx !== -1) {
116
+ const provider = configModel.slice(0, slashIdx);
117
+ const modelId = configModel.slice(slashIdx + 1);
118
+
119
+ // Build a set of available model keys for fast lookup
120
+ const available = registry.getAvailable?.();
121
+ const availableKeys = available
122
+ ? new Set(available.map((m: any) => `${m.provider}/${m.id}`))
123
+ : undefined;
124
+ const isAvailable = (p: string, id: string) =>
125
+ !availableKeys || availableKeys.has(`${p}/${id}`);
126
+
127
+ const found = registry.find(provider, modelId);
128
+ if (found && isAvailable(provider, modelId)) return found;
129
+ }
130
+ }
131
+
132
+ return parentModel;
133
+ }
134
+
135
+ /** Info about a tool event in the subagent. */
136
+ export interface ToolActivity {
137
+ type: "start" | "end";
138
+ toolName: string;
139
+ }
140
+
141
+ export interface RunOptions {
142
+ /** ExtensionAPI instance — used for pi.exec() instead of execSync. */
143
+ pi: ExtensionAPI;
144
+ model?: Model<any>;
145
+ maxTurns?: number;
146
+ signal?: AbortSignal;
147
+ isolated?: boolean;
148
+ inheritContext?: boolean;
149
+ thinkingLevel?: ThinkingLevel;
150
+ /** Override working directory (e.g. for worktree isolation). */
151
+ cwd?: string;
152
+ /** Called on tool start/end with activity info. */
153
+ onToolActivity?: (activity: ToolActivity) => void;
154
+ /** Called on streaming text deltas from the assistant response. */
155
+ onTextDelta?: (delta: string, fullText: string) => void;
156
+ onSessionCreated?: (session: AgentSession) => void;
157
+ /** Called at the end of each agentic turn with the cumulative count. */
158
+ onTurnEnd?: (turnCount: number) => void;
159
+ /**
160
+ * Called once per assistant message_end with that message's usage delta.
161
+ * Lets callers maintain a lifetime accumulator that survives compaction
162
+ * (which replaces session.state.messages and resets stats-derived sums).
163
+ */
164
+ onAssistantUsage?: (usage: {
165
+ input: number;
166
+ output: number;
167
+ cacheWrite: number;
168
+ }) => void;
169
+ /**
170
+ * Called when the session successfully compacts. `tokensBefore` is upstream's
171
+ * pre-compaction context size estimate. Aborted compactions don't fire.
172
+ */
173
+ onCompaction?: (info: {
174
+ reason: "manual" | "threshold" | "overflow";
175
+ tokensBefore: number;
176
+ }) => void;
177
+ }
178
+
179
+ export interface RunResult {
180
+ responseText: string;
181
+ session: AgentSession;
182
+ /** True if the agent was hard-aborted (max_turns + grace exceeded). */
183
+ aborted: boolean;
184
+ /** True if the agent was steered to wrap up (hit soft turn limit) but finished in time. */
185
+ steered: boolean;
186
+ }
187
+
188
+ /**
189
+ * Subscribe to a session and collect the last assistant message text.
190
+ * Returns an object with a `getText()` getter and an `unsubscribe` function.
191
+ */
192
+ function collectResponseText(session: AgentSession) {
193
+ let text = "";
194
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
195
+ if (event.type === "message_start") {
196
+ text = "";
197
+ }
198
+ if (
199
+ event.type === "message_update" &&
200
+ event.assistantMessageEvent.type === "text_delta"
201
+ ) {
202
+ text += event.assistantMessageEvent.delta;
203
+ }
204
+ });
205
+ return { getText: () => text, unsubscribe };
206
+ }
207
+
208
+ /** Get the last assistant text from the completed session history. */
209
+ function getLastAssistantText(session: AgentSession): string {
210
+ for (let i = session.messages.length - 1; i >= 0; i--) {
211
+ const msg = session.messages[i];
212
+ if (msg.role !== "assistant") continue;
213
+ const text = extractText(msg.content).trim();
214
+ if (text) return text;
215
+ }
216
+ return "";
217
+ }
218
+
219
+ /**
220
+ * Wire an AbortSignal to abort a session.
221
+ * Returns a cleanup function to remove the listener.
222
+ */
223
+ function forwardAbortSignal(
224
+ session: AgentSession,
225
+ signal?: AbortSignal,
226
+ ): () => void {
227
+ if (!signal) return () => {};
228
+ const onAbort = () => session.abort();
229
+ signal.addEventListener("abort", onAbort, { once: true });
230
+ return () => signal.removeEventListener("abort", onAbort);
231
+ }
232
+
233
+ export async function runAgent(
234
+ ctx: ExtensionContext,
235
+ type: SubagentType,
236
+ prompt: string,
237
+ options: RunOptions,
238
+ ): Promise<RunResult> {
239
+ const config = getConfig(type);
240
+ const agentConfig = getAgentConfig(type);
241
+
242
+ // Resolve working directory: worktree override > parent cwd
243
+ const effectiveCwd = options.cwd ?? ctx.cwd;
244
+
245
+ const env = await detectEnv(options.pi, effectiveCwd);
246
+
247
+ // Get parent system prompt for append-mode agents
248
+ const parentSystemPrompt = ctx.getSystemPrompt();
249
+
250
+ // Build prompt extras (memory, skill preloading)
251
+ const extras: PromptExtras = {};
252
+
253
+ // Resolve extensions/skills: isolated overrides to false
254
+ const extensions = options.isolated ? false : config.extensions;
255
+ const skills = options.isolated ? false : config.skills;
256
+
257
+ // Skill preloading: when skills is string[], preload their content into prompt
258
+ if (Array.isArray(skills)) {
259
+ const loaded = preloadSkills(skills, effectiveCwd);
260
+ if (loaded.length > 0) {
261
+ extras.skillBlocks = loaded;
262
+ }
263
+ }
264
+
265
+ let toolNames = getToolNamesForType(type);
266
+
267
+ // Persistent memory: detect write capability and branch accordingly.
268
+ // Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
269
+ if (agentConfig?.memory) {
270
+ const existingNames = new Set(toolNames);
271
+ const denied = agentConfig.disallowedTools
272
+ ? new Set(agentConfig.disallowedTools)
273
+ : undefined;
274
+ const effectivelyHas = (name: string) =>
275
+ existingNames.has(name) && !denied?.has(name);
276
+ const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
277
+
278
+ if (hasWriteTools) {
279
+ // Read-write memory: add any missing memory tool names (read/write/edit)
280
+ const extraNames = getMemoryToolNames(existingNames);
281
+ if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames];
282
+ extras.memoryBlock = buildMemoryBlock(
283
+ agentConfig.name,
284
+ agentConfig.memory,
285
+ effectiveCwd,
286
+ );
287
+ } else {
288
+ // Read-only memory: only add read tool name, use read-only prompt
289
+ const extraNames = getReadOnlyMemoryToolNames(existingNames);
290
+ if (extraNames.length > 0) toolNames = [...toolNames, ...extraNames];
291
+ extras.memoryBlock = buildReadOnlyMemoryBlock(
292
+ agentConfig.name,
293
+ agentConfig.memory,
294
+ effectiveCwd,
295
+ );
296
+ }
297
+ }
298
+
299
+ // Build system prompt from agent config
300
+ let systemPrompt: string;
301
+ if (agentConfig) {
302
+ systemPrompt = buildAgentPrompt(
303
+ agentConfig,
304
+ effectiveCwd,
305
+ env,
306
+ parentSystemPrompt,
307
+ extras,
308
+ );
309
+ } else {
310
+ // Unknown type fallback: spread the canonical general-purpose config (defensive —
311
+ // unreachable in practice since index.ts resolves unknown types before calling runAgent).
312
+ const fallback = DEFAULT_AGENTS.get("general-purpose");
313
+ if (!fallback)
314
+ throw new Error(
315
+ `No fallback config available for unknown type "${type}"`,
316
+ );
317
+ systemPrompt = buildAgentPrompt(
318
+ { ...fallback, name: type },
319
+ effectiveCwd,
320
+ env,
321
+ parentSystemPrompt,
322
+ extras,
323
+ );
324
+ }
325
+
326
+ // When skills is string[], we've already preloaded them into the prompt.
327
+ // Still pass noSkills: true since we don't need the skill loader to load them again.
328
+ const noSkills = skills === false || Array.isArray(skills);
329
+
330
+ const agentDir = getAgentDir();
331
+
332
+ // Load extensions/skills: true or string[] → load; false → don't.
333
+ // Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md — upstream's
334
+ // buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
335
+ // would defeat prompt_mode: replace and isolated: true. Parent context, if
336
+ // wanted, reaches the subagent via prompt_mode: append (parentSystemPrompt
337
+ // is embedded in systemPromptOverride) or inherit_context (conversation).
338
+ const loader = new DefaultResourceLoader({
339
+ cwd: effectiveCwd,
340
+ agentDir,
341
+ noExtensions: extensions === false,
342
+ noSkills,
343
+ noPromptTemplates: true,
344
+ noThemes: true,
345
+ noContextFiles: true,
346
+ systemPromptOverride: () => systemPrompt,
347
+ appendSystemPromptOverride: () => [],
348
+ });
349
+ await loader.reload();
350
+
351
+ // Resolve model: explicit option > config.model > parent model
352
+ const model =
353
+ options.model ??
354
+ resolveDefaultModel(ctx.model, ctx.modelRegistry, agentConfig?.model);
355
+
356
+ // Resolve thinking level: explicit option > agent config > undefined (inherit)
357
+ const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
358
+
359
+ const sessionOpts: Parameters<typeof createAgentSession>[0] = {
360
+ cwd: effectiveCwd,
361
+ agentDir,
362
+ sessionManager: SessionManager.inMemory(effectiveCwd),
363
+ settingsManager: SettingsManager.create(effectiveCwd, agentDir),
364
+ modelRegistry: ctx.modelRegistry,
365
+ model,
366
+ tools: toolNames,
367
+ resourceLoader: loader,
368
+ };
369
+ if (thinkingLevel) {
370
+ sessionOpts.thinkingLevel = thinkingLevel;
371
+ }
372
+
373
+ const { session } = await createAgentSession(sessionOpts);
374
+
375
+ // Build disallowed tools set from agent config
376
+ const disallowedSet = agentConfig?.disallowedTools
377
+ ? new Set(agentConfig.disallowedTools)
378
+ : undefined;
379
+
380
+ // Filter active tools: remove our own tools to prevent nesting,
381
+ // apply extension allowlist if specified, and apply disallowedTools denylist.
382
+ // First pass — over built-in tools, before bindExtensions registers extension tools.
383
+ if (extensions !== false || disallowedSet) {
384
+ const filtered = filterActiveTools(
385
+ session.getActiveToolNames(),
386
+ toolNames,
387
+ extensions,
388
+ disallowedSet,
389
+ );
390
+ session.setActiveToolsByName(filtered);
391
+ }
392
+
393
+ // Bind extensions so that session_start fires and extensions can initialize
394
+ // (e.g. loading credentials, setting up state). Placed after tool filtering
395
+ // so extension-provided skills/prompts from extendResourcesFromExtensions()
396
+ // respect the active tool set. All ExtensionBindings fields are optional.
397
+ await session.bindExtensions({
398
+ onError: (err) => {
399
+ options.onToolActivity?.({
400
+ type: "end",
401
+ toolName: `extension-error:${err.extensionPath}`,
402
+ });
403
+ },
404
+ });
405
+
406
+ // Patch 2 (RepOne #443): re-filter active tools after bindExtensions.
407
+ // Extension-registered tools (added during bindExtensions) are not in the
408
+ // session's active set when the first filter pass runs above. Without this
409
+ // re-filter, the `extensions: string[]` allowlist branch never matches any
410
+ // extension tools and `extensions: true` lets non-allowlisted denylist
411
+ // entries slip in. Run the same filter against the post-bind active set.
412
+ if (extensions !== false || disallowedSet) {
413
+ const refiltered = filterActiveTools(
414
+ session.getActiveToolNames(),
415
+ toolNames,
416
+ extensions,
417
+ disallowedSet,
418
+ );
419
+ session.setActiveToolsByName(refiltered);
420
+ }
421
+
422
+ options.onSessionCreated?.(session);
423
+
424
+ // Track turns for graceful max_turns enforcement
425
+ let turnCount = 0;
426
+ const maxTurns = normalizeMaxTurns(
427
+ options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns,
428
+ );
429
+ let softLimitReached = false;
430
+ let aborted = false;
431
+
432
+ let currentMessageText = "";
433
+ const unsubTurns = session.subscribe((event: AgentSessionEvent) => {
434
+ if (event.type === "turn_end") {
435
+ turnCount++;
436
+ options.onTurnEnd?.(turnCount);
437
+ if (maxTurns != null) {
438
+ if (!softLimitReached && turnCount >= maxTurns) {
439
+ softLimitReached = true;
440
+ session.steer(
441
+ "You have reached your turn limit. Wrap up immediately — provide your final answer now.",
442
+ );
443
+ } else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
444
+ aborted = true;
445
+ session.abort();
446
+ }
447
+ }
448
+ }
449
+ if (event.type === "message_start") {
450
+ currentMessageText = "";
451
+ }
452
+ if (
453
+ event.type === "message_update" &&
454
+ event.assistantMessageEvent.type === "text_delta"
455
+ ) {
456
+ currentMessageText += event.assistantMessageEvent.delta;
457
+ options.onTextDelta?.(
458
+ event.assistantMessageEvent.delta,
459
+ currentMessageText,
460
+ );
461
+ }
462
+ if (event.type === "tool_execution_start") {
463
+ options.onToolActivity?.({ type: "start", toolName: event.toolName });
464
+ }
465
+ if (event.type === "tool_execution_end") {
466
+ options.onToolActivity?.({ type: "end", toolName: event.toolName });
467
+ }
468
+ if (event.type === "message_end" && event.message.role === "assistant") {
469
+ const u = (event.message as any).usage;
470
+ if (u)
471
+ options.onAssistantUsage?.({
472
+ input: u.input ?? 0,
473
+ output: u.output ?? 0,
474
+ cacheWrite: u.cacheWrite ?? 0,
475
+ });
476
+ }
477
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
478
+ options.onCompaction?.({
479
+ reason: event.reason,
480
+ tokensBefore: event.result.tokensBefore,
481
+ });
482
+ }
483
+ });
484
+
485
+ const collector = collectResponseText(session);
486
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
487
+
488
+ // Build the effective prompt: optionally prepend parent context
489
+ let effectivePrompt = prompt;
490
+ if (options.inheritContext) {
491
+ const parentContext = buildParentContext(ctx);
492
+ if (parentContext) {
493
+ effectivePrompt = parentContext + prompt;
494
+ }
495
+ }
496
+
497
+ try {
498
+ await session.prompt(effectivePrompt);
499
+ } finally {
500
+ unsubTurns();
501
+ collector.unsubscribe();
502
+ cleanupAbort();
503
+ }
504
+
505
+ const responseText =
506
+ collector.getText().trim() || getLastAssistantText(session);
507
+ return { responseText, session, aborted, steered: softLimitReached };
508
+ }
509
+
510
+ /**
511
+ * Send a new prompt to an existing session (resume).
512
+ */
513
+ export async function resumeAgent(
514
+ session: AgentSession,
515
+ prompt: string,
516
+ options: {
517
+ onToolActivity?: (activity: ToolActivity) => void;
518
+ onAssistantUsage?: (usage: {
519
+ input: number;
520
+ output: number;
521
+ cacheWrite: number;
522
+ }) => void;
523
+ onCompaction?: (info: {
524
+ reason: "manual" | "threshold" | "overflow";
525
+ tokensBefore: number;
526
+ }) => void;
527
+ signal?: AbortSignal;
528
+ } = {},
529
+ ): Promise<string> {
530
+ const collector = collectResponseText(session);
531
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
532
+
533
+ const unsubEvents =
534
+ options.onToolActivity || options.onAssistantUsage || options.onCompaction
535
+ ? session.subscribe((event: AgentSessionEvent) => {
536
+ if (event.type === "tool_execution_start")
537
+ options.onToolActivity?.({
538
+ type: "start",
539
+ toolName: event.toolName,
540
+ });
541
+ if (event.type === "tool_execution_end")
542
+ options.onToolActivity?.({ type: "end", toolName: event.toolName });
543
+ if (
544
+ event.type === "message_end" &&
545
+ event.message.role === "assistant"
546
+ ) {
547
+ const u = (event.message as any).usage;
548
+ if (u)
549
+ options.onAssistantUsage?.({
550
+ input: u.input ?? 0,
551
+ output: u.output ?? 0,
552
+ cacheWrite: u.cacheWrite ?? 0,
553
+ });
554
+ }
555
+ if (
556
+ event.type === "compaction_end" &&
557
+ !event.aborted &&
558
+ event.result
559
+ ) {
560
+ options.onCompaction?.({
561
+ reason: event.reason,
562
+ tokensBefore: event.result.tokensBefore,
563
+ });
564
+ }
565
+ })
566
+ : () => {};
567
+
568
+ try {
569
+ await session.prompt(prompt);
570
+ } finally {
571
+ collector.unsubscribe();
572
+ unsubEvents();
573
+ cleanupAbort();
574
+ }
575
+
576
+ return collector.getText().trim() || getLastAssistantText(session);
577
+ }
578
+
579
+ /**
580
+ * Send a steering message to a running subagent.
581
+ * The message will interrupt the agent after its current tool execution.
582
+ */
583
+ export async function steerAgent(
584
+ session: AgentSession,
585
+ message: string,
586
+ ): Promise<void> {
587
+ await session.steer(message);
588
+ }
589
+
590
+ /**
591
+ * Get the subagent's conversation messages as formatted text.
592
+ */
593
+ export function getAgentConversation(session: AgentSession): string {
594
+ const parts: string[] = [];
595
+
596
+ for (const msg of session.messages) {
597
+ if (msg.role === "user") {
598
+ const text =
599
+ typeof msg.content === "string"
600
+ ? msg.content
601
+ : extractText(msg.content);
602
+ if (text.trim()) parts.push(`[User]: ${text.trim()}`);
603
+ } else if (msg.role === "assistant") {
604
+ const textParts: string[] = [];
605
+ const toolCalls: string[] = [];
606
+ for (const c of msg.content) {
607
+ if (c.type === "text" && c.text) textParts.push(c.text);
608
+ else if (c.type === "toolCall")
609
+ toolCalls.push(
610
+ ` Tool: ${(c as any).name ?? (c as any).toolName ?? "unknown"}`,
611
+ );
612
+ }
613
+ if (textParts.length > 0)
614
+ parts.push(`[Assistant]: ${textParts.join("\n")}`);
615
+ if (toolCalls.length > 0)
616
+ parts.push(`[Tool Calls]:\n${toolCalls.join("\n")}`);
617
+ } else if (msg.role === "toolResult") {
618
+ const text = extractText(msg.content);
619
+ const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text;
620
+ parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`);
621
+ }
622
+ }
623
+
624
+ return parts.join("\n\n");
625
+ }