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
allow a harness binding on a backend that declares more than one transport (#6460)
[._.]/ Adam Eivya3291a379dda
diff --git a/server/lib/README.md b/server/lib/README.mdindex 0f8df1bb79..a52aea27e4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -200,9 +200,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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). || `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. || `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; 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. |+| `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. |-| `providerRouteRecipes.js` | Minting a FRESH executable route from a connection and a harness command recipe (#6369) — the reverse of `providerConnections.js`, which reads an existing record. `buildRouteRecord({harnessId, mode, providerId, name, connection})` materializes a connection's endpoint, credentials and backend marker into a DISABLED `data/providers.json` record through `PROVIDER_HARNESSES[].recipe`; `mintRouteIds` allocates readable ids keeping the `<stem>` / `<stem>-tui` pairing `providerModeGroups` recognizes; `bindingBlocker` is the pre-write refusal (no recipe, unsupported mode, a transport the harness does not speak or is not the backend's only one, a credential the program requires); `CREATABLE_CONNECTION_KINDS` / `connectionKindLabel` / `connectionKindMarkers` bound the backends a route can honestly describe (`slotstream` and `vendor` deliberately excluded); `bindingProtocol` names the wire a binding needs. Pure: no I/O, no spawn, no provider call.+| `providerRouteRecipes.js` | Minting a FRESH executable route from a connection and a harness command recipe (#6369) — the reverse of `providerConnections.js`, which reads an existing record. `buildRouteRecord({harnessId, mode, providerId, name, connection})` materializes a connection's endpoint, credentials and backend marker into a DISABLED `data/providers.json` record through `PROVIDER_HARNESSES[].recipe`; `mintRouteIds` allocates readable ids keeping the `<stem>` / `<stem>-tui` pairing `providerModeGroups` recognizes; `bindingBlocker` is the pre-write refusal (no recipe, unsupported mode, a transport the backend does not declare, a credential the program requires); `CREATABLE_CONNECTION_KINDS` / `connectionKindLabel` / `connectionKindMarkers` bound the backends a route can honestly describe (`slotstream` and `vendor` deliberately excluded); `bindingProtocol` names the wire a binding needs. Pure: no I/O, no spawn, no provider call.| `providerRouteSettings.js` | The MODE-OVERRIDE half of a provider route (#6369) — the route-owned fields a human tunes per execution mode (`args`, `timeout`, `effort` and the `defaultModel`/`lightModel`/`mediumModel`/`heavyModel`/`ultraModel` pins), mirroring what the toolkit's `sharedModeUpdates` already declares mode-specific. `ROUTE_SETTING_FIELDS` / `ROUTE_SETTING_KEYS` / `routeSettingKeys(mode)` name the set (`args` reaches cli/tui only); `routeSettingsFor(provider)` reads it off a record with absent and cleared collapsing to `null`; `routeSettingsSchema` is the wire shape `GET /api/providers/management` publishes; `unsupportedRouteSettings` rejects a key the route's mode does not accept; and `routeSettingsRevision` is the stale-edit fingerprint — a hash of the values as they are in providers.json rather than a graph row revision, so an edit made through `/ai/edit/:providerId` is caught too. Connection-owned values and execution consent (`enabled`) are deliberately absent. Pure: no I/O.| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. |diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsindex da07fc33e7..e302a66e2b 100644--- a/server/lib/providerGraphRecords.js+++ b/server/lib/providerGraphRecords.js@@ -286,9 +286,11 @@ const identityKey = ({ kind, transports, credentials }) => JSON.stringify([* `sameConnectionIdentity` stays strict on purpose: it answers "are these two* records the same backend?" at IMPORT time, where equality is what stops an* accidental merge. This is the looser question reconciliation asks about a- * link a human already made.+ * link a human already made — and the same question `createBinding` asks of a+ * freshly minted record, so a create is accepted on exactly the terms the next+ * reconciliation pass will judge it by.*/-function routeBelongsOnConnection(profile, connection) {+export function routeBelongsOnConnection(profile, connection) {if (!connection || profile.kind !== connection.kind) return false;const declared = connection.transports || {};const transports = Object.entries(profile.transports || {});diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.jsindex 05da154b2f..98e6f22284 100644--- a/server/lib/providerRouteRecipes.js+++ b/server/lib/providerRouteRecipes.js@@ -115,13 +115,18 @@ export function connectionBlocker({ kind, transports }) {/*** Why this connection cannot carry a route for this harness, or `null`.*- * The transport rule is stricter than "declares the protocol": the connection- * must declare that protocol and NOTHING else. It was written that way because- * reconciliation demanded a route describe its connection EXACTLY, so a route- * minted onto a two-protocol row was cloned straight back off it on the next- * pass. #6452 replaced that with containment, so the strictness is now- * conservatism rather than a guard against a silently undone create — relaxing- * it to "declares the protocol" is tracked in #6460.+ * The transport rule is CONTAINMENT: the connection must declare the harness's+ * protocol, and may declare others beside it. It once demanded that protocol+ * and nothing else, because reconciliation asked a route to describe its+ * connection EXACTLY and so cloned a route minted onto a two-protocol row+ * straight back off it on the next pass. #6452 replaced that equality test+ * with containment (`routeBelongsOnConnection`), which is what lets a second+ * harness be CREATED on one multi-protocol daemon rather than only linked onto+ * it (#6460) — an Ollama daemon reached by Claude on its Anthropic port and by+ * Codex on its `/v1` port is one backend, and both routes stay on it.+ *+ * A connection declaring NO transport is still refused: a row naming no+ * endpoint cannot carry a route at all.** @returns {{code:string, message:string}|null}*/@@ -143,10 +148,10 @@ export function bindingBlocker({ harnessId, modes, connection }) {const protocol = bindingProtocol(harnessId);const declared = Object.keys(connection.transports || {});- if (declared.length !== 1 || declared[0] !== protocol) {+ if (!declared.includes(protocol)) {return {code: 'PROVIDER_GRAPH_TRANSPORT_MISMATCH',- message: `This backend declares ${declared.length > 0 ? declared.join(', ') : 'no'} transport(s); a ${harness?.label || 'direct API'} route needs a backend that declares ${protocol} and nothing else.`,+ message: `This backend declares ${declared.length > 0 ? declared.join(', ') : 'no'} transport(s); a ${harness?.label || 'direct API'} route needs a backend that declares ${protocol}.`,};}diff --git a/server/routes/providers.connectionCreate.test.js b/server/routes/providers.connectionCreate.test.jsindex 75d782340a..c941359b5e 100644--- a/server/routes/providers.connectionCreate.test.js+++ b/server/routes/providers.connectionCreate.test.js@@ -25,6 +25,7 @@ import express, { Router } from 'express';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';import { providerConnectionProfile, sameConnectionIdentity } from '../lib/providerConnections.js';+import { planGraphReconciliation, reconciliationIsNoop } from '../lib/providerGraphRecords.js';const store = {readGraph: vi.fn(),@@ -301,6 +302,9 @@ describe('POST /api/providers/bindings', () => {});it('refuses a backend whose transport the harness does not speak', async () => {+ // The half of the transport rule that did NOT relax: this row declares the+ // openai wire and nothing else, so a Claude route on it would name an+ // endpoint the backend does not serve.const res = await request(app()).post('/api/providers/bindings').send({ connectionId: OLLAMA_OPENAI, harnessId: 'claude', modes: ['cli'] });@@ -309,15 +313,49 @@ describe('POST /api/providers/bindings', () => {expect(providerService.createProvider).not.toHaveBeenCalled();});- it('refuses a backend a minted route could not describe, before anything is written', async () => {- // Two transports: a provider record names one endpoint, so no minted route- // could ever report this connection's identity back.+ it('mints a route on a backend that declares a SECOND protocol for another harness', async () => {+ // One Ollama daemon reached by Claude on its Anthropic port and by an+ // OpenAI-compatible harness on `/v1` is ONE backend. A provider record+ // names one endpoint, so this route describes only the anthropic half —+ // #6452 made reconciliation judge that by CONTAINMENT, which is what lets+ // the create through instead of refusing it (#6460).const res = await request(app()).post('/api/providers/bindings').send({ connectionId: MULTI, harnessId: 'claude', modes: ['cli'] });- expect(res.status).toBe(409);- expect(providerService.createProvider).not.toHaveBeenCalled();- expect(store.writeGraph).not.toHaveBeenCalled();+ expect(res.status).toBe(201);+ const record = created().get(res.body.routeIds[0]);+ // The harness's OWN transport, and only it: the record carries no trace of+ // the protocol the other harness on this backend speaks.+ expect(record.envVars).toEqual({ ANTHROPIC_BASE_URL: DAEMON, ANTHROPIC_AUTH_TOKEN: TOKEN });+ expect(record.endpoint).toBe(DAEMON);+ expect(record.envVars).not.toHaveProperty('OPENAI_BASE_URL');+ expect(record.envVars).not.toHaveProperty('OPENAI_API_KEY');+ expect(record.secretEnvVars).toEqual(['ANTHROPIC_AUTH_TOKEN']);+ });++ it('leaves that cross-protocol binding untouched through a reconciliation pass', async () => {+ // The property #6452 established and this create depends on: a route the+ // stored connection CONTAINS stays on it, rather than being cloned onto a+ // single-transport connection of its own on the very next pass.+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: MULTI, harnessId: 'claude', modes: ['cli'] });+ const [written] = store.writeGraph.mock.calls.at(-1);++ const plan = planGraphReconciliation(+ { connections: graphFixture().connections, bindings: written.bindings, routes: written.routes },+ [created().get(res.body.routeIds[0])],+ );++ expect(reconciliationIsNoop(plan)).toBe(true);+ expect(plan.conflicts).toEqual([]);+ expect(plan.regroups).toHaveLength(1);+ expect(plan.regroups[0]).toMatchObject({+ bindingId: written.bindings[0].id,+ connectionAction: 'unchanged',+ // Republished AS STORED — narrowing the row to this route's single+ // transport would strand the other harness on it.+ connection: { id: MULTI, transports: { anthropic: { baseUrl: DAEMON }, openai: { baseUrl: DAEMON_OPENAI } } },+ });});it('refuses a Claude route on a backend with no auth token rather than minting one that cannot start', async () => {diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex 7a492441c6..00b235b883 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -3,7 +3,6 @@ import { ServerError } from '../lib/errorHandler.js';import {compareBackendEndpoints,providerConnectionProfile,- sameConnectionIdentity,withConnectionOwnedFields,} from '../lib/providerConnections.js';import {@@ -12,6 +11,7 @@ import {nextConnectionCatalog,planGraphReconciliation,reconciliationIsNoop,+ routeBelongsOnConnection,sanitizeCatalogError,toConnectionDto,toManagementGraphDto,@@ -838,11 +838,15 @@ export function createConnection({ kind, label, transports, credentials }) {* 1. **Refuse before writing.** `bindingBlocker` rejects a harness with no* recipe, a mode it has no support for, a backend whose transport it does* not speak, and a backend missing a credential the program requires.- * 2. **A minted route must describe the connection it was minted for.** The+ * 2. **A minted route must sit on the connection it was minted for.** The* record is fed straight back through `providerConnectionProfile` and- * compared with `sameConnectionIdentity`. A mismatch is refused rather- * than stored, because reconciliation would otherwise clone the binding- * onto a connection of its own on the very next pass.+ * checked with `routeBelongsOnConnection` — the SAME containment test+ * reconciliation applies, so a create is judged on exactly the terms the+ * next pass will judge it by. A route the row does not contain is refused+ * rather than stored, because reconciliation would otherwise clone the+ * binding onto a connection of its own on the very next pass. Containment+ * rather than identity is what lets one route be minted on a backend that+ * declares a second protocol for another harness (#6460).* 3. **Nothing is enabled.** The binding and every route arrive disabled with* no model pins and no transport consent. Enabling stays an explicit act* on the route editor, which is where granting execution belongs.@@ -884,7 +888,7 @@ export function createBinding({ connectionId, harnessId, modes, label }) {connection,}));for (const record of records) {- if (!sameConnectionIdentity(providerConnectionProfile(record), asProfile(connection))) {+ if (!routeBelongsOnConnection(providerConnectionProfile(record), connection)) {throw new ServerError(`A ${harnessLabel} route cannot describe this backend as it is configured; adjust the backend's transport or credentials first`,{ status: 409, code: 'PROVIDER_GRAPH_CONNECTION_INCOMPATIBLE' });