@pi-unipi/subagents 2.6.1 → 2.6.2

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 (107) hide show
  1. package/README.md +89 -78
  2. package/agents/delegate.md +14 -0
  3. package/agents/oracle.md +78 -0
  4. package/agents/researcher.md +52 -0
  5. package/agents/reviewer.md +79 -0
  6. package/agents/scout.md +50 -0
  7. package/agents/worker.md +59 -0
  8. package/package.json +19 -17
  9. package/prompts/council.md +48 -0
  10. package/prompts/gather-context-and-clarify.md +13 -0
  11. package/prompts/parallel-cleanup.md +59 -0
  12. package/prompts/parallel-research.md +50 -0
  13. package/prompts/parallel-review.md +54 -0
  14. package/prompts/review-loop.md +43 -0
  15. package/skills/council-mode/SKILL.md +230 -0
  16. package/skills/subagents/SKILL.md +49 -0
  17. package/skills/subagents/references/constraints-and-recipes.md +259 -0
  18. package/skills/subagents/references/execution-controls.md +454 -0
  19. package/skills/subagents/references/management-authoring-rpc.md +161 -0
  20. package/skills/subagents/references/multi-lane-orchestration.md +39 -0
  21. package/skills/subagents/references/prompting-and-roles.md +267 -0
  22. package/src/acceptance.ts +331 -0
  23. package/src/agent-manager.ts +405 -0
  24. package/src/agent-memory.ts +300 -0
  25. package/src/agent-overrides.ts +183 -0
  26. package/src/agent-runner.ts +265 -0
  27. package/src/async-runner.ts +417 -0
  28. package/src/authority-policy.ts +47 -0
  29. package/src/budgets.ts +285 -0
  30. package/src/child-safety.ts +140 -0
  31. package/src/config.ts +226 -0
  32. package/src/conversation-viewer.ts +281 -0
  33. package/src/core-compat.ts +94 -0
  34. package/src/custom-agents.ts +323 -0
  35. package/src/file-system-retry.ts +50 -0
  36. package/src/fleet-data.ts +61 -0
  37. package/src/fleet-view.ts +316 -0
  38. package/src/foreground-detach.ts +59 -0
  39. package/src/fork-context.ts +285 -0
  40. package/src/global.d.ts +7 -0
  41. package/src/guide.ts +129 -0
  42. package/src/index.ts +1149 -0
  43. package/src/mission-state.ts +133 -0
  44. package/src/mission-store.ts +434 -0
  45. package/src/model-resolver.ts +79 -0
  46. package/src/output-limits.ts +142 -0
  47. package/src/parity-types.ts +315 -0
  48. package/src/pi-args.ts +161 -0
  49. package/src/pi-spawn.ts +147 -0
  50. package/src/result-files.ts +232 -0
  51. package/src/result-watcher.ts +221 -0
  52. package/src/retained-children.ts +176 -0
  53. package/src/run-fanout-budget.ts +356 -0
  54. package/src/scheduled-runs.ts +351 -0
  55. package/src/schemas.ts +263 -0
  56. package/src/slash-commands.ts +77 -0
  57. package/src/supervisor-channel.ts +249 -0
  58. package/src/tool-handler.ts +1144 -0
  59. package/src/types.ts +238 -0
  60. package/src/widget.ts +447 -0
  61. package/src/workflow-script.ts +737 -0
  62. package/src/workflow-worker.ts +384 -0
  63. package/src/worktree.ts +614 -0
  64. package/dist/agent-manager.d.ts +0 -81
  65. package/dist/agent-manager.d.ts.map +0 -1
  66. package/dist/agent-manager.js +0 -295
  67. package/dist/agent-manager.js.map +0 -1
  68. package/dist/agent-runner.d.ts +0 -51
  69. package/dist/agent-runner.d.ts.map +0 -1
  70. package/dist/agent-runner.js +0 -262
  71. package/dist/agent-runner.js.map +0 -1
  72. package/dist/config.d.ts +0 -24
  73. package/dist/config.d.ts.map +0 -1
  74. package/dist/config.js +0 -132
  75. package/dist/config.js.map +0 -1
  76. package/dist/conversation-viewer.d.ts +0 -40
  77. package/dist/conversation-viewer.d.ts.map +0 -1
  78. package/dist/conversation-viewer.js +0 -276
  79. package/dist/conversation-viewer.js.map +0 -1
  80. package/dist/core-compat.d.ts +0 -21
  81. package/dist/core-compat.d.ts.map +0 -1
  82. package/dist/core-compat.js +0 -86
  83. package/dist/core-compat.js.map +0 -1
  84. package/dist/custom-agents.d.ts +0 -14
  85. package/dist/custom-agents.d.ts.map +0 -1
  86. package/dist/custom-agents.js +0 -113
  87. package/dist/custom-agents.js.map +0 -1
  88. package/dist/file-lock.d.ts +0 -42
  89. package/dist/file-lock.d.ts.map +0 -1
  90. package/dist/file-lock.js +0 -91
  91. package/dist/file-lock.js.map +0 -1
  92. package/dist/index.d.ts +0 -10
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/index.js +0 -758
  95. package/dist/index.js.map +0 -1
  96. package/dist/model-resolver.d.ts +0 -19
  97. package/dist/model-resolver.d.ts.map +0 -1
  98. package/dist/model-resolver.js +0 -61
  99. package/dist/model-resolver.js.map +0 -1
  100. package/dist/types.d.ts +0 -98
  101. package/dist/types.d.ts.map +0 -1
  102. package/dist/types.js +0 -47
  103. package/dist/types.js.map +0 -1
  104. package/dist/widget.d.ts +0 -56
  105. package/dist/widget.d.ts.map +0 -1
  106. package/dist/widget.js +0 -396
  107. package/dist/widget.js.map +0 -1
@@ -0,0 +1,183 @@
1
+ /**
2
+ * @pi-unipi/subagents — Builtin agent overrides + defaults
3
+ *
4
+ * Ported from pi-subagents applyBuiltinOverrides/applySubagentDefaults
5
+ * (src/agents/agents.ts). Semantics identical; the source of settings is OUR
6
+ * subagents.json `subagents` object (user: ~/.unipi/config/subagents.json;
7
+ * project: <ws>/.unipi/config/subagents.json) instead of pi settings files.
8
+ *
9
+ * Our existing enablement rule is preserved: merged JSON types[name].enabled
10
+ * !== false AND resolved agent frontmatter enabled !== false. disableBuiltins
11
+ * (reference parity) disables ALL builtin agents (code + file) while custom
12
+ * user/project agents keep working.
13
+ */
14
+
15
+ import type { AgentConfig } from "./types.js";
16
+
17
+ export interface BuiltinAgentOverrideConfig {
18
+ description?: string;
19
+ outputMode?: "inline" | "file-only";
20
+ model?: string | false;
21
+ fallbackModels?: string[] | false;
22
+ thinking?: string | false;
23
+ systemPromptMode?: "replace" | "append";
24
+ inheritProjectContext?: boolean;
25
+ inheritSkills?: boolean;
26
+ defaultContext?: "fresh" | "fork" | false;
27
+ disabled?: boolean;
28
+ systemPrompt?: string;
29
+ skills?: string[] | false;
30
+ tools?: string[] | false | "inherit";
31
+ extensions?: string[] | false;
32
+ toolBudget?: { soft?: number; hard: number; block?: string[] | "*" } | false;
33
+ maxSubagentDepth?: number;
34
+ }
35
+
36
+ /** Settings block inside our subagents.json: { "subagents": { ... } }. */
37
+ export interface SubagentSettings {
38
+ overrides: Record<string, BuiltinAgentOverrideConfig>;
39
+ defaultModel?: string;
40
+ defaultThinking?: string | false;
41
+ defaultExtensions?: string[];
42
+ disableBuiltins?: boolean;
43
+ disableThinking?: boolean;
44
+ }
45
+
46
+ export const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {} };
47
+
48
+ /** Parse the settings block from a parsed subagents.json (missing → empty). */
49
+ export function parseSubagentSettings(raw: unknown): SubagentSettings {
50
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return EMPTY_SUBAGENT_SETTINGS;
51
+ const obj = raw as Record<string, unknown>;
52
+ const overrides: Record<string, BuiltinAgentOverrideConfig> = {};
53
+ if (obj.overrides && typeof obj.overrides === "object" && !Array.isArray(obj.overrides)) {
54
+ for (const [name, value] of Object.entries(obj.overrides as Record<string, unknown>)) {
55
+ if (value && typeof value === "object" && !Array.isArray(value)) {
56
+ overrides[name] = value as BuiltinAgentOverrideConfig;
57
+ }
58
+ }
59
+ }
60
+ const settings: SubagentSettings = { overrides };
61
+ if (typeof obj.defaultModel === "string" && obj.defaultModel.trim()) {
62
+ settings.defaultModel = obj.defaultModel.trim();
63
+ }
64
+ if (obj.defaultThinking === false || typeof obj.defaultThinking === "string") {
65
+ settings.defaultThinking = obj.defaultThinking;
66
+ }
67
+ if (Array.isArray(obj.defaultExtensions)) {
68
+ settings.defaultExtensions = obj.defaultExtensions.filter(
69
+ (entry): entry is string => typeof entry === "string" && entry.trim().length > 0,
70
+ );
71
+ }
72
+ if (obj.disableBuiltins === true) settings.disableBuiltins = true;
73
+ if (obj.disableThinking === true) settings.disableThinking = true;
74
+ return settings;
75
+ }
76
+
77
+ function applyToolsOverride(target: AgentConfig, toolsOverride: string[] | false | "inherit"): void {
78
+ if (toolsOverride === "inherit") {
79
+ delete target.builtinToolNames;
80
+ return;
81
+ }
82
+ target.builtinToolNames = toolsOverride === false ? [] : [...toolsOverride];
83
+ }
84
+
85
+ /** Apply a single override to a builtin agent (reference applyBuiltinOverride). */
86
+ export function applyBuiltinOverride(
87
+ agent: AgentConfig,
88
+ override: BuiltinAgentOverrideConfig,
89
+ ): AgentConfig {
90
+ const next: AgentConfig = { ...agent };
91
+ if (override.description !== undefined) next.description = override.description;
92
+ if (override.outputMode !== undefined) next.outputMode = override.outputMode;
93
+ if (override.model !== undefined) next.model = override.model === false ? undefined : override.model;
94
+ if (override.fallbackModels !== undefined) {
95
+ next.fallbackModels = override.fallbackModels === false ? undefined : [...override.fallbackModels];
96
+ }
97
+ if (override.thinking !== undefined) next.thinking = override.thinking;
98
+ if (override.systemPromptMode !== undefined) {
99
+ next.promptMode = override.systemPromptMode;
100
+ next.systemPromptMode = override.systemPromptMode;
101
+ }
102
+ if (override.inheritProjectContext !== undefined) next.inheritProjectContext = override.inheritProjectContext;
103
+ if (override.inheritSkills !== undefined) next.inheritSkills = override.inheritSkills;
104
+ if (override.defaultContext !== undefined) {
105
+ next.defaultContext = override.defaultContext === false ? undefined : override.defaultContext;
106
+ }
107
+ if (override.systemPrompt !== undefined && override.systemPrompt.trim()) {
108
+ next.systemPrompt = override.systemPrompt;
109
+ }
110
+ if (override.skills !== undefined) {
111
+ next.skills = override.skills === false ? false : [...override.skills];
112
+ }
113
+ if (override.tools !== undefined) applyToolsOverride(next, override.tools);
114
+ if (override.extensions !== undefined) {
115
+ next.extensions = override.extensions === false ? false : [...override.extensions];
116
+ }
117
+ if (override.toolBudget !== undefined) {
118
+ // Stored for Phase 2 budget resolution.
119
+ (next as AgentConfig & { toolBudget?: unknown }).toolBudget =
120
+ override.toolBudget === false ? undefined : override.toolBudget;
121
+ }
122
+ if (override.maxSubagentDepth !== undefined) next.maxSubagentDepth = override.maxSubagentDepth;
123
+ if (override.disabled === true) next.enabled = false;
124
+ else if (override.disabled === false) next.enabled = true;
125
+ return next;
126
+ }
127
+
128
+ /** Apply defaultModel/defaultThinking/defaultExtensions to a loaded agent list. */
129
+ export function applySubagentDefaults(
130
+ agents: AgentConfig[],
131
+ settings: SubagentSettings,
132
+ ): AgentConfig[] {
133
+ return agents.map((agent) => {
134
+ let next = agent;
135
+ if (settings.defaultModel && !agent.model) {
136
+ next = { ...next, model: settings.defaultModel };
137
+ }
138
+ if (settings.defaultThinking !== undefined && agent.thinking === undefined) {
139
+ next = { ...next, thinking: settings.defaultThinking };
140
+ }
141
+ if (settings.defaultExtensions?.length && agent.extensions === true) {
142
+ next = { ...next, extensions: [...settings.defaultExtensions] };
143
+ }
144
+ return next;
145
+ });
146
+ }
147
+
148
+ /**
149
+ * Apply builtin overrides to a builtin agent list. Project settings win over
150
+ * user settings per-field; disableBuiltins disables every builtin agent when
151
+ * active; disableThinking clears thinking from builtins without an explicit
152
+ * override (reference semantics).
153
+ */
154
+ export function applyBuiltinOverrides(
155
+ builtinAgents: AgentConfig[],
156
+ userSettings: SubagentSettings,
157
+ projectSettings: SubagentSettings,
158
+ ): AgentConfig[] {
159
+ const projectBulkDisabled = projectSettings.disableBuiltins === true;
160
+ const userBulkDisabled = !projectBulkDisabled && userSettings.disableBuiltins === true;
161
+ const disableThinking = projectSettings.disableThinking ?? userSettings.disableThinking ?? false;
162
+
163
+ return builtinAgents.map((agent) => {
164
+ const projectOverride = projectSettings.overrides[agent.name];
165
+ if (projectOverride) {
166
+ return withThinkingPolicy(applyBuiltinOverride(agent, projectOverride), projectOverride.thinking !== undefined);
167
+ }
168
+ const userOverride = userSettings.overrides[agent.name];
169
+ if (userOverride) {
170
+ return withThinkingPolicy(applyBuiltinOverride(agent, userOverride), userOverride.thinking !== undefined);
171
+ }
172
+ if (projectBulkDisabled || userBulkDisabled) {
173
+ return withThinkingPolicy({ ...agent, enabled: false }, false);
174
+ }
175
+ return withThinkingPolicy(agent, false);
176
+ });
177
+
178
+ function withThinkingPolicy(agent: AgentConfig, hasExplicitThinkingOverride: boolean): AgentConfig {
179
+ if (!disableThinking || hasExplicitThinkingOverride) return agent;
180
+ if (agent.thinking === undefined) return agent;
181
+ return { ...agent, thinking: undefined };
182
+ }
183
+ }
@@ -0,0 +1,265 @@
1
+ /**
2
+ * @pi-unipi/subagents — Agent runner
3
+ *
4
+ * Creates sessions, runs agents, collects results.
5
+ * Forwards abort signals for ESC propagation.
6
+ */
7
+
8
+ import type { Model } from "@earendil-works/pi-ai";
9
+ import type { ExtensionContext } 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_CONFIGS, type AgentConfig, type AgentType, type ThinkingLevel } from "./types.js";
21
+
22
+ /** Coerce frontmatter thinking (string | false | ThinkingLevel) to ThinkingLevel. */
23
+ export function coerceThinkingLevel(raw: AgentConfig["thinking"]): ThinkingLevel | undefined {
24
+ if (raw === false || raw === undefined || raw === null) return undefined;
25
+ if (typeof raw === "string") {
26
+ const valid: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
27
+ return valid.includes(raw as ThinkingLevel) ? (raw as ThinkingLevel) : undefined;
28
+ }
29
+ return raw;
30
+ }
31
+
32
+ /** Tools excluded from subagents to prevent nesting. Legacy names remain for older hosts. */
33
+ const EXCLUDED_TOOL_NAMES = ["spawn_helper", "get_helper_result", "Agent", "get_result"];
34
+
35
+ /** All known built-in tool names. */
36
+ const BUILTIN_TOOL_NAMES = ["read", "bash", "edit", "write", "grep", "find", "ls"];
37
+
38
+ /** Grace turns after the soft turn limit before aborting. */
39
+ const GRACE_TURNS = 5;
40
+
41
+ /** Tool activity info. */
42
+ export interface ToolActivity {
43
+ type: "start" | "end";
44
+ toolName: string;
45
+ }
46
+
47
+ /** Options for running an agent. */
48
+ export interface RunOptions {
49
+ pi: ExtensionAPI;
50
+ model?: Model<any>;
51
+ agentConfig?: AgentConfig;
52
+ maxTurns?: number;
53
+ signal?: AbortSignal;
54
+ isolated?: boolean;
55
+ thinkingLevel?: ThinkingLevel;
56
+ cwd?: string;
57
+ onToolActivity?: (activity: ToolActivity) => void;
58
+ onTextDelta?: (delta: string, fullText: string) => void;
59
+ onSessionCreated?: (session: AgentSession) => void;
60
+ onTurnEnd?: (turnCount: number) => void;
61
+ }
62
+
63
+ /** Result from running an agent. */
64
+ export interface RunResult {
65
+ responseText: string;
66
+ session: AgentSession;
67
+ aborted: boolean;
68
+ steered: boolean;
69
+ }
70
+
71
+ /** Collect last assistant message text. */
72
+ function collectResponseText(session: AgentSession) {
73
+ let text = "";
74
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
75
+ if (event.type === "message_start") {
76
+ text = "";
77
+ }
78
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
79
+ text += event.assistantMessageEvent.delta;
80
+ }
81
+ });
82
+ return { getText: () => text, unsubscribe };
83
+ }
84
+
85
+ /** Get last assistant text from session history. */
86
+ function getLastAssistantText(session: AgentSession): string {
87
+ for (let i = session.messages.length - 1; i >= 0; i--) {
88
+ const msg = session.messages[i];
89
+ if (msg.role !== "assistant") continue;
90
+ const text = msg.content
91
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
92
+ .map((c) => c.text)
93
+ .join("")
94
+ .trim();
95
+ if (text) return text;
96
+ }
97
+ return "";
98
+ }
99
+
100
+ /** Wire abort signal to session. */
101
+ function forwardAbortSignal(session: AgentSession, signal?: AbortSignal): () => void {
102
+ if (!signal) return () => {};
103
+ const onAbort = () => session.abort();
104
+ signal.addEventListener("abort", onAbort, { once: true });
105
+ return () => signal.removeEventListener("abort", onAbort);
106
+ }
107
+
108
+ /** Get tool names for agent type. */
109
+ function getToolNamesForType(type: AgentType, config?: AgentConfig): string[] {
110
+ if (config?.builtinToolNames?.length) {
111
+ return [...config.builtinToolNames];
112
+ }
113
+ return [...BUILTIN_TOOL_NAMES];
114
+ }
115
+
116
+ /** Resolve agent config for a type.
117
+ * Priority: explicit config > builtin config > default
118
+ */
119
+ function resolveAgentConfig(type: AgentType, explicitConfig?: AgentConfig): AgentConfig | undefined {
120
+ if (explicitConfig) return explicitConfig;
121
+ return BUILTIN_CONFIGS[type];
122
+ }
123
+
124
+ /**
125
+ * Run an agent session.
126
+ */
127
+ export async function runAgent(
128
+ ctx: ExtensionContext,
129
+ type: AgentType,
130
+ prompt: string,
131
+ options: RunOptions,
132
+ ): Promise<RunResult> {
133
+ const effectiveCwd = options.cwd ?? ctx.cwd;
134
+
135
+ // Resolve agent config
136
+ const agentConfig = resolveAgentConfig(type, options.agentConfig);
137
+ const parentSystemPrompt = ctx.getSystemPrompt();
138
+
139
+ // Build system prompt using config or defaults
140
+ let systemPrompt: string;
141
+ if (agentConfig?.systemPrompt && agentConfig.promptMode === "replace") {
142
+ systemPrompt = agentConfig.systemPrompt;
143
+ } else if (options.isolated) {
144
+ const base = agentConfig?.systemPrompt ?? `You are a ${type} agent.`;
145
+ systemPrompt = `${base} Follow the task instructions precisely. Do not ask questions.`;
146
+ } else {
147
+ const agentPrompt = agentConfig?.systemPrompt ?? `You are a ${type} agent.`;
148
+ systemPrompt = parentSystemPrompt + `\n\n${agentPrompt}`;
149
+ }
150
+
151
+ // Get tool names from config
152
+ let toolNames = getToolNamesForType(type, agentConfig);
153
+
154
+ // Create resource loader
155
+ // Respect agentConfig.extensions/skills flags: if explicitly false, skip loading.
156
+ // This prevents explore/work agents from loading all parent extensions.
157
+ const agentDir = getAgentDir();
158
+ const skipExtensions = options.isolated || agentConfig?.extensions === false;
159
+ const skipSkills = options.isolated || agentConfig?.skills === false;
160
+ const loader = new DefaultResourceLoader({
161
+ cwd: effectiveCwd,
162
+ agentDir,
163
+ noExtensions: skipExtensions,
164
+ noSkills: skipSkills,
165
+ noPromptTemplates: true,
166
+ noThemes: true,
167
+ noContextFiles: true,
168
+ systemPromptOverride: () => systemPrompt,
169
+ appendSystemPromptOverride: () => [],
170
+ });
171
+ await loader.reload();
172
+
173
+ // Resolve model
174
+ const model = options.model ?? ctx.model;
175
+
176
+ // Create session
177
+ const sessionOpts: Parameters<typeof createAgentSession>[0] = {
178
+ cwd: effectiveCwd,
179
+ agentDir,
180
+ sessionManager: SessionManager.inMemory(effectiveCwd),
181
+ settingsManager: SettingsManager.create(effectiveCwd, agentDir),
182
+ modelRegistry: ctx.modelRegistry,
183
+ model,
184
+ tools: toolNames,
185
+ resourceLoader: loader,
186
+ };
187
+ if (options.thinkingLevel) {
188
+ sessionOpts.thinkingLevel = options.thinkingLevel;
189
+ }
190
+
191
+ const { session } = await createAgentSession(sessionOpts);
192
+
193
+ // Filter out our tools to prevent nesting
194
+ const activeTools = session.getActiveToolNames().filter((t) => {
195
+ if (EXCLUDED_TOOL_NAMES.includes(t)) return false;
196
+ return true;
197
+ });
198
+ session.setActiveToolsByName(activeTools);
199
+
200
+ // Bind extensions — only if extensions were loaded.
201
+ // Skipping for agents with extensions: false avoids firing session_start
202
+ // on an empty extension set, preventing unnecessary MODULE_READY cascade.
203
+ if (!skipExtensions) {
204
+ await session.bindExtensions({
205
+ onError: (err) => {
206
+ options.onToolActivity?.({
207
+ type: "end",
208
+ toolName: `extension-error:${err.extensionPath}`,
209
+ });
210
+ },
211
+ });
212
+ }
213
+
214
+ options.onSessionCreated?.(session);
215
+
216
+ // Track turns
217
+ let turnCount = 0;
218
+ const maxTurns = options.maxTurns;
219
+ let softLimitReached = false;
220
+ let aborted = false;
221
+
222
+ let currentMessageText = "";
223
+ const unsubTurns = session.subscribe((event: AgentSessionEvent) => {
224
+ if (event.type === "turn_end") {
225
+ turnCount++;
226
+ options.onTurnEnd?.(turnCount);
227
+ if (maxTurns != null) {
228
+ if (!softLimitReached && turnCount >= maxTurns) {
229
+ softLimitReached = true;
230
+ session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
231
+ } else if (softLimitReached && turnCount >= maxTurns + GRACE_TURNS) {
232
+ aborted = true;
233
+ session.abort();
234
+ }
235
+ }
236
+ }
237
+ if (event.type === "message_start") {
238
+ currentMessageText = "";
239
+ }
240
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
241
+ currentMessageText += event.assistantMessageEvent.delta;
242
+ options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
243
+ }
244
+ if (event.type === "tool_execution_start") {
245
+ options.onToolActivity?.({ type: "start", toolName: event.toolName });
246
+ }
247
+ if (event.type === "tool_execution_end") {
248
+ options.onToolActivity?.({ type: "end", toolName: event.toolName });
249
+ }
250
+ });
251
+
252
+ const collector = collectResponseText(session);
253
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
254
+
255
+ try {
256
+ await session.prompt(prompt);
257
+ } finally {
258
+ unsubTurns();
259
+ collector.unsubscribe();
260
+ cleanupAbort();
261
+ }
262
+
263
+ const responseText = collector.getText().trim() || getLastAssistantText(session);
264
+ return { responseText, session, aborted, steered: softLimitReached };
265
+ }