@causyne/agent 1.20.7 → 1.20.8

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.
@@ -10,6 +10,7 @@
10
10
  //
11
11
  // ZERO-MALWARE: Pure TypeScript/ESM. Strictly respects timeouts, no secret leakage, no unprompted background calls.
12
12
 
13
+ import crypto from 'node:crypto';
13
14
  import fs from 'node:fs';
14
15
  import path from 'node:path';
15
16
  import { execFile } from 'node:child_process';
@@ -17,26 +18,42 @@ import { promisify } from 'node:util';
17
18
  import { causyneHome } from './utils/paths.js';
18
19
  import { MODEL_CATALOGUE, PEER_MODEL_CATALOGUE, DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
19
20
  import {
21
+ BASELINE_ANTIGRAVITY_MODELS,
20
22
  ANTIGRAVITY_MODELS,
23
+ ANTIGRAVITY_MODEL_IDS,
21
24
  ANTIGRAVITY_LABEL_BY_ID,
22
25
  registerAntigravityModel,
26
+ replaceAntigravityModels,
23
27
  parseAgyModelsOutput,
28
+ isAntigravityOnboarded,
24
29
  resolveAgyBinary
25
30
  } from './providers/antigravity.js';
26
- import { isBinaryOnPath, BUILTIN_PEER_PRESETS } from './acp/agentCatalog.js';
31
+ import {
32
+ isBinaryOnPath,
33
+ BUILTIN_PEER_PRESETS,
34
+ probePresetAuth,
35
+ testPeerHandshake
36
+ } from './acp/agentCatalog.js';
37
+ import { getPeerProfile } from './acp/peerProfiles.js';
27
38
 
28
39
  const execFileAsync = promisify(execFile);
29
40
 
41
+ export interface DynamicCatalogueCacheEntry {
42
+ timestamp: number;
43
+ models: string[];
44
+ fingerprint?: string | undefined;
45
+ currentModel?: string | undefined;
46
+ modelIdMap?: Record<string, string> | undefined;
47
+ }
48
+
30
49
  export interface DynamicCatalogueCache {
31
50
  version: 1;
32
51
  updatedAt: string;
33
- providers: Record<string, {
34
- timestamp: number;
35
- models: string[];
36
- }>;
52
+ providers: Record<string, DynamicCatalogueCacheEntry>;
37
53
  }
38
54
 
39
- const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
55
+ const BYOK_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour for cloud API model lists
56
+ const PEER_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes for fluctuating local/ACP peer tiers
40
57
  const REQUEST_TIMEOUT_MS = 3500; // Fast timeout to never block user interaction
41
58
 
42
59
  export function cacheFilePath(): string {
@@ -79,11 +96,11 @@ export function peerIdFromProviderKey(provider: string): string | null {
79
96
  return peer || null;
80
97
  }
81
98
 
82
- /** Get the static curated models for a provider id. */
99
+ /** Get the static curated baseline models for a provider id (offline fallback). */
83
100
  export function getCuratedModels(provider: string): string[] {
84
101
  const norm = normalizeProviderKey(provider);
85
- if (norm === 'antigravity') return [...ANTIGRAVITY_MODELS];
86
- if (norm === 'pi') return [...(MODEL_CATALOGUE['Pi (Local Peer)'] || [])];
102
+ if (norm === 'antigravity') return Object.keys(BASELINE_ANTIGRAVITY_MODELS);
103
+ if (norm === 'pi') return [...(MODEL_CATALOGUE['Pi (Local Peer)'] || ['default'])];
87
104
  const peer = peerIdFromProviderKey(norm);
88
105
  if (peer) return [...(PEER_MODEL_CATALOGUE[peer] ?? [])];
89
106
  if (norm === 'acp') return [...(MODEL_CATALOGUE['ACP (Peer Agents)'] ?? [])];
@@ -107,6 +124,115 @@ export function getCuratedModels(provider: string): string[] {
107
124
  return [];
108
125
  }
109
126
 
127
+ function isLocalOrAcpProvider(norm: string): boolean {
128
+ return norm === 'antigravity' || norm === 'pi' || norm === 'acp' || peerIdFromProviderKey(norm) !== null;
129
+ }
130
+
131
+ function statSignature(filePath: string): string {
132
+ try {
133
+ if (!fs.existsSync(filePath)) return 'missing';
134
+ const stat = fs.statSync(filePath);
135
+ return `${Math.floor(stat.mtimeMs)}:${stat.size}`;
136
+ } catch {
137
+ return 'err';
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Compute a fast, non-secret fingerprint of a provider's local auth/account/config state.
143
+ * When a user switches accounts, upgrades tiers (e.g. Starter -> Pro -> Ultra), or edits
144
+ * their CLI settings, the fingerprint changes and invalidates stale cached models immediately.
145
+ */
146
+ export function computeProviderAuthFingerprint(
147
+ provider: string,
148
+ config: { apiKey?: string; baseUrl?: string; providerKeys?: Record<string, string> } = {}
149
+ ): string {
150
+ const norm = normalizeProviderKey(provider);
151
+ const home = process.env.HOME || process.env.USERPROFILE || '';
152
+ const parts: string[] = [norm];
153
+
154
+ if (norm === 'antigravity') {
155
+ parts.push(
156
+ statSignature(path.join(home, '.gemini', 'oauth_creds.json')),
157
+ statSignature(path.join(home, '.gemini', 'google_accounts.json')),
158
+ statSignature(path.join(home, '.gemini', 'antigravity-cli', 'settings.json')),
159
+ statSignature(path.join(home, '.gemini', 'antigravity-cli', 'cache', 'onboarding.json'))
160
+ );
161
+ } else if (norm === 'pi') {
162
+ parts.push(
163
+ statSignature(path.join(home, '.pi', 'agent', 'models.json')),
164
+ statSignature(path.join(home, '.pi', 'agent', 'auth.json')),
165
+ statSignature(path.join(home, '.pi', 'agent', 'settings.json')),
166
+ statSignature(path.join(home, '.config', 'pi', 'config.json'))
167
+ );
168
+ } else if (peerIdFromProviderKey(norm)) {
169
+ const peer = peerIdFromProviderKey(norm)!;
170
+ const peerFiles: Record<string, string[]> = {
171
+ opencode: [
172
+ path.join(home, '.config', 'opencode', 'opencode.json'),
173
+ path.join(home, '.config', 'opencode', 'config.json'),
174
+ path.join(home, '.local', 'share', 'opencode', 'auth.json'),
175
+ path.join(home, '.opencode', 'config.json')
176
+ ],
177
+ claude: [
178
+ path.join(home, '.claude', 'settings.json'),
179
+ path.join(home, '.claude.json'),
180
+ path.join(home, '.config', 'claude', 'config.json')
181
+ ],
182
+ codex: [
183
+ path.join(home, '.codex', 'auth.json'),
184
+ path.join(home, '.codex', 'config.toml'),
185
+ path.join(home, '.codex', 'config.json')
186
+ ],
187
+ gemini: [
188
+ path.join(home, '.gemini', 'oauth_creds.json'),
189
+ path.join(home, '.gemini', 'google_accounts.json'),
190
+ path.join(home, '.gemini', 'settings.json')
191
+ ],
192
+ cursor: [
193
+ path.join(home, '.cursor', 'cli-config.json'),
194
+ path.join(home, '.config', 'cursor', 'auth.json')
195
+ ],
196
+ qwen: [
197
+ path.join(home, '.qwen', 'oauth_creds.json'),
198
+ path.join(home, '.qwen', 'settings.json')
199
+ ],
200
+ copilot: [
201
+ path.join(home, '.config', 'github-copilot', 'hosts.json'),
202
+ path.join(home, '.config', 'github-copilot', 'apps.json')
203
+ ],
204
+ kimi: [
205
+ path.join(home, '.kimi', 'config.toml'),
206
+ path.join(home, '.kimi', 'config.json')
207
+ ],
208
+ goose: [
209
+ path.join(home, '.config', 'goose', 'config.yaml'),
210
+ path.join(home, '.config', 'goose', 'profiles.yaml')
211
+ ],
212
+ hermes: [
213
+ path.join(home, '.hermes', 'config.yaml'),
214
+ path.join(home, '.hermes', 'config.json')
215
+ ]
216
+ };
217
+ for (const file of peerFiles[peer] || []) {
218
+ parts.push(statSignature(file));
219
+ }
220
+ if (peer === 'claude') {
221
+ parts.push(process.env.ANTHROPIC_MODEL || '', process.env.CLAUDE_MODEL || '', String(Boolean(process.env.ANTHROPIC_API_KEY)));
222
+ } else if (peer === 'codex') {
223
+ parts.push(process.env.OPENAI_MODEL || '', String(Boolean(process.env.OPENAI_API_KEY)));
224
+ } else if (peer === 'gemini') {
225
+ parts.push(process.env.GEMINI_MODEL || '', String(Boolean(process.env.GEMINI_API_KEY)));
226
+ }
227
+ } else {
228
+ const key = config.apiKey || (config.providerKeys && config.providerKeys[norm]) || '';
229
+ const keyDigest = key ? crypto.createHash('sha256').update(key).digest('hex').slice(0, 12) : 'nokey';
230
+ parts.push(keyDigest, config.baseUrl || '');
231
+ }
232
+
233
+ return crypto.createHash('sha256').update(parts.join('|')).digest('hex').slice(0, 16);
234
+ }
235
+
110
236
  export interface ByokProviderInfo {
111
237
  id: string;
112
238
  label: string;
@@ -210,14 +336,16 @@ export function getAvailableProvidersOverview(
210
336
  || Boolean(config.providerKeys && (config.providerKeys[def.id] || (def.id === 'qwen' && config.providerKeys['dashscope-byok'])))
211
337
  || Boolean(def.envVar && process.env[def.envVar]);
212
338
  const isConfigured = def.id === 'ollama' || hasStoredKey;
339
+ const cachedByok = getCachedModels(def.id, config);
340
+ const models = cachedByok && cachedByok.length > 0 ? [...cachedByok] : def.models;
213
341
 
214
342
  return {
215
343
  id: def.id,
216
344
  label: def.label,
217
345
  isConfigured,
218
346
  isCurrent,
219
- models: def.models,
220
- defaultModel: def.defaultModel,
347
+ models,
348
+ defaultModel: models[0] || def.defaultModel,
221
349
  envVar: def.envVar
222
350
  };
223
351
  });
@@ -226,6 +354,10 @@ export function getAvailableProvidersOverview(
226
354
 
227
355
  // Antigravity (special native local provider)
228
356
  const hasAgy = Boolean(resolveAgyBinary());
357
+ const cachedAgyModels = getCachedModels('antigravity', config);
358
+ const agyModels = cachedAgyModels && cachedAgyModels.length > 0
359
+ ? replaceAntigravityModels(cachedAgyModels)
360
+ : [...ANTIGRAVITY_MODELS];
229
361
  acpPeers.push({
230
362
  id: 'antigravity',
231
363
  providerKey: 'antigravity',
@@ -234,16 +366,21 @@ export function getAvailableProvidersOverview(
234
366
  status: hasAgy ? 'ready' : 'not_installed',
235
367
  isCurrent: currentProvider === 'antigravity',
236
368
  command: 'agy --output-format json',
237
- models: [...ANTIGRAVITY_MODELS],
369
+ models: agyModels,
238
370
  setupInstruction: 'Install Antigravity IDE or agy CLI to enable Google AGY models.'
239
371
  });
240
372
 
241
373
  const hasPi = isBinaryOnPath('pi');
374
+ const cachedPiModels = getCachedModels('pi', config);
375
+ const configPiModels = detectPeerConfigModels('pi');
376
+ const piModels = (cachedPiModels && cachedPiModels.length > 0)
377
+ ? [...cachedPiModels]
378
+ : (configPiModels.length > 0 ? configPiModels : ['default']);
242
379
  acpPeers.push({
243
380
  id: 'pi', providerKey: 'pi', label: 'Pi coding agent',
244
381
  installed: hasPi, status: hasPi ? 'ready' : 'not_installed',
245
382
  isCurrent: currentProvider === 'pi', command: 'pi --mode rpc --no-tools',
246
- models: ['default'],
383
+ models: piModels,
247
384
  setupInstruction: 'Install Pi CLI and configure its model login before selecting it in Causyne.'
248
385
  });
249
386
 
@@ -263,12 +400,15 @@ export function getAvailableProvidersOverview(
263
400
  const providerKey = `acp/${preset.id}`;
264
401
  const isCurrent = currentProvider === providerKey;
265
402
 
266
- const cachedPeerModels = getCachedModels(providerKey) || getCachedModels(preset.id);
403
+ const cachedPeerModels = getCachedModels(providerKey, config) || getCachedModels(preset.id, config);
404
+ const localConfigModels = detectPeerConfigModels(preset.id);
267
405
  let models: string[] = [];
268
406
  if (cachedPeerModels && cachedPeerModels.length > 0) {
269
407
  models = [...cachedPeerModels];
270
408
  } else if (preset.id === 'claude') {
271
409
  models = detectClaudeModels();
410
+ } else if (localConfigModels.length > 0) {
411
+ models = [...new Set([...localConfigModels, ...(PEER_MODEL_CATALOGUE[preset.id] || [])])];
272
412
  } else if (PEER_MODEL_CATALOGUE[preset.id]) {
273
413
  models = [...(PEER_MODEL_CATALOGUE[preset.id] || [])];
274
414
  } else if (DEFAULT_MODEL_BY_PROVIDER[providerKey]) {
@@ -277,6 +417,12 @@ export function getAvailableProvidersOverview(
277
417
  models = [preset.id];
278
418
  }
279
419
 
420
+ // A saved preference is not evidence that the active peer still offers it.
421
+ // Only retain it as a fallback when no fresh peer model list is cached.
422
+ if (isCurrent && currentModel && !cachedPeerModels && !models.includes(currentModel)) {
423
+ models = [currentModel, ...models];
424
+ }
425
+
280
426
  acpPeers.push({
281
427
  id: preset.id,
282
428
  providerKey,
@@ -299,6 +445,7 @@ export function getAvailableProvidersOverview(
299
445
  }
300
446
 
301
447
  const MODEL_LIST_TIMEOUT_MS = 8000;
448
+ const ACP_DISCOVERY_TIMEOUT_MS = 4500;
302
449
  const ANSI_ESCAPE = /\u001b\[[0-9;]*[A-Za-z]/g;
303
450
 
304
451
  const PEER_MODEL_COMMANDS: Record<string, { command: string; args: string[] }> = {
@@ -311,7 +458,8 @@ async function runModelList(command: string, args: string[]): Promise<string[]>
311
458
  const { stdout } = await execFileAsync(command, args, {
312
459
  timeout: MODEL_LIST_TIMEOUT_MS,
313
460
  maxBuffer: 4 * 1024 * 1024,
314
- windowsHide: true
461
+ windowsHide: true,
462
+ env: { ...process.env, CI: '1', BROWSER: 'false', NO_BROWSER: '1' }
315
463
  });
316
464
  return stdout.replace(ANSI_ESCAPE, '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
317
465
  } catch {
@@ -319,91 +467,362 @@ async function runModelList(command: string, args: string[]): Promise<string[]>
319
467
  }
320
468
  }
321
469
 
322
- function parseModelIds(lines: string[]): string[] {
470
+ export function parseModelIds(lines: string[]): string[] {
323
471
  const models: string[] = [];
324
472
  for (const rawLine of lines) {
325
473
  const line = rawLine.replace(ANSI_ESCAPE, '').trim();
326
474
  if (!line) continue;
327
- if (/^(fetching|loading|no models|error)/i.test(line)) continue;
328
- if (line.endsWith('…') || line.endsWith('...')) continue;
329
- const match = line.match(/^([a-z0-9_./-]+)/i);
475
+ if (/^(fetching|loading|no models|error|warning|usage|available|use\s|see\s|run\s|help|models|provider\s+model|id\s+name|default|configured|login|please|note:|tip:|info:)/i.test(line)) {
476
+ continue;
477
+ }
478
+ if (line.endsWith('…') || line.endsWith('...') || line.endsWith(':')) continue;
479
+ if (/^(\/|~|\.|--|http:\/\/|https:\/\/)/i.test(line)) continue;
480
+ const match = line.match(/^([a-z0-9][a-z0-9_.:/-]*)/i);
330
481
  if (match && match[1]) {
331
- models.push(match[1]);
482
+ const candidate = match[1].replace(/[.,;:]+$/, '');
483
+ if (!candidate || candidate.length < 2) continue;
484
+ if (/^(node_modules|provider|model|context|thinking|images|none|null|undefined)$/i.test(candidate)) continue;
485
+ if (/\.(md|json|js|ts|yaml|yml|toml|txt|html)$/i.test(candidate)) continue;
486
+ models.push(candidate);
332
487
  }
333
488
  }
334
489
  return [...new Set(models)];
335
490
  }
336
491
 
337
- function detectClaudeModels(): string[] {
492
+ export function parsePiModelsOutput(stdout: string): string[] {
493
+ const models: string[] = [];
494
+ if (!stdout || typeof stdout !== 'string') return models;
495
+ const lines = stdout.replace(ANSI_ESCAPE, '').split(/\r?\n/);
496
+ for (const rawLine of lines) {
497
+ const line = rawLine.trim();
498
+ if (!line) continue;
499
+ if (/^(no models|warning|error|use\s+\/login|see:|provider\s+model)/i.test(line)) continue;
500
+ if (/^(\/|~|\.|http:\/\/|https:\/\/)/i.test(line)) continue;
501
+ const cols = line.split(/\s{2,}/).map(c => c.trim()).filter(Boolean);
502
+ if (cols.length >= 2) {
503
+ const provider = cols[0]!;
504
+ const model = cols[1]!;
505
+ if (provider.toLowerCase() === 'provider' && model.toLowerCase() === 'model') continue;
506
+ if (/^[a-z0-9_.-]+$/i.test(provider) && /^[a-z0-9_.:/-]+$/i.test(model)) {
507
+ models.push(model.includes('/') ? model : `${provider}/${model}`);
508
+ }
509
+ }
510
+ }
511
+ return [...new Set(models)];
512
+ }
513
+
514
+ /**
515
+ * Inspect local CLI configuration files (JSON/TOML/YAML) and environment variables
516
+ * to discover user-configured models for a peer agent with zero process overhead.
517
+ */
518
+ export function detectPeerConfigModels(peerId: string): string[] {
519
+ const peer = (peerId || '').toLowerCase().trim();
338
520
  const models: string[] = [];
521
+ const home = process.env.HOME || process.env.USERPROFILE || '';
522
+
523
+ const addModel = (val: unknown): void => {
524
+ if (typeof val === 'string' && val.trim()) {
525
+ const clean = val.trim();
526
+ if (!models.includes(clean)) models.push(clean);
527
+ }
528
+ };
529
+
339
530
  try {
340
- const home = process.env.HOME || process.env.USERPROFILE || '';
341
- if (home) {
342
- const settingsFile = path.join(home, '.claude', 'settings.json');
343
- if (fs.existsSync(settingsFile)) {
344
- const content = fs.readFileSync(settingsFile, 'utf8');
345
- const parsed = JSON.parse(content) as { model?: string; availableModels?: string[] };
346
- if (typeof parsed?.model === 'string' && parsed.model.trim()) {
347
- models.push(parsed.model.trim());
531
+ if (peer === 'claude') {
532
+ if (home) {
533
+ for (const rel of [['.claude', 'settings.json'], ['.claude.json'], ['.config', 'claude', 'settings.json']]) {
534
+ const file = path.join(home, ...rel);
535
+ if (fs.existsSync(file)) {
536
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, unknown>;
537
+ addModel(parsed?.model);
538
+ addModel(parsed?.defaultModel);
539
+ if (Array.isArray(parsed?.availableModels)) {
540
+ for (const m of parsed.availableModels) addModel(m);
541
+ }
542
+ }
543
+ }
544
+ }
545
+ addModel(process.env.ANTHROPIC_MODEL || process.env.CLAUDE_MODEL);
546
+ } else if (peer === 'codex') {
547
+ addModel(process.env.OPENAI_MODEL);
548
+ if (home) {
549
+ const tomlFile = path.join(home, '.codex', 'config.toml');
550
+ if (fs.existsSync(tomlFile)) {
551
+ const content = fs.readFileSync(tomlFile, 'utf8');
552
+ for (const match of content.matchAll(/^\s*model\s*=\s*["']([^"']+)["']/gm)) {
553
+ addModel(match[1]);
554
+ }
555
+ }
556
+ const jsonFile = path.join(home, '.codex', 'config.json');
557
+ if (fs.existsSync(jsonFile)) {
558
+ const parsed = JSON.parse(fs.readFileSync(jsonFile, 'utf8')) as Record<string, unknown>;
559
+ addModel(parsed?.model);
348
560
  }
349
- if (Array.isArray(parsed?.availableModels)) {
350
- for (const m of parsed.availableModels) {
351
- if (typeof m === 'string' && m.trim()) models.push(m.trim());
561
+ }
562
+ } else if (peer === 'gemini') {
563
+ addModel(process.env.GEMINI_MODEL);
564
+ if (home) {
565
+ const settingsFile = path.join(home, '.gemini', 'settings.json');
566
+ if (fs.existsSync(settingsFile)) {
567
+ const parsed = JSON.parse(fs.readFileSync(settingsFile, 'utf8')) as Record<string, unknown>;
568
+ addModel(parsed?.model);
569
+ addModel(parsed?.selectedModel);
570
+ if (Array.isArray(parsed?.availableModels)) {
571
+ for (const m of parsed.availableModels) addModel(m);
572
+ }
573
+ }
574
+ }
575
+ } else if (peer === 'opencode') {
576
+ if (home) {
577
+ for (const file of [
578
+ path.join(home, '.config', 'opencode', 'opencode.json'),
579
+ path.join(home, '.config', 'opencode', 'config.json'),
580
+ path.join(home, '.opencode', 'config.json')
581
+ ]) {
582
+ if (fs.existsSync(file)) {
583
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, unknown>;
584
+ addModel(parsed?.model);
585
+ addModel(parsed?.small_model);
586
+ if (parsed?.provider && typeof parsed.provider === 'object') {
587
+ for (const [provId, provCfg] of Object.entries(parsed.provider as Record<string, unknown>)) {
588
+ if (provCfg && typeof provCfg === 'object' && 'models' in provCfg) {
589
+ const modelsObj = (provCfg as Record<string, unknown>).models;
590
+ if (modelsObj && typeof modelsObj === 'object') {
591
+ for (const modelKey of Object.keys(modelsObj as Record<string, unknown>)) {
592
+ addModel(modelKey.includes('/') ? modelKey : `${provId}/${modelKey}`);
593
+ }
594
+ }
595
+ }
596
+ }
597
+ }
598
+ }
599
+ }
600
+ }
601
+ } else if (peer === 'qwen') {
602
+ if (home) {
603
+ const settingsFile = path.join(home, '.qwen', 'settings.json');
604
+ if (fs.existsSync(settingsFile)) {
605
+ const parsed = JSON.parse(fs.readFileSync(settingsFile, 'utf8')) as Record<string, unknown>;
606
+ addModel(parsed?.model);
607
+ if (Array.isArray(parsed?.availableModels)) {
608
+ for (const m of parsed.availableModels) addModel(m);
609
+ }
610
+ }
611
+ }
612
+ } else if (peer === 'kimi') {
613
+ if (home) {
614
+ const tomlFile = path.join(home, '.kimi', 'config.toml');
615
+ if (fs.existsSync(tomlFile)) {
616
+ const content = fs.readFileSync(tomlFile, 'utf8');
617
+ for (const match of content.matchAll(/^\s*(?:default_)?model\s*=\s*["']([^"']+)["']/gm)) {
618
+ addModel(match[1]);
619
+ }
620
+ }
621
+ }
622
+ } else if (peer === 'goose') {
623
+ if (home) {
624
+ const yamlFile = path.join(home, '.config', 'goose', 'config.yaml');
625
+ if (fs.existsSync(yamlFile)) {
626
+ const content = fs.readFileSync(yamlFile, 'utf8');
627
+ for (const match of content.matchAll(/^\s*(?:GOOSE_MODEL|model)\s*:\s*["']?([a-zA-Z0-9_.:/-]+)["']?/gm)) {
628
+ addModel(match[1]);
629
+ }
630
+ }
631
+ }
632
+ } else if (peer === 'hermes') {
633
+ if (home) {
634
+ const yamlFile = path.join(home, '.hermes', 'config.yaml');
635
+ if (fs.existsSync(yamlFile)) {
636
+ const content = fs.readFileSync(yamlFile, 'utf8');
637
+ for (const match of content.matchAll(/^\s*(?:default_)?model\s*:\s*["']?([a-zA-Z0-9_.:/-]+)["']?/gm)) {
638
+ addModel(match[1]);
639
+ }
640
+ }
641
+ }
642
+ } else if (peer === 'pi') {
643
+ if (home) {
644
+ const settingsFile = path.join(home, '.pi', 'agent', 'settings.json');
645
+ if (fs.existsSync(settingsFile)) {
646
+ const parsed = JSON.parse(fs.readFileSync(settingsFile, 'utf8')) as Record<string, unknown>;
647
+ const defaultProvider = typeof parsed?.defaultProvider === 'string' ? parsed.defaultProvider.trim() : '';
648
+ const defaultModel = typeof parsed?.defaultModel === 'string' ? parsed.defaultModel.trim() : '';
649
+ if (defaultProvider && defaultModel) {
650
+ addModel(`${defaultProvider}/${defaultModel}`);
651
+ } else {
652
+ addModel(defaultModel || parsed?.model);
653
+ }
654
+ }
655
+ const modelsFile = path.join(home, '.pi', 'agent', 'models.json');
656
+ if (fs.existsSync(modelsFile)) {
657
+ const parsed = JSON.parse(fs.readFileSync(modelsFile, 'utf8')) as Record<string, unknown>;
658
+ if (parsed?.providers && typeof parsed.providers === 'object') {
659
+ for (const [provId, provData] of Object.entries(parsed.providers as Record<string, unknown>)) {
660
+ if (provData && typeof provData === 'object' && Array.isArray((provData as Record<string, unknown>).models)) {
661
+ for (const m of (provData as { models: Array<{ id?: string } | string> }).models) {
662
+ if (typeof m === 'string') addModel(`${provId}/${m}`);
663
+ else if (m && typeof m.id === 'string') addModel(`${provId}/${m.id}`);
664
+ }
665
+ }
666
+ }
352
667
  }
353
668
  }
354
669
  }
355
670
  }
356
671
  } catch {
357
- // Ignore settings read errors
672
+ // Ignore malformed user config files
358
673
  }
359
674
 
360
- const envModel = process.env.ANTHROPIC_MODEL || process.env.CLAUDE_MODEL;
361
- if (envModel && typeof envModel === 'string' && envModel.trim()) {
362
- models.push(envModel.trim());
363
- }
675
+ return models;
676
+ }
364
677
 
678
+ function detectClaudeModels(): string[] {
679
+ const models = detectPeerConfigModels('claude');
365
680
  const curated = PEER_MODEL_CATALOGUE['claude'] ?? ['sonnet', 'opus', 'haiku'];
366
681
  for (const m of curated) {
367
- models.push(m);
682
+ if (!models.includes(m)) models.push(m);
368
683
  }
369
-
370
684
  return [...new Set(models)];
371
685
  }
372
686
 
687
+ /**
688
+ * Probe an ACP peer via zero-token `initialize` + `session/new` handshake to
689
+ * discover the exact live models advertised for the user's current account/tier.
690
+ */
691
+ export async function discoverPeerModelsViaAcp(
692
+ peerId: string,
693
+ timeoutMs = ACP_DISCOVERY_TIMEOUT_MS
694
+ ): Promise<string[]> {
695
+ const peer = (peerId || '').toLowerCase().trim();
696
+ const profile = getPeerProfile(peer);
697
+ const preset = BUILTIN_PEER_PRESETS[peer];
698
+ if (!profile && !preset) return [];
699
+
700
+ if (preset) {
701
+ const hasDirectBinary = isBinaryOnPath(preset.binaryName);
702
+ if (!hasDirectBinary) return [];
703
+ const auth = await probePresetAuth(preset);
704
+ if (!auth.authenticated) return [];
705
+ }
706
+
707
+ const command = profile?.command || preset?.command || peer;
708
+ const args = profile?.args || preset?.args || ['acp'];
709
+ if (!isBinaryOnPath(command)) return [];
710
+
711
+ try {
712
+ const handshake = await testPeerHandshake({
713
+ command,
714
+ args,
715
+ cwd: process.cwd(),
716
+ timeoutMs
717
+ });
718
+ if (handshake.ready && Array.isArray(handshake.availableModels) && handshake.availableModels.length > 0) {
719
+ return [...new Set(handshake.availableModels)];
720
+ }
721
+ } catch {
722
+ // Silent fallback if ACP handshake fails or times out
723
+ }
724
+ return [];
725
+ }
726
+
727
+ /** Discover live models from Pi CLI (`pi --list-models` + local config). */
728
+ export async function discoverPiModels(): Promise<string[]> {
729
+ const configModels = detectPeerConfigModels('pi');
730
+ if (isBinaryOnPath('pi')) {
731
+ try {
732
+ const { stdout } = await execFileAsync('pi', ['--list-models'], {
733
+ timeout: MODEL_LIST_TIMEOUT_MS,
734
+ maxBuffer: 4 * 1024 * 1024,
735
+ windowsHide: true,
736
+ env: { ...process.env, CI: '1', BROWSER: 'false', NO_BROWSER: '1' }
737
+ });
738
+ const parsed = parsePiModelsOutput(stdout);
739
+ if (parsed.length > 0) {
740
+ return [...new Set([...parsed, ...configModels])];
741
+ }
742
+ } catch {
743
+ // Fall back to config or default
744
+ }
745
+ }
746
+ return configModels.length > 0 ? configModels : ['default'];
747
+ }
748
+
373
749
  /**
374
750
  * Ask a peer CLI which models its account can reach. Zero tokens: this runs the
375
- * peer's own listing command, never a model request.
751
+ * peer's own listing command or zero-token ACP session handshake, never a prompt.
376
752
  */
377
- export async function discoverPeerModels(peerId: string): Promise<string[]> {
753
+ export async function discoverPeerModels(
754
+ peerId: string,
755
+ options: { allowAcpHandshake?: boolean } = {}
756
+ ): Promise<string[]> {
378
757
  const peer = (peerId || '').toLowerCase().trim();
379
- if (peer === 'claude') {
380
- return detectClaudeModels();
758
+ if (!peer) return [];
759
+ if (peer === 'pi') {
760
+ return discoverPiModels();
381
761
  }
762
+
763
+ const configModels = detectPeerConfigModels(peer);
764
+
765
+ // 1. Fast CLI `models` subcommand (e.g. `opencode models`, `cursor-agent models`)
382
766
  const listing = PEER_MODEL_COMMANDS[peer];
383
- if (listing) {
767
+ if (listing && isBinaryOnPath(listing.command)) {
384
768
  const discovered = parseModelIds(await runModelList(listing.command, listing.args));
385
- if (discovered.length > 0) return discovered;
769
+ if (discovered.length > 0) {
770
+ return [...new Set([...discovered, ...configModels])];
771
+ }
772
+ }
773
+
774
+ // 2. Zero-token ACP session/new discovery (`configOptions` / `models`)
775
+ const allowHandshake = options.allowAcpHandshake ?? !process.env.NODE_TEST_CONTEXT;
776
+ if (allowHandshake) {
777
+ const acpModels = await discoverPeerModelsViaAcp(peer);
778
+ if (acpModels.length > 0) {
779
+ return [...new Set([...acpModels, ...configModels])];
780
+ }
781
+ }
782
+
783
+ // 3. Local config + curated fallback
784
+ if (peer === 'claude') {
785
+ return detectClaudeModels();
786
+ }
787
+ if (configModels.length > 0) {
788
+ return [...new Set([...configModels, ...(PEER_MODEL_CATALOGUE[peer] || [])])];
386
789
  }
387
790
  return PEER_MODEL_CATALOGUE[peer] ? [...PEER_MODEL_CATALOGUE[peer]] : [];
388
791
  }
389
792
 
390
793
  /** Ask Antigravity for its live model list and return the readable labels. */
391
- export async function discoverAntigravityModels(): Promise<string[]> {
392
- try {
393
- const { stdout } = await execFileAsync(resolveAgyBinary(), ['models'], {
394
- timeout: MODEL_LIST_TIMEOUT_MS,
395
- maxBuffer: 4 * 1024 * 1024,
396
- windowsHide: true
397
- });
398
- const parsed = parseAgyModelsOutput(stdout);
399
- if (parsed.length > 0) {
400
- for (const item of parsed) {
401
- registerAntigravityModel(item.id, item.label);
794
+ export async function discoverAntigravityModels(
795
+ options: { command?: string; forceSpawn?: boolean } = {}
796
+ ): Promise<string[]> {
797
+ const customCommand = options.command;
798
+ const shouldSpawn = Boolean(customCommand)
799
+ || Boolean(options.forceSpawn)
800
+ || (!process.env.NODE_TEST_CONTEXT && isAntigravityOnboarded());
801
+
802
+ if (shouldSpawn) {
803
+ try {
804
+ const bin = customCommand || resolveAgyBinary();
805
+ const { stdout } = await execFileAsync(bin, ['models'], {
806
+ timeout: MODEL_LIST_TIMEOUT_MS,
807
+ maxBuffer: 4 * 1024 * 1024,
808
+ windowsHide: true,
809
+ env: { ...process.env, CI: '1', BROWSER: 'false', NO_BROWSER: '1' }
810
+ });
811
+ const parsed = parseAgyModelsOutput(stdout, { replaceActiveList: true });
812
+ if (parsed.length > 0) {
813
+ const modelIdMap: Record<string, string> = {};
814
+ const labels: string[] = [];
815
+ for (const item of parsed) {
816
+ const label = item.label || item.id;
817
+ modelIdMap[label] = item.id;
818
+ if (!labels.includes(label)) labels.push(label);
819
+ }
820
+ saveCachedModels('antigravity', labels, { modelIdMap });
821
+ return labels;
402
822
  }
403
- return [...new Set(parsed.map((item) => item.label || item.id))];
823
+ } catch {
824
+ // Fall back to current registered or baseline models
404
825
  }
405
- } catch {
406
- // Fall back to current registered or baseline models
407
826
  }
408
827
  return [...ANTIGRAVITY_MODELS];
409
828
  }
@@ -438,34 +857,79 @@ export function writeModelCache(cache: DynamicCatalogueCache): void {
438
857
  }
439
858
  }
440
859
 
441
- /** Get cached models for a provider if not expired */
442
- export function getCachedModels(provider: string): string[] | null {
860
+ /** Get cached models for a provider if not expired and account fingerprint still matches */
861
+ export function getCachedModels(
862
+ provider: string,
863
+ config: { apiKey?: string; baseUrl?: string; providerKeys?: Record<string, string> } = {}
864
+ ): string[] | null {
443
865
  const cache = readModelCache();
444
866
  if (!cache) return null;
445
867
  const norm = normalizeProviderKey(provider);
446
868
  const entry = cache.providers[norm];
447
- if (!entry) return null;
448
- if (Date.now() - entry.timestamp > CACHE_TTL_MS) return null;
869
+ if (!entry || !Array.isArray(entry.models) || entry.models.length === 0) return null;
870
+
871
+ const ttl = isLocalOrAcpProvider(norm) ? PEER_CACHE_TTL_MS : BYOK_CACHE_TTL_MS;
872
+ if (Date.now() - entry.timestamp > ttl) return null;
873
+
874
+ if (entry.fingerprint) {
875
+ const currentFingerprint = computeProviderAuthFingerprint(norm, config);
876
+ if (entry.fingerprint !== currentFingerprint) {
877
+ return null;
878
+ }
879
+ }
880
+
881
+ if (norm === 'antigravity' && entry.modelIdMap && typeof entry.modelIdMap === 'object') {
882
+ for (const [label, slug] of Object.entries(entry.modelIdMap)) {
883
+ if (typeof slug === 'string' && slug.trim()) {
884
+ registerAntigravityModel(slug.trim(), label);
885
+ }
886
+ }
887
+ }
888
+
449
889
  return entry.models;
450
890
  }
451
891
 
452
- /** Save models for a provider into the local cache */
453
- export function saveCachedModels(provider: string, models: string[]): void {
892
+ /** Save models for a provider into the local cache along with its current account fingerprint */
893
+ export function saveCachedModels(
894
+ provider: string,
895
+ models: string[],
896
+ options: {
897
+ config?: { apiKey?: string; baseUrl?: string; providerKeys?: Record<string, string> };
898
+ modelIdMap?: Record<string, string>;
899
+ currentModel?: string;
900
+ } = {}
901
+ ): void {
454
902
  const norm = normalizeProviderKey(provider);
455
903
  const cache: DynamicCatalogueCache = readModelCache() || {
456
904
  version: 1,
457
905
  updatedAt: new Date().toISOString(),
458
906
  providers: {}
459
907
  };
460
- cache.providers[norm] = {
908
+ const entry: DynamicCatalogueCacheEntry = {
461
909
  timestamp: Date.now(),
462
- models: [...new Set(models)]
910
+ models: [...new Set(models)],
911
+ fingerprint: computeProviderAuthFingerprint(norm, options.config)
463
912
  };
913
+ if (options.modelIdMap && Object.keys(options.modelIdMap).length > 0) {
914
+ entry.modelIdMap = { ...options.modelIdMap };
915
+ } else if (norm === 'antigravity') {
916
+ const map: Record<string, string> = {};
917
+ for (const label of entry.models) {
918
+ if (ANTIGRAVITY_MODEL_IDS[label]) {
919
+ map[label] = ANTIGRAVITY_MODEL_IDS[label]!;
920
+ }
921
+ }
922
+ if (Object.keys(map).length > 0) entry.modelIdMap = map;
923
+ }
924
+ if (options.currentModel) {
925
+ entry.currentModel = options.currentModel;
926
+ }
927
+ cache.providers[norm] = entry;
464
928
  cache.updatedAt = new Date().toISOString();
465
929
  writeModelCache(cache);
466
930
  }
467
931
 
468
- /** Live query provider API to discover available models */
932
+ /** Live query provider API or CLI/ACP peer to discover available models */
469
933
  export async function fetchLiveModels(
470
934
  provider: string,
471
935
  config: { apiKey?: string; baseUrl?: string } = {}
@@ -474,6 +938,7 @@ export async function fetchLiveModels(
474
938
  const { apiKey, baseUrl } = config;
475
939
 
476
940
  if (norm === 'antigravity') return discoverAntigravityModels();
941
+ if (norm === 'pi') return discoverPiModels();
477
942
  const peer = peerIdFromProviderKey(norm);
478
943
  if (peer) return discoverPeerModels(peer);
479
944
 
@@ -591,39 +1056,103 @@ export interface ModelResolutionResult {
591
1056
  */
592
1057
  export async function resolveAvailableModels(
593
1058
  provider: string,
594
- config: { apiKey?: string; baseUrl?: string } = {},
1059
+ config: { apiKey?: string; baseUrl?: string; providerKeys?: Record<string, string> } = {},
595
1060
  forceRefresh = false
596
1061
  ): Promise<ModelResolutionResult> {
597
1062
  const norm = normalizeProviderKey(provider);
598
1063
  const curated = getCuratedModels(norm);
1064
+ const localAgent = isLocalOrAcpProvider(norm);
599
1065
 
600
1066
  if (forceRefresh) {
601
1067
  const live = await fetchLiveModels(norm, config);
602
1068
  if (live.length > 0) {
603
- const combined = [...new Set([...live, ...curated])];
604
- saveCachedModels(norm, combined);
605
- return { models: combined, source: 'live' };
1069
+ const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
1070
+ saveCachedModels(norm, models, { config });
1071
+ return { models, source: 'live' };
606
1072
  }
607
1073
  }
608
1074
 
609
- const cached = getCachedModels(norm);
1075
+ const cached = getCachedModels(norm, config);
610
1076
  if (cached && cached.length > 0) {
611
- const combined = [...new Set([...cached, ...curated])];
612
- return { models: combined, source: 'cache' };
1077
+ const models = localAgent ? [...new Set(cached)] : [...new Set([...cached, ...curated])];
1078
+ return { models, source: 'cache' };
613
1079
  }
614
1080
 
615
1081
  // Attempt lazy background discovery if credentials exist. Peer agents and
616
1082
  // Antigravity are credentialed by their own CLI login, so they qualify even
617
1083
  // with no apiKey in Causyne's vault.
618
- const localAgent = norm === 'antigravity' || peerIdFromProviderKey(norm) !== null;
619
1084
  if (config.apiKey || norm === 'ollama' || localAgent) {
620
1085
  const live = await fetchLiveModels(norm, config);
621
1086
  if (live.length > 0) {
622
- const combined = [...new Set([...live, ...curated])];
623
- saveCachedModels(norm, combined);
624
- return { models: combined, source: 'live' };
1087
+ const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
1088
+ saveCachedModels(norm, models, { config });
1089
+ return { models, source: 'live' };
625
1090
  }
626
1091
  }
627
1092
 
628
1093
  return { models: curated, source: 'catalogue' };
629
1094
  }
1095
+
1096
+ /**
1097
+ * Asynchronously refresh installed ACP/local peers and configured BYOK providers
1098
+ * whose cache is missing, expired, or invalidated by an account/tier change,
1099
+ * then return the updated ProviderOverview.
1100
+ */
1101
+ export async function resolveAvailableProvidersOverview(
1102
+ config: { provider?: string; apiKey?: string; model?: string; baseUrl?: string; providerKeys?: Record<string, string> } = {},
1103
+ options: { forceRefresh?: boolean } = {}
1104
+ ): Promise<ProviderOverview> {
1105
+ const initial = getAvailableProvidersOverview(config);
1106
+ const forceRefresh = Boolean(options.forceRefresh);
1107
+ const tasks: Array<Promise<unknown>> = [];
1108
+
1109
+ for (const peer of initial.acp) {
1110
+ if (!peer.installed) continue;
1111
+ const cached = getCachedModels(peer.providerKey, config);
1112
+ if (forceRefresh || !cached || cached.length === 0) {
1113
+ tasks.push(
1114
+ resolveAvailableModels(peer.providerKey, config, forceRefresh).catch(() => null)
1115
+ );
1116
+ }
1117
+ }
1118
+
1119
+ for (const byok of initial.byok) {
1120
+ if (!byok.isConfigured) continue;
1121
+ const cached = getCachedModels(byok.id, config);
1122
+ if (forceRefresh || (!cached && byok.id === String(config.provider || '').toLowerCase())) {
1123
+ const apiKey = (config.provider === byok.id && config.apiKey)
1124
+ || (config.providerKeys && config.providerKeys[byok.id])
1125
+ || (byok.envVar && process.env[byok.envVar])
1126
+ || '';
1127
+ if (apiKey || byok.id === 'ollama') {
1128
+ tasks.push(
1129
+ resolveAvailableModels(byok.id, { ...config, apiKey }, forceRefresh).catch(() => null)
1130
+ );
1131
+ }
1132
+ }
1133
+ }
1134
+
1135
+ if (tasks.length > 0) {
1136
+ await Promise.allSettled(tasks);
1137
+ }
1138
+
1139
+ return getAvailableProvidersOverview(config);
1140
+ }
1141
+
1142
+ /**
1143
+ * Select the most appropriate default model for a peer/provider given its live
1144
+ * or cached advertised model list. Prefers the canonical default if still present
1145
+ * on the user's account, otherwise falls back to the first live advertised model.
1146
+ */
1147
+ export function pickDefaultPeerModel(providerKey: string, advertisedModels: string[] = []): string {
1148
+ const norm = normalizeProviderKey(providerKey);
1149
+ const staticDefault = (DEFAULT_MODEL_BY_PROVIDER as Record<string, string>)[norm];
1150
+ if (Array.isArray(advertisedModels) && advertisedModels.length > 0) {
1151
+ if (staticDefault && advertisedModels.includes(staticDefault)) {
1152
+ return staticDefault;
1153
+ }
1154
+ return advertisedModels[0]!;
1155
+ }
1156
+ const peer = peerIdFromProviderKey(norm);
1157
+ return staticDefault || peer || norm;
1158
+ }