Skip to content

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

feat: harness capability bindings, a direct-API harness and service definitions (#7562)

[._.]/ Adam Eivyb1b1f641d7ff
diff --git a/server/lib/README.md b/server/lib/README.md
index ad3350d116..2a0872251b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -228,15 +228,16 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, idPattern, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)`, `familyForProviderId(id)` (the weaker id-only classifier a Zod schema can use, null when the id names no family) → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |
| `fleetQuotas.js` | Unifies subscription-quota readings across federated instances — one plan, several machines, each able to read only its own local CLI. `sanitizeQuotaCards` bounds a peer-supplied payload to the wire shape; `mergeFleetQuotaCards(localCards, peerEntries)` folds every peer's reading into this install's cards, taking the FRESHEST reading per limit key (the meters are account-wide, so summing them would multiply one allowance) and SUMMING activity counts (those are per-machine, which is why the provider captions them "does not include other devices"); `fleetNote` writes the caption naming what was combined. `metrics[]` is left local — its values are prose, not addends. Fed by `services/providerQuotaShare.js` (this machine's readings, persisted) and `services/peerUsage.js` (the `usage` sync category that carries them). |
| `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. 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`. |
+| `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. |
+| `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)` / `isCompatible` (which bindings reach a resolved service instance), `CREATABLE_HARNESS_IDS` (mintable from a bare connection) and `harnessConnectionBlocker` (why not: `noRecipe`, or a `connectionLimit` on 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 id table 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. |
| `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. |
| `providerModePairing.js` | May an existing record gain the OTHER execution mode of its harness (#7501) — `tuiModeAddition(provider, providers, executionModes?)` is the ONE verdict behind both the `canAddTuiMode` flag `GET /providers` decorates each record with (so the card offers "Add interactive mode") and the refusal `POST /providers/:id/modes/tui` answers with, so a card can never advertise an action the server rejects. Refuses a non-CLI record (the CLI id is the stem, so minting it from a TUI record would be a rename), a record storing no command, and a KNOWN harness declaring no TUI mode; an UNKNOWN harness passes with empty argv rather than a guess, while a known one starts from its recipe’s proven interactive line. Asks whether the harness already HAS its interactive mode (the record’s `providerModeGroups` group — the shipped `grok-cli`/`grok-tui` pair leaves `grok-cli-tui` unclaimed, so an id-only check would mint a third record beside it), and separately 409s on a taken `<id>-tui` rather than suffixing around it. 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 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.
+| `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. `materializeRoute({harness, method, serviceInstance, bootstrap?, selection?, overrides?})` (#7562) generalizes `buildRouteRecord` from a connection to a SERVICE instance: picks the harness's first compatible binding, writes base URL / credential / static env / backend markers / inline OpenCode config / Pi `--provider` per that binding plus the recipe's mode argv, stamps `harnessId` / `method` / `serviceId` / `servicePlan`, and — for a non-`api` method with a bootstrap app — the `credentialBootstrap` object `composeBootstrapSpawn` turns into `<bootstrap> run <harness> -- <args>`; throws typed errors (`HARNESS_SERVICE_INCOMPATIBLE`, `SERVICE_ENDPOINT_REQUIRED`, `SERVICE_CREDENTIAL_REQUIRED`, `SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED`) rather than minting a route that cannot run. `routeDescribesService(profile, instance)` is the round-trip contract: fed back through `providerConnectionProfile`, a materialized record classifies onto the service it was built for. 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/`), `parseKimiWireLog`/`parseKimiSessionIndex` (`~/.kimi-code/sessions/.../agents/<id>/wire.jsonl`, indexed by `~/.kimi-code/session_index.jsonl`), `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. Kimi's `usage.record` lines are already discrete per-call deltas (no cumulative-snapshot trap), but split across one `wire.jsonl` per agent — a subagent's spend is never in its parent's file. 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/aiToolkit/internal/harnesses.js b/server/lib/aiToolkit/internal/harnesses.js
new file mode 100644
index 0000000000..74e83612c3
--- /dev/null
+++ b/server/lib/aiToolkit/internal/harnesses.js
@@ -0,0 +1,32 @@
+/**
+ * The harness ids PortOS composes AI runs from, and the one translation between
+ * the registry's name for a direct API binding (`direct`) and the graph's
+ * (`harness_id = NULL`).
+ *
+ * A DELIBERATE MIRROR of the minimum `server/lib/providerHarnesses.js` the
+ * toolkit needs (#7562). This directory is vendored and stays self-contained —
+ * no imports out to other PortOS modules (see `aiToolkit/AGENTS.md`) — so the
+ * lookups are duplicated rather than imported, exactly as `gateways.js` is.
+ * `server/lib/providerHarnesses.parity.test.js` fails when the two drift.
+ *
+ * Only IDENTITY is mirrored: the bindings, recipes and matchers stay host-side,
+ * because the toolkit never materializes a route — it resolves a composite
+ * provider id (`harness.method@service`) back to a record the host wrote.
+ */
+
+/** Every harness id, in registry order. */
+export const HARNESS_IDS = Object.freeze([
+ 'claude', 'opencode', 'kilo', 'openchamber', 'codex', 'antigravity', 'cursor', 'grok', 'kimi', 'pi', 'direct',
+]);
+
+/** The harness id a direct API record resolves to. */
+export const DIRECT_HARNESS_ID = 'direct';
+
+/** `null` (the graph's spelling of a direct API binding) → `direct`. */
+export const normalizeHarnessId = (harnessId) => harnessId ?? DIRECT_HARNESS_ID;
+
+/** `direct` → `null`, so the graph keeps its nullable column and partial unique index. */
+export const graphHarnessId = (harnessId) => (harnessId === DIRECT_HARNESS_ID ? null : harnessId ?? null);
+
+/** Whether `harnessId` names a harness this build knows. */
+export const isHarnessId = (harnessId) => HARNESS_IDS.includes(harnessId);
diff --git a/server/lib/index.js b/server/lib/index.js
index 4cc500ae1f..3d5da1e9c9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -491,6 +491,7 @@ export * from './providerGraphRecords.js';
export * from './providerModelAliases.js';
export * from './providerModePairing.js';
export * from './providerRouteRecipes.js';
+export * from './serviceDefinitions.js';
export * from './providerRouteSettings.js';
export * from './personaTraitBlend.js';
export * from './pipelineIssueOrder.js';
diff --git a/server/lib/providerGateways.js b/server/lib/providerGateways.js
index a4af62ad65..e6fc9010b3 100644
--- a/server/lib/providerGateways.js
+++ b/server/lib/providerGateways.js
@@ -21,8 +21,9 @@
* thinking toggle (`THINKING_STYLE[<gateway>] === null`).
*
* Dependency-light on purpose (mirrors `providerVendors.js` / `cliProviderArgs.js`):
- * it imports nothing, so it stays importable from `providerModels.js`, which the
- * standalone autofixer process pulls in.
+ * it imports only the dependency-free `serviceDefinitions.js` leaf it is derived
+ * from, so it stays importable from `providerModels.js`, which the standalone
+ * autofixer process pulls in.
*
* **Two copies of this table exist, by architecture, and must stay in lockstep:**
* 1. this file — the PortOS server;
@@ -33,6 +34,8 @@
* `client/src/utils/providerGateways.js` re-exports it.
*/
+import { SERVICE_DEFINITIONS } from './serviceDefinitions.js';
+
/**
* @typedef {object} ProviderGateway
* @property {string} id — the OpenCode provider namespace, the `gatewayBacked`
@@ -52,30 +55,26 @@
* own key field.
*/
-/** @type {readonly ProviderGateway[]} */
-export const PROVIDER_GATEWAYS = Object.freeze([
- Object.freeze({
- id: 'orcarouter',
- label: 'OrcaRouter',
- baseURL: 'https://api.orcarouter.ai/v1',
- apiKeyEnv: 'ORCAROUTER_API_KEY',
- legacyMarker: 'orcarouterBacked',
- legacyApiKeyField: 'orcarouterApiKey',
- }),
- Object.freeze({
- id: 'openrouter',
- label: 'OpenRouter',
- baseURL: 'https://openrouter.ai/api/v1',
- apiKeyEnv: 'OPENROUTER_API_KEY',
- }),
- Object.freeze({
- id: 'nvidia-nim',
- label: 'NVIDIA NIM',
- baseURL: 'https://integrate.api.nvidia.com/v1',
- apiKeyEnv: 'NVIDIA_API_KEY',
- keyUrl: 'https://build.nvidia.com',
- }),
-]);
+/**
+ * @type {readonly ProviderGateway[]}
+ *
+ * DERIVED from the service definitions carrying a `gateway` column
+ * (`serviceDefinitions.js`, #7562) rather than typed here: a gateway is a
+ * service a harness can be pointed at, and the epic composes routes from that
+ * table. The projection keeps this row shape byte-for-byte, so every consumer
+ * and the toolkit mirror (`aiToolkit/internal/gateways.js`) are untouched.
+ */
+export const PROVIDER_GATEWAYS = Object.freeze(SERVICE_DEFINITIONS
+ .filter((service) => service.gateway)
+ .map((service) => Object.freeze({
+ id: service.id,
+ label: service.label,
+ baseURL: service.transports.openai.defaultBaseUrl,
+ apiKeyEnv: service.gateway.apiKeyEnv,
+ ...(service.credential.keyUrl ? { keyUrl: service.credential.keyUrl } : {}),
+ ...(service.gateway.legacyMarker ? { legacyMarker: service.gateway.legacyMarker } : {}),
+ ...(service.gateway.legacyApiKeyField ? { legacyApiKeyField: service.gateway.legacyApiKeyField } : {}),
+ })));
/** Every gateway id — the namespace key space `opencodeConfig.js` extends. */
export const PROVIDER_GATEWAY_IDS = Object.freeze(PROVIDER_GATEWAYS.map((g) => g.id));
diff --git a/server/lib/providerGraphPreview.js b/server/lib/providerGraphPreview.js
index dd7632b0bf..2e6af33dcb 100644
--- a/server/lib/providerGraphPreview.js
+++ b/server/lib/providerGraphPreview.js
@@ -13,6 +13,7 @@ import {
import {
PROVIDER_HARNESS_IDS,
ROUTE_MODES,
+ graphHarnessId,
harnessForProvider,
harnessSupportsMode,
providerRouteMode,
@@ -295,7 +296,9 @@ export function buildProviderGraphPreview({ providers = [], activeProvider = nul
continue;
}
- const harnessId = harness?.id ?? null;
+ // The registry names a direct API record's harness `direct` (#7562); the
+ // graph stores it as `NULL`, and this is the one translation point.
+ const harnessId = graphHarnessId(harness?.id);
const bucketKey = connectionBucketKey(harnessId, leadProfile);
const bucket = buckets.get(bucketKey) || [];
// A record that declares NO transport (a vendor subscription harness, say)
diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.js
index e302a66e2b..2b22b474ad 100644
--- a/server/lib/providerGraphRecords.js
+++ b/server/lib/providerGraphRecords.js
@@ -6,7 +6,7 @@ import {
PROVIDER_GRAPH_SCHEMA_VERSION,
buildProviderGraphPreview,
} from './providerGraphPreview.js';
-import { PROVIDER_HARNESSES, PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './providerHarnesses.js';
+import { CREATABLE_HARNESS_IDS, PROVIDER_HARNESSES, PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './providerHarnesses.js';
import {
effectiveModelAliases,
modelAliasRevision,
@@ -142,7 +142,9 @@ const creatableKindSchema = z.object({
/** The static half of the create surface. Derived from code, never from rows. */
const CREATABLE = Object.freeze({
- harnesses: Object.freeze(PROVIDER_HARNESSES.filter((harness) => harness.recipe).map((harness) => Object.freeze({
+ // Creatable FROM A CONNECTION — a subscription program or Pi carries a
+ // recipe too (#7562) but composes only onto named services, not here.
+ harnesses: Object.freeze(PROVIDER_HARNESSES.filter((harness) => CREATABLE_HARNESS_IDS.includes(harness.id)).map((harness) => Object.freeze({
id: harness.id,
label: harness.label,
modes: [...harness.modes],
diff --git a/server/lib/providerHarnesses.js b/server/lib/providerHarnesses.js
index 4dc1701fa3..6fbd5ec5eb 100644
--- a/server/lib/providerHarnesses.js
+++ b/server/lib/providerHarnesses.js
@@ -26,8 +26,15 @@ import { isOpenchamberProvider } from './openchamber.js';
* - `providerGateways.js`, which is a hosted OpenAI-compatible backend.
*
* A harness answers only: which program runs, which execution modes it can be
- * driven in, which wire protocol it speaks to a backend connection, and how a
- * canonical backend model name becomes the string that program accepts.
+ * driven in, which wire protocol it speaks to a backend connection, how a
+ * canonical backend model name becomes the string that program accepts — and,
+ * since #7562, every WAY it can be pointed at a service (`bindings`, below).
+ *
+ * The `direct` row is the one harness that is not a program: a direct API
+ * record is PortOS's own HTTP client speaking the OpenAI wire. Giving it a row
+ * lets the epic compose `direct.api@<service>` from the same tables as every
+ * CLI, while the graph keeps storing it as `harness_id = NULL` — see
+ * {@link normalizeHarnessId} / {@link graphHarnessId}.
*
* Rows match through the existing `is*Provider` predicates rather than a fresh
* command-string test, so a path-configured binary, a `.exe`, and the shipped
@@ -37,9 +44,12 @@ import { isOpenchamberProvider } from './openchamber.js';
/** Execution modes a route can carry. Mirrors the provider record's `type`. */
export const ROUTE_MODES = Object.freeze(['cli', 'tui', 'api']);
-/** Modes every CLI/TUI harness supports. Direct API bindings carry no harness. */
+/** Modes every CLI/TUI harness supports. */
const CLI_TUI_MODES = Object.freeze(['cli', 'tui']);
+/** The `direct` harness only: PortOS's own HTTP client has no process to drive. */
+const API_ONLY_MODES = Object.freeze(['api']);
+
/**
* Headless only. A harness whose interactive surface is not a terminal — today
* OpenChamber, whose UI is a web app and whose bare binary starts a server —
@@ -56,17 +66,55 @@ const CLI_ONLY_MODES = Object.freeze(['cli']);
* one — so adding a `recipe: null` row for either of the others would have told
* the user their harness "reaches only its own vendor service", which is both
* wrong and points at the wrong remedy. `noRecipe` is set on exactly the rows
- * whose `recipe` is `null`, an invariant `providerHarnesses.test.js` pins.
+ * with no `bindings` — the ones no service can be composed onto — an invariant
+ * `providerHarnesses.test.js` pins. (`direct` has no recipe either, but it is
+ * not a program; it binds, so it carries no reason.)
*/
const NO_RECIPE = Object.freeze({
- /** A `native`-protocol program: there is no user-supplied backend to name. */
- VENDOR_SERVICE: 'reaches only its own vendor service',
/** The backend lives in a config file PortOS does not write (Kilo). */
UNWRITTEN_CONFIG: 'resolves its backend from its own config file, which PortOS does not write',
/** The backend belongs to a separate runtime the user configures (OpenChamber). */
EXTERNAL_RUNTIME: 'runs against a workspace runtime you sign in to separately',
});
+/**
+ * Why a harness that DOES carry a recipe still cannot be minted from a bare
+ * connection (`connectionLimit` on the row). Such a row is composable onto the
+ * services its bindings name — `materializeRoute` runs it — but a connection
+ * is an arbitrary endpoint, and these programs cannot be pointed at one.
+ * Quoted by the create endpoint's refusal, like {@link NO_RECIPE}.
+ */
+const CONNECTION_LIMIT = Object.freeze({
+ /** A subscription program: it signs into its own vendor service and nothing else. */
+ VENDOR_SERVICE: 'reaches only its own vendor service',
+ /**
+ * Verified against the installed CLI (`pi --help`, its `docs/models.md`): Pi
+ * reaches a backend by `--provider <name>` / `--model provider/id` plus that
+ * provider's env key, and a CUSTOM endpoint only through
+ * `~/.pi/agent/models.json`, a user-owned file PortOS does not write. So a
+ * Pi route can be materialized for any service Pi ships a provider name for
+ * (`piProvider` on the definition) — nvidia, openrouter, anthropic, … — but
+ * not for an arbitrary local daemon or endpoint.
+ */
+ PI_BUILTIN_PROVIDERS: 'reaches only the services Pi ships a provider name for (a custom endpoint lives in Pi\'s own models.json, which PortOS does not write)',
+});
+
+/**
+ * A recipe for a program that only ever talks to the service it signs into:
+ * its argv is real (lifted from the shipped samples like every other recipe)
+ * but it has no endpoint or credential column to materialize.
+ */
+const subscriptionRecipe = (command, { cli, tui }) => Object.freeze({
+ command,
+ timeout: HARNESS_TIMEOUT_MS,
+ baseUrl: null,
+ credential: null,
+ modes: {
+ cli: { args: cli, headlessArgs: [] },
+ tui: { args: tui, tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },
+ },
+});
+
/**
* The COMMAND RECIPE half of a harness row (#6369).
*
@@ -109,7 +157,49 @@ const TUI_PROMPT_DELAY_MS = 2500;
const HARNESS_TIMEOUT_MS = 600000;
/**
- * @type {readonly {id:string,label:string,modes:readonly string[],protocol:string,recipe:object|null,matches:(p:object)=>boolean}[]}
+ * The CAPABILITY BINDINGS of a harness row (#7562): one entry per way the
+ * program can be pointed at a service definition (`serviceDefinitions.js`).
+ * `compatibleBindings` matches them against a resolved service instance, and
+ * `materializeRoute` (`providerRouteRecipes.js`) writes the record each one
+ * describes. Shapes (frozen; a new shape is a new writer arm, not a new field):
+ *
+ * - `{ via: 'subscription', service }` — the harness signs in itself; the
+ * record carries no endpoint and no key.
+ * - `{ protocol, baseUrl, credential }` — any service declaring `protocol`
+ * as a transport. `baseUrl.via` is `env` (`name`), `field` (the record's
+ * own `endpoint`) or `opencodeConfig` (the inline provider JSON OpenCode
+ * reads). `credential.via` is `env` (`name`, `required`), `field` (the
+ * record's `apiKey`) or `gatewayEnv` (the gateway's own key var).
+ * - `{ service, env, credential }` — a named service reached through a static
+ * env switch (Bedrock: `CLAUDE_CODE_USE_BEDROCK=1`).
+ * - `{ service, baseUrl: { via: 'opencodeConfig', builtin: true }, credential }`
+ * — a service OpenCode already knows; only permissions are declared.
+ * - `{ via: 'codexOss', localRuntime: [...], protocol, baseUrl, credential }`
+ * — Codex's `--oss --local-provider` (≥ `CODEX_OSS_MIN_VERSION`), emitted
+ * at spawn from the runtime marker the record carries; the endpoint lands
+ * on the record like any protocol binding's.
+ * - `{ via: 'piProvider', credential }` — any service carrying `piProvider`,
+ * selected with `--provider <name>` and keyed from the service's own env var.
+ *
+ * A row with NO bindings is exactly a row with `noRecipe`: the program cannot
+ * be pointed at anything from data. `providerHarnesses.test.js` pins that.
+ */
+
+/** The one direct-API binding: PortOS's HTTP client on any OpenAI-compatible service. */
+const DIRECT_API_BINDING = Object.freeze({
+ protocol: 'openai',
+ baseUrl: Object.freeze({ via: 'field' }),
+ credential: Object.freeze({ via: 'field', required: false }),
+});
+
+/** The credential Claude Code sends: required even to a daemon that ignores it. */
+const CLAUDE_AUTH_TOKEN = Object.freeze({ via: 'env', name: 'ANTHROPIC_AUTH_TOKEN', required: true });
+
+/** Pi's argv for the two modes, lifted from the shipped `pi-cli` / `pi-tui` samples. */
+const PI_TUI_ARGS = Object.freeze(['--approve']);
+
+/**
+ * @type {readonly {id:string,label:string,modes:readonly string[],protocol:string,recipe:object|null,bindings:readonly object[],matches:(p:object)=>boolean}[]}
*/
export const PROVIDER_HARNESSES = Object.freeze([
Object.freeze({
@@ -123,12 +213,21 @@ export const PROVIDER_HARNESSES = Object.freeze([
baseUrl: { via: 'env', name: 'ANTHROPIC_BASE_URL' },
// Claude Code will not start without a token, even against a local daemon
// that ignores it — so a backend carrying none cannot mint a Claude route.
- credential: { via: 'env', name: 'ANTHROPIC_AUTH_TOKEN', required: true },
+ credential: CLAUDE_AUTH_TOKEN,
modes: {
cli: { args: ['--print'], headlessArgs: CLAUDE_HEADLESS_ARGS },
tui: { args: ['--dangerously-skip-permissions'], tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },
},
}),
+ bindings: Object.freeze([
+ Object.freeze({ via: 'subscription', service: 'claude-subscription' }),
+ Object.freeze({ protocol: 'anthropic', baseUrl: Object.freeze({ via: 'env', name: 'ANTHROPIC_BASE_URL' }), credential: CLAUDE_AUTH_TOKEN }),
+ Object.freeze({
+ service: 'bedrock',
+ env: Object.freeze({ CLAUDE_CODE_USE_BEDROCK: '1' }),
+ credential: Object.freeze({ via: 'env', name: 'AWS_BEARER_TOKEN_BEDROCK', required: true }),
+ }),
+ ]),
matches: isClaudeProvider,
}),
Object.freeze({
@@ -148,6 +247,18 @@ export const PROVIDER_HARNESSES = Object.freeze([
tui: { args: [], tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },
},
}),
+ bindings: Object.freeze([
+ // OpenCode's own hosted service is a provider it ships; only permissions
+ // go in the inline config, and the key rides its documented env var.
+ Object.freeze({
+ service: 'opencode-zen',
+ baseUrl: Object.freeze({ via: 'opencodeConfig', builtin: true }),
+ credential: Object.freeze({ via: 'env', name: 'OPENCODE_API_KEY', required: true }),
+ }),
+ // A gateway's key is materialized under the gateway's own variable (what
+ // the spawner exports for OpenCode); anything else keys off the record.
+ Object.freeze({ protocol: 'openai', baseUrl: Object.freeze({ via: 'opencodeConfig' }), credential: Object.freeze({ via: 'gatewayEnv', required: false }) }),
+ ]),
matches: isOpencodeProvider,
}),
Object.freeze({
@@ -164,6 +275,7 @@ export const PROVIDER_HARNESSES = Object.freeze([
// installable but not creatable from a connection.
recipe: null,
noRecipe: NO_RECIPE.UNWRITTEN_CONFIG,
+ bindings: Object.freeze([]),
matches: isKiloProvider,
}),
Object.freeze({
@@ -176,6 +288,7 @@ export const PROVIDER_HARNESSES = Object.freeze([
// is no PortOS-supplied backend for a minted route to carry.
recipe: null,
noRecipe: NO_RECIPE.EXTERNAL_RUNTIME,
+ bindings: Object.freeze([]),
matches: isOpenchamberProvider,
}),
Object.freeze({
@@ -193,6 +306,21 @@ export const PROVIDER_HARNESSES = Object.freeze([
tui: { args: [], tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },
},
}),
+ bindings: Object.freeze([
+ Object.freeze({ via: 'subscription', service: 'codex-subscription' }),
+ // `--oss --local-provider <ollama|lmstudio>` is emitted at spawn from the
+ // record's runtime marker (`buildCodexOssArgs`), so the binding only has
+ // to name the runtimes Codex can serve — the same pair as
+ // `CODEX_OSS_LOCAL_PROVIDERS`, pinned by providerHarnesses.test.js.
+ Object.freeze({
+ via: 'codexOss',
+ localRuntime: Object.freeze(['ollama', 'lmstudio']),
+ protocol: 'openai',
+ baseUrl: Object.freeze({ via: 'field' }),
+ credential: Object.freeze({ via: 'field', required: false }),
+ }),
+ Object.freeze({ protocol: 'openai', baseUrl: Object.freeze({ via: 'env', name: 'OPENAI_BASE_URL' }), credential: Object.freeze({ via: 'env', name: 'OPENAI_API_KEY', required: true }) }),
+ ]),
matches: isCodexProvider,
}),
Object.freeze({
@@ -200,10 +328,9 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Antigravity',
modes: CLI_TUI_MODES,
protocol: 'native',
- // This program reaches only its own vendor service, so there is no
- // connection to point a freshly minted route at.
- recipe: null,
- noRecipe: NO_RECIPE.VENDOR_SERVICE,
+ recipe: subscriptionRecipe('agy', { cli: ['--print', '--dangerously-skip-permissions'], tui: ['--dangerously-skip-permissions'] }),
+ connectionLimit: CONNECTION_LIMIT.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ via: 'subscription', service: 'antigravity' })]),
matches: isAntigravityProvider,
}),
Object.freeze({
@@ -211,10 +338,9 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Cursor Agent',
modes: CLI_TUI_MODES,
protocol: 'native',
- // This program reaches only its own vendor service, so there is no
- // connection to point a freshly minted route at.
- recipe: null,
- noRecipe: NO_RECIPE.VENDOR_SERVICE,
+ recipe: subscriptionRecipe('cursor-agent', { cli: ['--print', '--force'], tui: ['--force'] }),
+ connectionLimit: CONNECTION_LIMIT.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ via: 'subscription', service: 'cursor' })]),
matches: isCursorProvider,
}),
Object.freeze({
@@ -222,10 +348,9 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Grok',
modes: CLI_TUI_MODES,
protocol: 'native',
- // This program reaches only its own vendor service, so there is no
- // connection to point a freshly minted route at.
- recipe: null,
- noRecipe: NO_RECIPE.VENDOR_SERVICE,
+ recipe: subscriptionRecipe('grok', { cli: [], tui: [] }),
+ connectionLimit: CONNECTION_LIMIT.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ via: 'subscription', service: 'grok-build' })]),
matches: isGrokProvider,
}),
Object.freeze({
@@ -233,27 +358,63 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Kimi Code',
modes: CLI_TUI_MODES,
protocol: 'native',
- // This program reaches only its own vendor service, so there is no
- // connection to point a freshly minted route at.
- recipe: null,
- noRecipe: NO_RECIPE.VENDOR_SERVICE,
+ recipe: subscriptionRecipe('kimi', { cli: [], tui: ['--yolo'] }),
+ connectionLimit: CONNECTION_LIMIT.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ via: 'subscription', service: 'kimi' })]),
matches: isKimiProvider,
}),
Object.freeze({
id: 'pi',
label: 'Pi',
modes: CLI_TUI_MODES,
- protocol: 'native',
- // This program reaches only its own vendor service, so there is no
- // connection to point a freshly minted route at.
- recipe: null,
- noRecipe: NO_RECIPE.VENDOR_SERVICE,
+ // Pi speaks both wires; `openai` is what a bare record classifies as, and
+ // the binding below is what says which one a given service gets.
+ protocol: 'openai',
+ recipe: Object.freeze({
+ command: 'pi',
+ timeout: HARNESS_TIMEOUT_MS,
+ // Pi selects its backend by provider NAME, not by URL — see
+ // CONNECTION_LIMIT.PI_BUILTIN_PROVIDERS. The flag is appended to the mode
+ // argv by the writer, so the shipped sample argv stays the prefix.
+ baseUrl: { via: 'piProvider', flag: '--provider' },
+ credential: { via: 'env', required: true },
+ modes: {
+ cli: { args: ['--print', ...PI_TUI_ARGS], headlessArgs: [] },
+ tui: { args: [...PI_TUI_ARGS] },
+ },
+ }),
+ connectionLimit: CONNECTION_LIMIT.PI_BUILTIN_PROVIDERS,
+ bindings: Object.freeze([
+ Object.freeze({ via: 'piProvider', credential: Object.freeze({ via: 'env', required: true }) }),
+ ]),
// No `isPiProvider` predicate exists — `pi` has no vendor module of its own
// beyond `aiToolkit/internal/pi.js`, so match its binary basename directly.
matches: (provider) => commandBasename(provider?.command) === 'pi',
}),
+ Object.freeze({
+ id: 'direct',
+ label: 'Direct API',
+ modes: API_ONLY_MODES,
+ protocol: 'openai',
+ // Not a program: nothing to spawn, so no command recipe — and no
+ // `noRecipe` either, because it CAN be pointed at a service.
+ recipe: null,
+ bindings: Object.freeze([DIRECT_API_BINDING]),
+ matches: (provider) => provider?.type === 'api',
+ }),
]);
+/** The harness id a direct API record resolves to. */
+export const DIRECT_HARNESS_ID = 'direct';
+
+/**
+ * The graph stores a direct API binding as `harness_id = NULL` (nullable
+ * column, partial unique index untouched); the registry names it `direct`.
+ * These two are the only translation between the two vocabularies.
+ */
+export const normalizeHarnessId = (harnessId) => harnessId ?? DIRECT_HARNESS_ID;
+export const graphHarnessId = (harnessId) => (harnessId === DIRECT_HARNESS_ID ? null : harnessId ?? null);
+
/** Every harness id, for schemas that must accept only a real harness. */
export const PROVIDER_HARNESS_IDS = Object.freeze(PROVIDER_HARNESSES.map((h) => h.id));
@@ -266,28 +427,71 @@ export const harnessById = (id) => PROVIDER_HARNESSES.find((h) => h.id === id) |
* property of the program, not a gap in this table.
*/
export const CREATABLE_HARNESS_IDS = Object.freeze(
- PROVIDER_HARNESSES.filter((h) => h.recipe).map((h) => h.id),
+ PROVIDER_HARNESSES.filter((h) => h.recipe && !h.connectionLimit).map((h) => h.id),
);
+/**
+ * Why `harnessId` cannot be minted from a bare connection, or `null` when it
+ * can. A row with no recipe says so through `noRecipe`; Pi has a recipe but a
+ * backend it can only name, not address (`connectionLimit`).
+ */
+export const harnessConnectionBlocker = (harnessId) => {
+ const harness = harnessById(harnessId);
+ return harness?.noRecipe || harness?.connectionLimit || null;
+};
+
/** The command recipe for a harness id, or `null` when it has none. */
export const harnessRecipe = (id) => harnessById(id)?.recipe || null;
/**
- * The harness a provider record is driven by, or `null`.
+ * The harness a provider record is driven by, or `null` for an UNKNOWN one.
*
- * `null` has TWO distinct causes and the caller must not conflate them: an
- * `api`-type record legitimately has no harness (a direct API binding), while a
- * `cli`/`tui` record with no matching row is an UNKNOWN harness that must stay
- * an unlinked legacy route. Use {@link providerRouteMode} to tell them apart.
+ * An `api`-type record resolves to the `direct` row (#7562); it used to be
+ * `null`, which conflated "no program" with "a program this build does not
+ * know" — a `cli`/`tui` record with no matching row, which must stay an
+ * unlinked legacy route. Graph code that stores the id passes it through
+ * {@link graphHarnessId} so a direct binding still lands as `NULL`.
*
* @param {{id?:string, type?:string, command?:string}|null|undefined} provider
* @returns {{id:string,label:string,modes:readonly string[],protocol:string}|null}
*/
export function harnessForProvider(provider) {
- if (!provider || typeof provider !== 'object' || provider.type === 'api') return null;
+ if (!provider || typeof provider !== 'object') return null;
return PROVIDER_HARNESSES.find((h) => h.matches(provider)) || null;
}
+/**
+ * The bindings of `harness` that can reach `serviceInstance` (a resolved
+ * instance from `resolveServiceInstance`), in row order — the first is the one
+ * `materializeRoute` writes. Empty when the pair cannot be composed.
+ *
+ * Matching rules, one per binding shape: a `subscription` / `service` binding
+ * matches by definition id; a `protocol` binding matches when the instance
+ * declares that transport; a `codexOss` binding matches the instance's local
+ * runtime; a `piProvider` binding matches a definition Pi ships a name for. A
+ * definition that is `harnessOnly` matches nothing but that harness.
+ *
+ * @param {object|string} harness - a registry row or its id
+ * @param {{definition: object, transports: object}} serviceInstance
+ * @returns {readonly object[]}
+ */
+export function compatibleBindings(harness, serviceInstance) {
+ const row = typeof harness === 'string' ? harnessById(harness) : harness;
+ const definition = serviceInstance?.definition;
+ if (!row || !definition) return [];
+ if (definition.harnessOnly && definition.harnessOnly !== row.id) return [];
+ const declares = (protocol) => Boolean(serviceInstance.transports?.[protocol]);
+ return row.bindings.filter((binding) => {
+ if (binding.service) return binding.service === definition.id;
+ if (binding.via === 'codexOss') return binding.localRuntime.includes(definition.localRuntime) && declares(binding.protocol);
+ if (binding.via === 'piProvider') return typeof definition.piProvider === 'string';
+ return Boolean(binding.protocol) && declares(binding.protocol);
+ });
+}
+
+/** Whether `harness` can be pointed at `serviceInstance` at all. */
+export const isCompatible = (harness, serviceInstance) => compatibleBindings(harness, serviceInstance).length > 0;
+
/** Whether `harnessId` can be driven in `mode`. Unknown harness → false. */
export const harnessSupportsMode = (harnessId, mode) =>
Boolean(harnessById(harnessId)?.modes.includes(mode));
diff --git a/server/lib/providerHarnesses.parity.test.js b/server/lib/providerHarnesses.parity.test.js
new file mode 100644
index 0000000000..c9da5fee04
--- /dev/null
+++ b/server/lib/providerHarnesses.parity.test.js
@@ -0,0 +1,40 @@
+/**
+ * The harness identity table exists in two places by architecture — the
+ * vendored `aiToolkit/` may not import out of its own directory, so it carries
+ * its own copy of the ids and the `direct` ↔ `null` translation. This pins the
+ * two together, as `providerGateways.parity.test.js` does for gateways, so a
+ * harness added to the registry can never be one the toolkit refuses to
+ * resolve a composite id for.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ DIRECT_HARNESS_ID as SERVER_DIRECT,
+ PROVIDER_HARNESS_IDS,
+ graphHarnessId as serverGraphId,
+ normalizeHarnessId as serverNormalize,
+} from './providerHarnesses.js';
+import {
+ DIRECT_HARNESS_ID as TOOLKIT_DIRECT,
+ HARNESS_IDS,
+ graphHarnessId as toolkitGraphId,
+ isHarnessId,
+ normalizeHarnessId as toolkitNormalize,
+} from './aiToolkit/internal/harnesses.js';
+
+describe('providerHarnesses ↔ aiToolkit/internal/harnesses parity', () => {
+ it('declares the same ids, in the same order', () => {
+ expect(HARNESS_IDS).toEqual(PROVIDER_HARNESS_IDS);
+ expect(TOOLKIT_DIRECT).toBe(SERVER_DIRECT);
+ for (const id of PROVIDER_HARNESS_IDS) expect(isHarnessId(id)).toBe(true);
+ });
+
+ it('translates the direct binding the same way in both directions', () => {
+ for (const id of [null, undefined, 'direct', 'claude', 'pi']) {
+ expect(toolkitNormalize(id)).toBe(serverNormalize(id));
+ expect(toolkitGraphId(id)).toBe(serverGraphId(id));
+ }
+ expect(serverNormalize(null)).toBe('direct');
+ expect(serverGraphId('direct')).toBeNull();
+ expect(serverGraphId(serverNormalize(null))).toBeNull();
+ });
+});
diff --git a/server/lib/providerHarnesses.test.js b/server/lib/providerHarnesses.test.js
index 66bffc3559..2e6664e10d 100644
--- a/server/lib/providerHarnesses.test.js
+++ b/server/lib/providerHarnesses.test.js
@@ -12,9 +12,18 @@ import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { PROVIDER_HARNESSES, harnessById, harnessForProvider } from './providerHarnesses.js';
+import {
+ CREATABLE_HARNESS_IDS,
+ PROVIDER_HARNESSES,
+ compatibleBindings,
+ harnessById,
+ harnessForProvider,
+ isCompatible,
+} from './providerHarnesses.js';
+import { CODEX_OSS_LOCAL_PROVIDERS } from './providerModels.js';
import { PROVIDER_VENDORS } from './providerVendors.js';
import { bindingBlocker } from './providerRouteRecipes.js';
+import { SERVICE_DEFINITIONS, resolveServiceInstance } from './serviceDefinitions.js';
/**
* The legacy Gemini CLI row is a vendor with no harness on purpose: it exists
@@ -28,25 +37,109 @@ describe('harness rows say why they carry no recipe', () => {
// The refusal quotes this field. While `bindingBlocker` hardcoded one reason,
// a row added for a different one told the user their harness "reaches only
// its own vendor service" — wrong, and it points at the wrong remedy.
- it('sets noRecipe on exactly the rows with no recipe', () => {
+ //
+ // Since #7562 the invariant is stated against BINDINGS: a row with none is
+ // exactly a row nothing can be composed onto. `direct` has no recipe (it is
+ // not a program) yet binds, so it carries no reason.
+ it('sets noRecipe on exactly the rows with no bindings', () => {
for (const harness of PROVIDER_HARNESSES) {
- expect(Boolean(harness.noRecipe), `${harness.id}: noRecipe must accompany a null recipe`)
- .toBe(harness.recipe === null);
+ expect(Boolean(harness.noRecipe), `${harness.id}: noRecipe must accompany an empty bindings list`)
+ .toBe(harness.bindings.length === 0);
+ if (harness.id !== 'direct') {
+ expect(harness.recipe === null, `${harness.id}: a program with bindings needs a recipe to materialize them`)
+ .toBe(Boolean(harness.noRecipe));
+ }
}
});
+ // A subscription program (or Pi) HAS a recipe — `<harness>.cli@<service>`
+ // materializes — but cannot be minted from an arbitrary connection; the row
+ // says so, and the create endpoint quotes it.
+ it('marks every recipe-bearing, non-creatable row with a connection limit', () => {
+ for (const harness of PROVIDER_HARNESSES.filter((row) => row.recipe)) {
+ expect(Boolean(harness.connectionLimit), `${harness.id}`).toBe(!CREATABLE_HARNESS_IDS.includes(harness.id));
+ }
+ expect(CREATABLE_HARNESS_IDS).toEqual(['claude', 'opencode', 'codex']);
+ });
+
it('refuses each uncreatable harness with its own reason, not a shared guess', () => {
const connection = { kind: 'ollama', transports: { openai: { baseUrl: 'http://localhost:11434/v1' } }, credentials: {} };
const messages = PROVIDER_HARNESSES
- .filter((harness) => harness.recipe === null)
+ .filter((harness) => harness.id !== 'direct' && !CREATABLE_HARNESS_IDS.includes(harness.id))
.map((harness) => bindingBlocker({ harnessId: harness.id, modes: ['cli'], connection }).message);
// Kilo and OpenChamber are `openai`-protocol rows that still cannot be
// minted — the case that makes "reaches only its own vendor service" false.
expect(messages).toContain(`${harnessById('kilo').label} ${harnessById('kilo').noRecipe}, so it cannot be pointed at a backend connection. Add it from the provider editor instead.`);
- expect(new Set(messages).size).toBeGreaterThan(1);
+ expect(messages).toContain(`${harnessById('pi').label} ${harnessById('pi').connectionLimit}, so it cannot be pointed at a backend connection. Add it from the provider editor instead.`);
+ expect(new Set(messages).size).toBeGreaterThan(2);
for (const message of messages) expect(message).not.toMatch(/undefined|has no command recipe/);
});
+
+ // The graph names a direct binding `null`; the registry names it `direct`.
+ // Either spelling must be the same request to the create endpoint.
+ it('treats a "direct" harnessId exactly like the graph\'s null', () => {
+ const connection = { kind: 'ollama', transports: { openai: { baseUrl: 'http://localhost:11434/v1' } }, credentials: {} };
+ expect(bindingBlocker({ harnessId: 'direct', modes: ['api'], connection }))
+ .toEqual(bindingBlocker({ harnessId: null, modes: ['api'], connection }));
+ expect(bindingBlocker({ harnessId: 'direct', modes: ['cli'], connection })?.code).toBe('PROVIDER_HARNESS_MODE_UNSUPPORTED');
+ });
+});
+
+describe('capability bindings (#7562)', () => {
+ it('has eleven rows, and direct is the harness of an api record', () => {
+ expect(PROVIDER_HARNESSES).toHaveLength(11);
+ expect(harnessForProvider({ type: 'api', endpoint: 'https://api.example.com/v1' })?.id).toBe('direct');
+ expect(harnessForProvider({ type: 'cli', command: 'not-a-harness' })).toBeNull();
+ expect(harnessById('direct').modes).toEqual(['api']);
+ });
+
+ // Codex emits `--oss --local-provider <x>` from the runtime marker at spawn;
+ // the binding must name exactly the runtimes that emitter serves.
+ it('binds codexOss to the runtimes buildCodexOssArgs can name', () => {
+ const binding = harnessById('codex').bindings.find((row) => row.via === 'codexOss');
+ expect([...binding.localRuntime].sort()).toEqual(Object.keys(CODEX_OSS_LOCAL_PROVIDERS).sort());
+ });
+
+ it('names a service every subscription/service binding can resolve', () => {
+ const ids = new Set(SERVICE_DEFINITIONS.map((row) => row.id));
+ for (const harness of PROVIDER_HARNESSES) {
+ for (const binding of harness.bindings.filter((row) => row.service)) {
+ expect(ids.has(binding.service), `${harness.id} → ${binding.service}`).toBe(true);
+ }
+ }
+ });
+
+ // The compatibility table from the issue, verbatim — each row is a product
+ // decision, not a derivation (Claude on NIM is wrong because NIM speaks no
+ // Anthropic wire; Pi on NIM is right because Pi ships a `nvidia` provider).
+ const local = (id, transports) => resolveServiceInstance({ definitionId: id, transports });
+ const OLLAMA = local('ollama', { anthropic: { baseUrl: 'http://127.0.0.1:11434' }, openai: { baseUrl: 'http://127.0.0.1:11434/v1' } });
+ it.each([
+ ['claude', OLLAMA, true],
+ ['claude', 'nvidia-nim', false],
+ ['pi', 'nvidia-nim', true],
+ ['codex', OLLAMA, true],
+ ['codex', 'nvidia-nim', true],
+ ['opencode', 'openrouter', true],
+ ['direct', 'anthropic', false],
+ ['antigravity', 'nvidia-nim', false],
+ ['antigravity', OLLAMA, false],
+ ['antigravity', 'openai', false],
+ ['antigravity', 'antigravity', true],
+ ['kilo', OLLAMA, false],
+ // `harnessOnly`: Kimi's service is reachable through Kimi Code alone.
+ ['direct', 'kimi', false],
+ ['kimi', 'kimi', true],
+ ])('%s × %s → %s', (harnessId, service, expected) => {
+ const instance = typeof service === 'string' ? resolveServiceInstance(service) : service;
+ expect(isCompatible(harnessId, instance)).toBe(expected);
+ });
+
+ it('prefers the codexOss binding to the generic OpenAI one for a local daemon', () => {
+ expect(compatibleBindings('codex', OLLAMA)[0].via).toBe('codexOss');
+ expect(compatibleBindings('codex', resolveServiceInstance('nvidia-nim'))[0].baseUrl).toEqual({ via: 'env', name: 'OPENAI_BASE_URL' });
+ });
});
describe('a harness and its vendor agree about what can be driven', () => {
diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.js
index 7f6de94b08..620cdc475e 100644
--- a/server/lib/providerRouteRecipes.js
+++ b/server/lib/providerRouteRecipes.js
@@ -1,8 +1,16 @@
import { CONNECTION_CREDENTIAL_ENV_VARS, CONNECTION_PROTOCOLS } from './providerConnections.js';
import { modeSiblingId } from './aiToolkit/internal/providerModes.js';
import { PROVIDER_GATEWAYS } from './providerGateways.js';
-import { CREATABLE_HARNESS_IDS, harnessById, harnessRecipe } from './providerHarnesses.js';
+import {
+ CREATABLE_HARNESS_IDS,
+ compatibleBindings,
+ graphHarnessId,
+ harnessById,
+ harnessConnectionBlocker,
+ harnessRecipe,
+} from './providerHarnesses.js';
import { LOCAL_RUNTIMES } from './localProviderRuntime.js';
+import { resolveServiceInstance, serviceError } from './serviceDefinitions.js';
/**
* Minting a FRESH executable route from a connection and a harness recipe
@@ -131,16 +139,19 @@ export function connectionBlocker({ kind, transports }) {
*
* @returns {{code:string, message:string}|null}
*/
-export function bindingBlocker({ harnessId, modes, connection }) {
+export function bindingBlocker({ harnessId: requestedHarnessId, modes, connection }) {
+ // The graph's vocabulary is `null` for a direct API binding; the registry's
+ // is `direct`. Either spelling means the same thing here.
+ const harnessId = graphHarnessId(requestedHarnessId);
if (harnessId !== null && !CREATABLE_HARNESS_IDS.includes(harnessId)) {
return {
code: 'PROVIDER_HARNESS_NOT_CREATABLE',
- // The REASON is the row's (`noRecipe` in providerHarnesses.js), not this
- // string's: three different things make a harness uncreatable, and a
- // hardcoded clause here told two of them the wrong one — sending a user
- // looking for a vendor service when the real remedy is their own config
- // file or a runtime they have to start.
- message: `${harnessById(harnessId)?.label || harnessId} ${harnessById(harnessId)?.noRecipe || 'has no command recipe'}, so it cannot be pointed at a backend connection. Add it from the provider editor instead.`,
+ // The REASON is the row's (`noRecipe` / `connectionLimit` in
+ // providerHarnesses.js), not this string's: several different things make
+ // a harness uncreatable, and a hardcoded clause here told two of them the
+ // wrong one — sending a user looking for a vendor service when the real
+ // remedy is their own config file or a runtime they have to start.
+ message: `${harnessById(harnessId)?.label || harnessId} ${harnessConnectionBlocker(harnessId) || 'has no command recipe'}, so it cannot be pointed at a backend connection. Add it from the provider editor instead.`,
};
}
const harness = harnessId ? harnessById(harnessId) : null;
@@ -161,7 +172,7 @@ export function bindingBlocker({ harnessId, modes, connection }) {
};
}
- const credential = harnessId ? harnessRecipe(harnessId)?.credential : null;
+ const credential = harnessId ? harnessRecipe(harnessId)?.credential ?? null : null;
const key = credential?.via === 'env' ? credential.name : 'apiKey';
if (credential?.required && !connection.credentials?.[key]) {
return {
@@ -175,18 +186,26 @@ export function bindingBlocker({ harnessId, modes, connection }) {
/** The base URL a connection declares for `protocol`. */
const connectionBaseUrl = (connection, protocol) => connection.transports?.[protocol]?.baseUrl ?? null;
-/** OpenCode's inline provider declaration for one namespace and base URL. */
-const opencodeConfigContent = (kind, baseUrl) => JSON.stringify({
+/**
+ * OpenCode's inline provider declaration for one namespace and base URL, or
+ * the permission-only form for a provider OpenCode already ships (`builtin`).
+ */
+const opencodeProviderConfig = ({ namespace, label, baseUrl, builtin = false }) => JSON.stringify({
permission: 'allow',
- provider: {
- [opencodeNamespace(kind)]: {
- npm: '@ai-sdk/openai-compatible',
- name: connectionKindLabel(kind),
- options: { baseURL: baseUrl },
+ ...(builtin ? {} : {
+ provider: {
+ [namespace]: {
+ npm: '@ai-sdk/openai-compatible',
+ name: label,
+ options: { baseURL: baseUrl },
+ },
},
- },
+ }),
});
+const opencodeConfigContent = (kind, baseUrl) =>
+ opencodeProviderConfig({ namespace: opencodeNamespace(kind), label: connectionKindLabel(kind), baseUrl });
+
/**
* The executable record for one freshly minted route.
*
@@ -209,8 +228,8 @@ export function buildRouteRecord({ harnessId, mode, providerId, name, connection
const envVars = {};
const secretEnvVars = [];
- if (recipe?.baseUrl.via === 'env') envVars[recipe.baseUrl.name] = baseUrl;
- if (recipe?.baseUrl.via === 'opencodeConfig') {
+ if (recipe?.baseUrl?.via === 'env') envVars[recipe.baseUrl.name] = baseUrl;
+ if (recipe?.baseUrl?.via === 'opencodeConfig') {
envVars.OPENCODE_CONFIG_CONTENT = opencodeConfigContent(connection.kind, baseUrl);
}
// Every credential the connection holds is materialized, not just the one
@@ -228,7 +247,7 @@ export function buildRouteRecord({ harnessId, mode, providerId, name, connection
// declares one always declares the variable — empty only if the guard above
// let a credential-less connection through, which it does not for a required
// credential.
- if (recipe?.credential.via === 'env' && !Object.hasOwn(envVars, recipe.credential.name)) {
+ if (recipe?.credential?.via === 'env' && !Object.hasOwn(envVars, recipe.credential.name)) {
envVars[recipe.credential.name] = '';
}
@@ -280,3 +299,182 @@ export function mintRouteIds({ harnessId, kind, modes, taken }) {
// one, and an explicit throw beats returning a colliding id.
throw new Error(`Could not mint a free route id for ${stem}`);
}
+
+/**
+ * The record markers a materialized route on a service definition must carry,
+ * so the spawner and `providerConnectionProfile` classify it onto that service:
+ * the runtime's `*Backed` boolean, or `gatewayBacked: '<id>'`. Slotstream and
+ * a plain API endpoint carry none, exactly as {@link connectionKindMarkers}.
+ */
+const serviceMarkers = (harness, definition) => {
+ if (definition.localRuntime) return connectionKindMarkers(definition.localRuntime) || {};
+ // `gatewayBacked` marks a WRAPPER fronting a gateway (the sibling api record
+ // owns the key); a direct API record IS the gateway, so it carries none —
+ // exactly as every shipped `api` sample.
+ if (definition.gateway && harness.id !== 'direct') return { gatewayBacked: definition.id };
+ return {};
+};
+
+/** The OpenCode namespace a service instance is declared under: the marker's, or the slug's. */
+const serviceOpencodeNamespace = (instance) =>
+ instance.definition.localRuntime || (instance.definition.gateway ? instance.definition.id : instance.slug);
+
+/** Default wall clock for a record no recipe times — every shipped `api` sample. */
+const API_ROUTE_TIMEOUT_MS = 300000;
+
+/**
+ * The executable record for a (harness, method, service) composition (#7562) —
+ * {@link buildRouteRecord} generalized from "a connection" to "a service
+ * instance", and from "one recipe" to "the first compatible binding".
+ *
+ * Given a harness row (or id), the execution method, a service instance (see
+ * `resolveServiceInstance`), an optional credential-bootstrap app, and the
+ * model/effort selection, it writes every value the binding says the program
+ * reads — base URL, credential, static env, backend markers, inline
+ * OpenCode/Pi selection — plus the recipe's per-mode argv, so the result is a
+ * complete `data/providers.json` record with no further lookup. Feeding it
+ * back through `providerConnectionProfile` classifies it onto the same
+ * service ({@link routeDescribesService}), which is the contract
+ * `createBinding` already holds a minted route to.
+ *
+ * Pure: no I/O, no clock, no spawn. Throws a typed error (`err.code`) rather
+ * than minting a route that cannot run:
+ * - `HARNESS_UNKNOWN` / `HARNESS_METHOD_UNSUPPORTED`
+ * - `HARNESS_SERVICE_INCOMPATIBLE` — no binding reaches this service
+ * - `SERVICE_ENDPOINT_REQUIRED` — the binding needs a base URL the instance
+ * does not declare (a local daemon's port is an install-specific fact)
+ * - `SERVICE_CREDENTIAL_REQUIRED` — the program refuses to start without one
+ * - `SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED` — the instance's credential is
+ * minted by a bootstrap CLI at spawn, and none was supplied
+ *
+ * @param {{harness: object|string, method: 'cli'|'tui'|'api',
+ * serviceInstance: object|string,
+ * bootstrap?: {id?: string, command: string, args?: string[], argsSeparator?: string, harnessNames?: Record<string,string>}|null,
+ * selection?: {model?: string|null, effort?: string|null, tiers?: Record<string,string>},
+ * overrides?: object, providerId?: string, name?: string}} input
+ * @returns {object} the record to hand `createProvider`
+ */
+export function materializeRoute({
+ harness: harnessInput, method, serviceInstance, bootstrap = null, selection = {}, overrides = {}, providerId, name,
+}) {
+ const harness = typeof harnessInput === 'string' ? harnessById(harnessInput) : harnessInput;
+ if (!harness) throw serviceError('HARNESS_UNKNOWN', `No harness "${harnessInput ?? ''}"`);
+ if (!harness.modes.includes(method)) {
+ throw serviceError('HARNESS_METHOD_UNSUPPORTED', `${harness.label} has no ${method} mode.`);
+ }
+ const instance = resolveServiceInstance(serviceInstance);
+ const { definition } = instance;
+ const [binding] = compatibleBindings(harness, instance);
+ if (!binding) {
+ throw serviceError('HARNESS_SERVICE_INCOMPATIBLE', `${harness.label} cannot be pointed at ${definition.label}.`);
+ }
+ if (instance.credentialVia === 'bootstrap' && method !== 'api' && !bootstrap) {
+ throw serviceError('SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED',
+ `${definition.label} is credentialed by a bootstrap CLI at spawn; name the bootstrap app to compose this route.`);
+ }
+
+ const recipe = harness.recipe;
+ const envVars = {};
+ const secretEnvVars = [];
+ const fields = {};
+ const args = [...(recipe?.modes?.[method]?.args || [])];
+ const apiKey = typeof instance.credentials.apiKey === 'string' ? instance.credentials.apiKey : '';
+
+ // --- endpoint --------------------------------------------------------------
+ const protocol = binding.protocol || null;
+ const baseUrl = protocol ? instance.transports[protocol]?.baseUrl ?? null : null;
+ if (protocol && !baseUrl) {
+ throw serviceError('SERVICE_ENDPOINT_REQUIRED', `${definition.label} declares no ${protocol} endpoint; set its base URL first.`);
+ }
+ const baseUrlVia = binding.baseUrl?.via ?? null;
+ if (baseUrlVia === 'env') envVars[binding.baseUrl.name] = baseUrl;
+ if (baseUrlVia === 'field') fields.endpoint = baseUrl;
+ if (baseUrlVia === 'opencodeConfig') {
+ envVars.OPENCODE_CONFIG_CONTENT = opencodeProviderConfig({
+ namespace: serviceOpencodeNamespace(instance), label: definition.label, baseUrl, builtin: binding.baseUrl.builtin === true,
+ });
+ }
+ if (binding.via === 'piProvider') args.push(recipe.baseUrl.flag, definition.piProvider);
+ // A service the program addresses through an env var, inline config or a
+ // provider name still records where it is, as every shipped wrapper sample
+ // does — the readiness probe and the catalog refresh read `endpoint` off the
+ // record.
+ const recordedEndpoint = instance.transports.openai?.baseUrl ?? baseUrl ?? null;
+ if (baseUrlVia !== 'field' && binding.via !== 'subscription' && recordedEndpoint) fields.endpoint = recordedEndpoint;
+
+ // --- credential ------------------------------------------------------------
+ const credential = binding.credential || null;
+ const credentialEnvName = credential?.via === 'gatewayEnv'
+ ? definition.gateway?.apiKeyEnv ?? null
+ : credential?.via === 'env' ? credential.name ?? definition.credential.envVars[0] ?? null : null;
+ const credentialRequired = credential?.required === true && instance.credentialVia !== 'bootstrap';
+ if (credentialRequired && apiKey === '') {
+ throw serviceError('SERVICE_CREDENTIAL_REQUIRED',
+ `${harness.label} will not start without a ${credentialEnvName || 'key'} for ${definition.label}. Set one first — any non-empty value works for a local daemon that ignores it.`);
+ }
+ if (credential?.via === 'field') fields.apiKey = apiKey;
+ if (credentialEnvName && (apiKey !== '' || credentialRequired)) {
+ envVars[credentialEnvName] = apiKey;
+ secretEnvVars.push(credentialEnvName);
+ }
+ Object.assign(envVars, binding.env || {});
+
+ // --- assembly --------------------------------------------------------------
+ const tiers = selection.tiers && typeof selection.tiers === 'object' ? selection.tiers : {};
+ const modeFields = recipe ? { ...recipe.modes[method], args } : {};
+ const record = {
+ id: providerId ?? `${harness.id}.${method}@${instance.slug}${bootstrap ? `+${bootstrap.id ?? bootstrap.command}` : ''}`,
+ name: name ?? `${harness.label} · ${definition.label}`,
+ type: method,
+ harnessId: harness.id,
+ method,
+ serviceId: instance.slug,
+ servicePlan: instance.plan,
+ ...fields,
+ ...serviceMarkers(harness, definition),
+ ...(recipe ? { command: recipe.command, timeout: recipe.timeout } : { timeout: API_ROUTE_TIMEOUT_MS }),
+ ...modeFields,
+ models: [],
+ defaultModel: selection.model ?? null,
+ ...(selection.effort ? { effort: selection.effort } : {}),
+ ...tiers,
+ enabled: true,
+ envVars,
+ secretEnvVars,
+ ...overrides,
+ };
+ if (bootstrap && method !== 'api') {
+ record.credentialBootstrap = {
+ command: bootstrap.command,
+ ...(Array.isArray(bootstrap.args) ? { args: [...bootstrap.args] } : {}),
+ // The bootstrap CLI's own name for this harness, when it differs from the
+ // binary PortOS spawns — `resolveCliSpawn` reads it unchanged.
+ harnessId: bootstrap.harnessNames?.[harness.id] ?? recipe.command,
+ ...(bootstrap.argsSeparator ? { argsSeparator: bootstrap.argsSeparator } : {}),
+ };
+ }
+ return record;
+}
+
+/**
+ * Whether a record's connection profile describes `serviceInstance`: it
+ * classifies onto the service's backend kind, and every endpoint it declares is
+ * one the instance is reached at. The round-trip contract `materializeRoute`
+ * owes, stated once so its test and a later store can share it.
+ *
+ * @param {ReturnType<typeof import('./providerConnections.js').providerConnectionProfile>} profile
+ * @param {object} serviceInstance - resolved
+ */
+export function routeDescribesService(profile, serviceInstance) {
+ const instance = resolveServiceInstance(serviceInstance);
+ const { definition } = instance;
+ // A wrapper on a gateway reads back as `gateway:<id>`; a direct API record
+ // on the same gateway reads back as `api` (it carries no marker, see
+ // `serviceMarkers`). Both are that service.
+ const expectedKinds = definition.localRuntime ? [definition.localRuntime]
+ : definition.gateway ? [`gateway:${definition.id}`, 'api']
+ : ['api', 'vendor'];
+ if (!expectedKinds.includes(profile.kind)) return false;
+ return Object.entries(profile.transports).every(([protocol, transport]) =>
+ transport.baseUrl === instance.transports[protocol]?.baseUrl);
+}
diff --git a/server/lib/providerRouteRecipes.materialize.test.js b/server/lib/providerRouteRecipes.materialize.test.js
new file mode 100644
index 0000000000..2b7ae042d5
--- /dev/null
+++ b/server/lib/providerRouteRecipes.materialize.test.js
@@ -0,0 +1,261 @@
+/**
+ * `materializeRoute` (#7562): a (harness, method, service) composition is an
+ * executable record with no further lookup, and one that reads back as the
+ * service it was built for.
+ *
+ * Three contracts are pinned, each one a way the registries could drift apart
+ * without any single row looking wrong:
+ * 1. every (harness, definition) pair `isCompatible` accepts round-trips
+ * through `providerConnectionProfile` onto the same service;
+ * 2. the 55 shipped samples that profile cleanly are reproduced — every
+ * connection-owned value the sample declares is what the composition
+ * writes, byte for byte;
+ * 3. a bootstrap app becomes the `credentialBootstrap` object the spawn
+ * composer already understands, and only when one is supplied.
+ */
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { composeBootstrapSpawn } from './aiToolkit/internal/credentialBootstrap.js';
+import { ensurePiHeadlessArgs } from './pi.js';
+import { providerConnectionProfile } from './providerConnections.js';
+import { PROVIDER_HARNESSES, harnessForProvider, isCompatible } from './providerHarnesses.js';
+import { materializeRoute, routeDescribesService } from './providerRouteRecipes.js';
+import { SERVICE_DEFINITIONS, resolveServiceInstance, serviceDefinitionById, serviceDefinitionForLocalRuntime } from './serviceDefinitions.js';
+
+const SAMPLES = JSON.parse(readFileSync(
+ resolve(dirname(fileURLToPath(import.meta.url)), 'aiToolkit/defaults/providers.sample.json'),
+ 'utf8',
+)).providers;
+
+/** A local daemon's endpoints, as an install would declare them. */
+const LOCAL_TRANSPORTS = { openai: { baseUrl: 'http://127.0.0.1:11434/v1' }, anthropic: { baseUrl: 'http://127.0.0.1:11434' } };
+
+/** A remote endpoint for the definitions that default to none (a proxy, a peer). */
+const REMOTE_TRANSPORTS = { openai: { baseUrl: 'https://gateway.example.com/v1' } };
+
+/** An instance of `definition` with every endpoint and a key filled in. */
+const instanceFor = (definition, credentials = { apiKey: 'example-key' }) => resolveServiceInstance({
+ definitionId: definition.id,
+ transports: Object.fromEntries(Object.keys(definition.transports).map((protocol) => [protocol, {
+ baseUrl: definition.transports[protocol].defaultBaseUrl
+ ?? (definition.family === 'local' ? LOCAL_TRANSPORTS : REMOTE_TRANSPORTS)[protocol].baseUrl,
+ }])),
+ credentials,
+});
+
+const compatiblePairs = PROVIDER_HARNESSES.flatMap((harness) => SERVICE_DEFINITIONS
+ .map((definition) => instanceFor(definition))
+ .filter((instance) => isCompatible(harness, instance))
+ .map((instance) => ({ harness, instance, name: `${harness.id} × ${instance.definition.id}` })));
+
+describe('materializeRoute round-trips onto its service', () => {
+ it('accepts a meaningful number of pairs', () => {
+ expect(compatiblePairs.length).toBeGreaterThan(25);
+ });
+
+ it.each(compatiblePairs)('$name', ({ harness, instance }) => {
+ const method = harness.modes[0];
+ const record = materializeRoute({ harness, method, serviceInstance: instance });
+ expect(record).toMatchObject({
+ id: `${harness.id}.${method}@${instance.slug}`,
+ type: method,
+ harnessId: harness.id,
+ method,
+ serviceId: instance.slug,
+ servicePlan: instance.plan,
+ enabled: true,
+ models: [],
+ });
+ expect(record).not.toHaveProperty('credentialBootstrap');
+ if (harness.recipe) expect(record.command).toBe(harness.recipe.command);
+ else expect(record).not.toHaveProperty('command');
+
+ const profile = providerConnectionProfile(record);
+ expect(profile.reasons, `${harness.id} on ${instance.definition.id} isolates: ${JSON.stringify(profile.reasons)}`).toEqual([]);
+ expect(harnessForProvider(record)?.id).toBe(harness.id);
+ expect(routeDescribesService(profile, instance)).toBe(true);
+ // A key never rides an unlisted env var: the profile reads every credential
+ // the record carries, or the record describes a backend it is not on.
+ for (const name of record.secretEnvVars) expect(record.envVars).toHaveProperty(name);
+ });
+
+ it('refuses the pairs the registries rule out, with a typed reason', () => {
+ const refuse = (input) => { try { materializeRoute(input); return null; } catch (err) { return err.code; } };
+ expect(refuse({ harness: 'claude', method: 'cli', serviceInstance: 'nvidia-nim' })).toBe('HARNESS_SERVICE_INCOMPATIBLE');
+ expect(refuse({ harness: 'antigravity', method: 'api', serviceInstance: 'antigravity' })).toBe('HARNESS_METHOD_UNSUPPORTED');
+ expect(refuse({ harness: 'nope', method: 'cli', serviceInstance: 'antigravity' })).toBe('HARNESS_UNKNOWN');
+ // A local daemon whose instance names no endpoint: never a guessed port.
+ expect(refuse({ harness: 'codex', method: 'cli', serviceInstance: 'ollama' })).toBe('SERVICE_ENDPOINT_REQUIRED');
+ // Claude Code will not start without a token, even to a daemon that ignores it.
+ expect(refuse({ harness: 'claude', method: 'cli', serviceInstance: { definitionId: 'ollama', transports: LOCAL_TRANSPORTS } })).toBe('SERVICE_CREDENTIAL_REQUIRED');
+ // ...while OpenCode on the same daemon needs none.
+ expect(refuse({ harness: 'opencode', method: 'cli', serviceInstance: { definitionId: 'ollama', transports: LOCAL_TRANSPORTS } })).toBeNull();
+ });
+});
+
+describe('materializeRoute writes what each binding shape says', () => {
+ it('materializes Bedrock through Claude Code\'s static env switch', () => {
+ const record = materializeRoute({ harness: 'claude', method: 'cli', serviceInstance: { definitionId: 'bedrock', credentials: { apiKey: 'token' } } });
+ expect(record.envVars).toEqual({ AWS_BEARER_TOKEN_BEDROCK: 'token', CLAUDE_CODE_USE_BEDROCK: '1' });
+ expect(record.secretEnvVars).toEqual(['AWS_BEARER_TOKEN_BEDROCK']);
+ expect(record).not.toHaveProperty('endpoint');
+ });
+
+ it('declares OpenCode Zen as the provider OpenCode ships, permissions only', () => {
+ const record = materializeRoute({ harness: 'opencode', method: 'cli', serviceInstance: { definitionId: 'opencode-zen', credentials: { apiKey: 'zen' } } });
+ expect(record.envVars.OPENCODE_CONFIG_CONTENT).toBe(SAMPLES['opencode-zen-cli'].envVars.OPENCODE_CONFIG_CONTENT);
+ expect(record.envVars.OPENCODE_API_KEY).toBe('zen');
+ expect(record.secretEnvVars).toEqual(SAMPLES['opencode-zen-cli'].secretEnvVars);
+ });
+
+ // Two instances of one definition under different plans are how "NVIDIA
+ // free vs paid" is represented; each is its own route.
+ it('keys a second plan of the same service by its slug', () => {
+ const free = materializeRoute({ harness: 'direct', method: 'api', serviceInstance: { definitionId: 'nvidia-nim', slug: 'nvidia-free', plan: 'free' } });
+ const paid = materializeRoute({ harness: 'direct', method: 'api', serviceInstance: { definitionId: 'nvidia-nim', slug: 'nvidia-paid', plan: 'paid', credentials: { apiKey: 'k' } } });
+ expect([free.id, paid.id]).toEqual(['direct.api@nvidia-free', 'direct.api@nvidia-paid']);
+ expect([free.servicePlan, paid.servicePlan]).toEqual(['free', 'paid']);
+ expect(free).toMatchObject({ endpoint: 'https://integrate.api.nvidia.com/v1', apiKey: '', timeout: 300000 });
+ // A direct record IS the gateway; the marker is for a wrapper in front of one.
+ expect(free).not.toHaveProperty('gatewayBacked');
+ expect(materializeRoute({ harness: 'opencode', method: 'cli', serviceInstance: 'nvidia-nim' }).gatewayBacked).toBe('nvidia-nim');
+ expect(paid.apiKey).toBe('k');
+ });
+
+ it('carries the selection onto the record', () => {
+ const record = materializeRoute({
+ harness: 'codex', method: 'cli', serviceInstance: { definitionId: 'nvidia-nim', credentials: { apiKey: 'k' } },
+ selection: { model: 'vendor/model-a', effort: 'high', tiers: { lightModel: 'vendor/model-b' } },
+ overrides: { timeout: 42 },
+ });
+ expect(record).toMatchObject({ defaultModel: 'vendor/model-a', effort: 'high', lightModel: 'vendor/model-b', timeout: 42 });
+ });
+});
+
+describe('Pi is pointed at a service by the provider name it ships (verified against pi 0.85)', () => {
+ it('selects the provider with --provider and keys it from the service\'s own env var', () => {
+ const record = materializeRoute({ harness: 'pi', method: 'cli', serviceInstance: { definitionId: 'nvidia-nim', credentials: { apiKey: 'nv' } } });
+ expect(record.command).toBe('pi');
+ expect(record.args).toEqual(['--print', '--approve', '--provider', 'nvidia']);
+ expect(record.envVars).toEqual({ NVIDIA_API_KEY: 'nv' });
+ expect(record.secretEnvVars).toEqual(['NVIDIA_API_KEY']);
+ // The spawn-time argv builder keeps the selection and adds the model in the
+ // `provider/id` form Pi documents for `--model`.
+ expect(ensurePiHeadlessArgs(record.args, 'nvidia/example-model', null))
+ .toEqual(['--print', '--approve', '--provider', 'nvidia', '--model', 'nvidia/example-model']);
+ });
+
+ it('cannot be pointed at a custom endpoint, which is Pi\'s own models.json', () => {
+ expect(() => materializeRoute({ harness: 'pi', method: 'cli', serviceInstance: { definitionId: 'ollama', transports: LOCAL_TRANSPORTS } }))
+ .toThrow(expect.objectContaining({ code: 'HARNESS_SERVICE_INCOMPATIBLE' }));
+ expect(() => materializeRoute({ harness: 'pi', method: 'cli', serviceInstance: { definitionId: 'openai-compatible', transports: LOCAL_TRANSPORTS } }))
+ .toThrow(expect.objectContaining({ code: 'HARNESS_SERVICE_INCOMPATIBLE' }));
+ });
+});
+
+describe('a bootstrap app becomes the credentialBootstrap the spawn composer reads', () => {
+ const BOOTSTRAP = { id: 'corp-auth', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } };
+ const PROXY = { definitionId: 'openai-compatible', transports: { openai: { baseUrl: 'https://proxy.example.com/v1' } }, credential: { via: 'bootstrap' } };
+
+ it('emits <bootstrap> run <harness name> -- <args>', () => {
+ const record = materializeRoute({ harness: 'codex', method: 'cli', serviceInstance: PROXY, bootstrap: BOOTSTRAP });
+ expect(record.id).toBe('codex.cli@openai-compatible+corp-auth');
+ expect(record.credentialBootstrap).toEqual({ command: 'corp-auth', args: ['run'], harnessId: 'codex', argsSeparator: '--' });
+ expect(composeBootstrapSpawn(record, record.command, [...record.args, '--flag']))
+ .toEqual({ command: 'corp-auth', args: ['run', 'codex', '--', '--flag'], wrapped: true });
+ // The bootstrap-minted credential is not a stored key: none is required,
+ // and the key env var is left for the bootstrap CLI to provide.
+ expect(record.envVars).toEqual({ OPENAI_BASE_URL: 'https://proxy.example.com/v1' });
+ expect(record.secretEnvVars).toEqual([]);
+ });
+
+ it('uses the bootstrap CLI\'s own name for a harness when it has one', () => {
+ const record = materializeRoute({
+ harness: 'claude', method: 'tui', bootstrap: BOOTSTRAP,
+ serviceInstance: { definitionId: 'ollama', transports: LOCAL_TRANSPORTS, credential: { via: 'bootstrap' } },
+ });
+ expect(record.credentialBootstrap.harnessId).toBe('claude-code');
+ expect(composeBootstrapSpawn(record, record.command, record.args).args).toEqual(['run', 'claude-code', '--', '--dangerously-skip-permissions']);
+ });
+
+ it('refuses a bootstrap-credentialed service with no bootstrap, and never wraps an api route', () => {
+ expect(() => materializeRoute({ harness: 'codex', method: 'cli', serviceInstance: PROXY }))
+ .toThrow(expect.objectContaining({ code: 'SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED' }));
+ const api = materializeRoute({ harness: 'direct', method: 'api', serviceInstance: PROXY, bootstrap: BOOTSTRAP });
+ expect(api).not.toHaveProperty('credentialBootstrap');
+ expect(composeBootstrapSpawn(api, 'x', []).wrapped).toBe(false);
+ });
+});
+
+/**
+ * The service a shipped sample is on, read the same way a later migration
+ * will read it: from the record's own profile (kind + endpoint), then — for a
+ * record that names no backend — from the harness's subscription binding or
+ * the static switch it carries.
+ */
+function serviceForSample(sample, profile, harness) {
+ const local = serviceDefinitionForLocalRuntime(profile.kind);
+ if (local) return local;
+ if (profile.kind.startsWith('gateway:')) return serviceDefinitionById(profile.kind.slice('gateway:'.length));
+ if (sample.envVars?.CLAUDE_CODE_USE_BEDROCK === '1') return serviceDefinitionById('bedrock');
+ if (sample.secretEnvVars?.includes('OPENCODE_API_KEY')) return serviceDefinitionById('opencode-zen');
+ const endpoint = profile.transports.openai?.baseUrl;
+ if (endpoint) return SERVICE_DEFINITIONS.find((row) => row.transports.openai?.defaultBaseUrl === endpoint) || null;
+ const subscription = harness.bindings.find((binding) => binding.via === 'subscription');
+ return subscription ? serviceDefinitionById(subscription.service) : null;
+}
+
+describe('the shipped samples are reproduced by their (harness, service) composition', () => {
+ const mapped = [];
+ const unmapped = [];
+ for (const [id, sample] of Object.entries(SAMPLES)) {
+ const profile = providerConnectionProfile(sample);
+ const harness = harnessForProvider(sample);
+ const definition = harness && profile.reasons.length === 0 ? serviceForSample(sample, profile, harness) : null;
+ if (!definition) { unmapped.push(id); continue; }
+ const [credentialValue] = Object.values(profile.credentials);
+ const serviceInstance = resolveServiceInstance({
+ definitionId: definition.id,
+ // The profile reports ONE transport (the env var wins over `endpoint`);
+ // a sample that also stores the daemon's OpenAI URL declares both.
+ transports: {
+ ...(definition.transports.openai && sample.endpoint ? { openai: { baseUrl: sample.endpoint } } : {}),
+ ...profile.transports,
+ },
+ // A sample stores a blank key; the composition needs a real one where
+ // the program refuses to start without it. The VALUE is compared only
+ // where the sample itself carries one.
+ credentials: { apiKey: credentialValue ?? 'example-key' },
+ });
+ if (!isCompatible(harness, serviceInstance)) { unmapped.push(id); continue; }
+ mapped.push({ id, sample, profile, harness, serviceInstance });
+ }
+
+ // Kilo and OpenChamber bind to nothing; the two Pi samples name no service
+ // at all (Pi's default provider is whatever the user last logged into), so
+ // they are pinned by `providerRouteRecipes.sampleParity.test.js` instead.
+ it('maps every sample except the ones that name no service', () => {
+ expect(unmapped.sort()).toEqual(['kilo-cli', 'kilo-tui', 'openchamber-cli', 'pi-cli', 'pi-tui']);
+ expect(mapped.length + unmapped.length).toBe(Object.keys(SAMPLES).length);
+ });
+
+ it.each(mapped)('$id', ({ sample, profile, harness, serviceInstance }) => {
+ const minted = materializeRoute({ harness, method: sample.type, serviceInstance });
+ // Every connection-owned value the sample declares is what the composition
+ // writes: endpoint / apiKey fields and the transport + credential env vars.
+ for (const [field, value] of Object.entries(profile.owned.fields)) {
+ if (field === 'apiKey' && value === '') continue;
+ expect(minted[field], field).toBe(value);
+ }
+ for (const [name, value] of Object.entries(profile.owned.envVars)) {
+ if (value === '') continue;
+ expect(minted.envVars[name], name).toBe(value);
+ }
+ // ...and the composition reads back onto the same service and kind.
+ const reread = providerConnectionProfile(minted);
+ expect(reread.kind).toBe(profile.kind);
+ expect(routeDescribesService(reread, serviceInstance)).toBe(true);
+ });
+});
diff --git a/server/lib/providerRouteRecipes.sampleParity.test.js b/server/lib/providerRouteRecipes.sampleParity.test.js
index 278b7f1aad..1c92d8a8fd 100644
--- a/server/lib/providerRouteRecipes.sampleParity.test.js
+++ b/server/lib/providerRouteRecipes.sampleParity.test.js
@@ -18,8 +18,8 @@ import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { CREATABLE_HARNESS_IDS } from './providerHarnesses.js';
-import { buildRouteRecord } from './providerRouteRecipes.js';
+import { CREATABLE_HARNESS_IDS, PROVIDER_HARNESSES } from './providerHarnesses.js';
+import { buildRouteRecord, materializeRoute } from './providerRouteRecipes.js';
const SAMPLES = JSON.parse(readFileSync(
resolve(dirname(fileURLToPath(import.meta.url)), 'aiToolkit/defaults/providers.sample.json'),
@@ -49,6 +49,26 @@ const CASES = [
const mint = ({ harnessId, mode, connection, sample }) =>
buildRouteRecord({ harnessId, mode, providerId: sample, name: 'Example', connection });
+/**
+ * The harnesses that carry a recipe but cannot be minted from a bare
+ * connection (#7562): a subscription program composes onto its own service,
+ * Pi onto a service it ships a provider name for. Their argv is pinned the
+ * same way, through `materializeRoute`; Pi's `--provider` pair is the one
+ * binding-added suffix, so the shipped argv is asserted as the prefix.
+ */
+const COMPOSED_CASES = [
+ { harnessId: 'antigravity', mode: 'cli', sample: 'antigravity-cli', service: 'antigravity' },
+ { harnessId: 'antigravity', mode: 'tui', sample: 'antigravity-tui', service: 'antigravity' },
+ { harnessId: 'cursor', mode: 'cli', sample: 'cursor-cli', service: 'cursor' },
+ { harnessId: 'cursor', mode: 'tui', sample: 'cursor-tui', service: 'cursor' },
+ { harnessId: 'grok', mode: 'cli', sample: 'grok-cli', service: 'grok-build' },
+ { harnessId: 'grok', mode: 'tui', sample: 'grok-tui', service: 'grok-build' },
+ { harnessId: 'kimi', mode: 'cli', sample: 'kimi-cli', service: 'kimi' },
+ { harnessId: 'kimi', mode: 'tui', sample: 'kimi-tui', service: 'kimi' },
+ { harnessId: 'pi', mode: 'cli', sample: 'pi-cli', service: { definitionId: 'nvidia-nim', credentials: { apiKey: 'example-key' } }, suffix: ['--provider', 'nvidia'] },
+ { harnessId: 'pi', mode: 'tui', sample: 'pi-tui', service: { definitionId: 'nvidia-nim', credentials: { apiKey: 'example-key' } }, suffix: ['--provider', 'nvidia'] },
+];
+
describe('harness command recipes match the shipped provider samples', () => {
it('covers every creatable harness, so a new one cannot ship unpinned', () => {
expect([...new Set(CASES.map((entry) => entry.harnessId))].sort())
@@ -97,3 +117,22 @@ describe('harness command recipes match the shipped provider samples', () => {
}
});
});
+
+describe('composed-only harness recipes match the shipped provider samples', () => {
+ it('covers every recipe-bearing harness the connection path does not', () => {
+ const composedOnly = PROVIDER_HARNESSES.filter((h) => h.recipe && !CREATABLE_HARNESS_IDS.includes(h.id)).map((h) => h.id);
+ expect([...new Set(COMPOSED_CASES.map((entry) => entry.harnessId))].sort()).toEqual(composedOnly.sort());
+ });
+
+ it.each(COMPOSED_CASES)('composes $harnessId $mode like $sample', ({ harnessId, mode, sample, service, suffix = [] }) => {
+ const shipped = SAMPLES[sample];
+ expect(shipped, `${sample} is missing from providers.sample.json`).toBeDefined();
+ const minted = materializeRoute({ harness: harnessId, method: mode, serviceInstance: service });
+
+ expect(minted.command).toBe(shipped.command);
+ expect(minted.args).toEqual([...shipped.args, ...suffix]);
+ expect(minted.type).toBe(shipped.type);
+ if (mode === 'cli') expect(minted.headlessArgs).toEqual(shipped.headlessArgs ?? []);
+ if (mode === 'tui') expect(minted.tuiPromptDelayMs).toBe(shipped.tuiPromptDelayMs);
+ });
+});
diff --git a/server/lib/serviceDefinitions.js b/server/lib/serviceDefinitions.js
new file mode 100644
index 0000000000..1f9faf3f6f
--- /dev/null
+++ b/server/lib/serviceDefinitions.js
@@ -0,0 +1,356 @@
+/**
+ * `SERVICE_DEFINITIONS` — every backend a harness can be pointed at, as ONE
+ * table (#7562, the first slice of #7561).
+ *
+ * Before this file, "which backends exist?" was answered by four registries
+ * that never met: `PROVIDER_GATEWAYS` (hosted OpenAI-compatible gateways),
+ * `LOCAL_RUNTIMES` (daemons on this machine), the AI rows of
+ * `credentialRegistry.js` (vendor API keys), and the implicit vendor cloud a
+ * subscription harness signs into. A service is any of those, in one shape, so
+ * a harness's capability bindings (`providerHarnesses.js`) can name a service
+ * by id and `materializeRoute` (`providerRouteRecipes.js`) can turn a
+ * (harness, service) pair into an executable record from data alone.
+ *
+ * Three families, one shape (epic D2):
+ * - `subscription` — auth lives inside the harness (claude.ai login, the
+ * ChatGPT/Codex login, Google for Antigravity, xAI for Grok Build, Cursor).
+ * PortOS holds no key and the service is reachable ONLY by its own program
+ * (`harnessOnly`).
+ * - `api-key` — a hosted API PortOS holds a key for. Some are also hosted
+ * GATEWAYS an OpenCode wrapper can front-end; those rows carry `gateway`,
+ * and {@link PROVIDER_GATEWAYS} in `providerGateways.js` is DERIVED from
+ * them, so a gateway is one row here and nowhere else.
+ * - `local` — a daemon on this machine, one row per `LOCAL_RUNTIMES` id
+ * (`serviceDefinitions.test.js` pins the two id sets together). The daemon's
+ * endpoint is configured per install, so these rows declare WHICH transports
+ * the runtime speaks and no default URL: an instance must name its endpoint,
+ * exactly as `providerConnectionProfile` already demands of a local record.
+ * - `fleet` — a peer's OpenAI-compatible gateway.
+ *
+ * A DEFINITION is code; an INSTANCE (a definition + plan + credential + catalog)
+ * is a later slice's persisted row. {@link resolveServiceInstance} is the pure
+ * shape both halves agree on until then.
+ *
+ * Dependency-light on purpose: imports nothing, so `providerGateways.js` (which
+ * `providerModels.js` and the browser reach) can derive its table from here
+ * without growing its closure. Default base URLs are literal strings for the
+ * same reason — the local-runtime defaults, which need `PORTS`, stay in
+ * `LOCAL_RUNTIMES`.
+ */
+
+/** The four families a definition belongs to. */
+export const SERVICE_FAMILIES = Object.freeze(['subscription', 'api-key', 'local', 'fleet']);
+
+/**
+ * User-declared plans. `free` / `paid` are the two tiers a metered API sells;
+ * `subscription` is a login the harness owns; `local` is a daemon that bills
+ * nobody. A definition lists the plans it can honestly be instantiated under.
+ */
+export const SERVICE_PLANS = Object.freeze(['free', 'paid', 'subscription', 'local']);
+
+/**
+ * How an instance's model catalog is learned. `probe` — GET `/models` on the
+ * endpoint; `daemon` — ask the local runtime manager; `harness` — ask the
+ * program that signs in (`claude`, `codex`, `agy` list their own catalogs);
+ * `static` — nothing to ask, the instance's declared list is the catalog.
+ */
+export const CATALOG_STRATEGIES = Object.freeze(['probe', 'daemon', 'harness', 'static']);
+
+const METERED = Object.freeze(['free', 'paid']);
+const PAID = Object.freeze(['paid']);
+const SUBSCRIPTION = Object.freeze(['subscription']);
+const LOCAL = Object.freeze(['local']);
+const NO_CREDENTIAL = Object.freeze({ envVars: Object.freeze([]) });
+
+/** A model-id suffix filter for the one plan a vendor marks in the id itself. */
+const suffixPlanFilter = (suffix) => (plan, models) => (
+ plan === 'free' ? models.filter((model) => String(model).endsWith(suffix)) : models
+);
+
+const definition = ({ transports = {}, credential = NO_CREDENTIAL, catalog, ...row }) => Object.freeze({
+ ...row,
+ transports: Object.freeze(Object.fromEntries(
+ Object.entries(transports).map(([protocol, transport]) => [protocol, Object.freeze({ defaultBaseUrl: null, ...transport })]),
+ )),
+ credential: Object.freeze({ envVars: Object.freeze([]), ...credential }),
+ catalog: Object.freeze(catalog),
+});
+
+const localRuntime = (id, label, { anthropic = false } = {}) => definition({
+ id,
+ label,
+ family: 'local',
+ localRuntime: id,
+ transports: { openai: {}, ...(anthropic ? { anthropic: {} } : {}) },
+ plans: LOCAL,
+ catalog: { strategy: 'daemon' },
+});
+
+const subscription = (id, label, harnessOnly, extra = {}) => definition({
+ id,
+ label,
+ family: 'subscription',
+ harnessOnly,
+ plans: SUBSCRIPTION,
+ catalog: { strategy: 'harness' },
+ ...extra,
+});
+
+/**
+ * @typedef {object} ServiceDefinition
+ * @property {string} id — stable identity; also the default instance slug, the
+ * OpenCode namespace for a gateway, and the `service` a harness binding names.
+ * @property {string} label
+ * @property {'subscription'|'api-key'|'local'|'fleet'} family
+ * @property {Record<'anthropic'|'openai', {defaultBaseUrl: string|null}>} transports —
+ * the wire protocols the service speaks. A service declaring none is reached
+ * only through a program that knows it (`harnessOnly`) or a static env switch.
+ * @property {{envVars: readonly string[], keyUrl?: string}} credential — the env
+ * var names a key for this service is conventionally held under (first is
+ * canonical), and where to obtain one.
+ * @property {readonly string[]} plans — the {@link SERVICE_PLANS} an instance may declare.
+ * @property {{strategy: string, planFilter?: (plan: string, models: string[]) => string[]}} catalog
+ * @property {string} [localRuntime] — the `LOCAL_RUNTIMES` id this row IS.
+ * @property {string} [harnessOnly] — reachable only through this harness id.
+ * @property {{apiKeyEnv: string, legacyMarker?: string, legacyApiKeyField?: string}} [gateway] —
+ * present on the rows `PROVIDER_GATEWAYS` derives from.
+ * @property {string} [piProvider] — the built-in provider name Pi ships for this
+ * service (`pi --provider <name>`), read by Pi's harness binding.
+ */
+
+/** @type {readonly ServiceDefinition[]} */
+export const SERVICE_DEFINITIONS = Object.freeze([
+ // --- subscription ---------------------------------------------------------
+ subscription('claude-subscription', 'Claude subscription', 'claude'),
+ subscription('codex-subscription', 'ChatGPT / Codex subscription', 'codex'),
+ subscription('antigravity', 'Antigravity (Google)', 'antigravity'),
+ subscription('grok-build', 'Grok Build (xAI)', 'grok'),
+ subscription('cursor', 'Cursor', 'cursor', {
+ credential: { envVars: ['CURSOR_API_KEY'], keyUrl: 'https://cursor.com/dashboard' },
+ }),
+
+ // --- api-key --------------------------------------------------------------
+ definition({
+ id: 'anthropic',
+ label: 'Anthropic API',
+ family: 'api-key',
+ transports: { anthropic: { defaultBaseUrl: 'https://api.anthropic.com' } },
+ credential: { envVars: ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN'], keyUrl: 'https://console.anthropic.com/settings/keys' },
+ plans: PAID,
+ catalog: { strategy: 'probe' },
+ piProvider: 'anthropic',
+ }),
+ definition({
+ id: 'openai',
+ label: 'OpenAI API',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://api.openai.com/v1' } },
+ credential: { envVars: ['OPENAI_API_KEY'], keyUrl: 'https://platform.openai.com/api-keys' },
+ plans: PAID,
+ catalog: { strategy: 'probe' },
+ piProvider: 'openai',
+ }),
+ definition({
+ id: 'google',
+ label: 'Google AI Studio (Gemini)',
+ family: 'api-key',
+ // Gemini's OpenAI-compatible surface; the native Generative Language API is
+ // reached only by programs that speak it (Pi's `google` provider).
+ transports: { openai: { defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai' } },
+ credential: { envVars: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_GENAI_API_KEY'], keyUrl: 'https://aistudio.google.com/apikey' },
+ plans: METERED,
+ catalog: { strategy: 'probe' },
+ piProvider: 'google',
+ }),
+ definition({
+ id: 'xai',
+ label: 'xAI API',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://api.x.ai/v1' } },
+ credential: { envVars: ['XAI_API_KEY', 'GROK_API_KEY'], keyUrl: 'https://console.x.ai/' },
+ plans: PAID,
+ catalog: { strategy: 'probe' },
+ piProvider: 'xai',
+ }),
+ definition({
+ id: 'bedrock',
+ label: 'Amazon Bedrock',
+ family: 'api-key',
+ // No transport of its own: Claude Code reaches it through a static env
+ // switch (`CLAUDE_CODE_USE_BEDROCK=1`) and Pi through its own provider name.
+ credential: { envVars: ['AWS_BEARER_TOKEN_BEDROCK'], keyUrl: 'https://console.aws.amazon.com/bedrock/' },
+ plans: PAID,
+ catalog: { strategy: 'static' },
+ piProvider: 'amazon-bedrock',
+ }),
+ definition({
+ id: 'kimi',
+ label: 'Kimi / Moonshot',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://api.moonshot.ai/v1' } },
+ credential: { envVars: ['KIMI_API_KEY', 'MOONSHOT_API_KEY'], keyUrl: 'https://platform.moonshot.ai/console/api-keys' },
+ plans: PAID,
+ catalog: { strategy: 'probe' },
+ harnessOnly: 'kimi',
+ piProvider: 'kimi-coding',
+ }),
+ // The three hosted gateways, in the order `PROVIDER_GATEWAYS` has always
+ // listed them — registry order breaks a tie on a record carrying two markers.
+ definition({
+ id: 'orcarouter',
+ label: 'OrcaRouter',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://api.orcarouter.ai/v1' } },
+ credential: { envVars: ['ORCAROUTER_API_KEY'] },
+ plans: PAID,
+ catalog: { strategy: 'probe' },
+ gateway: Object.freeze({ apiKeyEnv: 'ORCAROUTER_API_KEY', legacyMarker: 'orcarouterBacked', legacyApiKeyField: 'orcarouterApiKey' }),
+ }),
+ definition({
+ id: 'openrouter',
+ label: 'OpenRouter',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://openrouter.ai/api/v1' } },
+ credential: { envVars: ['OPENROUTER_API_KEY'] },
+ plans: METERED,
+ // OpenRouter marks its free tier in the model id itself — the one real signal.
+ catalog: { strategy: 'probe', planFilter: suffixPlanFilter(':free') },
+ gateway: Object.freeze({ apiKeyEnv: 'OPENROUTER_API_KEY' }),
+ piProvider: 'openrouter',
+ }),
+ definition({
+ id: 'nvidia-nim',
+ label: 'NVIDIA NIM',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://integrate.api.nvidia.com/v1' } },
+ credential: { envVars: ['NVIDIA_API_KEY'], keyUrl: 'https://build.nvidia.com' },
+ // Free vs paid is declared by the user: NIM's `/models` carries no tier field.
+ plans: METERED,
+ catalog: { strategy: 'probe' },
+ gateway: Object.freeze({ apiKeyEnv: 'NVIDIA_API_KEY' }),
+ piProvider: 'nvidia',
+ }),
+ definition({
+ id: 'opencode-zen',
+ label: 'OpenCode Zen',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://opencode.ai/zen/v1' } },
+ credential: { envVars: ['OPENCODE_API_KEY'], keyUrl: 'https://opencode.ai/auth' },
+ plans: METERED,
+ catalog: { strategy: 'probe', planFilter: suffixPlanFilter('-free') },
+ piProvider: 'opencode',
+ }),
+ definition({
+ id: 'cerebras',
+ label: 'Cerebras',
+ family: 'api-key',
+ transports: { openai: { defaultBaseUrl: 'https://api.cerebras.ai/v1' } },
+ credential: { envVars: ['CEREBRAS_API_KEY'], keyUrl: 'https://cloud.cerebras.ai/' },
+ plans: METERED,
+ catalog: { strategy: 'probe' },
+ piProvider: 'cerebras',
+ }),
+ definition({
+ id: 'openai-compatible',
+ label: 'OpenAI-compatible endpoint',
+ family: 'api-key',
+ // A bare endpoint the user names; nothing conventional to default to.
+ transports: { openai: {} },
+ plans: METERED,
+ catalog: { strategy: 'probe' },
+ }),
+
+ // --- local ----------------------------------------------------------------
+ // Ollama serves an Anthropic-compatible surface beside its `/v1`, which is
+ // what lets Claude Code drive it.
+ localRuntime('ollama', 'Ollama', { anthropic: true }),
+ localRuntime('lmstudio', 'LM Studio'),
+ localRuntime('mtplx', 'MTPLX'),
+ localRuntime('llama', 'llama.cpp'),
+ localRuntime('vllm', 'vLLM'),
+ localRuntime('sglang', 'SGLang', { anthropic: true }),
+ localRuntime('slotstream', 'Slotstream'),
+
+ // --- fleet ----------------------------------------------------------------
+ definition({
+ id: 'fleet-host',
+ label: 'Fleet host',
+ family: 'fleet',
+ transports: { openai: {} },
+ plans: Object.freeze(['free']),
+ catalog: { strategy: 'probe' },
+ }),
+]);
+
+/** Every definition id. */
+export const SERVICE_DEFINITION_IDS = Object.freeze(SERVICE_DEFINITIONS.map((row) => row.id));
+
+/** The definition for an id, or `null`. */
+export const serviceDefinitionById = (id) => SERVICE_DEFINITIONS.find((row) => row.id === id) || null;
+
+/** The definition that IS a local runtime id, or `null`. */
+export const serviceDefinitionForLocalRuntime = (runtimeId) =>
+ SERVICE_DEFINITIONS.find((row) => row.localRuntime === runtimeId) || null;
+
+/**
+ * A slug an instance may be addressed by: `[a-z0-9][a-z0-9-]*`, so it can sit
+ * inside a composite provider id (`harness.method@service`) unescaped.
+ */
+export const SERVICE_SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
+
+/**
+ * The pure INSTANCE shape the rest of the epic composes over: a definition,
+ * the slug it is addressed by, the plan the user declared, the endpoints it is
+ * actually reached at, and its credential material.
+ *
+ * Accepts either a definition id or an already-resolved instance (returned as
+ * is), so every consumer can take both. A transport the instance does not
+ * override falls back to the definition's default base URL; a transport with
+ * neither is still DECLARED (the service speaks it) but has no endpoint, which
+ * `materializeRoute` refuses rather than guessing — a local daemon's port is an
+ * install-specific fact.
+ *
+ * `credentials` holds raw secret material, exactly as `providerConnectionProfile`'s
+ * does, and must never be serialized into a response.
+ *
+ * @param {{definitionId?: string, definition?: ServiceDefinition, slug?: string, plan?: string,
+ * transports?: Record<string, {baseUrl?: string|null}>, credentials?: {apiKey?: string},
+ * credential?: {via?: 'bootstrap'|'stored'}}|string} input
+ * @returns {{definition: ServiceDefinition, slug: string, plan: string,
+ * transports: Record<string, {baseUrl: string|null}>, credentials: {apiKey?: string},
+ * credentialVia: 'stored'|'bootstrap'}}
+ */
+export function resolveServiceInstance(input) {
+ const raw = typeof input === 'string' ? { definitionId: input } : (input || {});
+ if (raw.definition && raw.slug && raw.transports && raw.credentials && raw.credentialVia) return raw;
+ const definition = raw.definition || serviceDefinitionById(raw.definitionId);
+ if (!definition) throw serviceError('SERVICE_DEFINITION_UNKNOWN', `No service definition "${raw.definitionId ?? ''}"`);
+
+ const slug = raw.slug ?? definition.id;
+ if (!SERVICE_SLUG_RE.test(slug)) throw serviceError('SERVICE_SLUG_INVALID', `"${slug}" is not a service slug ([a-z0-9][a-z0-9-]*)`);
+ const plan = raw.plan ?? definition.plans[0];
+ if (!definition.plans.includes(plan)) {
+ throw serviceError('SERVICE_PLAN_UNSUPPORTED', `${definition.label} has no "${plan}" plan; choose one of ${definition.plans.join(', ')}`);
+ }
+
+ const transports = {};
+ for (const [protocol, transport] of Object.entries(definition.transports)) {
+ const override = raw.transports?.[protocol]?.baseUrl;
+ transports[protocol] = { baseUrl: typeof override === 'string' && override !== '' ? override : transport.defaultBaseUrl };
+ }
+ return {
+ definition,
+ slug,
+ plan,
+ transports,
+ credentials: { ...(raw.credentials || {}) },
+ credentialVia: raw.credential?.via === 'bootstrap' ? 'bootstrap' : 'stored',
+ };
+}
+
+/** A typed error every consumer can key on. */
+export function serviceError(code, message) {
+ const err = new Error(message);
+ err.code = code;
+ return err;
+}
diff --git a/server/lib/serviceDefinitions.test.js b/server/lib/serviceDefinitions.test.js
new file mode 100644
index 0000000000..5eefea3a45
--- /dev/null
+++ b/server/lib/serviceDefinitions.test.js
@@ -0,0 +1,131 @@
+/**
+ * The service table absorbs three registries (#7562). What is pinned here is
+ * the absorption itself: that every id the epic (#7561, D2) names exists, that
+ * the local rows ARE the `LOCAL_RUNTIMES` ids, that `PROVIDER_GATEWAYS` derived
+ * from it is byte-identical to the table it replaced, and that Pi's built-in
+ * provider names stay the ones the installed CLI documents.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ CATALOG_STRATEGIES,
+ SERVICE_DEFINITIONS,
+ SERVICE_DEFINITION_IDS,
+ SERVICE_FAMILIES,
+ SERVICE_PLANS,
+ resolveServiceInstance,
+ serviceDefinitionById,
+ serviceDefinitionForLocalRuntime,
+} from './serviceDefinitions.js';
+import { LOCAL_RUNTIMES } from './localProviderRuntime.js';
+import { PROVIDER_GATEWAYS } from './providerGateways.js';
+import { CREDENTIALS } from './credentialRegistry.js';
+
+/** Epic D2, verbatim: the ids the rest of the epic composes from. */
+const D2_IDS = [
+ 'claude-subscription', 'codex-subscription', 'antigravity', 'grok-build', 'cursor', 'kimi',
+ 'anthropic', 'openai', 'google', 'xai', 'bedrock', 'nvidia-nim', 'openrouter', 'orcarouter', 'opencode-zen', 'cerebras', 'openai-compatible',
+ 'ollama', 'lmstudio', 'mtplx', 'llama', 'vllm', 'sglang', 'slotstream', 'fleet-host',
+];
+
+/** `pi --help` / `docs/providers.md` of the installed Pi CLI (0.85.x): provider name → env key. */
+const PI_PROVIDERS = {
+ anthropic: 'ANTHROPIC_API_KEY',
+ openai: 'OPENAI_API_KEY',
+ nvidia: 'NVIDIA_API_KEY',
+ google: 'GEMINI_API_KEY',
+ 'amazon-bedrock': 'AWS_BEARER_TOKEN_BEDROCK',
+ cerebras: 'CEREBRAS_API_KEY',
+ xai: 'XAI_API_KEY',
+ openrouter: 'OPENROUTER_API_KEY',
+ opencode: 'OPENCODE_API_KEY',
+ 'kimi-coding': 'KIMI_API_KEY',
+};
+
+describe('SERVICE_DEFINITIONS', () => {
+ it('covers every id the epic names, each exactly once', () => {
+ for (const id of D2_IDS) expect(serviceDefinitionById(id), id).not.toBeNull();
+ expect(new Set(SERVICE_DEFINITION_IDS).size).toBe(SERVICE_DEFINITION_IDS.length);
+ });
+
+ it('keeps every row inside the declared vocabularies', () => {
+ for (const row of SERVICE_DEFINITIONS) {
+ expect(SERVICE_FAMILIES, row.id).toContain(row.family);
+ expect(row.plans.length, row.id).toBeGreaterThan(0);
+ for (const plan of row.plans) expect(SERVICE_PLANS, row.id).toContain(plan);
+ expect(CATALOG_STRATEGIES, row.id).toContain(row.catalog.strategy);
+ for (const protocol of Object.keys(row.transports)) expect(['anthropic', 'openai'], row.id).toContain(protocol);
+ if (row.family === 'subscription') expect(typeof row.harnessOnly, row.id).toBe('string');
+ if (row.family === 'local') expect(row.plans, row.id).toEqual(['local']);
+ }
+ });
+
+ // One row per daemon PortOS can check for — a runtime added to either table
+ // alone is one a harness could not be composed onto (or one nothing probes).
+ it('has exactly the LOCAL_RUNTIMES ids as its local rows', () => {
+ const local = SERVICE_DEFINITIONS.filter((row) => row.family === 'local').map((row) => row.localRuntime).sort();
+ expect(local).toEqual(Object.keys(LOCAL_RUNTIMES).sort());
+ for (const id of Object.keys(LOCAL_RUNTIMES)) expect(serviceDefinitionForLocalRuntime(id)?.id).toBe(id);
+ });
+
+ // The projection must reproduce the table it replaced: every consumer keys on
+ // these exact fields, and the toolkit mirror is compared with toEqual.
+ it('derives PROVIDER_GATEWAYS unchanged', () => {
+ expect(PROVIDER_GATEWAYS).toEqual([
+ { id: 'orcarouter', label: 'OrcaRouter', baseURL: 'https://api.orcarouter.ai/v1', apiKeyEnv: 'ORCAROUTER_API_KEY', legacyMarker: 'orcarouterBacked', legacyApiKeyField: 'orcarouterApiKey' },
+ { id: 'openrouter', label: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKeyEnv: 'OPENROUTER_API_KEY' },
+ { id: 'nvidia-nim', label: 'NVIDIA NIM', baseURL: 'https://integrate.api.nvidia.com/v1', apiKeyEnv: 'NVIDIA_API_KEY', keyUrl: 'https://build.nvidia.com' },
+ ]);
+ });
+
+ // The AI rows of the credential registry are the same keys, so a user who
+ // pasted one under Settings > Credentials is the one a service reads.
+ it('names the credential registry\'s env vars for the vendors it absorbs', () => {
+ for (const [credentialId, serviceId] of [['anthropic', 'anthropic'], ['openai', 'openai'], ['google', 'google'], ['xai', 'xai'], ['cursor', 'cursor'], ['kimi', 'kimi']]) {
+ const credential = CREDENTIALS.find((row) => row.id === credentialId);
+ expect(serviceDefinitionById(serviceId).credential.envVars, serviceId).toEqual(credential.envVars);
+ }
+ });
+
+ it('only names Pi providers the installed CLI ships, keyed by Pi\'s own env var', () => {
+ for (const row of SERVICE_DEFINITIONS.filter((entry) => entry.piProvider)) {
+ expect(PI_PROVIDERS, row.id).toHaveProperty(row.piProvider);
+ expect(row.credential.envVars[0], row.id).toBe(PI_PROVIDERS[row.piProvider]);
+ }
+ });
+
+ it('filters a plan only where the vendor marks the tier in the model id', () => {
+ const models = ['vendor/big', 'vendor/small:free', 'big-pickle-free'];
+ expect(serviceDefinitionById('openrouter').catalog.planFilter('free', models)).toEqual(['vendor/small:free']);
+ expect(serviceDefinitionById('openrouter').catalog.planFilter('paid', models)).toEqual(models);
+ expect(serviceDefinitionById('opencode-zen').catalog.planFilter('free', models)).toEqual(['big-pickle-free']);
+ expect(serviceDefinitionById('nvidia-nim').catalog.planFilter).toBeUndefined();
+ });
+});
+
+describe('resolveServiceInstance', () => {
+ it('defaults slug, plan and transports from the definition, and keeps overrides', () => {
+ const instance = resolveServiceInstance('nvidia-nim');
+ expect(instance).toMatchObject({ slug: 'nvidia-nim', plan: 'free', credentialVia: 'stored' });
+ expect(instance.transports).toEqual({ openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } });
+
+ const paid = resolveServiceInstance({ definitionId: 'nvidia-nim', slug: 'nvidia-paid', plan: 'paid', credentials: { apiKey: 'k' } });
+ expect(paid).toMatchObject({ slug: 'nvidia-paid', plan: 'paid', credentials: { apiKey: 'k' } });
+ expect(resolveServiceInstance(paid)).toBe(paid);
+ });
+
+ // A local daemon's port is an install fact: the row declares the wire, and
+ // an instance that names no endpoint has NONE — never a guessed default.
+ it('leaves a local transport endpoint-less until the instance names it', () => {
+ expect(resolveServiceInstance('ollama').transports).toEqual({ openai: { baseUrl: null }, anthropic: { baseUrl: null } });
+ expect(resolveServiceInstance({ definitionId: 'ollama', transports: { openai: { baseUrl: 'http://127.0.0.1:11434/v1' } } }).transports.openai.baseUrl)
+ .toBe('http://127.0.0.1:11434/v1');
+ });
+
+ it.each([
+ [{ definitionId: 'nope' }, 'SERVICE_DEFINITION_UNKNOWN'],
+ [{ definitionId: 'ollama', slug: 'Bad Slug' }, 'SERVICE_SLUG_INVALID'],
+ [{ definitionId: 'ollama', plan: 'paid' }, 'SERVICE_PLAN_UNSUPPORTED'],
+ ])('refuses %j with %s', (input, code) => {
+ expect(() => resolveServiceInstance(input)).toThrow(expect.objectContaining({ code }));
+ });
+});