@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.
@@ -9,16 +9,19 @@
9
9
  // with resilient local caching in ~/.causyne/models_cache.json.
10
10
  //
11
11
  // ZERO-MALWARE: Pure TypeScript/ESM. Strictly respects timeouts, no secret leakage, no unprompted background calls.
12
+ import crypto from 'node:crypto';
12
13
  import fs from 'node:fs';
13
14
  import path from 'node:path';
14
15
  import { execFile } from 'node:child_process';
15
16
  import { promisify } from 'node:util';
16
17
  import { causyneHome } from './utils/paths.js';
17
18
  import { MODEL_CATALOGUE, PEER_MODEL_CATALOGUE, DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
18
- import { ANTIGRAVITY_MODELS, ANTIGRAVITY_LABEL_BY_ID, registerAntigravityModel, parseAgyModelsOutput, resolveAgyBinary } from './providers/antigravity.js';
19
- import { isBinaryOnPath, BUILTIN_PEER_PRESETS } from './acp/agentCatalog.js';
19
+ import { BASELINE_ANTIGRAVITY_MODELS, ANTIGRAVITY_MODELS, ANTIGRAVITY_MODEL_IDS, ANTIGRAVITY_LABEL_BY_ID, registerAntigravityModel, replaceAntigravityModels, parseAgyModelsOutput, isAntigravityOnboarded, resolveAgyBinary } from './providers/antigravity.js';
20
+ import { isBinaryOnPath, BUILTIN_PEER_PRESETS, probePresetAuth, testPeerHandshake } from './acp/agentCatalog.js';
21
+ import { getPeerProfile } from './acp/peerProfiles.js';
20
22
  const execFileAsync = promisify(execFile);
21
- const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
23
+ const BYOK_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour for cloud API model lists
24
+ const PEER_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes for fluctuating local/ACP peer tiers
22
25
  const REQUEST_TIMEOUT_MS = 3500; // Fast timeout to never block user interaction
23
26
  export function cacheFilePath() {
24
27
  return path.join(causyneHome(), 'models_cache.json');
@@ -70,13 +73,13 @@ export function peerIdFromProviderKey(provider) {
70
73
  const peer = p.slice(4).split('/')[0];
71
74
  return peer || null;
72
75
  }
73
- /** Get the static curated models for a provider id. */
76
+ /** Get the static curated baseline models for a provider id (offline fallback). */
74
77
  export function getCuratedModels(provider) {
75
78
  const norm = normalizeProviderKey(provider);
76
79
  if (norm === 'antigravity')
77
- return [...ANTIGRAVITY_MODELS];
80
+ return Object.keys(BASELINE_ANTIGRAVITY_MODELS);
78
81
  if (norm === 'pi')
79
- return [...(MODEL_CATALOGUE['Pi (Local Peer)'] || [])];
82
+ return [...(MODEL_CATALOGUE['Pi (Local Peer)'] || ['default'])];
80
83
  const peer = peerIdFromProviderKey(norm);
81
84
  if (peer)
82
85
  return [...(PEER_MODEL_CATALOGUE[peer] ?? [])];
@@ -101,6 +104,104 @@ export function getCuratedModels(provider) {
101
104
  }
102
105
  return [];
103
106
  }
107
+ function isLocalOrAcpProvider(norm) {
108
+ return norm === 'antigravity' || norm === 'pi' || norm === 'acp' || peerIdFromProviderKey(norm) !== null;
109
+ }
110
+ function statSignature(filePath) {
111
+ try {
112
+ if (!fs.existsSync(filePath))
113
+ return 'missing';
114
+ const stat = fs.statSync(filePath);
115
+ return `${Math.floor(stat.mtimeMs)}:${stat.size}`;
116
+ }
117
+ catch {
118
+ return 'err';
119
+ }
120
+ }
121
+ /**
122
+ * Compute a fast, non-secret fingerprint of a provider's local auth/account/config state.
123
+ * When a user switches accounts, upgrades tiers (e.g. Starter -> Pro -> Ultra), or edits
124
+ * their CLI settings, the fingerprint changes and invalidates stale cached models immediately.
125
+ */
126
+ export function computeProviderAuthFingerprint(provider, config = {}) {
127
+ const norm = normalizeProviderKey(provider);
128
+ const home = process.env.HOME || process.env.USERPROFILE || '';
129
+ const parts = [norm];
130
+ if (norm === 'antigravity') {
131
+ parts.push(statSignature(path.join(home, '.gemini', 'oauth_creds.json')), statSignature(path.join(home, '.gemini', 'google_accounts.json')), statSignature(path.join(home, '.gemini', 'antigravity-cli', 'settings.json')), statSignature(path.join(home, '.gemini', 'antigravity-cli', 'cache', 'onboarding.json')));
132
+ }
133
+ else if (norm === 'pi') {
134
+ parts.push(statSignature(path.join(home, '.pi', 'agent', 'models.json')), statSignature(path.join(home, '.pi', 'agent', 'auth.json')), statSignature(path.join(home, '.pi', 'agent', 'settings.json')), statSignature(path.join(home, '.config', 'pi', 'config.json')));
135
+ }
136
+ else if (peerIdFromProviderKey(norm)) {
137
+ const peer = peerIdFromProviderKey(norm);
138
+ const peerFiles = {
139
+ opencode: [
140
+ path.join(home, '.config', 'opencode', 'opencode.json'),
141
+ path.join(home, '.config', 'opencode', 'config.json'),
142
+ path.join(home, '.local', 'share', 'opencode', 'auth.json'),
143
+ path.join(home, '.opencode', 'config.json')
144
+ ],
145
+ claude: [
146
+ path.join(home, '.claude', 'settings.json'),
147
+ path.join(home, '.claude.json'),
148
+ path.join(home, '.config', 'claude', 'config.json')
149
+ ],
150
+ codex: [
151
+ path.join(home, '.codex', 'auth.json'),
152
+ path.join(home, '.codex', 'config.toml'),
153
+ path.join(home, '.codex', 'config.json')
154
+ ],
155
+ gemini: [
156
+ path.join(home, '.gemini', 'oauth_creds.json'),
157
+ path.join(home, '.gemini', 'google_accounts.json'),
158
+ path.join(home, '.gemini', 'settings.json')
159
+ ],
160
+ cursor: [
161
+ path.join(home, '.cursor', 'cli-config.json'),
162
+ path.join(home, '.config', 'cursor', 'auth.json')
163
+ ],
164
+ qwen: [
165
+ path.join(home, '.qwen', 'oauth_creds.json'),
166
+ path.join(home, '.qwen', 'settings.json')
167
+ ],
168
+ copilot: [
169
+ path.join(home, '.config', 'github-copilot', 'hosts.json'),
170
+ path.join(home, '.config', 'github-copilot', 'apps.json')
171
+ ],
172
+ kimi: [
173
+ path.join(home, '.kimi', 'config.toml'),
174
+ path.join(home, '.kimi', 'config.json')
175
+ ],
176
+ goose: [
177
+ path.join(home, '.config', 'goose', 'config.yaml'),
178
+ path.join(home, '.config', 'goose', 'profiles.yaml')
179
+ ],
180
+ hermes: [
181
+ path.join(home, '.hermes', 'config.yaml'),
182
+ path.join(home, '.hermes', 'config.json')
183
+ ]
184
+ };
185
+ for (const file of peerFiles[peer] || []) {
186
+ parts.push(statSignature(file));
187
+ }
188
+ if (peer === 'claude') {
189
+ parts.push(process.env.ANTHROPIC_MODEL || '', process.env.CLAUDE_MODEL || '', String(Boolean(process.env.ANTHROPIC_API_KEY)));
190
+ }
191
+ else if (peer === 'codex') {
192
+ parts.push(process.env.OPENAI_MODEL || '', String(Boolean(process.env.OPENAI_API_KEY)));
193
+ }
194
+ else if (peer === 'gemini') {
195
+ parts.push(process.env.GEMINI_MODEL || '', String(Boolean(process.env.GEMINI_API_KEY)));
196
+ }
197
+ }
198
+ else {
199
+ const key = config.apiKey || (config.providerKeys && config.providerKeys[norm]) || '';
200
+ const keyDigest = key ? crypto.createHash('sha256').update(key).digest('hex').slice(0, 12) : 'nokey';
201
+ parts.push(keyDigest, config.baseUrl || '');
202
+ }
203
+ return crypto.createHash('sha256').update(parts.join('|')).digest('hex').slice(0, 16);
204
+ }
104
205
  /**
105
206
  * Categorize available providers into BYOK and ACP peer agents,
106
207
  * checking configured state for BYOK and installation status for ACP agents.
@@ -171,19 +272,25 @@ export function getAvailableProvidersOverview(config = {}) {
171
272
  || Boolean(config.providerKeys && (config.providerKeys[def.id] || (def.id === 'qwen' && config.providerKeys['dashscope-byok'])))
172
273
  || Boolean(def.envVar && process.env[def.envVar]);
173
274
  const isConfigured = def.id === 'ollama' || hasStoredKey;
275
+ const cachedByok = getCachedModels(def.id, config);
276
+ const models = cachedByok && cachedByok.length > 0 ? [...cachedByok] : def.models;
174
277
  return {
175
278
  id: def.id,
176
279
  label: def.label,
177
280
  isConfigured,
178
281
  isCurrent,
179
- models: def.models,
180
- defaultModel: def.defaultModel,
282
+ models,
283
+ defaultModel: models[0] || def.defaultModel,
181
284
  envVar: def.envVar
182
285
  };
183
286
  });
184
287
  const acpPeers = [];
185
288
  // Antigravity (special native local provider)
186
289
  const hasAgy = Boolean(resolveAgyBinary());
290
+ const cachedAgyModels = getCachedModels('antigravity', config);
291
+ const agyModels = cachedAgyModels && cachedAgyModels.length > 0
292
+ ? replaceAntigravityModels(cachedAgyModels)
293
+ : [...ANTIGRAVITY_MODELS];
187
294
  acpPeers.push({
188
295
  id: 'antigravity',
189
296
  providerKey: 'antigravity',
@@ -192,15 +299,20 @@ export function getAvailableProvidersOverview(config = {}) {
192
299
  status: hasAgy ? 'ready' : 'not_installed',
193
300
  isCurrent: currentProvider === 'antigravity',
194
301
  command: 'agy --output-format json',
195
- models: [...ANTIGRAVITY_MODELS],
302
+ models: agyModels,
196
303
  setupInstruction: 'Install Antigravity IDE or agy CLI to enable Google AGY models.'
197
304
  });
198
305
  const hasPi = isBinaryOnPath('pi');
306
+ const cachedPiModels = getCachedModels('pi', config);
307
+ const configPiModels = detectPeerConfigModels('pi');
308
+ const piModels = (cachedPiModels && cachedPiModels.length > 0)
309
+ ? [...cachedPiModels]
310
+ : (configPiModels.length > 0 ? configPiModels : ['default']);
199
311
  acpPeers.push({
200
312
  id: 'pi', providerKey: 'pi', label: 'Pi coding agent',
201
313
  installed: hasPi, status: hasPi ? 'ready' : 'not_installed',
202
314
  isCurrent: currentProvider === 'pi', command: 'pi --mode rpc --no-tools',
203
- models: ['default'],
315
+ models: piModels,
204
316
  setupInstruction: 'Install Pi CLI and configure its model login before selecting it in Causyne.'
205
317
  });
206
318
  // Standard ACP presets
@@ -218,7 +330,8 @@ export function getAvailableProvidersOverview(config = {}) {
218
330
  }
219
331
  const providerKey = `acp/${preset.id}`;
220
332
  const isCurrent = currentProvider === providerKey;
221
- const cachedPeerModels = getCachedModels(providerKey) || getCachedModels(preset.id);
333
+ const cachedPeerModels = getCachedModels(providerKey, config) || getCachedModels(preset.id, config);
334
+ const localConfigModels = detectPeerConfigModels(preset.id);
222
335
  let models = [];
223
336
  if (cachedPeerModels && cachedPeerModels.length > 0) {
224
337
  models = [...cachedPeerModels];
@@ -226,6 +339,9 @@ export function getAvailableProvidersOverview(config = {}) {
226
339
  else if (preset.id === 'claude') {
227
340
  models = detectClaudeModels();
228
341
  }
342
+ else if (localConfigModels.length > 0) {
343
+ models = [...new Set([...localConfigModels, ...(PEER_MODEL_CATALOGUE[preset.id] || [])])];
344
+ }
229
345
  else if (PEER_MODEL_CATALOGUE[preset.id]) {
230
346
  models = [...(PEER_MODEL_CATALOGUE[preset.id] || [])];
231
347
  }
@@ -235,6 +351,11 @@ export function getAvailableProvidersOverview(config = {}) {
235
351
  else {
236
352
  models = [preset.id];
237
353
  }
354
+ // A saved preference is not evidence that the active peer still offers it.
355
+ // Only retain it as a fallback when no fresh peer model list is cached.
356
+ if (isCurrent && currentModel && !cachedPeerModels && !models.includes(currentModel)) {
357
+ models = [currentModel, ...models];
358
+ }
238
359
  acpPeers.push({
239
360
  id: preset.id,
240
361
  providerKey,
@@ -255,6 +376,7 @@ export function getAvailableProvidersOverview(config = {}) {
255
376
  };
256
377
  }
257
378
  const MODEL_LIST_TIMEOUT_MS = 8000;
379
+ const ACP_DISCOVERY_TIMEOUT_MS = 4500;
258
380
  const ANSI_ESCAPE = /\u001b\[[0-9;]*[A-Za-z]/g;
259
381
  const PEER_MODEL_COMMANDS = {
260
382
  opencode: { command: 'opencode', args: ['models'] },
@@ -265,7 +387,8 @@ async function runModelList(command, args) {
265
387
  const { stdout } = await execFileAsync(command, args, {
266
388
  timeout: MODEL_LIST_TIMEOUT_MS,
267
389
  maxBuffer: 4 * 1024 * 1024,
268
- windowsHide: true
390
+ windowsHide: true,
391
+ env: { ...process.env, CI: '1', BROWSER: 'false', NO_BROWSER: '1' }
269
392
  });
270
393
  return stdout.replace(ANSI_ESCAPE, '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
271
394
  }
@@ -273,92 +396,373 @@ async function runModelList(command, args) {
273
396
  return [];
274
397
  }
275
398
  }
276
- function parseModelIds(lines) {
399
+ export function parseModelIds(lines) {
277
400
  const models = [];
278
401
  for (const rawLine of lines) {
279
402
  const line = rawLine.replace(ANSI_ESCAPE, '').trim();
280
403
  if (!line)
281
404
  continue;
282
- if (/^(fetching|loading|no models|error)/i.test(line))
405
+ 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)) {
406
+ continue;
407
+ }
408
+ if (line.endsWith('…') || line.endsWith('...') || line.endsWith(':'))
283
409
  continue;
284
- if (line.endsWith('…') || line.endsWith('...'))
410
+ if (/^(\/|~|\.|--|http:\/\/|https:\/\/)/i.test(line))
285
411
  continue;
286
- const match = line.match(/^([a-z0-9_./-]+)/i);
412
+ const match = line.match(/^([a-z0-9][a-z0-9_.:/-]*)/i);
287
413
  if (match && match[1]) {
288
- models.push(match[1]);
414
+ const candidate = match[1].replace(/[.,;:]+$/, '');
415
+ if (!candidate || candidate.length < 2)
416
+ continue;
417
+ if (/^(node_modules|provider|model|context|thinking|images|none|null|undefined)$/i.test(candidate))
418
+ continue;
419
+ if (/\.(md|json|js|ts|yaml|yml|toml|txt|html)$/i.test(candidate))
420
+ continue;
421
+ models.push(candidate);
289
422
  }
290
423
  }
291
424
  return [...new Set(models)];
292
425
  }
293
- function detectClaudeModels() {
426
+ export function parsePiModelsOutput(stdout) {
427
+ const models = [];
428
+ if (!stdout || typeof stdout !== 'string')
429
+ return models;
430
+ const lines = stdout.replace(ANSI_ESCAPE, '').split(/\r?\n/);
431
+ for (const rawLine of lines) {
432
+ const line = rawLine.trim();
433
+ if (!line)
434
+ continue;
435
+ if (/^(no models|warning|error|use\s+\/login|see:|provider\s+model)/i.test(line))
436
+ continue;
437
+ if (/^(\/|~|\.|http:\/\/|https:\/\/)/i.test(line))
438
+ continue;
439
+ const cols = line.split(/\s{2,}/).map(c => c.trim()).filter(Boolean);
440
+ if (cols.length >= 2) {
441
+ const provider = cols[0];
442
+ const model = cols[1];
443
+ if (provider.toLowerCase() === 'provider' && model.toLowerCase() === 'model')
444
+ continue;
445
+ if (/^[a-z0-9_.-]+$/i.test(provider) && /^[a-z0-9_.:/-]+$/i.test(model)) {
446
+ models.push(model.includes('/') ? model : `${provider}/${model}`);
447
+ }
448
+ }
449
+ }
450
+ return [...new Set(models)];
451
+ }
452
+ /**
453
+ * Inspect local CLI configuration files (JSON/TOML/YAML) and environment variables
454
+ * to discover user-configured models for a peer agent with zero process overhead.
455
+ */
456
+ export function detectPeerConfigModels(peerId) {
457
+ const peer = (peerId || '').toLowerCase().trim();
294
458
  const models = [];
459
+ const home = process.env.HOME || process.env.USERPROFILE || '';
460
+ const addModel = (val) => {
461
+ if (typeof val === 'string' && val.trim()) {
462
+ const clean = val.trim();
463
+ if (!models.includes(clean))
464
+ models.push(clean);
465
+ }
466
+ };
295
467
  try {
296
- const home = process.env.HOME || process.env.USERPROFILE || '';
297
- if (home) {
298
- const settingsFile = path.join(home, '.claude', 'settings.json');
299
- if (fs.existsSync(settingsFile)) {
300
- const content = fs.readFileSync(settingsFile, 'utf8');
301
- const parsed = JSON.parse(content);
302
- if (typeof parsed?.model === 'string' && parsed.model.trim()) {
303
- models.push(parsed.model.trim());
468
+ if (peer === 'claude') {
469
+ if (home) {
470
+ for (const rel of [['.claude', 'settings.json'], ['.claude.json'], ['.config', 'claude', 'settings.json']]) {
471
+ const file = path.join(home, ...rel);
472
+ if (fs.existsSync(file)) {
473
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
474
+ addModel(parsed?.model);
475
+ addModel(parsed?.defaultModel);
476
+ if (Array.isArray(parsed?.availableModels)) {
477
+ for (const m of parsed.availableModels)
478
+ addModel(m);
479
+ }
480
+ }
304
481
  }
305
- if (Array.isArray(parsed?.availableModels)) {
306
- for (const m of parsed.availableModels) {
307
- if (typeof m === 'string' && m.trim())
308
- models.push(m.trim());
482
+ }
483
+ addModel(process.env.ANTHROPIC_MODEL || process.env.CLAUDE_MODEL);
484
+ }
485
+ else if (peer === 'codex') {
486
+ addModel(process.env.OPENAI_MODEL);
487
+ if (home) {
488
+ const tomlFile = path.join(home, '.codex', 'config.toml');
489
+ if (fs.existsSync(tomlFile)) {
490
+ const content = fs.readFileSync(tomlFile, 'utf8');
491
+ for (const match of content.matchAll(/^\s*model\s*=\s*["']([^"']+)["']/gm)) {
492
+ addModel(match[1]);
493
+ }
494
+ }
495
+ const jsonFile = path.join(home, '.codex', 'config.json');
496
+ if (fs.existsSync(jsonFile)) {
497
+ const parsed = JSON.parse(fs.readFileSync(jsonFile, 'utf8'));
498
+ addModel(parsed?.model);
499
+ }
500
+ }
501
+ }
502
+ else if (peer === 'gemini') {
503
+ addModel(process.env.GEMINI_MODEL);
504
+ if (home) {
505
+ const settingsFile = path.join(home, '.gemini', 'settings.json');
506
+ if (fs.existsSync(settingsFile)) {
507
+ const parsed = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
508
+ addModel(parsed?.model);
509
+ addModel(parsed?.selectedModel);
510
+ if (Array.isArray(parsed?.availableModels)) {
511
+ for (const m of parsed.availableModels)
512
+ addModel(m);
513
+ }
514
+ }
515
+ }
516
+ }
517
+ else if (peer === 'opencode') {
518
+ if (home) {
519
+ for (const file of [
520
+ path.join(home, '.config', 'opencode', 'opencode.json'),
521
+ path.join(home, '.config', 'opencode', 'config.json'),
522
+ path.join(home, '.opencode', 'config.json')
523
+ ]) {
524
+ if (fs.existsSync(file)) {
525
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
526
+ addModel(parsed?.model);
527
+ addModel(parsed?.small_model);
528
+ if (parsed?.provider && typeof parsed.provider === 'object') {
529
+ for (const [provId, provCfg] of Object.entries(parsed.provider)) {
530
+ if (provCfg && typeof provCfg === 'object' && 'models' in provCfg) {
531
+ const modelsObj = provCfg.models;
532
+ if (modelsObj && typeof modelsObj === 'object') {
533
+ for (const modelKey of Object.keys(modelsObj)) {
534
+ addModel(modelKey.includes('/') ? modelKey : `${provId}/${modelKey}`);
535
+ }
536
+ }
537
+ }
538
+ }
539
+ }
540
+ }
541
+ }
542
+ }
543
+ }
544
+ else if (peer === 'qwen') {
545
+ if (home) {
546
+ const settingsFile = path.join(home, '.qwen', 'settings.json');
547
+ if (fs.existsSync(settingsFile)) {
548
+ const parsed = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
549
+ addModel(parsed?.model);
550
+ if (Array.isArray(parsed?.availableModels)) {
551
+ for (const m of parsed.availableModels)
552
+ addModel(m);
553
+ }
554
+ }
555
+ }
556
+ }
557
+ else if (peer === 'kimi') {
558
+ if (home) {
559
+ const tomlFile = path.join(home, '.kimi', 'config.toml');
560
+ if (fs.existsSync(tomlFile)) {
561
+ const content = fs.readFileSync(tomlFile, 'utf8');
562
+ for (const match of content.matchAll(/^\s*(?:default_)?model\s*=\s*["']([^"']+)["']/gm)) {
563
+ addModel(match[1]);
564
+ }
565
+ }
566
+ }
567
+ }
568
+ else if (peer === 'goose') {
569
+ if (home) {
570
+ const yamlFile = path.join(home, '.config', 'goose', 'config.yaml');
571
+ if (fs.existsSync(yamlFile)) {
572
+ const content = fs.readFileSync(yamlFile, 'utf8');
573
+ for (const match of content.matchAll(/^\s*(?:GOOSE_MODEL|model)\s*:\s*["']?([a-zA-Z0-9_.:/-]+)["']?/gm)) {
574
+ addModel(match[1]);
575
+ }
576
+ }
577
+ }
578
+ }
579
+ else if (peer === 'hermes') {
580
+ if (home) {
581
+ const yamlFile = path.join(home, '.hermes', 'config.yaml');
582
+ if (fs.existsSync(yamlFile)) {
583
+ const content = fs.readFileSync(yamlFile, 'utf8');
584
+ for (const match of content.matchAll(/^\s*(?:default_)?model\s*:\s*["']?([a-zA-Z0-9_.:/-]+)["']?/gm)) {
585
+ addModel(match[1]);
586
+ }
587
+ }
588
+ }
589
+ }
590
+ else if (peer === 'pi') {
591
+ if (home) {
592
+ const settingsFile = path.join(home, '.pi', 'agent', 'settings.json');
593
+ if (fs.existsSync(settingsFile)) {
594
+ const parsed = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
595
+ const defaultProvider = typeof parsed?.defaultProvider === 'string' ? parsed.defaultProvider.trim() : '';
596
+ const defaultModel = typeof parsed?.defaultModel === 'string' ? parsed.defaultModel.trim() : '';
597
+ if (defaultProvider && defaultModel) {
598
+ addModel(`${defaultProvider}/${defaultModel}`);
599
+ }
600
+ else {
601
+ addModel(defaultModel || parsed?.model);
602
+ }
603
+ }
604
+ const modelsFile = path.join(home, '.pi', 'agent', 'models.json');
605
+ if (fs.existsSync(modelsFile)) {
606
+ const parsed = JSON.parse(fs.readFileSync(modelsFile, 'utf8'));
607
+ if (parsed?.providers && typeof parsed.providers === 'object') {
608
+ for (const [provId, provData] of Object.entries(parsed.providers)) {
609
+ if (provData && typeof provData === 'object' && Array.isArray(provData.models)) {
610
+ for (const m of provData.models) {
611
+ if (typeof m === 'string')
612
+ addModel(`${provId}/${m}`);
613
+ else if (m && typeof m.id === 'string')
614
+ addModel(`${provId}/${m.id}`);
615
+ }
616
+ }
617
+ }
309
618
  }
310
619
  }
311
620
  }
312
621
  }
313
622
  }
314
623
  catch {
315
- // Ignore settings read errors
316
- }
317
- const envModel = process.env.ANTHROPIC_MODEL || process.env.CLAUDE_MODEL;
318
- if (envModel && typeof envModel === 'string' && envModel.trim()) {
319
- models.push(envModel.trim());
624
+ // Ignore malformed user config files
320
625
  }
626
+ return models;
627
+ }
628
+ function detectClaudeModels() {
629
+ const models = detectPeerConfigModels('claude');
321
630
  const curated = PEER_MODEL_CATALOGUE['claude'] ?? ['sonnet', 'opus', 'haiku'];
322
631
  for (const m of curated) {
323
- models.push(m);
632
+ if (!models.includes(m))
633
+ models.push(m);
324
634
  }
325
635
  return [...new Set(models)];
326
636
  }
637
+ /**
638
+ * Probe an ACP peer via zero-token `initialize` + `session/new` handshake to
639
+ * discover the exact live models advertised for the user's current account/tier.
640
+ */
641
+ export async function discoverPeerModelsViaAcp(peerId, timeoutMs = ACP_DISCOVERY_TIMEOUT_MS) {
642
+ const peer = (peerId || '').toLowerCase().trim();
643
+ const profile = getPeerProfile(peer);
644
+ const preset = BUILTIN_PEER_PRESETS[peer];
645
+ if (!profile && !preset)
646
+ return [];
647
+ if (preset) {
648
+ const hasDirectBinary = isBinaryOnPath(preset.binaryName);
649
+ if (!hasDirectBinary)
650
+ return [];
651
+ const auth = await probePresetAuth(preset);
652
+ if (!auth.authenticated)
653
+ return [];
654
+ }
655
+ const command = profile?.command || preset?.command || peer;
656
+ const args = profile?.args || preset?.args || ['acp'];
657
+ if (!isBinaryOnPath(command))
658
+ return [];
659
+ try {
660
+ const handshake = await testPeerHandshake({
661
+ command,
662
+ args,
663
+ cwd: process.cwd(),
664
+ timeoutMs
665
+ });
666
+ if (handshake.ready && Array.isArray(handshake.availableModels) && handshake.availableModels.length > 0) {
667
+ return [...new Set(handshake.availableModels)];
668
+ }
669
+ }
670
+ catch {
671
+ // Silent fallback if ACP handshake fails or times out
672
+ }
673
+ return [];
674
+ }
675
+ /** Discover live models from Pi CLI (`pi --list-models` + local config). */
676
+ export async function discoverPiModels() {
677
+ const configModels = detectPeerConfigModels('pi');
678
+ if (isBinaryOnPath('pi')) {
679
+ try {
680
+ const { stdout } = await execFileAsync('pi', ['--list-models'], {
681
+ timeout: MODEL_LIST_TIMEOUT_MS,
682
+ maxBuffer: 4 * 1024 * 1024,
683
+ windowsHide: true,
684
+ env: { ...process.env, CI: '1', BROWSER: 'false', NO_BROWSER: '1' }
685
+ });
686
+ const parsed = parsePiModelsOutput(stdout);
687
+ if (parsed.length > 0) {
688
+ return [...new Set([...parsed, ...configModels])];
689
+ }
690
+ }
691
+ catch {
692
+ // Fall back to config or default
693
+ }
694
+ }
695
+ return configModels.length > 0 ? configModels : ['default'];
696
+ }
327
697
  /**
328
698
  * Ask a peer CLI which models its account can reach. Zero tokens: this runs the
329
- * peer's own listing command, never a model request.
699
+ * peer's own listing command or zero-token ACP session handshake, never a prompt.
330
700
  */
331
- export async function discoverPeerModels(peerId) {
701
+ export async function discoverPeerModels(peerId, options = {}) {
332
702
  const peer = (peerId || '').toLowerCase().trim();
333
- if (peer === 'claude') {
334
- return detectClaudeModels();
703
+ if (!peer)
704
+ return [];
705
+ if (peer === 'pi') {
706
+ return discoverPiModels();
335
707
  }
708
+ const configModels = detectPeerConfigModels(peer);
709
+ // 1. Fast CLI `models` subcommand (e.g. `opencode models`, `cursor-agent models`)
336
710
  const listing = PEER_MODEL_COMMANDS[peer];
337
- if (listing) {
711
+ if (listing && isBinaryOnPath(listing.command)) {
338
712
  const discovered = parseModelIds(await runModelList(listing.command, listing.args));
339
- if (discovered.length > 0)
340
- return discovered;
713
+ if (discovered.length > 0) {
714
+ return [...new Set([...discovered, ...configModels])];
715
+ }
716
+ }
717
+ // 2. Zero-token ACP session/new discovery (`configOptions` / `models`)
718
+ const allowHandshake = options.allowAcpHandshake ?? !process.env.NODE_TEST_CONTEXT;
719
+ if (allowHandshake) {
720
+ const acpModels = await discoverPeerModelsViaAcp(peer);
721
+ if (acpModels.length > 0) {
722
+ return [...new Set([...acpModels, ...configModels])];
723
+ }
724
+ }
725
+ // 3. Local config + curated fallback
726
+ if (peer === 'claude') {
727
+ return detectClaudeModels();
728
+ }
729
+ if (configModels.length > 0) {
730
+ return [...new Set([...configModels, ...(PEER_MODEL_CATALOGUE[peer] || [])])];
341
731
  }
342
732
  return PEER_MODEL_CATALOGUE[peer] ? [...PEER_MODEL_CATALOGUE[peer]] : [];
343
733
  }
344
734
  /** Ask Antigravity for its live model list and return the readable labels. */
345
- export async function discoverAntigravityModels() {
346
- try {
347
- const { stdout } = await execFileAsync(resolveAgyBinary(), ['models'], {
348
- timeout: MODEL_LIST_TIMEOUT_MS,
349
- maxBuffer: 4 * 1024 * 1024,
350
- windowsHide: true
351
- });
352
- const parsed = parseAgyModelsOutput(stdout);
353
- if (parsed.length > 0) {
354
- for (const item of parsed) {
355
- registerAntigravityModel(item.id, item.label);
735
+ export async function discoverAntigravityModels(options = {}) {
736
+ const customCommand = options.command;
737
+ const shouldSpawn = Boolean(customCommand)
738
+ || Boolean(options.forceSpawn)
739
+ || (!process.env.NODE_TEST_CONTEXT && isAntigravityOnboarded());
740
+ if (shouldSpawn) {
741
+ try {
742
+ const bin = customCommand || resolveAgyBinary();
743
+ const { stdout } = await execFileAsync(bin, ['models'], {
744
+ timeout: MODEL_LIST_TIMEOUT_MS,
745
+ maxBuffer: 4 * 1024 * 1024,
746
+ windowsHide: true,
747
+ env: { ...process.env, CI: '1', BROWSER: 'false', NO_BROWSER: '1' }
748
+ });
749
+ const parsed = parseAgyModelsOutput(stdout, { replaceActiveList: true });
750
+ if (parsed.length > 0) {
751
+ const modelIdMap = {};
752
+ const labels = [];
753
+ for (const item of parsed) {
754
+ const label = item.label || item.id;
755
+ modelIdMap[label] = item.id;
756
+ if (!labels.includes(label))
757
+ labels.push(label);
758
+ }
759
+ saveCachedModels('antigravity', labels, { modelIdMap });
760
+ return labels;
356
761
  }
357
- return [...new Set(parsed.map((item) => item.label || item.id))];
358
762
  }
359
- }
360
- catch {
361
- // Fall back to current registered or baseline models
763
+ catch {
764
+ // Fall back to current registered or baseline models
765
+ }
362
766
  }
363
767
  return [...ANTIGRAVITY_MODELS];
364
768
  }
@@ -393,40 +797,74 @@ export function writeModelCache(cache) {
393
797
  // Cache failures must never crash the CLI
394
798
  }
395
799
  }
396
- /** Get cached models for a provider if not expired */
397
- export function getCachedModels(provider) {
800
+ /** Get cached models for a provider if not expired and account fingerprint still matches */
801
+ export function getCachedModels(provider, config = {}) {
398
802
  const cache = readModelCache();
399
803
  if (!cache)
400
804
  return null;
401
805
  const norm = normalizeProviderKey(provider);
402
806
  const entry = cache.providers[norm];
403
- if (!entry)
807
+ if (!entry || !Array.isArray(entry.models) || entry.models.length === 0)
404
808
  return null;
405
- if (Date.now() - entry.timestamp > CACHE_TTL_MS)
809
+ const ttl = isLocalOrAcpProvider(norm) ? PEER_CACHE_TTL_MS : BYOK_CACHE_TTL_MS;
810
+ if (Date.now() - entry.timestamp > ttl)
406
811
  return null;
812
+ if (entry.fingerprint) {
813
+ const currentFingerprint = computeProviderAuthFingerprint(norm, config);
814
+ if (entry.fingerprint !== currentFingerprint) {
815
+ return null;
816
+ }
817
+ }
818
+ if (norm === 'antigravity' && entry.modelIdMap && typeof entry.modelIdMap === 'object') {
819
+ for (const [label, slug] of Object.entries(entry.modelIdMap)) {
820
+ if (typeof slug === 'string' && slug.trim()) {
821
+ registerAntigravityModel(slug.trim(), label);
822
+ }
823
+ }
824
+ }
407
825
  return entry.models;
408
826
  }
409
- /** Save models for a provider into the local cache */
410
- export function saveCachedModels(provider, models) {
827
+ /** Save models for a provider into the local cache along with its current account fingerprint */
828
+ export function saveCachedModels(provider, models, options = {}) {
411
829
  const norm = normalizeProviderKey(provider);
412
830
  const cache = readModelCache() || {
413
831
  version: 1,
414
832
  updatedAt: new Date().toISOString(),
415
833
  providers: {}
416
834
  };
417
- cache.providers[norm] = {
835
+ const entry = {
418
836
  timestamp: Date.now(),
419
- models: [...new Set(models)]
837
+ models: [...new Set(models)],
838
+ fingerprint: computeProviderAuthFingerprint(norm, options.config)
420
839
  };
840
+ if (options.modelIdMap && Object.keys(options.modelIdMap).length > 0) {
841
+ entry.modelIdMap = { ...options.modelIdMap };
842
+ }
843
+ else if (norm === 'antigravity') {
844
+ const map = {};
845
+ for (const label of entry.models) {
846
+ if (ANTIGRAVITY_MODEL_IDS[label]) {
847
+ map[label] = ANTIGRAVITY_MODEL_IDS[label];
848
+ }
849
+ }
850
+ if (Object.keys(map).length > 0)
851
+ entry.modelIdMap = map;
852
+ }
853
+ if (options.currentModel) {
854
+ entry.currentModel = options.currentModel;
855
+ }
856
+ cache.providers[norm] = entry;
421
857
  cache.updatedAt = new Date().toISOString();
422
858
  writeModelCache(cache);
423
859
  }
424
- /** Live query provider API to discover available models */
860
+ /** Live query provider API or CLI/ACP peer to discover available models */
425
861
  export async function fetchLiveModels(provider, config = {}) {
426
862
  const norm = normalizeProviderKey(provider);
427
863
  const { apiKey, baseUrl } = config;
428
864
  if (norm === 'antigravity')
429
865
  return discoverAntigravityModels();
866
+ if (norm === 'pi')
867
+ return discoverPiModels();
430
868
  const peer = peerIdFromProviderKey(norm);
431
869
  if (peer)
432
870
  return discoverPeerModels(peer);
@@ -547,30 +985,83 @@ export async function fetchLiveModels(provider, config = {}) {
547
985
  export async function resolveAvailableModels(provider, config = {}, forceRefresh = false) {
548
986
  const norm = normalizeProviderKey(provider);
549
987
  const curated = getCuratedModels(norm);
988
+ const localAgent = isLocalOrAcpProvider(norm);
550
989
  if (forceRefresh) {
551
990
  const live = await fetchLiveModels(norm, config);
552
991
  if (live.length > 0) {
553
- const combined = [...new Set([...live, ...curated])];
554
- saveCachedModels(norm, combined);
555
- return { models: combined, source: 'live' };
992
+ const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
993
+ saveCachedModels(norm, models, { config });
994
+ return { models, source: 'live' };
556
995
  }
557
996
  }
558
- const cached = getCachedModels(norm);
997
+ const cached = getCachedModels(norm, config);
559
998
  if (cached && cached.length > 0) {
560
- const combined = [...new Set([...cached, ...curated])];
561
- return { models: combined, source: 'cache' };
999
+ const models = localAgent ? [...new Set(cached)] : [...new Set([...cached, ...curated])];
1000
+ return { models, source: 'cache' };
562
1001
  }
563
1002
  // Attempt lazy background discovery if credentials exist. Peer agents and
564
1003
  // Antigravity are credentialed by their own CLI login, so they qualify even
565
1004
  // with no apiKey in Causyne's vault.
566
- const localAgent = norm === 'antigravity' || peerIdFromProviderKey(norm) !== null;
567
1005
  if (config.apiKey || norm === 'ollama' || localAgent) {
568
1006
  const live = await fetchLiveModels(norm, config);
569
1007
  if (live.length > 0) {
570
- const combined = [...new Set([...live, ...curated])];
571
- saveCachedModels(norm, combined);
572
- return { models: combined, source: 'live' };
1008
+ const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
1009
+ saveCachedModels(norm, models, { config });
1010
+ return { models, source: 'live' };
573
1011
  }
574
1012
  }
575
1013
  return { models: curated, source: 'catalogue' };
576
1014
  }
1015
+ /**
1016
+ * Asynchronously refresh installed ACP/local peers and configured BYOK providers
1017
+ * whose cache is missing, expired, or invalidated by an account/tier change,
1018
+ * then return the updated ProviderOverview.
1019
+ */
1020
+ export async function resolveAvailableProvidersOverview(config = {}, options = {}) {
1021
+ const initial = getAvailableProvidersOverview(config);
1022
+ const forceRefresh = Boolean(options.forceRefresh);
1023
+ const tasks = [];
1024
+ for (const peer of initial.acp) {
1025
+ if (!peer.installed)
1026
+ continue;
1027
+ const cached = getCachedModels(peer.providerKey, config);
1028
+ if (forceRefresh || !cached || cached.length === 0) {
1029
+ tasks.push(resolveAvailableModels(peer.providerKey, config, forceRefresh).catch(() => null));
1030
+ }
1031
+ }
1032
+ for (const byok of initial.byok) {
1033
+ if (!byok.isConfigured)
1034
+ continue;
1035
+ const cached = getCachedModels(byok.id, config);
1036
+ if (forceRefresh || (!cached && byok.id === String(config.provider || '').toLowerCase())) {
1037
+ const apiKey = (config.provider === byok.id && config.apiKey)
1038
+ || (config.providerKeys && config.providerKeys[byok.id])
1039
+ || (byok.envVar && process.env[byok.envVar])
1040
+ || '';
1041
+ if (apiKey || byok.id === 'ollama') {
1042
+ tasks.push(resolveAvailableModels(byok.id, { ...config, apiKey }, forceRefresh).catch(() => null));
1043
+ }
1044
+ }
1045
+ }
1046
+ if (tasks.length > 0) {
1047
+ await Promise.allSettled(tasks);
1048
+ }
1049
+ return getAvailableProvidersOverview(config);
1050
+ }
1051
+ /**
1052
+ * Select the most appropriate default model for a peer/provider given its live
1053
+ * or cached advertised model list. Prefers the canonical default if still present
1054
+ * on the user's account, otherwise falls back to the first live advertised model.
1055
+ */
1056
+ export function pickDefaultPeerModel(providerKey, advertisedModels = []) {
1057
+ const norm = normalizeProviderKey(providerKey);
1058
+ const staticDefault = DEFAULT_MODEL_BY_PROVIDER[norm];
1059
+ if (Array.isArray(advertisedModels) && advertisedModels.length > 0) {
1060
+ if (staticDefault && advertisedModels.includes(staticDefault)) {
1061
+ return staticDefault;
1062
+ }
1063
+ return advertisedModels[0];
1064
+ }
1065
+ const peer = peerIdFromProviderKey(norm);
1066
+ return staticDefault || peer || norm;
1067
+ }