pi-subagents 0.31.0 → 0.31.1

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.
@@ -0,0 +1,637 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import { BUILTIN_AGENT_NAMES } from "../agents/agents.ts";
6
+ import { findModelInfo, getSupportedThinkingLevels, splitKnownThinkingSuffix, toModelInfo } from "../shared/model-info.ts";
7
+ import { getAgentDir } from "../shared/utils.ts";
8
+
9
+ export const DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS = 7;
10
+
11
+ type BuiltinAgentName = typeof BUILTIN_AGENT_NAMES[number];
12
+ export type ProfileKind = "quota" | "quality";
13
+ export type ProbeStatus = "ok" | "unavailable" | "auth" | "timeout" | "error" | "skipped";
14
+ export type CostTier = "cheap" | "medium" | "expensive";
15
+ export type QualityTier = "weak" | "medium" | "strong";
16
+ export type LatencyTier = "fast" | "medium" | "slow";
17
+ export type RecommendedRoleTier = "cheap" | "medium" | "strong";
18
+
19
+ interface ProfileAgentOverride {
20
+ model?: string;
21
+ }
22
+
23
+ export interface SubagentProfileFile {
24
+ subagents: {
25
+ agentOverrides: Record<string, ProfileAgentOverride>;
26
+ };
27
+ }
28
+
29
+ export type ClassificationSource = "official-metadata" | "heuristic-name";
30
+
31
+ export interface ProviderModelCatalogModel {
32
+ id: string;
33
+ fullId: string;
34
+ observed: {
35
+ availableInRegistry: boolean;
36
+ name?: string;
37
+ reasoning?: boolean;
38
+ thinkingLevels: string[];
39
+ contextWindow?: number;
40
+ maxTokens?: number;
41
+ cost?: {
42
+ input?: number;
43
+ output?: number;
44
+ cacheRead?: number;
45
+ cacheWrite?: number;
46
+ };
47
+ probe: {
48
+ status: ProbeStatus;
49
+ checkedAt: string;
50
+ message?: string;
51
+ };
52
+ };
53
+ derived: {
54
+ profileRank: number;
55
+ costTier: CostTier;
56
+ qualityTier: QualityTier;
57
+ latencyTier: LatencyTier;
58
+ recommendedRoleTier: RecommendedRoleTier;
59
+ recommendedAgents: BuiltinAgentName[];
60
+ classificationSources: ClassificationSource[];
61
+ };
62
+ warnings: string[];
63
+ notes: string[];
64
+ }
65
+
66
+ export interface ProviderModelCatalogFile {
67
+ provider: string;
68
+ refreshedAt: string;
69
+ maxAgeDays: number;
70
+ sources: string[];
71
+ models: ProviderModelCatalogModel[];
72
+ }
73
+
74
+ export interface ProfileCheckResult {
75
+ profileName: string;
76
+ filePath: string;
77
+ results: Array<{
78
+ agent: string;
79
+ model: string;
80
+ inRegistry: boolean;
81
+ probe: { status: ProbeStatus; message?: string };
82
+ }>;
83
+ }
84
+
85
+ function readJsonObjectFile(filePath: string): Record<string, unknown> {
86
+ const raw = fs.readFileSync(filePath, "utf-8");
87
+ const parsed = JSON.parse(raw) as unknown;
88
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
89
+ throw new Error(`File '${filePath}' must contain a JSON object.`);
90
+ }
91
+ return parsed as Record<string, unknown>;
92
+ }
93
+
94
+ function writeJsonFile(filePath: string, value: unknown): void {
95
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
96
+ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
97
+ }
98
+
99
+ const SAFE_PATH_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
100
+
101
+ function normalizePathToken(value: string, label: string): string {
102
+ const trimmed = value.trim();
103
+ if (!trimmed) throw new Error(`${label} is required.`);
104
+ if (!SAFE_PATH_TOKEN.test(trimmed) || trimmed === "." || trimmed === ".." || trimmed.includes("/") || trimmed.includes("\\")) {
105
+ throw new Error(`${label} must be a safe file name using only letters, numbers, dots, underscores, and hyphens.`);
106
+ }
107
+ return trimmed;
108
+ }
109
+
110
+ function normalizeProfileName(name: string): string {
111
+ const trimmed = name.trim();
112
+ const stem = trimmed.endsWith(".json") ? trimmed.slice(0, -5) : trimmed;
113
+ return normalizePathToken(stem, "Profile name");
114
+ }
115
+
116
+ function normalizeProviderName(provider: string): string {
117
+ return normalizePathToken(provider, "Provider");
118
+ }
119
+
120
+ function validateSubagentProfile(filePath: string, parsed: Record<string, unknown>): SubagentProfileFile {
121
+ const subagents = parsed.subagents;
122
+ if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) {
123
+ throw new Error(`Profile '${filePath}' must contain a 'subagents' object.`);
124
+ }
125
+ const agentOverrides = (subagents as Record<string, unknown>).agentOverrides;
126
+ if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) {
127
+ throw new Error(`Profile '${filePath}' must contain 'subagents.agentOverrides' as an object.`);
128
+ }
129
+ for (const [name, value] of Object.entries(agentOverrides)) {
130
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
131
+ throw new Error(`Profile '${filePath}' has invalid override '${name}'; expected an object.`);
132
+ }
133
+ const model = (value as Record<string, unknown>).model;
134
+ if (model !== undefined && typeof model !== "string") {
135
+ throw new Error(`Profile '${filePath}' has invalid model for '${name}'; expected a string.`);
136
+ }
137
+ }
138
+ return parsed as unknown as SubagentProfileFile;
139
+ }
140
+
141
+ function getUserSettingsPath(): string {
142
+ return path.join(getAgentDir(), "settings.json");
143
+ }
144
+
145
+ function readSettingsFile(filePath: string): Record<string, unknown> {
146
+ if (!fs.existsSync(filePath)) return {};
147
+ return readJsonObjectFile(filePath);
148
+ }
149
+
150
+ function extractVersionScore(id: string): number {
151
+ const match = id.match(/(\d+(?:\.\d+)?)/g);
152
+ if (!match || match.length === 0) return 0;
153
+ return Math.max(...match.map((value) => Number.parseFloat(value)).filter((value) => Number.isFinite(value)));
154
+ }
155
+
156
+ function modelNameTokens(modelName: string): string[] {
157
+ return modelName
158
+ .toLowerCase()
159
+ .replace(/([a-z])([0-9])/g, "$1 $2")
160
+ .replace(/([0-9])([a-z])/g, "$1 $2")
161
+ .split(/[^a-z0-9.]+/)
162
+ .filter(Boolean);
163
+ }
164
+
165
+ function inferProfileBand(modelName: string): 0 | 1 | 2 | 3 | 4 {
166
+ const tokens = new Set(modelNameTokens(modelName));
167
+ if (["spark", "flash", "nano", "tiny", "instant"].some((token) => tokens.has(token))) return 0;
168
+ if (["mini", "haiku", "small"].some((token) => tokens.has(token))) return 1;
169
+ if (["opus", "max", "ultra", "pro"].some((token) => tokens.has(token))) return 4;
170
+ if (["sonnet", "turbo", "plus"].some((token) => tokens.has(token))) return 3;
171
+ return 2;
172
+ }
173
+
174
+ interface ModelClassificationInput {
175
+ id: string;
176
+ name?: string;
177
+ reasoning?: boolean;
178
+ contextWindow?: number;
179
+ maxTokens?: number;
180
+ cost?: {
181
+ input?: number;
182
+ output?: number;
183
+ cacheRead?: number;
184
+ cacheWrite?: number;
185
+ };
186
+ }
187
+
188
+ interface NumericStats {
189
+ min: number;
190
+ max: number;
191
+ }
192
+
193
+ interface ClassificationContext {
194
+ cost?: NumericStats;
195
+ contextWindow?: NumericStats;
196
+ maxTokens?: NumericStats;
197
+ }
198
+
199
+ function combinedCost(cost: ModelClassificationInput["cost"]): number | undefined {
200
+ if (!cost) return undefined;
201
+ const values = [cost.input, cost.output, cost.cacheRead, cost.cacheWrite].filter((value): value is number => typeof value === "number" && Number.isFinite(value));
202
+ if (values.length === 0) return undefined;
203
+ return values.reduce((sum, value) => sum + value, 0);
204
+ }
205
+
206
+ function collectStats(values: Array<number | undefined>): NumericStats | undefined {
207
+ const filtered = values.filter((value): value is number => typeof value === "number" && Number.isFinite(value));
208
+ if (filtered.length === 0) return undefined;
209
+ return { min: Math.min(...filtered), max: Math.max(...filtered) };
210
+ }
211
+
212
+ function normalize(value: number | undefined, stats: NumericStats | undefined): number | undefined {
213
+ if (value === undefined || !stats) return undefined;
214
+ if (stats.max <= stats.min) return 0.5;
215
+ return (value - stats.min) / (stats.max - stats.min);
216
+ }
217
+
218
+ function buildClassificationContext(models: ModelClassificationInput[]): ClassificationContext {
219
+ return {
220
+ cost: collectStats(models.map((model) => combinedCost(model.cost))),
221
+ contextWindow: collectStats(models.map((model) => model.contextWindow)),
222
+ maxTokens: collectStats(models.map((model) => model.maxTokens)),
223
+ };
224
+ }
225
+
226
+ function rankToCostTier(rank: number): CostTier {
227
+ if (rank <= 0.33) return "cheap";
228
+ if (rank <= 0.66) return "medium";
229
+ return "expensive";
230
+ }
231
+
232
+ function scoreToQualityTier(score: number): QualityTier {
233
+ if (score <= 0.33) return "weak";
234
+ if (score <= 0.66) return "medium";
235
+ return "strong";
236
+ }
237
+
238
+ function qualityTierToRoleTier(quality: QualityTier, cost: CostTier): RecommendedRoleTier {
239
+ if (quality === "strong") return "strong";
240
+ if (quality === "medium") return cost === "cheap" ? "cheap" : "medium";
241
+ return "cheap";
242
+ }
243
+
244
+ function agentsForRoleTier(roleTier: RecommendedRoleTier): BuiltinAgentName[] {
245
+ if (roleTier === "cheap") return ["scout", "delegate"];
246
+ if (roleTier === "medium") return ["planner", "context-builder", "researcher"];
247
+ return ["worker", "reviewer", "oracle"];
248
+ }
249
+
250
+ function classifyModel(input: ModelClassificationInput, context: ClassificationContext): {
251
+ profileRank: number;
252
+ costTier: CostTier;
253
+ qualityTier: QualityTier;
254
+ latencyTier: LatencyTier;
255
+ recommendedRoleTier: RecommendedRoleTier;
256
+ recommendedAgents: BuiltinAgentName[];
257
+ classificationSources: ClassificationSource[];
258
+ } {
259
+ const modelName = input.name?.trim() || input.id;
260
+ const tokens = new Set(modelNameTokens(modelName));
261
+ const band = inferProfileBand(modelName);
262
+ const versionScore = extractVersionScore(input.id);
263
+ const costNorm = normalize(combinedCost(input.cost), context.cost);
264
+ const contextNorm = normalize(input.contextWindow, context.contextWindow);
265
+ const maxTokensNorm = normalize(input.maxTokens, context.maxTokens);
266
+ const hasOfficialMetadata = costNorm !== undefined || contextNorm !== undefined || maxTokensNorm !== undefined;
267
+ const classificationSources: ClassificationSource[] = hasOfficialMetadata
268
+ ? ["official-metadata", "heuristic-name"]
269
+ : ["heuristic-name"];
270
+ const heuristicBase = band / 4;
271
+ const qualitySignals = [
272
+ heuristicBase,
273
+ ...(contextNorm !== undefined ? [contextNorm] : []),
274
+ ...(maxTokensNorm !== undefined ? [maxTokensNorm] : []),
275
+ ...(input.reasoning === true ? [1] : []),
276
+ ...(input.reasoning === false ? [0] : []),
277
+ ];
278
+ const latencyHintsFast = tokens.has("highspeed") || tokens.has("flash") || tokens.has("instant") || tokens.has("turbo");
279
+ const latencyHintsSlow = tokens.has("pro") || tokens.has("ultra") || tokens.has("opus") || tokens.has("max");
280
+ let qualityScore = qualitySignals.reduce((sum, value) => sum + value, 0) / qualitySignals.length;
281
+ if (latencyHintsFast) {
282
+ qualityScore -= 0.2;
283
+ }
284
+ qualityScore = Math.max(0, Math.min(1, qualityScore));
285
+ const costTier = costNorm !== undefined
286
+ ? rankToCostTier(costNorm)
287
+ : band === 0 ? "cheap" : band >= 3 ? "expensive" : "medium";
288
+ const qualityTier = scoreToQualityTier(qualityScore);
289
+ const latencyTier: LatencyTier = latencyHintsFast
290
+ ? "fast"
291
+ : latencyHintsSlow
292
+ ? "slow"
293
+ : costNorm !== undefined
294
+ ? (costNorm <= 0.33 ? "fast" : costNorm <= 0.66 ? "medium" : "slow")
295
+ : (band <= 1 ? "fast" : band >= 3 ? "slow" : "medium");
296
+ const recommendedRoleTier = qualityTierToRoleTier(qualityTier, costTier);
297
+ const latencyPenalty = latencyHintsFast ? 125 : 0;
298
+ const profileRank = Math.round((qualityScore * 100) * 10) + Math.round(versionScore * 25) - latencyPenalty;
299
+ return {
300
+ profileRank,
301
+ costTier,
302
+ qualityTier,
303
+ latencyTier,
304
+ recommendedRoleTier,
305
+ recommendedAgents: agentsForRoleTier(recommendedRoleTier),
306
+ classificationSources,
307
+ };
308
+ }
309
+
310
+ function resolveProbeStatus(text: string, timedOut: boolean): ProbeStatus {
311
+ if (timedOut) return "timeout";
312
+ if (!text) return "error";
313
+ if (/(unauthori[sz]ed|forbidden|api key|auth|billing|credit|quota)/i.test(text)) return "auth";
314
+ if (/(not found|unknown model|model unavailable|model disabled|unsupported model|unavailable)/i.test(text)) return "unavailable";
315
+ return "error";
316
+ }
317
+
318
+ async function probeModel(
319
+ pi: Pick<ExtensionAPI, "exec"> | { exec?: ExtensionAPI["exec"] },
320
+ ctx: Pick<ExtensionContext, "cwd">,
321
+ fullId: string,
322
+ ): Promise<{ status: ProbeStatus; message?: string }> {
323
+ if (typeof pi.exec !== "function") {
324
+ return { status: "skipped", message: "pi.exec is unavailable in this runtime." };
325
+ }
326
+ const result = await pi.exec("pi", ["-p", "--model", fullId, "--no-tools", 'Reply with exactly "OK".'], {
327
+ cwd: os.tmpdir(),
328
+ timeout: 45_000,
329
+ } as Record<string, unknown>);
330
+ const stdout = typeof result.stdout === "string" ? result.stdout.trim() : "";
331
+ const stderr = typeof result.stderr === "string" ? result.stderr.trim() : "";
332
+ const combined = [stderr, stdout].filter(Boolean).join("\n").trim();
333
+ if (result.code === 0) return { status: "ok", message: stdout || "Probe succeeded." };
334
+ return { status: resolveProbeStatus(combined, result.killed === true), message: combined || `Probe exited with code ${result.code ?? "unknown"}.` };
335
+ }
336
+
337
+ function roundIndex(count: number, position: number): number {
338
+ if (count <= 1) return 0;
339
+ return Math.max(0, Math.min(count - 1, Math.round((count - 1) * position)));
340
+ }
341
+
342
+ function profilePositions(kind: ProfileKind): { cheap: number; medium: number; strong: number } {
343
+ return kind === "quota"
344
+ ? { cheap: 0, medium: 1 / 3, strong: 2 / 3 }
345
+ : { cheap: 1 / 3, medium: 2 / 3, strong: 1 };
346
+ }
347
+
348
+ function pickTierModels(models: ProviderModelCatalogModel[], kind: ProfileKind): { cheap: string; medium: string; strong: string } {
349
+ if (models.length === 0) throw new Error("No provider models are available for profile generation.");
350
+ const selectionPool = kind === "quota" && models.length > 1
351
+ ? models.slice(0, -1)
352
+ : models;
353
+ const positions = profilePositions(kind);
354
+ return {
355
+ cheap: selectionPool[roundIndex(selectionPool.length, positions.cheap)]!.fullId,
356
+ medium: selectionPool[roundIndex(selectionPool.length, positions.medium)]!.fullId,
357
+ strong: selectionPool[roundIndex(selectionPool.length, positions.strong)]!.fullId,
358
+ };
359
+ }
360
+
361
+ function observedCombinedCost(model: ProviderModelCatalogModel): number | undefined {
362
+ return combinedCost(model.observed.cost);
363
+ }
364
+
365
+ function dominatesModel(a: ProviderModelCatalogModel, b: ProviderModelCatalogModel): boolean {
366
+ const costA = observedCombinedCost(a);
367
+ const costB = observedCombinedCost(b);
368
+ if (costA === undefined || costB === undefined) return false;
369
+ if (costA > costB) return false;
370
+ if (a.derived.profileRank < b.derived.profileRank) return false;
371
+ if ((a.observed.reasoning === true ? 1 : 0) < (b.observed.reasoning === true ? 1 : 0)) return false;
372
+ if ((a.observed.contextWindow ?? 0) < (b.observed.contextWindow ?? 0)) return false;
373
+ if ((a.observed.maxTokens ?? 0) < (b.observed.maxTokens ?? 0)) return false;
374
+ return costA < costB
375
+ || a.derived.profileRank > b.derived.profileRank
376
+ || (a.observed.reasoning === true && b.observed.reasoning !== true)
377
+ || (a.observed.contextWindow ?? 0) > (b.observed.contextWindow ?? 0)
378
+ || (a.observed.maxTokens ?? 0) > (b.observed.maxTokens ?? 0);
379
+ }
380
+
381
+ function filterDominatedModels(models: ProviderModelCatalogModel[]): ProviderModelCatalogModel[] {
382
+ return models.filter((candidate, index) => !models.some((other, otherIndex) => otherIndex !== index && dominatesModel(other, candidate)));
383
+ }
384
+
385
+ function buildProfileFile(kind: ProfileKind, models: { cheap: string; medium: string; strong: string }): SubagentProfileFile {
386
+ return {
387
+ subagents: {
388
+ agentOverrides: {
389
+ scout: { model: models.cheap },
390
+ delegate: { model: models.cheap },
391
+ planner: { model: models.medium },
392
+ "context-builder": { model: models.medium },
393
+ researcher: { model: models.medium },
394
+ worker: { model: models.strong },
395
+ reviewer: { model: models.strong },
396
+ oracle: { model: models.strong },
397
+ },
398
+ },
399
+ };
400
+ }
401
+
402
+ function catalogModelIsUsable(model: ProviderModelCatalogModel): boolean {
403
+ return model.observed.availableInRegistry && model.observed.probe.status !== "unavailable" && model.observed.probe.status !== "auth" && model.observed.probe.status !== "timeout" && model.observed.probe.status !== "error";
404
+ }
405
+
406
+ function modelUsesHeuristicClassification(model: ProviderModelCatalogModel): boolean {
407
+ return model.derived.classificationSources.includes("heuristic-name")
408
+ && !model.derived.classificationSources.includes("official-metadata");
409
+ }
410
+
411
+ function warningLineForHeuristicFallback(): string {
412
+ return "Classification fell back to name heuristics.";
413
+ }
414
+
415
+ export function countHeuristicFallbackModels(catalog: ProviderModelCatalogFile): number {
416
+ return catalog.models.filter(modelUsesHeuristicClassification).length;
417
+ }
418
+
419
+ function resolveProfilePath(name: string): string {
420
+ const dir = ensureSubagentProfilesDir();
421
+ return path.join(dir, `${normalizeProfileName(name)}.json`);
422
+ }
423
+
424
+ export function getSubagentProfilesRootDir(): string {
425
+ return path.join(getAgentDir(), "profiles", "pi-subagents");
426
+ }
427
+
428
+ export function getSubagentProfilesDir(): string {
429
+ return getSubagentProfilesRootDir();
430
+ }
431
+
432
+ export function ensureSubagentProfilesDir(): string {
433
+ const dir = getSubagentProfilesDir();
434
+ fs.mkdirSync(dir, { recursive: true });
435
+ return dir;
436
+ }
437
+
438
+ export function getProviderModelsDir(): string {
439
+ return path.join(getSubagentProfilesRootDir(), "providers");
440
+ }
441
+
442
+ export function ensureProviderModelsDir(): string {
443
+ const dir = getProviderModelsDir();
444
+ fs.mkdirSync(dir, { recursive: true });
445
+ return dir;
446
+ }
447
+
448
+ export function getProviderModelsPath(provider: string): string {
449
+ return path.join(ensureProviderModelsDir(), `${normalizeProviderName(provider)}.models.json`);
450
+ }
451
+
452
+ export function listSubagentProfiles(): string[] {
453
+ const dir = ensureSubagentProfilesDir();
454
+ return fs.readdirSync(dir, { withFileTypes: true })
455
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
456
+ .map((entry) => entry.name.slice(0, -5))
457
+ .sort((a, b) => a.localeCompare(b));
458
+ }
459
+
460
+ export function readSubagentProfile(name: string): { filePath: string; profile: SubagentProfileFile } {
461
+ const filePath = resolveProfilePath(name);
462
+ if (!fs.existsSync(filePath)) throw new Error(`Profile not found: ${name}`);
463
+ const parsed = readJsonObjectFile(filePath);
464
+ return { filePath, profile: validateSubagentProfile(filePath, parsed) };
465
+ }
466
+
467
+ export function applySubagentProfile(name: string): { filePath: string; settingsPath: string } {
468
+ const { filePath, profile } = readSubagentProfile(name);
469
+ const settingsPath = getUserSettingsPath();
470
+ const settings = readSettingsFile(settingsPath);
471
+ settings.subagents = profile.subagents;
472
+ writeJsonFile(settingsPath, settings);
473
+ return { filePath, settingsPath };
474
+ }
475
+
476
+ export function readProviderModelCatalog(provider: string): ProviderModelCatalogFile | null {
477
+ const filePath = getProviderModelsPath(provider);
478
+ if (!fs.existsSync(filePath)) return null;
479
+ return readJsonObjectFile(filePath) as unknown as ProviderModelCatalogFile;
480
+ }
481
+
482
+ export function isProviderModelCatalogStale(catalog: ProviderModelCatalogFile, maxAgeDays = DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS): boolean {
483
+ const refreshedAt = Date.parse(catalog.refreshedAt);
484
+ if (!Number.isFinite(refreshedAt)) return true;
485
+ const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000;
486
+ return Date.now() - refreshedAt > maxAgeMs;
487
+ }
488
+
489
+ export async function refreshProviderModelCatalog(
490
+ pi: Pick<ExtensionAPI, "exec"> | { exec?: ExtensionAPI["exec"] },
491
+ ctx: Pick<ExtensionContext, "cwd" | "modelRegistry">,
492
+ provider: string,
493
+ options: { force?: boolean; maxAgeDays?: number; probe?: boolean } = {},
494
+ ): Promise<{ filePath: string; catalog: ProviderModelCatalogFile; reused: boolean; heuristicFallbackCount: number }> {
495
+ const normalizedProvider = normalizeProviderName(provider);
496
+ const maxAgeDays = options.maxAgeDays ?? DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS;
497
+ const filePath = getProviderModelsPath(normalizedProvider);
498
+ if (!options.force) {
499
+ const existing = readProviderModelCatalog(normalizedProvider);
500
+ if (existing && !isProviderModelCatalogStale(existing, maxAgeDays)) {
501
+ return { filePath, catalog: existing, reused: true, heuristicFallbackCount: countHeuristicFallbackModels(existing) };
502
+ }
503
+ }
504
+
505
+ const availableModels = ctx.modelRegistry.getAvailable().filter((model) => model.provider === normalizedProvider);
506
+ if (availableModels.length === 0) {
507
+ throw new Error(`No models found in the current registry for provider '${normalizedProvider}'.`);
508
+ }
509
+
510
+ const observedModels = [] as Array<{
511
+ rawModel: typeof availableModels[number];
512
+ modelRecord: Record<string, unknown> & { provider: string; id: string; name?: string };
513
+ fullId: string;
514
+ probe: { status: ProbeStatus; message?: string };
515
+ }>;
516
+ for (const rawModel of availableModels) {
517
+ const modelRecord = rawModel as Record<string, unknown> & { provider: string; id: string; name?: string };
518
+ const fullId = `${modelRecord.provider}/${modelRecord.id}`;
519
+ const probe = options.probe === false
520
+ ? { status: "skipped" as const, message: "Live probing disabled." }
521
+ : await probeModel(pi, ctx, fullId);
522
+ observedModels.push({ rawModel, modelRecord, fullId, probe });
523
+ }
524
+ const classificationContext = buildClassificationContext(observedModels.map(({ modelRecord }) => ({
525
+ id: modelRecord.id,
526
+ ...(typeof modelRecord.name === "string" ? { name: modelRecord.name } : {}),
527
+ ...(typeof modelRecord.reasoning === "boolean" ? { reasoning: modelRecord.reasoning } : {}),
528
+ ...(typeof modelRecord.contextWindow === "number" ? { contextWindow: modelRecord.contextWindow } : {}),
529
+ ...(typeof modelRecord.maxTokens === "number" ? { maxTokens: modelRecord.maxTokens } : {}),
530
+ ...(modelRecord.cost && typeof modelRecord.cost === "object" ? { cost: modelRecord.cost as ProviderModelCatalogModel["observed"]["cost"] } : {}),
531
+ })));
532
+ const models: ProviderModelCatalogModel[] = [];
533
+ for (const { rawModel, modelRecord, fullId, probe } of observedModels) {
534
+ const classification = classifyModel({
535
+ id: modelRecord.id,
536
+ ...(typeof modelRecord.name === "string" ? { name: modelRecord.name } : {}),
537
+ ...(typeof modelRecord.reasoning === "boolean" ? { reasoning: modelRecord.reasoning } : {}),
538
+ ...(typeof modelRecord.contextWindow === "number" ? { contextWindow: modelRecord.contextWindow } : {}),
539
+ ...(typeof modelRecord.maxTokens === "number" ? { maxTokens: modelRecord.maxTokens } : {}),
540
+ ...(modelRecord.cost && typeof modelRecord.cost === "object" ? { cost: modelRecord.cost as ProviderModelCatalogModel["observed"]["cost"] } : {}),
541
+ }, classificationContext);
542
+ const warnings = classification.classificationSources.includes("heuristic-name") && !classification.classificationSources.includes("official-metadata")
543
+ ? [warningLineForHeuristicFallback()]
544
+ : [];
545
+ models.push({
546
+ id: modelRecord.id,
547
+ fullId,
548
+ observed: {
549
+ availableInRegistry: true,
550
+ ...(typeof modelRecord.name === "string" ? { name: modelRecord.name } : {}),
551
+ ...(typeof modelRecord.reasoning === "boolean" ? { reasoning: modelRecord.reasoning } : {}),
552
+ thinkingLevels: getSupportedThinkingLevels(toModelInfo(rawModel)).map((level) => level),
553
+ ...(typeof modelRecord.contextWindow === "number" ? { contextWindow: modelRecord.contextWindow } : {}),
554
+ ...(typeof modelRecord.maxTokens === "number" ? { maxTokens: modelRecord.maxTokens } : {}),
555
+ ...(modelRecord.cost && typeof modelRecord.cost === "object" ? { cost: modelRecord.cost as ProviderModelCatalogModel["observed"]["cost"] } : {}),
556
+ probe: {
557
+ status: probe.status,
558
+ checkedAt: new Date().toISOString(),
559
+ ...(probe.message ? { message: probe.message } : {}),
560
+ },
561
+ },
562
+ derived: classification,
563
+ warnings,
564
+ notes: [],
565
+ });
566
+ }
567
+ models.sort((a, b) => a.derived.profileRank - b.derived.profileRank || a.fullId.localeCompare(b.fullId));
568
+ const catalog: ProviderModelCatalogFile = {
569
+ provider: normalizedProvider,
570
+ refreshedAt: new Date().toISOString(),
571
+ maxAgeDays,
572
+ sources: ["runtime-registry", ...(options.probe === false ? [] : ["live-probe"]), "heuristic-classifier"],
573
+ models,
574
+ };
575
+ writeJsonFile(filePath, catalog);
576
+ return { filePath, catalog, reused: false, heuristicFallbackCount: countHeuristicFallbackModels(catalog) };
577
+ }
578
+
579
+ export async function generateProfilesForProvider(
580
+ pi: Pick<ExtensionAPI, "exec"> | { exec?: ExtensionAPI["exec"] },
581
+ ctx: Pick<ExtensionContext, "cwd" | "modelRegistry">,
582
+ provider: string,
583
+ options: { maxAgeDays?: number; forceRefresh?: boolean; probe?: boolean } = {},
584
+ ): Promise<{ quotaPath: string; qualityPath: string; catalogPath: string; quotaModels: { cheap: string; medium: string; strong: string }; qualityModels: { cheap: string; medium: string; strong: string }; heuristicFallbackCount: number; selectedHeuristicFallbackCount: number }> {
585
+ const normalizedProvider = normalizeProviderName(provider);
586
+ const { filePath: catalogPath, catalog, heuristicFallbackCount } = await refreshProviderModelCatalog(pi, ctx, normalizedProvider, {
587
+ maxAgeDays: options.maxAgeDays,
588
+ force: options.forceRefresh,
589
+ probe: options.probe,
590
+ });
591
+ const usableModels = catalog.models.filter(catalogModelIsUsable);
592
+ const profileModels = filterDominatedModels(usableModels);
593
+ if (profileModels.length === 0) {
594
+ throw new Error(`Provider '${normalizedProvider}' has no usable models after filtering.`);
595
+ }
596
+ const quotaModels = pickTierModels(profileModels, "quota");
597
+ const qualityModels = pickTierModels(profileModels, "quality");
598
+ const dir = ensureSubagentProfilesDir();
599
+ const quotaPath = path.join(dir, `${normalizedProvider}.quota.json`);
600
+ const qualityPath = path.join(dir, `${normalizedProvider}.quality.json`);
601
+ writeJsonFile(quotaPath, buildProfileFile("quota", quotaModels));
602
+ writeJsonFile(qualityPath, buildProfileFile("quality", qualityModels));
603
+ const selectedModels = new Set([...Object.values(quotaModels), ...Object.values(qualityModels)]);
604
+ const selectedHeuristicFallbackCount = profileModels.filter((model) => selectedModels.has(model.fullId) && modelUsesHeuristicClassification(model)).length;
605
+ return { quotaPath, qualityPath, catalogPath, quotaModels, qualityModels, heuristicFallbackCount, selectedHeuristicFallbackCount };
606
+ }
607
+
608
+ export async function checkSubagentProfile(
609
+ pi: Pick<ExtensionAPI, "exec"> | { exec?: ExtensionAPI["exec"] },
610
+ ctx: Pick<ExtensionContext, "cwd" | "modelRegistry">,
611
+ name: string,
612
+ ): Promise<ProfileCheckResult> {
613
+ const { filePath, profile } = readSubagentProfile(name);
614
+ const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
615
+ const entries = Object.entries(profile.subagents.agentOverrides)
616
+ .filter(([, value]) => typeof value?.model === "string" && value.model.trim())
617
+ .map(([agent, value]) => ({ agent, model: value.model!.trim() }));
618
+ const probeCache = new Map<string, { status: ProbeStatus; message?: string }>();
619
+ const results: ProfileCheckResult["results"] = [];
620
+ for (const entry of entries) {
621
+ const modelInfo = findModelInfo(entry.model, availableModels);
622
+ const { thinkingSuffix } = splitKnownThinkingSuffix(entry.model);
623
+ const probeModelId = modelInfo ? `${modelInfo.fullId}${thinkingSuffix}` : entry.model;
624
+ let probe = probeCache.get(probeModelId);
625
+ if (!probe) {
626
+ probe = await probeModel(pi, ctx, probeModelId);
627
+ probeCache.set(probeModelId, probe);
628
+ }
629
+ results.push({
630
+ agent: entry.agent,
631
+ model: entry.model,
632
+ inRegistry: modelInfo !== undefined,
633
+ probe,
634
+ });
635
+ }
636
+ return { profileName: name, filePath, results };
637
+ }
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { ASYNC_DIR, RESULTS_DIR, type AsyncStatus, type SubagentState } from "../../shared/types.ts";
4
4
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
5
+ import { deliverInterruptRequest } from "./control-channel.ts";
5
6
  import { reconcileAsyncRun } from "./stale-run-reconciler.ts";
6
7
 
7
8
  export const ASYNC_RESUME_INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
@@ -38,33 +39,30 @@ export type AsyncResumeTarget = {
38
39
 
39
40
  type KillFn = (pid: number, signal?: NodeJS.Signals | 0) => boolean;
40
41
 
41
- function readAsyncStatus(asyncDir: string): AsyncStatus | null {
42
- const statusPath = path.join(asyncDir, "status.json");
43
- try {
44
- return JSON.parse(fs.readFileSync(statusPath, "utf-8")) as AsyncStatus;
45
- } catch (error) {
46
- const code = error && typeof error === "object" && "code" in error ? (error as NodeJS.ErrnoException).code : undefined;
47
- if (code === "ENOENT") return null;
48
- throw error;
49
- }
50
- }
51
-
52
42
  export function interruptLiveAsyncResumeTarget(input: {
53
43
  target: AsyncResumeTarget & { kind: "live" };
54
44
  state?: Pick<SubagentState, "asyncJobs">;
55
45
  kill?: KillFn;
56
46
  now?: () => number;
47
+ resultsDir?: string;
57
48
  }): { ok: true; asyncId: string } | { ok: false; message: string } {
58
49
  const asyncId = input.target.runId;
59
50
  if (!input.target.asyncDir) {
60
51
  return { ok: false, message: `Async run ${asyncId} is live but does not have an async directory to interrupt.` };
61
52
  }
62
- const status = readAsyncStatus(input.target.asyncDir);
53
+ const status = reconcileAsyncRun(input.target.asyncDir, { resultsDir: input.resultsDir, kill: input.kill, now: input.now }).status;
63
54
  if (!status || status.state !== "running" || typeof status.pid !== "number") {
64
55
  return { ok: false, message: `Async run ${asyncId} is live but no interrupt-capable runner pid was found.` };
65
56
  }
66
57
  try {
67
- (input.kill ?? process.kill)(status.pid, ASYNC_RESUME_INTERRUPT_SIGNAL);
58
+ deliverInterruptRequest({
59
+ asyncDir: input.target.asyncDir,
60
+ pid: status.pid,
61
+ kill: input.kill,
62
+ signal: ASYNC_RESUME_INTERRUPT_SIGNAL,
63
+ now: input.now,
64
+ source: "async-resume",
65
+ });
68
66
  const tracked = input.state?.asyncJobs.get(asyncId);
69
67
  if (tracked) {
70
68
  tracked.activityState = undefined;