Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor(aiToolkit): split provider service responsibilities (#8173)
[._.]/ Adam Eivy93ad19d1e06d
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex ba5d53de07..2b85b3c0ef 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -6,11 +6,11 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous- `index.js` exports `createAIToolkit`, `createProviderStatusService`, the four Router factories (providers / runs / prompts / providerStatus), and the context-fit pair `knownContextWindow` / `contextWindowRejection` — the host applies the same rule to the EXPLICITLY requested provider, which `getFallbackProvider` never sees. Both answer `null` for an unknown window, which every caller must keep reading as "no constraint"; nothing infers a window from a model id.- **The Ollama `num_ctx` ceiling is declared ONCE, in `internal/ollamaBacked.js`** (`clampToRuntimeContextWindow`), beside the predicate that gates it. `knownContextWindow` applies it through that helper and must never restate the `Math.min` inline — the host's prompt budgeter (`server/services/stageRunner.js#effectiveContextWindow`), the untrusted-content abuse guard (`server/services/untrustedContent.js#runUntrustedContentAnalysis`, which held its own hand-rolled `Math.min` pair until #7473) and the browser's provider-card meter call the same function, and when the rule was stated twice they drifted (#7466). It is an upper BOUND over every planning rung, a user's explicit `contextWindow` included, and the answer outright when nothing else declared one. Host callers import the `internal/` leaf directly, or `knownContextWindow`/`contextWindowRejection` straight off `providerStatus.js` (both deep imports skip the public barrel's `fs`/`child_process` reach): `stageRunner.js` sits inside the server suite's import budget, and `untrustedContent.js` — a request-path module — deliberately imports `providerStatus.js` rather than `stageRunner.js`, whose own closure would cost that budget ~40 extra module instantiations per reaching test file for no behavior it needs.- **A rung of that ceiling this directory cannot resolve arrives as DATA, never as an import out.** PortOS also sets the daemon-wide window through the ambient `OLLAMA_CONTEXT_LENGTH` (`server/lib/ollamaContext.js#resolveOllamaContextLength`), which the toolkit may not reach and the browser cannot read at all — so the host resolves it and stamps it onto an in-memory provider projection with `withRuntimeContextWindow`, declared in the same file as the clamp that reads it. `runtimeContextWindow` ranks BELOW `provider.numCtx`, exactly as `resolveOllamaContextLength` ranks the two, and is never persisted to `providers.json` (it describes the process running right now). Adding another host-resolved rung follows the same shape: stamp a field beside the reader, do not import out. Precedent: #7472.-- Provider configuration (models, tiers, fallbacks) lives in `providers.js`+- Provider configuration (models, tiers, fallbacks) is persisted and migrated by `internal/providerServiceState.js`; the public facade is `providers.js`- `loadProviders()` auto-migrates legacy codex configs to the `codex-configured-default` sentinel; `server/index.js` warms it at startup so the rewrite happens before any request- PortOS extends toolkit routes in `server/routes/providers.js` for vision testing and provider status (status routes live in PortOS, not the toolkit, because they call PortOS-side socket helpers)-- When adding new provider fields (e.g., `fallbackProvider`, `lightModel`), update `createProvider()` in `providers.js`-- `updateProvider()` uses spread so existing providers preserve custom fields, but `createProvider()` has an explicit field list+- When adding new provider fields (e.g., `fallbackProvider`, `lightModel`), update `buildProviderRecord()` in `internal/providerServiceState.js` and the corresponding validation schema+- `updateProvider()` uses spread so existing providers preserve custom fields, but `buildProviderRecord()` has an explicit field list- **Refreshing more than one provider goes through `refreshProviderModelsBatch(ids)`, never a loop over `refreshProviderModels(id)`.** Every single-provider refresh ends in `saveProviders`, which invalidates the read cache and rewrites all of `providers.json`; an N-provider fan-out that way is N full-file writes, each superseded by the next. The batch form groups by `ollamaRefreshGroupKey` (one probe per daemon + probe shape), probes each group's lead without persisting, then applies every result and saves **exactly once**. It never throws for a per-provider failure — each group carries its own `status` (`updated` / `failed` / `missing`) so the host logs one line per group rather than one per member. PortOS's post-install fan-out (`refreshOllamaBackedProviders` in `server/services/localLlm.js`) is the worked example.**A provider's MODEL ACCESS policy scopes on READ, never at refresh.** `internal/modelAccess.js` owns which of an upstream's advertised catalog an install is entitled to run — the thing a `/models` response cannot tell you (NVIDIA NIM answers with its whole product line and no tier field, so its free endpoints are indistinguishable over the wire). Three rules hold it together, and each has already been the bug the other way round:diff --git a/server/lib/aiToolkit/internal/antigravity.test.js b/server/lib/aiToolkit/internal/antigravity.test.jsindex 56304c5d83..1f4ae43c9a 100644--- a/server/lib/aiToolkit/internal/antigravity.test.js+++ b/server/lib/aiToolkit/internal/antigravity.test.js@@ -32,7 +32,7 @@ const TAB_LABELLED_OUTPUT = [].join('\n');describe('parseAntigravityModelList', () => {- // Success-path coverage for the parser extracted out of providers.js. Without+ // Success-path coverage for the parser extracted out of providerCatalogService.js. Without// it, `agy models` had no test that ever fed the filter real output — only a// spawn-failure case — so narrowing the character class or dropping the// sentinel filter would have kept the whole suite green.diff --git a/server/lib/aiToolkit/internal/claudeCodeCatalog.js b/server/lib/aiToolkit/internal/claudeCodeCatalog.jsindex c0b1658c38..29317d291e 100644--- a/server/lib/aiToolkit/internal/claudeCodeCatalog.js+++ b/server/lib/aiToolkit/internal/claudeCodeCatalog.js@@ -23,7 +23,7 @@* subscription-auth CLI provider does not have. A `type: 'api'` Anthropic* record with a key still goes through `_refreshAPIProviderModels`.*- * Pure by design (the fs read lives in `providers.js` with the rest of this+ * Pure by design (the fs read lives in `providerCatalogService.js` with the rest of this* directory's I/O) and self-contained — no imports out to other PortOS modules,* see ../AGENTS.md.*/diff --git a/server/lib/aiToolkit/internal/modelCatalog.js b/server/lib/aiToolkit/internal/modelCatalog.jsindex d693139335..9bb5d2ff04 100644--- a/server/lib/aiToolkit/internal/modelCatalog.js+++ b/server/lib/aiToolkit/internal/modelCatalog.js@@ -12,7 +12,7 @@* demands.** Kept in `internal/` (like `gateways.js` and `ollamaBacked.js`) because- * `providers.js` is the only caller and this directory stays self-contained —+ * `providerCatalogService.js` is the only caller and this directory stays self-contained —* no imports out to other PortOS modules (see ../AGENTS.md).*/diff --git a/server/lib/aiToolkit/internal/providerCatalogService.js b/server/lib/aiToolkit/internal/providerCatalogService.jsnew file mode 100644index 0000000000..9202fe3d5f--- /dev/null+++ b/server/lib/aiToolkit/internal/providerCatalogService.js@@ -0,0 +1,568 @@+import { readFile, readdir } from 'fs/promises';+import { existsSync } from 'fs';+import { homedir } from 'os';+import { join, isAbsolute, delimiter } from 'path';+import { execFile, spawn } from 'child_process';+import { promisify } from 'util';+import { assertSecretEndpoint, evaluateSecretEndpoint } from '../endpointGuard.js';+import { composeBootstrapSpawn } from './credentialBootstrap.js';+import { ANTIGRAVITY_CONFIGURED_DEFAULT, parseAntigravityModelList } from './antigravity.js';+import { CURSOR_COMMAND, parseCursorModelList } from './cursor.js';+import { ollamaBaseFromProvider } from './ollamaBacked.js';+import { providerModeGroups } from './providerModes.js';+import { ollamaRefreshGroupKey, resolveModelFetcher } from './modelFetchers.js';+import { modelCatalogUpdate, parseModelCatalog, toModelCatalog } from './modelCatalog.js';+import { CLAUDE_CATALOG_SUBPATH, catalogAge, claudeConfigDir, selectCatalogModels } from './claudeCodeCatalog.js';++const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];++function resolveWindowsExecutable(command, isWin32 = process.platform === 'win32', searchEnv = process.env) {+ if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;+ const pathDirs = (searchEnv.PATH || searchEnv.Path || '').split(delimiter).filter(Boolean);+ for (const dir of pathDirs) {+ for (const ext of WIN_EXECUTABLE_EXTS) {+ const candidate = join(dir, `${command}${ext}`);+ if (existsSync(candidate)) return candidate;+ }+ }+ return null;+}++const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;+const CMD_METACHAR_RE = /[&|<>^()]/g;+const NEEDS_NODE_QUOTING_RE = /[\s"]/;++function prepareWindowsSafeSpawn(command, args, isWin32 = process.platform === 'win32') {+ if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {+ return {+ command: 'cmd.exe',+ args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],+ };+ }+ return { command, args };+}++function escapeCmdMetacharsIfUnquoted(value) {+ const str = String(value);+ if (NEEDS_NODE_QUOTING_RE.test(str)) return str;+ return str.replace(CMD_METACHAR_RE, '^$&');+}++function resolveProbeSpawn(provider, defaultBin, args) {+ const spawned = composeBootstrapSpawn(provider, provider?.command || defaultBin, args);+ return { ...spawned, label: `'${spawned.command} ${spawned.args.join(' ')}'` };+}++const execFileAsync = (file, args, options) =>+ promisify(execFile)(file, args, { windowsHide: true, ...options });++const TOOL_USE_RE = new RegExp([+ 'qwen',+ 'llama-?3\\.[1-9]', 'llama-?4',+ 'mistral', 'mixtral', 'ministral', 'codestral', 'devstral', 'magistral',+ 'command-?r', 'command-?a', 'north-mini-code',+ 'firefunction', 'functionary', 'watt-tool', 'hermes', 'functiongemma',+ 'glm-?4',+ 'granite-?[34]',+ '(?:^|[-_/:])gemma-?4',+ 'gpt-oss',+ 'nemotron',+ 'olmo-?3',+ 'lfm2', 'ornith', 'muse-glimmer', 'nex-n2',+ 'smollm2',+ 'dflash',+ 'deepseek-v3', 'deepseek-r1', 'deepseek-v4',+].join('|'), 'i');++function ollamaModelSupportsTools(id, capabilities) {+ if (Array.isArray(capabilities) && capabilities.length > 0) {+ return capabilities.some((c) => String(c).toLowerCase() === 'tools');+ }+ return TOOL_USE_RE.test(String(id || ''));+}++export function createProviderCatalogService({+ loadProviders,+ saveProviders,+ withGatewayApiKey,+ cachedModelIds = null,+ sampleFile = null,+ defaultSamplePath,+}) {+ return {+ async testProvider(id) {+ const data = await loadProviders();+ const provider = withGatewayApiKey(data.providers[id], data.providers);+ if (!provider) return { success: false, error: 'Provider not found' };++ if (provider.type === 'cli' || provider.type === 'tui') {+ const isWin32 = process.platform === 'win32';+ const lookup = isWin32 ? 'where' : 'which';+ const probeCommand = composeBootstrapSpawn(provider, provider.command, []).command;+ const { stdout } = await execFileAsync(lookup, [probeCommand], { windowsHide: true })+ .catch(() => ({ stdout: '', stderr: 'not found' }));+ const commandPath = stdout.split(/\r?\n/).map(s => s.trim()).find(Boolean) || '';++ if (!commandPath) return { success: false, error: `Command '${probeCommand}' not found in PATH` };++ const searchEnv = { ...process.env, ...provider.envVars };+ const invokePath = (isWin32 && resolveWindowsExecutable(provider.command, isWin32, searchEnv)) || commandPath;+ let everSpawned = false;+ const tryVersion = async (flag) => {+ try {+ const { command: execCommand, args: execArgs } = prepareWindowsSafeSpawn(invokePath, [flag]);+ const out = await execFileAsync(execCommand, execArgs);+ everSpawned = true;+ return out?.stdout?.trim() || null;+ } catch (err) {+ if (typeof err?.code === 'number') everSpawned = true;+ return null;+ }+ };+ const versionOut = (await tryVersion('--version')) || (await tryVersion('-v'));+ if (!everSpawned) {+ return {+ success: false,+ error: `Resolved '${probeCommand}' to ${invokePath} but it could not be executed (a Windows .cmd/.bat npm shim is not directly spawnable by the agent runner)`,+ };+ }+ return { success: true, path: invokePath, version: versionOut || 'available' };+ }++ if (provider.type === 'api') {+ if (provider.apiKey) {+ const guard = evaluateSecretEndpoint(provider.endpoint, {+ allowCustomEndpoint: provider.allowCustomEndpoint === true,+ });+ if (!guard.allowed) return { success: false, error: `Endpoint blocked: ${guard.reason}` };+ }+ const modelsUrl = `${provider.endpoint}/models`;+ const response = await fetch(modelsUrl, {+ headers: provider.apiKey ? { Authorization: `Bearer ${provider.apiKey}` } : {},+ signal: AbortSignal.timeout(10000),+ }).catch(err => ({ ok: false, error: err.message }));++ if (!response.ok) return { success: false, error: `API not reachable: ${response.error || response.status}` };+ const models = await response.json().catch(() => ({ data: [] }));+ return {+ success: true,+ endpoint: provider.endpoint,+ models: models.data?.map(m => m.id) || [],+ };+ }++ return { success: false, error: 'Unknown provider type' };+ },++ async fetchProviderModelCatalog(id) {+ const data = await loadProviders();+ const provider = withGatewayApiKey(data.providers[id], data.providers);+ if (!provider) return null;++ let fetched = null;+ try {+ const tuiFetcher = provider.type === 'tui' ? resolveModelFetcher(provider) : null;+ const probe = provider.type === 'api'+ ? () => this._refreshAPIProviderModels(provider)+ : provider.type === 'cli'+ ? () => this._refreshCLIProviderModels(provider)+ : tuiFetcher+ ? () => this[tuiFetcher.fetch](provider)+ : null;++ if (!probe) {+ const unsupported = new Error(`Model refresh not supported for ${provider.type} provider '${provider.id}'`);+ unsupported.status = 400;+ throw unsupported;+ }+ fetched = await this._withCachedCheckpoints(provider, probe);+ } catch (error) {+ console.error(`Failed to refresh models for ${provider.name}:`, error.message);+ error.status = error.status || 502;+ throw error;+ }++ if (resolveModelFetcher(provider)?.key === 'pi' && Array.isArray(fetched)+ && fetched.length === 0 && provider.models?.length) {+ const error = new Error('Pi has no authenticated models. Use pi /login before refreshing the stored catalog.');+ error.status = 502;+ throw error;+ }+ const catalog = toModelCatalog(fetched);+ if (catalog === null) {+ const unsupported = new Error(`Model refresh returned nothing for provider '${provider.id}'`);+ unsupported.status = 400;+ throw unsupported;+ }+ return catalog;+ },++ async fetchProviderModels(id) {+ const catalog = await this.fetchProviderModelCatalog(id);+ return catalog === null ? null : catalog.models;+ },++ async refreshProviderModels(id) {+ const catalog = await this.fetchProviderModelCatalog(id);+ if (catalog === null) return null;+ const previous = (await this.getProviderById(id))?.modelContextWindows;+ return this.updateProvider(id, modelCatalogUpdate(catalog, previous));+ },++ async refreshProviderModelsBatch(ids) {+ const requested = [...new Set(Array.isArray(ids) ? ids : [])];+ if (requested.length === 0) return [];++ const data = await loadProviders();+ const groups = [];+ const byKey = new Map();+ for (const id of requested) {+ const provider = data.providers[id];+ if (!provider) {+ groups.push({ ids: [id], leadId: id, status: 'missing' });+ continue;+ }+ const key = ollamaRefreshGroupKey(provider);+ const existing = key ? byKey.get(key) : null;+ if (existing) {+ existing.ids.push(id);+ continue;+ }+ const group = { ids: [id], leadId: id, status: 'missing' };+ if (key) byKey.set(key, group);+ groups.push(group);+ }++ for (const group of groups) {+ if (!data.providers[group.leadId]) continue;+ const probed = await this.fetchProviderModelCatalog(group.leadId).then(+ (catalog) => ({ catalog }),+ (error) => ({ error })+ );+ if (probed.error) {+ group.status = 'failed';+ group.error = probed.error;+ continue;+ }+ if (!probed.catalog) continue;+ group.status = 'updated';+ group.catalog = probed.catalog;+ }++ const updated = groups.filter(group => group.status === 'updated');+ if (updated.length === 0) return groups;++ const fresh = await loadProviders();+ let changed = false;+ for (const group of updated) {+ for (const id of group.ids) {+ const provider = fresh.providers[id];+ if (!provider) continue;+ const modes = providerModeGroups(Object.values(fresh.providers)).find(entries => entries.some(entry => entry.id === id));+ for (const mode of modes || [provider]) {+ fresh.providers[mode.id] = {+ ...mode,+ ...modelCatalogUpdate(group.catalog, mode.modelContextWindows),+ };+ }+ changed = true;+ }+ }+ if (changed) await saveProviders(fresh);+ return groups;+ },++ async _refreshAPIProviderModels(provider) {+ if (provider.endpoint?.includes('ollama') || provider.endpoint?.includes(':11434')) {+ const ollamaUrl = `${provider.endpoint}/api/tags`;+ const response = await fetch(ollamaUrl, { signal: AbortSignal.timeout(8000) }).catch(() => null);+ if (response?.ok) {+ const data = await response.json().catch(() => null);+ if (data?.models) return data.models.map(m => m.name || m.model);+ }+ }++ assertSecretEndpoint(provider.endpoint, {+ hasSecret: Boolean(provider.apiKey),+ allowCustomEndpoint: provider.allowCustomEndpoint === true,+ });+ const modelsUrl = `${provider.endpoint}/models`;+ const headers = {};+ if (provider.apiKey) headers.Authorization = `Bearer ${provider.apiKey}`;+ const response = await fetch(modelsUrl, { headers, signal: AbortSignal.timeout(8000) }).catch(() => null);+ if (!response?.ok) throw new Error(`HTTP ${response?.status || 'error'}`);++ const responseData = await response.json().catch(() => null);+ if (!responseData || typeof responseData !== 'object') {+ throw new Error('Model list response was not valid JSON');+ }+ if (Array.isArray(responseData.data)) return parseModelCatalog(responseData.data, 'data');+ if (Array.isArray(responseData.models)) return parseModelCatalog(responseData.models, 'models');+ throw new Error('Model list response had no recognizable "data" or "models" array');+ },++ async _fetchMtplxModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },++ async _withCachedCheckpoints(provider, probeServed) {+ const [cached, probed] = await Promise.all([+ typeof cachedModelIds === 'function'+ ? Promise.resolve().then(() => cachedModelIds(provider)).catch(() => null)+ : null,+ probeServed().then((result) => ({ ok: true, result }), (error) => ({ ok: false, error })),+ ]);+ if (!Array.isArray(cached) || cached.length === 0) {+ if (!probed.ok) throw probed.error;+ return probed.result;+ }+ const catalog = toModelCatalog(probed.result) || { models: [], contextWindows: {} };+ const stale = !probed.ok && Array.isArray(provider?.models) ? provider.models : [];+ return {+ models: [...new Set([...catalog.models, ...stale, ...cached])],+ contextWindows: catalog.contextWindows,+ };+ },++ async _fetchLmstudioModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },++ async _fetchLlamaModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },++ async _fetchVllmModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },++ async _fetchSglangModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },++ async _fetchGatewayModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },++ async _refreshCLIProviderModels(provider) {+ const fetcher = resolveModelFetcher(provider);+ if (fetcher) return await this[fetcher.fetch](provider);+ const unsupported = new Error('Model refresh not supported for this CLI provider');+ unsupported.status = 400;+ throw unsupported;+ },++ async _fetchAntigravityModels(provider) {+ const listed = await this._execCliModelList(provider, 'agy', parseAntigravityModelList);+ return [ANTIGRAVITY_CONFIGURED_DEFAULT, ...new Set(listed)];+ },++ async _execCliModelList(provider, defaultBin, parse, listArgs = ['models'], isEmptyCatalog = () => false) {+ const spawned = resolveProbeSpawn(provider, defaultBin, listArgs);+ const probe = spawned.label;+ const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);+ const pending = execFileAsync(command, args, {+ timeout: 15000,+ env: { ...process.env, ...provider?.envVars },+ });+ pending.child?.stdin?.end();+ const { stdout } = await pending.catch((err) => {+ const output = `${err.stdout || ''}\n${err.stderr || ''}`;+ if (!err.killed && isEmptyCatalog(output)) return { stdout: output };+ throw new Error(`${probe} failed: ${err?.message || 'could not run the binary'}`);+ });+ const listed = parse(stdout);+ if (listed.length === 0 && !isEmptyCatalog(stdout)) {+ throw new Error(`${probe} returned no model ids`);+ }+ return listed;+ },++ async _fetchPiModels(provider) {+ const { PI_COMMAND, parsePiModelList } = await import('./pi.js');+ return this._execCliModelList(provider, PI_COMMAND, parsePiModelList, ['--list-models'],+ (stdout) => /No models available/i.test(stdout) && /\/login/.test(stdout));+ },++ async _fetchCursorModels(provider) {+ return await this._execCliModelList(provider, CURSOR_COMMAND, parseCursorModelList);+ },++ async _fetchCodexModels(provider) {+ const spawned = resolveProbeSpawn(provider, 'codex', ['app-server']);+ const probe = spawned.label;+ const childEnv = { ...process.env, ...provider?.envVars };+ const resolvedBin = resolveWindowsExecutable(spawned.command, process.platform === 'win32', childEnv) || spawned.command;+ const { command, args } = prepareWindowsSafeSpawn(resolvedBin, spawned.args);+ return new Promise((resolve, reject) => {+ let settled = false;+ let child;+ const settle = (err, result) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ try { child?.kill('SIGTERM'); } catch {}+ if (err) reject(err);+ else resolve(result);+ };+ const timer = setTimeout(() => {+ settle(new Error(`${probe} timed out waiting for model catalog`));+ }, 15000);+ timer.unref?.();+ try {+ child = spawn(command, args, {+ stdio: ['pipe', 'pipe', 'pipe'],+ env: childEnv,+ windowsHide: true,+ });+ } catch (err) {+ settle(new Error(`${probe} failed to spawn: ${err?.message || err}`));+ return;+ }+ child.on('error', (err) => settle(new Error(`${probe} failed: ${err?.message || err}`)));+ child.stdin?.on('error', () => {});+ child.on('exit', (code, signal) => settle(new Error(`${probe} exited prematurely with code ${code ?? signal}`)));++ let buffer = '';+ child.stdout?.on('data', (chunk) => {+ buffer += chunk.toString();+ const lines = buffer.split('\n');+ buffer = lines.pop() ?? '';+ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ try {+ const msg = JSON.parse(trimmed);+ if (msg.id === 1) {+ child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', method: 'initialized', params: {} }) + '\n');+ child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'model/list', params: {} }) + '\n');+ } else if (msg.id === 2) {+ if (msg.error) {+ settle(new Error(`${probe} model/list error: ${msg.error.message || JSON.stringify(msg.error)}`));+ return;+ }+ const rawModels = msg.result?.data || msg.result?.models || [];+ const ids = rawModels+ .filter(m => !m.hidden)+ .map(m => (typeof m === 'string' ? m : m?.id || m?.model))+ .filter(Boolean);+ if (ids.length === 0) {+ settle(new Error(`${probe} returned no model ids`));+ return;+ }+ settle(null, [...new Set(ids)]);+ return;+ }+ } catch {}+ }+ });+ child.stdin?.write(JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: { clientInfo: { name: 'portos', version: '1.0.0' } },+ }) + '\n');+ });+ },++ async _fetchOllamaToolCapableModels(provider) {+ const base = ollamaBaseFromProvider(provider);+ const res = await fetch(`${base}/api/tags`, { signal: AbortSignal.timeout(8000) }).catch(() => null);+ if (!res?.ok) throw new Error(`Ollama unreachable at ${base} (HTTP ${res?.status || 'error'})`);+ const data = await res.json().catch(() => null);+ const names = (data?.models || []).map(m => m.name || m.model).filter(Boolean);+ const checked = await Promise.all(names.map(async (name) => {+ const showRes = await fetch(`${base}/api/show`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ model: name, name }),+ signal: AbortSignal.timeout(8000),+ }).catch(() => null);+ const showData = showRes?.ok ? await showRes.json().catch(() => null) : null;+ const capabilities = Array.isArray(showData?.capabilities) ? showData.capabilities : null;+ return ollamaModelSupportsTools(name, capabilities) ? name : null;+ }));+ return checked.filter(Boolean);+ },++ async _fetchAnthropicModels(provider) {+ const env = { ...process.env, ...provider?.envVars };+ const configDir = claudeConfigDir(env, homedir());+ if (!configDir) throw new Error('Cannot locate the Claude Code config directory (no HOME and no CLAUDE_CONFIG_DIR)');+ const catalogDir = join(configDir, ...CLAUDE_CATALOG_SUBPATH);+ const files = await readdir(catalogDir).catch(() => null);+ if (!files) throw new Error(`Claude Code has not cached a model catalog yet (${catalogDir} is missing) — run \`claude\` once, then refresh`);++ const entries = (await Promise.all(+ files.filter(name => name.endsWith('.json')).map(async (name) => {+ const raw = await readFile(join(catalogDir, name), 'utf8').catch(() => null);+ if (raw === null) return null;+ try { return JSON.parse(raw); } catch { return null; }+ }),+ )).filter(Boolean);++ const cliVersion = await this._claudeCliVersion(provider);+ const models = selectCatalogModels(entries, { cliVersion });+ if (models.length === 0) {+ const present = selectCatalogModels(entries, { applyVersionFloor: false });+ if (present.length > 0) {+ throw new Error(`Claude Code ${cliVersion || 'unknown'} cannot select any model in the cached catalog — upgrade \`claude\`, then refresh`);+ }+ throw new Error(`No usable Claude Code model catalog in ${catalogDir} — run \`claude\` once, then refresh`);+ }++ const age = catalogAge(entries);+ const stamp = age ? new Date(age) : null;+ const cached = stamp && !Number.isNaN(stamp.getTime()) ? stamp.toISOString() : 'unknown';+ console.log(`📋 Claude Code catalog: ${models.length} models (cached ${cached})`);+ return models;+ },++ async _claudeCliVersion(provider) {+ const spawned = resolveProbeSpawn(provider, 'claude', ['--version']);+ const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);+ const pending = execFileAsync(command, args, {+ timeout: 10000,+ env: { ...process.env, ...provider?.envVars },+ });+ pending.child?.stdin?.end();+ const { stdout } = await pending.catch(() => ({ stdout: '' }));+ return (/(\d+\.\d+\.\d+)/.exec(stdout || '') || [])[1] || '';+ },++ async _fetchGeminiModels(provider) {+ const apiKey = provider.apiKey || process.env.GOOGLE_API_KEY;+ if (!apiKey) {+ const missingKey = new Error('Google API key required for model refresh');+ missingKey.status = 400;+ throw missingKey;+ }+ const response = await fetch(+ `https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`,+ { signal: AbortSignal.timeout(8000) }+ ).catch(() => null);+ if (!response?.ok) throw new Error(`HTTP ${response?.status || 'error'}`);+ const data = await response.json().catch(() => ({ models: [] }));+ return (data.models || [])+ .filter(m => m.supportedGenerationMethods?.includes('generateContent'))+ .map(m => m.name.replace('models/', ''));+ },++ async getSampleProviders() {+ const data = await loadProviders();+ const existingIds = new Set(Object.keys(data.providers));+ let sampleProviders = {};+ if (existsSync(defaultSamplePath)) {+ const content = await readFile(defaultSamplePath, 'utf-8');+ const parsed = JSON.parse(content);+ sampleProviders = { ...parsed.providers };+ }+ if (sampleFile && existsSync(sampleFile)) {+ const content = await readFile(sampleFile, 'utf-8');+ const parsed = JSON.parse(content);+ sampleProviders = { ...sampleProviders, ...parsed.providers };+ }+ return Object.values(sampleProviders).filter(p => !existingIds.has(p.id));+ },+ };+}diff --git a/server/lib/aiToolkit/internal/providerCrudService.js b/server/lib/aiToolkit/internal/providerCrudService.jsnew file mode 100644index 0000000000..0f9dbd725a--- /dev/null+++ b/server/lib/aiToolkit/internal/providerCrudService.js@@ -0,0 +1,134 @@+import { isCompositeProviderId } from './providerRef.js';++export function createProviderCrudService({+ loadProviders,+ saveProviders,+ buildProviderRecord,+ storeProviderRecords,+ withGatewayModelAccess,+ readProvider,+ resolveCompositeProvider = null,+ expandModePair,+ modeSiblingPayload,+ providerModeGroups,+ sharedModeUpdates,+ normalizeModelAccess,+}) {+ const normalizeClearedFields = (record) => {+ if (record.credentialBootstrap === null) delete record.credentialBootstrap;+ if (Object.hasOwn(record, 'modelAccess')) {+ const normalized = normalizeModelAccess(record.modelAccess);+ if (normalized) record.modelAccess = normalized;+ else delete record.modelAccess;+ }+ };++ return {+ async getAllProviders() {+ const data = await loadProviders();+ return {+ activeProvider: data.activeProvider,+ providers: Object.values(data.providers).map(provider => withGatewayModelAccess(provider, data.providers))+ };+ },++ async getProviderById(id) {+ const data = await loadProviders();+ const stored = readProvider(data.providers[id], data.providers);+ if (stored || typeof resolveCompositeProvider !== 'function' || !isCompositeProviderId(id)) return stored;+ return (await resolveCompositeProvider(id)) ?? null;+ },++ async getActiveProvider() {+ const data = await loadProviders();+ if (!data.activeProvider) return null;+ return readProvider(data.providers[data.activeProvider], data.providers);+ },++ async setActiveProvider(id) {+ const data = await loadProviders();+ if (!data.providers[id]) return null;+ data.activeProvider = id;+ await saveProviders(data);+ return data.providers[id];+ },++ async createProvider(providerData) {+ const data = await loadProviders();+ const provider = buildProviderRecord(data.providers, providerData);+ storeProviderRecords(data, [provider]);+ await saveProviders(data);+ return provider;+ },++ async createProviderModes(providerData) {+ const split = expandModePair(providerData);+ if (!split) throw new Error('createProviderModes requires a modes declaration');++ const data = await loadProviders();+ const created = split.map(modeData => buildProviderRecord(data.providers, modeData));+ storeProviderRecords(data, created);+ await saveProviders(data);+ return created;+ },++ async createProviderTuiMode(id, tuiOverrides = {}) {+ const data = await loadProviders();+ const stored = data.providers[id];+ if (!stored) return null;+ if (stored.type !== 'cli') throw new Error('Only a CLI provider can gain a TUI mode');++ const created = buildProviderRecord(data.providers, modeSiblingPayload(stored, 'tui', tuiOverrides));+ storeProviderRecords(data, [created]);+ await saveProviders(data);+ return created;+ },++ async updateProvider(id, updates) {+ const data = await loadProviders();+ if (!data.providers[id]) return null;++ const provider = { ...data.providers[id], ...updates, id };+ normalizeClearedFields(provider);++ const group = providerModeGroups(Object.values(data.providers)).find(modes => modes.some(mode => mode.id === id));+ data.providers[id] = provider;+ for (const sibling of group || []) {+ if (sibling.id === id) continue;+ Object.assign(sibling, sharedModeUpdates(updates));+ normalizeClearedFields(sibling);+ }+ await saveProviders(data);+ return provider;+ },++ async applyProviderPatches(patches) {+ const data = await loadProviders();+ const applied = [];+ for (const [id, updates] of Object.entries(patches || {})) {+ if (!data.providers[id]) continue;+ data.providers[id] = { ...data.providers[id], ...updates, id };+ applied.push(id);+ }+ if (applied.length > 0) await saveProviders(data);+ return applied;+ },++ async deleteProvider(id) {+ const data = await loadProviders();+ if (!data.providers[id]) return false;++ const group = providerModeGroups(Object.values(data.providers)).find(modes => modes.some(mode => mode.id === id));+ const removed = (group || []).map(mode => mode.id);+ for (const modeId of removed) delete data.providers[modeId];++ if (removed.includes(data.activeProvider)) {+ const remaining = Object.keys(data.providers);+ data.activeProvider = remaining.length > 0 ? remaining[0] : null;+ }++ await saveProviders(data);+ return true;+ },+ };+}diff --git a/server/lib/aiToolkit/internal/providerServiceState.js b/server/lib/aiToolkit/internal/providerServiceState.jsnew file mode 100644index 0000000000..e21dc938c3--- /dev/null+++ b/server/lib/aiToolkit/internal/providerServiceState.js@@ -0,0 +1,369 @@+import { readFile, rename } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { atomicWrite } from './atomicWrite.js';+import { ensureAntigravityPrintArgs, ensureAntigravityTuiArgs, ANTIGRAVITY_CLI_ID, ANTIGRAVITY_CONFIGURED_DEFAULT, ANTIGRAVITY_TUI_ID, LEGACY_GEMINI_CLI_ID, LEGACY_GEMINI_TUI_ID } from './antigravity.js';+import { unifyProviderModes } from './providerModes.js';+import { modelContextWindowPatch } from './modelCatalog.js';+import { normalizeModelAccess } from './modelAccess.js';++const CODEX_CONFIGURED_DEFAULT = 'codex-configured-default';+const CODEX_MODEL_KEYS = ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel'];+const CODEX_MODELS = [+ 'gpt-6-astra',+ 'gpt-5.6-sol',+ 'gpt-5.6-terra',+ 'gpt-5.6-luna',+ 'gpt-5.5',+ 'gpt-5.4',+ 'gpt-5.4-mini',+ 'gpt-5.3-codex-spark',+];+const CODEX_MODEL_DEFAULTS = {+ defaultModel: 'gpt-5.6-terra',+ lightModel: 'gpt-5.6-luna',+ mediumModel: 'gpt-5.6-terra',+ heavyModel: 'gpt-5.6-sol',+};+const PRIOR_CODEX_MODEL_CATALOGS = [+ ['gpt-5.6-luna', 'gpt-5.6-terra', 'gpt-5.6-sol'],+ ['gpt-5.6-luna', 'gpt-5.6-terra', 'gpt-5.6-sol', 'gpt-5.3-codex-spark'],+];+const ANTIGRAVITY_MODEL_KEYS = ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel'];+const ANTIGRAVITY_MODELS = [+ 'gemini-3.8-flash-high', 'gemini-3.8-flash-medium', 'gemini-3.8-flash-low',+ 'gemini-3.7-flash-high', 'gemini-3.7-flash-medium', 'gemini-3.7-flash-low',+ 'gemini-3.6-flash-high', 'gemini-3.6-flash-medium', 'gemini-3.6-flash-low',+ 'gemini-3.1-pro-high', 'gemini-3.1-pro-low', 'claude-sonnet-4-6',+ 'claude-opus-4-6-thinking', 'gpt-oss-120b-medium',+];+const ANTIGRAVITY_MODEL_CATALOG = [ANTIGRAVITY_CONFIGURED_DEFAULT, ...ANTIGRAVITY_MODELS];+const PRIOR_ANTIGRAVITY_MODEL_CATALOGS = [+ [+ ANTIGRAVITY_CONFIGURED_DEFAULT,+ 'gemini-3.6-flash-high', 'gemini-3.6-flash-medium', 'gemini-3.6-flash-low',+ 'gemini-3.5-flash-high', 'gemini-3.5-flash-medium', 'gemini-3.5-flash-low',+ 'gemini-3.1-pro-high', 'gemini-3.1-pro-low', 'claude-sonnet-4-6',+ 'claude-opus-4-6-thinking', 'gpt-oss-120b-medium',+ ],+ [+ ANTIGRAVITY_CONFIGURED_DEFAULT,+ 'gemini-3.7-flash-high', 'gemini-3.7-flash-medium', 'gemini-3.7-flash-low',+ 'gemini-3.6-flash-high', 'gemini-3.6-flash-medium', 'gemini-3.6-flash-low',+ 'gemini-3.5-flash-high', 'gemini-3.5-flash-medium', 'gemini-3.5-flash-low',+ 'gemini-3.1-pro-high', 'gemini-3.1-pro-low', 'claude-sonnet-4-6',+ 'claude-opus-4-6-thinking', 'gpt-oss-120b-medium',+ ],+];+const CODEX_CONTEXT_WINDOW = 1_000_000;+const GEMINI_CONTEXT_WINDOW = 1_048_576;+const STALE_GENERIC_CONTEXT_WINDOW = 128_000;++function matchesAnyExactCatalog(models, catalogs) {+ return Array.isArray(models) && catalogs.some(+ catalog => catalog.length === models.length && catalog.every((model, index) => model === models[index]),+ );+}++function shouldUpgradeContextWindow(value) {+ return value == null || Number(value) === STALE_GENERIC_CONTEXT_WINDOW;+}++function canonicalProviderContextWindow(provider) {+ if (provider?.type !== 'cli' && provider?.type !== 'tui') return null;+ const id = String(provider?.id || '').toLowerCase();+ const command = String(provider?.command || '').toLowerCase();+ if (id === 'codex' || id === 'codex-tui' || command === 'codex') return CODEX_CONTEXT_WINDOW;+ if (id === ANTIGRAVITY_CLI_ID || id === ANTIGRAVITY_TUI_ID || command === 'agy') return GEMINI_CONTEXT_WINDOW;+ return null;+}++function migrateCodexProvider(data) {+ if (!data?.providers) return false;+ let changed = false;+ for (const provider of Object.values(data.providers)) {+ const isCodexProcessProvider = (provider?.id === 'codex' || provider?.id === 'codex-tui')+ && (provider?.type === 'cli' || provider?.type === 'tui');+ if (!isCodexProcessProvider) continue;+ const isSentinelOnly = Array.isArray(provider.models)+ && provider.models.length === 1+ && provider.models[0] === CODEX_CONFIGURED_DEFAULT+ && CODEX_MODEL_KEYS.every(key => provider[key] === CODEX_CONFIGURED_DEFAULT);+ const isPriorSeededList = matchesAnyExactCatalog(provider.models, PRIOR_CODEX_MODEL_CATALOGS);+ if (!isSentinelOnly && !isPriorSeededList) continue;+ provider.models = [...CODEX_MODELS];+ if (isSentinelOnly) Object.assign(provider, CODEX_MODEL_DEFAULTS);+ changed = true;+ }+ return changed;+}++function stripLegacyModelPin(args) {+ const out = [];+ for (let i = 0; i < args.length; i++) {+ const arg = args[i];+ if (arg === '--model') {+ const next = args[i + 1];+ if (typeof next === 'string' && !next.startsWith('-')) i += 1;+ continue;+ }+ if (typeof arg === 'string' && arg.startsWith('--model=')) continue;+ out.push(arg);+ }+ return out;+}++function migrateAntigravityProviders(data) {+ if (!data?.providers) return false;+ let changed = false;+ const mappings = [+ { legacyId: LEGACY_GEMINI_CLI_ID, targetId: ANTIGRAVITY_CLI_ID, name: 'Antigravity CLI', type: 'cli', timeout: 300000 },+ { legacyId: LEGACY_GEMINI_TUI_ID, targetId: ANTIGRAVITY_TUI_ID, name: 'Antigravity TUI', type: 'tui', timeout: 600000 },+ ];+ for (const mapping of mappings) {+ const legacy = data.providers[mapping.legacyId];+ if (!legacy) continue;+ if (!data.providers[mapping.targetId]) {+ const envVars = { ...(legacy.envVars || {}) };+ delete envVars.GEMINI_SANDBOX;+ const legacyArgs = stripLegacyModelPin(legacy.args || []);+ const migrated = {+ ...legacy,+ id: mapping.targetId,+ name: mapping.name,+ type: mapping.type,+ command: 'agy',+ args: mapping.type === 'cli'+ ? ensureAntigravityPrintArgs(legacyArgs)+ : ensureAntigravityTuiArgs(legacyArgs),+ models: [...ANTIGRAVITY_MODEL_CATALOG],+ timeout: legacy.timeout || mapping.timeout,+ envVars,+ };+ for (const key of ANTIGRAVITY_MODEL_KEYS) migrated[key] = ANTIGRAVITY_CONFIGURED_DEFAULT;+ data.providers[mapping.targetId] = migrated;+ }+ if (data.activeProvider === mapping.legacyId) data.activeProvider = mapping.targetId;+ for (const p of Object.values(data.providers)) {+ if (p.fallbackProvider === mapping.legacyId) p.fallbackProvider = mapping.targetId;+ }+ delete data.providers[mapping.legacyId];+ changed = true;+ }+ return changed;+}++function migrateAntigravityModelCatalog(data) {+ if (!data?.providers) return false;+ let changed = false;+ for (const provider of Object.values(data.providers)) {+ const isAntigravityProcessProvider = (provider?.id === ANTIGRAVITY_CLI_ID || provider?.id === ANTIGRAVITY_TUI_ID)+ && (provider?.type === 'cli' || provider?.type === 'tui');+ if (!isAntigravityProcessProvider) continue;+ const isSentinelOnly = Array.isArray(provider.models)+ && provider.models.length === 1+ && provider.models[0] === ANTIGRAVITY_CONFIGURED_DEFAULT;+ const isPriorSeededList = matchesAnyExactCatalog(provider.models, PRIOR_ANTIGRAVITY_MODEL_CATALOGS);+ if (!isSentinelOnly && !isPriorSeededList) continue;+ provider.models = [...ANTIGRAVITY_MODEL_CATALOG];+ changed = true;+ }+ return changed;+}++function migrateProviderContextWindows(data) {+ if (!data?.providers) return false;+ let changed = false;+ for (const provider of Object.values(data.providers)) {+ const contextWindow = canonicalProviderContextWindow(provider);+ if (!contextWindow || !shouldUpgradeContextWindow(provider.contextWindow)) continue;+ provider.contextWindow = contextWindow;+ changed = true;+ }+ return changed;+}++export function createProviderServiceState(config = {}) {+ const {+ dataDir = './data',+ providersFile = 'providers.json',+ sampleFile = null,+ providersCacheTtlMs = 1000,+ onProvidersSaved = null,+ cachedModelIds = null,+ resolveCompositeProvider = null,+ } = config;+ const providersPath = join(dataDir, providersFile);+ let providersCache = null;+ let providersCacheAt = -Infinity;+ let providersLoadInFlight = null;+ let cacheGeneration = 0;++ function refreshProvidersCache(data) {+ if (data?.providers && Object.getPrototypeOf(data.providers) !== null) {+ data.providers = Object.assign(Object.create(null), data.providers);+ }+ providersCache = data;+ providersCacheAt = Date.now();+ cacheGeneration += 1;+ return data;+ }++ function invalidateProvidersCache() {+ providersCache = null;+ providersCacheAt = -Infinity;+ cacheGeneration += 1;+ }++ async function parseOrRescue(content, source) {+ try {+ return JSON.parse(content);+ } catch (err) {+ const corruptPath = `${source}.corrupt.${Date.now()}`;+ console.error(`❌ providers.json parse failed (${err.message}); renamed to ${corruptPath} and starting from empty`);+ await rename(source, corruptPath).catch(() => {});+ return { activeProvider: null, providers: {} };+ }+ }++ async function readProvidersFromDisk() {+ if (!existsSync(providersPath)) {+ if (sampleFile && existsSync(sampleFile)) {+ const sample = await readFile(sampleFile, 'utf-8');+ let parsed;+ try {+ parsed = JSON.parse(sample);+ } catch (err) {+ console.error(`❌ sample providers file ${sampleFile} parse failed (${err.message}); starting from empty`);+ return { activeProvider: null, providers: {} };+ }+ unifyProviderModes(parsed);+ await atomicWrite(providersPath, parsed);+ return parsed;+ }+ return { activeProvider: null, providers: {} };+ }++ const content = await readFile(providersPath, 'utf-8');+ const data = await parseOrRescue(content, providersPath);+ const migratedCodex = migrateCodexProvider(data);+ const migratedAntigravity = migrateAntigravityProviders(data);+ const migratedAntigravityModels = migrateAntigravityModelCatalog(data);+ const migratedContextWindows = migrateProviderContextWindows(data);+ const migratedModes = unifyProviderModes(data);+ if (migratedModes || migratedCodex || migratedAntigravity || migratedAntigravityModels || migratedContextWindows) {+ await atomicWrite(providersPath, data);+ if (migratedCodex) console.log('🔧 Migrated Codex providers to the selectable model catalog');+ if (migratedAntigravity) console.log('🔧 Migrated Gemini provider config to Antigravity CLI (agy)');+ if (migratedAntigravityModels) console.log('🔧 Migrated Antigravity providers to the selectable agy model catalog');+ if (migratedContextWindows) console.log('🔧 Migrated provider context windows to current canonical values');+ }+ return data;+ }++ async function loadProviders() {+ if (providersCache && (Date.now() - providersCacheAt) < providersCacheTtlMs) return providersCache;+ if (providersLoadInFlight) return providersLoadInFlight;+ const generation = cacheGeneration;+ providersLoadInFlight = readProvidersFromDisk()+ .then(data => {+ if (cacheGeneration === generation) return refreshProvidersCache(data);+ return providersCache ?? data;+ })+ .finally(() => { providersLoadInFlight = null; });+ return providersLoadInFlight;+ }++ async function notifyProvidersSaved(data) {+ if (typeof onProvidersSaved !== 'function') return;+ try {+ await onProvidersSaved(data);+ } catch (err) {+ console.error(`❌ providers save hook failed: ${err.message}`);+ }+ }++ async function saveProviders(data) {+ invalidateProvidersCache();+ await atomicWrite(providersPath, data);+ refreshProvidersCache(data);+ await notifyProvidersSaved(data);+ }++ function buildProviderRecord(existing, providerData) {+ const id = providerData.id || providerData.name.toLowerCase().replace(/[^a-z0-9]/g, '-');+ if (existing[id]) throw new Error('Provider with this ID already exists');+ const modelAccess = normalizeModelAccess(providerData.modelAccess);+ const provider = {+ id,+ name: providerData.name,+ type: providerData.type || 'cli',+ command: providerData.command || null,+ args: providerData.args || [],+ endpoint: providerData.endpoint || null,+ apiKey: providerData.apiKey || '',+ models: providerData.models || [],+ ...(providerData.hardwareRequirements ? { hardwareRequirements: providerData.hardwareRequirements } : {}),+ ...(providerData.modelHardwareRequirements ? { modelHardwareRequirements: providerData.modelHardwareRequirements } : {}),+ defaultModel: providerData.defaultModel || null,+ effort: providerData.effort || null,+ lightModel: providerData.lightModel || null,+ mediumModel: providerData.mediumModel || null,+ heavyModel: providerData.heavyModel || null,+ ultraModel: providerData.ultraModel || null,+ fallbackProvider: providerData.fallbackProvider || null,+ fallbackModel: providerData.fallbackModel || null,+ numCtx: providerData.numCtx || null,+ temperature: providerData.temperature,+ topP: providerData.topP,+ thinking: providerData.thinking,+ contextWindow: providerData.contextWindow || null,+ ...modelContextWindowPatch(providerData.modelContextWindows),+ timeout: providerData.timeout || 300000,+ enabled: providerData.enabled !== false,+ ...(typeof providerData.textTransport === 'string' && providerData.textTransport ? { textTransport: providerData.textTransport } : {}),+ ...(providerData.textTransportEnabled === true ? { textTransportEnabled: true } : {}),+ ...(providerData.textTransportReadRiskAcknowledged === true ? { textTransportReadRiskAcknowledged: true } : {}),+ ...(providerData.ollamaBacked === true ? { ollamaBacked: true } : {}),+ ...(providerData.lmstudioBacked === true ? { lmstudioBacked: true } : {}),+ ...(providerData.mtplxBacked === true ? { mtplxBacked: true } : {}),+ ...(providerData.llamaBacked === true ? { llamaBacked: true } : {}),+ ...(providerData.vllmBacked === true ? { vllmBacked: true } : {}),+ ...(providerData.sglangBacked === true ? { sglangBacked: true } : {}),+ ...(typeof providerData.gatewayBacked === 'string' && providerData.gatewayBacked ? { gatewayBacked: providerData.gatewayBacked } : {}),+ ...(providerData.orcarouterBacked === true ? { orcarouterBacked: true } : {}),+ ...(modelAccess ? { modelAccess } : {}),+ ...(providerData.allowCustomEndpoint === true ? { allowCustomEndpoint: true } : {}),+ ...(providerData.ignoreUserConfig === true ? { ignoreUserConfig: true } : {}),+ ...(providerData.credentialBootstrap?.command ? { credentialBootstrap: providerData.credentialBootstrap } : {}),+ envVars: providerData.envVars || {},+ secretEnvVars: providerData.secretEnvVars || [],+ headlessArgs: providerData.headlessArgs || [],+ tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,+ ...(providerData.tuiIdleTimeoutMs != null ? { tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs } : {}),+ ...Object.fromEntries(['harnessId', 'method', 'serviceId', 'credentialBootstrapId']+ .filter(key => typeof providerData[key] === 'string' && providerData[key])+ .map(key => [key, providerData[key]])),+ ...(Array.isArray(providerData.catalogNarrowing) ? { catalogNarrowing: [...providerData.catalogNarrowing] } : {}),+ };+ return provider;+ }++ function storeProviderRecords(data, records) {+ for (const record of records) {+ data.providers[record.id] = record;+ if (!data.activeProvider) data.activeProvider = record.id;+ }+ unifyProviderModes(data);+ }++ return {+ loadProviders,+ saveProviders,+ buildProviderRecord,+ storeProviderRecords,+ sampleFile,+ cachedModelIds,+ resolveCompositeProvider,+ };+}diff --git a/server/lib/aiToolkit/providers.decomposition.test.js b/server/lib/aiToolkit/providers.decomposition.test.jsnew file mode 100644index 0000000000..be87115a4d--- /dev/null+++ b/server/lib/aiToolkit/providers.decomposition.test.js@@ -0,0 +1,76 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, rm } from 'fs/promises';+import { readFileSync } from 'fs';+import { tmpdir } from 'os';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { createProviderService } from './providers.js';++const here = dirname(fileURLToPath(import.meta.url));+const source = (name) => readFileSync(join(here, name), 'utf8');+const methodNames = [+ 'getAllProviders', 'getProviderById', 'getActiveProvider', 'setActiveProvider',+ 'createProvider', 'createProviderModes', 'createProviderTuiMode', 'updateProvider',+ 'applyProviderPatches', 'deleteProvider', 'testProvider', 'fetchProviderModelCatalog',+ 'fetchProviderModels', 'refreshProviderModels', 'refreshProviderModelsBatch',+ '_refreshAPIProviderModels', '_fetchMtplxModels', '_withCachedCheckpoints',+ '_fetchLmstudioModels', '_fetchLlamaModels', '_fetchVllmModels', '_fetchSglangModels',+ '_fetchGatewayModels', '_refreshCLIProviderModels', '_fetchAntigravityModels',+ '_execCliModelList', '_fetchPiModels', '_fetchCursorModels', '_fetchCodexModels',+ '_fetchOllamaToolCapableModels', '_fetchAnthropicModels', '_claudeCliVersion',+ '_fetchGeminiModels', 'getSampleProviders',+];++describe('provider service decomposition', () => {+ let dataDir;++ afterEach(async () => {+ vi.restoreAllMocks();+ if (dataDir) await rm(dataDir, { recursive: true, force: true });+ });++ it('keeps the facade method surface and cross-method spy dispatch', async () => {+ dataDir = await mkdtemp(join(tmpdir(), 'portos-provider-decomposition-'));+ const service = createProviderService({ dataDir, providersFile: 'providers.json' });+ expect(Object.keys(service)).toEqual(methodNames);++ const provider = await service.createProvider({ name: 'Example', type: 'cli', command: 'example' });+ const fetch = vi.spyOn(service, 'fetchProviderModelCatalog').mockResolvedValue({+ models: ['fresh'],+ contextWindows: { fresh: 4096 },+ });+ const updated = await service.refreshProviderModels(provider.id);++ expect(fetch).toHaveBeenCalledWith(provider.id);+ expect(updated.models).toEqual(['fresh']);+ expect((await service.getProviderById(provider.id)).modelContextWindows).toEqual({ fresh: 4096 });+ });++ it('keeps CRUD and catalog responsibilities in private factories', async () => {+ const facade = source('providers.js');+ const state = source('internal/providerServiceState.js');+ const crud = source('internal/providerCrudService.js');+ const catalog = source('internal/providerCatalogService.js');++ expect(facade).toContain('createProviderServiceState');+ expect(facade).toContain('createProviderCrudService');+ expect(facade).toContain('createProviderCatalogService');+ expect(facade).not.toContain('async fetchProviderModelCatalog');+ expect(facade).not.toContain('async createProvider');+ expect(state).toContain('export function createProviderServiceState');+ expect(state).toContain('async function loadProviders');+ expect(state).toContain('async function saveProviders');+ expect(crud).toContain('export function createProviderCrudService');+ expect(crud).toContain('async getAllProviders');+ expect(crud).toContain('async updateProvider');+ expect(crud).not.toContain('async fetchProviderModelCatalog');+ expect(catalog).toContain('export function createProviderCatalogService');+ expect(catalog).toContain('async fetchProviderModelCatalog');+ expect(catalog).toContain('async getSampleProviders');+ expect(catalog).not.toContain('async updateProvider');+ expect(facade).not.toMatch(/\bclass\s/);+ expect(state).not.toMatch(/\bclass\s/);+ expect(crud).not.toMatch(/\bclass\s/);+ expect(catalog).not.toMatch(/\bclass\s/);+ });+});diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 61c99e15f6..28bcea9f81 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -1,65 +1,19 @@-import { composeBootstrapSpawn } from './internal/credentialBootstrap.js';-import { expandModePair, modeSiblingPayload, providerModeGroups, sharedModeUpdates, unifyProviderModes } from './internal/providerModes.js';-import { readFile, readdir, rename } from 'fs/promises';-import { homedir } from 'os';-import { existsSync } from 'fs';-import { join, dirname, delimiter, isAbsolute } from 'path';-import { atomicWrite } from './internal/atomicWrite.js';-import { assertSecretEndpoint, evaluateSecretEndpoint } from './endpointGuard.js';+import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { execFile, spawn } from 'child_process';-import { promisify } from 'util';-import {- ANTIGRAVITY_CLI_ID,- ANTIGRAVITY_CONFIGURED_DEFAULT,- ANTIGRAVITY_TUI_ID,- ensureAntigravityPrintArgs,- ensureAntigravityTuiArgs,- LEGACY_GEMINI_CLI_ID,- LEGACY_GEMINI_TUI_ID,- parseAntigravityModelList,-} from './internal/antigravity.js';-import {- CURSOR_COMMAND,- parseCursorModelList,-} from './internal/cursor.js';-import { isOllamaBackedProvider, ollamaBaseFromProvider } from './internal/ollamaBacked.js';-import { gatewayForProvider, isGatewayBackedProvider } from './internal/gateways.js';-import { canRefreshModels, ollamaRefreshGroupKey, resolveModelFetcher } from './internal/modelFetchers.js';-import { modelCatalogUpdate, modelContextWindowPatch, parseModelCatalog, toModelCatalog } from './internal/modelCatalog.js';+import { createProviderCrudService } from './internal/providerCrudService.js';+import { createProviderCatalogService } from './internal/providerCatalogService.js';+import { createProviderServiceState } from './internal/providerServiceState.js';+import { expandModePair, modeSiblingPayload, providerModeGroups, sharedModeUpdates } from './internal/providerModes.js';+import { gatewayForProvider } from './internal/gateways.js';import { normalizeModelAccess } from './internal/modelAccess.js';-import { isCompositeProviderId } from './internal/providerRef.js';-import {- CLAUDE_CATALOG_SUBPATH,- catalogAge,- claudeConfigDir,- selectCatalogModels,-} from './internal/claudeCodeCatalog.js';-// Re-exported (rather than defined here) so the model-fetcher table can key its-// ollama row on the same predicate without importing back into this module.-export { isOllamaBackedProvider, isGatewayBackedProvider };-// Groups providers that share one daemon + one probe shape, so a host fanning a-// refresh across them can fetch once instead of once per provider. The base-URL-// normalizer it keys on stays internal — the group key IS the contract, and an-// exported normalizer only invites callers to re-derive the grouping rule.-export { ollamaRefreshGroupKey };-// The pure capability predicate that both refresh arms below dispatch through —-// exported so the providers route can decorate its payload with it and the-// client stops re-deriving refreshability from command/name string sniffing.-export { canRefreshModels };+export { isOllamaBackedProvider } from './internal/ollamaBacked.js';+export { isGatewayBackedProvider } from './internal/gateways.js';+export { ollamaRefreshGroupKey, canRefreshModels } from './internal/modelFetchers.js';const __dirname = dirname(fileURLToPath(import.meta.url));const DEFAULT_SAMPLE_PATH = join(__dirname, 'defaults/providers.sample.json');-// Gateway-backed OpenCode wrappers intentionally keep no key in their persisted-// record. Attach the sibling API key only to execution-time copies, and make-// the property non-enumerable so provider responses and provider writes cannot-// accidentally expose or persist it.-//-// The sibling is looked up by the wrapper's OWN gateway id (internal/gateways.js),-// never a hardcoded one — an OrcaRouter key must not leak into an OpenRouter-// wrapper, which would send a secret to the wrong host.function withGatewayApiKey(provider, providers) {const gateway = gatewayForProvider(provider);const siblingKey = gateway ? providers?.[gateway.id]?.apiKey : null;@@ -73,32 +27,6 @@ function withGatewayApiKey(provider, providers) {return executionProvider;}-/**- * Resolve the MODEL ACCESS policy a provider read is governed by, stamped as- * the derived `modelAccessEffective` (+ `modelAccessSource`) rather than folded- * into the persisted `modelAccess` field.- *- * A gateway-backed OpenCode wrapper front-ends the SAME upstream catalog as the- * sibling `api` record whose id equals the gateway id — one NVIDIA NIM- * entitlement serves the api provider, its CLI wrapper and its TUI wrapper — so- * a wrapper with no policy of its own inherits the gateway's. Exactly the- * inheritance {@link withGatewayApiKey} already performs for the key, and for- * the same reason: the wrapper stores nothing the gateway record owns.- *- * Two separate field names, not one, because the resolved value must never be- * able to become the wrapper's OWN stored policy: `modelAccess` is in- * `providerSchema`, so a client that echoes a GET back on a PUT would persist- * whatever it was handed. `modelAccessEffective` is not in the schema and is- * stripped by `providerSchema.partial()`, which keeps inheritance live — a- * later edit to the gateway still reaches every wrapper.- *- * Returns the SAME object when no policy applies, so an install that has not- * configured this sees no change at all.- *- * Composition order against {@link withGatewayApiKey} is load-bearing: that one- * attaches the sibling key as a NON-ENUMERABLE property, which a spread here- * would silently drop. This runs first and the key attach stays outermost.- */function withGatewayModelAccess(provider, providers) {if (!provider || typeof provider !== 'object') return provider;const own = normalizeModelAccess(provider.modelAccess);@@ -109,1914 +37,42 @@ function withGatewayModelAccess(provider, providers) {return { ...provider, modelAccessEffective: inherited, modelAccessSource: gateway.id };}-/**- * One provider as a READ sees it: the gateway's model-access policy resolved,- * then the gateway's API key attached. In that order — the key rides as a- * NON-enumerable property, so a spread after it would silently drop the- * credential and every wrapper run would lose it.- */const readProvider = (provider, providers) => (provider? withGatewayApiKey(withGatewayModelAccess(provider, providers), providers): null);-// Extensions Windows can launch directly, checked in cmd.exe's own resolution-// preference. Deliberately excludes an extension-less match — npm ships a-// POSIX shell-script stub alongside a package's `.cmd`/`.bat`/`.ps1` Windows-// wrappers (for Git Bash/WSL); that stub is not natively launchable here, and-// is exactly what `where` can return as its first match (see #1865 — the-// issue's literal error text was produced by this function resolving that-// stub as `commandPath`, not by a missing shell).-const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];--/**- * Resolve a bare command name to its full path WITH extension on Windows —- * mirrors `resolveWindowsExecutable` in `server/lib/bufferedSpawn.js`- * (duplicated here for this directory's self-containment; see ./AGENTS.md).- * Filesystem-only (no subprocess), so it can't reorder/misselect the way a- * raw `where` first-line read can.- */-function resolveWindowsExecutable(command, isWin32 = process.platform === 'win32', searchEnv = process.env) {- if (!isWin32 || !command || isAbsolute(command) || /[\\/]/.test(command)) return null;- const pathDirs = (searchEnv.PATH || searchEnv.Path || '').split(delimiter).filter(Boolean);- for (const dir of pathDirs) {- for (const ext of WIN_EXECUTABLE_EXTS) {- const candidate = join(dir, `${command}${ext}`);- if (existsSync(candidate)) return candidate;- }- }- return null;-}--const WIN_BATCH_EXT_RE = /\.(cmd|bat)$/i;--/**- * Return the `{ command, args }` pair that's actually safe to hand to- * `execFile()` under `shell:false` — mirrors `prepareWindowsSafeSpawn` in- * `server/lib/bufferedSpawn.js` (duplicated here for self-containment).- * `.bat`/`.cmd` files cannot be launched directly under `shell:false` even- * with the explicit extension (Node's CVE-2024-27980 patch makes- * spawn/execFile refuse them outright); the documented safe alternative is- * to invoke `cmd.exe /c <path> <args>` directly.- */-function prepareWindowsSafeSpawn(command, args, isWin32 = process.platform === 'win32') {- if (isWin32 && WIN_BATCH_EXT_RE.test(command)) {- return {- command: 'cmd.exe',- args: ['/c', escapeCmdMetacharsIfUnquoted(command), ...args.map(escapeCmdMetacharsIfUnquoted)],- };- }- return { command, args };-}--// cmd.exe metacharacters that act as command separators / redirection /-// grouping on its raw command line.-const CMD_METACHAR_RE = /[&|<>^()]/g;-// Node's argv→command-line quoting wraps an argument in literal double-// quotes only when it contains whitespace or a `"`; characters inside that-// quoted span are not re-interpreted by cmd.exe.-const NEEDS_NODE_QUOTING_RE = /[\s"]/;--/**- * Caret-escape cmd.exe metacharacters, but ONLY when Node's own quoting- * would otherwise leave the argument unquoted on cmd.exe's raw command line.- * Mirrors server/lib/bufferedSpawn.js for self-containment.- */-function escapeCmdMetacharsIfUnquoted(value) {- const str = String(value);- if (NEEDS_NODE_QUOTING_RE.test(str)) return str;- return str.replace(CMD_METACHAR_RE, '^$&');-}--/**- * What a model-catalog probe should actually spawn for a provider, and the- * label its failure messages must name.- *- * The bootstrap wrap belongs on EVERY probe (a bare harness runs with no- * credential and answers for the wrong account — see- * `internal/credentialBootstrap.js`), and every message has to name what really- * ran or a missing bootstrap binary reports itself as the harness failing.- * Stating both once keeps the next vendor fetcher from spawning bare.- */-function resolveProbeSpawn(provider, defaultBin, args) {- const spawned = composeBootstrapSpawn(provider, provider?.command || defaultBin, args);- return { ...spawned, label: `'${spawned.command} ${spawned.args.join(' ')}'` };-}--// windowsHide is applied here rather than by importing server/lib/childProcess.js:-// the aiToolkit is contractually self-contained (see aiToolkit/AGENTS.md), so it-// carries its own copy of the default. Without it, every CLI probe below spawns-// a console from PortOS's console-less PM2 fork, which Windows hands off to-// Windows Terminal as a focus-stealing window. See docs/WINDOWS_CONSOLE.md.-// Spread last so an explicit windowsHide: false still wins, matching the-// contract server/lib/childProcess.js states.-const execFileAsync = (file, args, options) =>- promisify(execFile)(file, args, { windowsHide: true, ...options });--// Tool-use (function-calling) capable model families. Inlined here because the-// aiToolkit is self-contained (no imports out to server/lib). MIRROR of-// TOOL_USE_RE in server/lib/localModelHeuristics.js — keep the two in lockstep-// (server/lib/localModelHeuristics.mirror.test.js fails when they drift).-const TOOL_USE_RE = new RegExp([- 'qwen',- 'llama-?3\\.[1-9]', 'llama-?4',- 'mistral', 'mixtral', 'ministral', 'codestral', 'devstral', 'magistral',- 'command-?r', 'command-?a', 'north-mini-code',- 'firefunction', 'functionary', 'watt-tool', 'hermes', 'functiongemma',- 'glm-?4',- 'granite-?[34]',- '(?:^|[-_/:])gemma-?4',- 'gpt-oss',- 'nemotron',- 'olmo-?3',- 'lfm2', 'ornith', 'muse-glimmer', 'nex-n2',- 'smollm2',- 'dflash',- 'deepseek-v3', 'deepseek-r1', 'deepseek-v4',-].join('|'), 'i');--/**- * Whether an Ollama model supports tool use. Prefers the authoritative `tools`- * capability from /api/show (a non-empty capabilities array without `tools` is- * an explicit negative); falls back to the id heuristic when capabilities are- * unavailable (daemon hiccup / older Ollama).- */-function ollamaModelSupportsTools(id, capabilities) {- if (Array.isArray(capabilities) && capabilities.length > 0) {- return capabilities.some((c) => String(c).toLowerCase() === 'tools');- }- return TOOL_USE_RE.test(String(id || ''));-}--const CODEX_CONFIGURED_DEFAULT = 'codex-configured-default';-const CODEX_MODEL_KEYS = ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel'];-// Codex 0.144+ exposes selectable coding-model tiers. Keep the ids in provider-// config (rather than the old "use ~/.codex/config.toml" sentinel) so PortOS-// can pass the user's choice through as `codex --model <id>`.-const CODEX_MODELS = [- 'gpt-6-astra',- 'gpt-5.6-sol',- 'gpt-5.6-terra',- 'gpt-5.6-luna',- 'gpt-5.5',- 'gpt-5.4',- 'gpt-5.4-mini',- 'gpt-5.3-codex-spark',-];-const CODEX_MODEL_DEFAULTS = {- defaultModel: 'gpt-5.6-terra',- lightModel: 'gpt-5.6-luna',- mediumModel: 'gpt-5.6-terra',- heavyModel: 'gpt-5.6-sol',-};-const PRIOR_CODEX_MODEL_CATALOGS = [- // Prior 2026-07 catalog before Codex-Spark was added.- [- 'gpt-5.6-luna',- 'gpt-5.6-terra',- 'gpt-5.6-sol',- ],- // Prior 2026-08 catalog before GPT-6 Astra, GPT-5.5, GPT-5.4, GPT-5.4 Mini were added.- [- 'gpt-5.6-luna',- 'gpt-5.6-terra',- 'gpt-5.6-sol',- 'gpt-5.3-codex-spark',- ],-];-const ANTIGRAVITY_MODEL_KEYS = ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel'];-// agy exposes a per-session `--model` flag and lists its catalog via-// `agy models`. This is the shipped fallback list (agy 2026-09) used to seed a-// fresh install and when the live `agy models` probe can't run; the AI Providers-// "Refresh models" button replaces it with whatever the installed binary-// reports, which is the authoritative list for that user's plan.-const ANTIGRAVITY_MODELS = [- 'gemini-3.8-flash-high',- 'gemini-3.8-flash-medium',- 'gemini-3.8-flash-low',- 'gemini-3.7-flash-high',- 'gemini-3.7-flash-medium',- 'gemini-3.7-flash-low',- 'gemini-3.6-flash-high',- 'gemini-3.6-flash-medium',- 'gemini-3.6-flash-low',- 'gemini-3.1-pro-high',- 'gemini-3.1-pro-low',- 'claude-sonnet-4-6',- 'claude-opus-4-6-thinking',- 'gpt-oss-120b-medium',-];-// The sentinel stays FIRST in the list and remains the value of every-// `*Model` key: an install that never picks a model keeps agy's own configured-// default (no `--model` flag), exactly as before. The real ids ride alongside so-// the task/schedule model pickers (which filter the sentinel out) can offer a-// per-run override.-const ANTIGRAVITY_MODEL_CATALOG = [ANTIGRAVITY_CONFIGURED_DEFAULT, ...ANTIGRAVITY_MODELS];-const PRIOR_ANTIGRAVITY_MODEL_CATALOGS = [- // Prior 2026-07 catalog without gemini-3.7- [- ANTIGRAVITY_CONFIGURED_DEFAULT,- 'gemini-3.6-flash-high',- 'gemini-3.6-flash-medium',- 'gemini-3.6-flash-low',- 'gemini-3.5-flash-high',- 'gemini-3.5-flash-medium',- 'gemini-3.5-flash-low',- 'gemini-3.1-pro-high',- 'gemini-3.1-pro-low',- 'claude-sonnet-4-6',- 'claude-opus-4-6-thinking',- 'gpt-oss-120b-medium',- ],- // Prior 2026-08 catalog with gemini-3.5, without gemini-3.8- [- ANTIGRAVITY_CONFIGURED_DEFAULT,- 'gemini-3.7-flash-high',- 'gemini-3.7-flash-medium',- 'gemini-3.7-flash-low',- 'gemini-3.6-flash-high',- 'gemini-3.6-flash-medium',- 'gemini-3.6-flash-low',- 'gemini-3.5-flash-high',- 'gemini-3.5-flash-medium',- 'gemini-3.5-flash-low',- 'gemini-3.1-pro-high',- 'gemini-3.1-pro-low',- 'claude-sonnet-4-6',- 'claude-opus-4-6-thinking',- 'gpt-oss-120b-medium',- ],-];-const CODEX_CONTEXT_WINDOW = 1_000_000;-const GEMINI_CONTEXT_WINDOW = 1_048_576;-const STALE_GENERIC_CONTEXT_WINDOW = 128_000;--function matchesAnyExactCatalog(models, catalogs) {- return Array.isArray(models) && catalogs.some(- (catalog) => catalog.length === models.length && catalog.every((model, index) => model === models[index]),- );-}--function shouldUpgradeContextWindow(value) {- return value == null || Number(value) === STALE_GENERIC_CONTEXT_WINDOW;-}--function canonicalProviderContextWindow(provider) {- if (provider?.type !== 'cli' && provider?.type !== 'tui') return null;- const id = String(provider?.id || '').toLowerCase();- const command = String(provider?.command || '').toLowerCase();- if (id === 'codex' || id === 'codex-tui' || command === 'codex') return CODEX_CONTEXT_WINDOW;- if (id === ANTIGRAVITY_CLI_ID || id === ANTIGRAVITY_TUI_ID || command === 'agy') return GEMINI_CONTEXT_WINDOW;- return null;-}--// Replace only the old sentinel-only Codex setup or a prior shipped catalog-// with the current selectable Codex catalog. Real model choices are-// deliberately preserved: PortOS must never silently erase a model selected-// in AI Providers.-function migrateCodexProvider(data) {- if (!data?.providers) return false;- let changed = false;- for (const provider of Object.values(data.providers)) {- const isCodexProcessProvider = (provider?.id === 'codex' || provider?.id === 'codex-tui')- && (provider?.type === 'cli' || provider?.type === 'tui');- if (!isCodexProcessProvider) continue;-- const isSentinelOnly = Array.isArray(provider.models)- && provider.models.length === 1- && provider.models[0] === CODEX_CONFIGURED_DEFAULT- && CODEX_MODEL_KEYS.every((key) => provider[key] === CODEX_CONFIGURED_DEFAULT);- const isPriorSeededList = matchesAnyExactCatalog(provider.models, PRIOR_CODEX_MODEL_CATALOGS);- if (!isSentinelOnly && !isPriorSeededList) continue;-- provider.models = [...CODEX_MODELS];- if (isSentinelOnly) Object.assign(provider, CODEX_MODEL_DEFAULTS);- changed = true;- }- return changed;-}--// Remove a `--model <id>` / `--model=<id>` pin (both spellings) from a legacy-// Gemini-CLI argv being converted to agy. Only the legacy migration wants this —-// on the spawn paths a long-form `--model` is a legitimate agy pin and is kept.-function stripLegacyModelPin(args) {- const out = [];- for (let i = 0; i < args.length; i++) {- const arg = args[i];- if (arg === '--model') {- const next = args[i + 1];- if (typeof next === 'string' && !next.startsWith('-')) i += 1; // skip its value- continue;- }- if (typeof arg === 'string' && arg.startsWith('--model=')) continue;- out.push(arg);- }- return out;-}--function migrateAntigravityProviders(data) {- if (!data?.providers) return false;- let changed = false;- const mappings = [- { legacyId: LEGACY_GEMINI_CLI_ID, targetId: ANTIGRAVITY_CLI_ID, name: 'Antigravity CLI', type: 'cli', timeout: 300000 },- { legacyId: LEGACY_GEMINI_TUI_ID, targetId: ANTIGRAVITY_TUI_ID, name: 'Antigravity TUI', type: 'tui', timeout: 600000 },- ];-- for (const mapping of mappings) {- const legacy = data.providers[mapping.legacyId];- if (!legacy) continue;-- if (!data.providers[mapping.targetId]) {- const envVars = { ...(legacy.envVars || {}) };- delete envVars.GEMINI_SANDBOX;- // Drop any `--model` the legacy argv pinned BEFORE normalizing. The arg- // builders deliberately preserve a long-form `--model` (agy accepts it,- // so a pin is a real user selection) — but this argv came from the- // *Gemini* CLI, so its pin is a Gemini id (`gemini-2.5-pro`) that agy- // cannot resolve. Carrying it over would both break every run AND make- // `hasModelFlag` permanently suppress PortOS's own injection, leaving the- // user no way to fix it short of hand-editing the provider args.- const legacyArgs = stripLegacyModelPin(legacy.args || []);- const migrated = {- ...legacy,- id: mapping.targetId,- name: mapping.name,- type: mapping.type,- command: 'agy',- args: mapping.type === 'cli'- ? ensureAntigravityPrintArgs(legacyArgs)- : ensureAntigravityTuiArgs(legacyArgs),- models: [...ANTIGRAVITY_MODEL_CATALOG],- timeout: legacy.timeout || mapping.timeout,- envVars,- };- for (const key of ANTIGRAVITY_MODEL_KEYS) {- migrated[key] = ANTIGRAVITY_CONFIGURED_DEFAULT;- }- data.providers[mapping.targetId] = migrated;- }-- if (data.activeProvider === mapping.legacyId) {- data.activeProvider = mapping.targetId;- }-- // Rewrite fallbackProvider references on all other providers so- // user-defined fallback chains aren't silently broken after the- // legacy id is removed from the map.- for (const p of Object.values(data.providers)) {- if (p.fallbackProvider === mapping.legacyId) {- p.fallbackProvider = mapping.targetId;- }- }-- delete data.providers[mapping.legacyId];- changed = true;- }-- return changed;-}--// Installs that carry the sentinel-only model list from before agy grew a-// `--model` flag, or the prior shipped catalog before gemini-3.7 was released,-// are widened/updated to the current shipped catalog so pickers have the new-// model options. Guarded so a user's own customized list (or one already-// refreshed from `agy models`) is never overwritten, and the `*Model` keys are-// left alone so run behavior is unchanged until the user actually picks a model.-function migrateAntigravityModelCatalog(data) {- if (!data?.providers) return false;- let changed = false;- for (const provider of Object.values(data.providers)) {- const isAntigravityProcessProvider = (provider?.id === ANTIGRAVITY_CLI_ID || provider?.id === ANTIGRAVITY_TUI_ID)- && (provider?.type === 'cli' || provider?.type === 'tui');- if (!isAntigravityProcessProvider) continue;-- const isSentinelOnly = Array.isArray(provider.models)- && provider.models.length === 1- && provider.models[0] === ANTIGRAVITY_CONFIGURED_DEFAULT;-- const isPriorSeededList = matchesAnyExactCatalog(provider.models, PRIOR_ANTIGRAVITY_MODEL_CATALOGS);-- if (!isSentinelOnly && !isPriorSeededList) continue;-- provider.models = [...ANTIGRAVITY_MODEL_CATALOG];- changed = true;- }- return changed;-}--function migrateProviderContextWindows(data) {- if (!data?.providers) return false;- let changed = false;-- for (const provider of Object.values(data.providers)) {- const contextWindow = canonicalProviderContextWindow(provider);- if (!contextWindow || !shouldUpgradeContextWindow(provider.contextWindow)) continue;- provider.contextWindow = contextWindow;- changed = true;- }-- return changed;-}-export function createProviderService(config = {}) {+ const state = createProviderServiceState(config);const {- dataDir = './data',- providersFile = 'providers.json',- sampleFile = null,- // Short TTL cache on the parsed providers.json. The hot path is an- // N-way provider-failure storm: each failing call runs- // pickFallbackProvider → getAllProviders → loadProviders, which used- // to re-read providers.json from disk every time. A ~1s TTL collapses- // that storm to a single read without making config edits feel stale- // (provider config changes are human-paced; saveProviders refreshes- // the cache inline so a write is reflected immediately).- providersCacheTtlMs = 1000,- // Host persistence hook, called after every SUCCESSFUL providers.json write- // with the data that landed. Injected rather than imported because this- // directory stays self-contained (see AGENTS.md): PortOS uses it to keep- // its machine-local provider connection graph (#6367) reconciled with a- // file any old client, migration or downgraded release may also write.- // Unset standalone, so the toolkit behaves exactly as before.- onProvidersSaved = null,- // Host hook: the model ids a LOCAL one-checkpoint-per-process runtime has- // on disk but is not currently serving. `(provider) => Promise<string[]|null>`,- // where `null` means "not that kind of provider, or the cache could not be- // read" — deliberately distinct from `[]` ("read, and nothing is cached"),- // which must not resurrect a stale list. Injected rather than imported- // because reading a cache means host I/O and this directory stays- // self-contained (see AGENTS.md); PortOS supplies MTPLX's `mtplx models- // --json` listing from `services/mtplxServerManager.js`.- cachedModelIds = null,- // Host resolver for a COMPOSITE provider id (`harness.method@service- // [+bootstrap]`, #7564): `(id) => Promise<object|null>`, returning an- // executable record materialized from the host's harness registry, service- // instances and settings — never a stored one. Consulted by `getProviderById`- // only for an id the composite grammar recognizes and the stored map does- // not hold, so a preset lookup is byte-identical to before and a composite- // can never shadow a record. Injected rather than imported because the- // registries live host-side (see AGENTS.md). Unset standalone.- resolveCompositeProvider = null- } = config;-- const PROVIDERS_PATH = join(dataDir, providersFile);-- // Last successfully-loaded providers data + the wall-clock time it was- // cached. `providersLoadInFlight` coalesces concurrent cold reads so a- // simultaneous burst of callers shares one disk read instead of each- // racing its own. Per-service-instance (the toolkit builds one), so the- // cache is process-wide for the single-user server.- //- // `cacheGeneration` is bumped on every cache mutation (refresh or- // invalidate). A cold read captures it before reading disk and only- // adopts its result if the generation is unchanged on resolve — so a- // slow stale read can't clobber a fresher snapshot a concurrent- // `saveProviders` wrote while it was in flight.- let providersCache = null;- let providersCacheAt = -Infinity;- let providersLoadInFlight = null;- let cacheGeneration = 0;-- function refreshProvidersCache(data) {- // Null-prototype the providers map so a keyed lookup (`data.providers[id]`)- // in getProviderById / setActiveProvider / updateProvider / etc. can't- // resolve an inherited Object.prototype member (`__proto__`, `constructor`,- // `toString`, …) as a "provider that exists". Without this, a crafted id- // like `constructor` walks the prototype chain, tests truthy, and gets- // treated as a real provider (e.g. persisted as `activeProvider`). Own- // enumerable keys still serialize/iterate normally (JSON.stringify,- // Object.values, spread, delete all behave identically on a null-proto map).- if (data?.providers && Object.getPrototypeOf(data.providers) !== null) {- data.providers = Object.assign(Object.create(null), data.providers);- }- providersCache = data;- providersCacheAt = Date.now();- cacheGeneration += 1;- return data;- }-- function invalidateProvidersCache() {- providersCache = null;- providersCacheAt = -Infinity;- cacheGeneration += 1;- }-- // JSON.parse with a corrupt-file rescue. A garbled providers.json (truncated- // write, hand-edit typo, disk corruption) would otherwise crash server boot.- // Rename the bad file to <path>.corrupt + start from empty so the CLI can- // reseed from the sample on next save.- async function parseOrRescue(content, source) {- try {- return JSON.parse(content);- } catch (err) {- const corruptPath = `${source}.corrupt.${Date.now()}`;- console.error(`❌ providers.json parse failed (${err.message}); renamed to ${corruptPath} and starting from empty`);- await rename(source, corruptPath).catch(() => {});- return { activeProvider: null, providers: {} };- }- }-- async function readProvidersFromDisk() {- if (!existsSync(PROVIDERS_PATH)) {- if (sampleFile && existsSync(sampleFile)) {- const sample = await readFile(sampleFile, 'utf-8');- // Parse BEFORE persisting — if the shipped sample is malformed we- // don't want to seed user-side providers.json with garbage, and- // parseOrRescue's rename target must be the user file, not the- // shared sample (which would silently move it aside on every boot).- let parsed;- try {- parsed = JSON.parse(sample);- } catch (err) {- console.error(`❌ sample providers file ${sampleFile} parse failed (${err.message}); starting from empty`);- return { activeProvider: null, providers: {} };- }- unifyProviderModes(parsed);- await atomicWrite(PROVIDERS_PATH, parsed);- return parsed;- }- return { activeProvider: null, providers: {} };- }-- const content = await readFile(PROVIDERS_PATH, 'utf-8');- const data = await parseOrRescue(content, PROVIDERS_PATH);-- const migratedCodex = migrateCodexProvider(data);- const migratedAntigravity = migrateAntigravityProviders(data);- const migratedAntigravityModels = migrateAntigravityModelCatalog(data);- const migratedContextWindows = migrateProviderContextWindows(data);- const migratedModes = unifyProviderModes(data);- if (migratedModes || migratedCodex || migratedAntigravity || migratedAntigravityModels || migratedContextWindows) {- await atomicWrite(PROVIDERS_PATH, data);- if (migratedCodex) console.log('🔧 Migrated Codex providers to the selectable model catalog');- if (migratedAntigravity) console.log('🔧 Migrated Gemini provider config to Antigravity CLI (agy)');- if (migratedAntigravityModels) console.log('🔧 Migrated Antigravity providers to the selectable agy model catalog');- if (migratedContextWindows) console.log('🔧 Migrated provider context windows to current canonical values');- }-- return data;- }-- // Cache-fronted read. Returns the cached snapshot while it's within the- // TTL; otherwise reads from disk, coalescing concurrent cold reads into- // a single `readProvidersFromDisk` so an N-way failure storm triggers at- // most one read per TTL window.- async function loadProviders() {- if (providersCache && (Date.now() - providersCacheAt) < providersCacheTtlMs) {- return providersCache;- }- if (providersLoadInFlight) return providersLoadInFlight;- const gen = cacheGeneration;- providersLoadInFlight = readProvidersFromDisk()- .then(data => {- // Adopt this read only if no write/invalidate landed while it was- // in flight; otherwise that newer snapshot is fresher — return it- // rather than clobbering the cache with our stale parse.- if (cacheGeneration === gen) return refreshProvidersCache(data);- return providersCache ?? data;- })- .finally(() => { providersLoadInFlight = null; });- return providersLoadInFlight;- }-- // The write already landed and the cache already reflects it, so a host- // hook must never be able to turn a successful save into a failed one — and- // callers include schedulers and boot warmups with no Express `next(err)` to- // bubble to. Log and continue (AGENTS.md's stated try/catch exception).- async function notifyProvidersSaved(data) {- if (typeof onProvidersSaved !== 'function') return;- try {- await onProvidersSaved(data);- } catch (err) {- console.error(`❌ providers save hook failed: ${err.message}`);- }- }-- async function saveProviders(data) {- // Drop the cache BEFORE the write: mutators read → mutate the cached- // object in place → save, so the warm cache already holds the unsaved- // mutation. Invalidating first means a failed `atomicWrite` leaves no- // cache to serve the un-persisted change (the next read re-reads disk),- // and refreshing only after success keeps the cache consistent with- // what actually landed on disk.- invalidateProvidersCache();- await atomicWrite(PROVIDERS_PATH, data);- refreshProvidersCache(data);- await notifyProvidersSaved(data);- }-- /**- * Build ONE record, refusing an id `existing` already holds.- *- * PURE — it returns the record rather than storing it, which is what makes a- * multi-record create atomic for free: a throw on the second record cannot- * leave the first one behind. That matters because `loadProviders` hands back- * the WARM CACHE object, so a record written into it and then abandoned would- * stay visible to every reader in the process despite never reaching disk.- *- * The explicit field list (rather than a spread of the body) is the- * create-side contract this directory keeps — see AGENTS.md — so a new- * provider field is added here deliberately.- */- function buildProviderRecord(existing, providerData) {- const id = providerData.id || providerData.name.toLowerCase().replace(/[^a-z0-9]/g, '-');-- if (existing[id]) {- throw new Error('Provider with this ID already exists');- }-- const modelAccess = normalizeModelAccess(providerData.modelAccess);-- const provider = {- id,- name: providerData.name,- type: providerData.type || 'cli',- command: providerData.command || null,- args: providerData.args || [],- endpoint: providerData.endpoint || null,- apiKey: providerData.apiKey || '',- models: providerData.models || [],- ...(providerData.hardwareRequirements ? { hardwareRequirements: providerData.hardwareRequirements } : {}),- ...(providerData.modelHardwareRequirements- ? { modelHardwareRequirements: providerData.modelHardwareRequirements }- : {}),- defaultModel: providerData.defaultModel || null,- effort: providerData.effort || null,- lightModel: providerData.lightModel || null,- mediumModel: providerData.mediumModel || null,- heavyModel: providerData.heavyModel || null,- ultraModel: providerData.ultraModel || null,- fallbackProvider: providerData.fallbackProvider || null,- fallbackModel: providerData.fallbackModel || null,- numCtx: providerData.numCtx || null,- temperature: providerData.temperature,- topP: providerData.topP,- thinking: providerData.thinking,- contextWindow: providerData.contextWindow || null,- // Per-model windows learned from the provider's own /models catalog.- // Same non-empty rule the refresh path uses, from one implementation.- ...modelContextWindowPatch(providerData.modelContextWindows),- timeout: providerData.timeout || 300000,- enabled: providerData.enabled !== false,- // Subscription text-transport capability + its explicit opt-in. Only- // persisted when set, so every existing HTTP/CLI record stays byte-identical- // and an older install reading this file sees nothing new.- ...(typeof providerData.textTransport === 'string' && providerData.textTransport- ? { textTransport: providerData.textTransport } : {}),- ...(providerData.textTransportEnabled === true ? { textTransportEnabled: true } : {}),- ...(providerData.textTransportReadRiskAcknowledged === true- ? { textTransportReadRiskAcknowledged: true } : {}),- // Claude Ollama marker — preserve so adopting the sample via POST drives- // ollama-backed model refresh (see isOllamaBackedProvider).- ...(providerData.ollamaBacked === true ? { ollamaBacked: true } : {}),- // MTPLX's native MTP runtime is a separate local OpenAI-compatible- // backend. Preserve this marker so OpenCode receives the `mtplx/`- // namespace and model refresh probes its local endpoint.- // LM Studio is a local backend PortOS already manages; preserve the- // marker so OpenCode receives the `lmstudio/` namespace and model- // refresh probes the LM Studio server rather than the harness.- ...(providerData.lmstudioBacked === true ? { lmstudioBacked: true } : {}),- ...(providerData.mtplxBacked === true ? { mtplxBacked: true } : {}),- ...(providerData.llamaBacked === true ? { llamaBacked: true } : {}),- // The local vLLM container is a third distinct local backend: preserve- // the marker so OpenCode receives the `vllm/` namespace and model- // refresh probes the container rather than the OpenCode harness.- ...(providerData.vllmBacked === true ? { vllmBacked: true } : {}),- // The SGLang container is a fourth distinct local backend (Hopper/Blackwell,- // PortOS-owned launch line): preserve the marker so OpenCode receives the- // `sglang/` namespace and model refresh probes the container.- ...(providerData.sglangBacked === true ? { sglangBacked: true } : {}),- // Hosted gateway markers: the generic one plus the legacy per-gateway- // boolean, both preserved so a record written by any version keeps- // resolving through internal/gateways.js.- ...(typeof providerData.gatewayBacked === 'string' && providerData.gatewayBacked- ? { gatewayBacked: providerData.gatewayBacked } : {}),- ...(providerData.orcarouterBacked === true ? { orcarouterBacked: true } : {}),- // Which of the upstream catalog this install is entitled to run- // (internal/modelAccess.js). Normalized on the way in so a stored record- // never holds a mode this build does not know, and only persisted when it- // says something — an unconfigured provider stays byte-identical.- ...(modelAccess ? { modelAccess } : {}),- // Explicit opt-in to send the API key to an arbitrary (non-local,- // non-allowlisted) endpoint — see endpointGuard.js. Only- // persisted when true so existing keyless/local providers stay clean.- ...(providerData.allowCustomEndpoint === true ? { allowCustomEndpoint: true } : {}),- // Codex 'ignore my ~/.codex/config.toml' pin. Only persisted when true so- // every existing record stays byte-identical and an older install- // reading this file sees nothing new.- ...(providerData.ignoreUserConfig === true ? { ignoreUserConfig: true } : {}),- // Generic credential-bootstrap wrapper — only persisted when a bootstrap- // command is actually named, so every existing record stays byte-identical.- ...(providerData.credentialBootstrap?.command ? { credentialBootstrap: providerData.credentialBootstrap } : {}),- envVars: providerData.envVars || {},- secretEnvVars: providerData.secretEnvVars || [],- headlessArgs: providerData.headlessArgs || [],- tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,- ...(providerData.tuiIdleTimeoutMs != null ? { tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs } : {}),- // Preset structure (#7565) — only persisted when named, so every record- // created without it stays byte-identical and reads as a legacy preset.- ...Object.fromEntries(['harnessId', 'method', 'serviceId', 'credentialBootstrapId']- .filter((key) => typeof providerData[key] === 'string' && providerData[key])- .map((key) => [key, providerData[key]])),- ...(Array.isArray(providerData.catalogNarrowing) ? { catalogNarrowing: [...providerData.catalogNarrowing] } : {})- };-- return provider;- }-- /** Store freshly built records and adopt the first as active on an empty install. */- function storeProviderRecords(data, records) {- for (const record of records) {- data.providers[record.id] = record;- if (!data.activeProvider) data.activeProvider = record.id;- }- unifyProviderModes(data);- }-- return {- async getAllProviders() {- const data = await loadProviders();- // Model-access resolution only — the API key stays OFF the list shape,- // which is read by routes that serialize every provider. The envelope- // below is pinned by services/providers.shape.test.js; keep it literal.- return {- activeProvider: data.activeProvider,- providers: Object.values(data.providers).map(provider => withGatewayModelAccess(provider, data.providers))- };- },-- async getProviderById(id) {- const data = await loadProviders();- const stored = readProvider(data.providers[id], data.providers);- if (stored || typeof resolveCompositeProvider !== 'function' || !isCompositeProviderId(id)) return stored;- return (await resolveCompositeProvider(id)) ?? null;- },-- async getActiveProvider() {- const data = await loadProviders();- if (!data.activeProvider) return null;- return readProvider(data.providers[data.activeProvider], data.providers);- },-- async setActiveProvider(id) {- const data = await loadProviders();- if (!data.providers[id]) {- return null;- }- data.activeProvider = id;- await saveProviders(data);- return data.providers[id];- },-- async createProvider(providerData) {- const data = await loadProviders();- const provider = buildProviderRecord(data.providers, providerData);- storeProviderRecords(data, [provider]);- await saveProviders(data);- return provider;- },-- /**- * Create BOTH execution modes of one harness from a single body, in one- * `providers.json` write.- *- * A program that can be driven headlessly and interactively is one program- * on one backend, but a record stores exactly one `type` — so configuring- * both used to mean adding the provider twice and hoping the two records- * happened to satisfy the pairing rule. `expandModePair` mints them in the- * `<stem>` / `<stem>-tui` shape {@link providerModeGroups} recognizes with- * every grouped field shared, so the pair arrives already unified instead of- * as two unrelated routes.- *- * Either record colliding with an existing id aborts the whole create with- * nothing stored — see {@link buildProviderRecord} on why that has to hold- * against the warm cache and not just against the file.- *- * @param {object} providerData - a create body carrying `modes`- * @returns {Promise<object[]>} the created records, CLI first- */- async createProviderModes(providerData) {- const split = expandModePair(providerData);- if (!split) throw new Error('createProviderModes requires a modes declaration');-- const data = await loadProviders();- const created = split.map((modeData) => buildProviderRecord(data.providers, modeData));- storeProviderRecords(data, created);- await saveProviders(data);- return created;- },-- /**- * Complete an existing CLI record's harness by minting its TUI sibling.- *- * The sibling is built from the STORED record, never from a re-submitted- * form: retyping the command, endpoint, credentials and env is exactly the- * friction a dual-mode create removed for a provider being added, and a- * second hand-entry is also a second chance for a grouped field to differ- * and leave two unrelated routes. Everything but the mode's own argv comes- * across unchanged, which is what makes the result groupable.- *- * Routed through {@link modeSiblingPayload} — the same writer a dual-mode- * create goes through — so the `<stem>` / `<stem>-tui` id and name- * convention has ONE spelling whether a pair is born together or completed- * later. The CLI id is already fixed, so a taken sibling id is not a- * collision to suffix around — it is something else already standing there,- * and this throws rather than guessing.- *- * @param {string} id - the CLI record to derive from- * @param {object} [tuiOverrides] - mode-specific fields, typically `args`- * @returns {Promise<object|null>} the created TUI record, or `null` when `id` names no record- */- async createProviderTuiMode(id, tuiOverrides = {}) {- const data = await loadProviders();- const stored = data.providers[id];- if (!stored) return null;- if (stored.type !== 'cli') throw new Error('Only a CLI provider can gain a TUI mode');-- const created = buildProviderRecord(data.providers, modeSiblingPayload(stored, 'tui', tuiOverrides));- storeProviderRecords(data, [created]);- await saveProviders(data);- return created;- },-- async updateProvider(id, updates) {- const data = await loadProviders();-- if (!data.providers[id]) {- return null;- }-- const provider = {- ...data.providers[id],- ...updates,- id- };- // The editor clears a bootstrap with an explicit `null` (absent means- // "unchanged" on a PATCH). Drop the key rather than store the null, so- // the record reads exactly like one that never had a bootstrap — the- // invariant `createProvider` keeps by only writing the key when named.- // Applied to the fanned-out siblings too: a cleared sibling that kept a- // stored `null` would no longer read as "never had one".- // Fields whose CLEARED form has to be normalized away rather than stored:- // a record that was reset must read exactly like one that never had the- // field, or the next reader has to know two spellings of "none".- const normalizeClearedFields = (record) => {- if (record.credentialBootstrap === null) delete record.credentialBootstrap;- // Same convention for the model-access policy: an explicit `null` is- // "clear it", and a policy that normalizes to nothing (mode `all` with- // no patterns) is stored as absent rather than as an inert object, so a- // record that was reset reads exactly like one that never had a policy.- if (Object.hasOwn(record, 'modelAccess')) {- const normalized = normalizeModelAccess(record.modelAccess);- if (normalized) record.modelAccess = normalized;- else delete record.modelAccess;- }- };- normalizeClearedFields(provider);-- // Grouped BEFORE the edit lands: every connection-identity value the- // fan-out shares (endpoint, API key, env vars, bootstrap) is exactly what- // `providerModeGroups` pairs on, so reading the group after would find- // the siblings already split and skip the fan-out that keeps them- // together.- const group = providerModeGroups(Object.values(data.providers)).find(modes => modes.some(mode => mode.id === id));- data.providers[id] = provider;- for (const sibling of group || []) {- if (sibling.id === id) continue;- Object.assign(sibling, sharedModeUpdates(updates));- normalizeClearedFields(sibling);- }- await saveProviders(data);- return provider;- },-- /**- * Apply partial updates to SEVERAL providers in ONE providers.json write.- *- * Unlike {@link updateProvider} this performs no sibling fan-out: the- * caller names every route it means to change, which is the contract a- * projection needs — materializing a shared connection's values must touch- * exactly the routes bound to it and no conventional neighbour.- *- * @param {Record<string, object>} patches - provider id → partial update- * @returns {Promise<string[]>} the ids that existed and were updated- */- async applyProviderPatches(patches) {- const data = await loadProviders();- const applied = [];- for (const [id, updates] of Object.entries(patches || {})) {- if (!data.providers[id]) continue;- data.providers[id] = { ...data.providers[id], ...updates, id };- applied.push(id);- }- if (applied.length > 0) await saveProviders(data);- return applied;- },-- async deleteProvider(id) {- const data = await loadProviders();-- if (!data.providers[id]) {- return false;- }-- const group = providerModeGroups(Object.values(data.providers)).find(modes => modes.some(mode => mode.id === id));- const removed = (group || []).map(mode => mode.id);- for (const modeId of removed) delete data.providers[modeId];-- if (removed.includes(data.activeProvider)) {- const remaining = Object.keys(data.providers);- data.activeProvider = remaining.length > 0 ? remaining[0] : null;- }-- await saveProviders(data);- return true;- },-- async testProvider(id) {- const data = await loadProviders();- const provider = withGatewayApiKey(data.providers[id], data.providers);-- if (!provider) {- return { success: false, error: 'Provider not found' };- }-- if (provider.type === 'cli' || provider.type === 'tui') {- // Read fresh per call (not hoisted to module scope) so tests can drive- // both branches by stubbing process.platform per test.- const isWin32 = process.platform === 'win32';-- // Resolve the command on PATH. Windows has no `which` — it ships `where`- // instead — so a `which` lookup there always fails and falsely reports the- // command "not found in PATH" even when it resolves fine from a shell.- // Use execFile (no shell) so user-configured `provider.command` cannot- // inject extra shell commands via metacharacters.- const lookup = isWin32 ? 'where' : 'which';- // Probe what PortOS actually spawns: the credential-bootstrap CLI in- // front of the harness when one is named (the harness may then live- // behind it, off PATH), else the harness itself.- const probeCommand = composeBootstrapSpawn(provider, provider.command, []).command;- const { stdout } = await execFileAsync(lookup, [probeCommand], { windowsHide: true })- .catch(() => ({ stdout: '', stderr: 'not found' }));-- // `where` lists every match (one per line); `which` prints one. Take the- // first non-empty line as the resolved absolute path.- const commandPath = stdout.split(/\r?\n/).map(s => s.trim()).find(Boolean) || '';-- if (!commandPath) {- return { success: false, error: `Command '${probeCommand}' not found in PATH` };- }-- // On Windows, `where` can return the wrong file: npm ships an- // extension-less POSIX shell-script stub (for Git Bash/WSL) alongside- // the real `.cmd`/`.bat`/`.ps1` wrappers, and `where`'s first-line- // match is not guaranteed to be a launchable one (this is exactly- // what produced the literal error text in #1865). Re-resolve via the- // same extension-aware filesystem search the agent runner uses- // (server/lib/bufferedSpawn.js's resolveWindowsExecutable), searched- // against the same provider-envVars-merged env the runner actually- // spawns under (so a configured PATH override is honored here too),- // and prefer it for both the actual invocation AND what we report- // back — falling back to the `where` result only when that search- // finds nothing.- const searchEnv = { ...process.env, ...provider.envVars };- const invokePath = (isWin32 && resolveWindowsExecutable(provider.command, isWin32, searchEnv)) || commandPath;-- // Track whether the resolved path could actually be spawned. Without- // this, a non-spawnable shim falls through to `version: 'available'`- // and the Test button reports a provider the runner can never- // actually invoke as usable.- let everSpawned = false;- const tryVersion = async (flag) => {- // Invoke the resolved path so Windows runs the exact `.exe`/`.cmd`- // we found — execFile won't re-apply PATHEXT to a bare command- // name. A `.cmd`/`.bat` target still can't be launched directly- // under shell:false (Node refuses it outright, even with the- // explicit extension — see prepareWindowsSafeSpawn above), so wrap- // it through cmd.exe /c exactly like the runner does.- try {- const { command: execCommand, args: execArgs } = prepareWindowsSafeSpawn(invokePath, [flag]);- const out = await execFileAsync(execCommand, execArgs);- everSpawned = true;- return out?.stdout?.trim() || null;- } catch (err) {- // A numeric `code` is a non-zero EXIT — the process DID run (it just- // doesn't support this flag), so the path is spawnable. A string code- // (ENOENT/EACCES) or a spawn error means it could not be launched.- if (typeof err?.code === 'number') everSpawned = true;- return null;- }- };- const versionOut = (await tryVersion('--version')) || (await tryVersion('-v'));-- if (!everSpawned) {- return {- success: false,- error: `Resolved '${probeCommand}' to ${invokePath} but it could not be executed (a Windows .cmd/.bat npm shim is not directly spawnable by the agent runner)`,- };- }-- return {- success: true,- path: invokePath,- version: versionOut || 'available'- };- }-- if (provider.type === 'api') {- // Never send the API key to an arbitrary/metadata host (SSRF / key- // exfiltration). Keyless local-LLM checks are unaffected.- if (provider.apiKey) {- const guard = evaluateSecretEndpoint(provider.endpoint, {- allowCustomEndpoint: provider.allowCustomEndpoint === true,- });- if (!guard.allowed) {- return { success: false, error: `Endpoint blocked: ${guard.reason}` };- }- }- const modelsUrl = `${provider.endpoint}/models`;- const response = await fetch(modelsUrl, {- headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {},- signal: AbortSignal.timeout(10000),- }).catch(err => ({ ok: false, error: err.message }));-- if (!response.ok) {- return { success: false, error: `API not reachable: ${response.error || response.status}` };- }-- const models = await response.json().catch(() => ({ data: [] }));- return {- success: true,- endpoint: provider.endpoint,- models: models.data?.map(m => m.id) || []- };- }-- return { success: false, error: 'Unknown provider type' };- },-- /**- * Probe a provider's model list WITHOUT persisting it — the compute half of- * {@link refreshProviderModels}.- *- * Split out so a host fanning a refresh across several providers backed by- * the SAME upstream (see {@link ollamaRefreshGroupKey}) can run the probe- * once and apply the answer to each of them via `updateProvider`, instead of- * re-issuing an identical `/api/tags` + per-model `/api/show` sweep per- * provider.- *- * Same contract as `refreshProviderModels` minus the write: `null` means- * ONLY "no such provider"; every other failure throws (with `.status`).- *- * Answers the CATALOG shape: the id list plus, for the fetchers whose- * upstream declares it, each model's real context window. A fetcher with no- * window information yields `contextWindows: {}` — which means "unknown",- * never "these models have no window", so the caller must not persist it- * over what a previous refresh learned. {@link fetchProviderModels} is the- * id-list-only view for callers that don't care.- *- * @param {string} id- * @returns {Promise<{models: string[], contextWindows: Record<string, number>}|null>}- */- async fetchProviderModelCatalog(id) {- const data = await loadProviders();- const provider = withGatewayApiKey(data.providers[id], data.providers);-- if (!provider) {- return null;- }-- // `null` = no refreshable branch matched below (provider type/shape isn't- // refreshable — the pre-existing no-op case); a result = a completed- // fetch, which may legitimately be empty (e.g. an Ollama-backed provider- // whose only installed model was just deleted). Only the `null` sentinel- // means "nothing to persist" — a `.length === 0` check here would also- // swallow that legitimate empty result and leave a deleted model stuck- // in the provider's persisted list.- let fetched = null;-- try {- // A TUI provider's model is normally fixed by its CLI/config, so only- // the vendors whose `--model` flag also applies to the interactive- // session carry a `tuiMatch` column in the table (Ollama-backed,- // MTPLX-backed, Antigravity, Cursor today). One lookup replaces the- // per-vendor- // `else if` chain this used to be — see internal/modelFetchers.js.- const tuiFetcher = provider.type === 'tui' ? resolveModelFetcher(provider) : null;-- const probe = provider.type === 'api'- ? () => this._refreshAPIProviderModels(provider)- : provider.type === 'cli'- ? () => this._refreshCLIProviderModels(provider)- : tuiFetcher- ? () => this[tuiFetcher.fetch](provider)- : null;-- if (!probe) {- // No branch matched — this provider type/shape has no fetcher. Say so,- // the same 400 the CLI arm's own fall-through throws. Previously this- // fell out as `fetched === null` and the route rendered it as- // `404 Provider not found or not an API type`, which is exactly the- // false message the rethrow above set out to stop showing: a plain- // `codex-tui`/`grok-tui` provider exists and its type is fine, it just- // has no catalog to fetch. Thrown OUT here rather than from inside the- // wrapper below, which is allowed to answer over a failed probe — a- // provider with no fetcher at all must still 400.- const unsupported = new Error(`Model refresh not supported for ${provider.type} provider '${provider.id}'`);- unsupported.status = 400;- throw unsupported;- }-- // ONE wrapper over every arm rather than a per-vendor call: which- // providers have cached-but-unserved models is the host's question, not- // this dispatch's, and the shipped MTPLX records alone span two arms (an- // unmarked `api` record plus the `mtplxBacked` OpenCode wrappers the- // fetcher table routes). The hook answers `null` for everything else.- fetched = await this._withCachedCheckpoints(provider, probe);- } catch (error) {- console.error(`Failed to refresh models for ${provider.name}:`, error.message);- // RETHROW rather than collapsing to null. `null` means one specific- // thing here — "no refreshable branch matched" — and the route turns it- // into `404 Provider not found or not an API type`. Folding a fetcher- // failure into that same null made the user's toast read "Provider not- // found or not an API type" when the provider exists and its type is- // fine, burying the actual cause (`'cursor-agent models' failed: …- // ENOENT`) in the server log. That defeats the whole point of the- // throw-don't-fall-back posture in `_execCliModelList`: it goes to the- // trouble of refusing to persist a plausible-looking default precisely- // so the user learns WHY the refresh failed.- // 502, not 500: the failure is an upstream/vendor probe, not a bug here.- // The other caller (localLlm's post-install fan-out) already catches and- // logs per provider, so it is unaffected.- error.status = error.status || 502;- throw error;- }-- // Belt-and-braces: every branch above returns a list (or a catalog) or- // throws, so this is unreachable today — but a future fetcher that- // returns null must not persist `models: null` over the user's list. Throws rather than- // returning null so `null` keeps exactly ONE meaning out of this function:- // the provider does not exist. That is what lets the route's 404 say- // plainly "Provider not found" instead of guessing at a reason.- // Pi reports an unauthenticated install as an empty list. That is useful- // for first setup, but a lapsed login must not erase a populated catalog.- if (resolveModelFetcher(provider)?.key === 'pi' && Array.isArray(fetched)- && fetched.length === 0 && provider.models?.length) {- const error = new Error('Pi has no authenticated models. Use pi /login before refreshing the stored catalog.');- error.status = 502;- throw error;- }- const catalog = toModelCatalog(fetched);- if (catalog === null) {- const unsupported = new Error(`Model refresh returned nothing for provider '${provider.id}'`);- unsupported.status = 400;- throw unsupported;- }-- return catalog;- },-- /**- * The id-list-only view of {@link fetchProviderModelCatalog}, kept as the- * historical `string[] | null` contract. Nothing in PortOS calls it today- * (the post-install Ollama fan-out goes through `refreshProviderModelsBatch`);- * it stays because this directory is vendored and its method surface is the- * contract an upstream sync merges against — see ../AGENTS.md.- *- * @param {string} id- * @returns {Promise<string[]|null>}- */- async fetchProviderModels(id) {- const catalog = await this.fetchProviderModelCatalog(id);- return catalog === null ? null : catalog.models;- },-- /**- * Probe AND persist a provider's model list. Thin composition of- * {@link fetchProviderModelCatalog} + `updateProvider` — keep it that way so- * the two halves can't drift.- */- async refreshProviderModels(id) {- const catalog = await this.fetchProviderModelCatalog(id);- if (catalog === null) return null;- const previous = (await this.getProviderById(id))?.modelContextWindows;- return this.updateProvider(id, modelCatalogUpdate(catalog, previous));- },-- /**- * Refresh MANY providers with ONE `providers.json` write.- *- * `refreshProviderModels` is a per-provider `loadProviders` → mutate →- * `saveProviders` round-trip, and `saveProviders` invalidates the cache and- * rewrites the whole file. A host fanning a refresh across every provider- * backed by one local daemon (PortOS does this after an Ollama install or- * delete) therefore paid N full-file writes — each superseded by the next —- * plus N cache invalidate/repopulate cycles for any concurrent reader. This- * does the same work as three phases: group, probe, then a single write.- *- * 1. **Group** by {@link ollamaRefreshGroupKey}, so providers sharing a- * daemon AND a probe shape are probed once rather than once each. A- * `null` key is the "not a shared Ollama probe" sentinel, NOT a bucket —- * those providers each become a group of one and keep their own probe.- * 2. **Probe** one lead per group, sequentially. Nothing is persisted here,- * so a probe that fails or answers late cannot leave a half-written file.- * 3. **Apply + save once.** The providers map is re-read after the probes- * (they are network-bound and outlive the read cache's TTL), every- * probed list is applied in one pass, and `saveProviders` runs exactly- * once — or not at all when nothing was probed successfully.- *- * Never throws for a per-provider failure: each group carries its own- * outcome so the host can log group-level context (one line per group, not- * one per member) and decide what a failure means.- *- * - `updated` — probed successfully; the group's `catalog` was applied to- * every member still present at save time. An empty model list is a real- * answer (the user deleted their last model) and IS persisted; only the- * two statuses below skip.- * - `failed` — the probe threw; `error` carries it. The stored lists are- * left untouched.- * - `missing` — no such provider, or the lead was deleted between the- * grouping read and its probe.- *- * @param {string[]} ids- * @returns {Promise<Array<{ ids: string[], leadId: string, status: 'updated'|'failed'|'missing', catalog?: {models: string[], contextWindows: Record<string, number>}, error?: Error }>>}- */- async refreshProviderModelsBatch(ids) {- const requested = [...new Set(Array.isArray(ids) ? ids : [])];- if (requested.length === 0) return [];-- const data = await loadProviders();- const groups = [];- const byKey = new Map();-- for (const id of requested) {- const provider = data.providers[id];- if (!provider) {- groups.push({ ids: [id], leadId: id, status: 'missing' });- continue;- }- const key = ollamaRefreshGroupKey(provider);- const existing = key ? byKey.get(key) : null;- if (existing) {- existing.ids.push(id);- continue;- }- // `missing` is the starting status for EVERY group, not just the ones- // whose id is already unknown: the probe below either upgrades it or- // leaves it, which is exactly the answer for a lead that vanished- // between this read and its probe.- const group = { ids: [id], leadId: id, status: 'missing' };- if (key) byKey.set(key, group);- groups.push(group);- }-- // Sequential, not `Promise.all`: several groups commonly hit the same- // local daemon, and this whole call is background work behind an- // install/delete, so nothing is waiting on the wall clock.- for (const group of groups) {- if (!data.providers[group.leadId]) continue;- const probed = await this.fetchProviderModelCatalog(group.leadId).then(- (catalog) => ({ catalog }),- (error) => ({ error })- );- if (probed.error) {- group.status = 'failed';- group.error = probed.error;- continue;- }- // A falsy catalog means the lead vanished mid-probe — the same- // `missing` the group already carries, so leave the status alone.- // Anything truthy has been through `toModelCatalog`, so its shape is- // already guaranteed; a legitimately empty catalog still passes.- if (!probed.catalog) continue;- group.status = 'updated';- group.catalog = probed.catalog;- }-- const updated = groups.filter((g) => g.status === 'updated');- if (updated.length === 0) return groups;-- // Re-read rather than reusing the pre-probe snapshot: the probes above are- // network-bound and outlast the read cache's TTL, so `data` may no longer- // be the freshest view. Writing our stale copy would drop anything saved- // while we were probing.- const fresh = await loadProviders();- let changed = false;- for (const group of updated) {- for (const id of group.ids) {- const provider = fresh.providers[id];- // Deleted between the grouping read and now — nothing to write, and- // re-adding it here would resurrect a provider the user removed.- if (!provider) continue;- // Built per member rather than once per group: `modelCatalogUpdate`- // merges against THAT provider's previously-learned windows, and it- // copies the list, so members never share a mutable instance.- const modes = providerModeGroups(Object.values(fresh.providers)).find(entries => entries.some(entry => entry.id === id));- for (const mode of modes || [provider]) {- fresh.providers[mode.id] = {- ...mode,- ...modelCatalogUpdate(group.catalog, mode.modelContextWindows),- };- }- changed = true;- }- }- if (changed) await saveProviders(fresh);-- return groups;- },-- /**- * Probe an OpenAI-compatible `/models` endpoint.- *- * Returns the CATALOG shape (`{ models, contextWindows }`) rather than a- * bare id list — see internal/modelCatalog.js. The Ollama `/api/tags`- * short-circuit below still answers with a plain array; `toModelCatalog`- * normalizes both at the `fetchProviderModelCatalog` boundary.- */- async _refreshAPIProviderModels(provider) {- if (provider.endpoint?.includes('ollama') || provider.endpoint?.includes(':11434')) {- const ollamaUrl = `${provider.endpoint}/api/tags`;- const response = await fetch(ollamaUrl, { signal: AbortSignal.timeout(8000) }).catch(() => null);-- if (response?.ok) {- const data = await response.json().catch(() => null);- if (data?.models) {- return data.models.map(m => m.name || m.model);- }- }- }-- // Guard before attaching the API key to a generic /models fetch so a- // hostile/mistyped endpoint can't harvest a paid LLM key (SSRF).- assertSecretEndpoint(provider.endpoint, {- hasSecret: Boolean(provider.apiKey),- allowCustomEndpoint: provider.allowCustomEndpoint === true,- });-- const modelsUrl = `${provider.endpoint}/models`;- const headers = {};-- if (provider.apiKey) {- headers['Authorization'] = `Bearer ${provider.apiKey}`;- }-- const response = await fetch(modelsUrl, { headers, signal: AbortSignal.timeout(8000) }).catch(() => null);-- if (!response?.ok) {- throw new Error(`HTTP ${response?.status || 'error'}`);- }-- // THROW rather than degrade to `[]` — same posture as `_execCliModelList`.- // A 200 carrying a non-JSON body (an HTML login/captcha page, a proxy- // error page) or a shape with neither `data` nor `models` means the probe- // FAILED; returning an empty list makes that indistinguishable from a- // provider whose catalog is legitimately empty. `refreshProviderModels`- // persists whatever comes back and the UI toasts "Models refreshed", so- // the degraded path silently empties the model dropdown with no reason- // shown. Propagating the error leaves the stored list untouched and puts- // the real cause in the toast. A body that parses to a genuinely empty- // `data`/`models` array still returns `[]` — that distinction is the point.- const responseData = await response.json().catch(() => null);-- if (!responseData || typeof responseData !== 'object') {- throw new Error('Model list response was not valid JSON');- }-- // Entries are usually `{ id }` under `data` and bare strings under- // `models`, but servers mix all four shapes. Returning them unmapped (or- // mapping `m.id` blindly) persisted raw objects / a list of `undefined` —- // a plausible-looking, entirely unusable catalog. Anything that still- // resolves to nothing means the shape isn't one we understand, so throw- // rather than save it, same posture as the unparseable-body case above.- // `parseModelCatalog` also harvests each entry's declared context window- // (internal/modelCatalog.js) — the only source that knows a hosted- // gateway's model really has a 1M window rather than the assumed 128K.- if (Array.isArray(responseData.data)) return parseModelCatalog(responseData.data, 'data');- if (Array.isArray(responseData.models)) return parseModelCatalog(responseData.models, 'models');-- throw new Error('Model list response had no recognizable "data" or "models" array');- },-- /**- * Fetch the catalog from a local MTPLX server for its OpenCode CLI/TUI- * wrappers. MTPLX publishes its active native-MTP model through the same- * OpenAI-compatible `/v1/models` contract as an API provider, so reuse the- * guarded generic parser instead of executing an OpenCode model-list command- * (which would inventory the harness, not the MTPLX runtime).- *- * That endpoint answers with a single id no matter how many checkpoints are- * cached; `fetchProviderModelCatalog` merges the rest in around every arm- * (see `_withCachedCheckpoints`), so this stays the plain probe its siblings- * below are.- *- * This only runs from an explicit refresh request; seeding the disabled- * provider never starts MTPLX, downloads a model, or issues an LLM call.- *- * @param {object} provider- * @returns {Promise<{models: string[], contextWindows: Record<string, number>}>}- */- async _fetchMtplxModels(provider) {- return this._refreshAPIProviderModels(provider);- },-- /**- * Add the checkpoints a one-model-per-process local runtime has ON DISK to- * whatever its server is answering with right now.- *- * MTPLX and Slotstream load a single checkpoint and report only that one- * through `/v1/models` — so a refresh after pulling a second checkpoint- * returned the same lone id it returned before, and the newly downloaded- * weights were unreachable from the provider's model list. The cache is the- * honest catalog of what the machine can serve;- * `providerReadiness.catalogCheck` already grades `servesOneModel` runtimes- * leniently for exactly this reason (one servable id is all such a provider- * needs), and the pinned-model check still flags a provider aimed at a- * checkpoint the daemon has not loaded.- *- * The served probe comes FIRST in the merged list: it is the one id that is- * live right now, so it stays the natural default. Its context windows are- * kept as-is — a cached-but-unloaded checkpoint declares none, and guessing- * one would be worse than the caller's own fallback.- *- * A failed probe is survivable here and only here: when the cache lists- * something servable, a stopped daemon still has a real catalog to report,- * so the refresh succeeds instead of failing with `HTTP error`. With nothing- * cached the probe's error is rethrown unchanged, preserving the- * throw-don't-degrade posture `_refreshAPIProviderModels` documents.- *- * @param {object} provider- * @param {() => Promise<unknown>} probeServed- */- async _withCachedCheckpoints(provider, probeServed) {- // Both probes start before either is awaited: they are independent, and on- // the MTPLX path one is a subprocess while the other is an HTTP request to- // a daemon that may be down — sequentially that is the subprocess PLUS a- // connect timeout on every refresh click, rather than the longer of the two.- //- // `Promise.resolve().then` around the host call, not just `.catch` after- // it: a probe that throws SYNCHRONOUSLY would otherwise unwind past the- // handler and fail a refresh the endpoint could have answered on its own.- const [cached, probed] = await Promise.all([- typeof cachedModelIds === 'function'- ? Promise.resolve().then(() => cachedModelIds(provider)).catch(() => null)- : null,- // `ok` carries the outcome rather than the error's truthiness — the- // same absent-vs-falsy sentinel rule the rest of this file follows, so- // the two reads below say which case they mean instead of inferring it.- probeServed().then((result) => ({ ok: true, result }), (error) => ({ ok: false, error })),- ]);- if (!Array.isArray(cached) || cached.length === 0) {- if (!probed.ok) throw probed.error;- return probed.result;- }- const catalog = toModelCatalog(probed.result) || { models: [], contextWindows: {} };- // A failed probe means the daemon is not answering — NOT that its- // launch-line id stopped existing. That id is in a different namespace- // from the cache (MTPLX answers as a slug its launch line minted, its- // cache yields HF repo ids) and is typically the record's own- // `defaultModel`, so dropping it would prune the pin off a provider merely- // because its server was stopped. A SUCCESSFUL probe stays authoritative,- // so a genuinely delisted model still disappears.- const stale = !probed.ok && Array.isArray(provider?.models) ? provider.models : [];- return {- models: [...new Set([...catalog.models, ...stale, ...cached])],- contextWindows: catalog.contextWindows,- };- },-- /**- * Fetch the downloaded catalog from the local LM Studio server for its- * harness wrappers. Refresh-only, like every other local fetcher here: it- * never starts LM Studio, downloads a model, or issues a completion.- */- async _fetchLmstudioModels(provider) {- return this._refreshAPIProviderModels(provider);- },-- /** Fetch the llama-server catalog for OpenCode llama CLI/TUI wrappers. */- async _fetchLlamaModels(provider) {- return this._refreshAPIProviderModels(provider);- },-- /**- * Fetch the served catalog from a local vLLM container for its OpenCode- * CLI/TUI wrappers. Same OpenAI-compatible contract as MTPLX/llama-server,- * plus the compose stack's API key as a Bearer header (attached by- * `_refreshAPIProviderModels` from the wrapper's own `apiKey`).- *- * Refresh-only, like every other local fetcher here: it never starts the- * container, pulls the image, or issues a completion.- */- async _fetchVllmModels(provider) {- return this._refreshAPIProviderModels(provider);- },-- /**- * Fetch the served catalog from a local SGLang container for its OpenCode- * CLI/TUI wrappers. Refresh-only, like every other local fetcher here: it- * never starts the container, pulls the image, or issues a completion.- */- async _fetchSglangModels(provider) {- return this._refreshAPIProviderModels(provider);- },-- /** Fetch a hosted gateway's catalog for its OpenCode CLI/TUI wrappers. */- async _fetchGatewayModels(provider) {- return this._refreshAPIProviderModels(provider);- },-- async _refreshCLIProviderModels(provider) {- // One lookup, not a per-vendor `if` chain. The table- // (internal/modelFetchers.js) also owns the ORDER this used to encode in- // prose: the ollama row first (a `claude` CLI pointed at a local Ollama- // daemon must pull the installed tool-use-capable models, not the static- // Anthropic list), then every command/structural match, and only then the- // weaker display-name matches — so a cursor provider a user renamed- // "Cursor Claude Opus" reaches cursor-agent rather than having Anthropic's- // catalog persisted onto it.- const fetcher = resolveModelFetcher(provider);-- if (fetcher) {- return await this[fetcher.fetch](provider);- }-- // 400, not the rethrow's 502 default: nothing upstream failed — this CLI- // simply has no fetcher, which is a bad request, not a bad gateway.- const unsupported = new Error('Model refresh not supported for this CLI provider');- unsupported.status = 400;- throw unsupported;- },-- /**- * agy ships an `agy models` subcommand that prints one model id per line —- * the authoritative catalog for this user's plan and binary version, which- * a hardcoded list can only go stale against.- *- * Throws rather than falling back to `ANTIGRAVITY_MODEL_CATALOG` on a failed- * or unparseable probe — see `_execCliModelList` for why that matters. The- * shipped catalog is for *seeding and migration* only.- *- * The sentinel is always re-prepended: it is what keeps "use agy's own- * configured default" selectable after a refresh.- */- async _fetchAntigravityModels(provider) {- const listed = await this._execCliModelList(provider, 'agy', parseAntigravityModelList);- return [ANTIGRAVITY_CONFIGURED_DEFAULT, ...new Set(listed)];- },-- /**- * Shared scaffolding for every "shell `<bin> models` and parse stdout"- * fetcher. Owns the spawn conventions the vendors agree on — the Windows-safe- * invocation, the 15s cap, the provider `envVars` merge, closing the child's- * stdin, and the two failure messages — so a change to any of them (adding- * stderr to the error, reacting to a spawn quirk) is one edit rather than one- * per vendor. What differs per vendor is only the default binary and the- * parser; a sentinel prepend, if any, belongs to the caller.- *- * THROWS on a probe that can't run (binary not installed, service PATH can't- * resolve it, timeout, non-zero exit) AND on one that returns nothing- * parseable — never returns an empty list. That is the load-bearing part:- * every caller's alternative would be its shipped seed catalog, and- * surfacing that from a refresh would make a failed probe indistinguishable- * from a real fetch — `refreshProviderModels` would persist it and the UI- * would toast "Models refreshed", so a user whose PATH can't see the binary- * would pick a model their plan doesn't have and only find out when the run- * dies. `refreshProviderModels` propagates the throw (as a 502) rather than- * flattening it to null, so the toast names the actual cause instead of the- * route's generic not-found text — and the stored list is left untouched- * either way, since nothing is persisted. Same posture as- * `_fetchOllamaToolCapableModels`, and the root AGENTS.md rule that a- * reachable-but-list-failed backend must surface an explicit error rather- * than a plausible-looking empty/default result.- *- * @param {object} provider- * @param {string} defaultBin - binary to use when the provider pins no command- * @param {(stdout: string) => string[]} parse - vendor's stdout → ids parser- * @param {string[]} [listArgs] - catalog command arguments- * @param {(stdout: string) => boolean} [isEmptyCatalog] - explicit empty-catalog response- * @returns {Promise<string[]>} parsed ids; empty only when explicitly recognized- */- async _execCliModelList(provider, defaultBin, parse, listArgs = ['models'], isEmptyCatalog = () => false) {- const spawned = resolveProbeSpawn(provider, defaultBin, listArgs);- const probe = spawned.label;- const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);- const pending = execFileAsync(command, args, {- timeout: 15000,- env: { ...process.env, ...provider?.envVars },- });- // Close the child's stdin immediately. `agy models` blocks on an open- // stdin and prints NOTHING until it closes — with execFile's default pipe- // that's a full 15s hang ending in SIGTERM and an empty catalog. (execFile- // ignores an `stdio` option, so ending the stream is the way to do it.)- // Not every vendor needs it — cursor-agent 2026.08.04 answers in well- // under a second either way (measured 848ms with stdin open vs 825ms- // closed) — but it costs one FD close and makes the probe immune whether- // or not a given binary has the behavior.- pending.child?.stdin?.end();- const { stdout } = await pending.catch((err) => {- const output = `${err.stdout || ''}\n${err.stderr || ''}`;- if (!err.killed && isEmptyCatalog(output)) return { stdout: output };- throw new Error(`${probe} failed: ${err?.message || 'could not run the binary'}`);- });-- const listed = parse(stdout);- if (listed.length === 0 && !isEmptyCatalog(stdout)) {- throw new Error(`${probe} returned no model ids`);- }- return listed;- },-- async _fetchPiModels(provider) {- const { PI_COMMAND, parsePiModelList } = await import('./internal/pi.js');- return this._execCliModelList(provider, PI_COMMAND, parsePiModelList, ['--list-models'],- (stdout) => /No models available/i.test(stdout) && /\/login/.test(stdout));- },-- /**- * cursor-agent ships a `models` subcommand that prints the authoritative- * catalog for THIS account and binary version — 177 ids at time of writing,- * against the 27 hand-curated ones the provider seed ships. Unlike Grok/Kimi- * (no catalog subcommand at all, hence their `*-configured-default`- * sentinel), cursor can answer for itself, so a refresh asks it rather than- * re-serving a list that can only go stale.- *- * Throws rather than falling back to the shipped 27-id seed on a failed or- * unparseable probe — see `_execCliModelList` for why that matters.- *- * No sentinel is prepended (the one structural difference from the agy- * fetcher): cursor exposes a real `auto` id — its own server-side router,- * and the binary's default — and `models` lists it first, so "let cursor- * choose" survives a refresh as an ordinary catalog entry.- *- * The full list is persisted as reported, `-fast` priority-compute twins- * included. A refresh is an explicit user action and the account catalog is- * the authoritative answer; any thinning belongs in the picker, not here, so- * the stored list stays faithful to what the binary will actually accept.- */- async _fetchCursorModels(provider) {- return await this._execCliModelList(provider, CURSOR_COMMAND, parseCursorModelList);- },-- /**- * Codex exposes its model catalog through the `codex app-server` JSON-RPC- * interface via the `model/list` RPC method.- *- * Throws on failure or timeout rather than falling back to static seeds,- * consistent with _execCliModelList and _fetchOllamaToolCapableModels.- */- async _fetchCodexModels(provider) {- const spawned = resolveProbeSpawn(provider, 'codex', ['app-server']);- const probe = spawned.label;- // On Windows, npm places a POSIX `codex` stub beside its runnable- // `codex.cmd` shim. `spawn('codex')` can select the former (or fail to- // resolve it entirely), even though the provider passed its capability- // check. Resolve the extension-bearing shim before the safe cmd.exe- // wrapper below, matching the other CLI probes in this module.- const childEnv = { ...process.env, ...provider?.envVars };- const resolvedBin = resolveWindowsExecutable(spawned.command, process.platform === 'win32', childEnv) || spawned.command;- const { command, args } = prepareWindowsSafeSpawn(resolvedBin, spawned.args);- return new Promise((resolve, reject) => {- let settled = false;- let child;- const settle = (err, result) => {- if (settled) return;- settled = true;- clearTimeout(timer);- try {- child?.kill('SIGTERM');- } catch {}- if (err) reject(err);- else resolve(result);- };-- const timer = setTimeout(() => {- settle(new Error(`${probe} timed out waiting for model catalog`));- }, 15000);- timer.unref?.();-- try {- child = spawn(command, args, {- stdio: ['pipe', 'pipe', 'pipe'],- env: childEnv,- windowsHide: true,- });- } catch (err) {- settle(new Error(`${probe} failed to spawn: ${err?.message || err}`));- return;- }-- child.on('error', (err) => {- settle(new Error(`${probe} failed: ${err?.message || err}`));- });-- child.stdin?.on('error', () => {});-- child.on('exit', (code, signal) => {- settle(new Error(`${probe} exited prematurely with code ${code ?? signal}`));- });-- let buffer = '';- child.stdout?.on('data', (chunk) => {- buffer += chunk.toString();- const lines = buffer.split('\n');- buffer = lines.pop() ?? '';- for (const line of lines) {- const trimmed = line.trim();- if (!trimmed) continue;- try {- const msg = JSON.parse(trimmed);- if (msg.id === 1) {- child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', method: 'initialized', params: {} }) + '\n');- child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'model/list', params: {} }) + '\n');- } else if (msg.id === 2) {- if (msg.error) {- settle(new Error(`${probe} model/list error: ${msg.error.message || JSON.stringify(msg.error)}`));- return;- }- const rawModels = msg.result?.data || msg.result?.models || [];- const ids = rawModels- .filter((m) => !m.hidden)- .map((m) => (typeof m === 'string' ? m : m?.id || m?.model))- .filter(Boolean);- if (ids.length === 0) {- settle(new Error(`${probe} returned no model ids`));- return;- }- settle(null, [...new Set(ids)]);- return;- }- } catch {}- }- });-- child.stdin?.write(- JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'initialize',- params: { clientInfo: { name: 'portos', version: '1.0.0' } },- }) + '\n',- );- });- },-- async _fetchOllamaToolCapableModels(provider) {- const base = ollamaBaseFromProvider(provider);- const res = await fetch(`${base}/api/tags`, { signal: AbortSignal.timeout(8000) }).catch(() => null);- if (!res?.ok) {- throw new Error(`Ollama unreachable at ${base} (HTTP ${res?.status || 'error'})`);- }- const data = await res.json().catch(() => null);- const names = (data?.models || []).map(m => m.name || m.model).filter(Boolean);-- // Query /api/show per model for the authoritative `tools` capability; fall- // back to the id heuristic when the daemon doesn't answer. Filter to- // tool-use-capable models only — a Claude harness on a non-tool model- // "runs" but silently fails to edit files.- const checked = await Promise.all(names.map(async (name) => {- const showRes = await fetch(`${base}/api/show`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ model: name, name }),- signal: AbortSignal.timeout(8000)- }).catch(() => null);- const showData = showRes?.ok ? await showRes.json().catch(() => null) : null;- const capabilities = Array.isArray(showData?.capabilities) ? showData.capabilities : null;- return ollamaModelSupportsTools(name, capabilities) ? name : null;- }));- return checked.filter(Boolean);- },-- /**- * Read the model catalog the installed Claude Code caches for THIS account.- *- * Every other vendor in the fetcher table answers a `models` subcommand;- * `claude` ships none, so this reads the file the binary writes instead —- * `<configDir>/cache/model-catalog/*.json`, refreshed by the CLI whenever a- * session runs. See internal/claudeCodeCatalog.js for why that file and not- * `/v1/models` (which needs an API key a subscription record does not have).- *- * THROWS rather than falling back to a hardcoded list, the same posture- * `_execCliModelList` documents: `refreshProviderModels` persists whatever- * comes back and the card toasts "Models refreshed", so degrading to a- * static list would silently re-stamp the stale answer the user clicked- * Refresh to escape. Throwing leaves the stored catalog untouched and puts- * the real cause — "run `claude` once so it caches its catalog" — in the- * toast. The shipped `data.reference/providers.json` list remains the SEED- * for a fresh install, exactly as the antigravity catalog is.- */- async _fetchAnthropicModels(provider) {- const env = { ...process.env, ...provider?.envVars };- const configDir = claudeConfigDir(env, homedir());- if (!configDir) throw new Error('Cannot locate the Claude Code config directory (no HOME and no CLAUDE_CONFIG_DIR)');- const catalogDir = join(configDir, ...CLAUDE_CATALOG_SUBPATH);-- const files = await readdir(catalogDir).catch(() => null);- if (!files) {- throw new Error(`Claude Code has not cached a model catalog yet (${catalogDir} is missing) — run \`claude\` once, then refresh`);- }-- const entries = (await Promise.all(- files.filter((name) => name.endsWith('.json')).map(async (name) => {- const raw = await readFile(join(catalogDir, name), 'utf8').catch(() => null);- if (raw === null) return null;- try {- return JSON.parse(raw);- } catch {- // One unreadable file must not lose a sibling that parses — the- // directory holds one entry per signed-in account.- return null;- }- }),- )).filter(Boolean);-- const cliVersion = await this._claudeCliVersion(provider);- const models = selectCatalogModels(entries, { cliVersion });- if (models.length === 0) {- // A cache full of ids this binary's floor rejects is a different- // problem from an empty or unreadable cache. "Run claude once" does- // not help the first one — the file is already there.- const present = selectCatalogModels(entries, { applyVersionFloor: false });- if (present.length > 0) {- throw new Error(`Claude Code ${cliVersion || 'unknown'} cannot select any model in the cached catalog — upgrade \`claude\`, then refresh`);- }- throw new Error(`No usable Claude Code model catalog in ${catalogDir} — run \`claude\` once, then refresh`);- }-- const age = catalogAge(entries);- // An out-of-range `fetchedAt` must not fail a refresh that already- // selected ids. `Date#toISOString` throws on those, and this log runs- // before the list is returned.- const stamp = age ? new Date(age) : null;- const cached = stamp && !Number.isNaN(stamp.getTime()) ? stamp.toISOString() : 'unknown';- console.log(`📋 Claude Code catalog: ${models.length} models (cached ${cached})`);- return models;- },-- /**- * The installed binary's version, used only to drop catalog entries whose- * `min_claude_code_version` this build cannot select. Best-effort: an- * unreadable version means "no floor" (see `versionAtLeast`), so a failed- * probe widens the list rather than emptying it.- */- async _claudeCliVersion(provider) {- const spawned = resolveProbeSpawn(provider, 'claude', ['--version']);- const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);- const pending = execFileAsync(command, args, {- timeout: 10000,- env: { ...process.env, ...provider?.envVars },- });- // Same reason as `_execCliModelList`: an open stdin makes some CLIs wait- // out the whole timeout instead of printing `--version`.- pending.child?.stdin?.end();- const { stdout } = await pending.catch(() => ({ stdout: '' }));- return (/(\d+\.\d+\.\d+)/.exec(stdout || '') || [])[1] || '';- },-- async _fetchGeminiModels(provider) {- const apiKey = provider.apiKey || process.env.GOOGLE_API_KEY;-- if (!apiKey) {- // 400 for the same reason as the endpoint guard: a missing key is the- // user's to fix, not an upstream outage.- const missingKey = new Error('Google API key required for model refresh');- missingKey.status = 400;- throw missingKey;- }-- const response = await fetch(- `https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`,- { signal: AbortSignal.timeout(8000) }- ).catch(() => null);-- if (!response?.ok) {- throw new Error(`HTTP ${response?.status || 'error'}`);- }-- const data = await response.json().catch(() => ({ models: [] }));-- return (data.models || [])- .filter(m => m.supportedGenerationMethods?.includes('generateContent'))- .map(m => m.name.replace('models/', ''));- },-- async getSampleProviders() {- const data = await loadProviders();- const existingIds = new Set(Object.keys(data.providers));-- let sampleProviders = {};- if (existsSync(DEFAULT_SAMPLE_PATH)) {- const content = await readFile(DEFAULT_SAMPLE_PATH, 'utf-8');- const parsed = JSON.parse(content);- sampleProviders = { ...parsed.providers };- }-- if (sampleFile && existsSync(sampleFile)) {- const content = await readFile(sampleFile, 'utf-8');- const parsed = JSON.parse(content);- sampleProviders = { ...sampleProviders, ...parsed.providers };- }-- return Object.values(sampleProviders).filter(p => !existingIds.has(p.id));- }- };+ loadProviders,+ saveProviders,+ buildProviderRecord,+ storeProviderRecords,+ sampleFile,+ cachedModelIds,+ resolveCompositeProvider,+ } = state;+ const crud = createProviderCrudService({+ loadProviders,+ saveProviders,+ buildProviderRecord,+ storeProviderRecords,+ withGatewayModelAccess,+ readProvider,+ resolveCompositeProvider,+ expandModePair,+ modeSiblingPayload,+ providerModeGroups,+ sharedModeUpdates,+ normalizeModelAccess,+ });+ const catalog = createProviderCatalogService({+ loadProviders,+ saveProviders,+ withGatewayApiKey,+ cachedModelIds,+ sampleFile,+ defaultSamplePath: DEFAULT_SAMPLE_PATH,+ });+ return { ...crud, ...catalog };}diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.jsindex dd74d48d1c..db92101207 100644--- a/server/lib/cliChildEnv.test.js+++ b/server/lib/cliChildEnv.test.js@@ -683,7 +683,7 @@ describe('no spawn site rebuilds the CLI child env by hand', () => {// composer, and the dormancy is why its missing CLAUDECODE strip / OpenCode// map is not a live PortOS gap someone needs to chase.['lib/aiToolkit/runner.js', 'vendored toolkit — must not import out to other PortOS modules, and its spawn is dormant under PortOS\'s setCliRunner override'],- ['lib/aiToolkit/providers.js', 'vendored toolkit — must not import out to other PortOS modules; capability probe only (codex app-server), runs no models'],+ ['lib/aiToolkit/internal/providerCatalogService.js', 'vendored toolkit catalog probes — must not import out to other PortOS modules'],]);// Two independent markers, because either one alone has a blind spot: a newdiff --git a/server/lib/localModelHeuristics.mirror.test.js b/server/lib/localModelHeuristics.mirror.test.jsindex c449218eab..1905031e30 100644--- a/server/lib/localModelHeuristics.mirror.test.js+++ b/server/lib/localModelHeuristics.mirror.test.js@@ -2,7 +2,7 @@* Mirror parity test for the tool-use capability regex, which exists in two* copies by architecture:* 1. server/lib/localModelHeuristics.js — authoritative;- * 2. server/lib/aiToolkit/providers.js — the vendored toolkit may not import+ * 2. server/lib/aiToolkit/internal/providerCatalogService.js — the vendored toolkit may not import* out of its own directory (see aiToolkit/AGENTS.md), so TOOL_USE_RE is* inlined there too.*@@ -20,7 +20,7 @@ import { compareDeclaration } from './mirrorParity.js';const __dirname = dirname(fileURLToPath(import.meta.url));const SERVER_PATH = resolve(__dirname, 'localModelHeuristics.js');-const TOOLKIT_PATH = resolve(__dirname, 'aiToolkit/providers.js');+const TOOLKIT_PATH = resolve(__dirname, 'aiToolkit/internal/providerCatalogService.js');describe('localModelHeuristics↔aiToolkit TOOL_USE_RE mirror parity', () => {const serverSrc = readFileSync(SERVER_PATH, 'utf8');@@ -31,7 +31,7 @@ describe('localModelHeuristics↔aiToolkit TOOL_USE_RE mirror parity', () => {compareDeclaration(serverSrc, toolkitSrc, 'TOOL_USE_RE');expect(serverDecl, 'server/lib/localModelHeuristics.js is missing: TOOL_USE_RE').not.toBeNull();- expect(clientDecl, 'server/lib/aiToolkit/providers.js is missing: TOOL_USE_RE').not.toBeNull();+ expect(clientDecl, 'server/lib/aiToolkit/internal/providerCatalogService.js is missing: TOOL_USE_RE').not.toBeNull();expect(clientNorm,'TOOL_USE_RE diverged — the localModelHeuristics copy is authoritative; port the change verbatim',diff --git a/server/services/providers.shape.test.js b/server/services/providers.shape.test.jsindex 9a3d1bec92..5e35a8b30d 100644--- a/server/services/providers.shape.test.js+++ b/server/services/providers.shape.test.js@@ -19,7 +19,7 @@ import { collectServerSources, readServerSource, SERVER_DIR } from '../lib/testH*/describe('getAllProviders returns an envelope, not a list', () => {it('is documented as such at the definition', () => {- const src = readFileSync(join(SERVER_DIR, 'lib/aiToolkit/providers.js'), 'utf8');+ const src = readFileSync(join(SERVER_DIR, 'lib/aiToolkit/internal/providerCrudService.js'), 'utf8');// The toolkit builds the envelope inline; if this shape ever changes, every// `listProviders` consumer has to be revisited.expect(src).toMatch(/return \{\s*activeProvider: data\.activeProvider,\s*providers: Object\.values\(data\.providers\)/);