pi-legion 0.16.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CONTRIBUTING.md +58 -0
  2. package/README.md +313 -640
  3. package/agents/advisor.md +7 -5
  4. package/agents/centurion.md +53 -0
  5. package/agents/designer.md +33 -33
  6. package/agents/planner.md +1 -2
  7. package/agents/prototype.md +2 -2
  8. package/agents/reviewer.md +67 -31
  9. package/agents/scout.md +6 -2
  10. package/agents/worker.md +12 -3
  11. package/docs/contracts/esc-abort-v1.md +131 -0
  12. package/docs/contracts/esc-cascade-v2.md +100 -0
  13. package/docs/design.md +44 -25
  14. package/docs/legion-v2-contract.md +461 -0
  15. package/docs/legion-v2-delivery.md +62 -0
  16. package/docs/retire-hardening-contract.md +125 -0
  17. package/docs/subagents-teams.md +76 -0
  18. package/docs/tui-viewer-contract.md +276 -0
  19. package/docs/vexillatio-contract.md +162 -0
  20. package/index.ts +1462 -286
  21. package/package.json +12 -9
  22. package/skills/pi-legion/SKILL.md +74 -96
  23. package/src/agents/agents.ts +6 -11
  24. package/src/agents/overrides.ts +2 -1
  25. package/src/agents/paths.ts +1 -1
  26. package/src/agents/settings.ts +268 -20
  27. package/src/api.ts +47 -48
  28. package/src/{herdr → backends/legacy}/client.ts +14 -69
  29. package/src/{shared → backends/legacy}/cursor-chat.ts +2 -2
  30. package/src/{herdr → backends/legacy}/runner.ts +22 -9
  31. package/src/backends/legacy/types.ts +138 -0
  32. package/src/extension/auto-doctor.ts +144 -0
  33. package/src/extension/budget.ts +2 -2
  34. package/src/extension/child-guard.ts +214 -201
  35. package/src/extension/event-bus.ts +263 -0
  36. package/src/extension/legion-commands.ts +719 -0
  37. package/src/extension/legion-doctor.ts +888 -0
  38. package/src/extension/legion-stop.ts +150 -0
  39. package/src/extension/legion-tools.ts +816 -0
  40. package/src/extension/notify.ts +24 -19
  41. package/src/extension/playbook.ts +20 -89
  42. package/src/extension/recycle.ts +2 -7
  43. package/src/extension/runtime.ts +655 -105
  44. package/src/extension/scout-guard.ts +483 -0
  45. package/src/extension/slash.ts +89 -438
  46. package/src/extension/spawn-hints.ts +79 -0
  47. package/src/extension/summary.ts +17 -58
  48. package/src/legion/budget.ts +165 -0
  49. package/src/legion/db.ts +242 -0
  50. package/src/legion/events.ts +150 -0
  51. package/src/legion/mail.ts +412 -0
  52. package/src/legion/nodes.ts +461 -0
  53. package/src/legion/rebuild.ts +533 -0
  54. package/src/legion/state-machine.ts +313 -0
  55. package/src/legion/usage.ts +101 -0
  56. package/src/runs/acceptance.ts +82 -25
  57. package/src/runs/args.ts +51 -5
  58. package/src/runs/hygiene.ts +335 -0
  59. package/src/runs/orchestrator.ts +790 -1683
  60. package/src/runs/owner.ts +61 -0
  61. package/src/runs/provision.ts +135 -0
  62. package/src/runs/store.ts +44 -17
  63. package/src/runs/verify-queue.ts +195 -0
  64. package/src/shared/name.ts +29 -0
  65. package/src/shared/output-cap.ts +57 -0
  66. package/src/shared/progress.ts +57 -135
  67. package/src/shared/session.ts +243 -171
  68. package/src/shared/types.ts +107 -208
  69. package/src/supervisor/child-memory.ts +140 -0
  70. package/src/supervisor/proc-tree.ts +103 -0
  71. package/src/supervisor/rpc-supervisor.ts +1033 -0
  72. package/src/supervisor/types.ts +153 -0
  73. package/src/supervisor/ui-proxy.ts +226 -0
  74. package/src/tui/chat-items.ts +330 -0
  75. package/src/tui/live-overlay.ts +874 -0
  76. package/src/tui/status.ts +553 -27
  77. package/src/tui/tree-view.ts +808 -0
  78. package/src/tui/viz/canvas.ts +119 -0
  79. package/src/tui/viz/layout.ts +111 -0
  80. package/src/tui/viz/model.ts +123 -0
  81. package/src/tui/viz/palette.ts +188 -0
  82. package/src/tui/viz/panels.ts +530 -0
  83. package/src/tui/viz/railway.ts +313 -0
  84. package/src/tui/viz/rate.ts +211 -0
  85. package/src/tui/viz/view.ts +228 -0
  86. package/src/extension/parent-label.ts +0 -115
  87. package/src/profiles/classify.ts +0 -375
  88. package/src/profiles/profiles.ts +0 -730
  89. package/src/runs/layout.ts +0 -258
@@ -1,730 +0,0 @@
1
- /**
2
- * Subagent model profiles — cheap / medium / strong role assignments.
3
- *
4
- * Same workflow as pi-subagents:
5
- * refresh a provider catalog → generate quota + quality profiles → load one
6
- * into `~/.pi/agent/settings.json` as `subagents.agentOverrides`.
7
- *
8
- * Files live under `~/.pi/agent/profiles/pi-legion/` so they do not
9
- * collide with a side-by-side pi-subagents install.
10
- */
11
-
12
- import * as fs from "node:fs";
13
- import * as os from "node:os";
14
- import * as path from "node:path";
15
- import { getAgentDir } from "../agents/paths.ts";
16
- import { splitThinkingSuffix } from "../agents/model-scope.ts";
17
- import { THINKING_LEVELS } from "../shared/types.ts";
18
- import {
19
- buildClassificationContext,
20
- buildProfileFile,
21
- classifyModel,
22
- filterDominatedModels,
23
- pickTierModels,
24
- usesHeuristicClassification,
25
- type ClassificationSource,
26
- type ProfileKind,
27
- type SubagentProfileFile,
28
- } from "./classify.ts";
29
-
30
- export const DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS = 7;
31
- export const PROFILES_DIR_NAME = "pi-legion";
32
-
33
- export type ProbeStatus =
34
- | "ok"
35
- | "unavailable"
36
- | "auth"
37
- | "timeout"
38
- | "error"
39
- | "skipped";
40
-
41
- export interface RegistryModelLike {
42
- provider: string;
43
- id: string;
44
- name?: string;
45
- reasoning?: boolean;
46
- contextWindow?: number;
47
- maxTokens?: number;
48
- cost?: {
49
- input?: number;
50
- output?: number;
51
- cacheRead?: number;
52
- cacheWrite?: number;
53
- };
54
- thinkingLevelMap?: Record<string, string | null | undefined>;
55
- }
56
-
57
- export interface ModelRegistryLike {
58
- getAvailable(): RegistryModelLike[];
59
- find?(provider: string, id: string): RegistryModelLike | undefined;
60
- }
61
-
62
- export interface ProbeExec {
63
- exec?: (
64
- command: string,
65
- args: string[],
66
- options?: { cwd?: string; timeout?: number },
67
- ) => Promise<{
68
- code?: number | null;
69
- stdout?: string;
70
- stderr?: string;
71
- killed?: boolean;
72
- }>;
73
- }
74
-
75
- export interface ProfilePaths {
76
- agentDir: string;
77
- profilesDir: string;
78
- providersDir: string;
79
- settingsPath: string;
80
- }
81
-
82
- export interface ProviderModelCatalogModel {
83
- id: string;
84
- fullId: string;
85
- observed: {
86
- availableInRegistry: boolean;
87
- name?: string;
88
- reasoning?: boolean;
89
- thinkingLevels: string[];
90
- contextWindow?: number;
91
- maxTokens?: number;
92
- cost?: RegistryModelLike["cost"];
93
- probe: {
94
- status: ProbeStatus;
95
- checkedAt: string;
96
- message?: string;
97
- };
98
- };
99
- derived: {
100
- profileRank: number;
101
- costTier: string;
102
- qualityTier: string;
103
- latencyTier: string;
104
- recommendedRoleTier: string;
105
- recommendedAgents: string[];
106
- classificationSources: ClassificationSource[];
107
- };
108
- warnings: string[];
109
- notes: string[];
110
- }
111
-
112
- export interface ProviderModelCatalogFile {
113
- provider: string;
114
- refreshedAt: string;
115
- maxAgeDays: number;
116
- sources: string[];
117
- models: ProviderModelCatalogModel[];
118
- }
119
-
120
- export interface ProfileCheckResult {
121
- profileName: string;
122
- filePath: string;
123
- results: Array<{
124
- agent: string;
125
- model: string;
126
- inRegistry: boolean;
127
- probe: { status: ProbeStatus; message?: string };
128
- }>;
129
- }
130
-
131
- export interface ProfileIoOptions {
132
- agentDir?: string;
133
- }
134
-
135
- const SAFE_PATH_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
136
-
137
- function readJsonObjectFile(filePath: string): Record<string, unknown> {
138
- const raw = fs.readFileSync(filePath, "utf-8");
139
- let parsed: unknown;
140
- try {
141
- parsed = JSON.parse(raw) as unknown;
142
- } catch (error) {
143
- throw new Error(
144
- `Invalid JSON in '${filePath}': ${error instanceof Error ? error.message : String(error)}`,
145
- );
146
- }
147
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
148
- throw new Error(`File '${filePath}' must contain a JSON object.`);
149
- }
150
- return parsed as Record<string, unknown>;
151
- }
152
-
153
- export function writeJsonFile(filePath: string, value: unknown): void {
154
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
155
- fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
156
- }
157
-
158
- export function normalizePathToken(value: string, label: string): string {
159
- const trimmed = value.trim();
160
- if (!trimmed) throw new Error(`${label} is required.`);
161
- if (
162
- !SAFE_PATH_TOKEN.test(trimmed) ||
163
- trimmed === "." ||
164
- trimmed === ".." ||
165
- trimmed.includes("/") ||
166
- trimmed.includes("\\")
167
- ) {
168
- throw new Error(
169
- `${label} must be a safe file name using only letters, numbers, dots, underscores, and hyphens.`,
170
- );
171
- }
172
- return trimmed;
173
- }
174
-
175
- function normalizeProfileName(name: string): string {
176
- const trimmed = name.trim();
177
- const stem = trimmed.endsWith(".json") ? trimmed.slice(0, -5) : trimmed;
178
- return normalizePathToken(stem, "Profile name");
179
- }
180
-
181
- function normalizeProviderName(provider: string): string {
182
- return normalizePathToken(provider, "Provider");
183
- }
184
-
185
- export function resolveProfilePaths(opts?: ProfileIoOptions): ProfilePaths {
186
- const agentDir = opts?.agentDir ?? getAgentDir();
187
- const profilesDir = path.join(agentDir, "profiles", PROFILES_DIR_NAME);
188
- return {
189
- agentDir,
190
- profilesDir,
191
- providersDir: path.join(profilesDir, "providers"),
192
- settingsPath: path.join(agentDir, "settings.json"),
193
- };
194
- }
195
-
196
- export function ensureSubagentProfilesDir(opts?: ProfileIoOptions): string {
197
- const dir = resolveProfilePaths(opts).profilesDir;
198
- fs.mkdirSync(dir, { recursive: true });
199
- return dir;
200
- }
201
-
202
- export function getProviderModelsPath(
203
- provider: string,
204
- opts?: ProfileIoOptions,
205
- ): string {
206
- const normalized = normalizeProviderName(provider);
207
- const dir = resolveProfilePaths(opts).providersDir;
208
- fs.mkdirSync(dir, { recursive: true });
209
- return path.join(dir, `${normalized}.models.json`);
210
- }
211
-
212
- export function validateSubagentProfile(
213
- filePath: string,
214
- parsed: Record<string, unknown>,
215
- ): SubagentProfileFile {
216
- const subagents = parsed.subagents;
217
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) {
218
- throw new Error(`Profile '${filePath}' must contain a 'subagents' object.`);
219
- }
220
- const agentOverrides = (subagents as Record<string, unknown>).agentOverrides;
221
- if (
222
- !agentOverrides ||
223
- typeof agentOverrides !== "object" ||
224
- Array.isArray(agentOverrides)
225
- ) {
226
- throw new Error(
227
- `Profile '${filePath}' must contain 'subagents.agentOverrides' as an object.`,
228
- );
229
- }
230
- for (const [name, value] of Object.entries(agentOverrides)) {
231
- if (!value || typeof value !== "object" || Array.isArray(value)) {
232
- throw new Error(
233
- `Profile '${filePath}' has invalid override '${name}'; expected an object.`,
234
- );
235
- }
236
- const override = value as Record<string, unknown>;
237
- if (override.model !== undefined && typeof override.model !== "string") {
238
- throw new Error(
239
- `Profile '${filePath}' has invalid model for '${name}'; expected a string.`,
240
- );
241
- }
242
- if (
243
- override.thinking !== undefined &&
244
- override.thinking !== false &&
245
- typeof override.thinking !== "string"
246
- ) {
247
- throw new Error(
248
- `Profile '${filePath}' has invalid thinking for '${name}'; expected a string or false.`,
249
- );
250
- }
251
- if (
252
- override.fallbackModels !== undefined &&
253
- override.fallbackModels !== false &&
254
- (!Array.isArray(override.fallbackModels) ||
255
- override.fallbackModels.some((item) => typeof item !== "string"))
256
- ) {
257
- throw new Error(
258
- `Profile '${filePath}' has invalid fallbackModels for '${name}'; expected an array of strings or false.`,
259
- );
260
- }
261
- }
262
- const disableBuiltins = (subagents as Record<string, unknown>).disableBuiltins;
263
- if (disableBuiltins !== undefined && typeof disableBuiltins !== "boolean") {
264
- throw new Error(
265
- `Profile '${filePath}' has invalid subagents.disableBuiltins; expected a boolean.`,
266
- );
267
- }
268
- // SAFETY: readJsonObjectFile guarantees a non-array JSON object; the
269
- // validation above established the subagents/agentOverrides shape, so the
270
- // only fields left (model/thinking/fallbackModels/disableBuiltins) were all
271
- // type-checked in this function. The double cast just narrows the leftover
272
- // `unknown` fields to their declared types.
273
- return parsed as unknown as SubagentProfileFile;
274
- }
275
-
276
- export function listSubagentProfiles(opts?: ProfileIoOptions): string[] {
277
- const dir = ensureSubagentProfilesDir(opts);
278
- return fs
279
- .readdirSync(dir, { withFileTypes: true })
280
- .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
281
- .map((entry) => entry.name.slice(0, -5))
282
- .sort((a, b) => a.localeCompare(b));
283
- }
284
-
285
- export function readSubagentProfile(
286
- name: string,
287
- opts?: ProfileIoOptions,
288
- ): { filePath: string; profile: SubagentProfileFile } {
289
- const filePath = path.join(
290
- ensureSubagentProfilesDir(opts),
291
- `${normalizeProfileName(name)}.json`,
292
- );
293
- if (!fs.existsSync(filePath)) throw new Error(`Profile not found: ${name}`);
294
- const parsed = readJsonObjectFile(filePath);
295
- return { filePath, profile: validateSubagentProfile(filePath, parsed) };
296
- }
297
-
298
- export function readSettingsFile(filePath: string): Record<string, unknown> {
299
- if (!fs.existsSync(filePath)) return {};
300
- return readJsonObjectFile(filePath);
301
- }
302
-
303
- /**
304
- * Copy a profile's `agentOverrides` into user settings.
305
- *
306
- * Unrelated `subagents` keys (modelScope, herdr, disableBuiltins, …) survive
307
- * the switch; the profile owns the complete agent→model mapping.
308
- */
309
- export function applySubagentProfile(
310
- name: string,
311
- opts?: ProfileIoOptions,
312
- ): { filePath: string; settingsPath: string } {
313
- const { filePath, profile } = readSubagentProfile(name, opts);
314
- const settingsPath = resolveProfilePaths(opts).settingsPath;
315
- const settings = readSettingsFile(settingsPath);
316
- const existing =
317
- settings.subagents &&
318
- typeof settings.subagents === "object" &&
319
- !Array.isArray(settings.subagents)
320
- ? (settings.subagents as Record<string, unknown>)
321
- : {};
322
- settings.subagents = {
323
- ...existing,
324
- ...profile.subagents,
325
- agentOverrides: profile.subagents.agentOverrides,
326
- };
327
- writeJsonFile(settingsPath, settings);
328
- return { filePath, settingsPath };
329
- }
330
-
331
- export function readProviderModelCatalog(
332
- provider: string,
333
- opts?: ProfileIoOptions,
334
- ): ProviderModelCatalogFile | null {
335
- const filePath = getProviderModelsPath(provider, opts);
336
- if (!fs.existsSync(filePath)) return null;
337
- // SAFETY: readJsonObjectFile guarantees a non-array JSON object. A missing
338
- // or malformed catalog is handled by callers (isProviderModelCatalogStale /
339
- // validation at generate time); the cast narrows the JSON payload to the
340
- // catalog shape written by this package itself.
341
- return readJsonObjectFile(filePath) as unknown as ProviderModelCatalogFile;
342
- }
343
-
344
- export function isProviderModelCatalogStale(
345
- catalog: ProviderModelCatalogFile,
346
- maxAgeDays = DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS,
347
- now = Date.now(),
348
- ): boolean {
349
- const refreshedAt = Date.parse(catalog.refreshedAt);
350
- if (!Number.isFinite(refreshedAt)) return true;
351
- return now - refreshedAt > maxAgeDays * 24 * 60 * 60 * 1000;
352
- }
353
-
354
- function catalogModelIsUsable(model: ProviderModelCatalogModel): boolean {
355
- return (
356
- model.observed.availableInRegistry &&
357
- model.observed.probe.status !== "unavailable" &&
358
- model.observed.probe.status !== "auth" &&
359
- model.observed.probe.status !== "timeout" &&
360
- model.observed.probe.status !== "error"
361
- );
362
- }
363
-
364
- export function countHeuristicFallbackModels(
365
- catalog: ProviderModelCatalogFile,
366
- ): number {
367
- return catalog.models.filter((model) =>
368
- usesHeuristicClassification(model.derived.classificationSources),
369
- ).length;
370
- }
371
-
372
- function thinkingLevelsOf(model: RegistryModelLike): string[] {
373
- const map = model.thinkingLevelMap;
374
- if (!map) return model.reasoning ? [...THINKING_LEVELS] : [];
375
- return THINKING_LEVELS.filter((level) => map[level] !== null);
376
- }
377
-
378
- function resolveProbeStatus(text: string, timedOut: boolean): ProbeStatus {
379
- if (timedOut) return "timeout";
380
- if (!text) return "error";
381
- if (/(unauthori[sz]ed|forbidden|api key|auth|billing|credit|quota)/i.test(text)) {
382
- return "auth";
383
- }
384
- if (
385
- /(not found|unknown model|model unavailable|model disabled|unsupported model|unavailable)/i.test(
386
- text,
387
- )
388
- ) {
389
- return "unavailable";
390
- }
391
- return "error";
392
- }
393
-
394
- export async function probeModel(
395
- pi: ProbeExec,
396
- fullId: string,
397
- ): Promise<{ status: ProbeStatus; message?: string }> {
398
- if (typeof pi.exec !== "function") {
399
- return {
400
- status: "skipped",
401
- message: "pi.exec is unavailable in this runtime.",
402
- };
403
- }
404
- const result = await pi.exec(
405
- "pi",
406
- ["-p", "--model", fullId, "--no-tools", 'Reply with exactly "OK".'],
407
- { cwd: os.tmpdir(), timeout: 45_000 },
408
- );
409
- const stdout = typeof result.stdout === "string" ? result.stdout.trim() : "";
410
- const stderr = typeof result.stderr === "string" ? result.stderr.trim() : "";
411
- const combined = [stderr, stdout].filter(Boolean).join("\n").trim();
412
- if (result.code === 0) {
413
- return { status: "ok", message: stdout || "Probe succeeded." };
414
- }
415
- return {
416
- status: resolveProbeStatus(combined, result.killed === true),
417
- message: combined || `Probe exited with code ${result.code ?? "unknown"}.`,
418
- };
419
- }
420
-
421
- export function findRegistryModel(
422
- modelId: string,
423
- available: RegistryModelLike[],
424
- ): RegistryModelLike | undefined {
425
- const { baseModel } = splitThinkingSuffix(modelId);
426
- const slash = baseModel.indexOf("/");
427
- if (slash === -1) return available.find((model) => model.id === baseModel);
428
- const provider = baseModel.slice(0, slash);
429
- const id = baseModel.slice(slash + 1);
430
- return available.find(
431
- (model) => model.provider === provider && model.id === id,
432
- );
433
- }
434
-
435
- function rankedFromCatalog(
436
- model: ProviderModelCatalogModel,
437
- ): ProviderModelCatalogModel & {
438
- fullId: string;
439
- profileRank: number;
440
- cost?: RegistryModelLike["cost"];
441
- reasoning?: boolean;
442
- contextWindow?: number;
443
- maxTokens?: number;
444
- } {
445
- return {
446
- ...model,
447
- profileRank: model.derived.profileRank,
448
- cost: model.observed.cost,
449
- reasoning: model.observed.reasoning,
450
- contextWindow: model.observed.contextWindow,
451
- maxTokens: model.observed.maxTokens,
452
- };
453
- }
454
-
455
- export async function refreshProviderModelCatalog(
456
- pi: ProbeExec,
457
- registry: ModelRegistryLike,
458
- provider: string,
459
- options: {
460
- force?: boolean;
461
- maxAgeDays?: number;
462
- probe?: boolean;
463
- agentDir?: string;
464
- now?: () => number;
465
- } = {},
466
- ): Promise<{
467
- filePath: string;
468
- catalog: ProviderModelCatalogFile;
469
- reused: boolean;
470
- heuristicFallbackCount: number;
471
- }> {
472
- const normalizedProvider = normalizeProviderName(provider);
473
- const maxAgeDays = options.maxAgeDays ?? DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS;
474
- const filePath = getProviderModelsPath(normalizedProvider, options);
475
- if (!options.force) {
476
- const existing = readProviderModelCatalog(normalizedProvider, options);
477
- if (
478
- existing &&
479
- !isProviderModelCatalogStale(
480
- existing,
481
- maxAgeDays,
482
- options.now?.() ?? Date.now(),
483
- )
484
- ) {
485
- return {
486
- filePath,
487
- catalog: existing,
488
- reused: true,
489
- heuristicFallbackCount: countHeuristicFallbackModels(existing),
490
- };
491
- }
492
- }
493
-
494
- const availableModels = registry
495
- .getAvailable()
496
- .filter((model) => model.provider === normalizedProvider);
497
- if (availableModels.length === 0) {
498
- throw new Error(
499
- `No models found in the current registry for provider '${normalizedProvider}'.`,
500
- );
501
- }
502
-
503
- const observed: Array<{
504
- model: RegistryModelLike;
505
- fullId: string;
506
- probe: { status: ProbeStatus; message?: string };
507
- }> = [];
508
- for (const model of availableModels) {
509
- const fullId = `${model.provider}/${model.id}`;
510
- const probe =
511
- options.probe === false
512
- ? { status: "skipped" as const, message: "Live probing disabled." }
513
- : await probeModel(pi, fullId);
514
- observed.push({ model, fullId, probe });
515
- }
516
-
517
- const classificationContext = buildClassificationContext(
518
- observed.map(({ model }) => ({
519
- id: model.id,
520
- ...(typeof model.name === "string" ? { name: model.name } : {}),
521
- ...(typeof model.reasoning === "boolean"
522
- ? { reasoning: model.reasoning }
523
- : {}),
524
- ...(typeof model.contextWindow === "number"
525
- ? { contextWindow: model.contextWindow }
526
- : {}),
527
- ...(typeof model.maxTokens === "number"
528
- ? { maxTokens: model.maxTokens }
529
- : {}),
530
- ...(model.cost && typeof model.cost === "object"
531
- ? { cost: model.cost }
532
- : {}),
533
- })),
534
- );
535
-
536
- const models: ProviderModelCatalogModel[] = [];
537
- for (const { model, fullId, probe } of observed) {
538
- const classification = classifyModel(
539
- {
540
- id: model.id,
541
- ...(typeof model.name === "string" ? { name: model.name } : {}),
542
- ...(typeof model.reasoning === "boolean"
543
- ? { reasoning: model.reasoning }
544
- : {}),
545
- ...(typeof model.contextWindow === "number"
546
- ? { contextWindow: model.contextWindow }
547
- : {}),
548
- ...(typeof model.maxTokens === "number"
549
- ? { maxTokens: model.maxTokens }
550
- : {}),
551
- ...(model.cost && typeof model.cost === "object"
552
- ? { cost: model.cost }
553
- : {}),
554
- },
555
- classificationContext,
556
- );
557
- const warnings = usesHeuristicClassification(
558
- classification.classificationSources,
559
- )
560
- ? ["Classification fell back to name heuristics."]
561
- : [];
562
- models.push({
563
- id: model.id,
564
- fullId,
565
- observed: {
566
- availableInRegistry: true,
567
- ...(typeof model.name === "string" ? { name: model.name } : {}),
568
- ...(typeof model.reasoning === "boolean"
569
- ? { reasoning: model.reasoning }
570
- : {}),
571
- thinkingLevels: thinkingLevelsOf(model),
572
- ...(typeof model.contextWindow === "number"
573
- ? { contextWindow: model.contextWindow }
574
- : {}),
575
- ...(typeof model.maxTokens === "number"
576
- ? { maxTokens: model.maxTokens }
577
- : {}),
578
- ...(model.cost && typeof model.cost === "object"
579
- ? { cost: model.cost }
580
- : {}),
581
- probe: {
582
- status: probe.status,
583
- checkedAt: new Date(
584
- options.now?.() ?? Date.now(),
585
- ).toISOString(),
586
- ...(probe.message ? { message: probe.message } : {}),
587
- },
588
- },
589
- derived: classification,
590
- warnings,
591
- notes: [],
592
- });
593
- }
594
- models.sort(
595
- (a, b) =>
596
- a.derived.profileRank - b.derived.profileRank ||
597
- a.fullId.localeCompare(b.fullId),
598
- );
599
-
600
- const catalog: ProviderModelCatalogFile = {
601
- provider: normalizedProvider,
602
- refreshedAt: new Date(options.now?.() ?? Date.now()).toISOString(),
603
- maxAgeDays,
604
- sources: [
605
- "runtime-registry",
606
- ...(options.probe === false ? [] : ["live-probe"]),
607
- "heuristic-classifier",
608
- ],
609
- models,
610
- };
611
- writeJsonFile(filePath, catalog);
612
- return {
613
- filePath,
614
- catalog,
615
- reused: false,
616
- heuristicFallbackCount: countHeuristicFallbackModels(catalog),
617
- };
618
- }
619
-
620
- export async function generateProfilesForProvider(
621
- pi: ProbeExec,
622
- registry: ModelRegistryLike,
623
- provider: string,
624
- options: {
625
- maxAgeDays?: number;
626
- forceRefresh?: boolean;
627
- probe?: boolean;
628
- agentDir?: string;
629
- } = {},
630
- ): Promise<{
631
- quotaPath: string;
632
- qualityPath: string;
633
- catalogPath: string;
634
- quotaModels: { cheap: string; medium: string; strong: string };
635
- qualityModels: { cheap: string; medium: string; strong: string };
636
- heuristicFallbackCount: number;
637
- selectedHeuristicFallbackCount: number;
638
- }> {
639
- const normalizedProvider = normalizeProviderName(provider);
640
- const { filePath: catalogPath, catalog, heuristicFallbackCount } =
641
- await refreshProviderModelCatalog(pi, registry, normalizedProvider, {
642
- maxAgeDays: options.maxAgeDays,
643
- force: options.forceRefresh,
644
- probe: options.probe,
645
- agentDir: options.agentDir,
646
- });
647
- const usableModels = catalog.models.filter(catalogModelIsUsable);
648
- const profileModels = filterDominatedModels(
649
- usableModels.map(rankedFromCatalog),
650
- );
651
- if (profileModels.length === 0) {
652
- throw new Error(
653
- `Provider '${normalizedProvider}' has no usable models after filtering.`,
654
- );
655
- }
656
- const quotaModels = pickTierModels(profileModels, "quota");
657
- const qualityModels = pickTierModels(profileModels, "quality");
658
- const dir = ensureSubagentProfilesDir(options);
659
- const quotaPath = path.join(dir, `${normalizedProvider}.quota.json`);
660
- const qualityPath = path.join(dir, `${normalizedProvider}.quality.json`);
661
- writeJsonFile(quotaPath, buildProfileFile(quotaModels));
662
- writeJsonFile(qualityPath, buildProfileFile(qualityModels));
663
- const selectedModels = new Set([
664
- ...Object.values(quotaModels),
665
- ...Object.values(qualityModels),
666
- ]);
667
- const selectedHeuristicFallbackCount = profileModels.filter(
668
- (model) =>
669
- selectedModels.has(model.fullId) &&
670
- usesHeuristicClassification(model.derived.classificationSources),
671
- ).length;
672
- return {
673
- quotaPath,
674
- qualityPath,
675
- catalogPath,
676
- quotaModels,
677
- qualityModels,
678
- heuristicFallbackCount,
679
- selectedHeuristicFallbackCount,
680
- };
681
- }
682
-
683
- export function getProfileWorkerModel(
684
- profile: SubagentProfileFile,
685
- ): string | undefined {
686
- const model = profile.subagents.agentOverrides.worker?.model;
687
- return typeof model === "string" && model.trim() ? model.trim() : undefined;
688
- }
689
-
690
- export async function checkSubagentProfile(
691
- pi: ProbeExec,
692
- registry: ModelRegistryLike,
693
- name: string,
694
- options: { agentDir?: string; probe?: boolean } = {},
695
- ): Promise<ProfileCheckResult> {
696
- const { filePath, profile } = readSubagentProfile(name, options);
697
- const available = registry.getAvailable();
698
- const entries = Object.entries(profile.subagents.agentOverrides)
699
- .filter(
700
- ([, value]) => typeof value?.model === "string" && value.model.trim(),
701
- )
702
- .map(([agent, value]) => ({ agent, model: value.model!.trim() }));
703
- const probeCache = new Map<string, { status: ProbeStatus; message?: string }>();
704
- const results: ProfileCheckResult["results"] = [];
705
- for (const entry of entries) {
706
- const found = findRegistryModel(entry.model, available);
707
- const { thinking } = splitThinkingSuffix(entry.model);
708
- const probeModelId = found
709
- ? `${found.provider}/${found.id}${thinking ? `:${thinking}` : ""}`
710
- : entry.model;
711
- let probe = probeCache.get(probeModelId);
712
- if (!probe) {
713
- probe =
714
- options.probe === false
715
- ? { status: "skipped", message: "Live probing disabled." }
716
- : await probeModel(pi, probeModelId);
717
- probeCache.set(probeModelId, probe);
718
- }
719
- results.push({
720
- agent: entry.agent,
721
- model: entry.model,
722
- inRegistry: found !== undefined,
723
- probe,
724
- });
725
- }
726
- return { profileName: name, filePath, results };
727
- }
728
-
729
- /** @internal re-export so callers can name a kind without importing classify. */
730
- export type { ProfileKind, SubagentProfileFile };