pi-subagent-manager 0.1.1 → 0.3.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 +139 -17
- package/agents/architect.md +42 -0
- package/agents/coder.md +41 -0
- package/agents/reviewer.md +32 -0
- package/agents/tasker.md +38 -0
- package/agents/writer.md +34 -0
- package/docs/default-agents.md +105 -0
- package/docs/research-claude.md +258 -0
- package/docs/research-codex.md +143 -0
- package/docs/research-model-roles-coding.md +99 -0
- package/docs/research-model-roles-writing.md +78 -0
- package/package.json +8 -3
- package/src/agent-import.ts +245 -0
- package/src/config.ts +171 -42
- package/src/dialog.ts +631 -0
- package/src/import-discovery.ts +643 -0
- package/src/import-instructions.ts +156 -0
- package/src/import-picker.ts +231 -0
- package/src/index.ts +123 -29
- package/src/manager.ts +94 -5
- package/src/model-picker.ts +611 -0
- package/src/models.ts +60 -0
- package/src/runtime.ts +326 -64
- package/src/settings-ui.ts +173 -0
- package/src/settings.ts +269 -0
- package/src/status-ui.ts +288 -0
- package/src/thread-tree.ts +134 -0
- package/src/tools.ts +23 -11
- package/src/types.ts +31 -0
- package/src/ui.ts +924 -85
- package/agents/researcher.md +0 -14
- package/agents/worker.md +0 -6
package/src/runtime.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
2
3
|
import { existsSync } from "node:fs";
|
|
3
|
-
import { mkdir, realpath } from "node:fs/promises";
|
|
4
|
+
import { mkdir, readFile, realpath } from "node:fs/promises";
|
|
4
5
|
import {
|
|
5
6
|
createAgentSession,
|
|
6
7
|
DefaultResourceLoader,
|
|
@@ -18,12 +19,122 @@ import {
|
|
|
18
19
|
DurableMailbox,
|
|
19
20
|
} from "./mailbox.ts";
|
|
20
21
|
import { selectTools } from "./config.ts";
|
|
21
|
-
import {
|
|
22
|
+
import { modelIdentity, getModelPreferences, selectPreferredModel } from "./models.ts";
|
|
23
|
+
import {
|
|
24
|
+
THINKING_LEVELS,
|
|
25
|
+
type DriverFactory,
|
|
26
|
+
type DriverOptions,
|
|
27
|
+
type ThinkingLevel,
|
|
28
|
+
} from "./types.ts";
|
|
22
29
|
|
|
23
30
|
const BUILTINS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
|
|
31
|
+
/** Persisted before transcript messages so older-leaf restores still carry ownership. */
|
|
32
|
+
const THREAD_OWNERSHIP_TYPE = "pi-subagent:thread:v1";
|
|
33
|
+
const SESSION_FILE_ERROR =
|
|
34
|
+
"Subagent sessionFile must be a JSONL file inside this root's session directory";
|
|
35
|
+
type ScopedModel = ExtensionContext["scopedModels"][number];
|
|
36
|
+
interface ThreadOwnership {
|
|
37
|
+
rootId: string;
|
|
38
|
+
threadPath: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseModelIdentity(identity: string): { provider: string; id: string } {
|
|
42
|
+
const slash = identity.indexOf("/");
|
|
43
|
+
return { provider: identity.slice(0, slash), id: identity.slice(slash + 1) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function scopedModelsKey(scopedModels: readonly ScopedModel[]): string {
|
|
47
|
+
return scopedModels
|
|
48
|
+
.map(({ model, thinkingLevel }) => `${modelIdentity(model)}\0${thinkingLevel ?? ""}`)
|
|
49
|
+
.join("\n");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isJsonlWithin(directory: string, file: string): boolean {
|
|
53
|
+
const relative = path.relative(directory, file);
|
|
54
|
+
return (
|
|
55
|
+
!!relative &&
|
|
56
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
57
|
+
relative !== ".." &&
|
|
58
|
+
!path.isAbsolute(relative) &&
|
|
59
|
+
file.endsWith(".jsonl")
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function tryRealpath(target: string): Promise<string | undefined> {
|
|
64
|
+
try {
|
|
65
|
+
return await realpath(target);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
68
|
+
if (code === "ENOENT" || code === "ENOTDIR") return undefined;
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function ownershipFromTranscript(content: string): ThreadOwnership | undefined {
|
|
74
|
+
for (const line of content.split("\n")) {
|
|
75
|
+
if (!line.trim()) continue;
|
|
76
|
+
let parsed: unknown;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(line);
|
|
79
|
+
} catch {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (!parsed || typeof parsed !== "object") continue;
|
|
83
|
+
const entry = parsed as { type?: unknown; customType?: unknown; data?: unknown };
|
|
84
|
+
if (entry.type !== "custom" || entry.customType !== THREAD_OWNERSHIP_TYPE) continue;
|
|
85
|
+
const data = entry.data;
|
|
86
|
+
if (!data || typeof data !== "object") return undefined;
|
|
87
|
+
const { rootId, threadPath } = data as { rootId?: unknown; threadPath?: unknown };
|
|
88
|
+
if (typeof rootId !== "string" || typeof threadPath !== "string") return undefined;
|
|
89
|
+
return { rootId, threadPath };
|
|
90
|
+
}
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Orchestrator file for /root and independent roots; nested parents supply their own file. */
|
|
95
|
+
function resolveParentSession(
|
|
96
|
+
options: DriverOptions,
|
|
97
|
+
rootSessionFile: string | undefined,
|
|
98
|
+
): string | undefined {
|
|
99
|
+
if (options.parentSessionFile) return options.parentSessionFile;
|
|
100
|
+
if (!options.parentPath || options.parentPath === "/root") return rootSessionFile;
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function assertAcceptedSessionFile(
|
|
105
|
+
sessionFile: string,
|
|
106
|
+
sessionDir: string,
|
|
107
|
+
legacyDir: string,
|
|
108
|
+
rootId: string,
|
|
109
|
+
threadPath: string,
|
|
110
|
+
signal: AbortSignal,
|
|
111
|
+
): Promise<void> {
|
|
112
|
+
signal.throwIfAborted();
|
|
113
|
+
const sharedDir = await realpath(sessionDir);
|
|
114
|
+
signal.throwIfAborted();
|
|
115
|
+
const file = await tryRealpath(sessionFile);
|
|
116
|
+
signal.throwIfAborted();
|
|
117
|
+
const legacyDirReal = await tryRealpath(legacyDir);
|
|
118
|
+
signal.throwIfAborted();
|
|
119
|
+
// Legacy root-scoped transcripts stay valid, including files nested under that directory.
|
|
120
|
+
if (file && legacyDirReal && isJsonlWithin(legacyDirReal, file)) return;
|
|
121
|
+
if (!file || path.dirname(file) !== sharedDir || !file.endsWith(".jsonl")) {
|
|
122
|
+
throw new Error(SESSION_FILE_ERROR);
|
|
123
|
+
}
|
|
124
|
+
const ownership = ownershipFromTranscript(await readFile(file, { encoding: "utf8", signal }));
|
|
125
|
+
signal.throwIfAborted();
|
|
126
|
+
if (!ownership || ownership.rootId !== rootId || ownership.threadPath !== threadPath) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
"Subagent sessionFile ownership metadata does not match this rootId and thread path",
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
24
132
|
|
|
25
133
|
/** Isolated SDK sessions; neither external extensions nor the CLI's MCP factories are loaded. */
|
|
26
|
-
export function createDriverFactory(
|
|
134
|
+
export function createDriverFactory(
|
|
135
|
+
getRootContext: () => ExtensionContext,
|
|
136
|
+
getScopedModelFiltering: () => boolean = () => true,
|
|
137
|
+
): DriverFactory {
|
|
27
138
|
// Keep resolved settings even after disposal: descendants inherit settings, not the caller's history.
|
|
28
139
|
const resolved = new Map<string, { provider: string; id: string; thinking: ThinkingLevel }>();
|
|
29
140
|
return async (options) => {
|
|
@@ -33,36 +144,40 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
33
144
|
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(rootId))
|
|
34
145
|
throw new Error("Unsafe root session id for subagent storage");
|
|
35
146
|
const agentDir = getAgentDir();
|
|
36
|
-
const sessionDir =
|
|
147
|
+
const sessionDir = ctx.sessionManager.getSessionDir();
|
|
148
|
+
const legacyDir = path.join(agentDir, "subagents", rootId);
|
|
37
149
|
options.signal.throwIfAborted();
|
|
38
150
|
await mkdir(sessionDir, { recursive: true });
|
|
39
151
|
options.signal.throwIfAborted();
|
|
40
152
|
let sessionManager: SessionManager;
|
|
41
153
|
if (options.sessionFile) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
relative === ".." ||
|
|
52
|
-
path.isAbsolute(relative) ||
|
|
53
|
-
!file.endsWith(".jsonl")
|
|
54
|
-
) {
|
|
55
|
-
throw new Error(
|
|
56
|
-
"Subagent sessionFile must be a JSONL file inside this root's subagent sessions directory",
|
|
57
|
-
);
|
|
58
|
-
}
|
|
154
|
+
await assertAcceptedSessionFile(
|
|
155
|
+
options.sessionFile,
|
|
156
|
+
sessionDir,
|
|
157
|
+
legacyDir,
|
|
158
|
+
rootId,
|
|
159
|
+
options.path,
|
|
160
|
+
options.signal,
|
|
161
|
+
);
|
|
162
|
+
// Open the caller path, not its realpath, so retained sessionFile identity is stable.
|
|
59
163
|
sessionManager = SessionManager.open(path.resolve(options.sessionFile), sessionDir, ctx.cwd);
|
|
60
164
|
if (options.sessionLeafId !== undefined) {
|
|
61
165
|
if (options.sessionLeafId === null) sessionManager.resetLeaf();
|
|
62
166
|
else sessionManager.branch(options.sessionLeafId);
|
|
63
167
|
}
|
|
64
168
|
} else {
|
|
65
|
-
|
|
169
|
+
const parentSession = resolveParentSession(options, ctx.sessionManager.getSessionFile());
|
|
170
|
+
sessionManager = SessionManager.create(
|
|
171
|
+
ctx.cwd,
|
|
172
|
+
sessionDir,
|
|
173
|
+
parentSession ? { parentSession } : undefined,
|
|
174
|
+
);
|
|
175
|
+
// Before transcript messages so an older restored leaf still has name and ownership as ancestors.
|
|
176
|
+
sessionManager.appendSessionInfo(`${options.type.name} ${options.path}`);
|
|
177
|
+
sessionManager.appendCustomEntry(THREAD_OWNERSHIP_TYPE, {
|
|
178
|
+
rootId,
|
|
179
|
+
threadPath: options.path,
|
|
180
|
+
});
|
|
66
181
|
for (const message of options.inherited) {
|
|
67
182
|
// Summary messages are projections, not appendable SDK session entries.
|
|
68
183
|
if (message.role === "compactionSummary" || message.role === "branchSummary") {
|
|
@@ -88,6 +203,43 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
88
203
|
}
|
|
89
204
|
}
|
|
90
205
|
}
|
|
206
|
+
const parent = options.parentPath ? resolved.get(`${rootId}:${options.parentPath}`) : undefined;
|
|
207
|
+
const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
|
|
208
|
+
const modelPreferences = getModelPreferences(options.type);
|
|
209
|
+
const normalizeScopedModels = (
|
|
210
|
+
scopedModels: ExtensionContext["scopedModels"] | null | undefined,
|
|
211
|
+
): readonly ScopedModel[] => scopedModels ?? [];
|
|
212
|
+
const filteringEnabled = getScopedModelFiltering;
|
|
213
|
+
const selectModelPreference = (
|
|
214
|
+
candidates: readonly { model: { provider: string; id: string } }[],
|
|
215
|
+
filtering = filteringEnabled(),
|
|
216
|
+
) => {
|
|
217
|
+
try {
|
|
218
|
+
return selectPreferredModel(options.type, candidates, filtering);
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (
|
|
221
|
+
filtering &&
|
|
222
|
+
candidates.length === 0 &&
|
|
223
|
+
error instanceof Error &&
|
|
224
|
+
!error.message.includes("[]")
|
|
225
|
+
)
|
|
226
|
+
throw new Error(`${error.message} Current /scoped-models scope: [].`);
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const availableModelCandidates = () =>
|
|
231
|
+
ctx.modelRegistry.getAvailable().map((model) => ({ model }));
|
|
232
|
+
const initialScopedModels = normalizeScopedModels(ctx.scopedModels);
|
|
233
|
+
let provider = parent?.provider ?? ctx.model?.provider;
|
|
234
|
+
let id = parent?.id ?? ctx.model?.id;
|
|
235
|
+
if (modelPreferences !== undefined) {
|
|
236
|
+
const filtering = filteringEnabled();
|
|
237
|
+
const candidates = filtering ? initialScopedModels : availableModelCandidates();
|
|
238
|
+
({ provider, id } = parseModelIdentity(selectModelPreference(candidates, filtering)!));
|
|
239
|
+
} else if (restored?.model) {
|
|
240
|
+
provider = restored.model.provider;
|
|
241
|
+
id = restored.model.modelId;
|
|
242
|
+
}
|
|
91
243
|
options.signal.throwIfAborted();
|
|
92
244
|
const runtime = await ModelRuntime.create({
|
|
93
245
|
authPath: path.join(agentDir, "auth.json"),
|
|
@@ -103,40 +255,41 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
103
255
|
if (native) runtime.registerNativeProvider(native);
|
|
104
256
|
if (config) runtime.registerProvider(providerId, config);
|
|
105
257
|
}
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const slash = options.type.model.indexOf("/");
|
|
111
|
-
if (slash < 1 || slash === options.type.model.length - 1)
|
|
112
|
-
throw new Error("Agent model must be provider/model-id");
|
|
113
|
-
provider = options.type.model.slice(0, slash);
|
|
114
|
-
id = options.type.model.slice(slash + 1);
|
|
115
|
-
}
|
|
116
|
-
const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
|
|
117
|
-
if (restored?.model) {
|
|
118
|
-
provider = restored.model.provider;
|
|
119
|
-
id = restored.model.modelId;
|
|
120
|
-
}
|
|
121
|
-
options.signal.throwIfAborted();
|
|
122
|
-
if (provider && ctx.modelRegistry.getProviderAuthStatus(provider).source === "runtime") {
|
|
123
|
-
const apiKey = await ctx.modelRegistry.getApiKeyForProvider(provider);
|
|
258
|
+
const mirrorRuntimeAuth = async (providerId: string) => {
|
|
259
|
+
options.signal.throwIfAborted();
|
|
260
|
+
if (ctx.modelRegistry.getProviderAuthStatus(providerId).source !== "runtime") return;
|
|
261
|
+
const apiKey = await ctx.modelRegistry.getApiKeyForProvider(providerId);
|
|
124
262
|
options.signal.throwIfAborted();
|
|
125
263
|
if (apiKey !== undefined)
|
|
126
|
-
await runtime.setRuntimeApiKey(
|
|
264
|
+
await runtime.setRuntimeApiKey(providerId, apiKey, { signal: options.signal });
|
|
127
265
|
options.signal.throwIfAborted();
|
|
128
|
-
}
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
266
|
+
};
|
|
267
|
+
const resolveRuntimeModel = async (
|
|
268
|
+
providerId: string | undefined,
|
|
269
|
+
modelId: string | undefined,
|
|
270
|
+
scopedModels: readonly ScopedModel[],
|
|
271
|
+
) => {
|
|
272
|
+
if (!providerId || !modelId)
|
|
273
|
+
throw new Error(
|
|
274
|
+
`Subagent model ${providerId ?? "(unset)"}/${modelId ?? "(unset)"} is unavailable; select a physical model in the root or agent type`,
|
|
275
|
+
);
|
|
276
|
+
await mirrorRuntimeAuth(providerId);
|
|
277
|
+
const sourceModel =
|
|
278
|
+
scopedModels.find(({ model }) => model.provider === providerId && model.id === modelId)
|
|
279
|
+
?.model ?? ctx.modelRegistry.find(providerId, modelId);
|
|
280
|
+
if (sourceModel?.api === "pi-virtual") {
|
|
281
|
+
throw new Error(
|
|
282
|
+
`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
|
+
}
|
|
285
|
+
const runtimeModel = runtime.getModel(providerId, modelId);
|
|
286
|
+
if (!runtimeModel)
|
|
287
|
+
throw new Error(
|
|
288
|
+
`Subagent model ${providerId}/${modelId} is unavailable; select a physical model in the root or agent type`,
|
|
289
|
+
);
|
|
290
|
+
return runtimeModel;
|
|
291
|
+
};
|
|
292
|
+
const model = await resolveRuntimeModel(provider, id, initialScopedModels);
|
|
140
293
|
const savedThinking =
|
|
141
294
|
restored && THINKING_LEVELS.includes(restored.thinkingLevel as ThinkingLevel)
|
|
142
295
|
? (restored.thinkingLevel as ThinkingLevel)
|
|
@@ -171,6 +324,12 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
171
324
|
? `Your lexical parent is ${options.parentPath}; inherited conversation comes only from that parent.`
|
|
172
325
|
: "You are an independent root thread with no inherited history.",
|
|
173
326
|
"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.",
|
|
327
|
+
...(allowed.has("agent_spawn") && allowed.has("agent_wait")
|
|
328
|
+
? [
|
|
329
|
+
"Name child paths with concise task-based kebab-case slugs (e.g. /root/controller-security-research), independent of type.",
|
|
330
|
+
"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.",
|
|
331
|
+
]
|
|
332
|
+
: []),
|
|
174
333
|
].join("\n\n"),
|
|
175
334
|
appendSystemPromptOverride: () => [],
|
|
176
335
|
extensionFactories: [
|
|
@@ -194,13 +353,72 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
194
353
|
modelRuntime: runtime,
|
|
195
354
|
model,
|
|
196
355
|
thinkingLevel,
|
|
356
|
+
scopedModels: [...initialScopedModels],
|
|
197
357
|
settingsManager,
|
|
198
358
|
resourceLoader: loader,
|
|
199
359
|
sessionManager,
|
|
200
360
|
tools: toolNames,
|
|
201
361
|
customTools: options.tools.filter((tool) => allowed.has(tool.name)),
|
|
202
362
|
});
|
|
363
|
+
let lastScopedModelsKey = "";
|
|
364
|
+
const updateResolved = () => {
|
|
365
|
+
const currentModel = session.model;
|
|
366
|
+
if (!currentModel) throw new Error(`Subagent ${options.path} has no selected model`);
|
|
367
|
+
resolved.set(`${rootId}:${options.path}`, {
|
|
368
|
+
provider: currentModel.provider,
|
|
369
|
+
id: currentModel.id,
|
|
370
|
+
thinking: session.thinkingLevel,
|
|
371
|
+
});
|
|
372
|
+
};
|
|
373
|
+
const assertScopedRequestAuthorized = (
|
|
374
|
+
currentIdentity: string | undefined,
|
|
375
|
+
liveScopedModels: readonly ScopedModel[],
|
|
376
|
+
) => {
|
|
377
|
+
if (!filteringEnabled() || modelPreferences === undefined) return;
|
|
378
|
+
const preferredIdentity = selectModelPreference(liveScopedModels, true);
|
|
379
|
+
if (!preferredIdentity) return;
|
|
380
|
+
if (!currentIdentity) throw new Error(`Subagent ${options.path} has no selected model`);
|
|
381
|
+
if (currentIdentity !== preferredIdentity) {
|
|
382
|
+
throw new Error(
|
|
383
|
+
`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}.`,
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
const assertCurrentModelAuthorized = () => {
|
|
388
|
+
const currentModel = session.model;
|
|
389
|
+
assertScopedRequestAuthorized(
|
|
390
|
+
currentModel ? modelIdentity(currentModel) : undefined,
|
|
391
|
+
normalizeScopedModels(getRootContext().scopedModels),
|
|
392
|
+
);
|
|
393
|
+
};
|
|
394
|
+
const enforceScopedModelPolicy = async () => {
|
|
395
|
+
const liveScopedModels = normalizeScopedModels(getRootContext().scopedModels);
|
|
396
|
+
const key = scopedModelsKey(liveScopedModels);
|
|
397
|
+
if (key !== lastScopedModelsKey) {
|
|
398
|
+
session.setScopedModels([...liveScopedModels]);
|
|
399
|
+
lastScopedModelsKey = key;
|
|
400
|
+
}
|
|
401
|
+
if (!filteringEnabled() || modelPreferences === undefined) {
|
|
402
|
+
updateResolved();
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const preferredIdentity = selectModelPreference(liveScopedModels, true);
|
|
406
|
+
if (!preferredIdentity) {
|
|
407
|
+
updateResolved();
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const currentModel = session.model;
|
|
411
|
+
if (!currentModel || modelIdentity(currentModel) !== preferredIdentity) {
|
|
412
|
+
const { provider: preferredProvider, id: preferredId } =
|
|
413
|
+
parseModelIdentity(preferredIdentity);
|
|
414
|
+
await session.setModel(
|
|
415
|
+
await resolveRuntimeModel(preferredProvider, preferredId, liveScopedModels),
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
updateResolved();
|
|
419
|
+
};
|
|
203
420
|
try {
|
|
421
|
+
await enforceScopedModelPolicy();
|
|
204
422
|
options.signal.throwIfAborted();
|
|
205
423
|
await session.bindExtensions({ mode: "print" });
|
|
206
424
|
options.signal.throwIfAborted();
|
|
@@ -208,6 +426,14 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
208
426
|
session.dispose();
|
|
209
427
|
throw error;
|
|
210
428
|
}
|
|
429
|
+
const streamFunction = session.agent.streamFunction;
|
|
430
|
+
session.agent.streamFunction = async (requestModel, context, streamOptions) => {
|
|
431
|
+
assertScopedRequestAuthorized(
|
|
432
|
+
modelIdentity(requestModel),
|
|
433
|
+
normalizeScopedModels(getRootContext().scopedModels),
|
|
434
|
+
);
|
|
435
|
+
return streamFunction(requestModel, context, streamOptions);
|
|
436
|
+
};
|
|
211
437
|
const mailbox = new DurableMailbox(sessionManager);
|
|
212
438
|
const emitCheckpoint = () =>
|
|
213
439
|
options.onEvent({
|
|
@@ -223,6 +449,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
223
449
|
emit("activity", BOOTSTRAP_MESSAGE);
|
|
224
450
|
};
|
|
225
451
|
const queueAccepted = async (kind: "steer" | "followUp", content: string) => {
|
|
452
|
+
assertCurrentModelAuthorized();
|
|
226
453
|
ensurePersistedSession();
|
|
227
454
|
const accepted = mailbox.accept(kind, content);
|
|
228
455
|
emitCheckpoint();
|
|
@@ -266,19 +493,27 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
266
493
|
}
|
|
267
494
|
return decision || undefined;
|
|
268
495
|
};
|
|
269
|
-
|
|
270
|
-
provider: model.provider,
|
|
271
|
-
id: model.id,
|
|
272
|
-
thinking: session.thinkingLevel,
|
|
273
|
-
});
|
|
496
|
+
updateResolved();
|
|
274
497
|
let disposed = false;
|
|
275
498
|
let running = false;
|
|
276
499
|
let aborted = false;
|
|
277
500
|
let baseline = session.messages.length;
|
|
501
|
+
// Subscribe after inherited/restored history is loaded; only new assistant events are counted.
|
|
502
|
+
let settledInput = 0;
|
|
503
|
+
let settledOutput = 0;
|
|
504
|
+
const countedUsage = new WeakSet<object>();
|
|
278
505
|
let finalOutput = "";
|
|
279
506
|
let abortPromise: Promise<void> | undefined;
|
|
280
507
|
const emit = (kind: "activity" | "error", text: string) =>
|
|
281
508
|
options.onEvent({ kind, text: text.slice(0, 1000) });
|
|
509
|
+
const assistantUsage = (message: AssistantMessage) => {
|
|
510
|
+
const usage = message.usage;
|
|
511
|
+
const input = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
512
|
+
const output = usage.output;
|
|
513
|
+
if (!Number.isFinite(input) || !Number.isFinite(output)) return;
|
|
514
|
+
return { input, output, reported: input + output + usage.totalTokens > 0 };
|
|
515
|
+
};
|
|
516
|
+
|
|
282
517
|
const unsubscribe = session.subscribe((event) => {
|
|
283
518
|
if (event.type === "tool_execution_start") emit("activity", `Tool: ${event.toolName}`);
|
|
284
519
|
if (event.type === "tool_execution_end")
|
|
@@ -286,12 +521,37 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
286
521
|
event.isError ? "error" : "activity",
|
|
287
522
|
`Tool ${event.toolName}: ${event.isError ? "failed" : "finished"}`,
|
|
288
523
|
);
|
|
289
|
-
if (
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
524
|
+
if (
|
|
525
|
+
(event.type === "message_update" || event.type === "message_end") &&
|
|
526
|
+
event.message.role === "assistant" &&
|
|
527
|
+
!countedUsage.has(event.message)
|
|
528
|
+
) {
|
|
529
|
+
const usage = assistantUsage(event.message);
|
|
530
|
+
if (event.type === "message_update") {
|
|
531
|
+
if (usage?.reported)
|
|
532
|
+
options.onEvent({
|
|
533
|
+
kind: "usage",
|
|
534
|
+
inputTokens: settledInput + usage.input,
|
|
535
|
+
outputTokens: settledOutput + usage.output,
|
|
536
|
+
partial: true,
|
|
537
|
+
});
|
|
538
|
+
} else {
|
|
539
|
+
countedUsage.add(event.message);
|
|
540
|
+
if (usage) {
|
|
541
|
+
settledInput += usage.input;
|
|
542
|
+
settledOutput += usage.output;
|
|
543
|
+
}
|
|
544
|
+
options.onEvent({
|
|
545
|
+
kind: "usage",
|
|
546
|
+
inputTokens: settledInput,
|
|
547
|
+
outputTokens: settledOutput,
|
|
548
|
+
});
|
|
549
|
+
const text = event.message.content
|
|
550
|
+
.filter((block) => block.type === "text")
|
|
551
|
+
.map((block) => block.text)
|
|
552
|
+
.join("");
|
|
553
|
+
if (text) emit("activity", text);
|
|
554
|
+
}
|
|
295
555
|
}
|
|
296
556
|
});
|
|
297
557
|
const assertOpen = () => {
|
|
@@ -313,6 +573,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
313
573
|
baseline = session.messages.length;
|
|
314
574
|
finalOutput = "";
|
|
315
575
|
try {
|
|
576
|
+
await enforceScopedModelPolicy();
|
|
316
577
|
await resumePending();
|
|
317
578
|
await session.prompt(message, { expandPromptTemplates: false });
|
|
318
579
|
await session.waitForIdle();
|
|
@@ -332,6 +593,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
|
|
|
332
593
|
emit("error", error instanceof Error ? error.message : String(error));
|
|
333
594
|
throw error;
|
|
334
595
|
} finally {
|
|
596
|
+
updateResolved();
|
|
335
597
|
running = false;
|
|
336
598
|
}
|
|
337
599
|
},
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ConfigStore } from "./config.ts";
|
|
3
|
+
import {
|
|
4
|
+
canOpenDialog,
|
|
5
|
+
dialogInput,
|
|
6
|
+
dialogMenu,
|
|
7
|
+
withDialogSession,
|
|
8
|
+
} from "./dialog.ts";
|
|
9
|
+
import {
|
|
10
|
+
DEFAULT_MANAGER_SETTINGS,
|
|
11
|
+
saveManagerSettings,
|
|
12
|
+
type ManagerSettings,
|
|
13
|
+
} from "./settings.ts";
|
|
14
|
+
import { editAgentTypes } from "./ui.ts";
|
|
15
|
+
|
|
16
|
+
const FIELDS = [
|
|
17
|
+
{
|
|
18
|
+
id: "maxLevels",
|
|
19
|
+
label: "Maximum levels",
|
|
20
|
+
help: "Includes the root (L1). Positive integer, at most 32.",
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: "maxConcurrent",
|
|
24
|
+
label: "Concurrent agents",
|
|
25
|
+
help: "Shared active-thread limit, including waiting parents. Positive safe integer.",
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
id: "maxThreads",
|
|
29
|
+
label: "Retained threads",
|
|
30
|
+
help: "Maximum retained agent sessions. Positive safe integer.",
|
|
31
|
+
},
|
|
32
|
+
] as const;
|
|
33
|
+
|
|
34
|
+
const SCOPED_MODEL_FILTERING = {
|
|
35
|
+
id: "scopedModelFiltering",
|
|
36
|
+
label: "Scoped model filtering",
|
|
37
|
+
help: "On matches /scoped-models only. Off allows any available model. Draft only until save.",
|
|
38
|
+
} as const;
|
|
39
|
+
|
|
40
|
+
export async function configureAgents(
|
|
41
|
+
ctx: ExtensionCommandContext,
|
|
42
|
+
options: {
|
|
43
|
+
store: ConfigStore;
|
|
44
|
+
settings: ManagerSettings;
|
|
45
|
+
agentDir: string;
|
|
46
|
+
apply(): void;
|
|
47
|
+
},
|
|
48
|
+
): Promise<void> {
|
|
49
|
+
if (!canOpenDialog(ctx)) return;
|
|
50
|
+
await withDialogSession(ctx, (scoped) =>
|
|
51
|
+
configureAgentsDialog(scoped, options),
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function configureAgentsDialog(
|
|
56
|
+
ctx: ExtensionCommandContext,
|
|
57
|
+
options: {
|
|
58
|
+
store: ConfigStore;
|
|
59
|
+
settings: ManagerSettings;
|
|
60
|
+
agentDir: string;
|
|
61
|
+
apply(): void;
|
|
62
|
+
},
|
|
63
|
+
): Promise<void> {
|
|
64
|
+
let draft = { ...options.settings };
|
|
65
|
+
let scope: "user" | "project" = ctx.isProjectTrusted() ? "project" : "user";
|
|
66
|
+
let selectedId: string | undefined;
|
|
67
|
+
while (true) {
|
|
68
|
+
const dirty = JSON.stringify(draft) !== JSON.stringify(options.settings);
|
|
69
|
+
const action = await dialogMenu(
|
|
70
|
+
ctx,
|
|
71
|
+
`Agents settings${dirty ? " · unsaved" : ""}`,
|
|
72
|
+
[
|
|
73
|
+
...FIELDS.map((field) => ({
|
|
74
|
+
...field,
|
|
75
|
+
value: String(draft[field.id]),
|
|
76
|
+
})),
|
|
77
|
+
{
|
|
78
|
+
id: SCOPED_MODEL_FILTERING.id,
|
|
79
|
+
label: SCOPED_MODEL_FILTERING.label,
|
|
80
|
+
value: draft.scopedModelFiltering ? "on" : "off",
|
|
81
|
+
help: SCOPED_MODEL_FILTERING.help,
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
id: "scope",
|
|
85
|
+
label: "Save scope",
|
|
86
|
+
value: scope === "user" ? "Global" : "Trusted project",
|
|
87
|
+
help: "Project settings override global settings. Changes apply after saving.",
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: "types",
|
|
91
|
+
label: "Agent definitions",
|
|
92
|
+
value: `${options.store.list().length} types`,
|
|
93
|
+
help: "Create or edit agent definitions, model preferences and tool policy.",
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
id: "defaults",
|
|
97
|
+
label: "Restore defaults",
|
|
98
|
+
help: "Reset the draft only; save to apply.",
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: "save",
|
|
102
|
+
label: "Save and apply",
|
|
103
|
+
help: "Apply without interrupting existing agents or discarding retained sessions.",
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
id: "cancel",
|
|
107
|
+
label: "Cancel",
|
|
108
|
+
help: "Close without saving manager settings.",
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
{
|
|
112
|
+
selectedId,
|
|
113
|
+
saveId: "save",
|
|
114
|
+
footer: "↑↓/Tab navigate · Enter edit · Ctrl+S save · Esc cancel",
|
|
115
|
+
},
|
|
116
|
+
);
|
|
117
|
+
if (!action || action === "cancel") return;
|
|
118
|
+
selectedId = action;
|
|
119
|
+
try {
|
|
120
|
+
const field = FIELDS.find((field) => field.id === action);
|
|
121
|
+
if (field) {
|
|
122
|
+
const value = await dialogInput(
|
|
123
|
+
ctx,
|
|
124
|
+
field.label,
|
|
125
|
+
String(draft[field.id]),
|
|
126
|
+
field.help,
|
|
127
|
+
);
|
|
128
|
+
if (value === undefined) continue;
|
|
129
|
+
const number = Number(value.trim());
|
|
130
|
+
if (
|
|
131
|
+
!/^\d+$/.test(value.trim()) ||
|
|
132
|
+
!Number.isSafeInteger(number) ||
|
|
133
|
+
number < 1 ||
|
|
134
|
+
(field.id === "maxLevels" && number > 32)
|
|
135
|
+
)
|
|
136
|
+
throw new Error(field.help);
|
|
137
|
+
draft[field.id] = number;
|
|
138
|
+
} else if (action === "scopedModelFiltering") {
|
|
139
|
+
draft.scopedModelFiltering = !draft.scopedModelFiltering;
|
|
140
|
+
} else if (action === "scope") {
|
|
141
|
+
if (!ctx.isProjectTrusted())
|
|
142
|
+
ctx.ui.notify(
|
|
143
|
+
"Project settings require a trusted project; saving globally.",
|
|
144
|
+
"warning",
|
|
145
|
+
);
|
|
146
|
+
else scope = scope === "user" ? "project" : "user";
|
|
147
|
+
} else if (action === "defaults") draft = { ...DEFAULT_MANAGER_SETTINGS };
|
|
148
|
+
else if (action === "types") {
|
|
149
|
+
await editAgentTypes(ctx, options.store);
|
|
150
|
+
options.store.reload();
|
|
151
|
+
} else if (action === "save") {
|
|
152
|
+
const file = saveManagerSettings({
|
|
153
|
+
cwd: ctx.cwd,
|
|
154
|
+
agentDir: options.agentDir,
|
|
155
|
+
includeProject: ctx.isProjectTrusted(),
|
|
156
|
+
scope,
|
|
157
|
+
settings: draft,
|
|
158
|
+
});
|
|
159
|
+
options.apply();
|
|
160
|
+
ctx.ui.notify(
|
|
161
|
+
`Saved ${file}. Settings reloaded; project overrides take precedence.`,
|
|
162
|
+
"info",
|
|
163
|
+
);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
} catch (error) {
|
|
167
|
+
ctx.ui.notify(
|
|
168
|
+
error instanceof Error ? error.message : String(error),
|
|
169
|
+
"error",
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|