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

simplify the harness bindings: one blocker field, constraint matching, shared record tail (#7562)

[._.]/ Adam Eivy6d9bf183ec3d
diff --git a/server/lib/README.md b/server/lib/README.md
index 2a0872251b..0b3557aba0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -230,7 +230,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `harnessOutput.js` | Parsers for what a coding-agent HARNESS prints about itself: `parseHarnessVersion(stdout)` (the one semver run in a `--version` banner, `null` when unparseable), `compareHarnessVersions(a, b)` (the null-guarding wrapper around `versionUtils.js#compareSemver` — `null` when either side is unparseable, so a version that did not parse never reads as "out of date"), `parseHarnessModels(harnessId, stdout)` + `HARNESS_MODEL_PARSER_IDS` (OpenCode's `provider/model` lines and Grok's bulleted list are parsed here; Antigravity and Cursor DELEGATE to `antigravity.js#parseAntigravityModelList` / `aiToolkit/internal/cursor.js#parseCursorModelList`, which the provider-card refresh has used for far longer), `MAX_MODELS`, and `parseNpmLatestVersion`. Pure: the service layer runs the child and hands the captured stdout here, so the vendor output shapes are pinned by table-driven tests instead of by running six real binaries in CI. Model ids come back in the exact spelling `--model` takes — namespaces kept where the vendor keeps them. Consumed by `services/providerRuntimeInstaller.js` and `services/harnesses.js`. |
| `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`, `nvidia-nim`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, `isGatewayBackedProvider(config)`, and `attachGatewaySiblingKey(provider, providers)` — the synchronous twin of the toolkit's `withGatewayApiKey` for callers holding an already-loaded (RAW, keyless) collection: a fallback pick armed from such a map executes with its sibling's key instead of going out with no Authorization header. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) — `providerGateways.parity.test.js` fails when the two drift; `client/src/utils/providerGateways.js` re-exports this leaf rather than copying it. DERIVED (#7562) from the `serviceDefinitions.js` rows carrying a `gateway` column, so a gateway is one row in that table; the projected shape is unchanged. Dependency-light: imports only that leaf. |
| `serviceDefinitions.js` | `SERVICE_DEFINITIONS` (#7562) — every backend a harness can be pointed at, as ONE table: subscription services (claude-subscription, codex-subscription, antigravity, grok-build, cursor), API-key services (anthropic, openai, google, xai, bedrock, kimi, the three hosted gateways orcarouter/openrouter/nvidia-nim, opencode-zen, cerebras, a generic openai-compatible endpoint), one `local` row per `LOCAL_RUNTIMES` id, and `fleet-host`. Each row: `family`, `transports` (`anthropic` / `openai` with a default base URL, or none for a local daemon whose port is an install fact), `credential` (env var names, key URL), the `plans` it may be declared under (`SERVICE_PLANS`), a `catalog` strategy with an optional per-plan filter (OpenRouter `:free`, OpenCode Zen `*-free`), and where relevant `localRuntime`, `harnessOnly`, `gateway` (the rows `PROVIDER_GATEWAYS` derives from) and `piProvider` (Pi's built-in name). `resolveServiceInstance(input)` is the pure instance shape the epic composes over (definition + `slug` + `plan` + resolved `transports` + raw `credentials`), `serviceDefinitionById` / `serviceDefinitionForLocalRuntime` look rows up, `serviceError(code, message)` mints the typed errors. Imports nothing, so `providerGateways.js` and the browser can reach it. |
-| `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`. |
+| `providerHarnesses.js` | Provider HARNESS identity for the connection graph (#6366) — `PROVIDER_HARNESSES` (one row per agent program PortOS drives: claude/opencode/codex/antigravity/cursor/grok/kimi/pi, plus `direct` — PortOS's own HTTP client, the harness of an `api` record (#7562) — each with its supported `modes`, wire `protocol`, the existing `is*Provider` predicate as its matcher, and its capability `bindings`: every way the program can be pointed at a service definition — subscription, protocol+baseUrl+credential, static-env service (Bedrock), `codexOss`, `piProvider`), `PROVIDER_HARNESS_IDS`, `harnessById`, `harnessForProvider` (`direct` for an `api` record, null only for an UNKNOWN harness), `normalizeHarnessId` / `graphHarnessId` (the one `direct` ↔ `NULL` translation for the graph's nullable column), `compatibleBindings(harness, serviceInstance)` / `firstCompatibleBinding` / `isCompatible` (which bindings reach a resolved service instance), `CREATABLE_HARNESS_IDS` (mintable from a bare connection) and `harnessConnectionBlocker` (the row's `connectionBlocker`: why not — no recipe at all, or a subscription/Pi row that composes onto named services only), `harnessSupportsMode`, `ROUTE_MODES`, plus the model-name adapters `toExecutableModelName` / `toCanonicalModelName` (the verified inverse of `prefixOpencodeModel`: a stored alias is canonicalized only when it maps back to the exact stored string, so import never rewrites a saved model by heuristically stripping a prefix). Distinct from `providerVendors.js` (argv-shaped), `providerFamilies.js` (subscription quota) and `serviceDefinitions.js` (the backends). Pure leaf — `client/src/utils/providerHarnesses.js` names a binding's harness through `harnessById`; the `direct` ↔ `NULL` translation is mirrored in `aiToolkit/internal/harnesses.js` behind `providerHarnesses.parity.test.js`. |
| `providerContextWindows.js` | The context-window ladder for provider/model planning, split out of `services/stageRunner.js` so the browser shares it: the vendor constants (`DEFAULT_LARGE_CONTEXT_WINDOW` / `CODEX_CONTEXT_WINDOW` / `GEMINI_CONTEXT_WINDOW` / `GROK_CONTEXT_WINDOW` / `KIMI_CONTEXT_WINDOW`), `knownModelContextWindow(model)` (the known-model regex table), `knownProviderContextWindow(provider)` (the vendor window for a configured-default CLI/TUI provider) `catalogModelContextWindow(provider, model)` (the window the provider's own `/models` catalog reported, which outranks the table) and `mergeObservedContextWindows(provider, observed)` (folds a local daemon's LIVE `/v1/models` windows onto that catalog rung, so they outrank a stale refresh while an explicit `contextWindow` still wins; never persisted) and `aliasServedContextWindows(provider, runtime, served)` (re-keys a daemon's served windows by every spelling the provider could dispatch under, for a caller that already holds the listing). The Ollama `num_ctx` ceiling is deliberately NOT here — see `aiToolkit/`. `stageRunner.js` builds `effectiveContextWindow` on them; `client/src/utils/providerContextWindows.js` re-exports them for the provider-card budget meter, so the two ends can't resolve a different window. Pure. |
| `providerConnections.js` | Provider CONNECTION identity for the connection graph (#6366) — `providerConnectionProfile(provider)` reads one record as the backend it describes (`kind`, `protocol`, `transports`, RAW server-only `credentials`, the `owned` field/env split, and `reasons` from `CONNECTION_ISOLATION_REASONS` when the config is dynamic, external, unparsable or endpoint-less). `sameConnectionIdentity` compares real credential values and refuses once any is the `REDACTED_CREDENTIAL` sentinel, so a sanitized record can never merge two connections; `compareBackendEndpoints` is the looser same-daemon test that only ever produces a link SUGGESTION, applying the recognized OpenAI-compatible `/v1` conversion (never DNS resolution, loopback/remote equivalence or arbitrary path trimming). `projectConnectionOwnedFields(provider, connection)` projects a stored backend through the reader's protocol and env-ownership rules for the graph service; `withoutConnectionOwnedFields` / `withConnectionOwnedFields` are the lossless split/materialize pair that keeps a downgraded install runnable from `data/providers.json` alone. Pure: no I/O. |
| `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. |
diff --git a/server/lib/aiToolkit/internal/harnesses.js b/server/lib/aiToolkit/internal/harnesses.js
index 74e83612c3..eefc63ace8 100644
--- a/server/lib/aiToolkit/internal/harnesses.js
+++ b/server/lib/aiToolkit/internal/harnesses.js
@@ -1,7 +1,6 @@
/**
- * 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`).
+ * 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 —
@@ -9,16 +8,12 @@
* 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.
+ * Only this translation is mirrored: the id list, 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, and `direct` is the one id with two spellings.
*/
-/** 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';
@@ -27,6 +22,3 @@ 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/providerHarnesses.js b/server/lib/providerHarnesses.js
index 6fbd5ec5eb..1e17e063d4 100644
--- a/server/lib/providerHarnesses.js
+++ b/server/lib/providerHarnesses.js
@@ -58,33 +58,27 @@ const API_ONLY_MODES = Object.freeze(['api']);
const CLI_ONLY_MODES = Object.freeze(['cli']);
/**
- * Why a harness carries no command recipe, as the clause the create endpoint
- * refuses with (`bindingBlocker` in `providerRouteRecipes.js`).
+ * Why a harness cannot be minted from a bare CONNECTION (an arbitrary
+ * endpoint), as the clause the create endpoint refuses with (`bindingBlocker`
+ * in `providerRouteRecipes.js`). `connectionBlocker` on the row.
*
* This is DATA on the row rather than prose in a comment because the refusal
* quotes it. Until three reasons existed, `bindingBlocker` hardcoded the first
- * 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
- * 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.)
+ * one — so adding a row for a different reason told the user their harness
+ * "reaches only its own vendor service", which is both wrong and points at the
+ * wrong remedy.
+ *
+ * Two of these rows have no recipe at all (Kilo, OpenChamber: nothing can be
+ * composed onto them, so they carry no `bindings` either). The others DO carry
+ * a recipe and compose onto the services their bindings name through
+ * `materializeRoute`; they just cannot be pointed at an endpoint they were
+ * not built to know.
*/
-const NO_RECIPE = Object.freeze({
+const CONNECTION_BLOCKER = Object.freeze({
/** 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',
/**
@@ -99,22 +93,6 @@ const CONNECTION_LIMIT = Object.freeze({
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).
*
@@ -144,7 +122,7 @@ const subscriptionRecipe = (command, { cli, tui }) => Object.freeze({
*
* A harness with **no** recipe is not an oversight — it means this program has
* no backend PortOS can point at from a connection, and its row says WHICH of
- * the {@link NO_RECIPE} reasons applies. Adding one of those stays `/ai/new`.
+ * the {@link CONNECTION_BLOCKER} reasons applies. Adding one of those stays `/ai/new`.
*/
/** Claude Code's headless argv, shared by every Claude recipe mode. */
@@ -156,48 +134,61 @@ const TUI_PROMPT_DELAY_MS = 2500;
/** A local agent run is long; every shipped CLI/TUI sample uses this timeout. */
const HARNESS_TIMEOUT_MS = 600000;
+/**
+ * One recipe shape for every program: the binary, its per-mode argv (lifted
+ * from the shipped samples), and — for a program the legacy connection path
+ * can point at an endpoint — where that endpoint and its credential land.
+ * A subscription program or Pi has no such columns (`baseUrl`/`credential`
+ * stay `null`); their bindings say how they reach a service.
+ */
+const recipe = ({ command, cli, tui, headlessArgs = [], tuiPromptDelayMs = TUI_PROMPT_DELAY_MS, baseUrl = null, credential = null }) => Object.freeze({
+ command,
+ timeout: HARNESS_TIMEOUT_MS,
+ baseUrl,
+ credential,
+ modes: {
+ cli: { args: cli, headlessArgs },
+ // Pi's shipped TUI sample declares no prompt delay; `null` keeps it that way.
+ tui: { args: tui, ...(tuiPromptDelayMs === null ? {} : { tuiPromptDelayMs }) },
+ },
+});
+
/**
* 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):
+ * describes.
*
- * - `{ 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 binding is a set of CONSTRAINTS on the service (every one present must
+ * hold) plus WRITER columns saying where the service's values land:
*
- * 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.
+ * Constraints — `service` (this definition id), `localRuntime` (one of these
+ * `LOCAL_RUNTIMES` ids), `piProvider: true` (the definition carries a name Pi
+ * ships), `protocol` (the instance declares that transport).
+ *
+ * Writers — `baseUrl` is the ONE endpoint axis: `{via:'env', name}`,
+ * `{via:'field'}` (the record's own `endpoint`), `{via:'opencodeConfig',
+ * builtin?}` (the inline provider JSON OpenCode reads; `builtin` declares
+ * permissions only, for a provider OpenCode ships), `{via:'piProvider', flag}`
+ * (`--provider <name>` on the argv), or absent (nothing to write — the
+ * program signs in itself, or a static `env` switch selects the service, as
+ * Bedrock's `CLAUDE_CODE_USE_BEDROCK=1` does). `credential` is `{via:'env',
+ * name?, required}` (`name` defaults to the service's own key var),
+ * `{via:'field', required}` (the record's `apiKey`) or `{via:'gatewayEnv'}`
+ * (the gateway's own key var). `env` is static.
+ *
+ * Codex's local-runtime binding writes nothing Codex-specific: `--oss
+ * --local-provider <x>` is emitted at spawn from the runtime marker the record
+ * carries (`buildCodexOssArgs`), so the binding only constrains WHICH runtimes.
+ *
+ * A row with NO bindings is exactly a row nothing composes onto, and it says
+ * why in `connectionBlocker`. `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}[]}
*/
@@ -207,20 +198,18 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Claude Code',
modes: CLI_TUI_MODES,
protocol: 'anthropic',
- recipe: Object.freeze({
+ recipe: recipe({
command: 'claude',
- timeout: HARNESS_TIMEOUT_MS,
+ cli: ['--print'],
+ headlessArgs: CLAUDE_HEADLESS_ARGS,
+ tui: ['--dangerously-skip-permissions'],
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: 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({ service: 'claude-subscription' }),
Object.freeze({ protocol: 'anthropic', baseUrl: Object.freeze({ via: 'env', name: 'ANTHROPIC_BASE_URL' }), credential: CLAUDE_AUTH_TOKEN }),
Object.freeze({
service: 'bedrock',
@@ -235,17 +224,14 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'OpenCode',
modes: CLI_TUI_MODES,
protocol: 'openai',
- recipe: Object.freeze({
+ recipe: recipe({
command: 'opencode',
- timeout: HARNESS_TIMEOUT_MS,
+ cli: ['run'],
+ tui: [],
// OpenCode reads its backend out of an inline provider JSON rather than an
// environment variable, which is also why that string stays route-owned.
baseUrl: { via: 'opencodeConfig' },
credential: { via: 'field', required: false },
- modes: {
- cli: { args: ['run'], headlessArgs: [] },
- tui: { args: [], tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },
- },
}),
bindings: Object.freeze([
// OpenCode's own hosted service is a provider it ships; only permissions
@@ -274,7 +260,7 @@ export const PROVIDER_HARNESSES = Object.freeze([
// nothing while reporting a backend, so Kilo stays classifiable and
// installable but not creatable from a connection.
recipe: null,
- noRecipe: NO_RECIPE.UNWRITTEN_CONFIG,
+ connectionBlocker: CONNECTION_BLOCKER.UNWRITTEN_CONFIG,
bindings: Object.freeze([]),
matches: isKiloProvider,
}),
@@ -287,7 +273,7 @@ export const PROVIDER_HARNESSES = Object.freeze([
// configures (its providers are signed in through its own web UI), so there
// is no PortOS-supplied backend for a minted route to carry.
recipe: null,
- noRecipe: NO_RECIPE.EXTERNAL_RUNTIME,
+ connectionBlocker: CONNECTION_BLOCKER.EXTERNAL_RUNTIME,
bindings: Object.freeze([]),
matches: isOpenchamberProvider,
}),
@@ -296,24 +282,18 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Codex',
modes: CLI_TUI_MODES,
protocol: 'openai',
- recipe: Object.freeze({
+ recipe: recipe({
command: 'codex',
- timeout: HARNESS_TIMEOUT_MS,
+ cli: [],
+ tui: [],
baseUrl: { via: 'field' },
credential: { via: 'field', required: false },
- modes: {
- cli: { args: [], headlessArgs: [] },
- 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({ service: 'codex-subscription' }),
+ // The runtimes Codex's `--oss --local-provider` 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' }),
@@ -328,9 +308,9 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Antigravity',
modes: CLI_TUI_MODES,
protocol: 'native',
- 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' })]),
+ recipe: recipe({ command: 'agy', cli: ['--print', '--dangerously-skip-permissions'], tui: ['--dangerously-skip-permissions'] }),
+ connectionBlocker: CONNECTION_BLOCKER.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ service: 'antigravity' })]),
matches: isAntigravityProvider,
}),
Object.freeze({
@@ -338,9 +318,9 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Cursor Agent',
modes: CLI_TUI_MODES,
protocol: 'native',
- recipe: subscriptionRecipe('cursor-agent', { cli: ['--print', '--force'], tui: ['--force'] }),
- connectionLimit: CONNECTION_LIMIT.VENDOR_SERVICE,
- bindings: Object.freeze([Object.freeze({ via: 'subscription', service: 'cursor' })]),
+ recipe: recipe({ command: 'cursor-agent', cli: ['--print', '--force'], tui: ['--force'] }),
+ connectionBlocker: CONNECTION_BLOCKER.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ service: 'cursor' })]),
matches: isCursorProvider,
}),
Object.freeze({
@@ -348,9 +328,9 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Grok',
modes: CLI_TUI_MODES,
protocol: 'native',
- recipe: subscriptionRecipe('grok', { cli: [], tui: [] }),
- connectionLimit: CONNECTION_LIMIT.VENDOR_SERVICE,
- bindings: Object.freeze([Object.freeze({ via: 'subscription', service: 'grok-build' })]),
+ recipe: recipe({ command: 'grok', cli: [], tui: [] }),
+ connectionBlocker: CONNECTION_BLOCKER.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ service: 'grok-build' })]),
matches: isGrokProvider,
}),
Object.freeze({
@@ -358,9 +338,9 @@ export const PROVIDER_HARNESSES = Object.freeze([
label: 'Kimi Code',
modes: CLI_TUI_MODES,
protocol: 'native',
- recipe: subscriptionRecipe('kimi', { cli: [], tui: ['--yolo'] }),
- connectionLimit: CONNECTION_LIMIT.VENDOR_SERVICE,
- bindings: Object.freeze([Object.freeze({ via: 'subscription', service: 'kimi' })]),
+ recipe: recipe({ command: 'kimi', cli: [], tui: ['--yolo'] }),
+ connectionBlocker: CONNECTION_BLOCKER.VENDOR_SERVICE,
+ bindings: Object.freeze([Object.freeze({ service: 'kimi' })]),
matches: isKimiProvider,
}),
Object.freeze({
@@ -370,22 +350,17 @@ export const PROVIDER_HARNESSES = Object.freeze([
// 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,
+ recipe: recipe({ command: 'pi', cli: ['--print', '--approve'], tui: ['--approve'], tuiPromptDelayMs: null }),
+ connectionBlocker: CONNECTION_BLOCKER.PI_BUILTIN_PROVIDERS,
bindings: Object.freeze([
- Object.freeze({ via: 'piProvider', credential: Object.freeze({ via: 'env', required: true }) }),
+ // Pi selects its backend by provider NAME, not by URL — see
+ // CONNECTION_BLOCKER.PI_BUILTIN_PROVIDERS. The flag pair is appended to
+ // the mode argv, so the shipped sample argv stays the prefix.
+ Object.freeze({
+ piProvider: true,
+ baseUrl: Object.freeze({ via: 'piProvider', flag: '--provider' }),
+ 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.
@@ -397,13 +372,18 @@ export const PROVIDER_HARNESSES = Object.freeze([
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.
+ // `connectionBlocker` either, because it CAN be pointed at a service.
recipe: null,
- bindings: Object.freeze([DIRECT_API_BINDING]),
+ bindings: Object.freeze([
+ Object.freeze({ protocol: 'openai', baseUrl: Object.freeze({ via: 'field' }), credential: Object.freeze({ via: 'field', required: false }) }),
+ ]),
matches: (provider) => provider?.type === 'api',
}),
]);
+/** The `direct` row, resolved once: every `api` record is driven by it. */
+const DIRECT_HARNESS = PROVIDER_HARNESSES.find((h) => h.id === 'direct');
+
/** The harness id a direct API record resolves to. */
export const DIRECT_HARNESS_ID = 'direct';
@@ -427,18 +407,11 @@ 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 && !h.connectionLimit).map((h) => h.id),
+ PROVIDER_HARNESSES.filter((h) => h.recipe && !h.connectionBlocker).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;
-};
+/** Why `harnessId` cannot be minted from a bare connection, or `null` when it can. */
+export const harnessConnectionBlocker = (harnessId) => harnessById(harnessId)?.connectionBlocker ?? null;
/** The command recipe for a harness id, or `null` when it has none. */
export const harnessRecipe = (id) => harnessById(id)?.recipe || null;
@@ -457,40 +430,50 @@ export const harnessRecipe = (id) => harnessById(id)?.recipe || null;
*/
export function harnessForProvider(provider) {
if (!provider || typeof provider !== 'object') return null;
+ if (provider.type === 'api') return DIRECT_HARNESS;
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[]}
+ * Whether one binding's constraints all hold for a resolved service instance.
+ * Every constraint present must hold; a binding with none would match
+ * everything, so at least one is always declared.
*/
-export function compatibleBindings(harness, serviceInstance) {
+const bindingMatches = (binding, { definition, transports }) => (
+ (binding.service === undefined || binding.service === definition.id)
+ && (binding.localRuntime === undefined || binding.localRuntime.includes(definition.localRuntime))
+ && (binding.piProvider === undefined || typeof definition.piProvider === 'string')
+ && (binding.protocol === undefined || Boolean(transports?.[binding.protocol]))
+);
+
+/**
+ * The bindings a harness may use to reach a resolved service instance (from
+ * `resolveServiceInstance`), in row order — the first is the one
+ * `materializeRoute` writes. Empty when the pair cannot be composed. A
+ * definition that is `harnessOnly` composes onto nothing but that harness.
+ */
+const bindingsFor = (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);
- });
-}
+ return row.bindings;
+};
+
+/**
+ * @param {object|string} harness - a registry row or its id
+ * @param {{definition: object, transports: object}} serviceInstance
+ * @returns {readonly object[]}
+ */
+export const compatibleBindings = (harness, serviceInstance) =>
+ bindingsFor(harness, serviceInstance).filter((binding) => bindingMatches(binding, serviceInstance));
+
+/** The binding `materializeRoute` writes for this pair, or `null`. */
+export const firstCompatibleBinding = (harness, serviceInstance) =>
+ bindingsFor(harness, serviceInstance).find((binding) => bindingMatches(binding, serviceInstance)) ?? null;
/** Whether `harness` can be pointed at `serviceInstance` at all. */
-export const isCompatible = (harness, serviceInstance) => compatibleBindings(harness, serviceInstance).length > 0;
+export const isCompatible = (harness, serviceInstance) => firstCompatibleBinding(harness, serviceInstance) !== null;
/** Whether `harnessId` can be driven in `mode`. Unknown harness → false. */
export const harnessSupportsMode = (harnessId, mode) =>
diff --git a/server/lib/providerHarnesses.parity.test.js b/server/lib/providerHarnesses.parity.test.js
index c9da5fee04..fd1951f870 100644
--- a/server/lib/providerHarnesses.parity.test.js
+++ b/server/lib/providerHarnesses.parity.test.js
@@ -1,10 +1,9 @@
/**
* 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.
+ * its own copy of the `direct` ↔ `null` translation. This pins the two
+ * together, as `providerGateways.parity.test.js` does for gateways, so the
+ * toolkit can never spell a direct binding differently from the host.
*/
import { describe, expect, it } from 'vitest';
import {
@@ -15,17 +14,14 @@ import {
} 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);
+ it('names the direct harness the same, and it is a registry row', () => {
expect(TOOLKIT_DIRECT).toBe(SERVER_DIRECT);
- for (const id of PROVIDER_HARNESS_IDS) expect(isHarnessId(id)).toBe(true);
+ expect(PROVIDER_HARNESS_IDS).toContain(TOOLKIT_DIRECT);
});
it('translates the direct binding the same way in both directions', () => {
diff --git a/server/lib/providerHarnesses.test.js b/server/lib/providerHarnesses.test.js
index 2e6664e10d..385d60c6c3 100644
--- a/server/lib/providerHarnesses.test.js
+++ b/server/lib/providerHarnesses.test.js
@@ -33,33 +33,28 @@ const VENDOR_WITHOUT_HARNESS = 'gemini-legacy';
const spawnableVendors = PROVIDER_VENDORS.filter((vendor) => vendor.id !== VENDOR_WITHOUT_HARNESS);
-describe('harness rows say why they carry no recipe', () => {
+describe('harness rows say why they cannot be minted from a connection', () => {
// 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.
- //
- // 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 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));
- }
+ it('gives every non-creatable program a reason, and every creatable one none', () => {
+ for (const harness of PROVIDER_HARNESSES.filter((row) => row.id !== 'direct')) {
+ expect(Boolean(harness.connectionBlocker), `${harness.id}`).toBe(!CREATABLE_HARNESS_IDS.includes(harness.id));
}
+ expect(CREATABLE_HARNESS_IDS).toEqual(['claude', 'opencode', 'codex']);
});
- // 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));
+ // Since #7562 a row with no bindings is exactly a row nothing can be
+ // composed onto — it has no recipe either. `direct` has no recipe (it is not
+ // a program) yet binds, so it carries no reason. A subscription program (or
+ // Pi) HAS a recipe — `<harness>.cli@<service>` materializes — while still
+ // refusing an arbitrary connection.
+ it('leaves a row with no bindings recipe-less, and every program with bindings a recipe', () => {
+ for (const harness of PROVIDER_HARNESSES.filter((row) => row.id !== 'direct')) {
+ expect(harness.recipe === null, `${harness.id}`).toBe(harness.bindings.length === 0);
}
- expect(CREATABLE_HARNESS_IDS).toEqual(['claude', 'opencode', 'codex']);
+ expect(harnessById('direct').recipe).toBeNull();
+ expect(harnessById('direct').bindings).toHaveLength(1);
});
it('refuses each uncreatable harness with its own reason, not a shared guess', () => {
@@ -70,8 +65,8 @@ describe('harness rows say why they carry no recipe', () => {
// 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(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(messages).toContain(`${harnessById('kilo').label} ${harnessById('kilo').connectionBlocker}, so it cannot be pointed at a backend connection. Add it from the provider editor instead.`);
+ expect(messages).toContain(`${harnessById('pi').label} ${harnessById('pi').connectionBlocker}, 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/);
});
@@ -96,8 +91,8 @@ describe('capability bindings (#7562)', () => {
// 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');
+ it('binds Codex to exactly the local runtimes buildCodexOssArgs can name', () => {
+ const binding = harnessById('codex').bindings.find((row) => row.localRuntime);
expect([...binding.localRuntime].sort()).toEqual(Object.keys(CODEX_OSS_LOCAL_PROVIDERS).sort());
});
@@ -136,8 +131,8 @@ describe('capability bindings (#7562)', () => {
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');
+ it('prefers the local-runtime binding to the generic OpenAI one for a local daemon', () => {
+ expect(compatibleBindings('codex', OLLAMA)[0].localRuntime).toContain('ollama');
expect(compatibleBindings('codex', resolveServiceInstance('nvidia-nim'))[0].baseUrl).toEqual({ via: 'env', name: 'OPENAI_BASE_URL' });
});
});
diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.js
index 620cdc475e..80d3c8c30a 100644
--- a/server/lib/providerRouteRecipes.js
+++ b/server/lib/providerRouteRecipes.js
@@ -3,7 +3,7 @@ import { modeSiblingId } from './aiToolkit/internal/providerModes.js';
import { PROVIDER_GATEWAYS } from './providerGateways.js';
import {
CREATABLE_HARNESS_IDS,
- compatibleBindings,
+ firstCompatibleBinding,
graphHarnessId,
harnessById,
harnessConnectionBlocker,
@@ -172,7 +172,7 @@ export function bindingBlocker({ harnessId: requestedHarnessId, modes, connectio
};
}
- const credential = harnessId ? harnessRecipe(harnessId)?.credential ?? null : null;
+ const credential = harnessId ? harnessRecipe(harnessId)?.credential : null;
const key = credential?.via === 'env' ? credential.name : 'apiKey';
if (credential?.required && !connection.credentials?.[key]) {
return {
@@ -264,15 +264,32 @@ export function buildRouteRecord({ harnessId, mode, providerId, name, connection
// carry one. The record then simply has no marker, and the caller's identity
// check is what decides whether it still describes this backend.
...(connectionKindMarkers(connection.kind) || {}),
- ...(recipe ? { command: recipe.command, timeout: recipe.timeout } : { timeout: 300000 }),
- ...(recipe ? recipe.modes[mode] : {}),
+ ...executableRecordTail({ recipe, mode, enabled: false, envVars, secretEnvVars }),
+ };
+}
+
+/** Default wall clock for a record no recipe times — every shipped `api` sample. */
+const API_ROUTE_TIMEOUT_MS = 300000;
+
+/**
+ * The half of an executable record that every writer here assembles the same
+ * way: the program and its per-mode argv (or the API wall clock when there is
+ * no program), an empty catalog, and the env maps. Stated once so a new marker
+ * or env rule lands in {@link buildRouteRecord} and {@link materializeRoute}
+ * together.
+ */
+const executableRecordTail = ({ recipe, mode, args, enabled, envVars, secretEnvVars }) => {
+ const modeRecipe = recipe?.modes?.[mode] ?? null;
+ return {
+ ...(recipe ? { command: recipe.command, timeout: recipe.timeout } : { timeout: API_ROUTE_TIMEOUT_MS }),
+ ...(modeRecipe ? { ...modeRecipe, ...(args ? { args } : {}) } : {}),
models: [],
defaultModel: null,
- enabled: false,
+ enabled,
envVars,
secretEnvVars,
};
-}
+};
/**
* Route ids for a new binding's modes: readable, stable and free.
@@ -306,21 +323,22 @@ export function mintRouteIds({ harnessId, kind, modes, taken }) {
* the runtime's `*Backed` boolean, or `gatewayBacked: '<id>'`. Slotstream and
* a plain API endpoint carry none, exactly as {@link connectionKindMarkers}.
*/
-const serviceMarkers = (harness, definition) => {
+const serviceMarkers = (definition, { wrapper }) => {
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 };
+ // `gatewayBacked` marks a WRAPPER — a program spawned in front of a gateway
+ // (the sibling api record owns the key). A record that IS the client carries
+ // none, exactly as every shipped `api` sample.
+ if (definition.gateway && wrapper) 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 connection kind a service instance reads back as — the same key space
+ * {@link connectionKindMarkers} and {@link opencodeNamespace} are keyed on, so
+ * a materialized OpenCode config names the namespace its marker resolves to.
+ */
+const serviceConnectionKind = ({ definition, slug }) =>
+ definition.localRuntime || (definition.gateway ? `gateway:${definition.id}` : slug);
/**
* The executable record for a (harness, method, service) composition (#7562) —
@@ -364,7 +382,7 @@ export function materializeRoute({
}
const instance = resolveServiceInstance(serviceInstance);
const { definition } = instance;
- const [binding] = compatibleBindings(harness, instance);
+ const binding = firstCompatibleBinding(harness, instance);
if (!binding) {
throw serviceError('HARNESS_SERVICE_INCOMPATIBLE', `${harness.label} cannot be pointed at ${definition.label}.`);
}
@@ -386,21 +404,24 @@ export function materializeRoute({
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,
- });
+ switch (binding.baseUrl?.via) {
+ case 'env': envVars[binding.baseUrl.name] = baseUrl; break;
+ case 'opencodeConfig':
+ envVars.OPENCODE_CONFIG_CONTENT = opencodeProviderConfig({
+ namespace: opencodeNamespace(serviceConnectionKind(instance)), label: definition.label, baseUrl, builtin: binding.baseUrl.builtin === true,
+ });
+ break;
+ case 'piProvider': args.push(binding.baseUrl.flag, definition.piProvider); break;
+ default: break;
}
- 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;
+ // A binding that writes an endpoint also records it on the record: as
+ // `endpoint` for a program that reads that field, and beside an env var,
+ // inline config or provider name as every shipped wrapper sample does — the
+ // readiness probe and the catalog refresh read it off the record. A binding
+ // that writes none (the program signs in itself) records none.
+ const endpoint = !binding.baseUrl ? null
+ : binding.baseUrl.via === 'field' ? baseUrl : instance.transports.openai?.baseUrl ?? baseUrl;
+ if (endpoint) fields.endpoint = endpoint;
// --- credential ------------------------------------------------------------
const credential = binding.credential || null;
@@ -421,7 +442,6 @@ export function materializeRoute({
// --- 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}`,
@@ -431,16 +451,11 @@ export function materializeRoute({
serviceId: instance.slug,
servicePlan: instance.plan,
...fields,
- ...serviceMarkers(harness, definition),
- ...(recipe ? { command: recipe.command, timeout: recipe.timeout } : { timeout: API_ROUTE_TIMEOUT_MS }),
- ...modeFields,
- models: [],
+ ...serviceMarkers(definition, { wrapper: Boolean(recipe) }),
+ ...executableRecordTail({ recipe, mode: method, args, enabled: true, envVars, secretEnvVars }),
defaultModel: selection.model ?? null,
...(selection.effort ? { effort: selection.effort } : {}),
...tiers,
- enabled: true,
- envVars,
- secretEnvVars,
...overrides,
};
if (bootstrap && method !== 'api') {
diff --git a/server/lib/providerRouteRecipes.materialize.test.js b/server/lib/providerRouteRecipes.materialize.test.js
index 2b7ae042d5..f1336d9147 100644
--- a/server/lib/providerRouteRecipes.materialize.test.js
+++ b/server/lib/providerRouteRecipes.materialize.test.js
@@ -203,7 +203,7 @@ function serviceForSample(sample, profile, harness) {
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');
+ const subscription = harness.bindings.find((binding) => binding.service && !binding.env);
return subscription ? serviceDefinitionById(subscription.service) : null;
}
diff --git a/server/lib/serviceDefinitions.js b/server/lib/serviceDefinitions.js
index 1f9faf3f6f..3685498bf1 100644
--- a/server/lib/serviceDefinitions.js
+++ b/server/lib/serviceDefinitions.js
@@ -60,14 +60,13 @@ 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({
+const definition = ({ transports = {}, credential = {}, catalog, ...row }) => Object.freeze({
...row,
transports: Object.freeze(Object.fromEntries(
Object.entries(transports).map(([protocol, transport]) => [protocol, Object.freeze({ defaultBaseUrl: null, ...transport })]),
@@ -303,8 +302,9 @@ export const SERVICE_SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
* 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
+ * Accepts a definition id, an instance input, or an already-resolved instance
+ * (resolution is idempotent), so every consumer can take any of them. 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
@@ -315,14 +315,13 @@ export const SERVICE_SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
*
* @param {{definitionId?: string, definition?: ServiceDefinition, slug?: string, plan?: string,
* transports?: Record<string, {baseUrl?: string|null}>, credentials?: {apiKey?: string},
- * credential?: {via?: 'bootstrap'|'stored'}}|string} input
+ * credential?: {via?: 'bootstrap'|'stored'}, credentialVia?: '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 ?? ''}"`);
@@ -344,7 +343,7 @@ export function resolveServiceInstance(input) {
plan,
transports,
credentials: { ...(raw.credentials || {}) },
- credentialVia: raw.credential?.via === 'bootstrap' ? 'bootstrap' : 'stored',
+ credentialVia: raw.credentialVia === 'bootstrap' || raw.credential?.via === 'bootstrap' ? 'bootstrap' : 'stored',
};
}
diff --git a/server/lib/serviceDefinitions.test.js b/server/lib/serviceDefinitions.test.js
index 5eefea3a45..9e7aec04dc 100644
--- a/server/lib/serviceDefinitions.test.js
+++ b/server/lib/serviceDefinitions.test.js
@@ -110,7 +110,7 @@ describe('resolveServiceInstance', () => {
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);
+ expect(resolveServiceInstance(paid)).toEqual(paid);
});
// A local daemon's port is an install fact: the row declares the wire, and