Skip to content

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

scope a provider's model list to the plan you actually pay for

[._.]/ Adam Eivy9c47101131a1
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index 317a188f0e..cffba442a8 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -19,6 +19,8 @@ import Drawer from '../Drawer';
import useDrawerTab from '../../hooks/useDrawerTab';
import { FormField } from '../ui/FormField';
import { GatewayKeyHint } from './ProviderNotices';
+import ProviderModelAccess from './ProviderModelAccess';
+import { normalizeModelAccess, providerModelCatalog } from '../../utils/providerModelAccess';
// The provider editor's Drawer tabs. `connection` is the default, so a bare
// /ai/edit/:providerId deep link opens on the identity/transport fields; the
@@ -61,7 +63,15 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
apiKey: '',
allowCustomEndpoint: provider?.allowCustomEndpoint === true,
ignoreUserConfig: provider?.ignoreUserConfig === true,
- models: provider?.models || [],
+ // The FULL advertised catalog, never the model-access-scoped `models` the
+ // payload carries. This textarea is saved verbatim, so seeding it from the
+ // scoped list would let an ordinary Save persist the narrowed catalog over
+ // the real one — recoverable only by a refresh, and silently wrong until then.
+ models: providerModelCatalog(provider),
+ // Absent on a record with no policy, which is the shape the server reads as
+ // "unconstrained". `null` (not `undefined`) when cleared, so the PATCH
+ // spread-merge sees a clear rather than "unchanged".
+ modelAccess: provider?.modelAccess || null,
hardwareRequirements: provider?.hardwareRequirements,
modelHardwareRequirements: provider?.modelHardwareRequirements,
defaultModel: provider?.defaultModel || '',
@@ -371,6 +381,10 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
for (const field of ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel', 'ultraModel', 'fallbackModel']) {
if (isEmbeddingModel(data[field])) data[field] = '';
}
+ // An explicit `null` rather than `undefined` when the policy says nothing:
+ // the server merges a PATCH by spread, which reads `undefined` as "unchanged"
+ // and would leave a policy the user just cleared in place.
+ data.modelAccess = normalizeModelAccess(formData.modelAccess);
// Effort is meaningful only for providers/models that expose an effort
// ladder. Clear a stale value when an edit switches to an effort-less
// provider or Antigravity model; narrowed ladders are clamped by the
@@ -907,6 +921,17 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
</p>
</FormField>
+ {/* Which of that catalog this install is entitled to run. Fed the
+ FULL list (`formData.models`, seeded from `modelCatalog`), because
+ the policy is authored against everything the upstream
+ advertises — the scoped view is what it produces. */}
+ <ProviderModelAccess
+ catalog={formData.models || []}
+ value={formData.modelAccess}
+ provider={{ ...provider, ...formData, id: provider?.id }}
+ onChange={(modelAccess) => setFormData(prev => ({ ...prev, modelAccess }))}
+ />
+
<FormField label="Default Model">
{availableModels.length > 0 ? (
<select
diff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsx
index 990326528a..12edf36737 100644
--- a/client/src/components/providers/ProviderForm.test.jsx
+++ b/client/src/components/providers/ProviderForm.test.jsx
@@ -253,3 +253,84 @@ describe('ProviderForm planned context window', () => {
expect(payload).not.toHaveProperty('modelContextWindows');
});
});
+
+describe('ProviderForm model access', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.updateProvider.mockResolvedValue({});
+ });
+
+ // A scoped payload carries the narrowed list as `models` and the real one as
+ // `modelCatalog`. The editor saves its model textarea verbatim, so seeding it
+ // from `models` would let an unrelated edit persist the narrowed catalog over
+ // the real one — silently, and recoverable only by a refresh.
+ const scopedProvider = {
+ id: 'nvidia-nim',
+ name: 'NVIDIA NIM',
+ type: 'api',
+ endpoint: 'https://integrate.api.nvidia.com/v1',
+ models: ['meta/llama-3.3-70b-instruct'],
+ modelCatalog: ['meta/llama-3.3-70b-instruct', 'nvidia/nemotron-4-340b-instruct'],
+ modelAccess: { mode: 'allow', patterns: ['meta/*'] },
+ modelAccessHiddenCount: 1,
+ };
+
+ it('saves the full advertised catalog, not the scoped view', async () => {
+ renderForm({ provider: scopedProvider });
+ switchTab('Models');
+ expect(screen.getByRole('textbox', { name: /Available Models/i }))
+ .toHaveValue('meta/llama-3.3-70b-instruct, nvidia/nemotron-4-340b-instruct');
+
+ fireEvent.click(screen.getByRole('button', { name: /Update Provider|Save/i }));
+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalled());
+ const [, payload] = api.updateProvider.mock.calls[0];
+ expect(payload.models).toEqual(['meta/llama-3.3-70b-instruct', 'nvidia/nemotron-4-340b-instruct']);
+ expect(payload.modelAccess).toEqual({ mode: 'allow', patterns: ['meta/*'] });
+ });
+
+ it('previews the scope live and ticks a model into the pattern list', async () => {
+ renderForm({ provider: scopedProvider });
+ switchTab('Models');
+ expect(screen.getByText(/Showing 1 of 2 models \(1 hidden\)/)).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: /nvidia\/nemotron-4-340b-instruct/ }));
+ expect(screen.getByText(/Showing 2 of 2 models \(0 hidden\)/)).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: /Update Provider|Save/i }));
+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalled());
+ expect(api.updateProvider.mock.calls[0][1].modelAccess.patterns)
+ .toEqual(['meta/*', 'nvidia/nemotron-4-340b-instruct']);
+ });
+
+ it('switching back to "all" parks the curated list rather than discarding it', async () => {
+ // Re-opening a provider is a mode change, not a decision to throw away the
+ // list the user assembled. The server reads mode `all` as unconstrained, so
+ // the patterns ride along inert and are there when they scope it again.
+ renderForm({ provider: scopedProvider });
+ switchTab('Models');
+ fireEvent.change(screen.getByRole('combobox', { name: /Model Access/i }),
+ { target: { value: 'all' } });
+ expect(screen.queryByText(/Showing 1 of 2 models/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /Update Provider|Save/i }));
+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalled());
+ expect(api.updateProvider.mock.calls[0][1].modelAccess).toEqual({ mode: 'all', patterns: ['meta/*'] });
+ });
+
+ it('a provider that never had a policy sends an explicit null, not an omitted key', async () => {
+ // The server merges a PATCH by spread, so an omitted key reads as
+ // "unchanged" — a cleared policy has to arrive as a value.
+ renderForm({ provider: { ...scopedProvider, modelAccess: undefined, modelCatalog: undefined } });
+ switchTab('Models');
+ fireEvent.click(screen.getByRole('button', { name: /Update Provider|Save/i }));
+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalled());
+ expect(api.updateProvider.mock.calls[0][1].modelAccess).toBeNull();
+ });
+
+ it('says so when a mode is selected but nothing is scoped yet', () => {
+ // "Not configured yet" must not read as a working policy — the count line
+ // would otherwise reassure with "Showing 2 of 2".
+ renderForm({ provider: { ...scopedProvider, modelAccess: { mode: 'allow', patterns: [] } } });
+ switchTab('Models');
+ expect(screen.getByText(/No patterns yet/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/providers/ProviderModelAccess.jsx b/client/src/components/providers/ProviderModelAccess.jsx
new file mode 100644
index 0000000000..c79a2943dd
--- /dev/null
+++ b/client/src/components/providers/ProviderModelAccess.jsx
@@ -0,0 +1,147 @@
+import { useMemo, useState } from 'react';
+import { Check, Square, CheckSquare } from 'lucide-react';
+import { FormField } from '../ui/FormField';
+import { formatCount } from '../../utils/formatters';
+import {
+ MODEL_ACCESS_MODES,
+ MODEL_ACCESS_MODE_LABELS,
+ MAX_MODEL_ACCESS_PATTERNS,
+ modelMatchesAccessPatterns,
+ previewModelAccess,
+} from '../../utils/providerModelAccess';
+
+/**
+ * Editor for a provider's MODEL ACCESS policy — which of the catalog its
+ * upstream advertises this install is actually entitled to run.
+ *
+ * Why a hand-curated list rather than a detected one: entitlement is not in the
+ * catalog response. NVIDIA NIM's `/v1/models` answers with the full product line
+ * and carries no pricing, tier or entitlement field, so the ~38 endpoints that
+ * are free on build.nvidia.com are indistinguishable from the rest over the
+ * wire. The same is true of a vendor key scoped to two models out of thirty.
+ * The user is the only party that knows, so the editor's job is to make saying
+ * it cheap: tick the models off the refreshed catalog, or write a glob when the
+ * tier has a naming convention (OpenRouter's `*:free`).
+ *
+ * The two inputs are ONE list. A ticked checkbox writes the model's exact id as
+ * a pattern, so a user can start from globs and refine by hand — and so the
+ * saved policy always reads as exactly what it does.
+ */
+export default function ProviderModelAccess({ catalog, value, onChange, provider }) {
+ const [patternDraft, setPatternDraft] = useState(null);
+
+ const policy = value || { mode: 'all', patterns: [] };
+ const patterns = policy.patterns || [];
+ const preview = useMemo(
+ () => previewModelAccess(catalog, policy, provider),
+ [catalog, policy, provider],
+ );
+
+ const setPolicy = (next) => onChange({ mode: next.mode, patterns: next.patterns });
+ const setPatterns = (next) => setPolicy({ ...policy, patterns: [...new Set(next)].slice(0, MAX_MODEL_ACCESS_PATTERNS) });
+
+ const togglePattern = (model) => setPatterns(
+ patterns.includes(model) ? patterns.filter(p => p !== model) : [...patterns, model],
+ );
+
+ // A checkbox means "this exact id is in the list", never "the policy admits
+ // this model" — the two differ whenever a glob is in play, and conflating them
+ // would make a `deny` list render inverted. A model a glob already covers gets
+ // its own marker instead. Clicking such a row adds the exact id, which is
+ // additive and harmless; rewriting the user's glob for them would silently
+ // destroy the shorthand they typed.
+ const coveredByGlob = (model) =>
+ !patterns.includes(model) && modelMatchesAccessPatterns(model, patterns);
+
+ return (
+ <div className="space-y-4 border-t border-port-border pt-4">
+ <FormField label="Model Access">
+ <select
+ id="provider-model-access-mode"
+ value={policy.mode}
+ onChange={(e) => setPolicy({ ...policy, mode: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ >
+ {MODEL_ACCESS_MODES.map(mode => (
+ <option key={mode} value={mode}>{MODEL_ACCESS_MODE_LABELS[mode]}</option>
+ ))}
+ </select>
+ <p className="text-xs text-gray-500 mt-1">
+ Scopes every model picker in PortOS — and the model comparison chart — to the
+ models this account can actually run. The provider&apos;s stored catalog is never
+ narrowed, so switching back to &quot;All models&quot; restores it without a refresh.
+ </p>
+ </FormField>
+
+ {policy.mode !== 'all' && (
+ <>
+ <p className={`text-xs ${preview.inert ? 'text-amber-400' : 'text-gray-400'}`}>
+ {preview.inert
+ ? 'No patterns yet — nothing is scoped until you tick a model or add a pattern below.'
+ : `Showing ${formatCount(preview.visible.length)} of ${formatCount(preview.total)} models (${formatCount(preview.hidden)} hidden).`}
+ </p>
+
+ <FormField label="Patterns">
+ <textarea
+ id="provider-model-access-patterns"
+ value={patternDraft ?? patterns.join('\n')}
+ onChange={(e) => setPatternDraft(e.target.value)}
+ onBlur={() => {
+ setPatterns((patternDraft ?? '').split(/[\n,]/).map(p => p.trim()).filter(Boolean));
+ setPatternDraft(null);
+ }}
+ placeholder={'meta/*\nnvidia/llama-3.1-nemotron-70b-instruct\n*:free'}
+ rows={4}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white font-mono text-xs resize-none focus:border-port-accent focus:outline-hidden"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ One per line. <code>*</code> matches any characters and <code>?</code> exactly one;
+ everything else is literal, so a bare id is an exact pin. Matching is
+ case-insensitive and always against the whole model id.
+ </p>
+ </FormField>
+
+ {catalog.length > 0 && (
+ <div>
+ <p className="block text-sm text-gray-400 mb-1">Catalog ({formatCount(catalog.length)})</p>
+ <div className="flex gap-2 mb-2">
+ <button
+ type="button"
+ onClick={() => setPatterns(catalog)}
+ className="px-2 py-1 text-xs bg-port-bg border border-port-border rounded-sm text-gray-300 hover:text-white"
+ >Select all</button>
+ <button
+ type="button"
+ onClick={() => setPatterns([])}
+ className="px-2 py-1 text-xs bg-port-bg border border-port-border rounded-sm text-gray-300 hover:text-white"
+ >Clear</button>
+ </div>
+ <div className="max-h-64 overflow-y-auto border border-port-border rounded-lg divide-y divide-port-border">
+ {catalog.map(model => (
+ <button
+ key={model}
+ type="button"
+ onClick={() => togglePattern(model)}
+ className="w-full flex items-center gap-2 px-3 py-1.5 text-left text-xs text-gray-300 hover:bg-port-bg"
+ >
+ {patterns.includes(model)
+ ? <CheckSquare className="w-3.5 h-3.5 shrink-0 text-port-accent" />
+ : <Square className="w-3.5 h-3.5 shrink-0 text-gray-600" />}
+ <span className="font-mono truncate">{model}</span>
+ {coveredByGlob(model) && (
+ <Check className="w-3.5 h-3.5 shrink-0 text-port-accent ml-auto" aria-label="matched by a pattern" />
+ )}
+ </button>
+ ))}
+ </div>
+ <p className="text-xs text-gray-500 mt-1">
+ Ticking a model adds its exact id to the list above. A check on the right
+ marks a model one of your globs already matches.
+ </p>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 0b2eba4475..d0c63a2690 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -6,6 +6,7 @@ import * as api from '../services/api';
import socket from '../services/socket';
import { filterSelectableModels, isProviderHardwareCompatible, mergeModelLists, localBackendForProvider, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isCodexSubscriptionProvider, isLocalEndpoint, isLocalInstanceProvider, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';
import { copyToClipboard } from '../lib/clipboard';
+import { formatCount } from '../utils/formatters';
import { isHttpsUrl } from '../utils/urlNormalize';
import useLocalModels from '../hooks/useLocalModels';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
@@ -887,6 +888,17 @@ export default function AIProviders() {
{filterSelectableModels(provider.models).length > 0 && (
<p>Models: {filterSelectableModels(provider.models).slice(0, 3).join(', ')}{filterSelectableModels(provider.models).length > 3 ? ` +${filterSelectableModels(provider.models).length - 3}` : ''}</p>
)}
+ {/* The card's model line shows the SCOPED list, so say when a
+ model-access policy is what makes it short — otherwise a
+ user comparing it against the vendor's catalog reads a
+ deliberate scope as a failed refresh. */}
+ {provider.modelAccessHiddenCount > 0 && (
+ <p className="text-gray-500">
+ {formatCount(provider.modelAccessHiddenCount)} more hidden by model access
+ {provider.modelAccessSource && provider.modelAccessSource !== 'own'
+ ? ` (from ${provider.modelAccessSource})` : ''}
+ </p>
+ )}
{provider.envVars && Object.keys(provider.envVars).length > 0 && (
<div className="mt-0.5">
<span>Env:</span>
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 3835e3e5d3..f2b436e093 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -62,6 +62,7 @@ is where each shared table is re-exported from its `server/lib` leaf.
| `providerSelection` | Which providers and models a picker may OFFER on this install: `isProviderHardwareCompatible` / `isProviderModelHardwareCompatible` / `filterHardwareCompatibleProviderModels` (server-annotated, fail-open), `selectableProviders` (the single rule `ProviderModelSelector` renders from), `filterRunnableProviders` (agent jobs need a CLI/TUI harness), the fail-closed tool-free local policy (`TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, `toolFreeLocalSelectionPolicy`) used by security-sensitive pickers, and the pr-reviewer postures (`PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, `publicReviewSelectionPolicy` — mirror of `server/lib/agentExecutionProfiles.js`: a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` and `publicReviewEnforcedPostures` on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on, so no vendor is named on either side). Also the caller EXECUTION-MODE picker rule (`callerModeList`, `providerModeSelectionPolicy`) over `server/lib/callerModePolicy.js` — the server enforces the policy on the pin, on `activeProvider` inheritance and on every fallback candidate; this only lets a picker SHOW the rule, keeping an ineligible saved value visible-but-disabled instead of hidden or silently replaced — read off `CALLER_MODE_POLICIES` in that pure leaf, so it cannot drift). |
| `localModelHeuristics` | What an untyped LOCAL model can do, judged from its id: `isEmbeddingModel` / `isVisionModel` / `isToolUseModel` (re-exported from the pure leaf `server/lib/localModelHeuristics.js` — one regex per family; a model card's explicit capability metadata outranks the id regex), `isVisionCapableCliProvider`, `filterGenerationModels` (sentinels and embedding-only models dropped), `visionLocalModelFilter` and `localToolUseHint` / `withToolUseOptionLabel` (unioned with the server's authoritative per-provider capability maps from `useVisionModelIds` / `useToolUseModelIds`; tool-use is an annotation plus warning, never a filter), and `modelCapabilityInfo` (capability badges for a selected model without over-sharing a local runtime's answer with another provider). |
| `providerContextWindows` | How large a context window a provider/model gets for planning and where the number came from: the vendor constants and the `KNOWN_MODEL_CONTEXT_WINDOWS` ladder (`knownModelContextWindow`, `knownProviderContextWindow`), `catalogModelContextWindow` (the window the provider's own `/models` catalog reported), `resolveModelContextWindow` → `{ tokens, source }` with `CONTEXT_WINDOW_SOURCE` (`override` / `reported` / `assumed` — the state a card has to label rather than print as fact), `effectiveModelContextWindow`, and `modelOptionLabel` ("id (32K ctx)"). The constants and the known-model / known-provider / catalog rungs are re-exported from the pure leaf `server/lib/providerContextWindows.js`, the same rungs the server's `effectiveContextWindow` budgets with — including `mergeObservedContextWindows`, which folds a local daemon's live window (off the readiness payload) onto the catalog rung so the card shows what the dispatch gate enforces, and holds every resolved window down to an Ollama daemon's launch `num_ctx` through `clampToRuntimeContextWindow` (applied internally, from `server/lib/aiToolkit/internal/ollamaBacked.js` — the same module the server's budgeter and pre-dispatch gate use), so the meter can't promise a budget a run would be refused for (#7466). `withRuntimeContextWindow(provider, ceiling)` stamps that ceiling's second rung — the ambient `OLLAMA_CONTEXT_LENGTH` the server launched the daemon with, which the browser cannot read and so takes off the readiness payload as `runtimeContextWindow` (#7472). |
+| `providerModelAccess` | Which of a provider's advertised catalog this install is entitled to run (free tier, plan, hand-picked allowlist). Re-exports the policy rules from the pure leaf `server/lib/aiToolkit/internal/modelAccess.js` — `normalizeModelAccess`, `modelAccessConstrains`, `scopeModelsByAccess`, `applyModelAccess` — so the editor's live preview and the server's own scoping cannot disagree. Adds `providerModelCatalog(provider)` (the FULL list, off `modelCatalog` when the payload was scoped — seed a model editor from this or a Save persists the narrowed list), `previewModelAccess(catalog, policy, provider)` → `{ total, visible, hidden, inert }`, and `MODEL_ACCESS_MODE_LABELS`. |
| `providerReadiness` | Is a provider READY to run on this install, and why not. `credentialSource` (stored / inherited / env / subscription / none) and `providerCardState(provider, { runtime, status, keySetFor, envVarSet, codexAccount })` + `PROVIDER_CARD_STATE` — ready, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential env var / signed-out ChatGPT account), unknown, or simply switched off. Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, the same computation `getFallbackProvider` routes on) and adds only what the browser can see; unknown lookup values mean "not probed", never "missing". Distinct from `ProviderReadiness` / `GET /api/providers/readiness`, which probes the local daemon behind a provider. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner accept this command? Mirrors only the normalization in `server/cos-runner/allowedCommands.js` (the list arrives as `runnerAllowedCommands` on `GET /api/providers`); returns `null` for "list not fetched" so a failed fetch never renders a warning; pinned by `server/cos-runner/allowedCommands.parity.test.js`. `resolvesOutsidePortosPath` / `providerRuntimeKey` (the key a CLI runtime is published under by `GET /api/providers/runtimes`), `supportsModelRefresh` (`canRefreshModels === true`, the server's own answer) and `codexRoutingAdvisory` (the non-blocking "your `~/.codex/config.toml` re-points Codex" notice — server-only and machine-local, rendered in the UI and nowhere else). |
| `providerAssignments` | Which provider/model a RECORD resolves to, and the option helpers the assignment editors share: `resolveEffectiveProvider` (its pin, else the active provider, plus whether it fell back so a "Default" option can name what it resolves to), `resolveSeriesRunLlm` (mirror of `server/lib/seriesLlmOverride.js`: per-run override → `series.llm` → active provider), `getProviderTimeout`, `providerDisplayName` and `providerModelLabel` (the one "Provider / model" phrasing), and `assignmentProviderOptions` / `assignmentModelOptions` / `assignmentDefaultModel` / `assignmentToolUseState` over the `getAiAssignments` payload shape — shared by the global AI Assignments table and every per-record override drawer so none of them derives the rule differently. |
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 67697be001..80e38976a0 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -36,6 +36,7 @@ export * from './layeredIntelligenceReasons.js';
export * from './localModelHeuristics.js';
export * from './providerAssignments.js';
export * from './providerContextWindows.js';
+export * from './providerModelAccess.js';
export * from './providerEndpoints.js';
export * from './providerGateways.js';
export * from './providerHarnesses.js';
diff --git a/client/src/utils/providerModelAccess.js b/client/src/utils/providerModelAccess.js
new file mode 100644
index 0000000000..5a4fd6324b
--- /dev/null
+++ b/client/src/utils/providerModelAccess.js
@@ -0,0 +1,75 @@
+/**
+ * Which of a provider's advertised catalog this install is entitled to run —
+ * the browser half of the model-access policy.
+ *
+ * Every rule is re-exported from the server module that declares it
+ * (`server/lib/aiToolkit/internal/modelAccess.js`), reached at the toolkit's
+ * dependency-free `internal/` leaf exactly as `providerContextWindows.js`
+ * reaches `ollamaBacked.js`. Nothing here restates a pattern rule: the editor's
+ * live "N of M models" preview and the server's own scoping have to agree, or
+ * the user tunes a policy against a count the API never produces.
+ */
+
+export {
+ MODEL_ACCESS_MODES,
+ MAX_MODEL_ACCESS_PATTERNS,
+ MAX_MODEL_ACCESS_PATTERN_LENGTH,
+ CONFIGURED_MODEL_KEYS,
+ normalizeModelAccess,
+ modelAccessConstrains,
+ modelMatchesAccessPatterns,
+ scopeModelsByAccess,
+ providerConfiguredModels,
+ effectiveModelAccess,
+ applyModelAccess,
+ applyModelAccessList,
+} from '../../../server/lib/aiToolkit/internal/modelAccess.js';
+
+import {
+ modelAccessConstrains,
+ normalizeModelAccess,
+ providerConfiguredModels,
+ scopeModelsByAccess,
+} from '../../../server/lib/aiToolkit/internal/modelAccess.js';
+
+/** How each mode reads in the editor. Ordered as the mode selector renders them. */
+export const MODEL_ACCESS_MODE_LABELS = Object.freeze({
+ all: 'All models the provider advertises',
+ allow: 'Only models matching the list',
+ deny: 'All models except those matching the list',
+});
+
+/**
+ * The FULL advertised catalog for a provider payload.
+ *
+ * A scoped payload carries the untouched list as `modelCatalog` and a narrowed
+ * `models`; an unscoped one carries only `models`. Editors must read the
+ * catalog through this — seeding a model textarea from `models` alone would let
+ * an ordinary Save persist the narrowed list over the real one.
+ */
+export const providerModelCatalog = (provider) =>
+ (Array.isArray(provider?.modelCatalog) ? provider.modelCatalog
+ : Array.isArray(provider?.models) ? provider.models : []);
+
+/**
+ * What a policy WOULD do to a catalog, for the editor's live preview.
+ *
+ * Takes the catalog explicitly rather than reading `provider.models`, because
+ * the editor previews an unsaved policy against the full list — the value the
+ * server will scope once the form is saved.
+ */
+export function previewModelAccess(catalog, policy, provider) {
+ const models = (catalog || []).filter(model => typeof model === 'string' && model);
+ const normalized = normalizeModelAccess(policy);
+ const visible = scopeModelsByAccess(models, normalized, { keep: providerConfiguredModels(provider) });
+ return {
+ total: models.length,
+ visible,
+ hidden: models.length - visible.length,
+ // The distinction the sentinel discipline exists for: a mode is SELECTED
+ // but constrains nothing yet (no patterns typed). The editor says so rather
+ // than showing a reassuring "all 82 of 82 models", which reads as a saved
+ // policy that works.
+ inert: Boolean(normalized) && normalized.mode !== 'all' && !modelAccessConstrains(normalized),
+ };
+}
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index e5ebf9c916..85741438b2 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -12,6 +12,7 @@
* providerSelection.js — which providers/models a picker may OFFER
* localModelHeuristics.js — what an untyped local model can DO
* providerContextWindows.js — how large a CONTEXT WINDOW it gets
+ * providerModelAccess.js — which of its catalog this install is ENTITLED to
* providerReadiness.js — is it READY to run, and why not
* providerAssignments.js — which provider a RECORD resolves to; assignment options
*
@@ -24,6 +25,7 @@
export * from './localModelHeuristics.js';
export * from './providerAssignments.js';
export * from './providerContextWindows.js';
+export * from './providerModelAccess.js';
export * from './providerEndpoints.js';
export * from './providerGateways.js';
export * from './providerModels.js';
diff --git a/docs/MODEL_ACCESS.md b/docs/MODEL_ACCESS.md
new file mode 100644
index 0000000000..a49a5eba3c
--- /dev/null
+++ b/docs/MODEL_ACCESS.md
@@ -0,0 +1,95 @@
+# Model access — scoping a provider to what you are entitled to run
+
+A provider's model list is what its upstream **advertises**, which for a hosted
+gateway is the vendor's whole product line regardless of what your account can
+reach. NVIDIA NIM's `/v1/models` answers with 80+ models; only a subset is free
+on [build.nvidia.com](https://build.nvidia.com/models). An OpenRouter account may
+be limited to the `:free` variants. A vendor key may be scoped to two models out
+of thirty.
+
+Entitlement is **not in the catalog response** — NVIDIA's entries carry `id`,
+`object`, `created` and `owned_by` and no pricing, tier or entitlement field — so
+PortOS cannot detect it. It is declared instead, per provider, in
+**Settings → AI Providers → Edit → Models → Model Access**.
+
+## What a policy does
+
+| Mode | Effect |
+|------|--------|
+| `all` | Everything the provider advertises. The shipped default. |
+| `allow` | Only models matching the pattern list. |
+| `deny` | Everything except models matching the pattern list. |
+
+Once set, the scope applies to **every model picker in PortOS** — provider cards,
+CoS agent and task pickers, pipeline stage pickers, reviewer model selection —
+and to the **model comparison chart**, whose default pills and coverage list are
+built from the models your providers can dispatch.
+
+## Patterns
+
+Case-insensitive globs over the whole model id:
+
+- `*` matches any run of characters, `?` matches exactly one.
+- Everything else is literal, so `moonshotai/kimi-k2.5` is an exact pin and
+ `gpt-4.1` does not match `gpt-4x1`.
+- There is no substring matching: `gemma` does not match `google/gemma-3-4b-it`.
+ Write `*gemma*` if that is what you mean — a policy that silently widened
+ itself would be one you cannot audit by reading it.
+
+Ticking a model in the editor's catalog list adds its exact id to the same list,
+so you can start from globs (`meta/*`) and refine by hand. A check mark on the
+right of a row means one of your globs already covers it.
+
+Useful shapes:
+
+```
+meta/* # a vendor namespace
+*:free # an OpenRouter free variant
+nvidia/llama-3.1-nemotron-70b-instruct # an exact pin
+```
+
+## What it never does
+
+- **The stored catalog is never narrowed.** Scoping happens on the way out to a
+ reader; `providers.json` keeps the real list. Switching back to "All models"
+ restores it with no re-probe, and a refresh always re-learns the full catalog.
+- **A configured model is never hidden.** A model pinned as the provider's
+ default, a Light/Medium/Heavy/Ultra tier, or a fallback stays selectable even
+ when the policy would exclude it — a picker whose stored value is missing from
+ its options renders blank and re-points the provider on the next save. The
+ policy governs what can be chosen *next*, not what the record already says.
+- **A half-finished policy hides nothing.** Selecting `allow` before typing any
+ pattern means "not configured yet", not "hide everything", so model pickers
+ stay populated while you work. The editor says so explicitly rather than
+ showing a reassuring count.
+
+## Gateway inheritance
+
+A hosted gateway is usually three PortOS records: the `api` provider, its
+OpenCode CLI wrapper, and its TUI wrapper. They front the same upstream on one
+account, so **a wrapper with no policy of its own inherits the gateway's** —
+exactly as it already inherits the gateway's API key. Set the policy once on
+`nvidia-nim` and the API, CLI and TUI options all narrow together.
+
+A wrapper that declares its own policy keeps it. A CLI/TUI pair (`<stem>` /
+`<stem>-tui`) shares one policy the way it already shares `models`: it is one
+program on one backend.
+
+## Where it lives
+
+| Concern | File |
+|---------|------|
+| Policy rules (normalize, match, scope) | `server/lib/aiToolkit/internal/modelAccess.js` |
+| Storage + gateway inheritance | `server/lib/aiToolkit/providers.js` (`withGatewayModelAccess`) |
+| Schema | `server/lib/aiToolkit/validation.js` (`providerSchema.modelAccess`) |
+| Applied to provider payloads | `server/routes/providers.js` (`presentProvider`) and `server/lib/aiToolkit/routes/providers.js` |
+| Applied to the comparison chart | `server/routes/modelComparison.js` |
+| Editor | `client/src/components/providers/ProviderModelAccess.jsx` |
+| Browser-side rules | `client/src/utils/providerModelAccess.js` |
+
+The payload a client receives carries `models` (scoped), `modelCatalog` (the full
+advertised list, present only when something was hidden), `modelAccess` (the
+record's own policy), `modelAccessEffective` / `modelAccessSource` (the resolved
+one and where it came from) and `modelAccessHiddenCount`. **An editor that saves a
+model list must seed it from `modelCatalog`**, or an ordinary save persists the
+narrowed list over the real one.
diff --git a/docs/README.md b/docs/README.md
index 7b61366cce..23553b216d 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -21,6 +21,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [INSTANCE_FEATURES.md](./INSTANCE_FEATURES.md) | Optional per-install features — registry, client-side nav gating, feature groups, reconcile-at-toggle |
| [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects |
| [QUOTA-BURN.md](./QUOTA-BURN.md) | Quota-burn automation — spending subscription-backed CLI quota before expiry |
+| [MODEL_ACCESS.md](./MODEL_ACCESS.md) | Scoping a provider to the models your plan entitles you to — free tiers, allow/deny globs, gateway inheritance |
| [MODEL-COMPARISON.md](./MODEL-COMPARISON.md) | Sourced provider/model/effort comparisons, cost estimates and CoS research refresh |
| [THREEJS_MODELS.md](./THREEJS_MODELS.md) | Three.js procedural 3D model generation and trust boundary |
| [features/music-renderer-benchmarks.md](./features/music-renderer-benchmarks.md) | Technical and full-length listening evidence for local music renderer profiles |
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.md
index 872d45ddc5..d5851f13e3 100644
--- a/server/lib/aiToolkit/AGENTS.md
+++ b/server/lib/aiToolkit/AGENTS.md
@@ -13,6 +13,14 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous
- `updateProvider()` uses spread so existing providers preserve custom fields, but `createProvider()` 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:
+
+- **The stored catalog is never narrowed.** `applyModelAccess` runs at the route (`routes/providers.js` here, `presentProvider` in the host), so `providers.json` keeps the real list and a cleared policy restores it with no re-probe. The scoped payload carries the original as `modelCatalog` — **the provider editor seeds its model textarea from that**, because it saves the box verbatim and would otherwise persist the narrowed list over the real one.
+- **`all` and an empty pattern list both mean NO CONSTRAINT** (the root AGENTS.md sentinel rule). A mode picked before any pattern is typed is a half-finished edit, not an instruction to blank every model picker in the app. A stored `{ mode: 'all', patterns: [...] }` is a PARKED list and must keep its patterns.
+- **A model the record NAMES is never hidden** (`defaultModel`, the four tiers, `fallbackModel`) — a picker whose stored value is missing from its options renders blank and re-points the provider on the next save.
+
+Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy of its own takes the sibling gateway record's, resolved on read into `modelAccessEffective` / `modelAccessSource` — two derived field names, not the persisted `modelAccess`, because that one IS in `providerSchema` and a client echoing a GET back on a PUT would pin the inherited value forever. Composition order against `withGatewayApiKey` is load-bearing (that helper attaches the key NON-enumerably, so a spread after it drops the credential). A write response carries the resolution forward from the read the route already performed (`withResolvedModelAccess`) rather than re-reading — several suites drive those routes with a service double whose `getProviderById` answers a different fixture. Glob matching is a hand-rolled iterative matcher, not a translated RegExp: the patterns are user input (`*a*a*a*b` backtracks exponentially), and a translation would have to re-inline the escape `server/lib/textUtils.test.js` forbids — which this directory cannot import its way out of. Contract and field list: `docs/MODEL_ACCESS.md`.
+
**Provider-service extension point.** `createProviderService` / `createAIToolkit` accept `onProvidersSaved(data)`, invoked after every SUCCESSFUL `providers.json` write with the data that landed. PortOS injects it in `server/services/bootstrap.js` to keep its machine-local provider connection graph (`server/services/providerGraph.js`, #6367) reconciled with a file that a legacy `PATCH /api/providers/:id`, a model refresh, a migration or a downgraded release may also write. The hook is deliberately non-fatal: the write already landed and the cache already reflects it, and callers include boot warmups and schedulers with no `next(err)` to bubble to, so a throwing hook is logged and swallowed. Pair it with `applyProviderPatches(patches)`, which applies partial updates to SEVERAL named records in ONE write and — unlike `updateProvider` — performs no sibling fan-out, because a projection must touch exactly the routes it named and no conventional neighbour.
**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:
diff --git a/server/lib/aiToolkit/internal/modelAccess.js b/server/lib/aiToolkit/internal/modelAccess.js
new file mode 100644
index 0000000000..b27e21afbb
--- /dev/null
+++ b/server/lib/aiToolkit/internal/modelAccess.js
@@ -0,0 +1,223 @@
+/**
+ * Per-provider MODEL ACCESS policy — which of a provider's catalog this install
+ * is actually entitled to run.
+ *
+ * ## Why a policy rather than a shorter catalog
+ *
+ * A provider's `models` list is what its upstream ADVERTISES, and for a hosted
+ * gateway that is the vendor's whole product line regardless of what the user
+ * has paid for. NVIDIA NIM's `/v1/models` answers with its entire catalog; only
+ * a subset is reachable on the free build.nvidia.com tier, and nothing in the
+ * response says which (the entries carry `id`/`object`/`created`/`owned_by` and
+ * no pricing, tier or entitlement field). The same shape recurs everywhere a
+ * plan gates a catalog: an OpenRouter account with only the `:free` variants, a
+ * vendor key scoped to two models out of thirty.
+ *
+ * So entitlement cannot be DERIVED — it has to be DECLARED. This module is the
+ * declaration: a small, user-editable policy stored on the provider record.
+ *
+ * ## The catalog is never destroyed
+ *
+ * Scoping happens on the way OUT to a reader, never at refresh time, and the
+ * unscoped list stays in `providers.json`. Turning the policy off restores the
+ * full list with no re-probe, and a provider whose upstream catalog moved on
+ * still has the real answer stored. The scoped payload carries the original as
+ * `modelCatalog` so an editor round-trip cannot save the narrowed list over it.
+ *
+ * ## `all` and an empty pattern list both mean "no constraint"
+ *
+ * Following the sentinel discipline in the root AGENTS.md: *not configured* and
+ * *configured to hide everything* must not collapse into one value. A policy in
+ * `allow` mode with NO patterns is a half-finished edit (the user picked the
+ * mode, then went to type the list), not an instruction to blank every model
+ * picker in the app — so it reads as no constraint. Hiding everything is spelled
+ * by there being no matching model, which requires at least one real pattern.
+ *
+ * ## Patterns
+ *
+ * Case-insensitive globs over the WHOLE model id: `*` matches any run of
+ * characters, `?` exactly one, and everything else is literal. `meta/*` scopes a
+ * vendor namespace, `*:free` an OpenRouter tier suffix, and a bare
+ * `moonshotai/kimi-k2.5` is an exact pin. No substring matching — `gemma` does
+ * not match `google/gemma-3-4b-it`, because a policy that silently widened
+ * itself would be a policy the user cannot audit by reading it.
+ */
+
+/** The declared policy modes. `all` is the shipped default (today's behavior). */
+export const MODEL_ACCESS_MODES = Object.freeze(['all', 'allow', 'deny']);
+
+/** Bounds mirrored by the zod schema in ../validation.js. */
+export const MAX_MODEL_ACCESS_PATTERNS = 500;
+export const MAX_MODEL_ACCESS_PATTERN_LENGTH = 200;
+
+/**
+ * The provider fields that NAME a model to run with, as opposed to listing one
+ * that could be chosen. A named model is never scoped out (see
+ * {@link scopeModelsByAccess}).
+ */
+export const CONFIGURED_MODEL_KEYS = Object.freeze([
+ 'defaultModel', 'lightModel', 'mediumModel', 'heavyModel', 'ultraModel', 'fallbackModel',
+]);
+
+/**
+ * Normalize a stored/submitted policy to `{ mode, patterns }`, or `null` when
+ * it constrains nothing.
+ *
+ * `null` is the "no policy" sentinel every reader below keys on, and it covers
+ * three distinct inputs deliberately: a missing/garbage value, `mode: 'all'`,
+ * and a constraining mode with no usable pattern. What it does NOT do is erase
+ * a stored pattern list when the mode is `all` — that combination is how a user
+ * parks a curated list while temporarily opening the provider back up, so the
+ * patterns are preserved on the record and merely not applied. Readers ask
+ * {@link modelAccessConstrains} rather than re-deriving that rule.
+ */
+export function normalizeModelAccess(value) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const mode = MODEL_ACCESS_MODES.includes(value.mode) ? value.mode : 'all';
+ const patterns = [...new Set((Array.isArray(value.patterns) ? value.patterns : [])
+ .filter(pattern => typeof pattern === 'string')
+ .map(pattern => pattern.trim())
+ .filter(Boolean)
+ .map(pattern => pattern.slice(0, MAX_MODEL_ACCESS_PATTERN_LENGTH)))]
+ .slice(0, MAX_MODEL_ACCESS_PATTERNS);
+ if (mode === 'all' && patterns.length === 0) return null;
+ return { mode, patterns };
+}
+
+/** True when a normalized policy actually narrows a catalog. */
+export const modelAccessConstrains = (policy) =>
+ Boolean(policy) && policy.mode !== 'all' && policy.patterns.length > 0;
+
+/**
+ * Match one glob against one id — iterative, with no RegExp.
+ *
+ * Two reasons it is not a compiled RegExp. First, the patterns are USER INPUT,
+ * and a translated glob backtracks catastrophically: `*a*a*a*a*a*b` against a
+ * long non-matching id is exponential in a backtracking engine, and this runs
+ * once per model per read. The greedy-with-one-backtrack walk below is O(n·m)
+ * with no such cliff. Second, a RegExp translation has to escape every regex
+ * metacharacter in the pattern, and this directory may not import the repo's
+ * shared `escapeRegExp` (it stays self-contained — see ../AGENTS.md), so it
+ * would have to re-inline the escape the tree-wide guard in
+ * `server/lib/textUtils.test.js` exists to prevent.
+ *
+ * `*` consumes any run including empty, `?` exactly one character, everything
+ * else is literal — so a pattern with no wildcard is an exact, case-insensitive
+ * equality test.
+ */
+function globMatches(text, pattern) {
+ let t = 0;
+ let p = 0;
+ // Where the most recent `*` sat, and how much of the text it had consumed at
+ // the time. On a dead end we return here and let it eat one more character —
+ // the single backtrack that keeps this linear-ish instead of exponential.
+ let star = -1;
+ let consumedAtStar = 0;
+ while (t < text.length) {
+ if (p < pattern.length && (pattern[p] === '?' || pattern[p] === text[t])) {
+ t += 1;
+ p += 1;
+ } else if (p < pattern.length && pattern[p] === '*') {
+ star = p;
+ p += 1;
+ consumedAtStar = t;
+ } else if (star >= 0) {
+ p = star + 1;
+ consumedAtStar += 1;
+ t = consumedAtStar;
+ } else {
+ return false;
+ }
+ }
+ while (p < pattern.length && pattern[p] === '*') p += 1;
+ return p === pattern.length;
+}
+
+/** True when `modelId` matches any of `patterns`. */
+export function modelMatchesAccessPatterns(modelId, patterns) {
+ if (typeof modelId !== 'string' || !modelId) return false;
+ const id = modelId.toLowerCase();
+ return (patterns || []).some(pattern => globMatches(id, String(pattern).toLowerCase()));
+}
+
+/**
+ * The subset of `models` the policy admits.
+ *
+ * `keep` names ids that stay visible whatever the policy says — the models the
+ * provider is CONFIGURED to run. A picker rendering a stored `defaultModel` that
+ * the policy hides would show a blank selection and silently re-point the
+ * provider on the next save, which is a worse failure than showing one model
+ * the user did not list. The policy governs what can be CHOSEN next, not what
+ * the record already says.
+ *
+ * Order is the catalog's own; `keep` never reorders or introduces an id the
+ * catalog does not contain.
+ */
+export function scopeModelsByAccess(models, policy, { keep = [] } = {}) {
+ const catalog = (models || []).filter(model => typeof model === 'string' && model);
+ if (!modelAccessConstrains(policy)) return catalog;
+ const kept = new Set(keep.filter(model => typeof model === 'string' && model));
+ return catalog.filter(model => {
+ if (kept.has(model)) return true;
+ const matched = modelMatchesAccessPatterns(model, policy.patterns);
+ return policy.mode === 'allow' ? matched : !matched;
+ });
+}
+
+/** The model ids a provider record NAMES (see {@link CONFIGURED_MODEL_KEYS}). */
+export const providerConfiguredModels = (provider) =>
+ CONFIGURED_MODEL_KEYS.map(key => provider?.[key]).filter(model => typeof model === 'string' && model);
+
+/**
+ * The policy that governs a provider read: its OWN first, then the resolved
+ * `modelAccessEffective` a caller may have stamped (see `withGatewayModelAccess`
+ * in ../providers.js).
+ *
+ * Own-first matters on a write response, where a route carries the resolution
+ * forward from the read that preceded the write: a policy the write just SET
+ * must outrank the inherited one that was resolved a moment earlier. The two
+ * agree in every other case, because `withGatewayModelAccess` copies an own
+ * policy into the resolved field rather than inheriting past it.
+ *
+ * Consequence worth knowing: a wrapper cannot opt OUT of its gateway's policy by
+ * storing mode `all` with no patterns, because that normalizes to "no policy"
+ * and inheritance takes over. Opting out is spelled as a `deny` list that
+ * matches nothing. A third "explicitly unconstrained" state is not worth the
+ * field until someone needs it.
+ */
+export const effectiveModelAccess = (provider) =>
+ normalizeModelAccess(provider?.modelAccess) || normalizeModelAccess(provider?.modelAccessEffective);
+
+/**
+ * The shape a provider takes on its way out to a reader that SELECTS models:
+ * `models` narrowed to the policy, with the untouched catalog preserved as
+ * `modelCatalog` and the count it hid as `modelAccessHiddenCount`.
+ *
+ * Returns the SAME object when nothing was hidden, so a provider with no policy
+ * — every record on an install that has not configured this — serializes byte
+ * for byte as it did before, and `modelCatalog` is absent rather than a
+ * redundant copy of `models`.
+ *
+ * `modelCatalog` matters beyond display: the provider editor seeds its
+ * "Available Models" box from the payload, so without the full list in hand an
+ * ordinary Save on a scoped provider would persist the narrowed catalog over
+ * the real one — a silent, refresh-only-recoverable data loss.
+ */
+export function applyModelAccess(provider) {
+ if (!provider || typeof provider !== 'object') return provider;
+ const policy = effectiveModelAccess(provider);
+ if (!modelAccessConstrains(policy)) return provider;
+ const catalog = Array.isArray(provider.models) ? provider.models : [];
+ const scoped = scopeModelsByAccess(catalog, policy, { keep: providerConfiguredModels(provider) });
+ if (scoped.length === catalog.length) return provider;
+ return {
+ ...provider,
+ models: scoped,
+ modelCatalog: catalog,
+ modelAccessHiddenCount: catalog.length - scoped.length,
+ };
+}
+
+/** Array form of {@link applyModelAccess}. */
+export const applyModelAccessList = (providers) =>
+ (Array.isArray(providers) ? providers.map(applyModelAccess) : providers);
diff --git a/server/lib/aiToolkit/internal/modelAccess.test.js b/server/lib/aiToolkit/internal/modelAccess.test.js
new file mode 100644
index 0000000000..b45c663a1f
--- /dev/null
+++ b/server/lib/aiToolkit/internal/modelAccess.test.js
@@ -0,0 +1,187 @@
+import { describe, it, expect } from 'vitest';
+import {
+ applyModelAccess,
+ applyModelAccessList,
+ modelAccessConstrains,
+ modelMatchesAccessPatterns,
+ normalizeModelAccess,
+ providerConfiguredModels,
+ scopeModelsByAccess,
+} from './modelAccess.js';
+
+const NVIDIA_CATALOG = [
+ 'meta/llama-3.1-8b-instruct',
+ 'meta/llama-3.3-70b-instruct',
+ 'nvidia/llama-3.1-nemotron-70b-instruct',
+ 'nvidia/nv-embedqa-mistral-7b-v2',
+ 'moonshotai/kimi-k2.5',
+];
+
+describe('normalizeModelAccess', () => {
+ it('reads a missing, malformed or unconstraining policy as the same null sentinel', () => {
+ // One sentinel, three inputs: nothing stored, garbage stored, and a mode
+ // that constrains nothing. Every reader keys on `null`, so they must not
+ // each have to re-derive which of the three they are looking at.
+ for (const value of [undefined, null, 'allow', [], 42, { mode: 'all' }, { mode: 'all', patterns: [] }]) {
+ expect(normalizeModelAccess(value)).toBeNull();
+ }
+ });
+
+ it('keeps a parked pattern list when the mode is switched back to all', () => {
+ // The user turning a provider back open must not lose the list they curated
+ // — the mode is the switch, the patterns are the work.
+ expect(normalizeModelAccess({ mode: 'all', patterns: ['meta/*'] }))
+ .toEqual({ mode: 'all', patterns: ['meta/*'] });
+ expect(modelAccessConstrains(normalizeModelAccess({ mode: 'all', patterns: ['meta/*'] }))).toBe(false);
+ });
+
+ it('trims, de-duplicates and drops blanks without reordering', () => {
+ expect(normalizeModelAccess({ mode: 'allow', patterns: [' meta/* ', '', 'meta/*', 'nvidia/*'] }))
+ .toEqual({ mode: 'allow', patterns: ['meta/*', 'nvidia/*'] });
+ });
+
+ it('falls back to the unconstraining mode for an unknown one', () => {
+ // A record written by a newer build must degrade to "no constraint", never
+ // to an arbitrary constraining mode that hides models the user can run.
+ expect(normalizeModelAccess({ mode: 'subscription', patterns: ['meta/*'] }))
+ .toEqual({ mode: 'all', patterns: ['meta/*'] });
+ });
+});
+
+describe('modelMatchesAccessPatterns', () => {
+ it('matches the whole id, not a substring', () => {
+ expect(modelMatchesAccessPatterns('meta/llama-3.1-8b-instruct', ['llama'])).toBe(false);
+ expect(modelMatchesAccessPatterns('meta/llama-3.1-8b-instruct', ['*llama*'])).toBe(true);
+ });
+
+ it('treats regex metacharacters in a pattern as literals', () => {
+ // `gpt-4.1` must not match `gpt-4x1` — a dot that acted as a wildcard would
+ // silently widen a policy past what the user can read in it.
+ expect(modelMatchesAccessPatterns('gpt-4x1', ['gpt-4.1'])).toBe(false);
+ expect(modelMatchesAccessPatterns('gpt-4.1', ['gpt-4.1'])).toBe(true);
+ });
+
+ it('supports * and ? and ignores case', () => {
+ expect(modelMatchesAccessPatterns('openai/gpt-oss-120b:free', ['*:free'])).toBe(true);
+ expect(modelMatchesAccessPatterns('META/Llama-3.1-8b-instruct', ['meta/*'])).toBe(true);
+ expect(modelMatchesAccessPatterns('gpt-4', ['gpt-?'])).toBe(true);
+ expect(modelMatchesAccessPatterns('gpt-41', ['gpt-?'])).toBe(false);
+ });
+});
+
+describe('scopeModelsByAccess', () => {
+ it('admits everything when the policy constrains nothing', () => {
+ for (const policy of [null, { mode: 'all', patterns: ['meta/*'] }, { mode: 'allow', patterns: [] }]) {
+ expect(scopeModelsByAccess(NVIDIA_CATALOG, normalizeModelAccess(policy))).toEqual(NVIDIA_CATALOG);
+ }
+ });
+
+ it('a half-finished allow policy shows everything rather than nothing', () => {
+ // The regression this exists for: a user picks "only models matching the
+ // list", and before a single pattern is typed every model picker in PortOS
+ // goes blank. "Not configured yet" and "configured to hide everything" are
+ // different states and must not collapse.
+ expect(scopeModelsByAccess(NVIDIA_CATALOG, normalizeModelAccess({ mode: 'allow', patterns: [] })))
+ .toEqual(NVIDIA_CATALOG);
+ expect(scopeModelsByAccess(NVIDIA_CATALOG, normalizeModelAccess({ mode: 'allow', patterns: ['nothing-matches-this'] })))
+ .toEqual([]);
+ });
+
+ it('allow keeps matches, deny drops them, both in catalog order', () => {
+ expect(scopeModelsByAccess(NVIDIA_CATALOG, { mode: 'allow', patterns: ['meta/*', 'moonshotai/*'] }))
+ .toEqual(['meta/llama-3.1-8b-instruct', 'meta/llama-3.3-70b-instruct', 'moonshotai/kimi-k2.5']);
+ expect(scopeModelsByAccess(NVIDIA_CATALOG, { mode: 'deny', patterns: ['nvidia/*'] }))
+ .toEqual(['meta/llama-3.1-8b-instruct', 'meta/llama-3.3-70b-instruct', 'moonshotai/kimi-k2.5']);
+ });
+
+ it('never hides a model the provider is configured to run', () => {
+ // A picker whose stored value is missing from its options renders blank and
+ // re-points the provider on the next save. The policy governs what may be
+ // chosen NEXT, not what the record already says.
+ expect(scopeModelsByAccess(NVIDIA_CATALOG, { mode: 'allow', patterns: ['meta/*'] }, {
+ keep: ['nvidia/llama-3.1-nemotron-70b-instruct'],
+ })).toContain('nvidia/llama-3.1-nemotron-70b-instruct');
+ });
+
+ it('a kept id the catalog does not list is not introduced', () => {
+ expect(scopeModelsByAccess(NVIDIA_CATALOG, { mode: 'allow', patterns: ['meta/*'] }, {
+ keep: ['some/model-that-was-deleted'],
+ })).not.toContain('some/model-that-was-deleted');
+ });
+});
+
+describe('providerConfiguredModels', () => {
+ it('collects every tier a record pins and nothing else', () => {
+ expect(providerConfiguredModels({
+ defaultModel: 'a', lightModel: 'b', mediumModel: '', heavyModel: null,
+ ultraModel: 'c', fallbackModel: 'd', models: ['e'],
+ })).toEqual(['a', 'b', 'c', 'd']);
+ });
+});
+
+describe('applyModelAccess', () => {
+ const scoped = { id: 'nvidia-nim', models: NVIDIA_CATALOG, modelAccess: { mode: 'allow', patterns: ['meta/*'] } };
+
+ it('narrows models and preserves the full catalog for the editor', () => {
+ const result = applyModelAccess(scoped);
+ expect(result.models).toEqual(['meta/llama-3.1-8b-instruct', 'meta/llama-3.3-70b-instruct']);
+ // Without this the provider editor — which saves its model textarea verbatim
+ // — would persist the narrowed list over the real catalog on any unrelated edit.
+ expect(result.modelCatalog).toEqual(NVIDIA_CATALOG);
+ expect(result.modelAccessHiddenCount).toBe(3);
+ });
+
+ it('leaves the stored record untouched', () => {
+ applyModelAccess(scoped);
+ expect(scoped.models).toEqual(NVIDIA_CATALOG);
+ });
+
+ it('returns the SAME object when nothing is hidden', () => {
+ // An install that has not configured this must serialize byte for byte as
+ // before — no redundant `modelCatalog` copy on every provider in the list.
+ const plain = { id: 'ollama', models: NVIDIA_CATALOG };
+ expect(applyModelAccess(plain)).toBe(plain);
+ const openPolicy = { id: 'x', models: NVIDIA_CATALOG, modelAccess: { mode: 'allow', patterns: ['*'] } };
+ expect(applyModelAccess(openPolicy)).toBe(openPolicy);
+ });
+
+ it('prefers a resolved inherited policy over the record\'s own absent one', () => {
+ // `modelAccessEffective` is what `withGatewayModelAccess` stamps on a
+ // gateway-backed wrapper: one NVIDIA entitlement covers the api record, its
+ // CLI wrapper and its TUI wrapper.
+ const wrapper = {
+ id: 'opencode-nvidia-nim',
+ models: NVIDIA_CATALOG,
+ modelAccessEffective: { mode: 'allow', patterns: ['meta/*'] },
+ };
+ expect(applyModelAccess(wrapper).models).toHaveLength(2);
+ });
+
+ it('passes nullish and non-array inputs through', () => {
+ expect(applyModelAccess(null)).toBeNull();
+ expect(applyModelAccessList(undefined)).toBeUndefined();
+ expect(applyModelAccessList([{ id: 'a' }])).toEqual([{ id: 'a' }]);
+ });
+});
+
+describe('glob matching is not a translated RegExp', () => {
+ it('answers a pathological pattern instantly instead of backtracking', () => {
+ // Patterns are user input, and a glob translated to a RegExp backtracks
+ // exponentially on this shape — every model list read would hang. The
+ // greedy single-backtrack walk is O(n·m). Budgeted generously so the guard
+ // reports the cliff, not machine noise.
+ const started = Date.now();
+ expect(modelMatchesAccessPatterns('a'.repeat(400), ['*a*a*a*a*a*a*a*a*a*a*b'])).toBe(false);
+ expect(Date.now() - started).toBeLessThan(1000);
+ });
+
+ it('handles trailing, leading and consecutive wildcards', () => {
+ expect(modelMatchesAccessPatterns('meta/llama', ['*'])).toBe(true);
+ expect(modelMatchesAccessPatterns('meta/llama', ['**meta**'])).toBe(true);
+ expect(modelMatchesAccessPatterns('meta/llama', ['meta/*'])).toBe(true);
+ expect(modelMatchesAccessPatterns('meta/', ['meta/*'])).toBe(true);
+ expect(modelMatchesAccessPatterns('meta', ['meta/*'])).toBe(false);
+ expect(modelMatchesAccessPatterns('meta/llama', ['*llama'])).toBe(true);
+ expect(modelMatchesAccessPatterns('meta/llama-x', ['*llama'])).toBe(false);
+ });
+});
diff --git a/server/lib/aiToolkit/internal/providerModes.js b/server/lib/aiToolkit/internal/providerModes.js
index fa8da745f4..1641b69626 100644
--- a/server/lib/aiToolkit/internal/providerModes.js
+++ b/server/lib/aiToolkit/internal/providerModes.js
@@ -87,7 +87,13 @@ export function sharedModeUpdates(updates, sibling) {
// line and env from — pointed at the old backend with the old credential,
// and splits the one card in two on the next load. `unifyProviderModes`
// converges a pair that arrived asymmetric by some other route.
- const shared = Object.fromEntries(['enabled', 'models', 'modelContextWindows', ...MODE_GROUPED_KEYS]
+ // `modelAccess` rides with `models` rather than with the argv: a pair is one
+ // program on one backend, so the entitlement that scopes that backend's
+ // catalog cannot differ between the headless and interactive mode without the
+ // two cards offering different models for the same account. It stays OUT of
+ // MODE_GROUPED_KEYS, though — it is not connection identity, and pairing on it
+ // would split a card the moment one mode was edited first.
+ const shared = Object.fromEntries(['enabled', 'models', 'modelContextWindows', 'modelAccess', ...MODE_GROUPED_KEYS]
.filter(key => Object.hasOwn(updates, key))
.map(key => [key, detachModeValue(updates[key])]));
// A caller deliberately repicking a default with a new catalog (the editor
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index a41a63bbe8..f2e211c137 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -26,6 +26,7 @@ import { isOllamaBackedProvider, ollamaBaseFromProvider } from './internal/ollam
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 { normalizeModelAccess } from './internal/modelAccess.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.
@@ -64,6 +65,42 @@ 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);
+ if (own) return { ...provider, modelAccessEffective: own, modelAccessSource: 'own' };
+ const gateway = gatewayForProvider(provider);
+ const inherited = gateway ? normalizeModelAccess(providers?.[gateway.id]?.modelAccess) : null;
+ if (!inherited) return provider;
+ return { ...provider, modelAccessEffective: inherited, modelAccessSource: gateway.id };
+}
+
// 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
@@ -724,6 +761,12 @@ export function createProviderService(config = {}) {
...(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.
+ ...(normalizeModelAccess(providerData.modelAccess)
+ ? { modelAccess: normalizeModelAccess(providerData.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.
@@ -757,23 +800,26 @@ export function createProviderService(config = {}) {
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)
+ providers: Object.values(data.providers).map(provider => withGatewayModelAccess(provider, data.providers))
};
},
async getProviderById(id) {
const data = await loadProviders();
const provider = data.providers[id];
- return provider ? withGatewayApiKey(provider, data.providers) : null;
+ return provider ? withGatewayApiKey(withGatewayModelAccess(provider, data.providers), data.providers) : null;
},
async getActiveProvider() {
const data = await loadProviders();
if (!data.activeProvider) return null;
const provider = data.providers[data.activeProvider];
- return provider ? withGatewayApiKey(provider, data.providers) : null;
+ return provider ? withGatewayApiKey(withGatewayModelAccess(provider, data.providers), data.providers) : null;
},
async setActiveProvider(id) {
@@ -877,6 +923,15 @@ export function createProviderService(config = {}) {
// stored `null` would no longer read as "never had one".
const dropClearedBootstrap = (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;
+ }
};
dropClearedBootstrap(provider);
diff --git a/server/lib/aiToolkit/providers.modelAccess.test.js b/server/lib/aiToolkit/providers.modelAccess.test.js
new file mode 100644
index 0000000000..bc6074ef76
--- /dev/null
+++ b/server/lib/aiToolkit/providers.modelAccess.test.js
@@ -0,0 +1,141 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { createProviderService } from './providers.js';
+import { applyModelAccess } from './internal/modelAccess.js';
+
+// Temp dir, NOT a cwd-rooted one — see providerStatus.test.js (#3823).
+let TEST_DATA_DIR;
+
+const NVIDIA_CATALOG = ['meta/llama-3.1-8b-instruct', 'nvidia/nemotron-4-340b-instruct', 'moonshotai/kimi-k2.5'];
+
+/** The shipped NVIDIA shape: a gateway `api` record plus its OpenCode CLI/TUI wrappers. */
+const nvidiaInstall = (modelAccess) => ({
+ activeProvider: 'nvidia-nim',
+ providers: {
+ 'nvidia-nim': {
+ id: 'nvidia-nim', name: 'NVIDIA NIM', type: 'api',
+ endpoint: 'https://integrate.api.nvidia.com/v1', apiKey: 'nvapi-test',
+ models: NVIDIA_CATALOG, ...(modelAccess ? { modelAccess } : {}),
+ },
+ 'opencode-nvidia-nim': {
+ id: 'opencode-nvidia-nim', name: 'NVIDIA NIM via OpenCode', type: 'cli',
+ command: 'opencode', gatewayBacked: 'nvidia-nim', models: NVIDIA_CATALOG,
+ },
+ 'opencode-nvidia-nim-tui': {
+ id: 'opencode-nvidia-nim-tui', name: 'NVIDIA NIM via OpenCode (TUI)', type: 'tui',
+ command: 'opencode', gatewayBacked: 'nvidia-nim', models: NVIDIA_CATALOG,
+ },
+ },
+});
+
+describe('provider model access', () => {
+ let providerService;
+ const providersPath = () => join(TEST_DATA_DIR, 'providers.json');
+ const seed = (data) => writeFile(providersPath(), JSON.stringify(data));
+ const stored = async () => JSON.parse(await readFile(providersPath(), 'utf8')).providers;
+
+ beforeEach(async () => {
+ TEST_DATA_DIR = await mkdtemp(join(tmpdir(), 'portos-model-access-'));
+ providerService = createProviderService({ dataDir: TEST_DATA_DIR, providersFile: 'providers.json' });
+ });
+
+ afterEach(async () => {
+ if (TEST_DATA_DIR) await rm(TEST_DATA_DIR, { recursive: true, force: true });
+ });
+
+ it('one gateway policy scopes the API record and both OpenCode wrappers', async () => {
+ // The user's ask: NVIDIA's API, CLI and TUI options all show the entitled
+ // subset. The wrappers store no policy of their own, exactly as they store
+ // no API key — the gateway record owns both.
+ await seed(nvidiaInstall({ mode: 'allow', patterns: ['meta/*'] }));
+
+ const { providers } = await providerService.getAllProviders();
+ for (const id of ['nvidia-nim', 'opencode-nvidia-nim', 'opencode-nvidia-nim-tui']) {
+ const scoped = applyModelAccess(providers.find(p => p.id === id));
+ expect(scoped.models, id).toEqual(['meta/llama-3.1-8b-instruct']);
+ expect(scoped.modelCatalog, id).toEqual(NVIDIA_CATALOG);
+ }
+ expect(providers.find(p => p.id === 'opencode-nvidia-nim').modelAccessSource).toBe('nvidia-nim');
+ expect(providers.find(p => p.id === 'nvidia-nim').modelAccessSource).toBe('own');
+ });
+
+ it('a wrapper with its own policy is not overridden by the gateway', async () => {
+ const install = nvidiaInstall({ mode: 'allow', patterns: ['meta/*'] });
+ install.providers['opencode-nvidia-nim'].modelAccess = { mode: 'deny', patterns: ['meta/*'] };
+ await seed(install);
+
+ const wrapper = await providerService.getProviderById('opencode-nvidia-nim');
+ expect(wrapper.modelAccessSource).toBe('own');
+ expect(applyModelAccess(wrapper).models).toEqual(['nvidia/nemotron-4-340b-instruct', 'moonshotai/kimi-k2.5']);
+ });
+
+ it('the resolved policy never becomes the wrapper\'s own stored one', async () => {
+ // A client echoing a GET back on a PUT must not pin the inherited value:
+ // `modelAccessEffective` is outside `providerSchema`, so the round-trip
+ // strips it and a later edit to the gateway still reaches the wrapper.
+ await seed(nvidiaInstall({ mode: 'allow', patterns: ['meta/*'] }));
+ const wrapper = await providerService.getProviderById('opencode-nvidia-nim');
+ await providerService.updateProvider('opencode-nvidia-nim', { name: wrapper.name });
+ expect((await stored())['opencode-nvidia-nim'].modelAccess).toBeUndefined();
+
+ await providerService.updateProvider('nvidia-nim', { modelAccess: { mode: 'allow', patterns: ['moonshotai/*'] } });
+ const rescoped = applyModelAccess(await providerService.getProviderById('opencode-nvidia-nim'));
+ expect(rescoped.models).toEqual(['moonshotai/kimi-k2.5']);
+ });
+
+ it('keeps the api key attached to a scoped gateway wrapper', async () => {
+ // The key rides as a NON-enumerable property, so the model-access stamp has
+ // to compose underneath it — a spread on the other side drops it silently
+ // and every wrapper run loses its credential.
+ await seed(nvidiaInstall({ mode: 'allow', patterns: ['meta/*'] }));
+ expect((await providerService.getProviderById('opencode-nvidia-nim')).apiKey).toBe('nvapi-test');
+ });
+
+ it('a refresh re-learns the full catalog rather than the scoped view', async () => {
+ // The policy is applied on the way out, never at write time, so the stored
+ // record keeps the real catalog and clearing the policy restores it with no
+ // re-probe.
+ await seed(nvidiaInstall({ mode: 'allow', patterns: ['meta/*'] }));
+ await providerService.updateProvider('nvidia-nim', { models: [...NVIDIA_CATALOG, 'openai/gpt-oss-120b'] });
+ expect((await stored())['nvidia-nim'].models).toHaveLength(4);
+
+ await providerService.updateProvider('nvidia-nim', { modelAccess: null });
+ expect((await stored())['nvidia-nim'].modelAccess).toBeUndefined();
+ expect(applyModelAccess(await providerService.getProviderById('nvidia-nim')).models).toHaveLength(4);
+ });
+
+ it('stores a normalized policy and drops one that constrains nothing', async () => {
+ await seed(nvidiaInstall());
+ await providerService.updateProvider('nvidia-nim', { modelAccess: { mode: 'gold-plan', patterns: [' meta/* ', 'meta/*'] } });
+ // An unknown mode degrades to the unconstraining one rather than to an
+ // arbitrary constraining one.
+ expect((await stored())['nvidia-nim'].modelAccess).toEqual({ mode: 'all', patterns: ['meta/*'] });
+
+ await providerService.updateProvider('nvidia-nim', { modelAccess: { mode: 'all', patterns: [] } });
+ // A record reset to "no policy" must read exactly like one that never had
+ // one, not carry an inert object.
+ expect((await stored())['nvidia-nim']).not.toHaveProperty('modelAccess');
+ });
+
+ it('a create persists a policy only when it says something', async () => {
+ await providerService.createProvider({ name: 'Plain', type: 'api', endpoint: 'http://localhost:1234/v1' });
+ expect((await stored()).plain).not.toHaveProperty('modelAccess');
+
+ await providerService.createProvider({
+ name: 'Scoped', type: 'api', endpoint: 'http://localhost:1234/v1',
+ modelAccess: { mode: 'allow', patterns: ['meta/*'] },
+ });
+ expect((await stored()).scoped.modelAccess).toEqual({ mode: 'allow', patterns: ['meta/*'] });
+ });
+
+ it('fans the policy across a CLI/TUI pair so both modes offer one catalog', async () => {
+ await seed({ activeProvider: 'example', providers: {
+ example: { id: 'example', name: 'Example', type: 'cli', command: 'example', models: NVIDIA_CATALOG },
+ 'example-tui': { id: 'example-tui', name: 'Example TUI', type: 'tui', command: 'example', models: NVIDIA_CATALOG },
+ } });
+ await providerService.updateProvider('example', { modelAccess: { mode: 'allow', patterns: ['meta/*'] } });
+ expect((await stored())['example-tui'].modelAccess).toEqual({ mode: 'allow', patterns: ['meta/*'] });
+ });
+});
diff --git a/server/lib/aiToolkit/routes/providers.js b/server/lib/aiToolkit/routes/providers.js
index fdd17588bb..ff15f3447b 100644
--- a/server/lib/aiToolkit/routes/providers.js
+++ b/server/lib/aiToolkit/routes/providers.js
@@ -2,6 +2,14 @@ import { Router } from 'express';
import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';
import { providerSchema, providerActiveSchema, validate } from '../validation.js';
import { withRefreshCapability, withRefreshCapabilityList } from '../internal/modelFetchers.js';
+import { applyModelAccess, applyModelAccessList } from '../internal/modelAccess.js';
+
+// Model-access scoping is the same kind of on-the-way-out derivation as
+// `canRefreshModels`: the stored catalog is what the upstream advertises, and
+// the policy says which of it this install may actually run (internal/modelAccess.js).
+// Narrowing at the route rather than in the service keeps `providers.json` — and
+// every execution path that reads a record directly — holding the real catalog,
+// so clearing the policy restores the full list with no re-probe.
// `canRefreshModels` is DERIVED ON READ and decorated HERE, at the route —
// never inside `getAllProviders()`. Computing it in the service would put it on
@@ -23,12 +31,12 @@ export function createProvidersRoutes(providerService, options = {}) {
router.get('/', asyncHandler(async (req, res) => {
const data = await providerService.getAllProviders();
- res.json({ ...data, providers: withRefreshCapabilityList(data.providers) });
+ res.json({ ...data, providers: applyModelAccessList(withRefreshCapabilityList(data.providers)) });
}));
router.get('/active', asyncHandler(async (req, res) => {
const provider = await providerService.getActiveProvider();
- res.json(withRefreshCapability(provider));
+ res.json(applyModelAccess(withRefreshCapability(provider)));
}));
router.put('/active', asyncHandler(async (req, res) => {
@@ -44,7 +52,7 @@ export function createProvidersRoutes(providerService, options = {}) {
throw new ServerError('Provider not found', { status: 404 });
}
- res.json(withRefreshCapability(provider));
+ res.json(applyModelAccess(withRefreshCapability(provider)));
}));
router.get('/samples', asyncHandler(async (req, res) => {
@@ -52,7 +60,7 @@ export function createProvidersRoutes(providerService, options = {}) {
// Samples are provider-shaped and the flag is derived purely from that
// shape, so decorate them too — a sample's answer is what the provider it
// becomes will report. PortOS's shadowing `/samples` handler does the same.
- res.json({ providers: withRefreshCapabilityList(providers) });
+ res.json({ providers: applyModelAccessList(withRefreshCapabilityList(providers)) });
}));
router.get('/:id', asyncHandler(async (req, res) => {
@@ -62,7 +70,7 @@ export function createProvidersRoutes(providerService, options = {}) {
throw new ServerError('Provider not found', { status: 404 });
}
- res.json(withRefreshCapability(provider));
+ res.json(applyModelAccess(withRefreshCapability(provider)));
}));
router.post('/', asyncHandler(async (req, res) => {
@@ -72,7 +80,7 @@ export function createProvidersRoutes(providerService, options = {}) {
}
const provider = await providerService.createProvider(result.data);
- res.status(201).json(withRefreshCapability(provider));
+ res.status(201).json(applyModelAccess(withRefreshCapability(provider)));
}));
router.put('/:id', asyncHandler(async (req, res) => {
@@ -89,7 +97,7 @@ export function createProvidersRoutes(providerService, options = {}) {
throw new ServerError('Provider not found', { status: 404 });
}
- res.json(withRefreshCapability(provider));
+ res.json(applyModelAccess(withRefreshCapability(provider)));
}));
router.delete('/:id', asyncHandler(async (req, res) => {
@@ -120,7 +128,7 @@ export function createProvidersRoutes(providerService, options = {}) {
throw new ServerError('Provider not found', { status: 404 });
}
- res.json(withRefreshCapability(provider));
+ res.json(applyModelAccess(withRefreshCapability(provider)));
}));
return router;
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 114c83105d..8d11ef7583 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { MAX_MODEL_ACCESS_PATTERNS, MAX_MODEL_ACCESS_PATTERN_LENGTH, MODEL_ACCESS_MODES } from './internal/modelAccess.js';
import { basename, extname } from 'path';
import { MAX_TIMEOUT, MIN_TIMEOUT } from './constants.js';
@@ -127,6 +128,19 @@ export const providerSchema = z.object({
// what a person can type, this one has to accept whatever a vendor declares,
// and rejecting a 10M-window model would 400 the whole provider write.
modelContextWindows: z.record(z.number().int().min(512).max(33554432)).optional(),
+ // Which of the provider's advertised catalog this install is entitled to
+ // run — a plan/tier scope the upstream `/models` response does not declare
+ // (internal/modelAccess.js). Applied on the way OUT to model pickers; the
+ // stored `models` catalog is never narrowed by it. Nullable so the editor can
+ // clear a policy back to "none" (absent means "unchanged" on a PATCH).
+ modelAccess: z.object({
+ mode: z.enum(MODEL_ACCESS_MODES),
+ // An EMPTY list is valid and means "no constraint yet" — see the sentinel
+ // note in internal/modelAccess.js. Rejecting it here would make the editor
+ // unable to save the mode before the list is typed.
+ patterns: z.array(z.string().trim().min(1).max(MAX_MODEL_ACCESS_PATTERN_LENGTH))
+ .max(MAX_MODEL_ACCESS_PATTERNS).optional(),
+ }).strict().nullable().optional(),
timeout: z.number().int().min(MIN_TIMEOUT).max(MAX_TIMEOUT).optional(),
enabled: z.boolean().optional(),
// A CLI/TUI provider that can ALSO serve plain text through a non-HTTP
diff --git a/server/routes/modelComparison.js b/server/routes/modelComparison.js
index b0379ef10f..6f629fe007 100644
--- a/server/routes/modelComparison.js
+++ b/server/routes/modelComparison.js
@@ -6,6 +6,7 @@ import { hasArtificialAnalysisKey, syncArtificialAnalysisCatalog } from '../serv
import { canRefreshModels } from '../lib/aiToolkit/internal/modelFetchers.js';
import { effortLevelsForProvider, filterSelectableModels } from '../lib/providerModels.js';
import { catalogSlugForProviderModel } from '../lib/comparisonModelScope.js';
+import { applyModelAccess } from '../lib/aiToolkit/internal/modelAccess.js';
// The endpoint id plus the benchmark-index name it normalizes to. Both travel,
// because the page needs them for different things: the executable id labels
@@ -23,7 +24,12 @@ export function createModelComparisonRoutes(providerService) {
const [catalog, { providers }, artificialAnalysisKeyConfigured] = await Promise.all([
getModelComparison(), providerService.getAllProviders(), hasArtificialAnalysisKey(),
]);
- const inventory = providers.filter(p => p.enabled !== false).map(p => ({
+ // Scoped by the same model-access policy the provider pickers apply
+ // (aiToolkit/internal/modelAccess.js), so the chart's default pills and its
+ // coverage list describe the models this install can actually dispatch —
+ // not a vendor's whole advertised catalog. Without this the chart would
+ // plot, and offer to research, models an unentitled account cannot run.
+ const inventory = providers.filter(p => p.enabled !== false).map(applyModelAccess).map(p => ({
id: p.id, name: p.name, type: p.type, canDiscover: canRefreshModels(p),
models: filterSelectableModels(p.models).filter(m => typeof m === 'string' && m).map(model => inventoryModel(p, model)),
}));
@@ -44,8 +50,11 @@ export function createModelComparisonRoutes(providerService) {
if (!provider || !canRefreshModels(provider)) throw new ServerError('Provider is unavailable for model discovery', { status: 400 });
const catalog = await providerService.fetchProviderModelCatalog(provider.id);
if (!catalog) throw new ServerError('Provider model discovery returned no catalog', { status: 502 });
- const discovered = { ...provider, models: catalog.models };
- res.json({ providerId: provider.id, models: filterSelectableModels(catalog.models).map(model => inventoryModel(discovered, model)) });
+ // A freshly probed catalog is scoped the same way a stored one is: the
+ // policy describes the ACCOUNT, so it applies to whatever the upstream just
+ // advertised, not only to what happens to be on the record.
+ const discovered = applyModelAccess({ ...provider, models: catalog.models });
+ res.json({ providerId: provider.id, models: filterSelectableModels(discovered.models).map(model => inventoryModel(discovered, model)) });
}));
router.post('/import', asyncHandler(async (req, res) => {
res.json(await importModelComparison(validateRequest(modelComparisonImportSchema, req.body)));
diff --git a/server/routes/modelComparison.test.js b/server/routes/modelComparison.test.js
index 690650d1fe..5b51dff0bd 100644
--- a/server/routes/modelComparison.test.js
+++ b/server/routes/modelComparison.test.js
@@ -162,3 +162,28 @@ it('rejects sync-aa when no API key is provided and syncs successfully when mock
spy.mockRestore();
}
});
+
+it('scopes the chart inventory — and a fresh discovery — to the provider model-access policy', async () => {
+ // The chart defaults its pills to "models your providers can dispatch", so a
+ // provider scoped to a free tier must narrow the chart too. Otherwise the page
+ // plots, and offers to research, models an unentitled account cannot run.
+ providerService.getAllProviders.mockResolvedValue({ providers: [{
+ id: 'nvidia-nim', name: 'NVIDIA NIM', type: 'api', enabled: true,
+ models: ['meta/llama-3.3-70b-instruct', 'nvidia/nemotron-4-340b-instruct'],
+ modelAccess: { mode: 'allow', patterns: ['meta/*'] },
+ }] });
+ providerService.fetchProviderModelCatalog.mockResolvedValue({
+ models: ['meta/llama-3.1-8b-instruct', 'nvidia/nemotron-4-340b-instruct'], contextWindows: {},
+ });
+
+ const result = await request(app).get('/comparison');
+ expect(result.body.inventory[0].models.map(m => m.model)).toEqual(['meta/llama-3.3-70b-instruct']);
+ // The scoped inventory is what `availableModels` is read back off, so the
+ // chart's default selection cannot reach past the policy either.
+ expect(result.body.availableModels).not.toContain('nemotron-4-340b-instruct');
+
+ // A freshly probed catalog is scoped the same way: the policy describes the
+ // ACCOUNT, not just whatever happens to be on the stored record.
+ const discovery = await request(app).post('/comparison/discover').send({ providerId: 'nvidia-nim' });
+ expect(discovery.body.models.map(m => m.model)).toEqual(['meta/llama-3.1-8b-instruct']);
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 56233ddd7b..3970dc9669 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -21,6 +21,7 @@ import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/v
import { auditModelPins, clearModelPin } from '../services/modelPinAudit.js';
import { providerCreateSchema, providerSchema, providerActiveSchema, validate } from '../lib/aiToolkit/validation.js';
import { canRefreshModels, withRefreshCapability } from '../lib/aiToolkit/internal/modelFetchers.js';
+import { applyModelAccess } from '../lib/aiToolkit/internal/modelAccess.js';
import { ALLOWED_COMMANDS } from '../cos-runner/allowedCommands.js';
import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
@@ -175,8 +176,13 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =
// `publicReviewEnforcedPostures` is the subset backed by a vendor sandbox
// recipe. The two booleans are derived from it and kept for existing consumers.
const publicReviewPostures = publicReviewPosturesForProvider(provider);
+ // Narrow `models` to the install's declared entitlement, LAST, so every
+ // derivation above still reads the provider's full advertised catalog. The
+ // untouched list rides along as `modelCatalog` — the editor seeds its
+ // "Available Models" box from it, so an ordinary Save on a scoped provider
+ // cannot persist the narrowed list over the real one.
return sanitizeProvider({
- ...decorated,
+ ...applyModelAccess(decorated),
// The UNION of the two refresh paths, because the button asks only
// whether SOME path can serve this record. Which one actually serves it is
// decided in `POST /:id/refresh-models`, and the two must stay in step or
@@ -189,6 +195,31 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =
});
};
+/**
+ * Carry a gateway-backed wrapper's RESOLVED model-access policy from the read
+ * that preceded a write onto the record the write handed back.
+ *
+ * A write returns the PERSISTED record, and a wrapper stores no policy of its
+ * own — the gateway sibling owns it, and `withGatewayModelAccess` resolves it on
+ * read. Presenting the raw write result would answer that one request with the
+ * unscoped catalog and the next GET with the scoped one, which reads as a bug.
+ * The route already holds a resolved read (it needs it for the 404 and for
+ * secret preservation), so this is a field copy rather than a second load.
+ *
+ * Deliberately not a re-read: several suites drive these routes with a provider
+ * service double whose `getProviderById` answers a different fixture than the
+ * write does, and a write path is the wrong place to depend on a second lookup.
+ *
+ * Safe against a write that CHANGED the policy: `applyModelAccess` reads the
+ * record's own `modelAccess` first and only falls back to the resolved field,
+ * so a freshly written own policy outranks the inherited one copied here.
+ */
+const withResolvedModelAccess = (provider, resolved) => (
+ provider && resolved?.modelAccessEffective
+ ? { ...provider, modelAccessEffective: resolved.modelAccessEffective, modelAccessSource: resolved.modelAccessSource }
+ : provider
+);
+
/**
* Create PortOS-specific provider routes
* Extends AI Toolkit routes with vision testing endpoints
@@ -914,7 +945,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
}
const provider = await providerService.updateProvider(req.params.id, updates);
- res.json(presentProvider(provider, await detectSystemCapabilities()));
+ res.json(presentProvider(withResolvedModelAccess(provider, existing), await detectSystemCapabilities()));
}));
// POST /:id/refresh-models — intercept the toolkit response so the refreshed
@@ -944,7 +975,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
provider = await providerService.refreshProviderModels(req.params.id);
}
if (!provider) throw new ServerError('Provider not found', { status: 404 });
- res.json(presentProvider(provider, await detectSystemCapabilities()));
+ res.json(presentProvider(withResolvedModelAccess(provider, stored), await detectSystemCapabilities()));
}));
/**
diff --git a/server/routes/providers.modelAccess.test.js b/server/routes/providers.modelAccess.test.js
new file mode 100644
index 0000000000..ec0bbc981a
--- /dev/null
+++ b/server/routes/providers.modelAccess.test.js
@@ -0,0 +1,127 @@
+import { describe, it, expect, vi } from 'vitest';
+import express, { Router } from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { createPortOSProviderRoutes } from './providers.js';
+
+// The PortOS provider routes SHADOW the toolkit's own GET handlers, so the
+// toolkit's scoping never reaches the client on its own — `presentProvider` has
+// to apply it too. Everything downstream reads `provider.models` off this
+// payload (every `filterSelectableModels(provider.models)` picker in the client,
+// the CoS model allowlists, the comparison chart), which is what makes one
+// narrowing here cover the whole app.
+
+const CATALOG = ['meta/llama-3.3-70b-instruct', 'nvidia/nemotron-4-340b-instruct', 'moonshotai/kimi-k2.5'];
+
+const NVIDIA = {
+ id: 'nvidia-nim',
+ name: 'NVIDIA NIM',
+ type: 'api',
+ endpoint: 'https://integrate.api.nvidia.com/v1',
+ apiKey: 'nvapi-secret',
+ envVars: {},
+ models: CATALOG,
+ defaultModel: 'moonshotai/kimi-k2.5',
+ modelAccess: { mode: 'allow', patterns: ['meta/*'] },
+};
+
+function appWith(providerService) {
+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };
+ const app = express();
+ app.use(express.json());
+ app.use('/api/providers', createPortOSProviderRoutes(toolkit));
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('provider payloads carry the model-access-scoped catalog', () => {
+ it('GET / narrows models, keeps the full catalog, and still strips the key', async () => {
+ const app = appWith({
+ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: 'nvidia-nim', providers: [NVIDIA] }),
+ });
+
+ const res = await request(app).get('/api/providers');
+ expect(res.status).toBe(200);
+ const [provider] = res.body.providers;
+ // `defaultModel` is pinned to a model the policy does not match and stays
+ // visible — a picker whose stored value is missing from its options renders
+ // blank and re-points the provider on the next save.
+ expect(provider.models).toEqual(['meta/llama-3.3-70b-instruct', 'moonshotai/kimi-k2.5']);
+ expect(provider.modelCatalog).toEqual(CATALOG);
+ expect(provider.modelAccessHiddenCount).toBe(1);
+ // Scoping runs at the END of the presentation chain, so redaction is
+ // unaffected by it.
+ expect(provider.apiKey).toBeUndefined();
+ expect(provider.hasApiKey).toBe(true);
+ });
+
+ it('GET /:id and GET /active scope the same way', async () => {
+ const app = appWith({
+ getProviderById: vi.fn().mockResolvedValue(NVIDIA),
+ getActiveProvider: vi.fn().mockResolvedValue(NVIDIA),
+ });
+
+ for (const path of ['/api/providers/nvidia-nim', '/api/providers/active']) {
+ const res = await request(app).get(path);
+ expect(res.status, path).toBe(200);
+ expect(res.body.models, path).toEqual(['meta/llama-3.3-70b-instruct', 'moonshotai/kimi-k2.5']);
+ }
+ });
+
+ it('a provider with no policy serializes exactly as before', async () => {
+ // Every install that has not configured this must see no change at all —
+ // no redundant `modelCatalog` copy on every provider in the list.
+ const plain = { ...NVIDIA, modelAccess: undefined };
+ const app = appWith({ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: 'nvidia-nim', providers: [plain] }) });
+
+ const [provider] = (await request(app).get('/api/providers')).body.providers;
+ expect(provider.models).toEqual(CATALOG);
+ expect(provider).not.toHaveProperty('modelCatalog');
+ expect(provider).not.toHaveProperty('modelAccessHiddenCount');
+ });
+});
+
+describe('a write response is scoped the same way a read is', () => {
+ // A write returns the persisted record, and a gateway-backed wrapper stores no
+ // policy of its own. Without carrying the resolution forward, saving or
+ // refreshing a wrapper answers with the unscoped catalog and the next page load
+ // with the scoped one — which reads as a bug.
+ const WRAPPER = {
+ id: 'opencode-nvidia-nim', name: 'NVIDIA NIM via OpenCode', type: 'cli',
+ command: 'opencode', gatewayBacked: 'nvidia-nim', envVars: {}, models: CATALOG,
+ };
+ const resolved = { ...WRAPPER, modelAccessEffective: { mode: 'allow', patterns: ['meta/*'] }, modelAccessSource: 'nvidia-nim' };
+
+ it('PUT /:id returns the inherited scope', async () => {
+ const app = appWith({
+ getProviderById: vi.fn().mockResolvedValue(resolved),
+ updateProvider: vi.fn().mockResolvedValue({ ...WRAPPER, name: 'Renamed' }),
+ });
+ const res = await request(app).put('/api/providers/opencode-nvidia-nim').send({ name: 'Renamed' });
+ expect(res.status).toBe(200);
+ expect(res.body.models).toEqual(['meta/llama-3.3-70b-instruct']);
+ expect(res.body.modelAccessSource).toBe('nvidia-nim');
+ });
+
+ it('a policy the write just SET outranks the inherited one carried forward', async () => {
+ const app = appWith({
+ getProviderById: vi.fn().mockResolvedValue(resolved),
+ updateProvider: vi.fn().mockResolvedValue({ ...WRAPPER, modelAccess: { mode: 'allow', patterns: ['moonshotai/*'] } }),
+ });
+ const res = await request(app).put('/api/providers/opencode-nvidia-nim')
+ .send({ modelAccess: { mode: 'allow', patterns: ['moonshotai/*'] } });
+ expect(res.body.models).toEqual(['moonshotai/kimi-k2.5']);
+ });
+
+ it('POST /:id/refresh-models returns the inherited scope over the fresh catalog', async () => {
+ const app = appWith({
+ getProviderById: vi.fn().mockResolvedValue(resolved),
+ refreshProviderModels: vi.fn().mockResolvedValue({ ...WRAPPER, models: [...CATALOG, 'meta/llama-4-scout'] }),
+ });
+ const res = await request(app).post('/api/providers/opencode-nvidia-nim/refresh-models');
+ expect(res.status).toBe(200);
+ expect(res.body.models).toEqual(['meta/llama-3.3-70b-instruct', 'meta/llama-4-scout']);
+ // The full probe result is still what landed on disk and what the editor sees.
+ expect(res.body.modelCatalog).toEqual([...CATALOG, 'meta/llama-4-scout']);
+ });
+});