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: centralize provider connection projection in its transport owner
Adam Eivy5dbd3228776b
diff --git a/server/lib/README.md b/server/lib/README.mdindex c070f25981..726db7b2ef 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -203,7 +203,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`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, and `isGatewayBackedProvider(config)`. 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. Dependency-light: imports nothing. || `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, each with its supported `modes`, wire `protocol` and the existing `is*Provider` predicate as its matcher), `PROVIDER_HARNESS_IDS`, `harnessById`, `harnessForProvider` (null for an `api` record AND for an unknown harness — use `providerRouteMode` to tell them apart), `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 `providerGateways.js` (hosted backend). Pure leaf — `client/src/utils/providerHarnesses.js` names a binding's harness through `harnessById`. || `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) and `catalogModelContextWindow(provider, model)` (the window the provider's own `/models` catalog reported, which outranks the table). `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). `withoutConnectionOwnedFields` / `withConnectionOwnedFields` are the lossless split/materialize pair that keeps a downgraded install runnable from `data/providers.json` alone. Pure: no I/O. |+| `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. || `providerGraphPreview.js` | READ-ONLY import preview for the provider connection graph (#6366) — `buildProviderGraphPreview({providers, activeProvider})` projects the records an install already runs into proposed connections, harness bindings and executable routes, grouping ONLY the proven same-harness CLI/TUI siblings from `providerModeGroups` and surfacing a cross-harness daemon match as a `suggestedLinks` entry requiring an explicit link. `toManagementPreviewDto` sanitizes and validates the version-1 DTOs (`managementPreviewSchema`, `PROVIDER_GRAPH_SCHEMA_VERSION`) that `GET /api/providers/management/preview` returns; `projectPreviewToProviders` re-materializes every original record (pins, secrets, consent flags and unknown custom fields included) as the import-fidelity and downgrade proof; `providerGraphUniquenessViolations` checks the UNIQUE constraints #6367 will enforce; `routeModeEligibility` is the pure declarative half of mode eligibility (harness support + enabled + caller-allowed mode + text-transport consent), with the prerequisite/fallback policy left to #6368. Persists nothing and makes no generation call or runtime launch. || `providerGraphRecords.js` | The DURABLE half of the provider connection graph (#6367) — the pure record layer over `ai_connections` / `ai_harness_bindings` / `ai_route_bindings`. `graphFromPreview` / `importGraphFromProviders` mint UUID-keyed rows from a #6366 preview while every executable `providerId` stays untouched; `toManagementGraphDto` (`managementGraphSchema`) sanitizes them for `GET /api/providers/management` (credential PRESENCE only, no projection snapshots); `connectionOwnedSnapshot` / `applyProjections` materialize connection-owned values back into providers.json so a downgraded install still runs; `routeBelongsOnConnection` answers whether a stored connection still CONTAINS the backend one route describes (the create-time and reconcile-time test, looser than `sameConnectionIdentity`); and `planGraphReconciliation` / `reconciliationIsNoop` are the reconciliation contract shared by boot, legacy provider writes and downgrade-edit-reupgrade — acknowledging a landed projection, retrying an interrupted one, REFUSING a third externally changed value, dropping deleted records without resurrecting them, and detaching or splitting a binding whose backend moved. Pure: no DB handle, no file I/O, no provider call. || `providerModelAliases.js` | HAND-AUTHORED canonical→executable model aliases for one provider route (#6369) — the correction surface for a `modelMap` a refresh could only fill with what it could VERIFY. Observed aliases (`ai_route_bindings.model_map`) and user overrides (`model_alias_overrides`) are stored apart and merged on READ by `effectiveModelAliases` (`{ ...observed, ...overrides }`), which is what lets a hand-authored alias outlast the next refresh; `applyModelAliasPatch` is the three-valued edit (absent preserves, a string sets, `null` is the only thing that removes); `staleModelAliases` reports — never repairs — an override naming a spelling the record no longer lists, and makes no claim at all about a route listing no models; `connectionCatalogModels` is the union an alias write re-derives the shared catalog from, so a correction actually reaches the model menus; `modelAliasRevision` is the stale-edit fingerprint, reusing `routeSettingsRevision` because `ai_route_bindings` has no revision column. Pure: no I/O. |diff --git a/server/lib/providerConnections.js b/server/lib/providerConnections.jsindex 176f9e8fc5..ee797945a5 100644--- a/server/lib/providerConnections.js+++ b/server/lib/providerConnections.js@@ -260,6 +260,40 @@ export function withConnectionOwnedFields(routeRecord, owned) {return merged;}+/**+ * The connection-owned snapshot a route should carry once bound to+ * `connection`: the record's own owned KEY SET (so the split stays lossless for+ * this record's shape) filled with the connection's values. Uses the same+ * protocol and env ownership rules as the reader above; the graph service owns+ * only staging, writing and acknowledging this snapshot. Route-owned inline+ * configuration and unknown fields remain outside the projection.+ */+export function projectConnectionOwnedFields(provider, connection) {+ const { owned, protocol } = providerConnectionProfile(provider);+ // Read and project through the same protocol classification. Map insertion+ // order must not send an OpenAI endpoint to a connection's Anthropic wire.+ // Retain the legacy fallback for connections declaring only another wire.+ const baseUrl = connection.transports[protocol]?.baseUrl+ ?? Object.values(connection.transports)[0]?.baseUrl ?? null;+ const fields = { ...owned.fields };+ if (Object.hasOwn(fields, 'endpoint') && baseUrl !== null) fields.endpoint = baseUrl;+ if (Object.hasOwn(fields, 'apiKey')) fields.apiKey = connection.credentials.apiKey ?? fields.apiKey;+ const envVars = { ...owned.envVars };+ for (const name of Object.keys(envVars)) {+ if (Object.hasOwn(connection.credentials, name)) {+ envVars[name] = connection.credentials[name];+ continue;+ }+ // `ANTHROPIC_BASE_URL` names the anthropic transport, not merely "a URL":+ // a connection that speaks several protocols has a different base URL for+ // each, and picking the first would point the harness at the wrong port.+ const envProtocol = TRANSPORT_ENV_VARS[name];+ const url = envProtocol ? connection.transports[envProtocol]?.baseUrl ?? baseUrl : null;+ if (url) envVars[name] = url;+ }+ return { fields, envVars, hasEnvVars: owned.hasEnvVars };+}+/*** A stable, SECRET-FREE bucket key. Two profiles can only be the same* connection if their keys match — but a matching key is not sufficient, whichdiff --git a/server/routes/providers.connectionManagement.test.js b/server/routes/providers.connectionManagement.test.jsindex f6d2cd7b30..5bc3fd9a95 100644--- a/server/routes/providers.connectionManagement.test.js+++ b/server/routes/providers.connectionManagement.test.js@@ -217,6 +217,51 @@ describe('PATCH /api/providers/connections/:id', () => {expect(patches['claude-ollama']).not.toHaveProperty('enabled');});+ it('projects an endpoint-backed route through its declared protocol, preserving executable settings', async () => {+ const api = {+ id: 'example-api', type: 'api', ollamaBacked: true, enabled: false,+ endpoint: DAEMON_OPENAI, apiKey: 'example-api-key',+ models: ['example-model'], defaultModel: 'example-model', customField: 'keep',+ };+ const data = graphFixture();+ const bindingId = '55555555-5555-4555-8555-555555555555';+ data.bindings.push({ ...data.bindings[1], id: bindingId, harnessId: null });+ data.connections[0].credentials.apiKey = api.apiKey;+ data.routes.push(route(api.id, bindingId, 'api', {+ fields: { endpoint: api.endpoint, apiKey: api.apiKey }, envVars: {}, hasEnvVars: false,+ }));+ store.readGraph.mockResolvedValue(data);+ providerService.getAllProviders.mockResolvedValue({+ activeProvider: api.id, providers: [CLAUDE_CLI, CLAUDE_TUI, CODEX_CLI, api],+ });+ let executable;+ providerService.applyProviderPatches.mockImplementation(async (patches) => {+ executable = { ...api, ...patches[api.id] };+ return Object.keys(patches);+ });++ const res = await request(app()).patch(`/api/providers/connections/${CONNECTION}`)+ .send({+ expectedRevision: 3,+ // Anthropic is first deliberately: map order must not select the API wire.+ transports: {+ anthropic: { baseUrl: 'https://daemon.example.com/anthropic' },+ openai: { baseUrl: 'https://daemon.example.com/v1' },+ },+ });++ expect(res.status).toBe(200);+ expect(executable).toEqual({ ...api, endpoint: 'https://daemon.example.com/v1' });+ // Crash recovery must stage the same endpoint that execution receives.+ const pending = store.commitPendingProjection.mock.calls[0][0]+ .find((entry) => entry.providerId === api.id);+ expect(pending.owned).toEqual({+ fields: { endpoint: executable.endpoint, apiKey: api.apiKey },+ envVars: {}, hasEnvVars: false,+ });+ expect(res.body).not.toHaveProperty('credentials');+ });+it('stages the projection before writing the file and acknowledges only after', async () => {const order = [];store.commitPendingProjection.mockImplementation(async () => { order.push('stage'); });diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex 00b235b883..177a6779ea 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -3,6 +3,7 @@ import { ServerError } from '../lib/errorHandler.js';import {compareBackendEndpoints,providerConnectionProfile,+ projectConnectionOwnedFields,withConnectionOwnedFields,} from '../lib/providerConnections.js';import {@@ -399,7 +400,7 @@ async function projectRoutes(providerIds, connection) {const byId = new Map(providers.map((provider) => [provider.id, provider]));const projections = providerIds.filter((providerId) => byId.has(providerId))- .map((providerId) => ({ providerId, owned: ownedFromConnection(byId.get(providerId), connection) }));+ .map((providerId) => ({ providerId, owned: projectConnectionOwnedFields(byId.get(providerId), connection) }));if (projections.length === 0) return [];await commitPendingProjection(projections);@@ -438,33 +439,6 @@ function duringProviderWrite(work) {return Promise.resolve().then(work).finally(() => { reconciling = false; });}-/**- * The connection-owned snapshot a route should carry once bound to- * `connection`: the record's own owned KEY SET (so the split stays lossless for- * this record's shape) filled with the connection's values.- */-function ownedFromConnection(provider, connection) {- const owned = connectionOwnedSnapshot(provider);- const baseUrl = Object.values(connection.transports)[0]?.baseUrl ?? null;- const fields = { ...owned.fields };- if (Object.hasOwn(fields, 'endpoint') && baseUrl !== null) fields.endpoint = baseUrl;- if (Object.hasOwn(fields, 'apiKey')) fields.apiKey = connection.credentials.apiKey ?? fields.apiKey;- const envVars = { ...owned.envVars };- for (const name of Object.keys(envVars)) {- if (Object.hasOwn(connection.credentials, name)) {- envVars[name] = connection.credentials[name];- continue;- }- // `ANTHROPIC_BASE_URL` names the anthropic transport, not merely "a URL":- // a connection that speaks several protocols has a different base URL for- // each, and picking the first would point the harness at the wrong port.- const protocol = /_BASE_URL$/.test(name) ? name.replace(/_BASE_URL$/, '').toLowerCase() : null;- const url = protocol ? connection.transports[protocol]?.baseUrl ?? baseUrl : null;- if (url) envVars[name] = url;- }- return { fields, envVars, hasEnvVars: owned.hasEnvVars };-}-// --- explicit management edits (#6369) ---------------------------------------//// The three edits a human makes to a SHARED backend, as opposed to the link and