Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
name the selecting-vs-executing split instead of scoping at each call site
[._.]/ Adam Eivy89d9001b4f2d
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsxindex cffba442a8..c1ef16685a 100644--- a/client/src/components/providers/ProviderForm.jsx+++ b/client/src/components/providers/ProviderForm.jsx@@ -1,5 +1,5 @@import { hardwareUnavailableReason } from '../../utils/systemCapabilities';-import { useState } from 'react';+import { useMemo, useState } from 'react';import { AlertTriangle, Braces, Cpu, Plug, SlidersHorizontal } from 'lucide-react';import toast from '../ui/Toast';import * as api from '../../services/api';@@ -20,7 +20,7 @@ import useDrawerTab from '../../hooks/useDrawerTab';import { FormField } from '../ui/FormField';import { GatewayKeyHint } from './ProviderNotices';import ProviderModelAccess from './ProviderModelAccess';-import { normalizeModelAccess, providerModelCatalog } from '../../utils/providerModelAccess';+import { CONFIGURED_MODEL_KEYS, configuredModelsOf, 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@@ -150,6 +150,15 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose// models (and internal sentinels) so an embedding can't be chosen as a model// that runs prompts, consistent with the fallback picker below.const mergedModels = mergeModelLists(formData.models, liveModelsFor(formData));+ // The tier models the access policy must never scope out. Memoized on the six+ // fields themselves rather than on `formData`, so typing in any other field+ // cannot re-scope the whole catalog in the policy editor's preview.+ const modelAccessKeeps = useMemo(+ () => configuredModelsOf(formData),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [formData.defaultModel, formData.lightModel, formData.mediumModel,+ formData.heavyModel, formData.ultraModel, formData.fallbackModel],+ );// The server publishes compatibility for both the provider runtime and any// explicitly annotated model. Unknown probe results stay in the list; only a// definitive mismatch is hidden.@@ -378,7 +387,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose// still spread into `data` and silently persisted on an unrelated edit.// Clear any embedding value that slipped through so the saved record matches// what the picker allows.- for (const field of ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel', 'ultraModel', 'fallbackModel']) {+ for (const field of CONFIGURED_MODEL_KEYS) {if (isEmbeddingModel(data[field])) data[field] = '';}// An explicit `null` rather than `undefined` when the policy says nothing:@@ -928,7 +937,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose<ProviderModelAccesscatalog={formData.models || []}value={formData.modelAccess}- provider={{ ...provider, ...formData, id: provider?.id }}+ configuredModels={modelAccessKeeps}onChange={(modelAccess) => setFormData(prev => ({ ...prev, modelAccess }))}/>diff --git a/client/src/components/providers/ProviderModelAccess.jsx b/client/src/components/providers/ProviderModelAccess.jsxindex c79a2943dd..3b2323ccd1 100644--- a/client/src/components/providers/ProviderModelAccess.jsx+++ b/client/src/components/providers/ProviderModelAccess.jsx@@ -6,6 +6,7 @@ import {MODEL_ACCESS_MODES,MODEL_ACCESS_MODE_LABELS,MAX_MODEL_ACCESS_PATTERNS,+ NO_MODEL_ACCESS,modelMatchesAccessPatterns,previewModelAccess,} from '../../utils/providerModelAccess';@@ -26,33 +27,41 @@ import {* 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.+ *+ * `configuredModels` is passed rather than a provider record so the memos below+ * can key on values that actually change; a record rebuilt each render would+ * make every keystroke in any other form field re-scope the whole catalog.*/-export default function ProviderModelAccess({ catalog, value, onChange, provider }) {+export default function ProviderModelAccess({ catalog, value, onChange, configuredModels }) {const [patternDraft, setPatternDraft] = useState(null);- const policy = value || { mode: 'all', patterns: [] };- const patterns = policy.patterns || [];+ const policy = value || NO_MODEL_ACCESS;+ const patterns = policy.patterns || NO_MODEL_ACCESS.patterns;const preview = useMemo(- () => previewModelAccess(catalog, policy, provider),- [catalog, policy, provider],+ () => previewModelAccess(catalog, policy, configuredModels),+ [catalog, policy, configuredModels],);+ // One pass over the catalog for the row markers, so a row is O(1) rather than+ // two linear `includes` scans plus a glob sweep each. At the 500-pattern cap+ // the per-row form was ~500k comparisons on every keystroke in the textarea.+ const { listed, globCovered } = useMemo(() => {+ const selected = new Set(patterns);+ return {+ listed: selected,+ globCovered: new Set(catalog.filter(+ model => !selected.has(model) && modelMatchesAccessPatterns(model, patterns),+ )),+ };+ }, [catalog, patterns]);+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],+ listed.has(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">@@ -78,7 +87,7 @@ export default function ProviderModelAccess({ catalog, value, onChange, provider<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).`}+ : `Showing ${formatCount(preview.visibleCount)} of ${formatCount(preview.total)} models (${formatCount(preview.hidden)} hidden).`}</p><FormField label="Patterns">@@ -121,14 +130,18 @@ export default function ProviderModelAccess({ catalog, value, onChange, provider<buttonkey={model}type="button"+ // The row IS a checkbox; without this a screen reader hears+ // "<model id>, button" with no indication of whether it is in+ // the list, which is the whole state this control carries.+ aria-pressed={listed.has(model)}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)+ {listed.has(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) && (+ {globCovered.has(model) && (<Check className="w-3.5 h-3.5 shrink-0 text-port-accent ml-auto" aria-label="matched by a pattern" />)}</button>diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex f2b436e093..ff4ef033ea 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -62,7 +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`. |+| `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 the browser consumes from the pure leaf `server/lib/aiToolkit/internal/modelAccess.js` — `MODEL_ACCESS_MODES`, `MAX_MODEL_ACCESS_PATTERNS`, `CONFIGURED_MODEL_KEYS`, `normalizeModelAccess`, `modelMatchesAccessPatterns` — 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, configuredModels)` → `{ total, visibleCount, hidden, inert }`, `configuredModelsOf`, `NO_MODEL_ACCESS` and `MODEL_ACCESS_MODE_LABELS`. `applyModelAccess` is deliberately NOT re-exported: a client payload is already scoped, and re-scoping would overwrite `modelCatalog` with the narrowed list. || `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/providerModelAccess.js b/client/src/utils/providerModelAccess.jsindex 5a4fd6324b..99bcf61ecb 100644--- a/client/src/utils/providerModelAccess.js+++ b/client/src/utils/providerModelAccess.js@@ -2,34 +2,36 @@* 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+ * Every rule comes 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.+ *+ * Only what the browser actually consumes is re-exported. `applyModelAccess`+ * in particular is deliberately NOT: a client payload has already been scoped,+ * and scoping it again would overwrite `modelCatalog` with the narrowed list —+ * the one mistake that turns this feature into data loss on the next save.*/+import {+ modelAccessConstrains,+ normalizeModelAccess,+ providerConfiguredModels,+ scopeModelsByAccess,+} from '../../../server/lib/aiToolkit/internal/modelAccess.js';+export {+ // The mode enum and pattern cap, so the editor's controls and the server's+ // zod schema cannot disagree about what is accepted.MODEL_ACCESS_MODES,MAX_MODEL_ACCESS_PATTERNS,- MAX_MODEL_ACCESS_PATTERN_LENGTH,+ // The tier fields a record NAMES — the editor sanitizes the same set.CONFIGURED_MODEL_KEYS,+ // What the form submits, and what the catalog list marks as glob-covered.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. */@@ -39,6 +41,9 @@ export const MODEL_ACCESS_MODE_LABELS = Object.freeze({deny: 'All models except those matching the list',});+/** The "no policy" shape, stable so a memo keyed on it can hit. */+export const NO_MODEL_ACCESS = Object.freeze({ mode: 'all', patterns: Object.freeze([]) });+/*** The FULL advertised catalog for a provider payload.*@@ -54,17 +59,18 @@ export const providerModelCatalog = (provider) =>/*** 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.+ * Takes the catalog and the configured model ids explicitly rather than reading+ * them off a provider record, so the caller can memoize on values that actually+ * change — the editor previews an UNSAVED policy against the full list, and a+ * provider object rebuilt every render would defeat any memo keyed on it.*/-export function previewModelAccess(catalog, policy, provider) {+export function previewModelAccess(catalog, policy, configuredModels = []) {const models = (catalog || []).filter(model => typeof model === 'string' && model);const normalized = normalizeModelAccess(policy);- const visible = scopeModelsByAccess(models, normalized, { keep: providerConfiguredModels(provider) });+ const visible = scopeModelsByAccess(models, normalized, { keep: configuredModels });return {total: models.length,- visible,+ visibleCount: visible.length,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@@ -73,3 +79,6 @@ export function previewModelAccess(catalog, policy, provider) {inert: Boolean(normalized) && normalized.mode !== 'all' && !modelAccessConstrains(normalized),};}++/** The tier models a form/provider shape pins, for {@link previewModelAccess}. */+export const configuredModelsOf = providerConfiguredModels;diff --git a/docs/MODEL_ACCESS.md b/docs/MODEL_ACCESS.mdindex a49a5eba3c..ac2abe0a5d 100644--- a/docs/MODEL_ACCESS.md+++ b/docs/MODEL_ACCESS.md@@ -21,9 +21,15 @@ PortOS cannot detect it. It is declared instead, per provider, in| `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.+the Settings > AI assignment page, the Backend Connections model menus, 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.++One provider is deliberately out of scope: the Codex ChatGPT-subscription+catalog (`GET /api/providers/codex/models`) asks the Codex app-server what the+signed-in account may actually run, so it already answers with the account's real+entitlement. A policy on a codex record does not narrow it further.## Patterns@@ -58,6 +64,10 @@ nvidia/llama-3.1-nemotron-70b-instruct # an exact pinwhen the policy would exclude it — a picker whose stored value is missing fromits options renders blank and re-points the provider on the next save. Thepolicy governs what can be chosen *next*, not what the record already says.+- **Execution, accounting and refresh are never scoped.** Quota burn, usage+ reconciliation, the runner and every harness catalog refresh read the+ unscoped list. The policy is about what a human may pick next, not about what+ already ran or what the upstream advertises.- **A half-finished policy hides nothing.** Selecting `allow` before typing anypattern means "not configured yet", not "hide everything", so model pickersstay populated while you work. The editor says so explicitly rather than@@ -82,6 +92,7 @@ program on one backend.| 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`) |+| The selecting-vs-executing seam | `server/services/providers.js` (`getSelectableProviders` / `listSelectableProviders`) || 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` |diff --git a/server/AGENTS.md b/server/AGENTS.mdindex 8121c193d5..bd5d9880ac 100644--- a/server/AGENTS.md+++ b/server/AGENTS.md@@ -6,6 +6,10 @@ These apply to Express/service/model code. Universal constraints (no try/catch o- **Schema parity when adding fields.** When you add a field to a sanitizer, `createXxx`, or a payload shape, update the corresponding Zod schema (`server/lib/aiToolkit/validation.js` for toolkit shapes, `server/lib/validation.js` for PortOS routes) in the same change. Wire validation into POST and PUT (PUT can use `schema.partial()`); the PortOS convention is *all* inputs validated — an exported-but-unwired sub-schema creates false confidence. For polymorphic stores like `PUT /api/settings` that accept any sub-object, validate the relevant slice with `schema.partial()` when its key is present in the request body (see `server/routes/settings.js` for the `backupConfigSchema.partial()` pattern). Tolerate UI sentinels (`endpoint: ''` for CLI providers) with `z.preprocess(v => v === '' ? undefined : v, …)`. When a service migrates legacy keys on read, the schema must still accept the legacy shape so older clients don't 400 before the migration runs.+## Offering models vs running them++- **A caller that OFFERS a model choice reads providers through `getSelectableProviders()` / `listSelectableProviders()`; a caller that EXECUTES, ACCOUNTS or WRITES reads `getAllProviders()` / `listProviders()`.** The scoped pair narrows each record's `models` to the install's declared entitlement — which of a vendor's advertised catalog this account can actually run, a thing no `/models` response reports (see `docs/MODEL_ACCESS.md` and `lib/aiToolkit/internal/modelAccess.js`). Picking the wrong one is silent both ways: a picker on the unscoped list offers models the account cannot run, and a *write* path on the scoped list persists a truncated catalog over the real one, which no refresh restores until the policy is cleared. Two methods rather than a flag, because the answer is a property of the caller's purpose and has to be visible at the call site. Route payloads shaped by `presentProvider` are already scoped; anything reading the service directly is not.+## Write serialization and throughput- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.diff --git a/server/lib/aiToolkit/internal/modelAccess.js b/server/lib/aiToolkit/internal/modelAccess.jsindex b27e21afbb..5c47065e17 100644--- a/server/lib/aiToolkit/internal/modelAccess.js+++ b/server/lib/aiToolkit/internal/modelAccess.js@@ -133,11 +133,28 @@ function globMatches(text, pattern) {return p === pattern.length;}+/**+ * The pattern list folded to the case the matcher compares in.+ *+ * Hoisted out of {@link modelMatchesAccessPatterns} so a scope over a catalog+ * lowercases the list once rather than once per model: the per-model form was+ * M×P transient strings, which at the 500-pattern ceiling is 50,000 allocations+ * per provider per read — and the same module runs in the browser on every+ * keystroke in the policy editor.+ */+const loweredPatterns = (patterns) =>+ (patterns || []).map(pattern => String(pattern).toLowerCase());+/** True when `modelId` matches any of `patterns`. */export function modelMatchesAccessPatterns(modelId, patterns) {+ return matchesLowered(modelId, loweredPatterns(patterns));+}++/** {@link modelMatchesAccessPatterns} over an already-lowered pattern list. */+function matchesLowered(modelId, lowered) {if (typeof modelId !== 'string' || !modelId) return false;const id = modelId.toLowerCase();- return (patterns || []).some(pattern => globMatches(id, String(pattern).toLowerCase()));+ return lowered.some(pattern => globMatches(id, pattern));}/**@@ -157,10 +174,11 @@ 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));+ const lowered = loweredPatterns(policy.patterns);+ const allow = policy.mode === 'allow';return catalog.filter(model => {if (kept.has(model)) return true;- const matched = modelMatchesAccessPatterns(model, policy.patterns);- return policy.mode === 'allow' ? matched : !matched;+ return matchesLowered(model, lowered) === allow;});}@@ -186,7 +204,10 @@ export const providerConfiguredModels = (provider) =>* field until someone needs it.*/export const effectiveModelAccess = (provider) =>- normalizeModelAccess(provider?.modelAccess) || normalizeModelAccess(provider?.modelAccessEffective);+ // The stamped field is normalized by construction (`withGatewayModelAccess`+ // only ever writes a `normalizeModelAccess` result), so it is taken as-is —+ // re-normalizing it allocated four arrays and a Set per provider per read.+ normalizeModelAccess(provider?.modelAccess) || provider?.modelAccessEffective || null;/*** The shape a provider takes on its way out to a reader that SELECTS models:diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex f2e211c137..2ab206880d 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -91,6 +91,16 @@ function withGatewayApiKey(provider, providers) {* 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.*/+/**+ * One provider as a READ sees it: the gateway's model-access policy resolved,+ * then the gateway's API key attached. In that order — the key rides as a+ * NON-enumerable property, so a spread after it would silently drop the+ * credential and every wrapper run would lose it.+ */+const readProvider = (provider, providers) => (provider+ ? withGatewayApiKey(withGatewayModelAccess(provider, providers), providers)+ : null);+function withGatewayModelAccess(provider, providers) {if (!provider || typeof provider !== 'object') return provider;const own = normalizeModelAccess(provider.modelAccess);@@ -696,6 +706,8 @@ export function createProviderService(config = {}) {throw new Error('Provider with this ID already exists');}+ const modelAccess = normalizeModelAccess(providerData.modelAccess);+const provider = {id,name: providerData.name,@@ -765,8 +777,7 @@ export function createProviderService(config = {}) {// (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) } : {}),+ ...(modelAccess ? { modelAccess } : {}),// Explicit opt-in to send the API key to an arbitrary (non-local,// non-allowlisted) endpoint — see endpointGuard.js. Only// persisted when true so existing keyless/local providers stay clean.@@ -811,15 +822,13 @@ export function createProviderService(config = {}) {async getProviderById(id) {const data = await loadProviders();- const provider = data.providers[id];- return provider ? withGatewayApiKey(withGatewayModelAccess(provider, data.providers), data.providers) : null;+ return readProvider(data.providers[id], data.providers);},async getActiveProvider() {const data = await loadProviders();if (!data.activeProvider) return null;- const provider = data.providers[data.activeProvider];- return provider ? withGatewayApiKey(withGatewayModelAccess(provider, data.providers), data.providers) : null;+ return readProvider(data.providers[data.activeProvider], data.providers);},async setActiveProvider(id) {@@ -921,7 +930,10 @@ export function createProviderService(config = {}) {// invariant `createProvider` keeps by only writing the key when named.// Applied to the fanned-out siblings too: a cleared sibling that kept a// stored `null` would no longer read as "never had one".- const dropClearedBootstrap = (record) => {+ // Fields whose CLEARED form has to be normalized away rather than stored:+ // a record that was reset must read exactly like one that never had the+ // field, or the next reader has to know two spellings of "none".+ const normalizeClearedFields = (record) => {if (record.credentialBootstrap === null) delete record.credentialBootstrap;// Same convention for the model-access policy: an explicit `null` is// "clear it", and a policy that normalizes to nothing (mode `all` with@@ -933,7 +945,7 @@ export function createProviderService(config = {}) {else delete record.modelAccess;}};- dropClearedBootstrap(provider);+ normalizeClearedFields(provider);// Grouped BEFORE the edit lands: every connection-identity value the// fan-out shares (endpoint, API key, env vars, bootstrap) is exactly what@@ -945,7 +957,7 @@ export function createProviderService(config = {}) {for (const sibling of group || []) {if (sibling.id === id) continue;Object.assign(sibling, sharedModeUpdates(updates, sibling));- dropClearedBootstrap(sibling);+ normalizeClearedFields(sibling);}await saveProviders(data);return provider;diff --git a/server/lib/aiToolkit/routes/providers.js b/server/lib/aiToolkit/routes/providers.jsindex ff15f3447b..6613369e2c 100644--- a/server/lib/aiToolkit/routes/providers.js+++ b/server/lib/aiToolkit/routes/providers.js@@ -28,15 +28,20 @@ export function createProvidersRoutes(providerService, options = {}) {// `{ error, code, timestamp, context? }` and route to errorMiddleware).// Standalone, the toolkit's own defaults serialize the same envelope.const { asyncHandler = defaultAsyncHandler, ServerError = ToolkitHttpError } = options;+ // ONE spelling of the on-the-way-out derivations, so the next one added does+ // not have to be threaded through every handler — and a handler that missed it+ // cannot ship a payload shaped differently from its neighbours.+ const present = (provider) => applyModelAccess(withRefreshCapability(provider));+ const presentList = (providers) => applyModelAccessList(withRefreshCapabilityList(providers));router.get('/', asyncHandler(async (req, res) => {const data = await providerService.getAllProviders();- res.json({ ...data, providers: applyModelAccessList(withRefreshCapabilityList(data.providers)) });+ res.json({ ...data, providers: presentList(data.providers) });}));router.get('/active', asyncHandler(async (req, res) => {const provider = await providerService.getActiveProvider();- res.json(applyModelAccess(withRefreshCapability(provider)));+ res.json(present(provider));}));router.put('/active', asyncHandler(async (req, res) => {@@ -52,7 +57,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(applyModelAccess(withRefreshCapability(provider)));+ res.json(present(provider));}));router.get('/samples', asyncHandler(async (req, res) => {@@ -60,7 +65,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: applyModelAccessList(withRefreshCapabilityList(providers)) });+ res.json({ providers: presentList(providers) });}));router.get('/:id', asyncHandler(async (req, res) => {@@ -70,7 +75,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(applyModelAccess(withRefreshCapability(provider)));+ res.json(present(provider));}));router.post('/', asyncHandler(async (req, res) => {@@ -80,7 +85,7 @@ export function createProvidersRoutes(providerService, options = {}) {}const provider = await providerService.createProvider(result.data);- res.status(201).json(applyModelAccess(withRefreshCapability(provider)));+ res.status(201).json(present(provider));}));router.put('/:id', asyncHandler(async (req, res) => {@@ -97,7 +102,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(applyModelAccess(withRefreshCapability(provider)));+ res.json(present(provider));}));router.delete('/:id', asyncHandler(async (req, res) => {@@ -128,7 +133,7 @@ export function createProvidersRoutes(providerService, options = {}) {throw new ServerError('Provider not found', { status: 404 });}- res.json(applyModelAccess(withRefreshCapability(provider)));+ res.json(present(provider));}));return router;diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 3970dc9669..e54d6864eb 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -21,7 +21,7 @@ import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/vimport { 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 { applyModelAccess, applyModelAccessList } 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';@@ -357,7 +357,12 @@ export function createPortOSProviderRoutes(aiToolkit) {*/router.get('/management/preview', asyncHandler(async (_req, res) => {const data = await providerService.getAllProviders();- res.set('Cache-Control', 'no-store').json(toManagementPreviewDto(buildProviderGraphPreview(data)));+ // Scoped like every other picker payload: the preview's connection catalogs+ // and binding model menus are what the Backend Connections page offers, so+ // an unscoped read here would contradict the model-access policy four+ // handlers below (docs/MODEL_ACCESS.md).+ const scoped = { ...data, providers: applyModelAccessList(data.providers) };+ res.set('Cache-Control', 'no-store').json(toManagementPreviewDto(buildProviderGraphPreview(scoped)));}));/**diff --git a/server/services/aiAssignments.js b/server/services/aiAssignments.jsindex 4ffb8d05f0..22af7fa041 100644--- a/server/services/aiAssignments.js+++ b/server/services/aiAssignments.js@@ -1,5 +1,5 @@import { getSettings, updateSettings } from './settings.js';-import { getAllProviders, getProviderById, isOllamaBackedProvider, setActiveProvider, updateProvider } from './providers.js';+import { getProviderById, getSelectableProviders, isOllamaBackedProvider, setActiveProvider, updateProvider } from './providers.js';import * as brainService from './brain.js';import * as universeService from './universeBuilder.js';import * as storyBuilderService from './storyBuilder.js';@@ -474,7 +474,10 @@ const addRecordEntries = async (entries) => {};export async function getAiAssignments() {- const providersData = await getAllProviders();+ // The assignment page is a PICKER, so it takes the entitlement-scoped list:+ // offering a model the account cannot run is the failure this whole payload+ // exists to prevent (docs/MODEL_ACCESS.md).+ const providersData = await getSelectableProviders();const entries = [];await addSettingsEntries(entries);await addRecordEntries(entries);diff --git a/server/services/aiAssignments.test.js b/server/services/aiAssignments.test.jsindex b6eb6a88e6..03ceb62db8 100644--- a/server/services/aiAssignments.test.js+++ b/server/services/aiAssignments.test.js@@ -13,7 +13,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';const mocks = vi.hoisted(() => ({getSettings: vi.fn(),updateSettings: vi.fn(),- getAllProviders: vi.fn(),+ getSelectableProviders: vi.fn(),getProviderById: vi.fn(),setActiveProvider: vi.fn(),updateProvider: vi.fn(),@@ -43,7 +43,7 @@ const mocks = vi.hoisted(() => ({vi.mock('./settings.js', () => ({ getSettings: mocks.getSettings, updateSettings: mocks.updateSettings }));vi.mock('./providers.js', async () => ({- getAllProviders: mocks.getAllProviders,+ getSelectableProviders: mocks.getSelectableProviders,getProviderById: mocks.getProviderById,setActiveProvider: mocks.setActiveProvider,updateProvider: mocks.updateProvider,@@ -76,7 +76,7 @@ const { getAiAssignments, updateAiAssignment } = await import('./aiAssignments.jbeforeEach(() => {vi.clearAllMocks();// Defaults that let getAiAssignments() (called after every write) resolve.- mocks.getAllProviders.mockResolvedValue({+ mocks.getSelectableProviders.mockResolvedValue({activeProvider: 'openai',providers: [{ id: 'openai', name: 'OpenAI', type: 'api', enabled: true, defaultModel: 'gpt-4', models: ['gpt-4', 'gpt-4o'], fallbackProvider: null },@@ -180,7 +180,7 @@ describe('getAiAssignments', () => {// A renamed Claude-Ollama TUI: neither its id nor its name says "ollama",// and the curated payload ships no envVars — without the server-resolved// flag the tool-use warning silently skips the incident's provider class.- mocks.getAllProviders.mockResolvedValue({+ mocks.getSelectableProviders.mockResolvedValue({activeProvider: 'openai',providers: [{ id: 'openai', name: 'OpenAI', type: 'api', enabled: true, defaultModel: 'gpt-4', models: ['gpt-4'] },diff --git a/server/services/persistentMindTaskCapability.js b/server/services/persistentMindTaskCapability.jsindex c5eea09eec..3944ad5bbc 100644--- a/server/services/persistentMindTaskCapability.js+++ b/server/services/persistentMindTaskCapability.js@@ -28,7 +28,11 @@ import { loadState } from './cosState.js';import { addTask, firstLine, getCosTasks, getTaskById } from './cosTaskStore.js';import { getProviderPrerequisiteReadinessMap } from './providerPrerequisites.js';import { listManagedBackendModels } from './localLlm.js';-import { listProviders } from './providers.js';+// listSelectableProviders, not listProviders: both reads below OFFER models+// — the task catalog's per-provider allowlist and the choice validator that+// accepts or refuses a submitted model — so they must see the install's+// entitlement, not the vendor's whole advertised catalog (docs/MODEL_ACCESS.md).+import { listSelectableProviders } from './providers.js';import {assessPersistentMindWorkspaceReadiness,readPersistentMindWorkspacePreflight,@@ -158,7 +162,7 @@ const appCatalogEntry = (app) => ({export async function readPersistentMindTaskCatalog({ allowedAppIds, includeAllApps = false } = {}) {const [managedApps, providers, root] = await Promise.all([readPersistentMindManagedApps({ allowedAppIds }),- listProviders(),+ listSelectableProviders(),loadState(),]);const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);@@ -350,7 +354,7 @@ async function queueOneTask({ request, taskId, apps, allowedAppIds }) {}const existing = await getTaskById(taskId);if (existing) return { success: true, duplicate: true, task: existing };- const [providers, root] = await Promise.all([listProviders(), loadState()]);+ const [providers, root] = await Promise.all([listSelectableProviders(), loadState()]);const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);if (!capabilities.createTasks) return { success: false, error: 'Persistent mind task creation access is disabled' };const choice = await validateChoice(request, apps, providers, capabilities);diff --git a/server/services/persistentMindTaskCapability.test.js b/server/services/persistentMindTaskCapability.test.jsindex 409633c238..3bf2bb3a87 100644--- a/server/services/persistentMindTaskCapability.test.js+++ b/server/services/persistentMindTaskCapability.test.js@@ -30,7 +30,7 @@ vi.mock('./cosTaskStore.js', () => ({getCosTasks: vi.fn(async () => ({ tasks: mocks.cosTasks })),getTaskById: (...args) => mocks.getTaskById(...args),}));-vi.mock('./providers.js', () => ({ listProviders: vi.fn(async () => mocks.providers) }));+vi.mock('./providers.js', () => ({ listSelectableProviders: vi.fn(async () => mocks.providers) }));vi.mock('./localLlm.js', () => ({listManagedBackendModels: (...args) => mocks.listManagedBackendModels(...args),}));diff --git a/server/services/providers.js b/server/services/providers.jsindex 2ccd991d6f..dbf4f01d4e 100644--- a/server/services/providers.js+++ b/server/services/providers.js@@ -4,6 +4,7 @@*/import { setAIToolkitInstance, requireToolkit } from '../lib/aiToolkitState.js';+import { applyModelAccessList } from '../lib/aiToolkit/internal/modelAccess.js';// `server/index.js` imports `setAIToolkit` from here — keep the named export// stable while the underlying singleton lives in `lib/aiToolkitState.js` so@@ -50,6 +51,42 @@ export async function listProviders() {return Array.isArray(data?.providers) ? data.providers : [];}+/**+ * The provider records with each one's `models` narrowed to what this install is+ * ENTITLED to run — see `lib/aiToolkit/internal/modelAccess.js` and+ * `docs/MODEL_ACCESS.md`.+ *+ * The distinction this names, once, is SELECTING versus EXECUTING:+ *+ * - A caller OFFERING a choice — a picker payload, a task-model allowlist, the+ * connection graph's model menus, the comparison chart's inventory — must use+ * this one, or it offers models the account cannot run.+ * - A caller EXECUTING, ACCOUNTING or WRITING — the runner, quota burn, usage+ * reconciliation, a harness catalog refresh — must use {@link listProviders},+ * because the entitlement policy is about what a human may pick next, not+ * about what already ran or what the upstream actually advertises. Narrowing+ * there would also let a write path persist a truncated catalog over the real+ * one, which no refresh would restore until the policy was cleared.+ *+ * Two methods rather than a flag on one, because the answer is a property of the+ * CALLER's purpose and picking the wrong one has to be visible at the call site.+ * Each scoped record carries the untouched list as `modelCatalog`, so a caller+ * that needs both has both.+ */+export async function getSelectableProviders() {+ const data = await getAllProviders();+ return { ...data, providers: applyModelAccessList(data.providers) };+}++/**+ * The list form of {@link getSelectableProviders}, mirroring+ * {@link listProviders} against {@link getAllProviders} — same envelope trap,+ * same answer.+ */+export async function listSelectableProviders() {+ return applyModelAccessList(await listProviders());+}+export async function getProviderById(id) {return requireToolkit().services.providers.getProviderById(id);}