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
fix: fold duplicate AI service instances into one service per backend
[._.]/ Adam Eivy8d5dd72f390d
diff --git a/docs/PROVIDER_COMPOSITION.md b/docs/PROVIDER_COMPOSITION.mdindex eb7ff19768..badb5f02dd 100644--- a/docs/PROVIDER_COMPOSITION.md+++ b/docs/PROVIDER_COMPOSITION.md@@ -80,6 +80,8 @@ A record without the three keys is a **legacy preset**: fully hand-editable and**Backfill.** The boot reconcile pass (`reconcilePass` in `server/services/providerGraph.js`) stamps every legacy record the graph already routes onto a named service instance, under the same fixpoint rule (`planPresetBackfill`, `server/lib/providerPresets.js`): additive keys only, idempotent, row-derived and never a seed — so it rides every pass rather than a numbered migration, exactly as the service-column backfill does. A record whose re-derivation would change how it runs stays legacy, with the reason logged in aggregate: a path-configured binary, a wrapper that stores no gateway key, an inline bootstrap matching no configured app, a legacy per-gateway marker, a service that has not been given the credential its harness requires. Of the 55 shipped samples, 37 are stamped on first boot.+**One service per backend.** The graph import gives every harness its own connection, so an install running `nvidia-nim` (direct API) beside `opencode-nvidia-nim` (an OpenCode wrapper on the same endpoint) arrives with two NVIDIA NIM services, one named after the harness. The same reconcile pass then folds such rows into one instance (`planServiceInstanceMerges`, `server/lib/providerServiceMerge.js`): the rows must be the same definition — a generic `openai-compatible` row on a named definition's default endpoint counts as that definition — and share an endpoint, credential mode, plan and non-conflicting credentials, and every preset on them must re-derive onto the survivor with its model list unchanged. The survivor keeps its slug and takes the service's name; derived presets are re-pointed to it before the folded row is deleted. Two plans of one definition stay two instances, as does a row no harness is bound to yet. A saved composite id naming a folded slug resolves as an unresolved pin, never a substitute.+**Graph.** A derived preset is imported ONTO the connection it declares (`presetDeclaresConnection`), never as a fragment of its own, and stays there across passes even where profile containment would move it — a direct-API preset on a gateway instance reads back as kind `api`, not `gateway:<id>`. So a service edit re-projects it through the same pending/projected snapshot protocol as any route, and additionally re-runs the full materialization (`rematerializeDerivedPresets`) so the inline config, catalog and bootstrap follow the row too; a catalog refresh re-derives `models`; a link or unlink re-addresses `serviceId` to the instance the binding landed on.## Peersdiff --git a/server/lib/README.md b/server/lib/README.mdindex 62997ba53f..ae625a335b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -248,6 +248,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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; `takenServiceSlugs` is the set every allocation avoids; `storedTransports` is the transports map a new instance's row stores; `applyServicePlanFilter` narrows a listing to a plan; `credentialSourceFor` reports where an instance's credential comes from (`settings`, `env-file`, `env`, `cli`, `config`, `none`, the inventory's own precedence) without a value; `instanceApiKeyFor(connection, definition, env)` is the key it RUNS under (`stored` → the row, `env` → the definition's conventional variable, else none), shared by the catalog refresh and the composite resolver (#7564); `toServiceDto` (`serviceDtoSchema`, the connection DTO extended, strict) is the sanitized `GET /api/providers/services` row with a one-word `readiness`. |+| `providerServiceMerge.js` | Folds duplicate SERVICE INSTANCES into one (epic #7561) — the graph import gave each harness its own connection, so `opencode-nvidia-nim` and `nvidia-nim` became two NVIDIA NIM services. `planServiceInstanceMerges(graph, providers)` groups rows by definition (a generic `openai-compatible` row on a named definition's default endpoint counts as that definition), folds those sharing an endpoint, credential mode, plan and non-conflicting credentials whose legacy routes stay contained, and picks the survivor and its label; `presetPatchesForMerge` re-derives the derived presets onto the survivor, keeping each preset's model list. Pure; the reconcile pass (`providerGraph.js`) applies it. || `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/index.js b/server/lib/index.jsindex ad4a6fc041..cda8238296 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -528,6 +528,7 @@ export * from './providerConnections.js';export * from './providerGraphPreview.js';export * from './providerGraphRecords.js';export * from './providerServiceInstances.js';+export * from './providerServiceMerge.js';export * from './providerModelAliases.js';export * from './providerModePairing.js';export * from './providerPresets.js';diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsindex a7296f6bb3..fd25489dc8 100644--- a/server/lib/providerGraphRecords.js+++ b/server/lib/providerGraphRecords.js@@ -293,6 +293,17 @@ const identityKey = ({ kind, transports, credentials }) => JSON.stringify([Object.entries(credentials || {}).sort(([a], [b]) => a.localeCompare(b)),]);+/**+ * Whether a route of backend kind `routeKind` may sit on a connection of+ * `connectionKind`. Equal kinds, plus one widening: a direct `api` record reads+ * back as kind `api` even when its endpoint IS a hosted gateway's (the shipped+ * `nvidia-nim` record holds the key its OpenCode wrappers use), so a `gateway:`+ * service instance may hold it. The transport and credential checks below still+ * have to pass — the kind alone never places a route.+ */+const routeKindFitsConnection = (routeKind, connectionKind) => routeKind === connectionKind+ || (routeKind === 'api' && typeof connectionKind === 'string' && connectionKind.startsWith('gateway:'));+/*** Whether a stored connection still CONTAINS the backend a route describes.*@@ -306,7 +317,8 @@ const identityKey = ({ kind, transports, credentials }) => JSON.stringify([** Containment, precisely:*- * - `kind` matches exactly — a route never migrates between backend kinds.+ * - `kind` matches — a route never migrates between backend kinds, save a+ * direct `api` record on a `gateway:` instance ({@link routeKindFitsConnection}).* - The route's transport protocol is DECLARED by the connection at the same* `baseUrl`. A route declaring no transport at all matches only a* connection that declares none either: "names no endpoint" must never@@ -324,7 +336,7 @@ const identityKey = ({ kind, transports, credentials }) => JSON.stringify([* reconciliation pass will judge it by.*/export function routeBelongsOnConnection(profile, connection) {- if (!connection || profile.kind !== connection.kind) return false;+ if (!connection || !routeKindFitsConnection(profile.kind, connection.kind)) return false;const declared = connection.transports || {};const transports = Object.entries(profile.transports || {});if (transports.length === 0) return Object.keys(declared).length === 0;diff --git a/server/lib/providerServiceMerge.js b/server/lib/providerServiceMerge.jsnew file mode 100644index 0000000000..6b3db785dc--- /dev/null+++ b/server/lib/providerServiceMerge.js@@ -0,0 +1,256 @@+import { isDeepStrictEqual } from 'node:util';+import { providerConnectionProfile } from './providerConnections.js';+import { isDerivedPreset, routeBelongsOnConnection } from './providerGraphRecords.js';+import { harnessById } from './providerHarnesses.js';+import { bootstrapInputFor, derivedPresetPatch, listedModels, materializeDerivedPreset } from './providerPresets.js';+import { instanceApiKeyFor, instanceForConnection } from './providerServiceInstances.js';+import { SERVICE_DEFINITIONS, serviceDefinitionById } from './serviceDefinitions.js';++/**+ * Fold duplicate SERVICE INSTANCES into one (epic #7561, D2/D3).+ *+ * The graph import (#6366) gives every harness its own connection — sharing+ * across harnesses was an explicit link — so an install that ran `nvidia-nim`+ * (direct API) beside `opencode-nvidia-nim` (an OpenCode wrapper on the same+ * endpoint) ends up with two NVIDIA NIM services, one of them labelled after+ * the harness. Under the composed model a service is the backend alone and a+ * harness pointed at it is a PRESET, so both belong on one instance.+ *+ * This is the pure planner: which rows are one backend, which row keeps its+ * identity, and what the surviving row holds. Rows fold only on evidence that+ * they reach the SAME backend under the SAME terms:+ *+ * - the same service definition — or a generic `openai-compatible` row whose+ * endpoint is exactly a named definition's default (a direct API record on+ * NVIDIA's URL is the NVIDIA NIM service, not "some OpenAI-compatible API");+ * - at least one protocol both declare, at the same base URL, and no protocol+ * declared at two different ones. "Both named nothing" is never a match, so+ * a transport-less subscription row never folds;+ * - the same credential mode, no credential name holding two values, and+ * never two different keys the instance would run under;+ * - the same plan — two plans of one definition are two legitimate instances+ * (D3). The one exception is a generic row whose plan the named definition+ * does not even sell: that plan was a classification default, not a choice;+ * - every LEGACY route on the folded row is still contained by the merged row+ * (`routeBelongsOnConnection`), so the next reconcile pass keeps it there+ * rather than cloning it straight back off. A DERIVED preset names its+ * service by slug and is re-derived onto the survivor by the caller.+ *+ * A row with a route mid-projection, or a route whose record is gone, sits the+ * pass out: its values are exactly what is in dispute. A row NO harness is+ * bound to is never folded away — that is a service someone just created and+ * has not made a preset from yet, not an import's per-harness copy — though it+ * may survive a fold and absorb one.+ */++const GENERIC_DEFINITION_ID = 'openai-compatible';++/** Protocols whose URL a named definition ships as its default — what a generic row is recognized by. */+const DEFAULT_ENDPOINTS = SERVICE_DEFINITIONS.flatMap((definition) => Object.entries(definition.transports || {})+ .filter(([, transport]) => typeof transport?.defaultBaseUrl === 'string' && transport.defaultBaseUrl !== '')+ .map(([protocol, transport]) => ({ protocol, baseUrl: transport.defaultBaseUrl, definitionId: definition.id })));++/** The definition a row really is: its own, or the named one a generic row's endpoint belongs to. */+function effectiveDefinitionId(connection) {+ if (connection.definitionId !== GENERIC_DEFINITION_ID) return connection.definitionId;+ const match = DEFAULT_ENDPOINTS.find(({ protocol, baseUrl }) => connection.transports?.[protocol]?.baseUrl === baseUrl);+ return match?.definitionId ?? connection.definitionId;+}++/** Union two transport maps, or null when a protocol names two URLs or none is shared. */+function mergeTransports(a, b) {+ const shared = Object.keys(a).filter((protocol) => Object.hasOwn(b, protocol));+ if (shared.length === 0) return null;+ if (!shared.every((protocol) => a[protocol]?.baseUrl === b[protocol]?.baseUrl)) return null;+ return { ...b, ...a };+}++/** Union two credential maps, or null when one name holds two values. */+function mergeCredentials(a, b) {+ const shared = Object.keys(a).filter((name) => Object.hasOwn(b, name));+ if (!shared.every((name) => a[name] === b[name])) return null;+ return { ...b, ...a };+}++function mergeCatalogs(a, b) {+ const models = [...new Set([...(a?.models || []), ...(b?.models || [])])];+ const state = a?.state === 'known' || b?.state === 'known' ? 'known' : (a?.state ?? 'unknown');+ return { state, models };+}++/**+ * The row `candidate` and the accumulated `merged` row would become, or null+ * when they are not provably the same backend under the same terms.+ */+function foldInto(merged, candidate, definition) {+ if ((merged.credentialVia ?? 'stored') !== (candidate.credentialVia ?? 'stored')) return null;+ const planForeign = candidate.definitionId !== merged.definitionId && !definition.plans.includes(candidate.plan);+ if (candidate.plan !== merged.plan && !planForeign) return null;+ const transports = mergeTransports(merged.transports || {}, candidate.transports || {});+ if (!transports) return null;+ const credentials = mergeCredentials(merged.credentials || {}, candidate.credentials || {});+ if (!credentials) return null;+ const keys = [merged, candidate].map((row) => instanceApiKeyFor(row, definition, {})).filter(Boolean);+ if (new Set(keys).size > 1) return null;+ return {+ ...merged,+ transports,+ credentials,+ catalog: mergeCatalogs(merged.catalog, candidate.catalog),+ enabled: merged.enabled !== false || candidate.enabled !== false,+ };+}++/**+ * Plan every fold the graph admits.+ *+ * @param {{connections: object[], bindings: object[], routes: object[]}} graph+ * @param {object[]} providers - the executable records the routes name+ * @param {{bootstraps?: Record<string, object>, env?: Record<string, string|undefined>}} [context]+ * the configured bootstrap apps and the environment a derived preset resolves against+ * @returns {{keeper: object, absorbedIds: string[], absorbedSlugs: string[],+ * bindingMoves: {bindingId: string, variantKey: string}[], presetPatches: Record<string, object>}[]}+ * `keeper` is the surviving row as it should be stored (its id, kind, slug+ * and definition unchanged); `presetPatches` the `providers.json` writes+ * that re-point every derived preset on it ({@link presetPatchesForMerge}).+ */+export function planServiceInstanceMerges(graph, providers, { bootstraps = {}, env = process.env } = {}) {+ const records = new Map((Array.isArray(providers) ? providers : [])+ .filter((record) => record && typeof record === 'object' && record.id)+ .map((record) => [record.id, record]));+ const bindingsOf = (connectionId) => graph.bindings.filter((binding) => binding.connectionId === connectionId);+ const routesOf = (connectionId) => {+ const ids = new Set(bindingsOf(connectionId).map((binding) => binding.id));+ return graph.routes.filter((route) => ids.has(route.bindingId));+ };++ const groups = new Map();+ for (const connection of graph.connections) {+ if (!connection.slug || !connection.definitionId || Object.keys(connection.transports || {}).length === 0) continue;+ const routes = routesOf(connection.id);+ if (routes.some((route) => route.pending || !records.has(route.providerId))) continue;+ const definitionId = effectiveDefinitionId(connection);+ if (!serviceDefinitionById(definitionId)) continue;+ groups.set(definitionId, [...(groups.get(definitionId) || []), { connection, routes }]);+ }++ const merges = [];+ for (const [definitionId, members] of groups) {+ if (members.length < 2) continue;+ const definition = serviceDefinitionById(definitionId);+ // The survivor keeps its id, kind and slug, so prefer the row that already+ // IS the named definition, then the one addressed by the definition's own+ // id, then the one labelled as the service; ties keep table order.+ const rank = ({ connection }) => (connection.definitionId === definitionId ? 0 : 4)+ + (connection.slug === definitionId ? 0 : 2)+ + (connection.label === definition.label ? 0 : 1);+ const ordered = [...members].sort((a, b) => rank(a) - rank(b));+ const remaining = [...ordered];+ while (remaining.length > 1) {+ const lead = remaining.shift();+ let merged = { ...lead.connection };+ const absorbed = [];+ for (const member of [...remaining]) {+ if (bindingsOf(member.connection.id).length === 0) continue;+ const next = foldInto(merged, member.connection, definition);+ if (!next) continue;+ const legacy = member.routes.filter((route) => !isDerivedPreset(records.get(route.providerId)));+ if (!legacy.every((route) => routeBelongsOnConnection(providerConnectionProfile(records.get(route.providerId)), next))) continue;+ const onRow = [lead, ...absorbed, member].flatMap(({ routes }) => routes).map((route) => records.get(route.providerId));+ if (!presetPatchesForMerge(next, onRow, bootstraps, env)) continue;+ merged = next;+ absorbed.push(member);+ remaining.splice(remaining.indexOf(member), 1);+ }+ if (absorbed.length === 0) continue;+ merged.label = serviceLabel([lead, ...absorbed].map(({ connection }) => connection), definition, graph.bindings);+ const onKeeper = [lead, ...absorbed].flatMap(({ routes }) => routes).map((route) => records.get(route.providerId));+ const presetPatches = presetPatchesForMerge(merged, onKeeper, bootstraps, env);+ if (presetPatches) merges.push({ ...planMoves(graph, merged, absorbed), keeper: merged, presetPatches });+ }+ }+ return merges;+}++/**+ * The survivor's label. An import names each row after the record it came+ * from, so every row but a direct API one carries its harness ("OpenCode NVIDIA+ * NIM") — wrong once the row serves several. Prefer a member already named as+ * the service, then a direct-API member's name, then the definition's own.+ */+function serviceLabel(rows, definition, bindings) {+ const named = rows.find((row) => row.label === definition.label);+ if (named) return named.label;+ const direct = rows.find((row) => bindings.some((binding) => binding.connectionId === row.id && binding.harnessId == null));+ return direct?.label || definition.label;+}++/** Binding moves onto the survivor, each on a variant key free on it: `UNIQUE(connection, harness, variant)`. */+function planMoves(graph, keeper, absorbed) {+ const key = (harnessId, variantKey) => JSON.stringify([harnessId ?? null, variantKey]);+ const taken = new Set(graph.bindings.filter((binding) => binding.connectionId === keeper.id)+ .map((binding) => key(binding.harnessId, binding.variantKey)));+ const bindingMoves = [];+ for (const { connection } of absorbed) {+ for (const binding of graph.bindings.filter((candidate) => candidate.connectionId === connection.id)) {+ const variantKey = taken.has(key(binding.harnessId, binding.variantKey)) ? `variant:${binding.id}` : binding.variantKey;+ taken.add(key(binding.harnessId, variantKey));+ bindingMoves.push({ bindingId: binding.id, variantKey });+ }+ }+ return {+ absorbedIds: absorbed.map(({ connection }) => connection.id),+ absorbedSlugs: absorbed.map(({ connection }) => connection.slug),+ bindingMoves,+ };+}+++/**+ * The `providers.json` patches that put every DERIVED preset among `records`+ * on the fold's survivor: its `serviceId` becomes the survivor's slug and+ * everything the service owns is re-derived from the merged row. A preset keeps+ * the model list it was running with — the survivor's catalog is the union of+ * the folded rows', so a preset with no narrowing of its own is narrowed to its+ * current list whenever that list is still all listed (the same rule the+ * conversion backfill applies).+ *+ * `null` when any preset cannot be derived there unchanged (an unknown+ * harness, a deleted bootstrap app, a refused composition, a model list the+ * survivor's plan would cut): the planner then leaves that row out of the fold+ * rather than splitting a service's presets.+ *+ * @param {object} keeper - the survivor as `planServiceInstanceMerges` returned it+ * @param {object[]} records - the executable records on it (legacy ones are skipped)+ * @param {Record<string, object>} bootstraps - the configured bootstrap apps+ * @param {Record<string, string|undefined>} [env]+ * @returns {Record<string, object>|null}+ */+function presetPatchesForMerge(keeper, records, bootstraps, env = process.env) {+ const derived = records.filter(isDerivedPreset);+ if (derived.length === 0) return {};+ const instance = instanceForConnection(keeper, env);+ if (!instance) return null;+ const listed = listedModels(instance, keeper.catalog);+ const patches = {};+ for (const record of derived) {+ const harness = harnessById(record.harnessId);+ const app = record.credentialBootstrapId ? bootstraps[record.credentialBootstrapId] : null;+ if (!harness || (record.credentialBootstrapId && !app)) return null;+ const next = { ...record, serviceId: keeper.slug };+ const models = Array.isArray(record.models) ? record.models : [];+ if (!Array.isArray(record.catalogNarrowing) && listed.length > 0 && !isDeepStrictEqual(listed, models)+ && models.every((model) => listed.includes(model))) {+ next.catalogNarrowing = [...models];+ }+ const { record: materialized, error } = materializeDerivedPreset({+ record: next, harness, instance, catalog: keeper.catalog, bootstrap: app ? bootstrapInputFor(record.credentialBootstrapId, app) : null,+ });+ // A fold must not change what a preset runs: a list the survivor's plan+ // would cut (a paid-model preset onto a free-plan instance) refuses it.+ if (error || !isDeepStrictEqual(materialized.models, models)) return null;+ const patch = derivedPresetPatch(record, materialized);+ if (Object.keys(patch).length > 0) patches[record.id] = patch;+ }+ return patches;+}diff --git a/server/lib/providerServiceMerge.test.js b/server/lib/providerServiceMerge.test.jsnew file mode 100644index 0000000000..c5c5995051--- /dev/null+++ b/server/lib/providerServiceMerge.test.js@@ -0,0 +1,130 @@+/**+ * Folding duplicate service instances (epic #7561). The shipped samples are+ * the regression: imported as-is they give NVIDIA NIM two services — "NVIDIA+ * NIM" (the direct API record) and "OpenCode NVIDIA NIM" (the wrapper) — when a+ * harness on a service is a preset, not a second service.+ *+ * Fixtures are synthetic or the shipped reference samples. Nothing here is read+ * out of a running install.+ */+import { readFileSync } from 'node:fs';+import { describe, expect, it } from 'vitest';+import { importGraphFromProviders, isDerivedPreset, planGraphReconciliation } from './providerGraphRecords.js';+import { planPresetBackfill } from './providerPresets.js';+import { planServiceColumnBackfill } from './providerServiceInstances.js';+import { planServiceInstanceMerges } from './providerServiceMerge.js';++const SAMPLES = Object.values(JSON.parse(readFileSync(new URL('../../data.reference/providers.json', import.meta.url), 'utf8')).providers);++const minter = () => { let n = 0; return () => `id-${++n}`; };+const plan = (graph, providers) => planServiceInstanceMerges(graph, providers, { bootstraps: {}, env: {} });++/** What a first boot does before the fold: import, name, stamp the derivable presets. */+function bootedSamples() {+ const providers = structuredClone(SAMPLES);+ const graph = importGraphFromProviders({ providers }, minter());+ for (const row of planServiceColumnBackfill(graph, new Set())) Object.assign(graph.connections.find((c) => c.id === row.id), row);+ const { patches } = planPresetBackfill({ graph, providers, bootstraps: {}, env: {} });+ for (const record of providers) Object.assign(record, patches[record.id] || {});+ return { graph, providers };+}++/** Apply a fold in memory the way the preset write + `mergeServiceInstances` do. */+function applyFold(graph, providers, merge) {+ for (const record of providers) Object.assign(record, merge.presetPatches[record.id] || {});+ graph.connections = graph.connections.filter((c) => !merge.absorbedIds.includes(c.id)).map((c) => (c.id === merge.keeper.id ? merge.keeper : c));+ for (const { bindingId, variantKey } of merge.bindingMoves) {+ Object.assign(graph.bindings.find((b) => b.id === bindingId), { connectionId: merge.keeper.id, variantKey });+ }+}++/** The records whose routes sit on `connectionId`. */+const routedOn = (graph, connectionId) => {+ const bindings = new Set(graph.bindings.filter((b) => b.connectionId === connectionId).map((b) => b.id));+ return graph.routes.filter((route) => bindings.has(route.bindingId)).map((route) => route.providerId).sort();+};++describe('planServiceInstanceMerges over the shipped samples', () => {+ it('leaves one NVIDIA NIM service carrying the direct API and both OpenCode presets', () => {+ const { graph, providers } = bootedSamples();+ const nim = plan(graph, providers).find((merge) => merge.keeper.definitionId === 'nvidia-nim');+ expect(nim.keeper).toMatchObject({ slug: 'nvidia-nim', label: 'NVIDIA NIM', kind: 'gateway:nvidia-nim' });+ expect(nim.absorbedIds).toHaveLength(1);+ applyFold(graph, providers, nim);+ expect(routedOn(graph, nim.keeper.id)).toEqual(['nvidia-nim', 'opencode-nvidia-nim', 'opencode-nvidia-nim-tui']);+ const wrappers = providers.filter((record) => record.id.startsWith('opencode-nvidia-nim'));+ expect(wrappers.map((record) => record.serviceId)).toEqual(['nvidia-nim', 'nvidia-nim']);+ });++ it('holds after the next reconcile pass: no folded route is cloned back off the survivor', () => {+ const { graph, providers } = bootedSamples();+ const merges = plan(graph, providers);+ for (const merge of merges) applyFold(graph, providers, merge);+ expect(merges.map((merge) => merge.keeper.definitionId)).toEqual(expect.arrayContaining(['nvidia-nim', 'openrouter', 'ollama']));++ const reconciled = planGraphReconciliation(graph, providers, { mintId: minter() });+ expect(reconciled.regroups.filter((regroup) => regroup.connectionAction !== 'unchanged' || !regroup.bindingId)).toEqual([]);+ expect(reconciled.imports.routes).toEqual([]);+ // Every derived preset names a service that still exists, and a second fold plans nothing.+ const slugs = new Set(graph.connections.map((c) => c.slug));+ expect(providers.filter(isDerivedPreset).filter((record) => !slugs.has(record.serviceId))).toEqual([]);+ expect(plan(graph, providers)).toEqual([]);+ });++ it('never changes a preset\'s models: the paid-model Zen API stays off the free Zen instance', () => {+ const { graph, providers } = bootedSamples();+ const before = new Map(providers.map((record) => [record.id, structuredClone(record.models)]));+ const zenApi = graph.routes.find((route) => route.providerId === 'opencode-zen').bindingId;+ for (const merge of plan(graph, providers)) {+ expect(merge.bindingMoves.map((move) => move.bindingId)).not.toContain(zenApi);+ applyFold(graph, providers, merge);+ }+ for (const record of providers.filter(isDerivedPreset)) expect(record.models).toEqual(before.get(record.id));+ });+});++const NIM_URL = 'https://integrate.api.nvidia.com/v1';+const row = (id, overrides = {}) => ({+ id, revision: 1, kind: 'gateway:nvidia-nim', label: `Row ${id}`, slug: id, definitionId: 'nvidia-nim', plan: 'free',+ enabled: true, credentialVia: 'stored', transports: { openai: { baseUrl: NIM_URL } }, credentials: {},+ catalog: { state: 'known', models: ['example/model'] }, ...overrides,+});+const bound = (connectionId, harnessId = 'opencode') => ({+ id: `b-${connectionId}`, revision: 1, connectionId, harnessId, variantKey: 'default', label: '', enabled: false, selectedModels: [],+});+const twoRows = (a, b) => ({ connections: [row('nim-a', a), row('nim-b', b)], bindings: [bound('nim-a'), bound('nim-b')], routes: [] });++describe('planServiceInstanceMerges refusals', () => {+ it('folds two rows that are one backend under the same terms, onto a variant key free on the survivor', () => {+ const [merge] = plan(twoRows(), []);+ expect(merge).toMatchObject({ absorbedIds: ['nim-b'], bindingMoves: [{ bindingId: 'b-nim-b', variantKey: 'variant:b-nim-b' }] });+ });++ it.each([+ ['a different plan (free and paid are two instances)', {}, { plan: 'paid' }],+ ['a different endpoint', {}, { transports: { openai: { baseUrl: 'https://example.com/v1' } } }],+ ['two different keys', { credentials: { apiKey: 'key-one' } }, { credentials: { apiKey: 'key-two' } }],+ ['a different credential mode', {}, { credentialVia: 'env' }],+ ])('keeps two rows apart on %s', (_label, a, b) => {+ expect(plan(twoRows(a, b), [])).toEqual([]);+ });++ it('never folds away a service no harness is bound to yet', () => {+ const graph = twoRows();+ graph.bindings = [bound('nim-a')];+ expect(plan(graph, []).flatMap((merge) => merge.absorbedIds)).not.toContain('nim-b');+ });++ it('sits out a row whose route is mid-projection', () => {+ const graph = twoRows();+ graph.routes = [{ providerId: 'example', bindingId: 'b-nim-b', mode: 'cli', modelMap: {}, projected: {}, pending: {} }];+ expect(plan(graph, [{ id: 'example' }])).toEqual([]);+ });++ it('refuses a fold whose preset cannot be derived on the survivor', () => {+ const graph = twoRows();+ graph.routes = [{ providerId: 'example', bindingId: 'b-nim-b', mode: 'cli', modelMap: {}, projected: {}, pending: null }];+ const orphan = { id: 'example', harnessId: 'no-such-harness', method: 'cli', serviceId: 'nim-b' };+ expect(plan(graph, [orphan])).toEqual([]);+ });+});diff --git a/server/routes/providers.connectionCreate.test.js b/server/routes/providers.connectionCreate.test.jsindex 502a05eaba..20a98d108a 100644--- a/server/routes/providers.connectionCreate.test.js+++ b/server/routes/providers.connectionCreate.test.js@@ -37,6 +37,7 @@ const store = {relinkBinding: vi.fn().mockResolvedValue(undefined),deleteConnection: vi.fn(),detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+ mergeServiceInstances: vi.fn().mockResolvedValue(undefined),saveConnectionSettings: vi.fn().mockResolvedValue(2),saveBindingSettings: vi.fn().mockResolvedValue(2),saveRouteModelMap: vi.fn().mockResolvedValue(undefined),diff --git a/server/routes/providers.connectionManagement.test.js b/server/routes/providers.connectionManagement.test.jsindex a9646316e5..beeee91e0e 100644--- a/server/routes/providers.connectionManagement.test.js+++ b/server/routes/providers.connectionManagement.test.js@@ -31,6 +31,7 @@ const store = {relinkBinding: vi.fn().mockResolvedValue(undefined),deleteConnection: vi.fn(),detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+ mergeServiceInstances: vi.fn().mockResolvedValue(undefined),saveConnectionSettings: vi.fn().mockResolvedValue(2),saveBindingSettings: vi.fn().mockResolvedValue(2),saveRouteModelMap: vi.fn().mockResolvedValue(undefined),diff --git a/server/routes/providers.services.test.js b/server/routes/providers.services.test.jsindex f13ac13645..bc3b2245de 100644--- a/server/routes/providers.services.test.js+++ b/server/routes/providers.services.test.js@@ -33,6 +33,7 @@ const store = {relinkBinding: vi.fn().mockResolvedValue(undefined),deleteConnection: vi.fn(),detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+ mergeServiceInstances: vi.fn().mockResolvedValue(undefined),saveConnectionSettings: vi.fn().mockResolvedValue(2),saveBindingSettings: vi.fn().mockResolvedValue(2),saveRouteModelMap: vi.fn().mockResolvedValue(undefined),diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex ebb5f68c74..0bcead2b2a 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -55,6 +55,7 @@ import {serviceColumnsForConnection,takenServiceSlugs,} from '../lib/providerServiceInstances.js';+import { planServiceInstanceMerges } from '../lib/providerServiceMerge.js';import { SERVICE_CREDENTIAL_VIAS, assertServicePlan, serviceDefinitionById } from '../lib/serviceDefinitions.js';import { requireToolkit } from '../lib/aiToolkitState.js';import {@@ -64,6 +65,7 @@ import {commitPendingProjection,deleteConnection,detachBindingToConnection,+ mergeServiceInstances,readGraph,relinkBinding,saveBindingSettings,@@ -222,19 +224,30 @@ async function reconcilePass(reason) {// are eligible now, a clone or split waits for the next pass.const named = new Map(backfill.map((row) => [row.id, row]));const removed = new Set(plan.removals);- const presets = await backfillPresets({+ const applied = {connections: [...graph.connections.map((connection) => ({ ...connection, ...(named.get(connection.id) || {}) })), ...plan.imports.connections],bindings: [...graph.bindings, ...plan.imports.bindings],routes: [...graph.routes.filter((route) => !removed.has(route.providerId)), ...plan.imports.routes],- }, providers);+ };+ const presets = await backfillPresets(applied, providers);presetSkipReasons = new Map(presets.skipped.map(({ id, reason }) => [id, reason]));+ // One service per backend (epic #7561): the import gave every harness its+ // own row, so fold rows that provably reach one backend under one set of+ // terms into a single instance. Row-derived and idempotent like the steps+ // above — a folded graph plans nothing — so it rides every pass. It reads+ // the same as-applied view, which a regroup (clone, split, in-place update)+ // leaves stale, so a pass that moved rows leaves the fold to the next one.+ const regrouped = plan.regroups.some((regroup) => regroup.connectionAction !== 'unchanged' || !regroup.bindingId);+ const folded = regrouped ? 0 : await foldDuplicateServices(applied, presets.stamped.length > 0 ? null : providers);+const detached = plan.regroups.filter((regroup) => regroup.connectionAction === 'clone').length;const split = plan.regroups.filter((regroup) => !regroup.bindingId).length;- if (!noop || plan.conflicts.length > 0 || presets.stamped.length > 0) {+ if (!noop || plan.conflicts.length > 0 || presets.stamped.length > 0 || folded > 0) {console.log(`🔗 Provider graph reconciled (${reason}): ${plan.imports.routes.length} imported, `+ `${detached} detached, ${split} split, ${plan.removals.length} removed, `- + `${plan.acknowledgements.length} acknowledged, ${plan.conflicts.length} conflicted, ${presets.stamped.length} presets derived`);+ + `${plan.acknowledgements.length} acknowledged, ${plan.conflicts.length} conflicted, ${presets.stamped.length} presets derived, `+ + `${folded} services folded`);}for (const conflict of plan.conflicts) {console.error(`⚠️ Provider route ${conflict.providerId} changed outside the graph mid-projection; `@@ -243,6 +256,32 @@ async function reconcilePass(reason) {return { activeProvider, plan, noop, presets };}+/**+ * The service-fold half of a pass: `planServiceInstanceMerges` over the graph+ * as the steps above left it, applied one fold at a time. The provider file is+ * re-read only when the preset backfill just wrote it (`current` is null), so+ * the fold judges each record as derived or legacy by what it now is. Each+ * fold's derived presets are re-pointed in `providers.json` BEFORE the rows+ * move — they then name a slug that already exists, so a crash between the two+ * writes leaves every record resolvable and the next pass re-plans the same+ * fold. Writes through the toolkit directly, under the pass's latch, like+ * {@link backfillPresets}. Local I/O only.+ *+ * @returns {Promise<number>} how many rows were folded away+ */+async function foldDuplicateServices(graph, current) {+ const providers = current ?? (await providerService().getAllProviders()).providers;+ // Only a preset naming a bootstrap app consults the table.+ const bootstraps = providers.some((record) => record?.credentialBootstrapId) ? await bootstrapApps() : {};+ const merges = planServiceInstanceMerges(graph, providers, { bootstraps, env: process.env });+ for (const merge of merges) {+ if (Object.keys(merge.presetPatches).length > 0) await providerService().applyProviderPatches(merge.presetPatches);+ await mergeServiceInstances(merge);+ console.log(`🔗 Provider graph: folded service(s) ${merge.absorbedSlugs.join(', ')} into ${merge.keeper.slug}`);+ }+ return merges.reduce((sum, merge) => sum + merge.absorbedIds.length, 0);+}+/*** The preset backfill half of a pass (#7565). Writes through the toolkit* directly: the caller already holds the `reconciling` latch for the wholediff --git a/server/services/providerGraph.test.js b/server/services/providerGraph.test.jsindex 9b63ba1c29..62c262f22f 100644--- a/server/services/providerGraph.test.js+++ b/server/services/providerGraph.test.js@@ -23,6 +23,7 @@ const store = {relinkBinding: vi.fn().mockResolvedValue(undefined),deleteConnection: vi.fn(),detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+ mergeServiceInstances: vi.fn().mockResolvedValue(undefined),saveConnectionSettings: vi.fn().mockResolvedValue(2),};vi.mock('./providerGraphStore.js', () => store);diff --git a/server/services/providerGraphStore.db.test.js b/server/services/providerGraphStore.db.test.jsindex bfde18d81c..9f35faf24f 100644--- a/server/services/providerGraphStore.db.test.js+++ b/server/services/providerGraphStore.db.test.js@@ -170,6 +170,28 @@ describe.skipIf(!runDb)('ai_* connection graph store', () => {expect(await store.deleteConnection(conn.id)).toEqual({ deleted: true });});+ it('folds a duplicate service: the binding moves on its freed variant key and the emptied row goes', async () => {+ // Both rows carry a `default` Claude binding, so the move must land on the+ // variant key the planner freed or the partial unique index refuses it.+ const keeper = connection();+ const twin = connection();+ const kept = binding(keeper.id);+ const moved = binding(twin.id);+ await store.writeGraph({ connections: [keeper, twin], bindings: [kept, moved], routes: [route(moved.id, 'claude-ollama')] });++ await store.mergeServiceInstances({+ keeper: { ...keeper, label: 'Ollama', catalog: { state: 'known', models: ['example-model', 'other-model'] } },+ absorbedIds: [twin.id],+ bindingMoves: [{ bindingId: moved.id, variantKey: `variant:${moved.id}` }],+ });++ const read = await store.readGraph();+ expect(read.connections.map((row) => row.id)).toEqual([keeper.id]);+ expect(read.connections[0]).toMatchObject({ label: 'Ollama', revision: 2, catalog: { models: ['example-model', 'other-model'] } });+ expect(read.bindings.find((row) => row.id === moved.id)).toMatchObject({ connectionId: keeper.id, variantKey: `variant:${moved.id}` });+ expect(read.routes[0]).toMatchObject({ providerId: 'claude-ollama', bindingId: moved.id });+ });+it('stages, then acknowledges, a projection', async () => {const conn = connection();const bind = binding(conn.id);diff --git a/server/services/providerGraphStore.js b/server/services/providerGraphStore.jsindex 8ad1805069..501e12e1dd 100644--- a/server/services/providerGraphStore.js+++ b/server/services/providerGraphStore.js@@ -269,6 +269,31 @@ export async function detachBindingToConnection({ bindingId, connection }) {});}+/**+ * Fold duplicate service instances into one (`planServiceInstanceMerges`):+ * write the survivor, move every binding off the folded rows onto it (each on+ * the variant key the plan freed), then delete the folded rows — all or+ * nothing, so a crash never leaves a binding on a deleted row. The delete is+ * guarded by the same "no binding names it" rule as {@link deleteConnection}.+ */+export async function mergeServiceInstances({ keeper, absorbedIds, bindingMoves }) {+ await withTransaction(async (client) => {+ await upsertConnection(client, keeper);+ for (const { bindingId, variantKey } of bindingMoves) {+ await client.query(+ `UPDATE ai_harness_bindings SET connection_id = $1, variant_key = $2, revision = revision + 1, updated_at = NOW()+ WHERE id = $3`,+ [keeper.id, variantKey, bindingId],+ );+ }+ await client.query(+ `DELETE FROM ai_connections WHERE id = ANY($1::uuid[])+ AND NOT EXISTS (SELECT 1 FROM ai_harness_bindings WHERE connection_id = ai_connections.id)`,+ [absorbedIds],+ );+ });+}+/** Hard-delete an orphan connection. Refused while a binding still names it. */export async function deleteConnection(connectionId) {const { rows } = await query('SELECT 1 FROM ai_harness_bindings WHERE connection_id = $1 LIMIT 1', [connectionId]);diff --git a/server/services/providerPresets.test.js b/server/services/providerPresets.test.jsindex 27f3963ff8..0dd8557570 100644--- a/server/services/providerPresets.test.js+++ b/server/services/providerPresets.test.js@@ -25,6 +25,7 @@ const store = vi.hoisted(() => ({readGraph: vi.fn(async () => structuredClone(graphState.current)),applyReconciliation: vi.fn(async () => {}),applyServiceColumnBackfill: vi.fn(async () => {}),+ mergeServiceInstances: vi.fn(async () => {}),}));vi.mock('./providerGraphStore.js', () => store);vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({@@ -147,8 +148,10 @@ describe('derivePreset', () => {await providerService().createProvider(legacy);// The record is unmapped, so the pass its save fires imports it — as its// own fragment, a second instance of the daemon (import never auto-links),- // which is the service it is then derived from in that same pass. The store- // double records the plan and the next read serves it back.+ // which is the service it is then derived from in that same pass; the same+ // pass then folds that copy into the `ollama` instance it duplicates, so+ // the preset ends up naming the one service. The store double records the+ // plan and the next read serves it back.store.applyReconciliation.mockImplementation(async (plan) => {const imported = plan.imports;graphState.current = {@@ -158,7 +161,8 @@ describe('derivePreset', () => {};});const derived = await presets.derivePreset('claude-ollama');- expect(derived).toMatchObject({ harnessId: 'claude', method: 'cli', serviceId: 'ollama-2', command: 'claude', args: ['--print'] });+ expect(derived).toMatchObject({ harnessId: 'claude', method: 'cli', serviceId: 'ollama', command: 'claude', args: ['--print'] });+ expect(store.mergeServiceInstances).toHaveBeenCalledWith(expect.objectContaining({ absorbedSlugs: ['ollama-2'], keeper: expect.objectContaining({ slug: 'ollama' }) }));await providerService().createProvider({ ...legacy, id: 'claude-path', command: '/opt/bin/claude' });await expect(presets.derivePreset('claude-path')).rejects.toMatchObject({ status: 409, code: 'PRESET_NOT_DERIVABLE' });