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
feat: make each ai_connections row a service instance with a slug, plan and strategy-driven catalog refresh (#7563)
[._.]/ Adam Eivy98b56b2aee41
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex d0ba9ff5d2..ac5574efa6 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -44,7 +44,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.-- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — the AI provider connection graph (#6367, design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`.+- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — the AI provider connection graph (#6367, design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route.- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)diff --git a/server/lib/README.md b/server/lib/README.mdindex 0b3557aba0..bd02688593 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -230,6 +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`. || `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/db/schema/aiGraph.js b/server/lib/db/schema/aiGraph.jsindex cedb39c12a..a8c2e1c77a 100644--- a/server/lib/db/schema/aiGraph.js+++ b/server/lib/db/schema/aiGraph.js@@ -33,6 +33,25 @@ export const aiGraphDdl = [created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,+ // A connection IS a service instance (#7563, epic #7561): a `SERVICE_DEFINITIONS`+ // row (`definition_id`), addressed by a `slug` (the composite-id segment a+ // later slice reads), declared under one of the definition's `plan`s, and+ // switchable off without deleting it (`enabled`). `credential_via` says how+ // the instance authenticates — `stored` (a key on the row), `env`, `cli-login`+ // (the harness signed in) or `bootstrap` (a launch wrapper supplies the key at+ // spawn, so no secret is ever stored). All additive with defaults, so a row+ // written by an older release reads back unchanged and the boot reconcile+ // pass fills `slug` / `definition_id` / `plan` from `kind` — never a seed.+ `ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS slug TEXT`,+ `ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS definition_id TEXT`,+ `ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS plan TEXT NOT NULL DEFAULT 'paid'`,+ `ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS enabled BOOLEAN NOT NULL DEFAULT true`,+ `ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS credential_via TEXT NOT NULL DEFAULT 'stored'`,+ // Partial: a row the backfill has not reached yet carries NULL, and two NULLs+ // never collide, so the index constrains only addressed instances.+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_connections_slug+ ON ai_connections (slug)+ WHERE slug IS NOT NULL`,// One harness configuration on one connection. `harness_id` is NULL only for// a direct API binding, which is why the uniqueness below needs two partialdiff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 54772e3511..38af4c7528 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -681,7 +681,10 @@ describe('deferred imports stay deferred (#6156)', () => {// costs +709 over #7513's 109,282), and the ceiling keeps the ~1.5k of real// headroom this budget exists to carry rather than being pinned to the// measurement.-const MAX_STATIC_INSTANTIATIONS = 111500;+// 111,500 → 111,700 (#7563): `routes/providers.js` gained `providerServices.js`+// and `providerGraph.js` gained `providerServiceInstances.js`, each one file+// deep, plus two new suites.+const MAX_STATIC_INSTANTIATIONS = 111700;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex 3d5da1e9c9..36db407af1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -488,6 +488,7 @@ export * from './providerContextWindows.js';export * from './providerConnections.js';export * from './providerGraphPreview.js';export * from './providerGraphRecords.js';+export * from './providerServiceInstances.js';export * from './providerModelAliases.js';export * from './providerModePairing.js';export * from './providerRouteRecipes.js';diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsindex 8c56da1887..ff42ec4c1f 100644--- a/server/lib/modelPricing.js+++ b/server/lib/modelPricing.js@@ -263,6 +263,13 @@ export function resolveModelRates(providerId, model) {const LOCALHOST_ENDPOINT = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;const FREE_ID = /ollama|lmstudio|lm-studio/i;+// A record derived from a service instance (#7563) carries the plan the user+// DECLARED — `free` / `paid` / `subscription` / `local` — which beats every+// inference below: NVIDIA's free and paid tiers answer on the same endpoint+// with the same model ids, so nothing about the record could tell them apart.+// The string form and legacy records keep the id/endpoint rules.+const FREE_SERVICE_PLANS = new Set(['free', 'local']);+// OpenCode Zen is a free-tier quota, not API billing: the seeded `opencode-zen`// providers (API + CLI/TUI wrappers, see scripts/migrations/336-*) spend a// weekly/monthly allowance, so their rows resolve to $0 on the cost report and@@ -334,8 +341,9 @@ export function isFreeModelId(model) {* True when a provider's usage is free — local inference (Ollama, LM Studio,* any Ollama-/MTPLX-/llama-/vLLM-backed CLI wrapper, or an API provider pointed at localhost),* or a free-tier quota (OpenCode Zen: the `opencode-zen*` provider ids or the- * `opencode.ai/zen` endpoint). Accepts a provider config object or a bare provider-id string- * (usage records can outlive their provider config).+ * `opencode.ai/zen` endpoint). A record carrying a declared `servicePlan`+ * (#7563) answers from that alone. Accepts a provider config object or a bare+ * provider-id string (usage records can outlive their provider config).* @param {object|string|null|undefined} providerOrId* @returns {boolean}*/@@ -343,6 +351,7 @@ export function isFreeProvider(providerOrId) {if (providerOrId == null) return false;if (typeof providerOrId === 'string') return FREE_ID.test(providerOrId) || ZEN_PROVIDER_ID.test(providerOrId);const p = providerOrId;+ if (typeof p.servicePlan === 'string') return FREE_SERVICE_PLANS.has(p.servicePlan);if (p.ollamaBacked === true || p.lmstudioBacked === true || p.mtplxBacked === true || p.llamaBacked === true || p.vllmBacked === true || p.sglangBacked === true) return true;if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;if (ZEN_PROVIDER_ID.test(p.id || '')) return true;diff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.jsindex f72a88c341..d338341c33 100644--- a/server/lib/modelPricing.test.js+++ b/server/lib/modelPricing.test.js@@ -167,6 +167,21 @@ describe('resolveModelRates', () => {});});+describe('isFreeProvider — declared servicePlan (#7563)', () => {+ it('answers from the declared plan alone, ahead of every id and endpoint rule', () => {+ // Two NVIDIA instances: same endpoint, same ids, different plans.+ const nim = { id: 'nvidia-nim', type: 'api', endpoint: 'https://integrate.api.nvidia.com/v1' };+ expect(isFreeProvider({ ...nim, servicePlan: 'free' })).toBe(true);+ expect(isFreeProvider({ ...nim, servicePlan: 'paid' })).toBe(false);+ expect(isFreeProvider({ id: 'ollama-remote', servicePlan: 'local' })).toBe(true);+ expect(isFreeProvider({ id: 'claude-code', command: 'claude', servicePlan: 'subscription' })).toBe(false);+ // A declared paid plan beats an id the regex would have called free.+ expect(isFreeProvider({ id: 'opencode-zen-paid', endpoint: 'https://opencode.ai/zen/v1', servicePlan: 'paid' })).toBe(false);+ // No plan: the legacy inference is untouched.+ expect(isFreeProvider({ id: 'opencode-zen', endpoint: 'https://opencode.ai/zen/v1' })).toBe(true);+ });+});+describe('isFreeProvider', () => {it('classifies ollama and lmstudio ids as free (object and string forms)', () => {expect(isFreeProvider('ollama')).toBe(true);diff --git a/server/lib/openAiModelsProbe.js b/server/lib/openAiModelsProbe.jsindex 1862a19ee9..0b659dfd6a 100644--- a/server/lib/openAiModelsProbe.js+++ b/server/lib/openAiModelsProbe.js@@ -57,7 +57,10 @@ function shortFailureReason(err) {/*** @param {string} baseUrl - an OpenAI-compatible base (…/v1); trailing slashes tolerated- * @param {{timeoutMs?: number, apiKey?: string}} [opts]+ * @param {{timeoutMs?: number, apiKey?: string, headers?: Record<string,string>}} [opts] —+ * `headers` is for a listing that authenticates some other way than a bearer+ * token (the Anthropic API's `x-api-key` + `anthropic-version` pair, #7563);+ * it is merged over the bearer header when both are given.* @returns {Promise<{reachable:boolean, models:string[]|null, contextWindows:Record<string,number>|null, error:string|null}>}* `contextWindows` carries an entry only for a model whose window the listing* actually declared, so `{}` means "nothing declared one" — never "these@@ -65,9 +68,10 @@ function shortFailureReason(err) {* parsing (which key, and smallest-wins when a row declares several) is* `catalogContextWindow`'s rule, shared with model refresh.*/-export async function probeOpenAiModels(baseUrl, { timeoutMs = 2_000, apiKey = '' } = {}) {+export async function probeOpenAiModels(baseUrl, { timeoutMs = 2_000, apiKey = '', headers = {} } = {}) {const url = `${String(baseUrl || '').replace(/\/+$/, '')}/models`;- const init = { method: 'GET', ...(apiKey ? { headers: { Authorization: `Bearer ${apiKey}` } } : {}) };+ const merged = { ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), ...headers };+ const init = { method: 'GET', ...(Object.keys(merged).length > 0 ? { headers: merged } : {}) };const res = await fetchWithTimeout(url, init, timeoutMs)// undici reports every network failure as a bare `TypeError: fetch failed`;// the real reason (ECONNREFUSED vs. ETIMEDOUT — "nothing is listening" vs.diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsindex 2b22b474ad..f4963853c7 100644--- a/server/lib/providerGraphRecords.js+++ b/server/lib/providerGraphRecords.js@@ -15,6 +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';// `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@@ -58,8 +59,16 @@ const catalogSchema = z.object({// (#6369). Optional so rows written before the field existed still parse, and// nullable so a later SUCCESS can clear it without deleting the key.error: z.string().nullable().optional(),+ // Per-model facts a listing declared (#7563) and when it was last asked.+ // Optional for the same reason `error` is: older rows carry neither.+ capabilities: z.record(z.string(), z.object({ contextWindow: z.number().optional() }).strict()).optional(),+ 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({id: z.string().min(1),revision: z.number().int().positive(),@@ -68,6 +77,14 @@ const connectionDtoSchema = z.object({transports: z.record(z.string(), z.object({ baseUrl: z.string().min(1) }).strict()),hasCredentials: z.boolean(),catalog: catalogSchema,+ // The service-instance identity (#7563). Additive, so+ // `PROVIDER_GRAPH_SCHEMA_VERSION` stays at 1 and an older client ignores them.+ // `slug` / `definitionId` are null on a row the boot backfill has not named.+ slug: z.string().nullable(),+ definitionId: z.string().nullable(),+ plan: z.enum(SERVICE_PLANS),+ enabled: z.boolean(),+ credentialVia: z.enum(CREDENTIAL_VIAS),}).strict();const bindingDtoSchema = z.object({@@ -195,14 +212,24 @@ export function toManagementGraphDto({ connections, bindings, routes, activeProvactiveProvider: typeof activeProvider === 'string' ? activeProvider : null,creatableHarnesses: CREATABLE.harnesses,creatableConnectionKinds: CREATABLE.kinds,- connections: connections.map(({ id, revision, kind, label, transports, credentials, catalog }) => ({+ connections: connections.map(({+ id, revision, kind, label, transports, credentials, catalog,+ slug = null, definitionId = null, plan = 'paid', enabled = true, credentialVia = 'stored',+ }) => ({id,revision,kind,label,transports,- hasCredentials: Object.keys(credentials || {}).length > 0,+ // 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,catalog,+ slug,+ definitionId,+ plan,+ enabled,+ credentialVia,})),bindings: bindings.map(({ id, revision, connectionId, harnessId, variantKey, label, enabled, selectedModels }) => ({id, revision, connectionId, harnessId, variantKey, label, enabled, selectedModels, blocked: blocked.has(id),diff --git a/server/lib/providerServiceInstances.js b/server/lib/providerServiceInstances.jsnew file mode 100644index 0000000000..7dd0ba653e--- /dev/null+++ b/server/lib/providerServiceInstances.js@@ -0,0 +1,291 @@+import { z } from 'zod';+import { harnessById } from './providerHarnesses.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).+ *+ * `ai_connections` rows predate `SERVICE_DEFINITIONS`: they carry a `kind`+ * derived from the executable record (`ollama`, `gateway:openrouter`, `api`,+ * `vendor`) and nothing that names the backend as a service. This module is+ * 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.+ *+ * 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.+ */++/** 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']);++const GATEWAY_KIND = 'gateway:';++/**+ * The subscription (or harness-only) service a `vendor` connection stands for.+ *+ * A `vendor` row is one whose executable record names no daemon, no gateway+ * and no bare endpoint — the harness reaches its own cloud. Which cloud is a+ * fact about the HARNESS, so it is read off the harness's capability bindings:+ * the first binding naming a service that composes only onto this harness, or+ * failing that the first named service at all.+ */+function vendorDefinitionId(harnessId) {+ const harness = harnessById(harnessId);+ if (!harness) return null;+ const named = harness.bindings.filter((binding) => typeof binding.service === 'string');+ const own = named.find((binding) => serviceDefinitionById(binding.service)?.harnessOnly === harness.id);+ return (own ?? named[0])?.service ?? null;+}++/**+ * The `SERVICE_DEFINITIONS` id a connection `kind` maps to, or `null` for a+ * kind no definition describes.+ *+ * @param {string} kind - `ollama` | `gateway:<id>` | `api` | `vendor` | …+ * @param {{harnessId?: string|null}} [context] - the harness of a binding on the row+ */+export function definitionIdForKind(kind, { harnessId = null } = {}) {+ if (typeof kind !== 'string' || kind === '') return null;+ if (kind.startsWith(GATEWAY_KIND)) return serviceDefinitionById(kind.slice(GATEWAY_KIND.length))?.id ?? null;+ if (kind === 'api') return 'openai-compatible';+ if (kind === 'vendor') return vendorDefinitionId(harnessId);+ return serviceDefinitionForLocalRuntime(kind)?.id ?? 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.+ */+export function kindForDefinition(definition) {+ if (definition.localRuntime) return definition.localRuntime;+ if (definition.gateway) return `${GATEWAY_KIND}${definition.id}`;+ if (definition.family === 'subscription' || definition.harnessOnly) return 'vendor';+ return 'api';+}++/**+ * A slug not yet in `taken`: `base`, then `base-2`, `base-3`, …+ *+ * `taken` is mutated so one pass over many rows allocates distinct slugs+ * without re-reading the table between them.+ *+ * @param {string} base+ * @param {Set<string>} taken+ */+export function allocateServiceSlug(base, taken) {+ const root = SERVICE_SLUG_RE.test(base) ? base : 'service';+ let candidate = root;+ for (let n = 2; taken.has(candidate); n += 1) candidate = `${root}-${n}`;+ taken.add(candidate);+ return candidate;+}++/**+ * The service columns a row without them should carry.+ *+ * `plan` is the definition's FIRST plan — the same default `resolveServiceInstance`+ * applies — so a backfilled row and a freshly created one agree. A kind no+ * definition describes keeps `definitionId: null` but still gets a slug: the+ * row must stay addressable even when nothing composes onto it.+ *+ * @param {{kind: string}} connection+ * @param {{harnessId?: string|null, taken: Set<string>}} context+ * @returns {{slug: string, definitionId: string|null, plan: string}}+ */+export function serviceColumnsForConnection(connection, { harnessId = null, taken }) {+ const definitionId = definitionIdForKind(connection.kind, { harnessId });+ const definition = definitionId ? serviceDefinitionById(definitionId) : null;+ return {+ slug: allocateServiceSlug(definitionId ?? String(connection.kind || '').replace(GATEWAY_KIND, ''), taken),+ definitionId,+ plan: definition?.plans[0] ?? 'paid',+ };+}++/**+ * 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.+ *+ * @param {{connections: object[], bindings: object[]}} graph+ * @param {Set<string>} [taken] - slugs already allocated in this pass; defaults to the graph's own+ * @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))) {+ return graph.connections+ .filter((connection) => !connection.slug)+ .map((connection) => {+ const harnessId = graph.bindings.find((binding) => binding.connectionId === connection.id)?.harnessId ?? null;+ return { id: connection.id, ...serviceColumnsForConnection(connection, { harnessId, taken }) };+ });+}++/**+ * 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.+ */+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 }]));+}++/** 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.+ *+ * @param {{credentialVia?: string, credentials?: object, definition?: object|null}} instance+ * @param {{env?: Record<string, string|undefined>, envFile?: Map<string, string>|null}} [sources]+ */+export function credentialSourceFor(instance, { env = {}, envFile = null } = {}) {+ const via = instance.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';+}++// --- the sanitized service DTO ---------------------------------------------------++const definitionDtoSchema = z.object({+ id: z.string().min(1),+ label: z.string().min(1),+ family: z.enum(SERVICE_FAMILIES),+ plans: z.array(z.enum(SERVICE_PLANS)).min(1),+ catalogStrategy: z.enum(CATALOG_STRATEGIES),+ harnessOnly: z.string().nullable(),+}).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.+ */+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(),+ 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(),+ 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.+ readiness: z.enum(['ready', 'disabled', 'needs-endpoint', 'needs-credential', 'unknown-definition']),+}).strict();++function serviceReadiness(connection, definition, credentialSource) {+ if (!definition) return 'unknown-definition';+ if (connection.enabled === false) 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';+ // A definition naming no conventional key variable (a bare OpenAI-compatible+ // endpoint) may honestly run keyless, so only a keyed vendor can be waiting on one.+ const needsKey = definition.family === 'api-key' && definition.credential.envVars.length > 0;+ return needsKey && credentialSource === 'none' ? 'needs-credential' : 'ready';+}++/**+ * @param {object} connection - a store row+ * @param {{bindingCount?: number, credentialSource?: string}} [context]+ */+export function toServiceDto(connection, { bindingCount = 0, credentialSource = 'none' } = {}) {+ const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;+ 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,+ } : 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),+ });+}diff --git a/server/lib/providerServiceInstances.test.js b/server/lib/providerServiceInstances.test.jsnew file mode 100644index 0000000000..7dfa8faca6--- /dev/null+++ b/server/lib/providerServiceInstances.test.js@@ -0,0 +1,194 @@+/**+ * The pure service-instance rules (#7563): how an existing connection row is+ * named as an instance (the boot backfill), how a definition round-trips to+ * the `kind` reconciliation judges by, how a refresh outcome becomes a stored+ * catalog, and what the sanitized DTO may carry.+ *+ * The route-level contract (create / list / refresh through the API) lives in+ * `routes/providers.services.test.js`; what is pinned here is the input+ * matrix a route test would have to enumerate one request at a time.+ *+ * Fixtures are synthetic. Nothing here is read out of a running install.+ */+import { describe, expect, it } from 'vitest';+import {+ allocateServiceSlug,+ applyServicePlanFilter,+ credentialSourceFor,+ definitionIdForKind,+ kindForDefinition,+ nextServiceCatalog,+ planServiceColumnBackfill,+ toServiceDto,+} from './providerServiceInstances.js';+import { SERVICE_DEFINITIONS, serviceDefinitionById } from './serviceDefinitions.js';++const row = (overrides = {}) => ({+ id: overrides.id ?? '11111111-1111-4111-8111-111111111111',+ revision: 1,+ kind: 'ollama',+ label: 'Example daemon',+ transports: { openai: { baseUrl: 'http://127.0.0.1:11434/v1' } },+ credentials: {},+ catalog: { state: 'unknown', models: [] },+ slug: null,+ definitionId: null,+ plan: 'paid',+ enabled: true,+ credentialVia: 'stored',+ ...overrides,+});++describe('definitionIdForKind — the backfill rule', () => {+ it('maps every stored kind shape to the definition it stands for', () => {+ expect(definitionIdForKind('ollama')).toBe('ollama');+ expect(definitionIdForKind('gateway:openrouter')).toBe('openrouter');+ expect(definitionIdForKind('api')).toBe('openai-compatible');+ // A vendor row's cloud is a fact about its harness.+ expect(definitionIdForKind('vendor', { harnessId: 'claude' })).toBe('claude-subscription');+ expect(definitionIdForKind('vendor', { harnessId: 'codex' })).toBe('codex-subscription');+ expect(definitionIdForKind('vendor', { harnessId: 'opencode' })).toBe('opencode-zen');+ expect(definitionIdForKind('vendor', { harnessId: 'kimi' })).toBe('kimi');+ });++ it('answers null, never a guess, for a kind no definition describes', () => {+ expect(definitionIdForKind('vendor', { harnessId: null })).toBeNull();+ expect(definitionIdForKind('vendor', { harnessId: 'kilo' })).toBeNull();+ expect(definitionIdForKind('gateway:nope')).toBeNull();+ expect(definitionIdForKind('mystery')).toBeNull();+ expect(definitionIdForKind('')).toBeNull();+ });++ it('inverts kindForDefinition for every definition with a kind of its own', () => {+ // Keyed vendors with a plain endpoint (anthropic, openai, …) all become+ // `api` rows and read back as `openai-compatible` — their identity lives in+ // `definition_id`, which a created row always stores. Everything else must+ // round-trip, or a clone/backfill would rename the service it stands for.+ const own = SERVICE_DEFINITIONS.filter((definition) => definition.localRuntime || definition.gateway+ || definition.family === 'subscription' || definition.harnessOnly);+ expect(own.length).toBeGreaterThan(10);+ for (const definition of own) {+ expect(definitionIdForKind(kindForDefinition(definition), { harnessId: definition.harnessOnly ?? null })).toBe(definition.id);+ }+ expect(kindForDefinition(serviceDefinitionById('anthropic'))).toBe('api');+ });+});++describe('planServiceColumnBackfill', () => {+ it('names only the rows without a slug, with the definition\'s first plan and suffixed collisions', () => {+ const graph = {+ connections: [+ row({ id: 'a', kind: 'ollama', slug: 'ollama', definitionId: 'ollama', plan: 'local' }),+ row({ id: 'b', kind: 'ollama' }),+ row({ id: 'c', kind: 'ollama' }),+ row({ id: 'd', kind: 'gateway:nvidia-nim' }),+ row({ id: 'e', kind: 'vendor' }),+ row({ id: 'f', kind: 'mystery' }),+ ],+ bindings: [{ id: 'bind-e', connectionId: 'e', harnessId: 'claude' }],+ };+ expect(planServiceColumnBackfill(graph)).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.+ { id: 'd', slug: 'nvidia-nim', definitionId: 'nvidia-nim', plan: 'free' },+ { id: 'e', slug: 'claude-subscription', definitionId: 'claude-subscription', plan: 'subscription' },+ // Addressable even when nothing composes onto it.+ { id: 'f', slug: 'mystery', definitionId: null, plan: 'paid' },+ ]);+ });++ 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 named = { connections: graph.connections.map((connection) => ({ ...connection, ...first.find((entry) => entry.id === connection.id) })), bindings: [] };+ expect(planServiceColumnBackfill(named)).toEqual([]);+ expect(planServiceColumnBackfill({ connections: [], bindings: [] })).toEqual([]);+ });++ it('allocates against slugs a caller already handed out in the same pass', () => {+ const taken = new Set(['ollama', 'ollama-2']);+ expect(allocateServiceSlug('ollama', taken)).toBe('ollama-3');+ expect(allocateServiceSlug('Not a slug!', taken)).toBe('service');+ expect(taken.has('ollama-3') && taken.has('service')).toBe(true);+ });+});++describe('plan filter and refresh outcome', () => {+ const zen = serviceDefinitionById('opencode-zen');+ const nim = serviceDefinitionById('nvidia-nim');+ const listing = ['big-pickle', 'mimo-v2.5-free', 'deepseek-v4-flash-free'];++ it('narrows a free plan only where the definition marks its free tier', () => {+ expect(applyServicePlanFilter(zen, 'free', listing)).toEqual(['mimo-v2.5-free', 'deepseek-v4-flash-free']);+ expect(applyServicePlanFilter(zen, 'paid', listing)).toEqual(listing);+ // NIM's listing carries no tier: both plans see everything.+ 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');+ // 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');+ });+});++describe('toServiceDto', () => {+ it('publishes presence, plan and readiness — and never a credential value', () => {+ const dto = toServiceDto(row({+ kind: 'gateway:nvidia-nim', slug: 'nvidia-nim', definitionId: 'nvidia-nim', plan: 'free',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } },+ credentials: { apiKey: 'example-secret-key' },+ }), { bindingCount: 2, credentialSource: 'settings' });+ expect(JSON.stringify(dto)).not.toContain('example-secret-key');+ expect(dto).toMatchObject({+ slug: 'nvidia-nim', plan: 'free', enabled: true, hasCredentials: true, credentialVia: 'stored',+ credentialSource: 'settings', bindingCount: 2, readiness: 'ready',+ definition: { id: 'nvidia-nim', family: 'api-key', plans: ['free', 'paid'], catalogStrategy: 'probe', harnessOnly: null },+ });+ expect(Object.keys(dto)).not.toContain('credentials');+ });++ it('reports a bootstrap instance as holding no credential, and the readiness a card can act on', () => {+ const bootstrap = toServiceDto(row({+ kind: 'api', slug: 'openai', definitionId: 'openai', plan: 'paid', credentialVia: 'bootstrap',+ transports: { openai: { baseUrl: 'https://api.openai.com/v1' } }, credentials: {},+ }), { credentialSource: 'config' });+ expect(bootstrap).toMatchObject({ hasCredentials: false, credentialVia: 'bootstrap', enabled: true, readiness: 'ready' });++ expect(toServiceDto(row({ kind: 'api', definitionId: 'openai', plan: 'paid', credentials: {} }), { credentialSource: 'none' }).readiness)+ .toBe('needs-credential');+ expect(toServiceDto(row({ kind: 'ollama', definitionId: 'ollama', plan: 'local', transports: {} })).readiness).toBe('needs-endpoint');+ expect(toServiceDto(row({ kind: 'ollama', definitionId: 'ollama', plan: 'local', enabled: false })).readiness).toBe('disabled');+ expect(toServiceDto(row({ kind: 'mystery', slug: 'mystery' })).readiness).toBe('unknown-definition');+ // A subscription declares no transport and no key: signed in is ready.+ expect(toServiceDto(row({ kind: 'vendor', definitionId: 'claude-subscription', plan: 'subscription', transports: {}, credentialVia: 'cli-login' }),+ { credentialSource: 'cli' }).readiness).toBe('ready');+ });+});diff --git a/server/lib/serviceDefinitions.test.js b/server/lib/serviceDefinitions.test.jsindex 9e7aec04dc..91de8fd102 100644--- a/server/lib/serviceDefinitions.test.js+++ b/server/lib/serviceDefinitions.test.js@@ -12,6 +12,7 @@ import {SERVICE_DEFINITION_IDS,SERVICE_FAMILIES,SERVICE_PLANS,+ SERVICE_SLUG_RE,resolveServiceInstance,serviceDefinitionById,serviceDefinitionForLocalRuntime,@@ -19,6 +20,8 @@ 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 = [@@ -129,3 +132,15 @@ describe('resolveServiceInstance', () => {expect(() => resolveServiceInstance(input)).toThrow(expect.objectContaining({ code }));});});++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 b89339e0c1..af7ebc93d1 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -692,6 +692,48 @@ export const providerConnectionUpdateSchema = z.object({credentials: z.record(z.string().trim().min(1).max(128), z.string().max(4096).nullable()).optional(),}).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-]*$/, {+ 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']);++const serviceTransportsSchema = z.record(+ z.string().trim().min(1).max(64),+ z.object({ baseUrl: z.string().trim().min(1).max(2048) }).strict(),+);++// POST /api/providers/services — a NEW instance of a definition. The+// definition decides which transports and plans are legal (`resolveServiceInstance`+// in the service), so this bounds shape only. Credentials take no `null`, as+// on the connection create: nothing exists yet to clear.+export const providerServiceCreateSchema = z.object({+ definitionId: z.string().trim().min(1).max(64),+ slug: serviceSlugSchema.optional(),+ label: z.string().trim().min(1).max(200).optional(),+ plan: servicePlanSchema.optional(),+ enabled: z.boolean().optional(),+ transports: serviceTransportsSchema.optional(),+ credentials: z.record(z.string().trim().min(1).max(128), z.string().min(1).max(4096)).optional().default({}),+ credentialVia: serviceCredentialViaSchema.optional(),+}).strict();++// PATCH /api/providers/services/:slug — the connection update plus the+// instance's own plan / enabled / credential mode. Same three-valued+// credential rule, same required `expectedRevision`.+export const providerServiceUpdateSchema = providerConnectionUpdateSchema.extend({+ plan: servicePlanSchema.optional(),+ enabled: z.boolean().optional(),+ credentialVia: serviceCredentialViaSchema.optional(),+}).strict();+// PATCH /api/providers/bindings/:id (#6369). Management state only: no// `enabled`, because route enablement is an executable-record field that// PATCH /api/providers/:id owns and a binding toggle must never grant it.diff --git a/server/routes/providers.connectionCreate.test.js b/server/routes/providers.connectionCreate.test.jsindex c941359b5e..502a05eaba 100644--- a/server/routes/providers.connectionCreate.test.js+++ b/server/routes/providers.connectionCreate.test.js@@ -29,6 +29,7 @@ import { planGraphReconciliation, reconciliationIsNoop } from '../lib/providerGrconst store = {readGraph: vi.fn(),+ applyServiceColumnBackfill: vi.fn().mockResolvedValue(undefined),writeGraph: vi.fn().mockResolvedValue(undefined),applyReconciliation: vi.fn().mockResolvedValue(undefined),commitPendingProjection: vi.fn().mockResolvedValue(undefined),diff --git a/server/routes/providers.connectionManagement.test.js b/server/routes/providers.connectionManagement.test.jsindex 5bc3fd9a95..a9646316e5 100644--- a/server/routes/providers.connectionManagement.test.js+++ b/server/routes/providers.connectionManagement.test.js@@ -24,6 +24,7 @@ import { modelAliasRevision } from '../lib/providerModelAliases.js';const store = {readGraph: vi.fn(),+ applyServiceColumnBackfill: vi.fn().mockResolvedValue(undefined),applyReconciliation: vi.fn().mockResolvedValue(undefined),commitPendingProjection: vi.fn().mockResolvedValue(undefined),acknowledgeProjection: vi.fn().mockResolvedValue(undefined),diff --git a/server/routes/providers.js b/server/routes/providers.jsindex e54d6864eb..f700e9c998 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -15,6 +15,13 @@ import {updateRouteModelAliases,updateRouteSettings,} from '../services/providerGraph.js';+import {+ createService,+ getService,+ listServices,+ refreshServiceCatalog,+ updateService,+} from '../services/providerServices.js';import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';@@ -38,6 +45,8 @@ import {providerBindingUpdateSchema,providerConnectionCreateSchema,providerConnectionUpdateSchema,+ providerServiceCreateSchema,+ providerServiceUpdateSchema,providerRouteModelAliasSchema,providerRouteSettingsUpdateSchema,} from '../lib/validation.js';@@ -469,6 +478,55 @@ export function createPortOSProviderRoutes(aiToolkit) {res.json(await refreshConnectionCatalog(req.params.id));}));+ /**+ * Service INSTANCES (#7563) — the same `ai_connections` rows read as one+ * instance each of a `SERVICE_DEFINITIONS` entry: slug, definition, plan,+ * enabled, how it authenticates, and the catalog it last listed. Sanitized+ * like the graph: credential PRESENCE and SOURCE only, never a value.+ *+ * `:slug` also accepts the row's UUID, and every `/connections/:id` route+ * above accepts a slug, so the two surfaces address one row either way.+ */+ router.get('/services', asyncHandler(async (_req, res) => {+ res.set('Cache-Control', 'no-store').json(await listServices());+ }));++ // Create an instance from a definition. Nothing is probed and no route is+ // minted; the catalog starts `unknown` until the explicit refresh below.+ router.post('/services', asyncHandler(async (req, res) => {+ const input = validateRequest(providerServiceCreateSchema, req.body ?? {});+ res.status(201).json(await createService(input));+ }));++ router.get('/services/:slug', asyncHandler(async (req, res) => {+ res.set('Cache-Control', 'no-store').json(await getService(req.params.slug));+ }));++ // The shared-backend edit plus plan / enabled / credential mode. Same+ // required `expectedRevision`, same three-valued credential rule, same+ // projection into every route on the row.+ router.patch('/services/:slug', asyncHandler(async (req, res) => {+ const input = validateRequest(providerServiceUpdateSchema, req.body ?? {});+ res.json(await updateService(req.params.slug, input));+ }));++ // Refused with a 409 while a binding still names the row — the same rule as+ // the connection delete, because it IS the connection delete.+ router.delete('/services/:slug', asyncHandler(async (req, res) => {+ res.json(await removeConnection(req.params.slug));+ }));++ /**+ * List the instance's models through its DEFINITION's strategy — a probe of+ * its own endpoint with its own key, the local daemon, the program that signs+ * in, or the declared list — filtered to its plan. Needs no executable route.+ * An explicit discovery request: it lists, never generates, and a failure+ * keeps the catalog the instance already had.+ */+ router.post('/services/:slug/refresh-catalog', asyncHandler(async (req, res) => {+ res.json(await refreshServiceCatalog(req.params.slug));+ }));+/*** Edit one harness binding's management state: its label and the subset of* the shared catalog it offers. Never its routes' enablement or consent —diff --git a/server/routes/providers.services.test.js b/server/routes/providers.services.test.jsnew file mode 100644index 0000000000..4f8155314d--- /dev/null+++ b/server/routes/providers.services.test.js@@ -0,0 +1,328 @@+/**+ * Service instances end to end (#7563): real Express route → real Zod schema →+ * the real `providerServices` / `providerGraph` services → a doubled store,+ * toolkit, models probe and harness lister.+ *+ * What only this boundary can pin:+ *+ * - two instances of ONE definition under different plans refresh to+ * different catalogs from one probe answer, and the plan is what decides;+ * - a failed refresh keeps the previous catalog; a harness whose binary is+ * missing reports `failed`, never an empty list; an empty success is `[]`;+ * - a `bootstrap` instance stores nothing whatever was sent;+ * - no response carries a credential value, and the redaction placeholder is+ * refused when echoed back;+ * - a slug and a UUID address the same row on both surfaces.+ *+ * Fixtures are synthetic. Nothing here is read out of a running install.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express, { Router } from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { REDACTED_CREDENTIAL } from '../lib/providerConnections.js';++const store = {+ readGraph: vi.fn(),+ writeGraph: vi.fn().mockResolvedValue({ connections: 1, bindings: 0, routes: 0 }),+ applyReconciliation: vi.fn().mockResolvedValue(undefined),+ applyServiceColumnBackfill: vi.fn().mockResolvedValue(undefined),+ commitPendingProjection: vi.fn().mockResolvedValue(undefined),+ acknowledgeProjection: vi.fn().mockResolvedValue(undefined),+ relinkBinding: vi.fn().mockResolvedValue(undefined),+ deleteConnection: vi.fn(),+ detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+ saveConnectionSettings: vi.fn().mockResolvedValue(2),+ saveBindingSettings: vi.fn().mockResolvedValue(2),+ saveRouteModelMap: vi.fn().mockResolvedValue(undefined),+ saveRouteModelAliases: vi.fn().mockResolvedValue(undefined),+};+vi.mock('../services/providerGraphStore.js', () => store);++const providerService = {+ getAllProviders: vi.fn(),+ applyProviderPatches: vi.fn(),+ refreshProviderModelsBatch: vi.fn(),+};+vi.mock('../lib/aiToolkitState.js', async (importOriginal) => ({+ ...(await importOriginal()),+ requireToolkit: () => ({ services: { providers: providerService } }),+}));++const probe = vi.fn();+vi.mock('../lib/openAiModelsProbe.js', () => ({ probeOpenAiModels: probe }));++const harnessModels = vi.fn();+vi.mock('../services/harnesses.js', () => ({ refreshHarnessModels: harnessModels, harnessCatalogRuntime: vi.fn(() => null) }));++vi.mock('../services/credentialInventory.js', async (importOriginal) => ({+ ...(await importOriginal()),+ loadInstallEnvFile: async () => new Map([['CEREBRAS_API_KEY', 'example-env-file-key']]),+}));++const graph = await import('../services/providerGraph.js');+const { createPortOSProviderRoutes } = await import('./providers.js');++const ZEN_FREE = '11111111-1111-4111-8111-111111111111';+const ZEN_PAID = '22222222-2222-4222-8222-222222222222';+const NIM_FREE = '33333333-3333-4333-8333-333333333333';+const NIM_PAID = '44444444-4444-4444-8444-444444444444';+const CLAUDE_SUB = '55555555-5555-4555-8555-555555555555';+const BOOTSTRAP = '66666666-6666-4666-8666-666666666666';+const LEGACY = '77777777-7777-4777-8777-777777777777';+const BINDING = '88888888-8888-4888-8888-888888888888';+const ZEN_KEY = 'example-zen-secret';++const instance = (overrides) => ({+ revision: 1,+ label: 'Example',+ credentials: {},+ catalog: { state: 'unknown', models: [] },+ enabled: true,+ credentialVia: 'stored',+ ...overrides,+});++const graphFixture = () => ({+ connections: [+ instance({+ id: ZEN_FREE, kind: 'vendor', slug: 'opencode-zen', definitionId: 'opencode-zen', plan: 'free',+ transports: { openai: { baseUrl: 'https://opencode.ai/zen/v1' } }, credentials: { apiKey: ZEN_KEY },+ catalog: { state: 'known', models: ['old-free'] },+ }),+ instance({+ id: ZEN_PAID, kind: 'vendor', slug: 'opencode-zen-2', definitionId: 'opencode-zen', plan: 'paid',+ transports: { openai: { baseUrl: 'https://opencode.ai/zen/v1' } }, credentials: { apiKey: ZEN_KEY },+ }),+ instance({+ id: NIM_FREE, kind: 'gateway:nvidia-nim', slug: 'nvidia-nim', definitionId: 'nvidia-nim', plan: 'free',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } }, credentials: { apiKey: 'example-nim-key' },+ }),+ instance({+ id: NIM_PAID, kind: 'gateway:nvidia-nim', slug: 'nvidia-nim-2', definitionId: 'nvidia-nim', plan: 'paid',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } }, credentials: { apiKey: 'example-nim-key' },+ }),+ instance({+ id: CLAUDE_SUB, kind: 'vendor', slug: 'claude-subscription', definitionId: 'claude-subscription', plan: 'subscription',+ transports: {}, credentialVia: 'cli-login', catalog: { state: 'known', models: ['claude-example'] },+ }),+ instance({+ id: BOOTSTRAP, kind: 'api', slug: 'openai', definitionId: 'openai', plan: 'paid',+ transports: { openai: { baseUrl: 'https://api.openai.com/v1' } }, credentialVia: 'bootstrap',+ }),+ // A row from before the columns existed: no slug, no definition.+ instance({ id: LEGACY, kind: 'api', slug: null, definitionId: null, plan: 'paid', transports: { openai: { baseUrl: 'http://127.0.0.1:9999/v1' } } }),+ ],+ bindings: [{+ id: BINDING, revision: 1, connectionId: NIM_PAID, harnessId: 'opencode',+ variantKey: 'default', label: 'OpenCode', enabled: false, selectedModels: [],+ }],+ routes: [],+});++function app() {+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };+ const server = express();+ server.use(express.json());+ server.use('/api/providers', createPortOSProviderRoutes(toolkit));+ server.use(errorMiddleware);+ return server;+}++beforeEach(async () => {+ vi.clearAllMocks();+ graph.resetProviderGraphState();+ store.readGraph.mockResolvedValue(graphFixture());+ store.saveConnectionSettings.mockResolvedValue(2);+ providerService.getAllProviders.mockResolvedValue({ activeProvider: null, providers: [] });+ providerService.applyProviderPatches.mockImplementation(async (patches) => Object.keys(patches));+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await graph.initProviderGraph();+ vi.clearAllMocks();+ store.readGraph.mockResolvedValue(graphFixture());+ store.saveConnectionSettings.mockResolvedValue(2);+});++afterEach(() => vi.restoreAllMocks());++describe('GET /api/providers/services', () => {+ it('lists every instance with presence and source, and never a credential value', async () => {+ const res = await request(app()).get('/api/providers/services');+ expect(res.status).toBe(200);+ expect(res.text).not.toContain(ZEN_KEY);+ expect(res.text).not.toContain('example-nim-key');+ const bySlug = Object.fromEntries(res.body.services.map((service) => [service.slug, service]));+ expect(bySlug['opencode-zen']).toMatchObject({ plan: 'free', hasCredentials: true, credentialVia: 'stored', credentialSource: 'settings', readiness: 'ready' });+ expect(bySlug['claude-subscription']).toMatchObject({ hasCredentials: false, credentialVia: 'cli-login', credentialSource: 'cli', readiness: 'ready' });+ expect(bySlug.openai).toMatchObject({ hasCredentials: false, credentialVia: 'bootstrap', credentialSource: 'config', enabled: true });+ expect(bySlug['nvidia-nim-2'].bindingCount).toBe(1);+ // The unnamed legacy row is still listed, honestly: no definition yet.+ expect(res.body.services.find((service) => service.id === LEGACY)).toMatchObject({ slug: null, definition: null, readiness: 'unknown-definition' });+ });++ it('names the boot backfill for a row that predates the columns, without a provider call', async () => {+ graph.resetProviderGraphState();+ store.readGraph.mockResolvedValue(graphFixture());+ await graph.initProviderGraph();+ expect(store.applyServiceColumnBackfill).toHaveBeenCalledWith([+ { id: LEGACY, slug: 'openai-compatible', definitionId: 'openai-compatible', plan: 'free' },+ ]);+ expect(probe).not.toHaveBeenCalled();+ expect(harnessModels).not.toHaveBeenCalled();+ });+});++describe('POST /api/providers/services', () => {+ it('creates an instance from a definition with the next free slug, the first plan, and no probe', async () => {+ const res = await request(app()).post('/api/providers/services')+ .send({ definitionId: 'nvidia-nim', credentials: { apiKey: 'example-new-key' } });+ expect(res.status).toBe(201);+ const [written] = store.writeGraph.mock.calls.at(-1);+ expect(written.connections[0]).toMatchObject({+ kind: 'gateway:nvidia-nim', slug: 'nvidia-nim-3', definitionId: 'nvidia-nim', plan: 'free', enabled: true,+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } }, credentials: { apiKey: 'example-new-key' },+ catalog: { state: 'unknown', models: [] },+ });+ expect(res.body.service).toMatchObject({ slug: 'nvidia-nim-3', plan: 'free', hasCredentials: true, readiness: 'ready' });+ expect(res.text).not.toContain('example-new-key');+ expect(probe).not.toHaveBeenCalled();+ });++ it('stores no secret for a bootstrap instance, reports it keyless and enabled', async () => {+ const res = await request(app()).post('/api/providers/services')+ .send({ definitionId: 'anthropic', slug: 'anthropic-wrapped', credentialVia: 'bootstrap', credentials: { apiKey: 'must-not-land' } });+ expect(res.status).toBe(201);+ const [written] = store.writeGraph.mock.calls.at(-1);+ expect(written.connections[0]).toMatchObject({ credentials: {}, credentialVia: 'bootstrap', enabled: true, kind: 'api' });+ expect(res.body.service).toMatchObject({ hasCredentials: false, credentialVia: 'bootstrap', enabled: true, slug: 'anthropic-wrapped' });+ });++ it('refuses a plan the definition does not sell, a taken slug and an unknown definition', async () => {+ expect((await request(app()).post('/api/providers/services').send({ definitionId: 'anthropic', plan: 'free' })).status).toBe(400);+ const taken = await request(app()).post('/api/providers/services').send({ definitionId: 'nvidia-nim', slug: 'nvidia-nim' });+ expect(taken.status).toBe(409);+ expect(taken.body.code).toBe('SERVICE_SLUG_TAKEN');+ expect((await request(app()).post('/api/providers/services').send({ definitionId: 'no-such-service' })).status).toBe(400);+ expect((await request(app()).post('/api/providers/services').send({ definitionId: 'nvidia-nim', slug: 'Not Valid' })).status).toBe(400);+ expect(store.writeGraph).not.toHaveBeenCalled();+ });+});++describe('PATCH /api/providers/services/:slug', () => {+ it('changes the plan and enablement on the row, addressed by slug', async () => {+ const res = await request(app()).patch('/api/providers/services/nvidia-nim')+ .send({ expectedRevision: 1, plan: 'paid', enabled: false });+ expect(res.status).toBe(200);+ expect(store.saveConnectionSettings).toHaveBeenCalledWith(expect.objectContaining({+ id: NIM_FREE, plan: 'paid', enabled: false, credentials: { apiKey: 'example-nim-key' },+ }));+ });++ it('refuses a stale revision, an unsupported plan and an echoed redaction placeholder', async () => {+ expect((await request(app()).patch('/api/providers/services/nvidia-nim').send({ expectedRevision: 9, plan: 'paid' })).status).toBe(409);+ expect((await request(app()).patch(`/api/providers/services/${BOOTSTRAP}`).send({ expectedRevision: 1, plan: 'free' })).status).toBe(400);+ const echoed = await request(app()).patch('/api/providers/services/opencode-zen')+ .send({ expectedRevision: 1, credentials: { apiKey: REDACTED_CREDENTIAL } });+ expect(echoed.status).toBe(400);+ expect(echoed.body.code).toBe('PROVIDER_GRAPH_REDACTED_CREDENTIAL');+ expect(store.saveConnectionSettings).not.toHaveBeenCalled();+ });++ it('drops the stored secret when an instance switches to bootstrap', async () => {+ await request(app()).patch('/api/providers/services/opencode-zen').send({ expectedRevision: 1, credentialVia: 'bootstrap' });+ expect(store.saveConnectionSettings).toHaveBeenCalledWith(expect.objectContaining({ id: ZEN_FREE, credentials: {}, credentialVia: 'bootstrap' }));+ });+});++describe('DELETE /api/providers/services/:slug', () => {+ it('refuses while a binding still names the row, and deletes an unbound one by slug', async () => {+ store.deleteConnection.mockResolvedValueOnce({ deleted: false, reason: 'referenced-by-binding' });+ expect((await request(app()).delete('/api/providers/services/nvidia-nim-2')).status).toBe(409);+ store.deleteConnection.mockResolvedValueOnce({ deleted: true });+ expect((await request(app()).delete('/api/providers/services/nvidia-nim')).status).toBe(200);+ expect(store.deleteConnection).toHaveBeenLastCalledWith(NIM_FREE);+ expect((await request(app()).delete('/api/providers/services/nobody')).status).toBe(404);+ });+});++describe('POST /api/providers/services/:slug/refresh-catalog', () => {+ const listing = ['big-pickle', 'mimo-v2.5-free', 'deepseek-v4-flash-free'];++ it('gives two plans of one definition different catalogs from one probe answer', async () => {+ probe.mockResolvedValue({ reachable: true, models: listing, contextWindows: { 'big-pickle': 128000 }, error: null });+ const free = await request(app()).post('/api/providers/services/opencode-zen/refresh-catalog');+ const paid = await request(app()).post(`/api/providers/services/${ZEN_PAID}/refresh-catalog`);+ expect(free.status).toBe(200);+ expect(free.body.service.catalog).toMatchObject({ state: 'known', models: ['mimo-v2.5-free', 'deepseek-v4-flash-free'], error: null });+ expect(paid.body.service.catalog).toMatchObject({ state: 'known', models: listing, capabilities: { 'big-pickle': { contextWindow: 128000 } } });+ // Its OWN endpoint with its OWN key — never a route's.+ expect(probe).toHaveBeenCalledWith('https://opencode.ai/zen/v1', expect.objectContaining({ apiKey: ZEN_KEY }));+ expect(free.text).not.toContain(ZEN_KEY);+ expect(providerService.refreshProviderModelsBatch).not.toHaveBeenCalled();+ });++ it('lists the whole answer for both NIM plans, where no tier marker exists', async () => {+ probe.mockResolvedValue({ reachable: true, models: listing, contextWindows: {}, error: null });+ const free = await request(app()).post('/api/providers/services/nvidia-nim/refresh-catalog');+ const paid = await request(app()).post('/api/providers/services/nvidia-nim-2/refresh-catalog');+ expect(free.body.service.catalog.models).toEqual(listing);+ expect(paid.body.service.catalog.models).toEqual(listing);+ expect(free.body.service.plan).toBe('free');+ expect(paid.body.service.plan).toBe('paid');+ });++ it('keeps the previous catalog on a failure, with the secret stripped from the reason', async () => {+ probe.mockResolvedValue({ reachable: true, models: null, contextWindows: null, error: `authentication required for ${ZEN_KEY}` });+ const res = await request(app()).post('/api/providers/services/opencode-zen/refresh-catalog');+ expect(res.status).toBe(200);+ expect(res.body.service.catalog).toMatchObject({ state: 'failed', models: ['old-free'] });+ expect(res.body.service.catalog.error).toContain(REDACTED_CREDENTIAL);+ expect(res.body.service.catalog.error).not.toContain(ZEN_KEY);+ expect(store.saveConnectionSettings.mock.calls[0][0].catalog.error).not.toContain(ZEN_KEY);+ });++ it('records a successful empty answer as known-and-empty', async () => {+ probe.mockResolvedValue({ reachable: true, models: [], contextWindows: {}, error: null });+ const res = await request(app()).post('/api/providers/services/opencode-zen/refresh-catalog');+ expect(res.body.service.catalog).toMatchObject({ state: 'known', models: [], error: null });+ });++ it('asks the signing-in program for a harness catalog, and reports a missing binary as failed, never []', async () => {+ harnessModels.mockResolvedValue({ ok: false, reason: 'Claude Code is not installed on this host.', models: [], updated: [] });+ const res = await request(app()).post('/api/providers/services/claude-subscription/refresh-catalog');+ expect(harnessModels).toHaveBeenCalledWith('claude');+ expect(res.body.service.catalog).toMatchObject({ state: 'failed', models: ['claude-example'], error: 'Claude Code is not installed on this host.' });+ expect(probe).not.toHaveBeenCalled();++ harnessModels.mockResolvedValue({ ok: true, models: ['claude-a', 'claude-b'], updated: [] });+ const ok = await request(app()).post('/api/providers/services/claude-subscription/refresh-catalog');+ expect(ok.body.service.catalog).toMatchObject({ state: 'known', models: ['claude-a', 'claude-b'] });+ });++ it('refuses a row with no definition to list through, and 404s an unknown slug', async () => {+ const res = await request(app()).post(`/api/providers/services/${LEGACY}/refresh-catalog`);+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('SERVICE_DEFINITION_UNKNOWN');+ expect((await request(app()).post('/api/providers/services/nobody/refresh-catalog')).status).toBe(404);+ expect(probe).not.toHaveBeenCalled();+ });+});++describe('slug and UUID address one row on both surfaces', () => {+ it('lets the older connection routes take a slug', async () => {+ const res = await request(app()).patch('/api/providers/connections/nvidia-nim')+ .send({ expectedRevision: 1, label: 'Renamed' });+ expect(res.status).toBe(200);+ expect(res.body.connectionId).toBe(NIM_FREE);+ expect(store.saveConnectionSettings).toHaveBeenCalledWith(expect.objectContaining({ id: NIM_FREE, label: 'Renamed' }));+ });++ it('publishes the instance columns on the management graph too', async () => {+ const res = await request(app()).get('/api/providers/management');+ const zen = res.body.connections.find((connection) => connection.id === ZEN_FREE);+ expect(zen).toMatchObject({ slug: 'opencode-zen', definitionId: 'opencode-zen', plan: 'free', enabled: true, credentialVia: 'stored', hasCredentials: true });+ expect(res.body.connections.find((connection) => connection.id === BOOTSTRAP).hasCredentials).toBe(false);+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex cda5a33de6..7d2f6a7d89 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1967,6 +1967,16 @@ CREATE TABLE IF NOT EXISTS ai_connections (created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW());+-- Service-instance columns (#7563): a connection is one instance of a+-- SERVICE_DEFINITIONS row, addressed by slug, under a declared plan.+ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS slug TEXT;+ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS definition_id TEXT;+ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS plan TEXT NOT NULL DEFAULT 'paid';+ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS enabled BOOLEAN NOT NULL DEFAULT true;+ALTER TABLE ai_connections ADD COLUMN IF NOT EXISTS credential_via TEXT NOT NULL DEFAULT 'stored';+CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_connections_slug+ ON ai_connections (slug)+ WHERE slug IS NOT NULL;CREATE TABLE IF NOT EXISTS ai_harness_bindings (id UUID PRIMARY KEY,diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex bbcd2ba183..a5e355c80f 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -40,10 +40,18 @@ import {unsupportedRouteSettings,} from '../lib/providerRouteSettings.js';import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';+import {+ SERVICE_CREDENTIAL_VIAS,+ allocateServiceSlug,+ planServiceColumnBackfill,+ serviceColumnsForConnection,+} from '../lib/providerServiceInstances.js';+import { serviceDefinitionById } from '../lib/serviceDefinitions.js';import { requireToolkit } from '../lib/aiToolkitState.js';import {acknowledgeProjection,applyReconciliation,+ applyServiceColumnBackfill,commitPendingProjection,deleteConnection,detachBindingToConnection,@@ -105,6 +113,22 @@ 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+ * from `/services` can use it on the older surface too. `null` when neither+ * matches — and never a label match.+ */+export const findConnectionByRef = (graph, ref) =>+ graph.connections.find((candidate) => candidate.id === ref || (candidate.slug != null && candidate.slug === ref)) ?? null;+/*** The patch that materializes a connection-owned snapshot into an executable* record. Built from the live record so unknown custom fields and route-owned@@ -138,8 +162,30 @@ async function reconcilePass(reason) {plan.acknowledgements.push(...written.map((providerId) => ({ providerId })));}+ // Service-instance columns (#7563): a row written before they existed, an+ // imported fragment and a detached clone all arrive with no slug. The fresh+ // rows in the plan are named BEFORE it is applied, so they land addressed;+ // 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;+ for (const connection of plan.imports.connections) {+ Object.assign(connection, serviceColumnsForConnection(connection, { harnessId: harnessOf(connection.id, plan.imports.bindings), 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;+ Object.assign(regroup.connection, serviceColumnsForConnection(regroup.connection, { harnessId, taken }));+ }+ const backfill = planServiceColumnBackfill(graph, taken);+const noop = reconciliationIsNoop(plan);if (!noop) await applyReconciliation(plan);+ if (backfill.length > 0) {+ await applyServiceColumnBackfill(backfill);+ console.log(`🔗 Provider graph: named ${backfill.length} service instance(s) (${backfill.map((row) => row.slug).join(', ')})`);+ }const detached = plan.regroups.filter((regroup) => regroup.connectionAction === 'clone').length;const split = plan.regroups.filter((regroup) => !regroup.bindingId).length;@@ -237,6 +283,13 @@ const requireGraph = () => {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);+ if (!connection) throw new ServerError('Connection not found', { status: 404, code: 'CONNECTION_NOT_FOUND' });+ return connection;+};const stale = (what) => new ServerError(`${what} changed since the preview was taken; take a new preview`,@@ -256,9 +309,7 @@ async function resolveLink({ bindingId, targetConnectionId = null, expectedRevisconst binding = graph.bindings.find((candidate) => candidate.id === bindingId);if (!binding) throw new ServerError('Binding not found', { status: 404, code: 'BINDING_NOT_FOUND' });const source = graph.connections.find((candidate) => candidate.id === binding.connectionId) || null;- const target = targetConnectionId- ? graph.connections.find((candidate) => candidate.id === targetConnectionId) || null- : null;+ const target = targetConnectionId ? findConnectionByRef(graph, targetConnectionId) : null;if (targetConnectionId && !target) throw new ServerError('Connection not found', { status: 404, code: 'CONNECTION_NOT_FOUND' });if (target && target.id === binding.connectionId) {throw new ServerError('That binding already uses this connection', { status: 409, code: 'PROVIDER_GRAPH_ALREADY_LINKED' });@@ -362,8 +413,17 @@ export function linkBinding(input) {*/export function unlinkBinding(input) {return serialize(async () => {- const { binding, source } = await resolveLink({ ...input, targetConnectionId: null });- const connection = { ...source, id: randomUUID(), revision: 1 };+ const { graph, binding, source } = await resolveLink({ ...input, targetConnectionId: null });+ // 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 connection = {+ ...source,+ id: randomUUID(),+ revision: 1,+ slug: allocateServiceSlug(source.slug ?? source.definitionId ?? source.kind, taken),+ };await detachBindingToConnection({ bindingId: binding.id, connection });console.log(`🔗 Unlinked binding ${binding.id} onto its own connection ${connection.id}`);return { bindingId: binding.id, connectionId: connection.id };@@ -379,9 +439,10 @@ export function unlinkBinding(input) {* that keeps them from accumulating forever, and it is refused while a binding* still names the row: unlink first, so no binding is ever silently orphaned.*/-export async function removeConnection(connectionId) {+export async function removeConnection(connectionRef) {requireGraph();return serialize(async () => {+ const connectionId = requireConnection(await readGraph(), connectionRef).id;const result = await deleteConnection(connectionId);if (!result.deleted) {throw new ServerError('Unlink the bindings that use this connection first',@@ -474,6 +535,20 @@ 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);@@ -497,12 +572,19 @@ function connectionFanout(graph, connectionId) {* per declared transport and sends them all back: a client that sends a partial* map is asking to remove the rest.*/-export function updateConnectionSettings({ connectionId, expectedRevision, label, transports, credentials }) {+export function updateConnectionSettings({+ connectionId, expectedRevision, label, transports, credentials, plan, enabled, credentialVia,+}) {return serialize(async () => {requireGraph();const graph = await readGraph();- const connection = requireRow(graph.connections, connectionId, 'Connection', 'CONNECTION_NOT_FOUND');+ const connection = requireConnection(graph, connectionId);if (connection.revision !== expectedRevision) throw stale('The connection');+ requireServicePlan(connection, 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' });+ }const { routes } = connectionFanout(graph, connection.id);requireSettledRoutes(routes);@@ -513,11 +595,17 @@ export function updateConnectionSettings({ connectionId, expectedRevision, label{ status: 400, code: 'PROVIDER_GRAPH_REDACTED_CREDENTIAL' });}+ const nextVia = credentialVia ?? connection.credentialVia;const next = {...connection,label: label ?? connection.label,transports: transports ?? connection.transports,- credentials: merged.credentials,+ // A `bootstrap` instance stores no secret by definition: the launch+ // wrapper supplies it at spawn. Switching to it drops whatever was held.+ credentials: nextVia === 'bootstrap' ? {} : merged.credentials,+ plan: plan ?? connection.plan,+ enabled: enabled ?? connection.enabled,+ credentialVia: nextVia,};const revision = await saveConnectionSettings(next);const applied = await projectRoutes(routes.map((route) => route.providerId), next);@@ -567,11 +655,11 @@ export function updateBindingSettings({ bindingId, expectedRevision, label, sele* a backend whose last model was deleted is a real answer, not "never asked".* No pin, default or `activeProvider` is repicked either way.*/-export function refreshConnectionCatalog(connectionId) {+export function refreshConnectionCatalog(connectionRef) {return serialize(async () => {requireGraph();const graph = await readGraph();- const connection = requireRow(graph.connections, connectionId, 'Connection', 'CONNECTION_NOT_FOUND');+ const connection = requireConnection(graph, connectionRef);const { routes } = connectionFanout(graph, connection.id);if (routes.length === 0) {throw new ServerError('This connection has no executable route to probe',@@ -784,6 +872,8 @@ export function createConnection({ kind, label, transports, credentials }) {requireGraph();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,@@ -792,6 +882,11 @@ export function createConnection({ kind, label, transports, credentials }) {transports,credentials: 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 }),+ enabled: true,+ credentialVia: 'stored',};await writeGraph({ connections: [connection], bindings: [], routes: [] });console.log(`🔗 Created provider connection ${connection.id} (${kind}, no routes yet)`);@@ -834,7 +929,7 @@ export function createBinding({ connectionId, harnessId, modes, label }) {return serialize(async () => {requireGraph();const graph = await readGraph();- const connection = requireRow(graph.connections, connectionId, 'Connection', 'CONNECTION_NOT_FOUND');+ const connection = requireConnection(graph, connectionId);// A backend mid-projection is precisely where the graph and providers.json// disagree about the endpoint and credentials this route would be builtdiff --git a/server/services/providerGraph.test.js b/server/services/providerGraph.test.jsindex e25bd01262..855d1685d3 100644--- a/server/services/providerGraph.test.js+++ b/server/services/providerGraph.test.js@@ -16,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const store = {readGraph: vi.fn(),+ applyServiceColumnBackfill: vi.fn().mockResolvedValue(undefined),applyReconciliation: vi.fn().mockResolvedValue(undefined),commitPendingProjection: vi.fn().mockResolvedValue(undefined),acknowledgeProjection: vi.fn().mockResolvedValue(undefined),@@ -278,3 +279,34 @@ describe('deleting an emptied connection', () => {.rejects.toMatchObject({ status: 409, code: 'PROVIDER_GRAPH_CONNECTION_IN_USE' });});});++describe('service-instance naming (#7563)', () => {+ it('gives an unlinked clone the next free slug rather than copying the source\'s', async () => {+ const fixture = graphFixture();+ fixture.connections[0].slug = 'ollama';+ fixture.connections[0].definitionId = 'ollama';+ fixture.connections[1].slug = 'ollama-2';+ store.readGraph.mockResolvedValue(fixture);+ await graph.initProviderGraph();+ await graph.unlinkBinding({ bindingId: BINDING });+ const [[{ connection }]] = store.detachBindingToConnection.mock.calls;+ expect(connection.slug).toBe('ollama-3');+ expect(connection.id).not.toBe(CONN_A);+ expect(connection.definitionId).toBe('ollama');+ });++ it('names a boot-imported fragment before it is written, and backfills unnamed rows after', async () => {+ const fixture = graphFixture();+ // CONN_A predates the columns; CONN_B is already named.+ fixture.connections[1].slug = 'ollama';+ store.readGraph.mockResolvedValue(fixture);+ providers.getAllProviders.mockResolvedValue({+ activeProvider: 'claude-ollama',+ providers: [structuredClone(CLAUDE), { ...structuredClone(CLAUDE), id: 'claude-other', envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:5555', ANTHROPIC_AUTH_TOKEN: 'other' } }],+ });+ await graph.initProviderGraph();+ const [plan] = store.applyReconciliation.mock.calls[0];+ expect(plan.imports.connections[0]).toMatchObject({ kind: 'ollama', slug: 'ollama-2', definitionId: 'ollama', plan: 'local' });+ expect(store.applyServiceColumnBackfill).toHaveBeenCalledWith([{ id: CONN_A, slug: 'ollama-3', definitionId: 'ollama', plan: 'local' }]);+ });+});diff --git a/server/services/providerGraphStore.db.test.js b/server/services/providerGraphStore.db.test.jsindex 376aec1bee..bfde18d81c 100644--- a/server/services/providerGraphStore.db.test.js+++ b/server/services/providerGraphStore.db.test.js@@ -250,4 +250,61 @@ describe.skipIf(!runDb)('ai_* connection graph store', () => {const read = await store.readGraph();expect(read.bindings).toHaveLength(1);});++ describe('service-instance columns (#7563)', () => {+ it('round-trips the columns and refuses two rows on one slug', async () => {+ const conn = connection({ slug: 'ollama', definitionId: 'ollama', plan: 'local', enabled: false, credentialVia: 'env' });+ await store.writeGraph({ connections: [conn], bindings: [], routes: [] });+ const [read] = (await store.readGraph()).connections;+ expect(read).toMatchObject({ slug: 'ollama', definitionId: 'ollama', plan: 'local', enabled: false, credentialVia: 'env' });++ await expect(store.writeGraph({ connections: [connection({ slug: 'ollama' })], bindings: [], routes: [] }))+ .rejects.toThrow(/uq_ai_connections_slug|duplicate key/i);+ });++ it('reads a row written without the columns with their defaults, and backfills it exactly once', async () => {+ const conn = connection();+ await store.writeGraph({ connections: [conn], bindings: [], routes: [] });+ let [read] = (await store.readGraph()).connections;+ // A pre-#7563 row: unnamed, on the column defaults — nothing else changed.+ expect(read).toMatchObject({ slug: null, definitionId: null, plan: 'paid', enabled: true, credentialVia: 'stored', revision: 1 });+ expect(read.transports).toEqual(conn.transports);+ expect(read.credentials).toEqual(conn.credentials);+ expect(read.catalog).toEqual(conn.catalog);++ await store.applyServiceColumnBackfill([{ id: conn.id, slug: 'ollama', definitionId: 'ollama', plan: 'local' }]);+ [read] = (await store.readGraph()).connections;+ expect(read).toMatchObject({ slug: 'ollama', definitionId: 'ollama', plan: 'local', revision: 1 });+ expect(read.credentials).toEqual(conn.credentials);++ // A re-run must not rename a row that is already named.+ await store.applyServiceColumnBackfill([{ id: conn.id, slug: 'ollama-9', definitionId: 'ollama', plan: 'local' }]);+ [read] = (await store.readGraph()).connections;+ expect(read.slug).toBe('ollama');+ // And an empty table plans and creates nothing.+ await store.applyServiceColumnBackfill([]);+ });++ it('preserves the instance columns when a regroup re-upserts the row without them', async () => {+ const conn = connection({ slug: 'ollama', definitionId: 'ollama', plan: 'local', enabled: false, credentialVia: 'bootstrap' });+ await store.writeGraph({ connections: [conn], bindings: [], routes: [] });+ // What `planGraphReconciliation` hands `applyReconciliation` for an+ // in-place update: the connection-owned values and nothing about the slug.+ const { slug, definitionId, plan, enabled, credentialVia, ...bare } = conn;+ await store.writeGraph({ connections: [{ ...bare, label: 'Renamed by reconcile' }], bindings: [], routes: [] });+ const [read] = (await store.readGraph()).connections;+ expect(read).toMatchObject({ label: 'Renamed by reconcile', slug: 'ollama', definitionId: 'ollama', plan: 'local', enabled: false, credentialVia: 'bootstrap' });+ });++ it('writes plan, enabled and credential mode through the settings save, and leaves them alone when unnamed', async () => {+ const conn = connection({ slug: 'ollama', definitionId: 'ollama', plan: 'local' });+ await store.writeGraph({ connections: [conn], bindings: [], routes: [] });+ await store.saveConnectionSettings({ ...conn, plan: 'local', enabled: false, credentialVia: 'cli-login' });+ let [read] = (await store.readGraph()).connections;+ expect(read).toMatchObject({ enabled: false, credentialVia: 'cli-login', revision: 2 });+ await store.saveConnectionSettings({ ...conn, label: 'Only the label' });+ [read] = (await store.readGraph()).connections;+ expect(read).toMatchObject({ label: 'Only the label', enabled: false, credentialVia: 'cli-login', plan: 'local' });+ });+ });});diff --git a/server/services/providerGraphStore.js b/server/services/providerGraphStore.jsindex 8b80e441e2..8ad1805069 100644--- a/server/services/providerGraphStore.js+++ b/server/services/providerGraphStore.js@@ -30,6 +30,13 @@ const connectionRow = (row) => ({transports: row.transports || {},credentials: row.credentials || {},catalog: row.catalog || { state: 'unknown', models: [] },+ // Service-instance columns (#7563). `slug` / `definitionId` are null on a+ // row the boot backfill has not reached; the rest carry column defaults.+ slug: row.slug ?? null,+ definitionId: row.definition_id ?? null,+ plan: row.plan ?? 'paid',+ enabled: row.enabled !== false,+ credentialVia: row.credential_via ?? 'stored',});const bindingRow = (row) => ({@@ -68,17 +75,32 @@ export async function readGraph() {};}+// The service columns (#7563) are PRESERVED on conflict when the caller did not+// name them: a reconciliation regroup rebuilds a connection from its routes and+// knows nothing about the slug a human addresses it by, and `plan` / `enabled`+// / `credential_via` are NOT NULL, so the insert half substitutes the column+// default rather than a NULL the constraint would refuse before the conflict+// clause could run.const upsertConnection = (client, connection) => client.query(- `INSERT INTO ai_connections (id, revision, kind, label, transports, credentials, catalog, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())+ `INSERT INTO ai_connections+ (id, revision, kind, label, transports, credentials, catalog, slug, definition_id, plan, enabled, credential_via, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10, 'paid'), COALESCE($11, true), COALESCE($12, 'stored'), NOW())ON CONFLICT (id) DO UPDATE SETrevision = ai_connections.revision + 1,kind = EXCLUDED.kind, label = EXCLUDED.label,transports = EXCLUDED.transports, credentials = EXCLUDED.credentials,- catalog = EXCLUDED.catalog, updated_at = NOW()`,+ catalog = EXCLUDED.catalog,+ slug = COALESCE($8, ai_connections.slug),+ definition_id = COALESCE($9, ai_connections.definition_id),+ plan = COALESCE($10, ai_connections.plan),+ enabled = COALESCE($11, ai_connections.enabled),+ credential_via = COALESCE($12, ai_connections.credential_via),+ updated_at = NOW()`,[connection.id, connection.revision ?? 1, connection.kind, connection.label ?? '',JSON.stringify(connection.transports || {}), JSON.stringify(connection.credentials || {}),- JSON.stringify(connection.catalog || { state: 'unknown', models: [] })],+ JSON.stringify(connection.catalog || { state: 'unknown', models: [] }),+ connection.slug ?? null, connection.definitionId ?? null, connection.plan ?? null,+ typeof connection.enabled === 'boolean' ? connection.enabled : null, connection.credentialVia ?? null],);const upsertBinding = (client, binding) => client.query(@@ -269,19 +291,41 @@ export async function deleteConnection(connectionId) {** @returns {Promise<number|null>} the new revision, or `null` if the row is gone*/-export async function saveConnectionSettings({ id, label, transports, credentials, catalog }) {+export async function saveConnectionSettings({ id, label, transports, credentials, catalog, plan, enabled, credentialVia }) {const { rows } = await query(`UPDATE ai_connectionsSET label = $2, transports = $3, credentials = $4, catalog = $5,+ plan = COALESCE($6, plan), enabled = COALESCE($7, enabled),+ credential_via = COALESCE($8, credential_via),revision = revision + 1, updated_at = NOW()WHERE id = $1RETURNING revision`,[id, label ?? '', JSON.stringify(transports || {}), JSON.stringify(credentials || {}),- JSON.stringify(catalog || { state: 'unknown', models: [] })],+ JSON.stringify(catalog || { state: 'unknown', models: [] }),+ plan ?? null, typeof enabled === 'boolean' ? enabled : null, credentialVia ?? null],);return rows[0]?.revision ?? null;}+/**+ * Fill the service-instance columns on rows that have none (#7563) — the+ * boot-time backfill planned by `planServiceColumnBackfill`. No revision bump:+ * nothing a human edited changed, and a stale-revision 409 on the first read+ * after upgrade would be a lie.+ */+export async function applyServiceColumnBackfill(entries) {+ if (entries.length === 0) return;+ await withTransaction(async (client) => {+ for (const { id, slug, definitionId, plan } of entries) {+ await client.query(+ `UPDATE ai_connections SET slug = $2, definition_id = $3, plan = $4, updated_at = NOW()+ WHERE id = $1 AND slug IS NULL`,+ [id, slug, definitionId, plan],+ );+ }+ });+}+/*** Write a binding's management settings and bump its revision.*diff --git a/server/services/providerServices.js b/server/services/providerServices.jsnew file mode 100644index 0000000000..e6f3b3e156--- /dev/null+++ b/server/services/providerServices.js@@ -0,0 +1,269 @@+import { randomUUID } from 'node:crypto';+import { ServerError } from '../lib/errorHandler.js';+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';+import { sanitizeCatalogError } from '../lib/providerGraphRecords.js';+import {+ allocateServiceSlug,+ applyServicePlanFilter,+ credentialSourceFor,+ kindForDefinition,+ nextServiceCatalog,+ toServiceDto,+ transportsForDefinition,+} from '../lib/providerServiceInstances.js';+import { resolveServiceInstance, serviceDefinitionById } from '../lib/serviceDefinitions.js';+import { findConnectionByRef, requireProviderGraph, serializeProviderGraph, updateConnectionSettings } from './providerGraph.js';+import { readGraph, saveConnectionSettings, writeGraph } from './providerGraphStore.js';++/**+ * Service INSTANCES over the provider connection graph (#7563, epic #7561).+ *+ * An `ai_connections` row is one instance of a `SERVICE_DEFINITIONS` row: a+ * slug it is addressed by, the plan the user declared, how it authenticates,+ * and the catalog it last listed. This module is the management surface for+ * that reading of the row — list, create from a definition, refresh the catalog+ * through the DEFINITION's listing strategy — while the row itself stays the+ * connection every existing graph operation already handles. Edits and deletes+ * go through `providerGraph.js` unchanged, addressed by slug.+ *+ * Every mutation runs on the graph's serialization queue. **No provider is+ * contacted except by the explicit refresh** (AGENTS.md "No cold-bootstrap LLM+ * calls"): listing and creating are local I/O only.+ */++/** Hosted APIs answer `/models` slower than a loopback daemon; the probe default is tuned for the latter. */+const CATALOG_PROBE_TIMEOUT_MS = 10_000;+const ANTHROPIC_VERSION = '2023-06-01';+++/**+ * The key an instance runs under, or `''`. A `stored` instance holds it on the+ * row (under `apiKey`, or under the env var name a route-derived row kept); an+ * `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 stored = connection.credentials || {};+ return stored.apiKey ?? names.map((name) => stored[name]).find((value) => typeof value === 'string' && value !== '') ?? '';+}++/**+ * GET `/models` on the instance's own endpoint with its own key.+ *+ * Serves both `probe` (a hosted API) and `daemon` (a local runtime): the+ * runtime managers list the INSTALL's configured daemon, not the row's+ * endpoint, and an instance pointed at a second daemon would be answered for+ * by the first. The row names where it is; that is what gets asked.+ *+ * `reachable: true, models: null` (an unreadable listing, or a 401) is a+ * FAILED refresh, never an empty one — the three-state probe is what lets+ * "answered nothing" and "could not answer" stay apart.+ */+async function listByProbe(connection, definition, { env, probe }) {+ const apiKey = instanceApiKey(connection, definition, env);+ const openai = connection.transports?.openai?.baseUrl;+ const anthropic = connection.transports?.anthropic?.baseUrl;+ if (!openai && !anthropic) return { refreshed: false, error: 'This service declares no endpoint to list models from' };++ const result = openai+ ? await probe(openai, { apiKey, timeoutMs: CATALOG_PROBE_TIMEOUT_MS })+ // The Anthropic API lists at `/v1/models` under its own header pair.+ : await probe(`${anthropic.replace(/\/+$/, '')}/v1`, {+ timeoutMs: CATALOG_PROBE_TIMEOUT_MS,+ headers: { ...(apiKey ? { 'x-api-key': apiKey } : {}), 'anthropic-version': ANTHROPIC_VERSION },+ });+ if (!Array.isArray(result.models)) return { refreshed: false, error: result.error || 'The model listing was not readable' };+ return { refreshed: true, models: result.models, contextWindows: result.contextWindows };+}++/**+ * Ask the program that signs in. `ok: false` — an uninstalled binary, a+ * signed-out CLI, a refused probe — is a failure with its reason, never an+ * empty catalog: `refreshHarnessModels` already refuses to report a blank+ * listing as "zero models", and this keeps that refusal.+ */+async function listByHarness(definition, { harnessModels }) {+ const result = await harnessModels(definition.harnessOnly);+ if (!result?.ok) return { refreshed: false, error: result?.reason || `${definition.label} could not list its models` };+ return { refreshed: true, models: result.models || [] };+}++/**+ * One strategy dispatch, as `definition.catalog.strategy` names it. `static`+ * has nothing to ask: the instance's declared list IS the catalog, re-stamped+ * as known.+ */+async function listByStrategy(connection, definition, deps) {+ switch (definition.catalog.strategy) {+ case 'probe':+ case 'daemon':+ return listByProbe(connection, definition, deps);+ case 'harness':+ return listByHarness(definition, deps);+ case 'static':+ return { refreshed: true, models: connection.catalog?.models || [] };+ default:+ return { refreshed: false, error: `Unknown catalog strategy "${definition.catalog.strategy}"` };+ }+}++// 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,+ // The harness registry names programs by harness id (`antigravity`,+ // `cursor`); the runtime table lists them by binary (`agy`, `cursor-agent`)+ // with the harness id as its `vendor`. Resolve through the vendor so every+ // harness-only definition reaches its lister.+ harnessModels: async (harnessId) => {+ const [{ refreshHarnessModels }, { PROVIDER_RUNTIMES }] = await Promise.all([import('./harnesses.js'), import('./providerRuntimeInstaller.js')]);+ const runtime = PROVIDER_RUNTIMES.find((row) => row.vendor === harnessId || row.id === harnessId)?.id ?? harnessId;+ return refreshHarnessModels(runtime);+ },+ now: () => new Date().toISOString(),+});++function requireService(graph, ref) {+ const connection = findConnectionByRef(graph, ref);+ if (!connection) throw new ServerError('Service not found', { status: 404, code: 'SERVICE_NOT_FOUND' });+ return connection;+}++/** The sanitized DTO for one row, with the derived fields the list also carries. */+function describe(connection, graph, { env, envFile }) {+ const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;+ return toServiceDto(connection, {+ bindingCount: graph.bindings.filter((binding) => binding.connectionId === connection.id).length,+ credentialSource: credentialSourceFor({ ...connection, definition }, { env, envFile }),+ });+}++/** Every instance, sanitized: never a credential value, never a projection snapshot. */+export async function listServices({ env = process.env } = {}) {+ requireProviderGraph();+ const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);+ return { services: graph.connections.map((connection) => describe(connection, graph, { env, envFile })) };+}++/** One instance by slug or UUID, sanitized like the list. */+export async function getService(ref, { env = process.env } = {}) {+ requireProviderGraph();+ const [graph, envFile] = await Promise.all([readGraph(), loadInstallEnvFile()]);+ return { service: describe(requireService(graph, ref), graph, { env, 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.+ *+ * 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));+ 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,+ });++ const connection = {+ id: randomUUID(),+ revision: 1,+ kind: kindForDefinition(definition),+ label: label ?? definition.label,+ transports: transportsForDefinition(definition, transports),+ credentials: credentialVia === 'bootstrap' ? {} : credentials,+ catalog: { state: 'unknown', models: [] },+ slug: instance.slug,+ definitionId: definition.id,+ plan: instance.plan,+ enabled,+ credentialVia,+ };+ 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() }) };+ });+}++/**+ * 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.+ *+ * 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();+ await updateConnectionSettings({ connectionId: ref, ...input });+ return getService(ref, { env });+}++/**+ * Refresh one instance's catalog through its DEFINITION's listing strategy —+ * the whole point of the instance owning its catalog: it no longer needs an+ * executable route to have something to probe.+ *+ * The plan filter runs before the catalog rule, so two instances of one+ * definition under different plans list different models from one answer+ * (OpenCode Zen `free` keeps only `*-free`). Then `nextConnectionCatalog`'s+ * contract holds unchanged: a failure keeps what was known with a sanitized+ * reason, a successful empty answer is `known` and empty. No pin, default or+ * route model list is touched.+ */+export function refreshServiceCatalog(ref, deps = {}) {+ const { env, probe, harnessModels, now } = { ...defaultDeps(), ...deps };+ return serializeProviderGraph(async () => {+ requireProviderGraph();+ const graph = await readGraph();+ const connection = requireService(graph, ref);+ const definition = connection.definitionId ? serviceDefinitionById(connection.definitionId) : null;+ if (!definition) {+ throw new ServerError('This service has no definition to list models through; use the connection refresh',+ { status: 409, code: 'SERVICE_DEFINITION_UNKNOWN' });+ }++ const outcome = await listByStrategy(connection, definition, { env, probe, harnessModels })+ .catch((err) => ({ refreshed: false, error: err }));+ const catalog = nextServiceCatalog(connection.catalog, {+ ...outcome,+ models: outcome.refreshed ? applyServicePlanFilter(definition, connection.plan, outcome.models || []) : undefined,+ error: outcome.error == null ? null : sanitizeCatalogError(outcome.error, connection.credentials),+ }, { now });+ const revision = await saveConnectionSettings({ ...connection, catalog });++ 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() }) };+ });+}diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 642a8e406e..4f510bb641 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -1296,6 +1296,38 @@ describe('buildUsageReport — local models under a paid provider', () => {});});+describe('buildUsageReport — a declared service plan (#7563)', () => {+ // One NVIDIA endpoint, two instances: the record's declared plan is the ONLY+ // thing that separates the free tier from metered use, so the report must+ // bill from it — through the report, not the predicate.+ const nim = (id, servicePlan) => ({ id, name: id, type: 'api', endpoint: 'https://integrate.api.nvidia.com/v1', servicePlan });+ const dayFor = (providerId) => ({+ '2026-07-02': {+ sessions: 1, messages: 1,+ byProvider: {+ [providerId]: {+ name: providerId, sessions: 1, messages: 1, tokensIn: 0, tokensOut: 1_000_000,+ cacheReadTokens: 0, cacheWriteTokens: 0, source: 'measured',+ byModel: { 'meta/llama-example-70b': { sessions: 1, messages: 1, tokensIn: 0, tokensOut: 1_000_000, cacheReadTokens: 0, cacheWriteTokens: 0, source: 'measured' } }+ }+ }+ }+ });++ it('attributes a free-plan instance as free and a paid-plan one as metered', () => {+ const free = buildUsageReport(dayFor('nim-free'), { providers: [nim('nim-free', 'free')] });+ expect(free.totals.estimatedCost).toBe(0);+ expect(free.providers[0].free).toBe(true);++ const paid = buildUsageReport(dayFor('nim-paid'), { providers: [nim('nim-paid', 'paid')] });+ expect(paid.totals.estimatedCost).toBeGreaterThan(0);+ expect(paid.providers[0].free).toBe(false);++ const local = buildUsageReport(dayFor('remote-daemon'), { providers: [{ ...nim('remote-daemon', 'local'), endpoint: 'http://daemon.example.com:11434/v1' }] });+ expect(local.totals.estimatedCost).toBe(0);+ });+});+describe('usage.js — limit-block ledger (#7408)', () => {beforeEach(async () => {vi.useFakeTimers();