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