pi-subagent-manager 1.10.0 → 1.11.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 (186) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +836 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/orch/checklist-integration.d.ts +48 -0
  6. package/dist/orch/checklist-integration.d.ts.map +1 -0
  7. package/dist/orch/checklist-integration.js +204 -0
  8. package/dist/orch/checklist-integration.js.map +1 -0
  9. package/dist/orch/context-entries.d.ts +8 -0
  10. package/dist/orch/context-entries.d.ts.map +1 -0
  11. package/dist/orch/context-entries.js +8 -0
  12. package/dist/orch/context-entries.js.map +1 -0
  13. package/dist/orch/cost-ledger.d.ts +16 -0
  14. package/dist/orch/cost-ledger.d.ts.map +1 -0
  15. package/dist/orch/cost-ledger.js +43 -0
  16. package/dist/orch/cost-ledger.js.map +1 -0
  17. package/dist/orch/diagnostics.d.ts +13 -0
  18. package/dist/orch/diagnostics.d.ts.map +1 -0
  19. package/dist/orch/diagnostics.js +95 -0
  20. package/dist/orch/diagnostics.js.map +1 -0
  21. package/dist/orch/extensions.d.ts +15 -0
  22. package/dist/orch/extensions.d.ts.map +1 -0
  23. package/dist/orch/extensions.js +80 -0
  24. package/dist/orch/extensions.js.map +1 -0
  25. package/dist/orch/housekeeping-usage.d.ts +14 -0
  26. package/dist/orch/housekeeping-usage.d.ts.map +1 -0
  27. package/dist/orch/housekeeping-usage.js +27 -0
  28. package/dist/orch/housekeeping-usage.js.map +1 -0
  29. package/dist/orch/housekeeping.d.ts +89 -0
  30. package/dist/orch/housekeeping.d.ts.map +1 -0
  31. package/dist/orch/housekeeping.js +281 -0
  32. package/dist/orch/housekeeping.js.map +1 -0
  33. package/dist/orch/inherited-tools.d.ts +18 -0
  34. package/dist/orch/inherited-tools.d.ts.map +1 -0
  35. package/dist/orch/inherited-tools.js +71 -0
  36. package/dist/orch/inherited-tools.js.map +1 -0
  37. package/dist/orch/mailbox.d.ts +59 -0
  38. package/dist/orch/mailbox.d.ts.map +1 -0
  39. package/dist/orch/mailbox.js +196 -0
  40. package/dist/orch/mailbox.js.map +1 -0
  41. package/dist/orch/manager.d.ts +82 -0
  42. package/dist/orch/manager.d.ts.map +1 -0
  43. package/dist/orch/manager.js +1010 -0
  44. package/dist/orch/manager.js.map +1 -0
  45. package/dist/orch/paths.d.ts +7 -0
  46. package/dist/orch/paths.d.ts.map +1 -0
  47. package/dist/orch/paths.js +73 -0
  48. package/dist/orch/paths.js.map +1 -0
  49. package/dist/orch/prompt.d.ts +7 -0
  50. package/dist/orch/prompt.d.ts.map +1 -0
  51. package/dist/orch/prompt.js +34 -0
  52. package/dist/orch/prompt.js.map +1 -0
  53. package/dist/orch/registry.d.ts +49 -0
  54. package/dist/orch/registry.d.ts.map +1 -0
  55. package/dist/orch/registry.js +134 -0
  56. package/dist/orch/registry.js.map +1 -0
  57. package/dist/orch/runtime.d.ts +11 -0
  58. package/dist/orch/runtime.d.ts.map +1 -0
  59. package/dist/orch/runtime.js +882 -0
  60. package/dist/orch/runtime.js.map +1 -0
  61. package/dist/orch/tools.d.ts +6 -0
  62. package/dist/orch/tools.d.ts.map +1 -0
  63. package/dist/orch/tools.js +114 -0
  64. package/dist/orch/tools.js.map +1 -0
  65. package/dist/orch/transcript.d.ts +28 -0
  66. package/dist/orch/transcript.d.ts.map +1 -0
  67. package/dist/orch/transcript.js +176 -0
  68. package/dist/orch/transcript.js.map +1 -0
  69. package/dist/prefs/agent-import.d.ts +37 -0
  70. package/dist/prefs/agent-import.d.ts.map +1 -0
  71. package/dist/prefs/agent-import.js +196 -0
  72. package/dist/prefs/agent-import.js.map +1 -0
  73. package/dist/prefs/config.d.ts +108 -0
  74. package/dist/prefs/config.d.ts.map +1 -0
  75. package/dist/prefs/config.js +926 -0
  76. package/dist/prefs/config.js.map +1 -0
  77. package/dist/prefs/import-discovery.d.ts +28 -0
  78. package/dist/prefs/import-discovery.d.ts.map +1 -0
  79. package/dist/prefs/import-discovery.js +562 -0
  80. package/dist/prefs/import-discovery.js.map +1 -0
  81. package/dist/prefs/import-instructions.d.ts +3 -0
  82. package/dist/prefs/import-instructions.d.ts.map +1 -0
  83. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +1 -0
  84. package/dist/prefs/import-instructions.js.map +1 -0
  85. package/dist/prefs/models.d.ts +24 -0
  86. package/dist/prefs/models.d.ts.map +1 -0
  87. package/dist/prefs/models.js +57 -0
  88. package/dist/prefs/models.js.map +1 -0
  89. package/dist/prefs/settings.d.ts +89 -0
  90. package/dist/prefs/settings.d.ts.map +1 -0
  91. package/dist/prefs/settings.js +505 -0
  92. package/dist/prefs/settings.js.map +1 -0
  93. package/dist/types.d.ts +293 -0
  94. package/dist/types.d.ts.map +1 -0
  95. package/dist/types.js +2 -0
  96. package/dist/types.js.map +1 -0
  97. package/dist/ui/agent-loader.d.ts +21 -0
  98. package/dist/ui/agent-loader.d.ts.map +1 -0
  99. package/dist/ui/agent-loader.js +73 -0
  100. package/dist/ui/agent-loader.js.map +1 -0
  101. package/dist/ui/agent-navigation-editor.d.ts +46 -0
  102. package/dist/ui/agent-navigation-editor.d.ts.map +1 -0
  103. package/dist/ui/agent-navigation-editor.js +189 -0
  104. package/dist/ui/agent-navigation-editor.js.map +1 -0
  105. package/dist/ui/cost-footer.d.ts +37 -0
  106. package/dist/ui/cost-footer.d.ts.map +1 -0
  107. package/dist/ui/cost-footer.js +215 -0
  108. package/dist/ui/cost-footer.js.map +1 -0
  109. package/dist/ui/dialog.d.ts +135 -0
  110. package/dist/ui/dialog.d.ts.map +1 -0
  111. package/dist/ui/dialog.js +533 -0
  112. package/dist/ui/dialog.js.map +1 -0
  113. package/dist/ui/import-picker.d.ts +38 -0
  114. package/dist/ui/import-picker.d.ts.map +1 -0
  115. package/dist/ui/import-picker.js +211 -0
  116. package/dist/ui/import-picker.js.map +1 -0
  117. package/dist/ui/live-agent-view.d.ts +82 -0
  118. package/dist/ui/live-agent-view.d.ts.map +1 -0
  119. package/dist/ui/live-agent-view.js +546 -0
  120. package/dist/ui/live-agent-view.js.map +1 -0
  121. package/dist/ui/model-picker.d.ts +109 -0
  122. package/dist/ui/model-picker.d.ts.map +1 -0
  123. package/dist/ui/model-picker.js +549 -0
  124. package/dist/ui/model-picker.js.map +1 -0
  125. package/dist/ui/settings-ui.d.ts +17 -0
  126. package/dist/ui/settings-ui.d.ts.map +1 -0
  127. package/dist/ui/settings-ui.js +679 -0
  128. package/dist/ui/settings-ui.js.map +1 -0
  129. package/dist/ui/status-ui.d.ts +67 -0
  130. package/dist/ui/status-ui.d.ts.map +1 -0
  131. package/dist/ui/status-ui.js +487 -0
  132. package/dist/ui/status-ui.js.map +1 -0
  133. package/dist/ui/thread-tree.d.ts +22 -0
  134. package/dist/ui/thread-tree.d.ts.map +1 -0
  135. package/dist/ui/thread-tree.js +153 -0
  136. package/dist/ui/thread-tree.js.map +1 -0
  137. package/dist/ui/tool-picker.d.ts +46 -0
  138. package/dist/ui/tool-picker.d.ts.map +1 -0
  139. package/dist/ui/tool-picker.js +334 -0
  140. package/dist/ui/tool-picker.js.map +1 -0
  141. package/dist/ui/transcript-tool.d.ts +2 -0
  142. package/dist/ui/transcript-tool.d.ts.map +1 -0
  143. package/dist/ui/transcript-tool.js +100 -0
  144. package/dist/ui/transcript-tool.js.map +1 -0
  145. package/dist/ui/ui.d.ts +41 -0
  146. package/dist/ui/ui.d.ts.map +1 -0
  147. package/dist/ui/ui.js +1047 -0
  148. package/dist/ui/ui.js.map +1 -0
  149. package/docs/development.md +2 -1
  150. package/package.json +16 -4
  151. package/src/index.ts +0 -920
  152. package/src/orch/checklist-integration.ts +0 -230
  153. package/src/orch/context-entries.ts +0 -15
  154. package/src/orch/cost-ledger.ts +0 -56
  155. package/src/orch/diagnostics.ts +0 -95
  156. package/src/orch/extensions.ts +0 -83
  157. package/src/orch/housekeeping-usage.ts +0 -47
  158. package/src/orch/housekeeping.ts +0 -348
  159. package/src/orch/inherited-tools.ts +0 -84
  160. package/src/orch/mailbox.ts +0 -261
  161. package/src/orch/manager.ts +0 -1084
  162. package/src/orch/paths.ts +0 -73
  163. package/src/orch/prompt.ts +0 -39
  164. package/src/orch/registry.ts +0 -168
  165. package/src/orch/runtime.ts +0 -1041
  166. package/src/orch/tools.ts +0 -190
  167. package/src/orch/transcript.ts +0 -186
  168. package/src/prefs/agent-import.ts +0 -245
  169. package/src/prefs/config.ts +0 -1017
  170. package/src/prefs/import-discovery.ts +0 -643
  171. package/src/prefs/models.ts +0 -74
  172. package/src/prefs/settings.ts +0 -614
  173. package/src/types.ts +0 -271
  174. package/src/ui/agent-loader.ts +0 -98
  175. package/src/ui/agent-navigation-editor.ts +0 -233
  176. package/src/ui/cost-footer.ts +0 -230
  177. package/src/ui/dialog.ts +0 -678
  178. package/src/ui/import-picker.ts +0 -231
  179. package/src/ui/live-agent-view.ts +0 -600
  180. package/src/ui/model-picker.ts +0 -701
  181. package/src/ui/settings-ui.ts +0 -830
  182. package/src/ui/status-ui.ts +0 -628
  183. package/src/ui/thread-tree.ts +0 -173
  184. package/src/ui/tool-picker.ts +0 -398
  185. package/src/ui/transcript-tool.ts +0 -142
  186. package/src/ui/ui.ts +0 -1407
@@ -0,0 +1,882 @@
1
+ import path from "node:path";
2
+ import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
3
+ import { existsSync } from "node:fs";
4
+ import { mkdir, readFile, realpath } from "node:fs/promises";
5
+ import { createAgentSession, createEventBus, createExtensionRuntime, ExtensionRunner, ModelRegistry, createSyntheticSourceInfo, createCodemodeExtension, createToolSearchExtension, DefaultResourceLoader, getAgentDir, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
6
+ import { BOOTSTRAP_MESSAGE, buildBootstrapMessage, buildQueuedUserMessage, buildUpdateDetails, DurableMailbox, } from "./mailbox.js";
7
+ import { selectTools } from "../prefs/config.js";
8
+ import { TranscriptChannel } from "./transcript.js";
9
+ import { delegationGuidance } from "./prompt.js";
10
+ import { discoverSubagentExtensions, selectSubagentExtensions } from "./extensions.js";
11
+ import { inheritedContextEntries } from "./context-entries.js";
12
+ import { modelIdentity, getModelPreferences, selectPreferredModel } from "../prefs/models.js";
13
+ import { THINKING_LEVELS, } from "../types.js";
14
+ import { DIAGNOSTIC_CHANNEL, DIAGNOSTIC_PROBE_CHANNEL, respondDiagnosticCapability, diagnosticSink, diagnosticText, } from "./diagnostics.js";
15
+ const BUILTINS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
16
+ /** Persisted before transcript messages so older-leaf restores still carry ownership. */
17
+ const THREAD_OWNERSHIP_TYPE = "pi-subagent:thread:v1";
18
+ const SESSION_FILE_ERROR = "Subagent sessionFile must be a JSONL file inside this root's session directory";
19
+ function parseModelIdentity(identity) {
20
+ const slash = identity.indexOf("/");
21
+ return { provider: identity.slice(0, slash), id: identity.slice(slash + 1) };
22
+ }
23
+ function scopedModelsKey(scopedModels) {
24
+ return scopedModels
25
+ .map(({ model, thinkingLevel }) => `${modelIdentity(model)}\0${thinkingLevel ?? ""}`)
26
+ .join("\n");
27
+ }
28
+ function isJsonlWithin(directory, file) {
29
+ const relative = path.relative(directory, file);
30
+ return (!!relative &&
31
+ !relative.startsWith(`..${path.sep}`) &&
32
+ relative !== ".." &&
33
+ !path.isAbsolute(relative) &&
34
+ file.endsWith(".jsonl"));
35
+ }
36
+ async function tryRealpath(target) {
37
+ try {
38
+ return await realpath(target);
39
+ }
40
+ catch (error) {
41
+ const code = error.code;
42
+ if (code === "ENOENT" || code === "ENOTDIR")
43
+ return undefined;
44
+ throw error;
45
+ }
46
+ }
47
+ function ownershipFromTranscript(content) {
48
+ for (const line of content.split("\n")) {
49
+ if (!line.trim())
50
+ continue;
51
+ let parsed;
52
+ try {
53
+ parsed = JSON.parse(line);
54
+ }
55
+ catch {
56
+ continue;
57
+ }
58
+ if (!parsed || typeof parsed !== "object")
59
+ continue;
60
+ const entry = parsed;
61
+ if (entry.type !== "custom" || entry.customType !== THREAD_OWNERSHIP_TYPE)
62
+ continue;
63
+ const data = entry.data;
64
+ if (!data || typeof data !== "object")
65
+ return undefined;
66
+ const { rootId, threadPath } = data;
67
+ if (typeof rootId !== "string" || typeof threadPath !== "string")
68
+ return undefined;
69
+ return { rootId, threadPath };
70
+ }
71
+ return undefined;
72
+ }
73
+ /** Orchestrator file for /root and independent roots; nested parents supply their own file. */
74
+ function resolveParentSession(options, rootSessionFile) {
75
+ if (options.parentSessionFile)
76
+ return options.parentSessionFile;
77
+ if (!options.parentPath || options.parentPath === "/root")
78
+ return rootSessionFile;
79
+ return undefined;
80
+ }
81
+ async function assertAcceptedSessionFile(sessionFile, sessionDir, legacyDir, rootId, threadPath, signal) {
82
+ signal.throwIfAborted();
83
+ const sharedDir = await realpath(sessionDir);
84
+ signal.throwIfAborted();
85
+ const file = await tryRealpath(sessionFile);
86
+ signal.throwIfAborted();
87
+ const legacyDirReal = await tryRealpath(legacyDir);
88
+ signal.throwIfAborted();
89
+ // Legacy root-scoped transcripts stay valid, including files nested under that directory.
90
+ if (file && legacyDirReal && isJsonlWithin(legacyDirReal, file))
91
+ return;
92
+ if (!file || path.dirname(file) !== sharedDir || !file.endsWith(".jsonl")) {
93
+ throw new Error(SESSION_FILE_ERROR);
94
+ }
95
+ const ownership = ownershipFromTranscript(await readFile(file, { encoding: "utf8", signal }));
96
+ signal.throwIfAborted();
97
+ if (!ownership || ownership.rootId !== rootId || ownership.threadPath !== threadPath) {
98
+ throw new Error("Subagent sessionFile ownership metadata does not match this rootId and thread path");
99
+ }
100
+ }
101
+ const SNIPPET_KEYS = [
102
+ "command",
103
+ "path",
104
+ "file_path",
105
+ "filePath",
106
+ "pattern",
107
+ "query",
108
+ "url",
109
+ "description",
110
+ ];
111
+ /** Short single-line argument hint for housekeeping summaries; never shown verbatim as status. */
112
+ export function toolArgumentSnippet(args) {
113
+ if (args === null || args === undefined)
114
+ return undefined;
115
+ let text;
116
+ if (typeof args === "string")
117
+ text = args;
118
+ else if (typeof args === "object") {
119
+ const record = args;
120
+ const key = SNIPPET_KEYS.find((name) => typeof record[name] === "string");
121
+ if (key)
122
+ text = String(record[key]);
123
+ else {
124
+ try {
125
+ text = JSON.stringify(args);
126
+ }
127
+ catch {
128
+ return undefined;
129
+ }
130
+ }
131
+ }
132
+ const clean = text
133
+ ?.replace(/[\x00-\x1f\x7f-\x9f]+/g, " ")
134
+ .replace(/\s+/g, " ")
135
+ .trim();
136
+ return clean ? clean.slice(0, 160) : undefined;
137
+ }
138
+ /** Isolated SDK sessions; configured extension reload is experimental and opt-in. */
139
+ export function createDriverFactory(getRootContext, getModelSelection = () => "pick-first-scoped", getToolFiltering = () => "allowed", getInheritedTools = () => ({ tools: [], activeNames: [] }), getSubagentExtensions = () => false) {
140
+ // Keep resolved settings even after disposal: descendants inherit settings, not the caller's history.
141
+ const resolved = new Map();
142
+ const normalizeScopedModels = (scopedModels) => scopedModels ?? [];
143
+ const availableModelCandidates = () => getRootContext()
144
+ .modelRegistry.getAvailable()
145
+ .map((model) => ({ model }));
146
+ const availableScopedModels = (scopedModels) => {
147
+ const available = new Set(availableModelCandidates().map(({ model }) => modelIdentity(model)));
148
+ return scopedModels.filter(({ model }) => available.has(modelIdentity(model)));
149
+ };
150
+ // Pi represents an unrestricted scope with an empty array.
151
+ const selectTypeModelPreference = (type, scopedModels, filtering) => {
152
+ const restricted = filtering && scopedModels.length > 0;
153
+ return selectPreferredModel(type, restricted ? availableScopedModels(scopedModels) : availableModelCandidates(), restricted);
154
+ };
155
+ // Discovery and new/restored drivers share model selection and thinking inheritance.
156
+ const resolveInitialSettings = (type, parentPath, restored) => {
157
+ const ctx = getRootContext();
158
+ const parent = parentPath
159
+ ? resolved.get(`${ctx.sessionManager.getSessionId()}:${parentPath}`)
160
+ : undefined;
161
+ const mode = getModelSelection();
162
+ const preferences = mode === "use-current" ? undefined : getModelPreferences(type);
163
+ let provider = parent?.provider ?? ctx.model?.provider;
164
+ let id = parent?.id ?? ctx.model?.id;
165
+ if (mode === "use-current") {
166
+ provider = ctx.model?.provider;
167
+ id = ctx.model?.id;
168
+ }
169
+ else if (preferences !== undefined) {
170
+ const filtering = mode === "pick-first-scoped";
171
+ ({ provider, id } = parseModelIdentity(selectTypeModelPreference(type, normalizeScopedModels(ctx.scopedModels), filtering)));
172
+ }
173
+ else if (restored?.model) {
174
+ provider = restored.model.provider;
175
+ id = restored.model.modelId;
176
+ }
177
+ const savedThinking = restored && THINKING_LEVELS.includes(restored.thinkingLevel)
178
+ ? restored.thinkingLevel
179
+ : undefined;
180
+ const thinkingLevel = savedThinking ?? type.thinkingLevel ?? parent?.thinking ?? ctx.thinkingLevel ?? "off";
181
+ return { provider, id, thinkingLevel };
182
+ };
183
+ const resolveAgentSettings = (type, parentPath) => {
184
+ const ctx = getRootContext();
185
+ const { provider, id, thinkingLevel } = resolveInitialSettings(type, parentPath);
186
+ const model = normalizeScopedModels(ctx.scopedModels).find(({ model }) => model.provider === provider && model.id === id)?.model ?? (provider && id ? ctx.modelRegistry.find(provider, id) : undefined);
187
+ if (!model)
188
+ throw new Error(`Subagent model ${provider ?? "(unset)"}/${id ?? "(unset)"} is unavailable; select a physical model in the root or agent type`);
189
+ if (model.api === "pi-virtual")
190
+ throw new Error(`Virtual model ${provider}/${id} cannot be reproduced through the public registry API. Set this agent type's model to a physical provider/model-id.`);
191
+ return { model: modelIdentity(model), thinkingLevel: clampThinkingLevel(model, thinkingLevel) };
192
+ };
193
+ const createDriver = async (options) => {
194
+ options.signal.throwIfAborted();
195
+ const ctx = getRootContext();
196
+ // Tool policy is a startup snapshot; retained live sessions keep their selected set.
197
+ const toolFiltering = getToolFiltering();
198
+ const extensionSelection = getSubagentExtensions();
199
+ const rootId = ctx.sessionManager.getSessionId();
200
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(rootId))
201
+ throw new Error("Unsafe root session id for subagent storage");
202
+ const agentDir = getAgentDir();
203
+ const sessionDir = ctx.sessionManager.getSessionDir();
204
+ const legacyDir = path.join(agentDir, "subagents", rootId);
205
+ options.signal.throwIfAborted();
206
+ await mkdir(sessionDir, { recursive: true });
207
+ options.signal.throwIfAborted();
208
+ let sessionManager;
209
+ if (options.sessionFile) {
210
+ await assertAcceptedSessionFile(options.sessionFile, sessionDir, legacyDir, rootId, options.path, options.signal);
211
+ // Open the caller path, not its realpath, so retained sessionFile identity is stable.
212
+ sessionManager = SessionManager.open(path.resolve(options.sessionFile), sessionDir, ctx.cwd);
213
+ if (options.sessionLeafId !== undefined) {
214
+ if (options.sessionLeafId === null)
215
+ sessionManager.resetLeaf();
216
+ else
217
+ sessionManager.branch(options.sessionLeafId);
218
+ }
219
+ }
220
+ else {
221
+ const parentSession = resolveParentSession(options, ctx.sessionManager.getSessionFile());
222
+ sessionManager = SessionManager.create(ctx.cwd, sessionDir, parentSession ? { parentSession } : undefined);
223
+ // Before transcript messages so an older restored leaf still has name and ownership as ancestors.
224
+ sessionManager.appendSessionInfo(`${options.type.name} ${options.path}`);
225
+ sessionManager.appendCustomEntry(THREAD_OWNERSHIP_TYPE, {
226
+ rootId,
227
+ threadPath: options.path,
228
+ inheritedCount: options.inherited.length,
229
+ });
230
+ for (const message of options.inherited) {
231
+ // Summary messages are projections, not appendable SDK session entries.
232
+ if (message.role === "compactionSummary" || message.role === "branchSummary") {
233
+ sessionManager.appendMessage({
234
+ role: "user",
235
+ content: message.summary,
236
+ timestamp: message.timestamp,
237
+ });
238
+ }
239
+ else if (message.role === "custom") {
240
+ sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
241
+ }
242
+ else if (message.role === "user" ||
243
+ message.role === "assistant" ||
244
+ message.role === "toolResult" ||
245
+ message.role === "bashExecution") {
246
+ sessionManager.appendMessage(message);
247
+ }
248
+ }
249
+ for (const entry of options.inheritedContextEntries ?? []) {
250
+ sessionManager.appendCustomEntry(entry.customType, entry.data);
251
+ }
252
+ }
253
+ const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
254
+ const modelSelection = getModelSelection();
255
+ // Use Current ignores definition preferences, including for restored/nested sessions.
256
+ const modelPreferences = modelSelection === "use-current" ? undefined : getModelPreferences(options.type);
257
+ const filteringEnabled = () => getModelSelection() === "pick-first-scoped";
258
+ const selectModelPreference = (scopedModels, filtering = filteringEnabled()) => selectTypeModelPreference(options.type, scopedModels, filtering);
259
+ const initialScopedModels = normalizeScopedModels(ctx.scopedModels);
260
+ const { provider, id, thinkingLevel } = resolveInitialSettings(options.type, options.parentPath, restored);
261
+ options.signal.throwIfAborted();
262
+ const runtime = await ModelRuntime.create({
263
+ authPath: path.join(agentDir, "auth.json"),
264
+ modelsPath: path.join(agentDir, "models.json"),
265
+ modelsStorePath: path.join(agentDir, "models-store.json"),
266
+ allowModelNetwork: false,
267
+ signal: options.signal,
268
+ });
269
+ options.signal.throwIfAborted();
270
+ for (const providerId of ctx.modelRegistry.getRegisteredProviderIds()) {
271
+ const native = ctx.modelRegistry.getRegisteredNativeProvider(providerId);
272
+ const config = ctx.modelRegistry.getRegisteredProviderConfig(providerId);
273
+ if (native)
274
+ runtime.registerNativeProvider(native);
275
+ if (config)
276
+ runtime.registerProvider(providerId, config);
277
+ }
278
+ const mirrorRuntimeAuth = async (providerId) => {
279
+ options.signal.throwIfAborted();
280
+ if (ctx.modelRegistry.getProviderAuthStatus(providerId).source !== "runtime")
281
+ return;
282
+ const apiKey = await ctx.modelRegistry.getApiKeyForProvider(providerId);
283
+ options.signal.throwIfAborted();
284
+ if (apiKey !== undefined)
285
+ await runtime.setRuntimeApiKey(providerId, apiKey, { signal: options.signal });
286
+ options.signal.throwIfAborted();
287
+ };
288
+ const resolveRuntimeModel = async (providerId, modelId, scopedModels) => {
289
+ if (!providerId || !modelId)
290
+ throw new Error(`Subagent model ${providerId ?? "(unset)"}/${modelId ?? "(unset)"} is unavailable; select a physical model in the root or agent type`);
291
+ await mirrorRuntimeAuth(providerId);
292
+ const sourceModel = scopedModels.find(({ model }) => model.provider === providerId && model.id === modelId)
293
+ ?.model ?? ctx.modelRegistry.find(providerId, modelId);
294
+ if (sourceModel?.api === "pi-virtual") {
295
+ throw new Error(`Virtual model ${providerId}/${modelId} cannot be reproduced through the public registry API. Set this agent type's model to a physical provider/model-id.`);
296
+ }
297
+ const runtimeModel = runtime.getModel(providerId, modelId);
298
+ if (!runtimeModel)
299
+ throw new Error(`Subagent model ${providerId}/${modelId} is unavailable; select a physical model in the root or agent type`);
300
+ return runtimeModel;
301
+ };
302
+ const model = await resolveRuntimeModel(provider, id, initialScopedModels);
303
+ const inherited = getInheritedTools();
304
+ const localNames = new Set([...BUILTINS, ...options.tools.map((tool) => tool.name)]);
305
+ const externalTools = inherited.tools.filter((tool) => !localNames.has(tool.name));
306
+ const toolNames = selectTools(options.type.tools, [...localNames, ...externalTools.map((tool) => tool.name)], toolFiltering);
307
+ const allowed = new Set(toolNames);
308
+ const rootActive = new Set(inherited.activeNames);
309
+ // Preserve deferred/codemode exposure rather than flooding model declarations with MCP tools.
310
+ const activeToolNames = toolNames.filter((name) => localNames.has(name) ||
311
+ rootActive.has(name) ||
312
+ (options.type.tools?.allow?.includes(name) && toolFiltering === "allowed"));
313
+ const projectTrusted = ctx.isProjectTrusted?.() ?? false;
314
+ const extensionPaths = extensionSelection === false ||
315
+ (Array.isArray(extensionSelection) && !extensionSelection.length)
316
+ ? []
317
+ : selectSubagentExtensions(await discoverSubagentExtensions({ cwd: ctx.cwd, agentDir, projectTrusted }), extensionSelection);
318
+ const subagentExtensions = extensionPaths.length > 0;
319
+ // Keep discovery settings OUT of this loader: reload() resolves packages with
320
+ // auto-install enabled. An empty in-memory package/resource list ensures it
321
+ // only loads the already-resolved files and cannot install missing packages.
322
+ const settingsManager = SettingsManager.inMemory({ cacheWarming: "off" }, { projectTrusted });
323
+ let parkQueue = () => { };
324
+ const pauseBoundary = () => {
325
+ if (!options.shouldPause())
326
+ return undefined;
327
+ parkQueue();
328
+ return { continue: false };
329
+ };
330
+ // A separate bus per driver: never share parent/other-child extension events.
331
+ const childEvents = createEventBus();
332
+ let diagnosticsClosed = false;
333
+ let diagnosticsInitialized = false;
334
+ // The startup signal belongs to one run; a stopped driver may be reused.
335
+ const diagnosticsUnavailable = () => diagnosticsClosed || (!diagnosticsInitialized && options.signal.aborted);
336
+ if (subagentExtensions)
337
+ childEvents.on(DIAGNOSTIC_PROBE_CHANNEL, (payload) => {
338
+ try {
339
+ if (diagnosticsUnavailable() || !payload || typeof payload !== "object")
340
+ return;
341
+ respondDiagnosticCapability(payload);
342
+ }
343
+ catch {
344
+ /* Untrusted callbacks cannot escape into EventBus's stderr handler. */
345
+ }
346
+ });
347
+ if (subagentExtensions)
348
+ childEvents.on(DIAGNOSTIC_CHANNEL, diagnosticSink((diagnostic) => {
349
+ if (diagnosticsUnavailable())
350
+ return;
351
+ options.onEvent({ kind: "diagnostic", diagnostic });
352
+ try {
353
+ getRootContext().ui.notify(diagnosticText(options.path, diagnostic), diagnostic.level);
354
+ }
355
+ catch {
356
+ // Agent-facing delivery remains available if the UI is absent/unavailable.
357
+ }
358
+ }));
359
+ const loader = new DefaultResourceLoader({
360
+ eventBus: childEvents,
361
+ cwd: ctx.cwd,
362
+ agentDir,
363
+ settingsManager,
364
+ noExtensions: true,
365
+ additionalExtensionPaths: extensionPaths,
366
+ // Put bridges AFTER file extensions in the runner registry. First registration
367
+ // wins there, including tools registered by file extensions on session_start
368
+ // or later. SDK customTools would always override those child-local tools.
369
+ extensionsOverride: subagentExtensions
370
+ ? (base) => {
371
+ const sourceInfo = createSyntheticSourceInfo("<subagent-inherited-tools>", {
372
+ source: "sdk",
373
+ });
374
+ base.extensions.push({
375
+ path: "<subagent-inherited-tools>",
376
+ resolvedPath: "<subagent-inherited-tools>",
377
+ sourceInfo,
378
+ handlers: new Map(),
379
+ tools: new Map(externalTools
380
+ .filter((tool) => allowed.has(tool.name) &&
381
+ tool.name !== "codemode" &&
382
+ tool.name !== "tool_search")
383
+ .map((definition) => [definition.name, { definition, sourceInfo }])),
384
+ messageRenderers: new Map(),
385
+ commands: new Map(),
386
+ flags: new Map(),
387
+ shortcuts: new Map(),
388
+ });
389
+ return base;
390
+ }
391
+ : undefined,
392
+ noSkills: true,
393
+ noPromptTemplates: true,
394
+ noContextFiles: true,
395
+ noThemes: true,
396
+ systemPrompt: [
397
+ options.type.systemPrompt,
398
+ `Your thread path is ${options.path}.`,
399
+ options.parentPath
400
+ ? `Your lexical parent is ${options.parentPath}; inherited conversation comes only from that parent.`
401
+ : "You are an independent root thread with no inherited history.",
402
+ "When finished, give your final answer normally so it can be handed back. To retain unfinished work without a final answer, call agent_pause (if available), then stop; resume only when instructed.",
403
+ delegationGuidance(options.canSpawnChildren !== false),
404
+ ...(options.canSpawnChildren !== false &&
405
+ allowed.has("agent_spawn") &&
406
+ allowed.has("agent_wait")
407
+ ? [
408
+ "Name child paths with concise task-based kebab-case slugs (e.g. /root/controller-security-research), independent of type.",
409
+ "For independent parallel work, launch all siblings with agent_spawn wait:false before calling agent_wait. Children share the main conversation's depth and concurrency limits; waiting parents count as active. Do not delegate work beyond your assigned scope.",
410
+ ]
411
+ : []),
412
+ ].join("\n\n"),
413
+ appendSystemPromptOverride: () => [],
414
+ extensionFactories: [
415
+ // These orchestrators must see the CHILD loadout. Forwarding root codemode would
416
+ // let scripts discover/call tools outside the child's allow/block policy.
417
+ ...(allowed.has("codemode")
418
+ ? [
419
+ subagentExtensions
420
+ ? { name: "child-codemode", factory: createCodemodeExtension(), replaceable: true }
421
+ : createCodemodeExtension(),
422
+ ]
423
+ : []),
424
+ ...(allowed.has("tool_search")
425
+ ? [
426
+ subagentExtensions
427
+ ? {
428
+ name: "child-tool-search",
429
+ factory: createToolSearchExtension(),
430
+ replaceable: true,
431
+ }
432
+ : createToolSearchExtension(),
433
+ ]
434
+ : []),
435
+ (pi) => {
436
+ pi.on("turn_end", pauseBoundary);
437
+ pi.on("agent_before_settle", pauseBoundary);
438
+ pi.on("tool_call", (event) => allowed.has(event.toolName)
439
+ ? undefined
440
+ : { block: true, reason: "Tool is not allowed by this agent type" });
441
+ },
442
+ ],
443
+ });
444
+ options.signal.throwIfAborted();
445
+ try {
446
+ await loader.reload();
447
+ }
448
+ catch (error) {
449
+ diagnosticsClosed = true;
450
+ childEvents.clear();
451
+ throw error;
452
+ }
453
+ const loadedExtensions = loader.getExtensions();
454
+ // Manager controls remain SDK custom tools so loaded extensions cannot replace
455
+ // them. With reload disabled, preserve the existing SDK bridge behavior exactly.
456
+ const customTools = [...options.tools, ...(subagentExtensions ? [] : externalTools)].filter((tool) => allowed.has(tool.name) && tool.name !== "codemode" && tool.name !== "tool_search");
457
+ let session;
458
+ try {
459
+ ({ session } = await createAgentSession({
460
+ cwd: ctx.cwd,
461
+ agentDir,
462
+ modelRuntime: runtime,
463
+ model,
464
+ thinkingLevel,
465
+ scopedModels: [...initialScopedModels],
466
+ settingsManager,
467
+ resourceLoader: loader,
468
+ sessionManager,
469
+ // SDK `tools` is both a registry allowlist and an initial active list.
470
+ // Register every permitted deferred tool, then narrow declarations after bind.
471
+ tools: toolNames,
472
+ customTools,
473
+ }));
474
+ }
475
+ catch (error) {
476
+ if (subagentExtensions) {
477
+ // No session was returned, so normal disposal is unavailable. Give loaded
478
+ // factories a shutdown-only runner with child-local metadata/persistence;
479
+ // unavailable session actions remain throwing stubs, not root bridges.
480
+ await (async () => {
481
+ const runner = new ExtensionRunner(loadedExtensions.extensions, loadedExtensions.runtime, ctx.cwd, sessionManager, new ModelRegistry(runtime));
482
+ try {
483
+ runner.bindCore({
484
+ ...createExtensionRuntime(),
485
+ appendEntry: (customType, data) => sessionManager.appendCustomEntry(customType, data),
486
+ getSessionName: () => sessionManager.getSessionName(),
487
+ getSettings: () => settingsManager.getSettings(),
488
+ getThinkingLevel: () => clampThinkingLevel(model, thinkingLevel),
489
+ }, {
490
+ getModel: () => model,
491
+ getScopedModels: () => initialScopedModels,
492
+ isIdle: () => true,
493
+ isProjectTrusted: () => projectTrusted,
494
+ getSignal: () => undefined,
495
+ abort: () => { },
496
+ hasPendingMessages: () => false,
497
+ shutdown: () => { },
498
+ getContextUsage: () => undefined,
499
+ compact: () => { },
500
+ getSystemPrompt: () => loader.getSystemPrompt() ?? "",
501
+ });
502
+ await runner.emit({ type: "session_shutdown", reason: "quit" });
503
+ }
504
+ finally {
505
+ runner.invalidate();
506
+ }
507
+ })().catch(() => {
508
+ // Best-effort cleanup must not hide the SDK's original startup failure.
509
+ });
510
+ }
511
+ diagnosticsClosed = true;
512
+ childEvents.clear();
513
+ throw error;
514
+ }
515
+ const unsubscribeExtensionErrors = subagentExtensions
516
+ ? session.extensionRunner.onError((error) => options.onEvent({
517
+ kind: "error",
518
+ text: `Extension ${error.extensionPath} (${error.event}): ${error.error}`.slice(0, 1000),
519
+ }))
520
+ : () => { };
521
+ let shutdownPromise;
522
+ const disposeSession = () => {
523
+ if (!subagentExtensions) {
524
+ diagnosticsClosed = true;
525
+ childEvents.clear();
526
+ session.dispose();
527
+ return;
528
+ }
529
+ // SDK dispose invalidates contexts but does not emit session_shutdown. Await
530
+ // handlers before invalidation so session-scoped resources can be released.
531
+ return (shutdownPromise ??= (async () => {
532
+ try {
533
+ await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
534
+ }
535
+ finally {
536
+ unsubscribeExtensionErrors();
537
+ diagnosticsClosed = true;
538
+ childEvents.clear();
539
+ session.dispose();
540
+ }
541
+ })());
542
+ };
543
+ let lastScopedModelsKey = "";
544
+ const updateResolved = () => {
545
+ const currentModel = session.model;
546
+ if (!currentModel)
547
+ throw new Error(`Subagent ${options.path} has no selected model`);
548
+ resolved.set(`${rootId}:${options.path}`, {
549
+ provider: currentModel.provider,
550
+ id: currentModel.id,
551
+ thinking: session.thinkingLevel,
552
+ });
553
+ options.onEvent({
554
+ kind: "settings",
555
+ model: modelIdentity(currentModel),
556
+ thinkingLevel: session.thinkingLevel,
557
+ });
558
+ };
559
+ const assertScopedRequestAuthorized = (currentIdentity, liveScopedModels) => {
560
+ if (!filteringEnabled() || modelPreferences === undefined)
561
+ return;
562
+ const preferredIdentity = selectModelPreference(liveScopedModels, true);
563
+ if (!preferredIdentity)
564
+ return;
565
+ if (!currentIdentity)
566
+ throw new Error(`Subagent ${options.path} has no selected model`);
567
+ if (currentIdentity !== preferredIdentity) {
568
+ throw new Error(`Agent type ${JSON.stringify(options.type.name)} scope changed for subagent ${JSON.stringify(options.path)}: current model is ${currentIdentity} but preferred is ${preferredIdentity}; resume agent to use ${preferredIdentity}.`);
569
+ }
570
+ };
571
+ const assertCurrentModelAuthorized = () => {
572
+ const currentModel = session.model;
573
+ assertScopedRequestAuthorized(currentModel ? modelIdentity(currentModel) : undefined, normalizeScopedModels(getRootContext().scopedModels));
574
+ };
575
+ const enforceScopedModelPolicy = async () => {
576
+ const liveScopedModels = normalizeScopedModels(getRootContext().scopedModels);
577
+ const key = scopedModelsKey(liveScopedModels);
578
+ if (key !== lastScopedModelsKey) {
579
+ session.setScopedModels([...liveScopedModels]);
580
+ lastScopedModelsKey = key;
581
+ }
582
+ if (!filteringEnabled() || modelPreferences === undefined) {
583
+ updateResolved();
584
+ return;
585
+ }
586
+ const preferredIdentity = selectModelPreference(liveScopedModels, true);
587
+ if (!preferredIdentity) {
588
+ updateResolved();
589
+ return;
590
+ }
591
+ const currentModel = session.model;
592
+ if (!currentModel || modelIdentity(currentModel) !== preferredIdentity) {
593
+ const { provider: preferredProvider, id: preferredId } = parseModelIdentity(preferredIdentity);
594
+ await session.setModel(await resolveRuntimeModel(preferredProvider, preferredId, liveScopedModels));
595
+ }
596
+ updateResolved();
597
+ };
598
+ try {
599
+ // Factories have already run: abort/load failures must use the same awaited
600
+ // shutdown lifecycle as failures during extension binding, without emitting
601
+ // session_start or starting a model turn.
602
+ options.signal.throwIfAborted();
603
+ if (subagentExtensions && loadedExtensions.errors.length) {
604
+ throw new Error(`Subagent extension loading failed: ${loadedExtensions.errors
605
+ .map(({ path, error }) => `${path}: ${error}`)
606
+ .join("; ")}`);
607
+ }
608
+ await enforceScopedModelPolicy();
609
+ options.signal.throwIfAborted();
610
+ await session.bindExtensions({ mode: "print" });
611
+ session.setActiveToolsByName(activeToolNames);
612
+ options.signal.throwIfAborted();
613
+ }
614
+ catch (error) {
615
+ await disposeSession();
616
+ throw error;
617
+ }
618
+ diagnosticsInitialized = true;
619
+ const streamFunction = session.agent.streamFunction;
620
+ session.agent.streamFunction = async (requestModel, context, streamOptions) => {
621
+ assertScopedRequestAuthorized(modelIdentity(requestModel), normalizeScopedModels(getRootContext().scopedModels));
622
+ return streamFunction(requestModel, context, streamOptions);
623
+ };
624
+ const mailbox = new DurableMailbox(sessionManager);
625
+ const emitCheckpoint = () => options.onEvent({
626
+ kind: "checkpoint",
627
+ text: "",
628
+ sessionFile: session.sessionFile,
629
+ sessionLeafId: sessionManager.getLeafId(),
630
+ });
631
+ const restoreAppends = mailbox.wrapAppends(emitCheckpoint);
632
+ const ensurePersistedSession = () => {
633
+ if (session.sessionFile && existsSync(session.sessionFile))
634
+ return;
635
+ sessionManager.appendMessage(buildBootstrapMessage());
636
+ emit("activity", BOOTSTRAP_MESSAGE);
637
+ };
638
+ const queueAccepted = async (kind, content) => {
639
+ assertCurrentModelAuthorized();
640
+ ensurePersistedSession();
641
+ const accepted = mailbox.accept(kind, content);
642
+ emitCheckpoint();
643
+ if (kind === "followUp")
644
+ session.agent.followUp(buildQueuedUserMessage(accepted));
645
+ else
646
+ session.agent.steer(buildQueuedUserMessage(accepted));
647
+ mailbox.markEnqueued(accepted.id);
648
+ };
649
+ const resumePending = async () => {
650
+ for (const accepted of mailbox.replayablePending()) {
651
+ if (accepted.kind === "update") {
652
+ await session.sendCustomMessage({
653
+ customType: "subagent-update",
654
+ content: accepted.content,
655
+ display: true,
656
+ details: buildUpdateDetails(accepted),
657
+ }, { triggerTurn: false });
658
+ mailbox.markEnqueued(accepted.id);
659
+ continue;
660
+ }
661
+ if (accepted.kind === "followUp")
662
+ session.agent.followUp(buildQueuedUserMessage(accepted));
663
+ else
664
+ session.agent.steer(buildQueuedUserMessage(accepted));
665
+ mailbox.markEnqueued(accepted.id);
666
+ }
667
+ };
668
+ const clearPromptQueues = () => {
669
+ session.clearQueue();
670
+ mailbox.clearQueuedInputs();
671
+ };
672
+ // In 0.99.2 a boundary's continue:false only declines EXTRA continuation;
673
+ // the public core hook is needed to stop automatic tool/steering continuation.
674
+ parkQueue = clearPromptQueues;
675
+ const finishTurn = session.agent.finishTurn;
676
+ session.agent.finishTurn = async (turn, signal) => {
677
+ const decision = await finishTurn?.(turn, signal);
678
+ if (options.shouldPause()) {
679
+ clearPromptQueues();
680
+ return { action: "end" };
681
+ }
682
+ return decision || undefined;
683
+ };
684
+ updateResolved();
685
+ let disposed = false;
686
+ let running = false;
687
+ let aborted = false;
688
+ // Compaction can replace session.messages during a prompt, invalidating any saved index.
689
+ const promptResult = {};
690
+ const getLastAssistant = () => promptResult.lastAssistant;
691
+ // Subscribe after inherited/restored history is loaded; only new assistant events are counted.
692
+ let settledInput = 0;
693
+ let settledOutput = 0;
694
+ let settledCost;
695
+ const countedUsage = new WeakSet();
696
+ let finalOutput = "";
697
+ let abortPromise;
698
+ const emit = (kind, text, detail) => options.onEvent({ kind, text: text.slice(0, 1000), ...(detail ? { detail } : {}) });
699
+ const assistantUsage = (message) => {
700
+ const usage = message.usage;
701
+ const input = usage.input + usage.cacheRead + usage.cacheWrite;
702
+ const output = usage.output;
703
+ if (!Number.isFinite(input) || !Number.isFinite(output))
704
+ return;
705
+ const total = usage.cost?.total;
706
+ const costUsd = Number.isFinite(total) && total >= 0 ? total : undefined;
707
+ return {
708
+ input,
709
+ output,
710
+ costUsd,
711
+ reported: input + output + usage.totalTokens > 0 || (costUsd ?? 0) > 0,
712
+ };
713
+ };
714
+ const ownership = sessionManager
715
+ .getBranch()
716
+ .find((entry) => entry.type === "custom" && entry.customType === THREAD_OWNERSHIP_TYPE);
717
+ const inheritedMetadata = ownership?.type === "custom"
718
+ ? ownership.data?.inheritedCount
719
+ : undefined;
720
+ const inheritedCount = typeof inheritedMetadata === "number" &&
721
+ Number.isInteger(inheritedMetadata) &&
722
+ inheritedMetadata >= 0
723
+ ? inheritedMetadata
724
+ : options.inherited.length;
725
+ const transcript = new TranscriptChannel(() => session.messages,
726
+ // A restored compaction has replaced the original inherited prefix.
727
+ session.messages.some((message) => message.role === "compactionSummary") ? 0 : inheritedCount);
728
+ const unsubscribe = session.subscribe((event) => {
729
+ transcript.accept(event);
730
+ if (running && event.type === "message_end" && event.message.role === "assistant")
731
+ promptResult.lastAssistant = event.message;
732
+ if (event.type === "tool_execution_start")
733
+ emit("activity", `Tool: ${event.toolName}`, toolArgumentSnippet(event.args));
734
+ if (event.type === "tool_execution_end")
735
+ emit(event.isError ? "error" : "activity", `Tool ${event.toolName}: ${event.isError ? "failed" : "finished"}`);
736
+ if ((event.type === "message_update" || event.type === "message_end") &&
737
+ event.message.role === "assistant" &&
738
+ !countedUsage.has(event.message)) {
739
+ const usage = assistantUsage(event.message);
740
+ if (event.type === "message_update") {
741
+ if (usage?.reported)
742
+ options.onEvent({
743
+ kind: "usage",
744
+ inputTokens: settledInput + usage.input,
745
+ outputTokens: settledOutput + usage.output,
746
+ costUsd: usage.costUsd === undefined ? settledCost : (settledCost ?? 0) + usage.costUsd,
747
+ partial: true,
748
+ });
749
+ }
750
+ else {
751
+ countedUsage.add(event.message);
752
+ if (usage) {
753
+ settledInput += usage.input;
754
+ settledOutput += usage.output;
755
+ if (usage.costUsd !== undefined)
756
+ settledCost = (settledCost ?? 0) + usage.costUsd;
757
+ }
758
+ options.onEvent({
759
+ kind: "usage",
760
+ inputTokens: settledInput,
761
+ outputTokens: settledOutput,
762
+ costUsd: settledCost,
763
+ });
764
+ const text = event.message.content
765
+ .filter((block) => block.type === "text")
766
+ .map((block) => block.text)
767
+ .join("");
768
+ if (text)
769
+ emit("activity", text);
770
+ }
771
+ }
772
+ });
773
+ const assertOpen = () => {
774
+ if (disposed)
775
+ throw new Error("Subagent driver is disposed");
776
+ };
777
+ return {
778
+ get sessionFile() {
779
+ const file = session.sessionFile;
780
+ return file && existsSync(file) ? file : undefined;
781
+ },
782
+ get sessionLeafId() {
783
+ return sessionManager.getLeafId();
784
+ },
785
+ async prompt(message) {
786
+ assertOpen();
787
+ if (running)
788
+ throw new Error("Subagent is already running; use steer instead");
789
+ running = true;
790
+ aborted = false;
791
+ promptResult.lastAssistant = undefined;
792
+ finalOutput = "";
793
+ try {
794
+ await enforceScopedModelPolicy();
795
+ await resumePending();
796
+ await session.prompt(message, { expandPromptTemplates: false });
797
+ await session.waitForIdle();
798
+ const last = getLastAssistant();
799
+ if (aborted || last?.stopReason === "aborted")
800
+ throw new Error("Subagent run aborted");
801
+ if (last?.stopReason === "error")
802
+ throw new Error(last.errorMessage || "Subagent model failed");
803
+ if (last && !options.shouldPause())
804
+ finalOutput = last.content
805
+ .filter((block) => block.type === "text")
806
+ .map((block) => block.text)
807
+ .join("");
808
+ }
809
+ catch (error) {
810
+ emit("error", error instanceof Error ? error.message : String(error));
811
+ throw error;
812
+ }
813
+ finally {
814
+ updateResolved();
815
+ running = false;
816
+ }
817
+ },
818
+ async steer(message) {
819
+ assertOpen();
820
+ await queueAccepted("steer", message);
821
+ },
822
+ snapshot() {
823
+ return structuredClone(session.messages);
824
+ },
825
+ contextEntries() {
826
+ return inheritedContextEntries(sessionManager.getBranch());
827
+ },
828
+ observeTranscript(listener) {
829
+ assertOpen();
830
+ return transcript.observe(listener);
831
+ },
832
+ output() {
833
+ return finalOutput;
834
+ },
835
+ async abort() {
836
+ if (disposed)
837
+ return;
838
+ if (running)
839
+ aborted = true;
840
+ clearPromptQueues();
841
+ if (!abortPromise)
842
+ abortPromise = session.abort().finally(() => {
843
+ abortPromise = undefined;
844
+ });
845
+ await abortPromise;
846
+ },
847
+ dispose() {
848
+ if (disposed)
849
+ return shutdownPromise;
850
+ disposed = true;
851
+ aborted = true;
852
+ restoreAppends();
853
+ transcript.dispose();
854
+ unsubscribe();
855
+ return disposeSession();
856
+ },
857
+ async sendUpdate(content) {
858
+ assertOpen();
859
+ try {
860
+ ensurePersistedSession();
861
+ const accepted = mailbox.accept("update", content);
862
+ emitCheckpoint();
863
+ // SDK session method is sendCustomMessage (ExtensionAPI calls it sendMessage).
864
+ await session.sendCustomMessage({
865
+ customType: "subagent-update",
866
+ content,
867
+ display: true,
868
+ details: buildUpdateDetails(accepted),
869
+ }, { triggerTurn: false });
870
+ mailbox.markEnqueued(accepted.id);
871
+ transcript.reconcile();
872
+ }
873
+ catch (error) {
874
+ emit("error", error instanceof Error ? error.message : String(error));
875
+ throw error;
876
+ }
877
+ },
878
+ };
879
+ };
880
+ return Object.assign(createDriver, { resolveAgentSettings });
881
+ }
882
+ //# sourceMappingURL=runtime.js.map