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