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
simplify the service-instance slice: one credential-mode vocabulary, one plan check, one DTO projection, stamped catalogs on both refresh paths (#7563)
[._.]/ Adam Eivye6928be41fb7
diff --git a/server/lib/README.md b/server/lib/README.mdindex bd02688593..b7f955d0cf 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -230,7 +230,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `harnessOutput.js` | Parsers for what a coding-agent HARNESS prints about itself: `parseHarnessVersion(stdout)` (the one semver run in a `--version` banner, `null` when unparseable), `compareHarnessVersions(a, b)` (the null-guarding wrapper around `versionUtils.js#compareSemver` — `null` when either side is unparseable, so a version that did not parse never reads as "out of date"), `parseHarnessModels(harnessId, stdout)` + `HARNESS_MODEL_PARSER_IDS` (OpenCode's `provider/model` lines and Grok's bulleted list are parsed here; Antigravity and Cursor DELEGATE to `antigravity.js#parseAntigravityModelList` / `aiToolkit/internal/cursor.js#parseCursorModelList`, which the provider-card refresh has used for far longer), `MAX_MODELS`, and `parseNpmLatestVersion`. Pure: the service layer runs the child and hands the captured stdout here, so the vendor output shapes are pinned by table-driven tests instead of by running six real binaries in CI. Model ids come back in the exact spelling `--model` takes — namespaces kept where the vendor keeps them. Consumed by `services/providerRuntimeInstaller.js` and `services/harnesses.js`. || `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`, `nvidia-nim`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, `isGatewayBackedProvider(config)`, and `attachGatewaySiblingKey(provider, providers)` — the synchronous twin of the toolkit's `withGatewayApiKey` for callers holding an already-loaded (RAW, keyless) collection: a fallback pick armed from such a map executes with its sibling's key instead of going out with no Authorization header. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) — `providerGateways.parity.test.js` fails when the two drift; `client/src/utils/providerGateways.js` re-exports this leaf rather than copying it. DERIVED (#7562) from the `serviceDefinitions.js` rows carrying a `gateway` column, so a gateway is one row in that table; the projected shape is unchanged. Dependency-light: imports only that leaf. || `serviceDefinitions.js` | `SERVICE_DEFINITIONS` (#7562) — every backend a harness can be pointed at, as ONE table: subscription services (claude-subscription, codex-subscription, antigravity, grok-build, cursor), API-key services (anthropic, openai, google, xai, bedrock, kimi, the three hosted gateways orcarouter/openrouter/nvidia-nim, opencode-zen, cerebras, a generic openai-compatible endpoint), one `local` row per `LOCAL_RUNTIMES` id, and `fleet-host`. Each row: `family`, `transports` (`anthropic` / `openai` with a default base URL, or none for a local daemon whose port is an install fact), `credential` (env var names, key URL), the `plans` it may be declared under (`SERVICE_PLANS`), a `catalog` strategy with an optional per-plan filter (OpenRouter `:free`, OpenCode Zen `*-free`), and where relevant `localRuntime`, `harnessOnly`, `gateway` (the rows `PROVIDER_GATEWAYS` derives from) and `piProvider` (Pi's built-in name). `resolveServiceInstance(input)` is the pure instance shape the epic composes over (definition + `slug` + `plan` + resolved `transports` + raw `credentials`), `serviceDefinitionById` / `serviceDefinitionForLocalRuntime` look rows up, `serviceError(code, message)` mints the typed errors. Imports nothing, so `providerGateways.js` and the browser can reach it. |-| `providerServiceInstances.js` | A connection read as a SERVICE INSTANCE (#7563, epic #7561) — the pure bridge between `ai_connections` rows and `serviceDefinitions.js`. `definitionIdForKind` / `kindForDefinition` translate a row's `kind` (`ollama`, `gateway:<id>`, `api`, `vendor` + its binding's harness) to a definition id and back; `allocateServiceSlug` mints `base`, `base-2`, …; `serviceColumnsForConnection` / `planServiceColumnBackfill` are the boot-time backfill (slug, definition, first plan) the reconcile pass applies to rows that predate the columns — row-derived, idempotent, never a seed; `transportsForDefinition` is the stored transports map for a new instance; `applyServicePlanFilter` and `nextServiceCatalog` (`nextConnectionCatalog` plus `capabilities` / `refreshedAt`) shape a refresh outcome; `serviceHasCredentials` / `credentialSourceFor` report credential PRESENCE and SOURCE (`settings`, `env-file`, `env`, `cli`, `config`, `none`) without a value; `toServiceDto` (`serviceDtoSchema`, strict) is the sanitized `GET /api/providers/services` row with a one-word `readiness`. Constants: `SERVICE_CREDENTIAL_VIAS`, `SERVICE_CREDENTIAL_SOURCES`. |+| `providerServiceInstances.js` | A connection read as a SERVICE INSTANCE (#7563, epic #7561) — the pure bridge between `ai_connections` rows and `serviceDefinitions.js`. `definitionIdForKind` / `kindForDefinition` translate a row's `kind` (`ollama`, `gateway:<id>`, `api`, `vendor` + its binding's harness) to a definition id and back; `allocateServiceSlug` mints `base`, `base-2`, …; `serviceColumnsForConnection` / `planServiceColumnBackfill` are the boot-time backfill (slug, definition, first plan) the reconcile pass applies to rows that predate the columns — row-derived, idempotent, never a seed; `takenServiceSlugs` is the set every allocation avoids; `storedTransports` is the transports map a new instance's row stores; `applyServicePlanFilter` narrows a listing to a plan; `credentialSourceFor` reports where an instance's credential comes from (`settings`, `env-file`, `env`, `cli`, `config`, `none`, the inventory's own precedence) without a value; `toServiceDto` (`serviceDtoSchema`, the connection DTO extended, strict) is the sanitized `GET /api/providers/services` row with a one-word `readiness`. || `providerHarnesses.js` | Provider HARNESS identity for the connection graph (#6366) — `PROVIDER_HARNESSES` (one row per agent program PortOS drives: claude/opencode/codex/antigravity/cursor/grok/kimi/pi, plus `direct` — PortOS's own HTTP client, the harness of an `api` record (#7562) — each with its supported `modes`, wire `protocol`, the existing `is*Provider` predicate as its matcher, and its capability `bindings`: every way the program can be pointed at a service definition — subscription, protocol+baseUrl+credential, static-env service (Bedrock), `codexOss`, `piProvider`), `PROVIDER_HARNESS_IDS`, `harnessById`, `harnessForProvider` (`direct` for an `api` record, null only for an UNKNOWN harness), `normalizeHarnessId` / `graphHarnessId` (the one `direct` ↔ `NULL` translation for the graph's nullable column), `compatibleBindings(harness, serviceInstance)` / `firstCompatibleBinding` / `isCompatible` (which bindings reach a resolved service instance), `CREATABLE_HARNESS_IDS` (mintable from a bare connection) and `harnessConnectionBlocker` (the row's `connectionBlocker`: why not — no recipe at all, or a subscription/Pi row that composes onto named services only), `harnessSupportsMode`, `ROUTE_MODES`, plus the model-name adapters `toExecutableModelName` / `toCanonicalModelName` (the verified inverse of `prefixOpencodeModel`: a stored alias is canonicalized only when it maps back to the exact stored string, so import never rewrites a saved model by heuristically stripping a prefix). Distinct from `providerVendors.js` (argv-shaped), `providerFamilies.js` (subscription quota) and `serviceDefinitions.js` (the backends). Pure leaf — `client/src/utils/providerHarnesses.js` names a binding's harness through `harnessById`; the `direct` ↔ `NULL` translation is mirrored in `aiToolkit/internal/harnesses.js` behind `providerHarnesses.parity.test.js`. || `providerContextWindows.js` | The context-window ladder for provider/model planning, split out of `services/stageRunner.js` so the browser shares it: the vendor constants (`DEFAULT_LARGE_CONTEXT_WINDOW` / `CODEX_CONTEXT_WINDOW` / `GEMINI_CONTEXT_WINDOW` / `GROK_CONTEXT_WINDOW` / `KIMI_CONTEXT_WINDOW`), `knownModelContextWindow(model)` (the known-model regex table), `knownProviderContextWindow(provider)` (the vendor window for a configured-default CLI/TUI provider) `catalogModelContextWindow(provider, model)` (the window the provider's own `/models` catalog reported, which outranks the table) and `mergeObservedContextWindows(provider, observed)` (folds a local daemon's LIVE `/v1/models` windows onto that catalog rung, so they outrank a stale refresh while an explicit `contextWindow` still wins; never persisted) and `aliasServedContextWindows(provider, runtime, served)` (re-keys a daemon's served windows by every spelling the provider could dispatch under, for a caller that already holds the listing). The Ollama `num_ctx` ceiling is deliberately NOT here — see `aiToolkit/`. `stageRunner.js` builds `effectiveContextWindow` on them; `client/src/utils/providerContextWindows.js` re-exports them for the provider-card budget meter, so the two ends can't resolve a different window. Pure. || `providerConnections.js` | Provider CONNECTION identity for the connection graph (#6366) — `providerConnectionProfile(provider)` reads one record as the backend it describes (`kind`, `protocol`, `transports`, RAW server-only `credentials`, the `owned` field/env split, and `reasons` from `CONNECTION_ISOLATION_REASONS` when the config is dynamic, external, unparsable or endpoint-less). `sameConnectionIdentity` compares real credential values and refuses once any is the `REDACTED_CREDENTIAL` sentinel, so a sanitized record can never merge two connections; `compareBackendEndpoints` is the looser same-daemon test that only ever produces a link SUGGESTION, applying the recognized OpenAI-compatible `/v1` conversion (never DNS resolution, loopback/remote equivalence or arbitrary path trimming). `projectConnectionOwnedFields(provider, connection)` projects a stored backend through the reader's protocol and env-ownership rules for the graph service; `withoutConnectionOwnedFields` / `withConnectionOwnedFields` are the lossless split/materialize pair that keeps a downgraded install runnable from `data/providers.json` alone. Pure: no I/O. |diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsindex f4963853c7..5639b6c6f2 100644--- a/server/lib/providerGraphRecords.js+++ b/server/lib/providerGraphRecords.js@@ -15,7 +15,7 @@ import {} from './providerModelAliases.js';import { routeSettingsRevision, routeSettingsSchema } from './providerRouteSettings.js';import { CREATABLE_CONNECTION_KINDS, connectionKindLabel } from './providerRouteRecipes.js';-import { SERVICE_PLANS } from './serviceDefinitions.js';+import { SERVICE_CREDENTIAL_VIAS, SERVICE_PLANS } from './serviceDefinitions.js';// `PROVIDER_GRAPH_SCHEMA_VERSION` is deliberately NOT re-exported: it is one// wire version shared with the preview, and two flat `export *` modules in this@@ -65,11 +65,8 @@ const catalogSchema = z.object({refreshedAt: z.string().optional(),}).strict();-// `credentialVia` is mirrored from `providerServiceInstances.js` rather than-// imported: that module builds on this one, and the enum is four literals.-const CREDENTIAL_VIAS = ['stored', 'env', 'cli-login', 'bootstrap'];--const connectionDtoSchema = z.object({+/** One connection row as every management surface publishes it — exported so the service DTO extends it. */+export const connectionDtoSchema = z.object({id: z.string().min(1),revision: z.number().int().positive(),kind: z.string().min(1),@@ -84,7 +81,7 @@ const connectionDtoSchema = z.object({definitionId: z.string().nullable(),plan: z.enum(SERVICE_PLANS),enabled: z.boolean(),- credentialVia: z.enum(CREDENTIAL_VIAS),+ credentialVia: z.enum(SERVICE_CREDENTIAL_VIAS),}).strict();const bindingDtoSchema = z.object({@@ -221,9 +218,7 @@ export function toManagementGraphDto({ connections, bindings, routes, activeProvkind,label,transports,- // Only a `stored` instance holds a secret; a `bootstrap` one is supplied- // at spawn and an `env` / `cli-login` one is held by something else.- hasCredentials: credentialVia === 'stored' && Object.keys(credentials || {}).length > 0,+ hasCredentials: connectionHasCredentials({ credentials, credentialVia }),catalog,slug,definitionId,@@ -259,6 +254,14 @@ export function toManagementGraphDto({ connections, bindings, routes, activeProv});}+/**+ * Whether a row holds a secret. Only a `stored` instance does (#7563): a+ * `bootstrap` one is supplied at spawn and an `env` / `cli-login` one is+ * held by something else, so a key left on such a row is not the credential.+ */+export const connectionHasCredentials = ({ credentials, credentialVia = 'stored' }) =>+ credentialVia === 'stored' && Object.keys(credentials || {}).length > 0;+/*** One connection row, sanitized exactly as `GET /api/providers/management`* sanitizes it (#6369).@@ -656,14 +659,31 @@ export function sanitizeCatalogError(error, credentials = {}) {* because reporting it as clean would hide a harness that cannot reach the* backend behind the models of one that can.*- * @param {{state:string, models:string[]}} current - the stored catalog- * @param {{refreshed: boolean, models?: string[], error?: string|null}} outcome- * @returns {{state:'unknown'|'known'|'failed', models:string[], error:string|null}}+ * Every refresh stamps `refreshedAt` (#7563) — a failure too, so "last asked"+ * and "last answered" stay distinct facts — and a success records the+ * per-model `capabilities` its listing declared (today the context window),+ * while a failure keeps the previous ones with the previous models.+ *+ * @param {{state:string, models:string[], capabilities?: object}} current - the stored catalog+ * @param {{refreshed: boolean, models?: string[], error?: string|null, contextWindows?: Record<string, number>|null}} outcome+ * @param {{now?: () => string}} [options] - injected clock, for tests+ * @returns {{state:'unknown'|'known'|'failed', models:string[], error:string|null, capabilities?: object, refreshedAt: string}}*/-export function nextConnectionCatalog(current, outcome) {+export function nextConnectionCatalog(current, outcome, { now = () => new Date().toISOString() } = {}) {const models = Array.isArray(current?.models) ? current.models : [];if (!outcome?.refreshed) {- return { state: 'failed', models, error: outcome?.error ?? 'The model refresh failed' };+ return {+ state: 'failed',+ models,+ error: outcome?.error ?? 'The model refresh failed',+ ...(current?.capabilities ? { capabilities: current.capabilities } : {}),+ refreshedAt: now(),+ };}- return { state: 'known', models: [...new Set(outcome.models || [])], error: outcome.error ?? null };+ const next = [...new Set(outcome.models || [])];+ const windows = outcome.contextWindows && typeof outcome.contextWindows === 'object' ? outcome.contextWindows : {};+ const capabilities = Object.fromEntries(next+ .filter((model) => Number.isFinite(windows[model]))+ .map((model) => [model, { contextWindow: windows[model] }]));+ return { state: 'known', models: next, error: outcome.error ?? null, capabilities, refreshedAt: now() };}diff --git a/server/lib/providerGraphRecords.test.js b/server/lib/providerGraphRecords.test.jsindex ca3539688d..38d79639d5 100644--- a/server/lib/providerGraphRecords.test.js+++ b/server/lib/providerGraphRecords.test.js@@ -27,6 +27,7 @@ import {planGraphReconciliation,reconciliationIsNoop,toManagementGraphDto,+ nextConnectionCatalog,} from './providerGraphRecords.js';// A deterministic id minter so a plan can be asserted without matching UUIDs.@@ -466,3 +467,20 @@ describe('graphFromPreview', () => {expect(new Set(variants).size).toBe(variants.length);});});++describe('nextConnectionCatalog — stamping and capabilities (#7563)', () => {+ const current = { state: 'known', models: ['a'], capabilities: { a: { contextWindow: 8192 } } };++ it('keeps the known models AND their capabilities through a failed refresh, and stamps the attempt', () => {+ expect(nextConnectionCatalog(current, { refreshed: false, error: 'timed out' }, { now: () => 'T1' })).toEqual({+ state: 'failed', models: ['a'], error: 'timed out', capabilities: { a: { contextWindow: 8192 } }, refreshedAt: 'T1',+ });+ });++ it('writes what a success saw — including an empty answer — with the windows the listing declared', () => {+ expect(nextConnectionCatalog(current, { refreshed: true, models: ['b', 'c', 'b'], contextWindows: { b: 32768, zzz: 1 } }, { now: () => 'T2' }))+ .toEqual({ state: 'known', models: ['b', 'c'], error: null, capabilities: { b: { contextWindow: 32768 } }, refreshedAt: 'T2' });+ expect(nextConnectionCatalog(current, { refreshed: true, models: [] }, { now: () => 'T3' }))+ .toEqual({ state: 'known', models: [], error: null, capabilities: {}, refreshedAt: 'T3' });+ });+});diff --git a/server/lib/providerServiceInstances.js b/server/lib/providerServiceInstances.jsindex 7dd0ba653e..f7dff1e3d9 100644--- a/server/lib/providerServiceInstances.js+++ b/server/lib/providerServiceInstances.js@@ -1,16 +1,15 @@import { z } from 'zod';import { harnessById } from './providerHarnesses.js';+import { connectionDtoSchema, connectionHasCredentials, toConnectionDto } from './providerGraphRecords.js';import { isNonBlankStr } from './textUtils.js';import {CATALOG_STRATEGIES,SERVICE_FAMILIES,SERVICE_PLANS,SERVICE_SLUG_RE,- resolveServiceInstance,serviceDefinitionById,serviceDefinitionForLocalRuntime,} from './serviceDefinitions.js';-import { nextConnectionCatalog } from './providerGraphRecords.js';/*** The pure half of "a connection IS a service instance" (#7563, epic #7561).@@ -21,18 +20,15 @@ import { nextConnectionCatalog } from './providerGraphRecords.js';* the bridge — how an existing row learns its definition, its default plan and* an addressable slug (the backfill the boot reconcile pass runs), how a new* instance created FROM a definition gets the `kind` reconciliation expects,- * how a refresh outcome becomes the stored catalog, and the sanitized DTO- * `GET /api/providers/services` publishes.+ * which models a plan may list, where an instance's credential comes from, and+ * the sanitized DTO `GET /api/providers/services` publishes.*- * Pure on purpose: no DB handle, no probe, no clock beyond the injected `now`,- * so the backfill rule and the plan filter are pinned without a Postgres.+ * Pure on purpose: no DB handle, no probe, no clock, so the backfill rule and+ * the plan filter are pinned without a Postgres.*/-/** How an instance authenticates. Only `stored` means a secret is on the row. */-export const SERVICE_CREDENTIAL_VIAS = Object.freeze(['stored', 'env', 'cli-login', 'bootstrap']);--/** Where the credential an instance runs under was found; mirrors `credentialInventory`'s vocabulary. */-export const SERVICE_CREDENTIAL_SOURCES = Object.freeze(['settings', 'env-file', 'env', 'cli', 'config', 'none']);+/** Where a credential was found; `credentialInventory`'s vocabulary, so the two surfaces agree. */+const CREDENTIAL_SOURCES = Object.freeze(['settings', 'env-file', 'env', 'cli', 'config', 'none']);const GATEWAY_KIND = 'gateway:';@@ -71,7 +67,9 @@ export function definitionIdForKind(kind, { harnessId = null } = {}) {/*** The connection `kind` a definition's instances carry — the inverse of* {@link definitionIdForKind}, so a row created from a definition is judged by- * reconciliation on exactly the terms an imported record would be.+ * reconciliation on exactly the terms an imported record would be. (Not+ * `providerRouteRecipes`' `serviceConnectionKind`, which answers a different+ * question — the OpenCode namespace — and falls back to the slug.)*/export function kindForDefinition(definition) {if (definition.localRuntime) return definition.localRuntime;@@ -80,6 +78,9 @@ export function kindForDefinition(definition) {return 'api';}+/** The slugs a graph already uses — what every allocation must avoid. */+export const takenServiceSlugs = (connections) => new Set(connections.map((connection) => connection.slug).filter(Boolean));+/*** A slug not yet in `taken`: `base`, then `base-2`, `base-3`, …*@@ -121,15 +122,15 @@ export function serviceColumnsForConnection(connection, { harnessId = null, take/*** The backfill one reconcile pass applies: every connection with no `slug`- * gets its service columns, allocated against the slugs the graph already- * holds. Rows that have one are untouched, so a second pass plans nothing —- * the "re-run is a no-op" half of the migration contract.+ * gets its service columns, allocated against `taken`. Rows that have one are+ * untouched, so a second pass plans nothing — the "re-run is a no-op" half of+ * the migration contract.** @param {{connections: object[], bindings: object[]}} graph- * @param {Set<string>} [taken] - slugs already allocated in this pass; defaults to the graph's own+ * @param {Set<string>} taken - slugs already allocated in this pass* @returns {{id: string, slug: string, definitionId: string|null, plan: string}[]}*/-export function planServiceColumnBackfill(graph, taken = new Set(graph.connections.map((connection) => connection.slug).filter(Boolean))) {+export function planServiceColumnBackfill(graph, taken) {return graph.connections.filter((connection) => !connection.slug).map((connection) => {@@ -139,67 +140,39 @@ export function planServiceColumnBackfill(graph, taken = new Set(graph.connectio}/**- * The transports map a stored row carries for a definition: the instance's- * own overrides, else the definition's default base URL, and NO entry for a- * protocol with neither — a `{ baseUrl: null }` row would read as an endpoint.+ * The transports map a stored row carries for a resolved instance: only the+ * protocols with an endpoint — a `{ baseUrl: null }` row would read as one.*/-export function transportsForDefinition(definition, overrides = {}) {- return Object.fromEntries(Object.entries(resolveServiceInstance({ definition, transports: overrides }).transports)- .filter(([, transport]) => typeof transport.baseUrl === 'string' && transport.baseUrl !== '')- .map(([protocol, transport]) => [protocol, { baseUrl: transport.baseUrl }]));-}+export const storedTransports = (instance) => Object.fromEntries(Object.entries(instance.transports)+ .filter(([, transport]) => isNonBlankStr(transport.baseUrl))+ .map(([protocol, transport]) => [protocol, { baseUrl: transport.baseUrl }]));/** The models a plan may list, per the definition's own filter. Identity when it has none. */export const applyServicePlanFilter = (definition, plan, models) => (typeof definition?.catalog?.planFilter === 'function' ? definition.catalog.planFilter(plan, models) : models);-/**- * The catalog a service refresh leaves behind — `nextConnectionCatalog`'s- * rule (a failure keeps what was known, a success writes what it saw) plus- * `refreshedAt` and the per-model `capabilities` a listing declared. A failed- * refresh keeps the previous capabilities with the previous models.- *- * @param {object} current - the stored catalog- * @param {{refreshed: boolean, models?: string[], error?: string|null, contextWindows?: Record<string, number>|null}} outcome- * @param {{now?: () => string}} [options]- */-export function nextServiceCatalog(current, outcome, { now = () => new Date().toISOString() } = {}) {- const next = nextConnectionCatalog(current, outcome);- if (!outcome?.refreshed) {- return { ...next, ...(current?.capabilities ? { capabilities: current.capabilities } : {}), refreshedAt: now() };- }- const windows = outcome.contextWindows && typeof outcome.contextWindows === 'object' ? outcome.contextWindows : {};- const capabilities = Object.fromEntries(next.models- .filter((model) => Number.isFinite(windows[model]))- .map((model) => [model, { contextWindow: windows[model] }]));- return { ...next, capabilities, refreshedAt: now() };-}--/** Whether a stored secret is on the row — the only `credentialVia` that holds one. */-export const serviceHasCredentials = (connection) => (- (connection.credentialVia ?? 'stored') === 'stored' && Object.keys(connection.credentials || {}).length > 0-);-/*** Where the credential this instance runs under comes from, in- * `credentialInventory`'s vocabulary — so a subscription instance can report- * "signed in via CLI" without holding a key, and a `bootstrap` one "supplied by- * the launch wrapper" (`config`). Never the value itself.+ * `credentialInventory`'s vocabulary and with its precedence — so a+ * subscription instance can report "signed in via CLI" without holding a key,+ * and a `bootstrap` one "supplied by the launch wrapper" (`config`). Never+ * the value itself.*- * @param {{credentialVia?: string, credentials?: object, definition?: object|null}} instance- * @param {{env?: Record<string, string|undefined>, envFile?: Map<string, string>|null}} [sources]+ * @param {{credentialVia?: string, credentials?: object}} connection+ * @param {{definition?: object|null, env?: Record<string, string|undefined>, envFile?: Map<string, string>|null}} [sources]*/-export function credentialSourceFor(instance, { env = {}, envFile = null } = {}) {- const via = instance.credentialVia ?? 'stored';+export function credentialSourceFor(connection, { definition = null, env = {}, envFile = null } = {}) {+ const via = connection.credentialVia ?? 'stored';if (via === 'cli-login') return 'cli';if (via === 'bootstrap') return 'config';- if (via === 'stored' && serviceHasCredentials(instance)) return 'settings';- for (const name of instance.definition?.credential?.envVars ?? []) {- if (isNonBlankStr(envFile?.get?.(name))) return 'env-file';- if (isNonBlankStr(env[name])) return 'env';- }- return 'none';+ if (via === 'stored' && connectionHasCredentials(connection)) return 'settings';+ const names = definition?.credential?.envVars ?? [];+ const processKey = names.find((name) => isNonBlankStr(env[name]));+ const fileKey = names.find((name) => isNonBlankStr(envFile?.get?.(name)));+ if (processKey && fileKey && env[processKey] === envFile.get(fileKey)) return 'env-file';+ if (processKey) return 'env';+ return fileKey ? 'env-file' : 'none';}// --- the sanitized service DTO ---------------------------------------------------@@ -214,31 +187,14 @@ const definitionDtoSchema = z.object({}).strict();/**- * One instance as `GET /api/providers/services` publishes it. `.strict()` like- * every graph DTO: a column added to the row must never ride out because a- * mapper forgot to drop it, and `credentials` never appears at all.+ * One instance as `GET /api/providers/services` publishes it: the connection+ * DTO (so a column is mapped in exactly one place and `credentials` never+ * appears) plus what only the service reading adds. `.strict()` like every+ * graph DTO.*/-export const serviceDtoSchema = z.object({- id: z.string().min(1),- slug: z.string().nullable(),- revision: z.number().int().positive(),- label: z.string(),- kind: z.string().min(1),- definitionId: z.string().nullable(),+export const serviceDtoSchema = connectionDtoSchema.extend({definition: definitionDtoSchema.nullable(),- plan: z.enum(SERVICE_PLANS),- enabled: z.boolean(),- transports: z.record(z.string(), z.object({ baseUrl: z.string().min(1) }).strict()),- hasCredentials: z.boolean(),- credentialVia: z.enum(SERVICE_CREDENTIAL_VIAS),- credentialSource: z.enum(SERVICE_CREDENTIAL_SOURCES),- catalog: z.object({- state: z.enum(['unknown', 'known', 'failed']),- models: z.array(z.string()),- error: z.string().nullable().optional(),- capabilities: z.record(z.string(), z.object({ contextWindow: z.number().optional() }).strict()).optional(),- refreshedAt: z.string().optional(),- }).strict(),+ credentialSource: z.enum(CREDENTIAL_SOURCES),bindingCount: z.number().int().nonnegative(),// One word a card can act on. `unknown-definition` is a row nothing composes// onto (a kind this release has no definition for), not a broken one.@@ -247,7 +203,7 @@ export const serviceDtoSchema = z.object({function serviceReadiness(connection, definition, credentialSource) {if (!definition) return 'unknown-definition';- if (connection.enabled === false) return 'disabled';+ if (!connection.enabled) return 'disabled';const declares = Object.keys(definition.transports);const reachable = declares.length === 0 || declares.some((protocol) => connection.transports?.[protocol]?.baseUrl);if (!reachable) return 'needs-endpoint';@@ -259,33 +215,24 @@ function serviceReadiness(connection, definition, credentialSource) {/*** @param {object} connection - a store row- * @param {{bindingCount?: number, credentialSource?: string}} [context]+ * @param {{bindingCount?: number, credentialSource?: string, definition?: object|null}} [context] —+ * `definition` may be passed by a caller that already resolved it.*/-export function toServiceDto(connection, { bindingCount = 0, credentialSource = 'none' } = {}) {- const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;+export function toServiceDto(connection, { bindingCount = 0, credentialSource = 'none', definition } = {}) {+ const base = toConnectionDto(connection);+ const resolved = definition === undefined ? (base.definitionId ? serviceDefinitionById(base.definitionId) : null) : definition;return serviceDtoSchema.parse({- id: connection.id,- slug: connection.slug ?? null,- revision: connection.revision,- label: connection.label ?? '',- kind: connection.kind,- definitionId: connection.definitionId ?? null,- definition: definition ? {- id: definition.id,- label: definition.label,- family: definition.family,- plans: [...definition.plans],- catalogStrategy: definition.catalog.strategy,- harnessOnly: definition.harnessOnly ?? null,+ ...base,+ definition: resolved ? {+ id: resolved.id,+ label: resolved.label,+ family: resolved.family,+ plans: [...resolved.plans],+ catalogStrategy: resolved.catalog.strategy,+ harnessOnly: resolved.harnessOnly ?? null,} : null,- plan: connection.plan ?? 'paid',- enabled: connection.enabled ?? true,- transports: connection.transports || {},- hasCredentials: serviceHasCredentials(connection),- credentialVia: connection.credentialVia ?? 'stored',credentialSource,- catalog: connection.catalog || { state: 'unknown', models: [] },bindingCount,- readiness: serviceReadiness(connection, definition, credentialSource),+ readiness: serviceReadiness(base, resolved, credentialSource),});}diff --git a/server/lib/providerServiceInstances.test.js b/server/lib/providerServiceInstances.test.jsindex 7dfa8faca6..42ac638a6c 100644--- a/server/lib/providerServiceInstances.test.js+++ b/server/lib/providerServiceInstances.test.js@@ -17,8 +17,8 @@ import {credentialSourceFor,definitionIdForKind,kindForDefinition,- nextServiceCatalog,planServiceColumnBackfill,+ takenServiceSlugs,toServiceDto,} from './providerServiceInstances.js';import { SERVICE_DEFINITIONS, serviceDefinitionById } from './serviceDefinitions.js';@@ -87,7 +87,7 @@ describe('planServiceColumnBackfill', () => {],bindings: [{ id: 'bind-e', connectionId: 'e', harnessId: 'claude' }],};- expect(planServiceColumnBackfill(graph)).toEqual([+ expect(planServiceColumnBackfill(graph, takenServiceSlugs(graph.connections))).toEqual([{ id: 'b', slug: 'ollama-2', definitionId: 'ollama', plan: 'local' },{ id: 'c', slug: 'ollama-3', definitionId: 'ollama', plan: 'local' },// The first plan, exactly as `resolveServiceInstance` defaults it.@@ -100,10 +100,10 @@ describe('planServiceColumnBackfill', () => {it('plans nothing on a second pass — the re-run is a no-op', () => {const graph = { connections: [row({ id: 'a', kind: 'ollama' }), row({ id: 'b', kind: 'api' })], bindings: [] };- const first = planServiceColumnBackfill(graph);+ const first = planServiceColumnBackfill(graph, takenServiceSlugs(graph.connections));const named = { connections: graph.connections.map((connection) => ({ ...connection, ...first.find((entry) => entry.id === connection.id) })), bindings: [] };- expect(planServiceColumnBackfill(named)).toEqual([]);- expect(planServiceColumnBackfill({ connections: [], bindings: [] })).toEqual([]);+ expect(planServiceColumnBackfill(named, takenServiceSlugs(named.connections))).toEqual([]);+ expect(planServiceColumnBackfill({ connections: [], bindings: [] }, new Set())).toEqual([]);});it('allocates against slugs a caller already handed out in the same pass', () => {@@ -114,7 +114,7 @@ describe('planServiceColumnBackfill', () => {});});-describe('plan filter and refresh outcome', () => {+describe('applyServicePlanFilter', () => {const zen = serviceDefinitionById('opencode-zen');const nim = serviceDefinitionById('nvidia-nim');const listing = ['big-pickle', 'mimo-v2.5-free', 'deepseek-v4-flash-free'];@@ -126,36 +126,26 @@ describe('plan filter and refresh outcome', () => {expect(applyServicePlanFilter(nim, 'free', listing)).toEqual(listing);expect(applyServicePlanFilter(nim, 'paid', listing)).toEqual(listing);});-- it('keeps the known models AND their capabilities through a failed refresh, and stamps the attempt', () => {- const current = { state: 'known', models: ['a'], capabilities: { a: { contextWindow: 8192 } } };- expect(nextServiceCatalog(current, { refreshed: false, error: 'timed out' }, { now: () => 'T1' })).toEqual({- state: 'failed', models: ['a'], error: 'timed out', capabilities: { a: { contextWindow: 8192 } }, refreshedAt: 'T1',- });- });-- it('writes what a success saw — including an empty answer — with the windows the listing declared', () => {- const current = { state: 'known', models: ['a'], capabilities: { a: { contextWindow: 8192 } } };- expect(nextServiceCatalog(current, { refreshed: true, models: ['b', 'c'], contextWindows: { b: 32768, zzz: 1 } }, { now: () => 'T2' }))- .toEqual({ state: 'known', models: ['b', 'c'], error: null, capabilities: { b: { contextWindow: 32768 } }, refreshedAt: 'T2' });- expect(nextServiceCatalog(current, { refreshed: true, models: [] }, { now: () => 'T3' }))- .toEqual({ state: 'known', models: [], error: null, capabilities: {}, refreshedAt: 'T3' });- });});describe('credentialSourceFor', () => {const nim = serviceDefinitionById('nvidia-nim');it('reports where the key comes from, never the key', () => {- expect(credentialSourceFor({ credentialVia: 'stored', credentials: { apiKey: 'example-key' }, definition: nim })).toBe('settings');- expect(credentialSourceFor({ credentialVia: 'cli-login', credentials: {}, definition: serviceDefinitionById('claude-subscription') })).toBe('cli');- expect(credentialSourceFor({ credentialVia: 'bootstrap', credentials: {}, definition: nim })).toBe('config');- expect(credentialSourceFor({ credentialVia: 'env', credentials: {}, definition: nim }, { env: { NVIDIA_API_KEY: 'example' } })).toBe('env');- expect(credentialSourceFor({ credentialVia: 'env', credentials: {}, definition: nim },- { env: {}, envFile: new Map([['NVIDIA_API_KEY', 'example']]) })).toBe('env-file');- expect(credentialSourceFor({ credentialVia: 'env', credentials: {}, definition: nim }, { env: { NVIDIA_API_KEY: '' } })).toBe('none');+ const from = (via, sources = {}) => credentialSourceFor({ credentialVia: via, credentials: {} }, { definition: nim, ...sources });+ expect(credentialSourceFor({ credentialVia: 'stored', credentials: { apiKey: 'example-key' } }, { definition: nim })).toBe('settings');+ expect(from('cli-login')).toBe('cli');+ expect(from('bootstrap')).toBe('config');+ expect(from('env', { env: { NVIDIA_API_KEY: 'example' } })).toBe('env');+ expect(from('env', { env: {}, envFile: new Map([['NVIDIA_API_KEY', 'example']]) })).toBe('env-file');+ expect(from('env', { env: { NVIDIA_API_KEY: '' } })).toBe('none');+ // The same precedence as the credential inventory: a process value that+ // matches the install file is reported as the file; one that differs is+ // the environment's own.+ expect(from('env', { env: { NVIDIA_API_KEY: 'same' }, envFile: new Map([['NVIDIA_API_KEY', 'same']]) })).toBe('env-file');+ expect(from('env', { env: { NVIDIA_API_KEY: 'other' }, envFile: new Map([['NVIDIA_API_KEY', 'same']]) })).toBe('env');// A stored instance with nothing stored is still checked against the// environment: the key may simply live there.- expect(credentialSourceFor({ credentialVia: 'stored', credentials: {}, definition: nim }, { env: { NVIDIA_API_KEY: 'x' } })).toBe('env');+ expect(from('stored', { env: { NVIDIA_API_KEY: 'x' } })).toBe('env');});});diff --git a/server/lib/serviceDefinitions.js b/server/lib/serviceDefinitions.jsindex 3685498bf1..c7dbd0fc52 100644--- a/server/lib/serviceDefinitions.js+++ b/server/lib/serviceDefinitions.js@@ -56,6 +56,14 @@ export const SERVICE_PLANS = Object.freeze(['free', 'paid', 'subscription', 'loc*/export const CATALOG_STRATEGIES = Object.freeze(['probe', 'daemon', 'harness', 'static']);+/**+ * How an instance authenticates (#7563). Only `stored` holds a secret on the+ * row; `env` reads the definition's conventional variable, `cli-login` is+ * the harness's own sign-in, and `bootstrap` means a launch wrapper supplies+ * the key at spawn.+ */+export const SERVICE_CREDENTIAL_VIAS = Object.freeze(['stored', 'env', 'cli-login', 'bootstrap']);+const METERED = Object.freeze(['free', 'paid']);const PAID = Object.freeze(['paid']);const SUBSCRIPTION = Object.freeze(['subscription']);@@ -328,9 +336,7 @@ export function resolveServiceInstance(input) {const slug = raw.slug ?? definition.id;if (!SERVICE_SLUG_RE.test(slug)) throw serviceError('SERVICE_SLUG_INVALID', `"${slug}" is not a service slug ([a-z0-9][a-z0-9-]*)`);const plan = raw.plan ?? definition.plans[0];- if (!definition.plans.includes(plan)) {- throw serviceError('SERVICE_PLAN_UNSUPPORTED', `${definition.label} has no "${plan}" plan; choose one of ${definition.plans.join(', ')}`);- }+ assertServicePlan(definition, plan);const transports = {};for (const [protocol, transport] of Object.entries(definition.transports)) {@@ -347,9 +353,21 @@ export function resolveServiceInstance(input) {};}-/** A typed error every consumer can key on. */+/** Refuse a plan the definition does not sell — the one rule every instance write shares. */+export function assertServicePlan(definition, plan) {+ if (!definition.plans.includes(plan)) {+ throw serviceError('SERVICE_PLAN_UNSUPPORTED', `${definition.label} has no "${plan}" plan; choose one of ${definition.plans.join(', ')}`);+ }+}++/**+ * A typed error every consumer can key on. Every refusal here is about the+ * caller's input, so it carries the 400 the error middleware reads — a route+ * needs no translation layer to publish it.+ */export function serviceError(code, message) {const err = new Error(message);err.code = code;+ err.status = 400;return err;}diff --git a/server/lib/serviceDefinitions.test.js b/server/lib/serviceDefinitions.test.jsindex 91de8fd102..1e5a02b144 100644--- a/server/lib/serviceDefinitions.test.js+++ b/server/lib/serviceDefinitions.test.js@@ -12,7 +12,6 @@ import {SERVICE_DEFINITION_IDS,SERVICE_FAMILIES,SERVICE_PLANS,- SERVICE_SLUG_RE,resolveServiceInstance,serviceDefinitionById,serviceDefinitionForLocalRuntime,@@ -20,8 +19,6 @@ import {import { LOCAL_RUNTIMES } from './localProviderRuntime.js';import { PROVIDER_GATEWAYS } from './providerGateways.js';import { CREDENTIALS } from './credentialRegistry.js';-import { SERVICE_CREDENTIAL_VIAS } from './providerServiceInstances.js';-import { serviceCredentialViaSchema, servicePlanSchema, serviceSlugSchema } from './validation.js';/** Epic D2, verbatim: the ids the rest of the epic composes from. */const D2_IDS = [@@ -133,14 +130,3 @@ describe('resolveServiceInstance', () => {});});-describe('the route schemas mirror the definition vocabulary (#7563)', () => {- // `lib/validation.js` spells these as literals to stay off this module's- // import path; this is what keeps the two from drifting.- it('accepts exactly the plans, credential modes and slug shape the definitions declare', () => {- expect(servicePlanSchema.options).toEqual([...SERVICE_PLANS]);- expect(serviceCredentialViaSchema.options).toEqual([...SERVICE_CREDENTIAL_VIAS]);- for (const slug of ['nvidia-nim', 'a', 'x9-y', 'Nope', '-lead', 'under_score', 'sp ace', '']) {- expect(serviceSlugSchema.safeParse(slug).success).toBe(SERVICE_SLUG_RE.test(slug) && slug.length <= 64);- }- });-});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex af7ebc93d1..5bb649a46b 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -19,6 +19,7 @@ import { PR_COMPLETION_VALUES } from './prDisposition.js';import { EFFORT_LEVELS } from './providerModels.js';import { MODEL_ALIAS_LIMITS } from './providerModelAliases.js';import { PROVIDER_HARNESS_IDS, ROUTE_MODES } from './providerHarnesses.js';+import { SERVICE_CREDENTIAL_VIAS, SERVICE_PLANS, SERVICE_SLUG_RE } from './serviceDefinitions.js';import { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';import {FEDERATED_MEDIA_ASSET_MAX_COUNT,@@ -693,17 +694,13 @@ export const providerConnectionUpdateSchema = z.object({}).strict();// --- service instances (#7563) -------------------------------------------------//-// The literals below mirror `serviceDefinitions.js` (`SERVICE_SLUG_RE`,-// `SERVICE_PLANS`) and `providerServiceInstances.js` (`SERVICE_CREDENTIAL_VIAS`)-// rather than importing them: this module is reached by nearly every route-// (`lib/importScoping.test.js`), and `serviceDefinitions.test.js` pins the-// mirror so the two cannot drift.-export const serviceSlugSchema = z.string().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9-]*$/, {+// The vocabulary comes from `serviceDefinitions.js`, a zero-import leaf this+// module already reaches, so nothing here can drift from the definitions.+export const serviceSlugSchema = z.string().trim().min(1).max(64).regex(SERVICE_SLUG_RE, {message: 'A service slug is lowercase letters, digits and dashes, starting with a letter or digit',});-export const servicePlanSchema = z.enum(['free', 'paid', 'subscription', 'local']);-export const serviceCredentialViaSchema = z.enum(['stored', 'env', 'cli-login', 'bootstrap']);+export const servicePlanSchema = z.enum(SERVICE_PLANS);+export const serviceCredentialViaSchema = z.enum(SERVICE_CREDENTIAL_VIAS);const serviceTransportsSchema = z.record(z.string().trim().min(1).max(64),diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex a5e355c80f..19a89be489 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -41,12 +41,12 @@ import {} from '../lib/providerRouteSettings.js';import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';import {- SERVICE_CREDENTIAL_VIAS,allocateServiceSlug,planServiceColumnBackfill,serviceColumnsForConnection,+ takenServiceSlugs,} from '../lib/providerServiceInstances.js';-import { serviceDefinitionById } from '../lib/serviceDefinitions.js';+import { SERVICE_CREDENTIAL_VIAS, assertServicePlan, serviceDefinitionById } from '../lib/serviceDefinitions.js';import { requireToolkit } from '../lib/aiToolkitState.js';import {acknowledgeProjection,@@ -96,11 +96,16 @@ let graphEnabled = false;let reconciling = false;let queue = Promise.resolve();-/** One-at-a-time execution. A rejected pass must not poison the next one. */+/**+ * One-at-a-time execution. A rejected pass must not poison the next one.+ * Exported (as `serializeProviderGraph`) for the service-instance operations+ * in `providerServices.js`, which mutate the same rows.+ */const serialize = (fn) => {queue = queue.then(() => undefined, () => undefined).then(fn);return queue;};+export { serialize as serializeProviderGraph };export const providerGraphEnabled = () => graphEnabled;@@ -113,13 +118,6 @@ export function resetProviderGraphState() {const providerService = () => requireToolkit().services.providers;-/**- * Run `fn` on the graph's one serialization queue. Exported for the- * service-instance operations in `providerServices.js`, which mutate the same- * rows and must not interleave with a reconcile pass.- */-export const serializeProviderGraph = (fn) => serialize(fn);-/*** A connection addressed by UUID or by service slug (#7563). Every* `/connections/:id` route accepts either, so a client that learned the slug@@ -168,14 +166,15 @@ async function reconcilePass(reason) {// the pre-existing unnamed rows are backfilled after. Row-derived (never a// seed) and idempotent, so it rides every pass rather than a one-shot// migration. Local I/O only; nothing here contacts a provider.- const taken = new Set(graph.connections.map((connection) => connection.slug).filter(Boolean));- const harnessOf = (connectionId, bindings) => bindings.find((binding) => binding.connectionId === connectionId)?.harnessId ?? null;+ const taken = takenServiceSlugs(graph.connections);+ const harnessOf = (bindings, test) => bindings.find(test)?.harnessId ?? null;for (const connection of plan.imports.connections) {- Object.assign(connection, serviceColumnsForConnection(connection, { harnessId: harnessOf(connection.id, plan.imports.bindings), taken }));+ const harnessId = harnessOf(plan.imports.bindings, (binding) => binding.connectionId === connection.id);+ Object.assign(connection, serviceColumnsForConnection(connection, { harnessId, taken }));}for (const regroup of plan.regroups) {if (regroup.connectionAction !== 'clone') continue;- const harnessId = regroup.binding?.harnessId ?? graph.bindings.find((binding) => binding.id === regroup.bindingId)?.harnessId ?? null;+ const harnessId = regroup.binding?.harnessId ?? harnessOf(graph.bindings, (binding) => binding.id === regroup.bindingId);Object.assign(regroup.connection, serviceColumnsForConnection(regroup.connection, { harnessId, taken }));}const backfill = planServiceColumnBackfill(graph, taken);@@ -264,7 +263,7 @@ function describeRoute(provider) {/** The sanitized `GET /api/providers/management` body. */export async function getManagementGraph() {- requireGraph();+ requireProviderGraph();const [graph, data] = await Promise.all([readGraph(), providerService().getAllProviders()]);// Only the records the graph actually routes: an unmapped legacy provider has// no row to decorate, and resolving a shell invocation for it would be work@@ -278,12 +277,11 @@ export async function getManagementGraph() {// --- link / unlink ------------------------------------------------------------const requireGraph = () => {+export const requireProviderGraph = () => {if (!graphEnabled) {throw new ServerError('Provider connection graph is unavailable on this install', { status: 503, code: 'PROVIDER_GRAPH_UNAVAILABLE' });}};-export const requireProviderGraph = requireGraph;const requireConnection = (graph, ref) => {const connection = findConnectionByRef(graph, ref);@@ -304,7 +302,7 @@ const stale = (what) => new ServerError(* a 409 requiring a fresh preview rather than a last-writer merge.*/async function resolveLink({ bindingId, targetConnectionId = null, expectedRevisions = {} }) {- requireGraph();+ requireProviderGraph();const graph = await readGraph();const binding = graph.bindings.find((candidate) => candidate.id === bindingId);if (!binding) throw new ServerError('Binding not found', { status: 404, code: 'BINDING_NOT_FOUND' });@@ -417,7 +415,7 @@ export function unlinkBinding(input) {// A clone is a second INSTANCE of the same service, so it takes the next// free slug rather than the source's — `uq_ai_connections_slug` would// refuse the copy, and two rows answering to one address is the bug.- const taken = new Set(graph.connections.map((candidate) => candidate.slug).filter(Boolean));+ const taken = takenServiceSlugs(graph.connections);const connection = {...source,id: randomUUID(),@@ -440,7 +438,7 @@ export function unlinkBinding(input) {* still names the row: unlink first, so no binding is ever silently orphaned.*/export async function removeConnection(connectionRef) {- requireGraph();+ requireProviderGraph();return serialize(async () => {const connectionId = requireConnection(await readGraph(), connectionRef).id;const result = await deleteConnection(connectionId);@@ -535,20 +533,6 @@ function requireSettledRoutes(routes) {}}-/**- * A plan must be one the instance's definition sells (#7563). A row with no- * definition takes any plan: there is nothing to check it against, and refusing- * would strand a legacy row a human is trying to label.- */-function requireServicePlan(connection, plan) {- if (plan === undefined) return;- const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;- if (definition && !definition.plans.includes(plan)) {- throw new ServerError(`${definition.label} has no "${plan}" plan; choose one of ${definition.plans.join(', ')}`,- { status: 400, code: 'SERVICE_PLAN_UNSUPPORTED' });- }-}-/** Every binding on a connection, and the executable routes those bindings own. */function connectionFanout(graph, connectionId) {const bindings = graph.bindings.filter((binding) => binding.connectionId === connectionId);@@ -576,11 +560,14 @@ export function updateConnectionSettings({connectionId, expectedRevision, label, transports, credentials, plan, enabled, credentialVia,}) {return serialize(async () => {- requireGraph();+ requireProviderGraph();const graph = await readGraph();const connection = requireConnection(graph, connectionId);if (connection.revision !== expectedRevision) throw stale('The connection');- requireServicePlan(connection, plan);+ const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;+ // A row with no definition takes any plan: there is nothing to check it+ // against, and refusing would strand a legacy row a human is labelling.+ if (plan !== undefined && definition) assertServicePlan(definition, plan);if (credentialVia !== undefined && !SERVICE_CREDENTIAL_VIAS.includes(credentialVia)) {throw new ServerError(`credentialVia must be one of ${SERVICE_CREDENTIAL_VIAS.join(', ')}`,{ status: 400, code: 'PROVIDER_SERVICE_CREDENTIAL_VIA_INVALID' });@@ -625,7 +612,7 @@ export function updateConnectionSettings({*/export function updateBindingSettings({ bindingId, expectedRevision, label, selectedModels }) {return serialize(async () => {- requireGraph();+ requireProviderGraph();const graph = await readGraph();const binding = requireRow(graph.bindings, bindingId, 'Binding', 'BINDING_NOT_FOUND');if (binding.revision !== expectedRevision) throw stale('The binding');@@ -657,7 +644,7 @@ export function updateBindingSettings({ bindingId, expectedRevision, label, sele*/export function refreshConnectionCatalog(connectionRef) {return serialize(async () => {- requireGraph();+ requireProviderGraph();const graph = await readGraph();const connection = requireConnection(graph, connectionRef);const { routes } = connectionFanout(graph, connection.id);@@ -731,7 +718,7 @@ export function refreshConnectionCatalog(connectionRef) {*/export function updateRouteSettings({ providerId, expectedRevision, settings }) {return serialize(async () => {- requireGraph();+ requireProviderGraph();const graph = await readGraph();const route = graph.routes.find((candidate) => candidate.providerId === providerId);if (!route) throw new ServerError('Route not found', { status: 404, code: 'ROUTE_NOT_FOUND' });@@ -810,7 +797,7 @@ export function updateRouteSettings({ providerId, expectedRevision, settings })*/export function updateRouteModelAliases({ providerId, expectedRevision, aliases }) {return serialize(async () => {- requireGraph();+ requireProviderGraph();const graph = await readGraph();const route = graph.routes.find((candidate) => candidate.providerId === providerId);if (!route) throw new ServerError('Route not found', { status: 404, code: 'ROUTE_NOT_FOUND' });@@ -869,11 +856,10 @@ export function updateRouteModelAliases({ providerId, expectedRevision, aliases*/export function createConnection({ kind, label, transports, credentials }) {return serialize(async () => {- requireGraph();+ requireProviderGraph();const blocker = connectionBlocker({ kind, transports });if (blocker) throw new ServerError(blocker.message, { status: 400, code: blocker.code });const graph = await readGraph();- const taken = new Set(graph.connections.map((candidate) => candidate.slug).filter(Boolean));const connection = {id: randomUUID(),revision: 1,@@ -884,7 +870,7 @@ export function createConnection({ kind, label, transports, credentials }) {catalog: { state: 'unknown', models: [] },// Named as a service instance from the start (#7563), so the row is// addressable without waiting for the next reconcile pass.- ...serviceColumnsForConnection({ kind }, { taken }),+ ...serviceColumnsForConnection({ kind }, { taken: takenServiceSlugs(graph.connections) }),enabled: true,credentialVia: 'stored',};@@ -927,7 +913,7 @@ export function createConnection({ kind, label, transports, credentials }) {*/export function createBinding({ connectionId, harnessId, modes, label }) {return serialize(async () => {- requireGraph();+ requireProviderGraph();const graph = await readGraph();const connection = requireConnection(graph, connectionId);diff --git a/server/services/providerServices.js b/server/services/providerServices.jsindex e6f3b3e156..1e98d541fc 100644--- a/server/services/providerServices.js+++ b/server/services/providerServices.js@@ -1,16 +1,17 @@import { randomUUID } from 'node:crypto';import { ServerError } from '../lib/errorHandler.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';-import { sanitizeCatalogError } from '../lib/providerGraphRecords.js';+import { nextConnectionCatalog, sanitizeCatalogError } from '../lib/providerGraphRecords.js';import {allocateServiceSlug,applyServicePlanFilter,credentialSourceFor,kindForDefinition,- nextServiceCatalog,+ storedTransports,+ takenServiceSlugs,toServiceDto,- transportsForDefinition,} from '../lib/providerServiceInstances.js';+import { isNonBlankStr } from '../lib/textUtils.js';import { resolveServiceInstance, serviceDefinitionById } from '../lib/serviceDefinitions.js';import { findConnectionByRef, requireProviderGraph, serializeProviderGraph, updateConnectionSettings } from './providerGraph.js';import { readGraph, saveConnectionSettings, writeGraph } from './providerGraphStore.js';@@ -35,6 +36,11 @@ import { readGraph, saveConnectionSettings, writeGraph } from './providerGraphStconst CATALOG_PROBE_TIMEOUT_MS = 10_000;const ANTHROPIC_VERSION = '2023-06-01';+// Deferred: `credentialInventory.js` is otherwise unreachable from the+// providers route tree, and every suite that reaches the tree would pay its+// closure for a file read only when a service is described (server/AGENTS.md+// "Import scoping").+const loadInstallEnvFile = async () => (await import('./credentialInventory.js')).loadInstallEnvFile();/*** The key an instance runs under, or `''`. A `stored` instance holds it on the@@ -42,10 +48,10 @@ const ANTHROPIC_VERSION = '2023-06-01';* `env` one reads the definition's conventional variable from the process.*/function instanceApiKey(connection, definition, env) {- const names = definition.credential.envVars;- if (connection.credentialVia === 'env') return names.map((name) => env[name]).find((value) => typeof value === 'string' && value !== '') ?? '';+ const firstNamed = (bag) => definition.credential.envVars.map((name) => bag[name]).find(isNonBlankStr) ?? '';+ if (connection.credentialVia === 'env') return firstNamed(env);const stored = connection.credentials || {};- return stored.apiKey ?? names.map((name) => stored[name]).find((value) => typeof value === 'string' && value !== '') ?? '';+ return stored.apiKey ?? firstNamed(stored);}/**@@ -108,12 +114,6 @@ async function listByStrategy(connection, definition, deps) {}}-// Deferred: `credentialInventory.js` is otherwise unreachable from the-// providers route tree, and every suite that reaches the tree would pay its-// closure for a file read only when a service is described (server/AGENTS.md-// "Import scoping").-const loadInstallEnvFile = async () => (await import('./credentialInventory.js')).loadInstallEnvFile();-const defaultDeps = () => ({env: process.env,probe: probeOpenAiModels,@@ -136,70 +136,64 @@ function requireService(graph, ref) {}/** The sanitized DTO for one row, with the derived fields the list also carries. */-function describe(connection, graph, { env, envFile }) {+function describe(connection, graph, envFile) {const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;return toServiceDto(connection, {+ definition,bindingCount: graph.bindings.filter((binding) => binding.connectionId === connection.id).length,- credentialSource: credentialSourceFor({ ...connection, definition }, { env, envFile }),+ credentialSource: credentialSourceFor(connection, { definition, env: process.env, envFile }),});}/** Every instance, sanitized: never a credential value, never a projection snapshot. */-export async function listServices({ env = process.env } = {}) {+export async function listServices() {requireProviderGraph();const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);- return { services: graph.connections.map((connection) => describe(connection, graph, { env, envFile })) };+ return { services: graph.connections.map((connection) => describe(connection, graph, envFile)) };}/** One instance by slug or UUID, sanitized like the list. */-export async function getService(ref, { env = process.env } = {}) {+export async function getService(ref) {requireProviderGraph();const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);- return { service: describe(requireService(graph, ref), graph, { env, envFile }) };+ return { service: describe(requireService(graph, ref), graph, envFile) };}/*** Create an instance FROM a definition — the counterpart of* `createConnection`, which takes a bare kind and transports.*- * The definition decides what is legal (`resolveServiceInstance`: a plan it- * sells, transports it speaks, a well-formed slug), and the row is stored with- * the `kind` reconciliation derives for that definition's records, so the- * next pass judges it exactly as an imported route would be. A `bootstrap`- * instance stores no secret whatever was sent: the launch wrapper supplies it.+ * The definition decides what is legal (`resolveServiceInstance`: a known+ * definition, a plan it sells, transports it speaks — each a typed 400), and+ * the row is stored with the `kind` reconciliation derives for that+ * definition's records, so the next pass judges it exactly as an imported+ * route would be. A `bootstrap` instance stores no secret whatever was sent:+ * the launch wrapper supplies it.** Nothing is probed. The catalog starts `unknown`; discovery is the explicit* `POST /services/:slug/refresh-catalog`.*/export function createService({definitionId, slug, label, plan, enabled = true, transports = {}, credentials = {}, credentialVia = 'stored',-}, { env = process.env } = {}) {+}) {return serializeProviderGraph(async () => {requireProviderGraph();- const definition = serviceDefinitionById(definitionId);- if (!definition) throw new ServerError(`No service definition "${definitionId}"`, { status: 400, code: 'SERVICE_DEFINITION_UNKNOWN' });-- const graph = await readGraph();- const taken = new Set(graph.connections.map((connection) => connection.slug).filter(Boolean));+ const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);+ const taken = takenServiceSlugs(graph.connections);if (slug && taken.has(slug)) {throw new ServerError(`A service is already addressed as "${slug}"`, { status: 409, code: 'SERVICE_SLUG_TAKEN' });}- // The schema bounded the slug's shape and the plan's vocabulary; the one- // refusal left to the definition is a plan it does not sell.- if (plan !== undefined && !definition.plans.includes(plan)) {- throw new ServerError(`${definition.label} has no "${plan}" plan; choose one of ${definition.plans.join(', ')}`,- { status: 400, code: 'SERVICE_PLAN_UNSUPPORTED' });- }const instance = resolveServiceInstance({- definition, slug: slug ?? allocateServiceSlug(definition.id, taken), plan, transports, credentials, credentialVia,+ definitionId, slug: slug ?? allocateServiceSlug(definitionId, taken), plan, transports, credentials, credentialVia,});+ const { definition } = instance;const connection = {id: randomUUID(),revision: 1,kind: kindForDefinition(definition),label: label ?? definition.label,- transports: transportsForDefinition(definition, transports),+ transports: storedTransports(instance),credentials: credentialVia === 'bootstrap' ? {} : credentials,catalog: { state: 'unknown', models: [] },slug: instance.slug,@@ -210,22 +204,22 @@ export function createService({};await writeGraph({ connections: [connection], bindings: [], routes: [] });console.log(`🔗 Created service instance ${connection.slug} (${definition.id}, plan ${connection.plan})`);- return { service: describe(connection, graph, { env, envFile: await loadInstallEnvFile() }) };+ return { service: describe(connection, graph, envFile) };});}/*** Edit an instance: the shared-backend edit (`updateConnectionSettings`, which- * owns the revision gate, the credential merge and the route projection) plus- * plan / enabled / credential mode, then the row read back as a DTO.+ * owns the availability guard, the revision gate, the credential merge and the+ * route projection) plus plan / enabled / credential mode, then the row read+ * back as a DTO.** Not wrapped in a second `serialize`: the inner call already runs on the* queue, and queueing behind it from inside would wait on itself.*/-export async function updateService(ref, input, { env = process.env } = {}) {- requireProviderGraph();+export async function updateService(ref, input) {await updateConnectionSettings({ connectionId: ref, ...input });- return getService(ref, { env });+ return getService(ref);}/**@@ -244,7 +238,7 @@ export function refreshServiceCatalog(ref, deps = {}) {const { env, probe, harnessModels, now } = { ...defaultDeps(), ...deps };return serializeProviderGraph(async () => {requireProviderGraph();- const graph = await readGraph();+ const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);const connection = requireService(graph, ref);const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;if (!definition) {@@ -254,7 +248,7 @@ export function refreshServiceCatalog(ref, deps = {}) {const outcome = await listByStrategy(connection, definition, { env, probe, harnessModels }).catch((err) => ({ refreshed: false, error: err }));- const catalog = nextServiceCatalog(connection.catalog, {+ const catalog = nextConnectionCatalog(connection.catalog, {...outcome,models: outcome.refreshed ? applyServicePlanFilter(definition, connection.plan, outcome.models || []) : undefined,error: outcome.error == null ? null : sanitizeCatalogError(outcome.error, connection.credentials),@@ -263,7 +257,6 @@ export function refreshServiceCatalog(ref, deps = {}) {console.log(`🔗 Refreshed service ${connection.slug ?? connection.id} catalog via ${definition.catalog.strategy}: `+ `${catalog.state}, ${catalog.models.length} models`);- const refreshed = { ...connection, catalog, revision: revision ?? connection.revision };- return { service: describe(refreshed, graph, { env, envFile: await loadInstallEnvFile() }) };+ return { service: describe({ ...connection, catalog, revision: revision ?? connection.revision }, graph, envFile) };});}