Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: resolve composite provider ids (harness.method@service[+bootstrap]) through the toolkit and every run path, with per-harness enablement (#7564)
[._.]/ Adam Eivyd17184fc0674
diff --git a/docs/PROVIDER_COMPOSITION.md b/docs/PROVIDER_COMPOSITION.mdnew file mode 100644index 0000000000..7067648ad2--- /dev/null+++ b/docs/PROVIDER_COMPOSITION.md@@ -0,0 +1,62 @@+# Provider composition — composite ids++PortOS runs AI work on a **provider**. Until #7564 a provider was always a stored record in `data/providers.json` (a *preset*), one per (program × backend) combination. A **composite id** names a combination directly, from the parts that already exist, and every run path resolves it through the same lookup it resolves a preset today — so a `{ providerId, model, effort }` selection keeps its shape wherever it is stored.++```+<harness>.<method>@<service-slug>[+<bootstrap-slug>]++pi.tui@nvidia-nim-free Pi, driven in a PTY, against the "nvidia-nim-free" service instance+direct.api@ollama PortOS's own HTTP client against the local Ollama instance+opencode.cli@openrouter OpenCode headless, front-ending OpenRouter+claude.cli@anthropic+corp-auth Claude Code headless, credentialed at spawn by the "corp-auth" bootstrap app+```++| Part | Where it comes from | Grammar |+|---|---|---|+| `harness` | `PROVIDER_HARNESSES` in `server/lib/providerHarnesses.js` (`claude`, `opencode`, `codex`, `antigravity`, `cursor`, `grok`, `kimi`, `pi`, `direct`, …) | `[a-z0-9-]+` |+| `method` | one of the harness's `modes` | `cli` / `tui` / `api` |+| `service-slug` | an `ai_connections` row's `slug` (Settings › AI Providers › Services, `GET /api/providers/services`) | `[a-z0-9][a-z0-9-]*` |+| `bootstrap-slug` | a key of `settings.credentialBootstraps` | `[a-z0-9][a-z0-9-]*`, only with `cli` / `tui` |++A preset id is `^[a-z0-9][a-z0-9-]*$`; `.` and `@` are outside that alphabet, so the two grammars never collide and a composite can never shadow a stored record. The grammar lives in `server/lib/providerRef.js` (`parseProviderRef`, `formatCompositeId`) and is mirrored into the vendored toolkit at `server/lib/aiToolkit/internal/providerRef.js`.++## Resolution++`getProviderById(id)` on the toolkit's provider service answers a stored record when one exists. For a composite-shaped id it does not hold, it calls the host-injected `resolveCompositeProvider` (`server/services/compositeProviders.js`), which:++1. parses the id and looks up the harness row;+2. checks **harness enablement** — the user's explicit `settings.harnesses[id].enabled`, else whether the binary was detected on PATH by the runtime probe's cache (un-probed reads as enabled; `direct` is always enabled);+3. loads the **service instance** by slug (must be enabled and carry a definition), resolves its endpoints and the key it runs under;+4. checks the harness reaches that service (`isCompatible`) in that method;+5. resolves the bootstrap app for a `+suffix` (unknown slug → refused; a `bootstrap`-credentialed service with no suffix → refused);+6. materializes the record through `materializeRoute` — the same writer `POST /api/providers/bindings` uses — with the instance's plan-filtered catalog as `models` and its first entry as `defaultModel`.++The record is cached per (composite, service revision, settings revision) and **never persisted**: it does not appear in `providers.json`, in `GET /api/providers`, or in the management graph. A `field` credential is attached non-enumerably (the `attachGatewaySiblingKey` discipline) so a spread or JSON round-trip drops it; an env-borne key sits under a `secretEnvVars` name every client-facing sanitizer redacts.++An ineligible composite resolves to `null`, and the caller's existing "provider not found" path names it — a saved selection is never silently substituted. `GET /api/providers/composites/:id` returns the verdict with a `code` / `reason` (`harness-disabled`, `service-disabled`, `service-unknown`, `incompatible`, `bootstrap-unknown`, `SERVICE_CREDENTIAL_REQUIRED`, …) for a picker to show beside it. Re-enabling the harness or the service restores it with nothing to migrate.++## Where a composite is accepted++`providerRefSchema` (`server/lib/zodCompat.js`) accepts either grammar and is the schema of every **selection** field: CoS task metadata, task templates, orchestration roles, feature provider pins (`autofixer`, `calendarSync`, …), scheduled prompts, `POST /api/runs`, the pipeline `llm` field.++Three surfaces stay **preset-only** (`presetProviderIdSchema`) and answer a composite with a 400 naming the rule, because they key on the stored map: `PUT /api/providers/active`, a record's `fallbackProvider`, and an app's `taskTypeOverrides[].providerId`.++Fallback selection admits a composite only where a stored candidate would be admitted: the task-level fallback id is materialized into the candidate map, and the toolkit's `getFallbackProvider` applies the caller's `allowedModes` to it like any other row.++## Settings and endpoints++| Surface | Purpose |+|---|---|+| `settings.harnesses` | `{ [harnessId]: { enabled } }` — the user's explicit word per harness; validated on `PUT /api/settings` |+| `settings.credentialBootstraps` | `{ [slug]: { label, command, args?, argsSeparator?, setupCommand?, harnessNames? } }` — the wrapper CLIs a `+suffix` names; saving never spawns |+| `GET /api/providers/catalog` | Every axis a picker composes over: harnesses (with `enabled` / `detected` / `version`), services, bootstraps, `compatibility` (harness → service slugs), `effortLevels` per harness, `effortLevelsByModel`, and the sanitized presets — derived from cache and settings only |+| `GET/PUT /api/providers/harnesses[/:id]` | Read / flip enablement |+| `GET/PUT /api/providers/bootstraps` | Read / replace the bootstrap table |+| `GET /api/providers/composites/:id` | One composite's verdict and sanitized record |+| `GET /api/providers/readiness?providerId=<composite>` | Readiness for one composition |++`GET /api/providers` stays presets-only, so existing consumers are unaffected until the UI slices of the epic (#7561) land.++## Peers++`metadata.provider` crosses to a peer verbatim, as before. A peer with no service under that slug resolves the pin as unresolved through the existing reason path; no sync schema version changes.diff --git a/docs/README.md b/docs/README.mdindex 23553b216d..b814ab6362 100644--- a/docs/README.md+++ b/docs/README.md@@ -21,6 +21,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [INSTANCE_FEATURES.md](./INSTANCE_FEATURES.md) | Optional per-install features — registry, client-side nav gating, feature groups, reconcile-at-toggle || [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects || [QUOTA-BURN.md](./QUOTA-BURN.md) | Quota-burn automation — spending subscription-backed CLI quota before expiry |+| [PROVIDER_COMPOSITION.md](./PROVIDER_COMPOSITION.md) | Composite provider ids (`harness.method@service[+bootstrap]`): the grammar, per-harness enablement, bootstrap apps, how every run path resolves one, and the preset-only surfaces || [MODEL_ACCESS.md](./MODEL_ACCESS.md) | Scoping a provider to the models your plan entitles you to — free tiers, allow/deny globs, gateway inheritance || [MODEL-COMPARISON.md](./MODEL-COMPARISON.md) | Sourced provider/model/effort comparisons, cost estimates and CoS research refresh || [THREEJS_MODELS.md](./THREEJS_MODELS.md) | Three.js procedural 3D model generation and trust boundary |diff --git a/server/lib/README.md b/server/lib/README.mdindex b7f955d0cf..91e13f6e2b 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. |-| `providerServiceInstances.js` | A connection read as a SERVICE INSTANCE (#7563, epic #7561) — the pure bridge between `ai_connections` rows and `serviceDefinitions.js`. `definitionIdForKind` / `kindForDefinition` translate a row's `kind` (`ollama`, `gateway:<id>`, `api`, `vendor` + its binding's harness) to a definition id and back; `allocateServiceSlug` mints `base`, `base-2`, …; `serviceColumnsForConnection` / `planServiceColumnBackfill` are the boot-time backfill (slug, definition, first plan) the reconcile pass applies to rows that predate the columns — row-derived, idempotent, never a seed; `takenServiceSlugs` is the set every allocation avoids; `storedTransports` is the transports map a new instance's row stores; `applyServicePlanFilter` narrows a listing to a plan; `credentialSourceFor` reports where an instance's credential comes from (`settings`, `env-file`, `env`, `cli`, `config`, `none`, the inventory's own precedence) without a value; `toServiceDto` (`serviceDtoSchema`, the connection DTO extended, strict) is the sanitized `GET /api/providers/services` row with a one-word `readiness`. |+| `providerServiceInstances.js` | A connection read as a SERVICE INSTANCE (#7563, epic #7561) — the pure bridge between `ai_connections` rows and `serviceDefinitions.js`. `definitionIdForKind` / `kindForDefinition` translate a row's `kind` (`ollama`, `gateway:<id>`, `api`, `vendor` + its binding's harness) to a definition id and back; `allocateServiceSlug` mints `base`, `base-2`, …; `serviceColumnsForConnection` / `planServiceColumnBackfill` are the boot-time backfill (slug, definition, first plan) the reconcile pass applies to rows that predate the columns — row-derived, idempotent, never a seed; `takenServiceSlugs` is the set every allocation avoids; `storedTransports` is the transports map a new instance's row stores; `applyServicePlanFilter` narrows a listing to a plan; `credentialSourceFor` reports where an instance's credential comes from (`settings`, `env-file`, `env`, `cli`, `config`, `none`, the inventory's own precedence) without a value; `instanceApiKeyFor(connection, definition, env)` is the key it RUNS under (`stored` → the row, `env` → the definition's conventional variable, else none), shared by the catalog refresh and the composite resolver (#7564); `toServiceDto` (`serviceDtoSchema`, the connection DTO extended, strict) is the sanitized `GET /api/providers/services` row with a one-word `readiness`. || `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. |@@ -238,7 +238,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. `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.+| `providerRef.js` | Provider REFERENCE grammar (#7564, epic #7561) — the two spellings a `{ providerId, model, effort }` selection may name a provider by: a PRESET record id (`PRESET_ID_RE`, the slug `createProvider` mints) or a COMPOSITE `<harness>.<cli|tui|api>@<service-slug>[+<bootstrap-slug>]` (`COMPOSITE_ID_RE`; the bootstrap suffix only with a process method). `parseProviderRef(id)` → `{kind:'preset'}` / `{kind:'composite', harnessId, method, serviceSlug, bootstrapSlug}` / `null`, `isCompositeProviderId` / `isPresetProviderId`, `formatCompositeId(parts)` (throws on parts that would not parse back), `MAX_PROVIDER_REF_LENGTH`, and the two validation messages (`PROVIDER_REF_MESSAGE`, `PRESET_ONLY_MESSAGE`). The zod forms — `providerRefSchema` / `providerRefFieldSchema` (either grammar) and `presetProviderIdSchema` (preset-only, for `PUT /providers/active`, a record's `fallbackProvider`, an app's `taskTypeOverrides` pin) — live in `zodCompat.js` so `cosValidation.js` can share them. Pure and dependency-free; mirrored in `aiToolkit/internal/providerRef.js` (the toolkit may not import out) behind `providerRef.parity.test.js`. Resolution is host-side: `services/compositeProviders.js`. |+| `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. `materializeRouteOutcome(input)` is the same body as a VERDICT (`{ record }` or `{ error }` — the typed 400 without the throw) for the composite resolver (#7564), which reads a refusal as the reason to show beside a saved selection. `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. |@@ -641,7 +642,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant, ssh-alias-aware host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), `extraIssueLabels` / `formatForgeCategoryLabelFlags` (category + metric-slug labels + `plan` as repeated `--label` flags), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. || `eidoverseProxyRoutes.js` | Allowlist + path helpers for the same-origin Eidoverse reverse-proxy on `:5555` (`/eidoverse-host` prefix strip and root routes like `/ws` / `/version` while the host is active). Shared by `services/eidoverseProxy.js` so the main server and the optional `:5563` bridge stay in sync with eidoverse-worlds `server/routes.ts`. || `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `isWithinAllowedRoots(realPath)` is the single complete test — on Windows it also allows any lettered non-system drive (`D:\code`), which appears in no root, so never render `ALLOWED_WORKSPACE_ROOTS` as "the directories you may use". `outsideAllowedRootsMessage(realPath, { field })` formats a redacted server-only diagnostic with the rejected realpath and every checked root. Also `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, split on the platform path delimiter — `;` on Windows — and symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Defaults cover home plus wherever the platform mounts secondary volumes: `/tmp` + `/Users` + `/Volumes` + `/mnt` + `/media` + `/opt` on POSIX; home + the temp dir plus the non-system-drive rule on Windows, where those POSIX literals would resolve to whatever drive the process happens to be on. Used by `routes/commands.js`, `routes/scaffold.js`, and `routes/git.js` (always scoped) and `routes/detect.js` (scoped only when configured). |-| `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |+| `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. Also home to the provider-reference zod forms (#7564) — `providerRefSchema` / `providerRefFieldSchema` (a preset id OR a composite `harness.method@service[+bootstrap]`, per `providerRef.js`) and `presetProviderIdSchema` (preset-only) — because `cosValidation.js` needs them and must not import validation.js. |## Test supportdiff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex b6cb7c1b1f..8c0cc2c5e1 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -70,7 +70,9 @@ export function createAIToolkit(config = {}) {// Host probe for the checkpoints a one-model-per-process local runtime has// cached but is not serving — see createProviderService(). Unset// standalone, so a refresh reports only what the endpoint answers with.- cachedModelIds = null+ cachedModelIds = null,+ // Host resolver for composite provider ids — see createProviderService().+ resolveCompositeProvider = null} = config;const providerService = createProviderService({@@ -78,7 +80,8 @@ export function createAIToolkit(config = {}) {providersFile,sampleFile: sampleProvidersFile,onProvidersSaved,- cachedModelIds+ cachedModelIds,+ resolveCompositeProvider});let providerStatusService = null;diff --git a/server/lib/aiToolkit/internal/providerRef.js b/server/lib/aiToolkit/internal/providerRef.jsnew file mode 100644index 0000000000..3099a04265--- /dev/null+++ b/server/lib/aiToolkit/internal/providerRef.js@@ -0,0 +1,43 @@+/**+ * The composite provider-id grammar (`<harness>.<method>@<service-slug>+ * [+<bootstrap-slug>]`, #7564) as the toolkit needs it: enough to tell a+ * composite reference from a preset record id, so `getProviderById` knows when+ * to hand a lookup to the host's resolver and `runSchema.providerId` accepts+ * either spelling.+ *+ * A DELIBERATE MIRROR of `server/lib/providerRef.js`. This directory is+ * vendored and stays self-contained — no imports out to other PortOS modules+ * (see `aiToolkit/AGENTS.md`) — so the rule is duplicated rather than imported,+ * exactly as `gateways.js` and `harnesses.js` are. `server/lib/providerRef.parity.test.js`+ * fails when the two drift.+ *+ * Imports nothing.+ */++/** A preset record id — the slug `createProvider` assigns. */+export const PRESET_ID_RE = /^[a-z0-9][a-z0-9-]*$/;++/** `<harness>.<method>@<service-slug>[+<bootstrap-slug>]`. */+export const COMPOSITE_ID_RE = /^([a-z0-9-]+)\.(cli|tui|api)@([a-z0-9][a-z0-9-]*)(?:\+([a-z0-9][a-z0-9-]*))?$/;++/** Longest reference any selection field accepts. */+export const MAX_PROVIDER_REF_LENGTH = 200;++/**+ * @param {unknown} id+ * @returns {{kind: 'preset', id: string}+ * | {kind: 'composite', id: string, harnessId: string, method: string, serviceSlug: string, bootstrapSlug: string|null}+ * | null}+ */+export function parseProviderRef(id) {+ if (typeof id !== 'string' || id.length === 0 || id.length > MAX_PROVIDER_REF_LENGTH) return null;+ if (PRESET_ID_RE.test(id)) return { kind: 'preset', id };+ const match = COMPOSITE_ID_RE.exec(id);+ if (!match) return null;+ const [, harnessId, method, serviceSlug, bootstrapSlug = null] = match;+ if (bootstrapSlug && method === 'api') return null;+ return { kind: 'composite', id, harnessId, method, serviceSlug, bootstrapSlug };+}++/** Whether `id` is a well-formed composite reference. */+export const isCompositeProviderId = (id) => parseProviderRef(id)?.kind === 'composite';diff --git a/server/lib/aiToolkit/providers.composite.test.js b/server/lib/aiToolkit/providers.composite.test.jsnew file mode 100644index 0000000000..a3b2e0e2a4--- /dev/null+++ b/server/lib/aiToolkit/providers.composite.test.js@@ -0,0 +1,53 @@+/**+ * `getProviderById` and the host's composite resolver (#7564): a stored record+ * always wins, only a composite-shaped id that the map does not hold reaches+ * the hook, and a toolkit built without the hook answers exactly as before.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createProviderService } from './providers.js';++let dataDir;+beforeEach(async () => {+ dataDir = await mkdtemp(join(tmpdir(), 'portos-providers-composite-'));+ await writeFile(join(dataDir, 'providers.json'), JSON.stringify({+ activeProvider: 'claude-code',+ providers: { 'claude-code': { id: 'claude-code', name: 'Claude', type: 'cli', command: 'claude', enabled: true, models: [] } },+ }));+});+afterEach(() => rm(dataDir, { recursive: true, force: true }));++describe('createProviderService({ resolveCompositeProvider })', () => {+ it('hands only an unstored composite id to the resolver, and never a preset lookup', async () => {+ const materialized = { id: 'pi.tui@nvidia-nim', type: 'tui', command: 'pi', enabled: true };+ const resolveCompositeProvider = vi.fn(async (id) => (id === 'pi.tui@nvidia-nim' ? materialized : null));+ const service = createProviderService({ dataDir, resolveCompositeProvider });++ await expect(service.getProviderById('claude-code')).resolves.toMatchObject({ id: 'claude-code' });+ await expect(service.getProviderById('no-such-preset')).resolves.toBeNull();+ expect(resolveCompositeProvider).not.toHaveBeenCalled();++ await expect(service.getProviderById('pi.tui@nvidia-nim')).resolves.toBe(materialized);+ await expect(service.getProviderById('claude.cli@nowhere')).resolves.toBeNull();+ expect(resolveCompositeProvider.mock.calls.map(([id]) => id)).toEqual(['pi.tui@nvidia-nim', 'claude.cli@nowhere']);+ // Malformed references never reach the host: the grammar is the gate.+ await expect(service.getProviderById('pi.gui@x')).resolves.toBeNull();+ await expect(service.getProviderById('direct.api@ollama+corp-auth')).resolves.toBeNull();+ expect(resolveCompositeProvider).toHaveBeenCalledTimes(2);+ });++ it('keeps the stored map authoritative: a composite never appears in the list, and cannot become active', async () => {+ const service = createProviderService({ dataDir, resolveCompositeProvider: async () => ({ id: 'pi.tui@nvidia-nim', type: 'tui' }) });+ const { providers } = await service.getAllProviders();+ expect(providers.map((p) => p.id)).toEqual(['claude-code']);+ await expect(service.setActiveProvider('pi.tui@nvidia-nim')).resolves.toBeNull();+ expect((await service.getActiveProvider()).id).toBe('claude-code');+ });++ it('answers as before with no resolver configured', async () => {+ const service = createProviderService({ dataDir });+ await expect(service.getProviderById('pi.tui@nvidia-nim')).resolves.toBeNull();+ });+});diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex a02340c2df..f902176b03 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -27,6 +27,7 @@ import { gatewayForProvider, isGatewayBackedProvider } from './internal/gatewaysimport { canRefreshModels, ollamaRefreshGroupKey, resolveModelFetcher } from './internal/modelFetchers.js';import { modelCatalogUpdate, modelContextWindowPatch, parseModelCatalog, toModelCatalog } from './internal/modelCatalog.js';import { normalizeModelAccess } from './internal/modelAccess.js';+import { isCompositeProviderId } from './internal/providerRef.js';// Re-exported (rather than defined here) so the model-fetcher table can key its// ollama row on the same predicate without importing back into this module.@@ -537,7 +538,16 @@ export function createProviderService(config = {}) {// because reading a cache means host I/O and this directory stays// self-contained (see AGENTS.md); PortOS supplies MTPLX's `mtplx models// --json` listing from `services/mtplxServerManager.js`.- cachedModelIds = null+ cachedModelIds = null,+ // Host resolver for a COMPOSITE provider id (`harness.method@service+ // [+bootstrap]`, #7564): `(id) => Promise<object|null>`, returning an+ // executable record materialized from the host's harness registry, service+ // instances and settings — never a stored one. Consulted by `getProviderById`+ // only for an id the composite grammar recognizes and the stored map does+ // not hold, so a preset lookup is byte-identical to before and a composite+ // can never shadow a record. Injected rather than imported because the+ // registries live host-side (see AGENTS.md). Unset standalone.+ resolveCompositeProvider = null} = config;const PROVIDERS_PATH = join(dataDir, providersFile);@@ -822,7 +832,9 @@ export function createProviderService(config = {}) {async getProviderById(id) {const data = await loadProviders();- return readProvider(data.providers[id], data.providers);+ const stored = readProvider(data.providers[id], data.providers);+ if (stored || typeof resolveCompositeProvider !== 'function' || !isCompositeProviderId(id)) return stored;+ return (await resolveCompositeProvider(id)) ?? null;},async getActiveProvider() {diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 8d11ef7583..fee3738961 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -2,6 +2,20 @@ import { z } from 'zod';import { MAX_MODEL_ACCESS_PATTERNS, MAX_MODEL_ACCESS_PATTERN_LENGTH, MODEL_ACCESS_MODES } from './internal/modelAccess.js';import { basename, extname } from 'path';import { MAX_TIMEOUT, MIN_TIMEOUT } from './constants.js';+import { MAX_PROVIDER_REF_LENGTH, PRESET_ID_RE, parseProviderRef } from './internal/providerRef.js';++// The preset-only rule, named once so every surface that refuses a composite+// (`harness.method@service`, #7564) says the same thing: the active provider,+// a record's fallback, and anything else keyed on `providers.json`.+const PRESET_ONLY_MESSAGE = 'must be a preset provider id (lowercase alphanumeric with hyphens); a composite harness.method@service selection is not accepted here';++/**+ * A run's provider selection: a preset record id or a composite reference the+ * host resolves through `resolveCompositeProvider` (#7564). Mirrors the host's+ * `providerRefSchema` (`server/lib/zodCompat.js`) over the vendored grammar.+ */+export const providerRefSchema = z.string().trim().min(1).max(MAX_PROVIDER_REF_LENGTH)+ .refine((value) => parseProviderRef(value) !== null, 'providerId must be a preset id or a composite <harness>.<cli|tui|api>@<service-slug>[+<bootstrap-slug>]');// Image extensions a vision screenshot may carry. Mirrors the runner's// getMimeType keys — anything else (or a no-extension path like `passwd`) is@@ -98,7 +112,9 @@ export const providerSchema = z.object({mediumModel: z.string().nullable().optional(),heavyModel: z.string().nullable().optional(),ultraModel: z.string().nullable().optional(),- fallbackProvider: z.string().nullable().optional(),+ // PRESET-ONLY: the fallback chain reads `providers[fallbackProvider]` off the+ // stored map, where a composite never exists (#7564).+ fallbackProvider: z.string().regex(PRESET_ID_RE, PRESET_ONLY_MESSAGE).max(80).nullable().optional(),// Model to run on the fallback provider. The UI sends '' when no model is// pinned (fall back to the fallback provider's own default), so allow empty.fallbackModel: z.string().nullable().optional(),@@ -292,14 +308,14 @@ export const providerCreateSchema = providerSchema.extend({// setActiveProvider (which walks the prototype chain and would otherwise treat// `__proto__` as an existing provider and persist it as active).export const providerActiveSchema = z.object({- id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, 'id must be lowercase alphanumeric with hyphens').max(80)+ id: z.string().regex(PRESET_ID_RE, PRESET_ONLY_MESSAGE).max(80)});export const runSchema = z.object({// `type` defaults to 'ai' so the common case (AI run via /api/runs from// RunnerPage / AIProviders / etc.) doesn't have to send it explicitly.type: z.enum(['ai', 'command']).optional().default('ai'),- providerId: z.string().optional(),+ providerId: providerRefSchema.optional(),model: z.string().optional(),workspacePath: z.string().optional(),workspaceName: z.string().optional(),diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 66d842b5ce..8aa7047540 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -9,7 +9,7 @@* (flat); the barrel surfaces it as the `cosValidation` namespace.*/import { z } from 'zod';-import { emptyToUndefined, emptyToNull } from './zodCompat.js';+import { emptyToUndefined, emptyToNull, providerRefFieldSchema, providerRefSchema } from './zodCompat.js';import { isPlainObject } from './objects.js';import { EFFORT_LEVELS } from './providerModels.js';import { isValidSlashdoCommand } from './slashdoInvocation.js';@@ -138,7 +138,7 @@ const claimOverrideContextSchema = z.preprocess(// on update ''/null survives as null so the store can clear the pin// (absent-vs-cleared, AGENTS.md).const orchestrationRoleSchema = z.object({- provider: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(120).optional()),+ provider: z.preprocess(emptyToUndefined, providerRefSchema.optional()),model: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(300).optional()),// Per-role reasoning effort. The architect's own rung for its planning pass;// for the implementer it is the DEFAULT a spec's `REASONING:` line overrides.@@ -200,7 +200,7 @@ export const createCosTaskSchema = z.object({context: z.string().optional(),prompt: z.string().optional(),model: z.string().optional(),- provider: z.string().optional(),+ provider: providerRefFieldSchema.optional(),effort: effortInputSchema,orchestrationMode: orchestrationModeInputSchema,orchestrationProfile: orchestrationProfileSchema.optional(),@@ -339,7 +339,7 @@ export const updateCosTaskSchema = z.object({context: z.string().optional(),prompt: z.string().optional(),model: z.string().optional(),- provider: z.string().optional(),+ provider: providerRefFieldSchema.optional(),effort: effortUpdateSchema,orchestrationMode: orchestrationModeUpdateSchema,orchestrationProfile: orchestrationProfileSchema.nullable().optional(),@@ -592,7 +592,7 @@ export const createTaskTemplateSchema = z.object({icon: z.string().max(16).optional(),context: z.string().max(4000).optional(),category: z.string().max(60).optional(),- provider: z.string().max(120).optional(),+ provider: providerRefFieldSchema.optional(),model: z.string().max(200).optional(),effort: z.preprocess(emptyToUndefined, z.enum(EFFORT_LEVELS).optional()),app: z.string().max(200).optional(),@@ -609,7 +609,7 @@ export const taskTemplateFromTaskSchema = z.object({task: z.object({description: z.string().min(1).max(4000),context: z.string().max(4000).optional(),- provider: z.string().max(120).optional(),+ provider: providerRefFieldSchema.optional(),model: z.string().max(200).optional(),effort: z.preprocess(emptyToUndefined, z.enum(EFFORT_LEVELS).optional()),app: z.string().max(200).optional(),diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 38af4c7528..2857cd960b 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -684,7 +684,17 @@ describe('deferred imports stay deferred (#6156)', () => {// 111,500 → 111,700 (#7563): `routes/providers.js` gained `providerServices.js`// and `providerGraph.js` gained `providerServiceInstances.js`, each one file// deep, plus two new suites.-const MAX_STATIC_INSTANTIATIONS = 111700;+// 111,700 → 112,900 (#7564): the composite provider-id grammar is ONE+// dependency-free leaf (`lib/providerRef.js`) reached through `zodCompat.js`+// by every suite that validates a selection field, and its mirror+// (`aiToolkit/internal/providerRef.js`) by every suite that reaches the+// toolkit's provider service or validation — one node each on ~700 closures,+// no subtree. The resolver itself (`services/compositeProviders.js`) is+// reached only by `await import()` from the run paths and the routes, so its+// graph-store closure stays off every suite that does not test it. Measured+// after the change: 112,576, with five new suites; the ceiling keeps the same+// ~300 of headroom the previous number carried.+const MAX_STATIC_INSTANTIATIONS = 112900;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex 36db407af1..4d6110ee68 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -491,6 +491,7 @@ export * from './providerGraphRecords.js';export * from './providerServiceInstances.js';export * from './providerModelAliases.js';export * from './providerModePairing.js';+export * from './providerRef.js';export * from './providerRouteRecipes.js';export * from './serviceDefinitions.js';export * from './providerRouteSettings.js';diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 07bc7b18a7..308187f76e 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -526,6 +526,11 @@ export function foldCursorEffortIntoModel(model, effort) {*/export function effortLevelsForProvider(provider, model = null) {if (!provider) return null;+ // A record materialized from a composite id carries its harness by name+ // (#7564); read it before sniffing the command, which a bootstrap-wrapped+ // spawn or a path-configured binary can obscure.+ const byHarness = effortLevelsForHarness(provider.harnessId, provider, model);+ if (byHarness !== undefined) return byHarness;if (isOpencodeLocalProvider(provider)) return OPENCODE_LOCAL_EFFORT_LEVELS;if (isCodexProvider(provider)) return codexEffortLevelsForModel(model);if (isAntigravityProvider(provider)) {@@ -533,13 +538,40 @@ export function effortLevelsForProvider(provider, model = null) {if (perModel === null) return ANTIGRAVITY_EFFORT_LEVELS;return perModel.length ? perModel : null;}- if (commandBasename(provider.command) === 'pi') return ['low', 'medium', 'high', 'xhigh', 'max'];+ if (commandBasename(provider.command) === 'pi') return PI_EFFORT_LEVELS;if (isCursorProvider(provider)) return CURSOR_EFFORT_LEVELS;if (isGrokProvider(provider)) return GROK_EFFORT_LEVELS;if (isClaudeProvider(provider)) return CLAUDE_EFFORT_LEVELS;return null;}+/** Pi's reasoning ladder (`pi --effort`), shared by the harness table and command sniffing. */+const PI_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);++/**+ * The effort ladder a HARNESS id names, or `undefined` when the id is absent+ * or names no harness this table knows — the signal for+ * {@link effortLevelsForProvider} to fall through to command sniffing.+ * `null` is a real answer ("this harness takes no effort flag").+ */+function effortLevelsForHarness(harnessId, provider, model) {+ switch (harnessId) {+ case 'claude': return CLAUDE_EFFORT_LEVELS;+ case 'codex': return codexEffortLevelsForModel(model);+ case 'antigravity': {+ const perModel = model ? antigravityModelEffortLevels(model, provider?.models) : null;+ if (perModel === null) return ANTIGRAVITY_EFFORT_LEVELS;+ return perModel.length ? perModel : null;+ }+ case 'pi': return PI_EFFORT_LEVELS;+ case 'cursor': return CURSOR_EFFORT_LEVELS;+ case 'grok': return GROK_EFFORT_LEVELS;+ case 'opencode': return isOpencodeLocalProvider(provider) ? OPENCODE_LOCAL_EFFORT_LEVELS : null;+ case 'direct': case 'kimi': case 'kilo': case 'openchamber': return null;+ default: return undefined;+ }+}+// Every effort value any CLI accepts, ordered weakest→strongest. The clamp// below walks this so an effort saved against one provider survives a switch to// a provider with a narrower ladder (agy tops out at `high`; claude has nodiff --git a/server/lib/providerRef.js b/server/lib/providerRef.jsnew file mode 100644index 0000000000..b935413a61--- /dev/null+++ b/server/lib/providerRef.js@@ -0,0 +1,84 @@+/**+ * Provider REFERENCE grammar (#7564, epic #7561): the two spellings a+ * `{ providerId, model, effort }` selection may name a provider by.+ *+ * - a PRESET id — a `data/providers.json` record: `^[a-z0-9][a-z0-9-]*$`+ * (the same slug `aiToolkit/validation.js#providerSchema.id` mints);+ * - a COMPOSITE id — `<harness>.<method>@<service-slug>[+<bootstrap-slug>]`,+ * e.g. `pi.tui@nvidia-nim-free`, `direct.api@ollama`,+ * `claude.cli@anthropic+corp-auth`: an enabled harness driven in one of its+ * execution methods against an enabled service instance, materialized at+ * resolve time and never persisted as a record.+ *+ * The two grammars cannot collide: `.` and `@` are outside the preset+ * alphabet, so a composite is recognizable from the string alone and a preset+ * lookup can never accidentally read one. The `+<bootstrap-slug>` suffix names+ * a credential-bootstrap app (`settings.credentialBootstraps`) and is legal+ * only with a process method (`cli` / `tui`): a direct API call has no spawn+ * for a wrapper to sit in front of.+ *+ * Pure and dependency-free so both the browser and the vendored toolkit+ * (`aiToolkit/internal/providerRef.js`, a deliberate mirror behind+ * `providerRef.parity.test.js`) can carry the same rule.+ */++/** A preset record id — the slug `createProvider` assigns. */+export const PRESET_ID_RE = /^[a-z0-9][a-z0-9-]*$/;++/** The execution methods a composite may name; mirrors a record's `type`. */+export const COMPOSITE_METHODS = Object.freeze(['cli', 'tui', 'api']);++/**+ * `<harness>.<method>@<service-slug>[+<bootstrap-slug>]`. Groups: harness id,+ * method, service slug, optional bootstrap slug.+ */+export const COMPOSITE_ID_RE = /^([a-z0-9-]+)\.(cli|tui|api)@([a-z0-9][a-z0-9-]*)(?:\+([a-z0-9][a-z0-9-]*))?$/;++/** Longest reference any selection field accepts. */+export const MAX_PROVIDER_REF_LENGTH = 200;++/** The validation message a selection field reports for a malformed reference. */+export const PROVIDER_REF_MESSAGE = 'provider must be a preset id (lowercase alphanumeric with hyphens) or a composite <harness>.<cli|tui|api>@<service-slug>[+<bootstrap-slug>] (the bootstrap suffix only with cli or tui)';++/** The message a PRESET-ONLY field reports when handed a composite. */+export const PRESET_ONLY_MESSAGE = 'must be a preset provider id (lowercase alphanumeric with hyphens); a composite harness.method@service selection is not accepted here';++/**+ * Parse a provider reference.+ *+ * @param {unknown} id+ * @returns {{kind: 'preset', id: string}+ * | {kind: 'composite', id: string, harnessId: string, method: 'cli'|'tui'|'api', serviceSlug: string, bootstrapSlug: string|null}+ * | null} `null` for anything that is neither grammar — including a+ * bootstrap suffix on the `api` method.+ */+export function parseProviderRef(id) {+ if (typeof id !== 'string' || id.length === 0 || id.length > MAX_PROVIDER_REF_LENGTH) return null;+ if (PRESET_ID_RE.test(id)) return { kind: 'preset', id };+ const match = COMPOSITE_ID_RE.exec(id);+ if (!match) return null;+ const [, harnessId, method, serviceSlug, bootstrapSlug = null] = match;+ if (bootstrapSlug && method === 'api') return null;+ return { kind: 'composite', id, harnessId, method, serviceSlug, bootstrapSlug };+}++/** Whether `id` is a well-formed composite reference. */+export const isCompositeProviderId = (id) => parseProviderRef(id)?.kind === 'composite';++/** Whether `id` is a well-formed preset record id. */+export const isPresetProviderId = (id) => parseProviderRef(id)?.kind === 'preset';++/**+ * The composite id for its parts. Throws on parts that do not form a valid+ * reference, so a caller can never mint an id `parseProviderRef` rejects.+ *+ * @param {{harnessId: string, method: string, serviceSlug: string, bootstrapSlug?: string|null}} parts+ * @returns {string}+ */+export function formatCompositeId({ harnessId, method, serviceSlug, bootstrapSlug = null }) {+ const id = `${harnessId}.${method}@${serviceSlug}${bootstrapSlug ? `+${bootstrapSlug}` : ''}`;+ if (parseProviderRef(id)?.kind !== 'composite') {+ throw new Error(`"${id}" is not a composite provider id`);+ }+ return id;+}diff --git a/server/lib/providerRef.parity.test.js b/server/lib/providerRef.parity.test.jsnew file mode 100644index 0000000000..af43612c6a--- /dev/null+++ b/server/lib/providerRef.parity.test.js@@ -0,0 +1,28 @@+/**+ * The composite provider-id grammar exists in two places by architecture — the+ * vendored `aiToolkit/` may not import out of its own directory, so it carries+ * its own copy. This pins the two together, as the gateway and harness parity+ * suites do, so the toolkit can never read a reference differently from the+ * host that resolves it.+ */+import { describe, expect, it } from 'vitest';+import * as server from './providerRef.js';+import * as toolkit from './aiToolkit/internal/providerRef.js';++const SAMPLES = [+ 'claude-code', 'pi.tui@nvidia-nim-free', 'direct.api@ollama', 'claude.cli@anthropic+corp-auth',+ 'pi.tui@Nvidia', 'pi.tui@', 'pi.gui@x', 'direct.api@ollama+corp-auth', '', 'x'.repeat(201),+];++describe('providerRef ↔ aiToolkit/internal/providerRef parity', () => {+ it('compiles the same regexes and length bound', () => {+ expect(toolkit.PRESET_ID_RE.source).toBe(server.PRESET_ID_RE.source);+ expect(toolkit.COMPOSITE_ID_RE.source).toBe(server.COMPOSITE_ID_RE.source);+ expect(toolkit.MAX_PROVIDER_REF_LENGTH).toBe(server.MAX_PROVIDER_REF_LENGTH);+ });++ it.each(SAMPLES)('parses %j identically', (id) => {+ expect(toolkit.parseProviderRef(id)).toEqual(server.parseProviderRef(id));+ expect(toolkit.isCompositeProviderId(id)).toBe(server.isCompositeProviderId(id));+ });+});diff --git a/server/lib/providerRef.test.js b/server/lib/providerRef.test.jsnew file mode 100644index 0000000000..b609a17c02--- /dev/null+++ b/server/lib/providerRef.test.js@@ -0,0 +1,78 @@+/**+ * The provider-reference grammar (#7564): which strings name a preset, which+ * name a composite, and which name nothing — pinned on the exact examples the+ * epic's acceptance criteria list, plus the boundary the two grammars share.+ */+import { describe, expect, it } from 'vitest';+import {+ COMPOSITE_ID_RE,+ MAX_PROVIDER_REF_LENGTH,+ PRESET_ID_RE,+ formatCompositeId,+ isCompositeProviderId,+ isPresetProviderId,+ parseProviderRef,+} from './providerRef.js';++describe('parseProviderRef', () => {+ it('reads a preset record id', () => {+ expect(parseProviderRef('claude-code')).toEqual({ kind: 'preset', id: 'claude-code' });+ expect(isPresetProviderId('codex-configured-default')).toBe(true);+ expect(isCompositeProviderId('claude-code')).toBe(false);+ });++ it('reads every composite part, with the bootstrap suffix optional', () => {+ expect(parseProviderRef('pi.tui@nvidia-nim-free')).toEqual({+ kind: 'composite', id: 'pi.tui@nvidia-nim-free', harnessId: 'pi', method: 'tui', serviceSlug: 'nvidia-nim-free', bootstrapSlug: null,+ });+ expect(parseProviderRef('claude.cli@anthropic+corp-auth')).toEqual({+ kind: 'composite', id: 'claude.cli@anthropic+corp-auth', harnessId: 'claude', method: 'cli', serviceSlug: 'anthropic', bootstrapSlug: 'corp-auth',+ });+ expect(parseProviderRef('direct.api@ollama')).toMatchObject({ kind: 'composite', harnessId: 'direct', method: 'api', serviceSlug: 'ollama' });+ expect(isCompositeProviderId('opencode.cli@openrouter')).toBe(true);+ });++ it.each([+ ['pi.tui@Nvidia', 'an uppercase service slug'],+ ['pi.tui@', 'an empty service slug'],+ ['pi.gui@x', 'a method that is not cli/tui/api'],+ ['direct.api@ollama+corp-auth', 'a bootstrap suffix on the api method'],+ ['pi.tui@-nvidia', 'a slug starting with a hyphen'],+ ['pi@nvidia', 'no method'],+ ['.tui@nvidia', 'no harness'],+ ['Claude-Code', 'an uppercase preset'],+ ['', 'an empty string'],+ ['__proto__', 'a prototype key'],+ ['a'.repeat(MAX_PROVIDER_REF_LENGTH + 1), 'an over-long reference'],+ ])('rejects %s (%s)', (id) => {+ expect(parseProviderRef(id)).toBeNull();+ expect(isCompositeProviderId(id)).toBe(false);+ expect(isPresetProviderId(id)).toBe(false);+ });++ it('never reads a non-string', () => {+ for (const value of [null, undefined, 42, {}, ['pi.tui@nvidia-nim']]) expect(parseProviderRef(value)).toBeNull();+ });++ it('keeps the two grammars disjoint: no string matches both', () => {+ for (const id of ['claude-code', 'pi.tui@nvidia-nim', 'direct.api@ollama', 'claude.cli@anthropic+corp-auth']) {+ expect(PRESET_ID_RE.test(id)).not.toBe(COMPOSITE_ID_RE.test(id));+ }+ });+});++describe('formatCompositeId', () => {+ it('round-trips through parseProviderRef', () => {+ const parts = { harnessId: 'opencode', method: 'cli', serviceSlug: 'openrouter-free', bootstrapSlug: 'corp-auth' };+ const id = formatCompositeId(parts);+ expect(id).toBe('opencode.cli@openrouter-free+corp-auth');+ expect(parseProviderRef(id)).toEqual({ kind: 'composite', id, ...parts });+ expect(formatCompositeId({ harnessId: 'direct', method: 'api', serviceSlug: 'ollama' })).toBe('direct.api@ollama');+ });++ it('refuses parts that would not parse back', () => {+ expect(() => formatCompositeId({ harnessId: 'direct', method: 'api', serviceSlug: 'ollama', bootstrapSlug: 'x' })).toThrow(/not a composite/);+ expect(() => formatCompositeId({ harnessId: 'pi', method: 'gui', serviceSlug: 'x' })).toThrow(/not a composite/);+ expect(() => formatCompositeId({ harnessId: 'pi', method: 'tui', serviceSlug: 'Nvidia' })).toThrow(/not a composite/);+ });+});diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.jsindex aed3cf834a..63ee94fce6 100644--- a/server/lib/providerRouteRecipes.js+++ b/server/lib/providerRouteRecipes.js@@ -372,22 +372,38 @@ const serviceConnectionKind = ({ definition, slug }) =>* overrides?: object, providerId?: string, name?: string}} input* @returns {object} the record to hand `createProvider`*/-export function materializeRoute({+export function materializeRoute(input) {+ const { record, error } = materializeRouteOutcome(input);+ if (error) throw error;+ return record;+}++/**+ * {@link materializeRoute} as a VERDICT: `{ record }` when the composition is+ * runnable, `{ error }` (the same typed 400) when it is not. The composite+ * resolver (#7564) reads refusals as reasons to show beside a saved selection,+ * so it needs the answer without a throw; the create endpoint keeps the+ * throwing form. One body, two shapes.+ *+ * @returns {{record: object, error: null}|{record: null, error: Error & {code: string, status: 400}}}+ */+export function materializeRouteOutcome({harness: harnessInput, method, serviceInstance, bootstrap = null, selection = {}, overrides = {}, providerId, name,}) {+ const refuse = (code, message) => ({ record: null, error: serviceError(code, message) });const harness = typeof harnessInput === 'string' ? harnessById(harnessInput) : harnessInput;- if (!harness) throw serviceError('HARNESS_UNKNOWN', `No harness "${harnessInput ?? ''}"`);+ if (!harness) return refuse('HARNESS_UNKNOWN', `No harness "${harnessInput ?? ''}"`);if (!harness.modes.includes(method)) {- throw serviceError('HARNESS_METHOD_UNSUPPORTED', `${harness.label} has no ${method} mode.`);+ return refuse('HARNESS_METHOD_UNSUPPORTED', `${harness.label} has no ${method} mode.`);}const instance = resolveServiceInstance(serviceInstance);const { definition } = instance;const binding = firstCompatibleBinding(harness, instance);if (!binding) {- throw serviceError('HARNESS_SERVICE_INCOMPATIBLE', `${harness.label} cannot be pointed at ${definition.label}.`);+ return refuse('HARNESS_SERVICE_INCOMPATIBLE', `${harness.label} cannot be pointed at ${definition.label}.`);}if (instance.credentialVia === 'bootstrap' && method !== 'api' && !bootstrap) {- throw serviceError('SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED',+ return refuse('SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED',`${definition.label} is credentialed by a bootstrap CLI at spawn; name the bootstrap app to compose this route.`);}@@ -402,7 +418,7 @@ export function materializeRoute({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.`);+ return refuse('SERVICE_ENDPOINT_REQUIRED', `${definition.label} declares no ${protocol} endpoint; set its base URL first.`);}switch (binding.baseUrl?.via) {case 'env': envVars[binding.baseUrl.name] = baseUrl; break;@@ -437,7 +453,7 @@ export function materializeRoute({: credentialVia === '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',+ return refuse('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 (credentialVia === 'field') fields.apiKey = apiKey;@@ -475,7 +491,7 @@ export function materializeRoute({...(bootstrap.argsSeparator ? { argsSeparator: bootstrap.argsSeparator } : {}),};}- return record;+ return { record, error: null };}/**diff --git a/server/lib/providerServiceInstances.js b/server/lib/providerServiceInstances.jsindex f7dff1e3d9..2796866604 100644--- a/server/lib/providerServiceInstances.js+++ b/server/lib/providerServiceInstances.js@@ -1,5 +1,6 @@import { z } from 'zod';import { harnessById } from './providerHarnesses.js';+import { CONNECTION_CREDENTIAL_ENV_VARS } from './providerConnections.js';import { connectionDtoSchema, connectionHasCredentials, toConnectionDto } from './providerGraphRecords.js';import { isNonBlankStr } from './textUtils.js';import {@@ -78,6 +79,32 @@ export function kindForDefinition(definition) {return 'api';}+/**+ * The key an instance runs under, or `''`. A `stored` instance holds it on the+ * row (under `apiKey`, or under the env var name a route-derived row kept); an+ * `env` one reads the definition's conventional variable from the process; a+ * `cli-login` or `bootstrap` instance holds none — the program signs in, or the+ * launch wrapper supplies it.+ *+ * @param {{credentialVia?: string, credentials?: object}} connection+ * @param {{credential: {envVars: readonly string[]}}} definition+ * @param {Record<string, string|undefined>} env+ */+export function instanceApiKeyFor(connection, definition, env) {+ const firstNamed = (bag, names) => names.map((name) => bag?.[name]).find(isNonBlankStr) ?? '';+ const via = connection.credentialVia ?? 'stored';+ if (via === 'env') return firstNamed(env, definition.credential.envVars);+ if (via !== 'stored') return '';+ const stored = connection.credentials || {};+ if (isNonBlankStr(stored.apiKey)) return stored.apiKey;+ // A route-derived row keeps its key under the env var the record carried+ // (`ANTHROPIC_AUTH_TOKEN` on a Claude-Ollama import), which a local daemon's+ // definition names no conventional variable for — so every credential+ // variable the profile reads is a place the key may sit, after the+ // definition's own.+ return firstNamed(stored, [...definition.credential.envVars, ...CONNECTION_CREDENTIAL_ENV_VARS]);+}+/** The slugs a graph already uses — what every allocation must avoid. */export const takenServiceSlugs = (connections) => new Set(connections.map((connection) => connection.slug).filter(Boolean));diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 5bb649a46b..602c6e3206 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2,7 +2,7 @@ import { CREDENTIALS } from './credentialRegistry.js';import { DEFAULT_BACKUP_CRON } from './backupConfig.js';import { z } from 'zod';import { ServerError } from './errorHandler.js';-import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap } from './zodCompat.js';+import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap, presetProviderIdSchema, providerRefSchema } from './zodCompat.js';import { WORK_TRACKERS } from './workTracker.js';import { PROVIDER_FAMILY_IDS } from './providerFamilies.js';import { APP_FEATURE_IDS, INSTANCE_FEATURE_IDS, INSTANCE_FEATURE_GROUP_IDS } from './instanceFeatureRegistry.js';@@ -152,7 +152,7 @@ export const LAYERED_INTELLIGENCE_SCOPES = ['app-improvement', 'app-data-gap', 'export const layeredIntelligenceConfigSchema = z.object({enabled: z.boolean().optional(),intervalMs: z.number().int().min(60_000).optional(),- providerId: z.string().nullable().optional(),+ providerId: providerRefSchema.nullable().optional(),model: z.string().nullable().optional(),sources: z.object({goals: z.boolean().optional(),@@ -279,7 +279,10 @@ export const appSchema = z.object({// Declared here so a generic PUT /api/apps/:id can't silently strip them (Zod drops// unknown keys and updateApp replaces taskTypeOverrides wholesale).intervalMs: z.number().positive().nullable().optional(),- providerId: z.string().nullable().optional(),+ // PRESET-ONLY: an app pin is read straight off `providers.json` by the task+ // walker, so a composite (`harness.method@service`) would name a record+ // that never exists there (#7564).+ providerId: presetProviderIdSchema.nullable().optional(),model: z.string().nullable().optional(),taskMetadata: z.record(z.any()).nullable().optional()})).optional(), // Per-task overrides: { [taskType]: { enabled, interval, intervalMs, providerId, model, taskMetadata } }@@ -830,7 +833,7 @@ export const attachmentUploadRequestSchema = base64FileUploadSchema;// Run command schemaexport const runSchema = z.object({type: z.enum(['ai', 'command']),- providerId: z.string().optional(),+ providerId: providerRefSchema.optional(),model: z.string().optional(),workspaceId: z.string(),command: z.string().optional(),@@ -879,7 +882,7 @@ export const githubSecretSchema = z.object({// =============================================================================export const insightRefreshSchema = z.object({- providerId: z.string().optional(),+ providerId: providerRefSchema.optional(),model: z.string().optional()});@@ -890,7 +893,7 @@ export const scorecardComputeSchema = z.object({export const scorecardSettingsSchema = z.object({enabled: z.boolean().optional(),- provider: z.string().nullable().optional(),+ provider: providerRefSchema.nullable().optional(),model: z.string().nullable().optional(),feedBrainDigest: z.boolean().optional(),weekStartsOn: z.number().int().min(1).max(7).optional()@@ -1018,7 +1021,7 @@ export const seriesAutopilotScheduleSchema = z.object({enabled: z.boolean().optional().default(false),cron: z.string().min(1).max(120).refine(isValidCronExpression, 'invalid cron expression'),timezone: z.string().min(1).max(64).optional(),- provider: z.preprocess((v) => (v === '' ? undefined : v), z.string().min(1).max(120).optional()),+ provider: z.preprocess((v) => (v === '' ? undefined : v), providerRefSchema.optional()),model: z.preprocess((v) => (v === '' ? undefined : v), z.string().min(1).max(200).optional()),// Optional per-schedule reasoning effort (#3641), mapped to the run's// `effortOverride`. Validated against the union of accepted levels across@@ -1122,7 +1125,7 @@ export const restoreDbRequestSchema = z.object({// use it without a cycle through this module) — re-exported for deep imports.export { emptyToUndefined };export const featureProviderConfigSchema = z.object({- providerId: z.preprocess(emptyToUndefined, z.string().optional()),+ providerId: z.preprocess(emptyToUndefined, providerRefSchema.optional()),model: z.preprocess(emptyToUndefined, z.string().optional()),});@@ -2110,7 +2113,7 @@ export const subscriptionCreateSchema = z.object({// routes and pipeline arc-planning routes. Optional so callers that omit the// llm field fall back to the server's active provider.export const llmSchema = z.object({- provider: z.string().trim().max(80).nullable().optional(),+ provider: providerRefSchema.nullable().optional(),model: z.string().trim().max(200).nullable().optional(),}).optional();@@ -2236,3 +2239,47 @@ export const privateCredentialParamsSchema = z.object({ id: z.enum(CREDENTIALS.fexport const privateCredentialInputSchema = z.object({ value: z.string().trim().max(2000) }).strict();export const modelComparisonSyncSchema = z.object({ apiKey: z.string().min(1).max(200).optional() }).strict();++// =============================================================================+// HARNESS ENABLEMENT + CREDENTIAL BOOTSTRAP APPS (#7564)+// =============================================================================++/**+ * `settings.harnesses` — per-harness enablement: `{ [harnessId]: { enabled } }`.+ * Keyed by a registry id only, so a typo cannot store a rule nothing reads. A+ * harness with no entry is enabled when its binary is detected on PATH+ * (`services/harnessEnablement.js`); `direct` is always enabled.+ */+// `partialRecord`: a Zod 4 `record` over an enum key is EXHAUSTIVE and would+// demand an entry for every harness.+export const harnessSettingsSchema = z.partialRecord(+ z.enum(PROVIDER_HARNESS_IDS),+ z.object({ enabled: z.boolean() }).strict(),+);++/**+ * One credential-bootstrap APP (#7564): the wrapper CLI that mints a harness's+ * credential at spawn (`<command> <args...> <harnessName> [<separator>] <harness args>`).+ * Same field limits as the inline `credentialBootstrap` a record carries+ * (`aiToolkit/validation.js`); `harnessNames` maps a harness id to the name the+ * wrapper knows it by when that differs from the binary (`claude` → `claude-code`).+ * `setupCommand` is advisory text — PortOS never runs it.+ */+export const credentialBootstrapSchema = z.object({+ label: z.string().trim().min(1).max(100),+ command: z.string().trim().min(1).max(200),+ args: z.array(z.string().max(200)).max(20).optional(),+ argsSeparator: z.string().trim().max(20).optional(),+ setupCommand: z.string().trim().max(500).optional(),+ harnessNames: z.partialRecord(z.enum(PROVIDER_HARNESS_IDS), z.string().trim().min(1).max(100)).optional(),+}).strict();++/** `settings.credentialBootstraps` — apps keyed by the slug a composite id's `+<slug>` suffix names. */+export const credentialBootstrapsSettingsSchema = z.record(+ z.string().regex(SERVICE_SLUG_RE, 'bootstrap slug must be lowercase alphanumeric with hyphens').max(64),+ credentialBootstrapSchema,+);++/** `PUT /api/providers/harnesses/:id` — flip one harness's enablement. */+export const harnessEnablementUpdateSchema = z.object({ enabled: z.boolean() }).strict();+export const harnessIdParamSchema = z.enum(PROVIDER_HARNESS_IDS);diff --git a/server/lib/validation.providerRef.test.js b/server/lib/validation.providerRef.test.jsnew file mode 100644index 0000000000..1e8109f783--- /dev/null+++ b/server/lib/validation.providerRef.test.js@@ -0,0 +1,106 @@+/**+ * The provider-reference boundary (#7564): every SELECTION field accepts a+ * preset id or a composite; every PRESET-ONLY surface (the active provider, a+ * record's fallback, an app's task-type pin) refuses a composite by naming the+ * rule; and the two settings slices behind composition validate their shape.+ */+import { describe, expect, it } from 'vitest';+import { presetProviderIdSchema, providerRefFieldSchema, providerRefSchema } from './zodCompat.js';+import {+ appUpdateSchema,+ credentialBootstrapsSettingsSchema,+ featureProviderConfigSchema,+ harnessSettingsSchema,+ llmSchema,+ runSchema,+} from './validation.js';+import { createCosTaskSchema, createTaskTemplateSchema, updateTaskTemplateSchema } from './cosValidation.js';+import { providerActiveSchema, providerSchema, runSchema as toolkitRunSchema } from './aiToolkit/validation.js';++const ACCEPTED = ['claude-code', 'pi.tui@nvidia-nim-free', 'claude.cli@anthropic+corp-auth', 'direct.api@ollama'];+const REJECTED = ['pi.tui@Nvidia', 'pi.tui@', 'pi.gui@x', 'direct.api@ollama+corp-auth', '__proto__'];++describe('providerRefSchema', () => {+ it.each(ACCEPTED)('accepts %s', (id) => {+ expect(providerRefSchema.safeParse(id).success).toBe(true);+ });++ it.each(REJECTED)('rejects %s with the grammar named', (id) => {+ const result = providerRefSchema.safeParse(id);+ expect(result.success).toBe(false);+ expect(result.error.issues[0].message).toMatch(/preset id|composite/);+ });++ it('admits the empty picker sentinel only through the field form', () => {+ expect(providerRefSchema.safeParse('').success).toBe(false);+ expect(providerRefFieldSchema.safeParse('').success).toBe(true);+ expect(providerRefFieldSchema.safeParse('pi.gui@x').success).toBe(false);+ });+});++describe('selection validators take either grammar', () => {+ it.each(ACCEPTED)('%s is a valid selection everywhere a provider is picked', (id) => {+ expect(createCosTaskSchema.safeParse({ description: 'Ship the thing', provider: id }).success).toBe(true);+ expect(createTaskTemplateSchema.safeParse({ name: 'Template', description: 'Ship', provider: id }).success).toBe(true);+ expect(updateTaskTemplateSchema.safeParse({ provider: id }).success).toBe(true);+ expect(featureProviderConfigSchema.safeParse({ providerId: id }).success).toBe(true);+ expect(llmSchema.safeParse({ provider: id }).success).toBe(true);+ expect(runSchema.safeParse({ type: 'ai', providerId: id, workspaceId: 'ws' }).success).toBe(true);+ expect(toolkitRunSchema.safeParse({ providerId: id, prompt: 'hi' }).success).toBe(true);+ });++ it('refuses a malformed reference at the same fields', () => {+ expect(createCosTaskSchema.safeParse({ description: 'Ship', provider: 'pi.gui@x' }).success).toBe(false);+ expect(featureProviderConfigSchema.safeParse({ providerId: 'pi.tui@' }).success).toBe(false);+ expect(toolkitRunSchema.safeParse({ providerId: 'direct.api@ollama+corp-auth', prompt: 'hi' }).success).toBe(false);+ });+});++describe('preset-only surfaces refuse a composite and name the rule', () => {+ const message = (result) => result.error.issues.map((issue) => issue.message).join('\n');++ it('PUT /api/providers/active', () => {+ expect(providerActiveSchema.safeParse({ id: 'claude-code' }).success).toBe(true);+ const result = providerActiveSchema.safeParse({ id: 'pi.tui@nvidia-nim' });+ expect(result.success).toBe(false);+ expect(message(result)).toMatch(/preset provider id/);+ });++ it("a record's fallbackProvider", () => {+ const base = { name: 'Claude', type: 'cli' };+ expect(providerSchema.safeParse({ ...base, fallbackProvider: 'codex' }).success).toBe(true);+ expect(providerSchema.safeParse({ ...base, fallbackProvider: null }).success).toBe(true);+ const result = providerSchema.safeParse({ ...base, fallbackProvider: 'pi.tui@nvidia-nim' });+ expect(result.success).toBe(false);+ expect(message(result)).toMatch(/preset provider id/);+ });++ it("an app's taskTypeOverrides pin", () => {+ const app = (providerId) => ({ taskTypeOverrides: { 'code-review': { providerId } } });+ expect(appUpdateSchema.safeParse(app('claude-code')).success).toBe(true);+ expect(appUpdateSchema.safeParse(app(null)).success).toBe(true);+ const result = appUpdateSchema.safeParse(app('pi.tui@nvidia-nim'));+ expect(result.success).toBe(false);+ expect(message(result)).toMatch(/preset provider id/);+ expect(presetProviderIdSchema.safeParse('direct.api@ollama').success).toBe(false);+ });+});++describe('the settings slices behind composition', () => {+ it('harnesses: only registry ids, only a boolean, any subset', () => {+ expect(harnessSettingsSchema.safeParse({ pi: { enabled: false } }).success).toBe(true);+ expect(harnessSettingsSchema.safeParse({}).success).toBe(true);+ expect(harnessSettingsSchema.safeParse({ gui: { enabled: false } }).success).toBe(false);+ expect(harnessSettingsSchema.safeParse({ pi: { enabled: 'no' } }).success).toBe(false);+ expect(harnessSettingsSchema.safeParse({ pi: { enabled: true, extra: 1 } }).success).toBe(false);+ });++ it('credentialBootstraps: slug-keyed apps with the inline bootstrap limits and a harness-keyed name map', () => {+ const app = { label: 'Corp auth', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } };+ expect(credentialBootstrapsSettingsSchema.safeParse({ 'corp-auth': app }).success).toBe(true);+ expect(credentialBootstrapsSettingsSchema.safeParse({ 'Corp Auth': app }).success).toBe(false);+ expect(credentialBootstrapsSettingsSchema.safeParse({ 'corp-auth': { ...app, command: '' } }).success).toBe(false);+ expect(credentialBootstrapsSettingsSchema.safeParse({ 'corp-auth': { ...app, harnessNames: { gui: 'x' } } }).success).toBe(false);+ expect(credentialBootstrapsSettingsSchema.safeParse({ 'corp-auth': { ...app, secret: 'x' } }).success).toBe(false);+ });+});diff --git a/server/lib/zodCompat.js b/server/lib/zodCompat.jsindex 6544413ac8..d9eb6c4b56 100644--- a/server/lib/zodCompat.js+++ b/server/lib/zodCompat.js@@ -1,4 +1,5 @@import { z } from 'zod';+import { MAX_PROVIDER_REF_LENGTH, PRESET_ID_RE, PRESET_ONLY_MESSAGE, PROVIDER_REF_MESSAGE, parseProviderRef } from './providerRef.js';/*** Zod 4 compatibility helpers.@@ -98,3 +99,31 @@ export const optionalBooleanMap = (keys) =>* override). Pair with `z.string().nullable().optional()`.*/export const emptyToNull = (v) => (v === '' ? null : v);++/**+ * A provider SELECTION reference (#7564): a preset record id OR a composite+ * `<harness>.<method>@<service-slug>[+<bootstrap-slug>]`, as `parseProviderRef`+ * reads it. This is the schema every "which provider runs this?" field takes —+ * CoS task metadata, orchestration roles, feature pins, scheduled prompts —+ * so a `{ providerId, model, effort }` selection keeps its string shape while+ * accepting either spelling.+ *+ * `providerRefFieldSchema` also admits the empty string a picker sends for+ * "use the default"; pair it with the caller's own `emptyToUndefined` /+ * `emptyToNull` preprocess when the field must distinguish clear from absent.+ *+ * `presetProviderIdSchema` is the PRESET-ONLY form for the surfaces a composite+ * must never reach: `PUT /api/providers/active`, a record's `fallbackProvider`,+ * and an app's `taskTypeOverrides` pin — a materialized composite is never a+ * stored record, so nothing keyed on `providers.json` may name one.+ *+ * Here rather than in validation.js for the same TDZ-cycle reason as+ * `emptyToUndefined`: `cosValidation.js` needs it and must not import+ * validation.js.+ */+export const providerRefSchema = z.string().trim().min(1).max(MAX_PROVIDER_REF_LENGTH)+ .refine((value) => parseProviderRef(value) !== null, PROVIDER_REF_MESSAGE);++export const providerRefFieldSchema = z.union([z.literal(''), providerRefSchema]);++export const presetProviderIdSchema = z.string().regex(PRESET_ID_RE, PRESET_ONLY_MESSAGE).max(80);diff --git a/server/routes/providers.composite.test.js b/server/routes/providers.composite.test.jsnew file mode 100644index 0000000000..8025af567a--- /dev/null+++ b/server/routes/providers.composite.test.js@@ -0,0 +1,145 @@+/**+ * The composition surface of `/api/providers` (#7564): the catalog, per-harness+ * enablement, bootstrap apps, one composite's verdict, readiness for a+ * composite, and the preset-only refusal on `PUT /active`. Services are+ * doubled; what is pinned here is the HTTP contract — status codes, the+ * sanitization every provider-bearing payload gets, and which service each+ * route reaches with what.+ */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-composite-routes-') }));+afterAll(cleanupTempDataRoots);+import express, { Router } from 'express';+import { errorMiddleware } from '../lib/errorHandler.js';+import { request } from '../lib/testHelper.js';++const compositeService = vi.hoisted(() => ({ describeCompositeProvider: vi.fn(), buildProviderCatalog: vi.fn() }));+vi.mock('../services/compositeProviders.js', () => compositeService);+const enablementService = vi.hoisted(() => ({ listHarnessEnablement: vi.fn(), setHarnessEnabled: vi.fn() }));+vi.mock('../services/harnessEnablement.js', () => enablementService);+const bootstrapService = vi.hoisted(() => ({ listCredentialBootstraps: vi.fn(), saveCredentialBootstraps: vi.fn() }));+vi.mock('../services/credentialBootstrapApps.js', () => bootstrapService);+const readinessService = vi.hoisted(() => ({ getProviderReadinessMap: vi.fn(), resetProviderReadinessCache: vi.fn() }));+vi.mock('../services/providerReadiness.js', async (importOriginal) => ({ ...(await importOriginal()), ...readinessService }));+import { createPortOSProviderRoutes } from './providers.js';++const COMPOSITE = 'pi.tui@nvidia-nim';+const materialized = () => {+ const record = {+ id: COMPOSITE, name: 'Pi · NVIDIA NIM', type: 'tui', command: 'pi', args: ['--approve', '--provider', 'nvidia'], enabled: true,+ harnessId: 'pi', method: 'tui', serviceId: 'nvidia-nim', servicePlan: 'free', models: ['nvidia/example'], defaultModel: 'nvidia/example',+ envVars: { NVIDIA_API_KEY: 'nim-key' }, secretEnvVars: ['NVIDIA_API_KEY'], gatewayBacked: 'nvidia-nim', endpoint: 'https://integrate.api.nvidia.com/v1',+ };+ Object.defineProperty(record, 'apiKey', { value: 'nim-key', enumerable: false, configurable: true });+ return record;+};+const PRESET = { id: 'claude-code', name: 'Claude', type: 'cli', command: 'claude', enabled: true, apiKey: 'preset-secret', envVars: {}, secretEnvVars: [] };++const providerService = { getAllProviders: vi.fn(), getProviderById: vi.fn(), setActiveProvider: vi.fn() };+const app = () => {+ const server = express();+ server.use(express.json());+ server.use('/api/providers', createPortOSProviderRoutes({ services: { providers: providerService, providerStatus: {} }, routes: { providers: Router() } }));+ server.use(errorMiddleware);+ return server;+};++beforeEach(() => {+ vi.clearAllMocks();+ providerService.getAllProviders.mockResolvedValue({ activeProvider: 'claude-code', providers: [PRESET] });+ providerService.getProviderById.mockImplementation(async (id) => (id === COMPOSITE ? materialized() : id === 'claude-code' ? PRESET : null));+});++describe('PUT /api/providers/active', () => {+ it('refuses a composite with a 400 that names the preset-only rule, and never reaches the store', async () => {+ const res = await request(app()).put('/api/providers/active').send({ id: COMPOSITE });+ expect(res.status).toBe(400);+ expect(JSON.stringify(res.body.context.details)).toMatch(/preset provider id/);+ expect(providerService.setActiveProvider).not.toHaveBeenCalled();+ });+});++describe('GET /api/providers/catalog', () => {+ it('hands the sanitized presets to the catalog builder and returns its answer', async () => {+ compositeService.buildProviderCatalog.mockImplementation(async ({ presets }) => ({ harnesses: [], services: [], bootstraps: [], compatibility: {}, effortLevels: {}, effortLevelsByModel: {}, presets }));+ const res = await request(app()).get('/api/providers/catalog');+ expect(res.status).toBe(200);+ expect(res.body.presets).toHaveLength(1);+ expect(res.body.presets[0]).toMatchObject({ id: 'claude-code', hasApiKey: true });+ expect(JSON.stringify(res.body)).not.toContain('preset-secret');+ });+});++describe('GET /api/providers/composites/:id', () => {+ it('publishes the verdict with the record sanitized like a stored one — never the key', async () => {+ compositeService.describeCompositeProvider.mockResolvedValue({+ id: COMPOSITE, eligible: true, code: null, reason: null, parts: { harnessId: 'pi', method: 'tui', serviceSlug: 'nvidia-nim', bootstrapSlug: null }, record: materialized(),+ });+ const res = await request(app()).get(`/api/providers/composites/${encodeURIComponent(COMPOSITE)}`);+ expect(res.status).toBe(200);+ expect(compositeService.describeCompositeProvider).toHaveBeenCalledWith(COMPOSITE);+ expect(res.body).toMatchObject({ id: COMPOSITE, eligible: true, parts: { harnessId: 'pi' } });+ expect(res.body.provider).toMatchObject({ id: COMPOSITE, hasApiKey: true, harnessId: 'pi', envVars: { NVIDIA_API_KEY: '***' } });+ expect(res.body.provider).not.toHaveProperty('apiKey');+ expect(JSON.stringify(res.body)).not.toContain('nim-key');+ });++ it('carries an ineligible composite\'s reason with no provider', async () => {+ compositeService.describeCompositeProvider.mockResolvedValue({ id: COMPOSITE, eligible: false, code: 'harness-disabled', reason: 'Pi is switched off', parts: null, record: null });+ const res = await request(app()).get(`/api/providers/composites/${encodeURIComponent(COMPOSITE)}`);+ expect(res.body).toEqual({ id: COMPOSITE, eligible: false, code: 'harness-disabled', reason: 'Pi is switched off', parts: null, provider: null });+ });+});++describe('GET /api/providers/readiness?providerId=', () => {+ it('answers for one composite through the same lookup the run paths use', async () => {+ readinessService.getProviderReadinessMap.mockImplementation(async (providers) => Object.fromEntries(providers.map((p) => [p.id, { ready: true }])));+ const res = await request(app()).get(`/api/providers/readiness?providerId=${encodeURIComponent(COMPOSITE)}`);+ expect(res.status).toBe(200);+ expect(providerService.getProviderById).toHaveBeenCalledWith(COMPOSITE);+ expect(res.body).toEqual({ readiness: { [COMPOSITE]: { ready: true } } });+ expect(providerService.getAllProviders).not.toHaveBeenCalled();+ });++ it('answers an empty map for a composite that does not resolve', async () => {+ const res = await request(app()).get(`/api/providers/readiness?providerId=${encodeURIComponent('claude.cli@nowhere')}`);+ expect(res.body).toEqual({ readiness: {} });+ expect(readinessService.getProviderReadinessMap).not.toHaveBeenCalled();+ });+});++describe('harnesses and bootstraps', () => {+ it('GET /harnesses lists the verdicts; PUT /harnesses/:id records one flip and refuses an unknown id', async () => {+ enablementService.listHarnessEnablement.mockResolvedValue([{ id: 'pi', enabled: true, source: 'detected' }]);+ enablementService.setHarnessEnabled.mockResolvedValue({ enabled: false, source: 'setting', detected: true, version: '1.0.0' });+ expect((await request(app()).get('/api/providers/harnesses')).body).toEqual({ harnesses: [{ id: 'pi', enabled: true, source: 'detected' }] });++ const res = await request(app()).put('/api/providers/harnesses/pi').send({ enabled: false });+ expect(res.status).toBe(200);+ expect(enablementService.setHarnessEnabled).toHaveBeenCalledWith('pi', false);+ expect(res.body).toEqual({ harness: { id: 'pi', enabled: false, source: 'setting', detected: true, version: '1.0.0' } });++ expect((await request(app()).put('/api/providers/harnesses/gui').send({ enabled: false })).status).toBe(400);+ expect((await request(app()).put('/api/providers/harnesses/pi').send({ enabled: 'no' })).status).toBe(400);+ expect(enablementService.setHarnessEnabled).toHaveBeenCalledTimes(1);+ });++ it('GET /bootstraps reads the table; PUT /bootstraps validates before saving and never spawns', async () => {+ const apps = { 'corp-auth': { label: 'Corp auth', command: 'corp-auth', args: ['run'], harnessNames: { claude: 'claude-code' } } };+ bootstrapService.listCredentialBootstraps.mockResolvedValue(apps);+ bootstrapService.saveCredentialBootstraps.mockImplementation(async (value) => value);+ expect((await request(app()).get('/api/providers/bootstraps')).body).toEqual({ bootstraps: apps });++ const saved = await request(app()).put('/api/providers/bootstraps').send({ bootstraps: apps });+ expect(saved.status).toBe(200);+ expect(bootstrapService.saveCredentialBootstraps).toHaveBeenCalledWith(apps);+ expect(saved.body).toEqual({ bootstraps: apps });++ const bad = await request(app()).put('/api/providers/bootstraps').send({ bootstraps: { 'Corp Auth': apps['corp-auth'] } });+ expect(bad.status).toBe(400);+ expect(bootstrapService.saveCredentialBootstraps).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex f700e9c998..816dbae9b6 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -49,6 +49,9 @@ import {providerServiceUpdateSchema,providerRouteModelAliasSchema,providerRouteSettingsUpdateSchema,+ credentialBootstrapsSettingsSchema,+ harnessEnablementUpdateSchema,+ harnessIdParamSchema,} from '../lib/validation.js';import {getProviderRuntimeStatus,@@ -115,12 +118,12 @@ let runtimeSetupInFlight = false;* distinguish "configured but blank" from an unknown redacted value when it* paints provider readiness.*/-const sanitizeProvider = (provider) => {+const sanitizeProvider = (provider, { hasApiKey = Boolean(provider?.apiKey) } = {}) => {if (!provider) return provider;const { apiKey, envVars, secretEnvVars, ...rest } = provider;const sanitized = {...rest,- hasApiKey: Boolean(apiKey),+ hasApiKey,envVars: envVars ? { ...envVars } : {},secretEnvVars: secretEnvVars || []};@@ -190,6 +193,10 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =// untouched list rides along as `modelCatalog` — the editor seeds its// "Available Models" box from it, so an ordinary Save on a scoped provider// cannot persist the narrowed list over the real one.+ // `hasApiKey` is read off the RAW record: an inherited or materialized key+ // rides NON-enumerably (`withGatewayApiKey`, the composite resolver), and the+ // decorating spreads above have already dropped it by the time the sanitizer+ // looks — a composite with a key would otherwise read as keyless (#7564).return sanitizeProvider({...applyModelAccess(decorated),// The UNION of the two refresh paths, because the button asks only@@ -201,7 +208,7 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =publicReviewEnforcedPostures: enforcedPublicReviewPosturesForProvider(provider),publicReviewSupported: publicReviewPostures.includes(PUBLIC_REVIEW_NO_TOOL_POSTURE),publicReviewActionsSupported: publicReviewPostures.includes(PUBLIC_REVIEW_ACTIONS_POSTURE),- });+ }, { hasApiKey: Boolean(provider?.apiKey) });};/**@@ -605,11 +612,78 @@ export function createPortOSProviderRoutes(aiToolkit) {* probe at the wrong endpoint. The response carries booleans, labels, and the* provider's own already-displayed endpoint — never a resolved binary path.*/- router.get('/readiness', asyncHandler(async (_req, res) => {+ router.get('/readiness', asyncHandler(async (req, res) => {+ // `?providerId=<composite>` answers for ONE composition (#7564): the+ // materialized record is what the readiness probe reads, so a composite+ // that resolves is judged exactly as a stored record on the same daemon.+ const compositeId = typeof req.query.providerId === 'string' ? req.query.providerId : null;+ if (compositeId) {+ const provider = await providerService.getProviderById(compositeId);+ res.json({ readiness: provider ? await getProviderReadinessMap([provider]) : {} });+ return;+ }const data = await providerService.getAllProviders();res.json({ readiness: await getProviderReadinessMap(data.providers) });}));+ /**+ * The composition catalog (#7564): every axis a `{ providerId, model, effort }`+ * picker composes over — harnesses with their enablement, service instances,+ * bootstrap apps, which harness reaches which service, the effort ladder per+ * harness (and per model where a model narrows it), and the stored presets.+ * Derived from cache and settings only: harness detection is the runtime+ * probe's cache, nothing is spawned, no provider is contacted.+ *+ * `GET /api/providers` stays presets-only — every existing `useProviderModels`+ * consumer keeps its shape; this is the additive surface for composing.+ */+ router.get('/catalog', asyncHandler(async (_req, res) => {+ const { buildProviderCatalog } = await import('../services/compositeProviders.js');+ const [data, capabilities] = await Promise.all([providerService.getAllProviders(), detectSystemCapabilities()]);+ res.json(await buildProviderCatalog({ presets: data.providers.map((provider) => presentProvider(provider, capabilities)) }));+ }));++ /** Per-harness enablement (#7564): the user's word, else PATH detection, `direct` always on. */+ router.get('/harnesses', asyncHandler(async (_req, res) => {+ const { listHarnessEnablement } = await import('../services/harnessEnablement.js');+ res.json({ harnesses: await listHarnessEnablement() });+ }));++ router.put('/harnesses/:id', asyncHandler(async (req, res) => {+ const harnessId = validateRequest(harnessIdParamSchema, req.params.id);+ const { enabled } = validateRequest(harnessEnablementUpdateSchema, req.body || {});+ const { setHarnessEnabled } = await import('../services/harnessEnablement.js');+ res.json({ harness: { id: harnessId, ...(await setHarnessEnabled(harnessId, enabled)) } });+ }));++ /**+ * Credential-bootstrap apps (#7564): the wrapper CLIs a composite's+ * `+<slug>` suffix names. Saving never spawns anything — `setupCommand` is+ * advisory text, and the wrapper runs only when a composite is executed.+ */+ router.get('/bootstraps', asyncHandler(async (_req, res) => {+ const { listCredentialBootstraps } = await import('../services/credentialBootstrapApps.js');+ res.json({ bootstraps: await listCredentialBootstraps() });+ }));++ router.put('/bootstraps', asyncHandler(async (req, res) => {+ const bootstraps = validateRequest(credentialBootstrapsSettingsSchema, req.body?.bootstraps ?? req.body ?? {});+ const { saveCredentialBootstraps } = await import('../services/credentialBootstrapApps.js');+ res.json({ bootstraps: await saveCredentialBootstraps(bootstraps) });+ }));++ /**+ * One composite's verdict (#7564): eligible or not, with the reason a picker+ * shows beside a saved selection that names it, and — when eligible — the+ * materialized record sanitized exactly as a stored one (`presentProvider`:+ * `apiKey` → `hasApiKey`, secret env values redacted).+ */+ router.get('/composites/:id', asyncHandler(async (req, res) => {+ const { describeCompositeProvider } = await import('../services/compositeProviders.js');+ const { record, ...verdict } = await describeCompositeProvider(req.params.id);+ res.json({ ...verdict, provider: record ? presentProvider(record, await detectSystemCapabilities()) : null });+ }));+/*** Is a ChatGPT subscription signed in, and is it usable right now?*diff --git a/server/routes/settings.js b/server/routes/settings.jsindex c174994f38..cfb3c36742 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -25,7 +25,7 @@ import { storableAutoUpdateConfig } from '../lib/sharedSchemas.js';import { DEFAULT_UNTRUSTED_CONTENT_POLICY, untrustedContentSettingsSchema } from '../lib/untrustedContent.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';-import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';+import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -376,6 +376,15 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.untrustedContent !== undefined) {validateRequest(untrustedContentSettingsSchema, req.body.untrustedContent);}+ // Per-harness enablement and the credential-bootstrap app table (#7564):+ // both are read at composite-provider resolve time, so a malformed entry+ // would surface as a run that cannot spawn rather than a 400 here.+ if (req.body?.harnesses !== undefined) {+ validateRequest(harnessSettingsSchema, req.body.harnesses);+ }+ if (req.body?.credentialBootstraps !== undefined) {+ validateRequest(credentialBootstrapsSettingsSchema, req.body.credentialBootstraps);+ }if (req.body?.backup !== undefined) {validateRequest(backupConfigSchema.partial(), req.body.backup);}diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.jsindex edff634804..b94914cc91 100644--- a/server/services/agentProviderResolution.js+++ b/server/services/agentProviderResolution.js@@ -1,4 +1,5 @@import { isProcessProvider } from '../lib/providerTypes.js';+import { isCompositeProviderId } from '../lib/providerRef.js';import { isPrivateSecurityTask, PRIVATE_SECURITY_DELIVERY } from '../lib/privateSecurityPolicy.js';import { supportsPublicReviewProvider } from '../lib/providerVendors.js';/**@@ -222,6 +223,14 @@ async function resolveOrdinaryProviderAndModel(task) {const providersMap = Object.fromEntries(providerList.map((p) => [p.id, p]));const taskFallbackId = task.metadata?.fallbackProvider;const taskFallbackModel = task.metadata?.fallbackModel;+ // A composite (`harness.method@service`, #7564) is never in the stored map.+ // Materialize the ones this pick can name — the primary (for the toolkit's+ // self-loop guard) and the task-level fallback — so `getFallbackProvider`+ // judges a composite candidate under the SAME `allowedModes` policy as every+ // stored one, and admits it only when its method is allowed.+ if ([provider.id, taskFallbackId].some(isCompositeProviderId)) {+ await (await import('./compositeProviders.js')).withCompositeCandidates(providersMap, [provider.id, taskFallbackId]);+ }// The caller's mode policy travels WITH the fallback request, so an// ineligible candidate is skipped during selection rather than picked and// then rejected below — which used to burn the one retry the cascade had.diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 90e1f18c83..b0957e19e4 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -293,7 +293,13 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// `null` for every other provider, reads a local cache rather than calling// a model, and imports each runtime's cache reader lazily so neither subtree// reaches the boot closure (see `services/localCachedModels.js`).- cachedModelIds: localCachedModelIds+ cachedModelIds: localCachedModelIds,+ // A composite id (`harness.method@service[+bootstrap]`, #7564) names no+ // stored record: the toolkit hands it here, and the host materializes it+ // from the harness registry, the service instance and settings. Imported+ // lazily so the graph store's subtree stays off the boot closure until a+ // composite is actually asked for.+ resolveCompositeProvider: async (id) => (await import('./compositeProviders.js')).resolveCompositeProvider(id)}),// Compatibility shims for services that import from the old service files.@@ -764,7 +770,12 @@ const runDatabaseBootPhase = () => runDatabasePhase({// Provider connection graph (#6367): first run imports every provider record// into ai_connections / ai_harness_bindings / ai_route_bindings; later runs// reconcile against providers.json. Reads and writes local state only.- reconcileProviderGraph: async () => (await import('./providerGraph.js')).initProviderGraph(),+ reconcileProviderGraph: async () => {+ await (await import('./providerGraph.js')).initProviderGraph();+ // Per-harness enablement (#7564): normalize the settings slice and prime+ // the composite cache's revision. Settings-only — no provider is contacted.+ await (await import('./harnessEnablement.js')).reconcileHarnessEnablement();+ },reconcileStackerNews: reconcileStackerNewsSchedulers});diff --git a/server/services/compositeProviders.js b/server/services/compositeProviders.jsnew file mode 100644index 0000000000..f169d6f477--- /dev/null+++ b/server/services/compositeProviders.js@@ -0,0 +1,278 @@+import { parseProviderRef } from '../lib/providerRef.js';+import { PROVIDER_HARNESSES, harnessById, isCompatible } from '../lib/providerHarnesses.js';+import { materializeRouteOutcome } from '../lib/providerRouteRecipes.js';+import { applyServicePlanFilter, instanceApiKeyFor } from '../lib/providerServiceInstances.js';+import { effortLevelsForProvider } from '../lib/providerModels.js';+import { resolveServiceInstance, serviceDefinitionById } from '../lib/serviceDefinitions.js';+import { bootstrapInputFor, listCredentialBootstraps, presentCredentialBootstraps } from './credentialBootstrapApps.js';+import { harnessEnablementFrom, harnessSettingsRevision, listHarnessEnablement } from './harnessEnablement.js';+import { findConnectionByRef, providerGraphEnabled } from './providerGraph.js';+import { readGraph } from './providerGraphStore.js';+import { listServices } from './providerServices.js';+import { peekProviderRuntimeStatuses } from './providerRuntimeInstaller.js';+import { getSettings } from './settings.js';++/**+ * COMPOSITE provider resolution (#7564, epic #7561): turning a+ * `<harness>.<method>@<service-slug>[+<bootstrap-slug>]` id into the executable+ * record every run path already consumes — through the same seam it resolves a+ * preset id today (`getProviderById`), so `{ providerId, model, effort }`+ * selections keep their shape.+ *+ * A composite is materialized on every resolve from three live inputs and is+ * NEVER persisted: the harness registry (code), the service instance (an+ * `ai_connections` row addressed by slug) and settings (harness enablement,+ * bootstrap apps). Disabling the harness or the service makes it ineligible;+ * re-enabling restores it, with nothing to migrate.+ *+ * Every refusal has a reason (`describeCompositeProvider`), so a saved+ * selection that names an ineligible composite stays VISIBLE with its reason+ * rather than being substituted — never a silent swap onto another provider.+ *+ * The credential rides the record exactly as a preset's does: a `field`+ * credential is attached NON-enumerably (the `attachGatewaySiblingKey`+ * discipline, so a spread/JSON round-trip drops it), and an env-borne one+ * sits in `envVars` under a name listed in `secretEnvVars`, which every+ * client-facing sanitizer redacts. The record's `id` is the composite itself,+ * so a status/readiness lookup keyed on it answers for the composition.+ *+ * Settings-only and local I/O only: nothing here probes a binary or contacts a+ * provider (AGENTS.md "No cold-bootstrap LLM calls").+ */++/**+ * Short TTL on the graph read. The hot path is an N-way failure storm — each+ * failing run re-resolves its provider — and a composite lookup would otherwise+ * be three SELECTs each time. Human-paced edits to a service arrive on the next+ * tick; the materialized record itself is keyed on the row's revision below.+ */+const GRAPH_SNAPSHOT_TTL_MS = 1000;+let graphSnapshot = null;+let graphSnapshotAt = -Infinity;++/** id → { key, record } — one entry per composite, replaced when its inputs move. */+const materialized = new Map();++/** Drop every cached derivation. Exported for tests and for a caller that just changed a service row. */+export function invalidateCompositeCache() {+ graphSnapshot = null;+ graphSnapshotAt = -Infinity;+ materialized.clear();+}++async function graphWithinTtl(now = Date.now()) {+ if (graphSnapshot && now - graphSnapshotAt < GRAPH_SNAPSHOT_TTL_MS) return graphSnapshot;+ graphSnapshot = await readGraph();+ graphSnapshotAt = now;+ return graphSnapshot;+}++/**+ * The pure instance shape behind a connection row: its definition, slug, plan,+ * endpoints and the key it runs under. `null` when the row names no definition+ * this build has (nothing composes onto it).+ */+export function instanceForConnection(connection, env = process.env) {+ const definition = connection?.definitionId ? serviceDefinitionById(connection.definitionId) : null;+ if (!definition || !connection.slug) return null;+ const apiKey = instanceApiKeyFor(connection, definition, env);+ return resolveServiceInstance({+ definition,+ slug: connection.slug,+ plan: connection.plan,+ transports: connection.transports,+ credentials: apiKey ? { apiKey } : {},+ credentialVia: connection.credentialVia,+ });+}++const refusal = (code, reason) => ({ record: null, code, reason });++/**+ * Resolve, with the reason for a refusal. Pure over its inputs so the tests+ * pin the policy without a store: the graph, the settings and the bootstrap+ * table arrive as data.+ *+ * @param {string} id+ * @param {{graph: {connections: object[]}, settings: object, bootstraps: object, runtimes?: object, env?: object}} inputs+ * @returns {{record: object|null, code: string|null, reason: string|null, parts: object|null}}+ */+export function materializeComposite(id, { graph, settings, bootstraps, runtimes = undefined, env = process.env }) {+ const ref = parseProviderRef(id);+ if (ref?.kind !== 'composite') return { ...refusal('not-composite', `"${id}" is not a composite provider id`), parts: null };+ const parts = { harnessId: ref.harnessId, method: ref.method, serviceSlug: ref.serviceSlug, bootstrapSlug: ref.bootstrapSlug };+ const withParts = (outcome) => ({ ...outcome, parts });++ const harness = harnessById(ref.harnessId);+ if (!harness) return withParts(refusal('harness-unknown', `No harness "${ref.harnessId}"`));+ const enablement = harnessEnablementFrom(ref.harnessId, { settings, runtimes });+ if (!enablement?.enabled) {+ return withParts(refusal('harness-disabled', `${harness.label} is ${enablement?.source === 'setting' ? 'switched off' : 'not detected on this machine'}`));+ }+ if (!harness.modes.includes(ref.method)) return withParts(refusal('method-unsupported', `${harness.label} has no ${ref.method} mode`));++ const connection = findConnectionByRef(graph, ref.serviceSlug);+ if (!connection || connection.slug !== ref.serviceSlug) return withParts(refusal('service-unknown', `No service is addressed as "${ref.serviceSlug}"`));+ if (connection.enabled === false) return withParts(refusal('service-disabled', `Service "${ref.serviceSlug}" is switched off`));+ const instance = instanceForConnection(connection, env);+ if (!instance) return withParts(refusal('service-undefined', `Service "${ref.serviceSlug}" has no definition this build composes onto`));+ if (!isCompatible(harness, instance)) {+ return withParts(refusal('incompatible', `${harness.label} cannot be pointed at ${instance.definition.label}`));+ }++ let bootstrap = null;+ if (ref.bootstrapSlug) {+ const app = bootstraps?.[ref.bootstrapSlug];+ if (!app) return withParts(refusal('bootstrap-unknown', `No credential bootstrap app is addressed as "${ref.bootstrapSlug}"`));+ bootstrap = bootstrapInputFor(ref.bootstrapSlug, app);+ }++ const models = applyServicePlanFilter(instance.definition, instance.plan, connection.catalog?.models || []);+ const { record, error } = materializeRouteOutcome({+ harness,+ method: ref.method,+ serviceInstance: instance,+ bootstrap,+ providerId: id,+ name: `${harness.label} · ${connection.label || instance.definition.label}`,+ // No model pin unless the selection pairs one; the catalog's first entry+ // is the default a run with no model gets — mirroring a record with no+ // `defaultModel`, whose runs take the first of `models` today.+ selection: { model: models[0] ?? null },+ overrides: { models: [...models] },+ });+ // A refusal is a REASON on this composite, not a failure of the lookup: the+ // caller asked "is this runnable?", and "no, because…" is the answer.+ if (error) return withParts(refusal(error.code, error.message));+ return withParts({ record: withHiddenCredential(record), code: null, reason: null });+}++/**+ * Move a `field` credential off the enumerable surface. Same discipline as+ * `attachGatewaySiblingKey`: a spread or JSON round-trip drops it, and every+ * caller that clones a record for execution already re-carries it.+ */+function withHiddenCredential(record) {+ if (!Object.hasOwn(record, 'apiKey')) return record;+ const { apiKey, ...rest } = record;+ if (apiKey) Object.defineProperty(rest, 'apiKey', { value: apiKey, enumerable: false, configurable: true });+ return rest;+}++async function resolveInputs() {+ const [graph, settings, bootstraps] = await Promise.all([graphWithinTtl(), getSettings(), listCredentialBootstraps()]);+ return { graph, settings, bootstraps, runtimes: peekProviderRuntimeStatuses() };+}++/**+ * The full verdict for a composite id, from live inputs. `eligible: false`+ * carries the code and reason a picker shows beside a saved selection.+ *+ * @param {string} id+ * @returns {Promise<{id: string, eligible: boolean, code: string|null, reason: string|null, parts: object|null, record: object|null}>}+ */+export async function describeCompositeProvider(id) {+ const ref = parseProviderRef(id);+ if (ref?.kind !== 'composite') {+ return { id, eligible: false, code: 'not-composite', reason: `"${id}" is not a composite provider id`, parts: null, record: null };+ }+ if (!providerGraphEnabled()) {+ return { id, eligible: false, code: 'graph-unavailable', reason: 'Service instances are unavailable on this install', parts: null, record: null };+ }+ const inputs = await resolveInputs();+ const connection = findConnectionByRef(inputs.graph, ref.serviceSlug);+ const key = `${connection?.revision ?? 'none'}|${harnessSettingsRevision()}`;+ const cached = materialized.get(id);+ if (cached && cached.key === key) return { id, ...cached.outcome };+ const { record, code, reason, parts } = materializeComposite(id, inputs);+ const outcome = { eligible: record !== null, code, reason, parts, record };+ materialized.set(id, { key, outcome });+ return { id, ...outcome };+}++/**+ * The host resolver the toolkit calls from `getProviderById` for a composite+ * id (`createProviderService({ resolveCompositeProvider })`). `null` for+ * anything that is not runnable right now — the toolkit then answers exactly+ * as it does for an unknown preset id, and the caller's existing "provider not+ * found / using active provider" path names it.+ *+ * @param {string} id+ * @returns {Promise<object|null>}+ */+export async function resolveCompositeProvider(id) {+ return (await describeCompositeProvider(id)).record;+}++/**+ * A providers map with every composite among `ids` materialized into it, for+ * the toolkit's `getFallbackProvider` — which reads its candidates off the map+ * and applies the caller's `allowedModes` to each. So a composite is admitted+ * as a fallback under exactly the mode policy every stored candidate meets+ * (#6368), and never otherwise.+ *+ * @param {Record<string, object>} providersMap — mutated and returned+ * @param {Array<string|null|undefined>} ids+ */+export async function withCompositeCandidates(providersMap, ids) {+ for (const id of ids) {+ if (typeof id !== 'string' || providersMap[id] || parseProviderRef(id)?.kind !== 'composite') continue;+ const record = await resolveCompositeProvider(id);+ if (record) providersMap[id] = record;+ }+ return providersMap;+}++/** The ladder a harness accepts, read through the same function every route uses. */+const harnessEffortLevels = (harness, model = null) => effortLevelsForProvider(+ { harnessId: harness.id, command: harness.recipe?.command ?? null, type: harness.modes[0] },+ model,+);++/**+ * The composition catalog (`GET /api/providers/catalog`): every axis a picker+ * composes over, derived from cache and settings only — harness detection is+ * the runtime probe's cache, services are the graph rows, presets are the+ * stored records the caller hands in already sanitized.+ *+ * @param {{presets?: object[]}} [input]+ */+export async function buildProviderCatalog({ presets = [] } = {}) {+ const [harnesses, bootstraps, services] = await Promise.all([+ listHarnessEnablement(),+ listCredentialBootstraps(),+ providerGraphEnabled() ? listServices().then((result) => result.services) : [],+ ]);+ const graph = providerGraphEnabled() ? await graphWithinTtl() : { connections: [] };+ const instances = graph.connections.map((connection) => ({ connection, instance: instanceForConnection(connection) }))+ .filter(({ instance }) => instance !== null);++ const compatibility = Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [+ harness.id,+ instances.filter(({ instance }) => isCompatible(harness, instance)).map(({ instance }) => instance.slug),+ ]));+ const effortLevels = Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [harness.id, harnessEffortLevels(harness)]));+ // Per-model ladders, only where a model narrows or widens the harness's own+ // (Codex's Ultra-capable models, Antigravity's per-model rungs): every+ // catalog model of a compatible service, keyed under the harness.+ const effortLevelsByModel = Object.fromEntries(PROVIDER_HARNESSES.map((harness) => {+ const base = JSON.stringify(effortLevels[harness.id]);+ const models = new Set(instances+ .filter(({ instance }) => isCompatible(harness, instance))+ .flatMap(({ connection, instance }) => applyServicePlanFilter(instance.definition, instance.plan, connection.catalog?.models || [])));+ const perModel = [...models]+ .map((model) => [model, harnessEffortLevels(harness, model)])+ .filter(([, ladder]) => JSON.stringify(ladder) !== base);+ return [harness.id, Object.fromEntries(perModel)];+ }));++ return {+ harnesses,+ services,+ bootstraps: presentCredentialBootstraps(bootstraps),+ compatibility,+ effortLevels,+ effortLevelsByModel,+ presets,+ };+}diff --git a/server/services/compositeProviders.test.js b/server/services/compositeProviders.test.jsnew file mode 100644index 0000000000..f5418d96db--- /dev/null+++ b/server/services/compositeProviders.test.js@@ -0,0 +1,304 @@+/**+ * Composite provider resolution (#7564): a `harness.method@service[+bootstrap]`+ * id becomes an executable record with no `providers.json` entry, through the+ * REAL argv/env builders every run path uses — or is refused with the reason+ * a picker shows beside a saved selection.+ *+ * The policy half (`materializeComposite`) is pure over its inputs; the+ * store-backed half (`describeCompositeProvider`, the cache, fallback+ * admission) runs over doubled graph/settings/probe modules. Fixtures are+ * synthetic; nothing is read out of a running install and nothing is spawned.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const graphState = vi.hoisted(() => ({ current: { connections: [], bindings: [], routes: [] }, enabled: true }));+const settingsState = vi.hoisted(() => ({ current: {} }));+const runtimeState = vi.hoisted(() => ({ current: {} }));+const settingsMock = vi.hoisted(() => {+ const listeners = new Map();+ const settingsEvents = {+ on: (event, fn) => listeners.set(event, [...(listeners.get(event) || []), fn]),+ emit: (event, ...args) => (listeners.get(event) || []).forEach((fn) => fn(...args)),+ };+ return {+ settingsEvents,+ getSettings: vi.fn(async () => structuredClone(settingsState.current)),+ updateSettingsWith: vi.fn(async (mutate) => {+ settingsState.current = await mutate(structuredClone(settingsState.current));+ settingsEvents.emit('settings:updated', settingsState.current);+ return settingsState.current;+ }),+ };+});+vi.mock('./settings.js', () => settingsMock);+const store = vi.hoisted(() => ({ readGraph: vi.fn(async () => structuredClone(graphState.current)) }));+vi.mock('./providerGraphStore.js', () => store);+vi.mock('./providerGraph.js', async (importOriginal) => ({+ ...(await importOriginal()),+ providerGraphEnabled: () => graphState.enabled,+}));+vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({+ ...(await importOriginal()),+ peekProviderRuntimeStatuses: () => runtimeState.current,+}));+vi.mock('./providerServices.js', () => ({ listServices: vi.fn(async () => ({ services: [{ slug: 'nvidia-nim' }] })) }));++const composite = await import('./compositeProviders.js');+const { buildCliArgs } = await import('../lib/cliProviderArgs.js');+const { buildTuiInvocation } = await import('../lib/tuiHandshake.js');+const { buildTuiShellLaunch } = await import('../lib/tuiShellLaunch.js');+const { buildCliChildEnv } = await import('../lib/cliChildEnv.js');+const { applyCredentialBootstrap, needsProcessGroup, resolveCliSpawn } = await import('../lib/credentialBootstrap.js');+const { PUBLIC_REVIEW_EXECUTION_PROFILES } = await import('../lib/agentExecutionProfiles.js');+const { createRunnerService } = await import('../lib/aiToolkit/runner.js');+const { createProviderStatusService } = await import('../lib/aiToolkit/providerStatus.js');+const { allowedModesFor } = await import('../lib/callerModePolicy.js');++const uuid = (n) => `${n}${n}${n}${n}${n}${n}${n}${n}-${n}${n}${n}${n}-4${n}${n}${n}-8${n}${n}${n}-${n}${n}${n}${n}${n}${n}${n}${n}${n}${n}${n}${n}`;+const connection = (n, row) => ({ id: uuid(n), revision: 1, enabled: true, credentialVia: 'stored', bindings: [], catalog: { state: 'known', models: [] }, ...row });++const GRAPH = {+ bindings: [],+ routes: [],+ connections: [+ connection(1, { kind: 'gateway:nvidia-nim', label: 'NVIDIA NIM (free)', slug: 'nvidia-nim', definitionId: 'nvidia-nim', plan: 'free',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } }, credentials: { apiKey: 'nim-key' },+ catalog: { state: 'known', models: ['nvidia/example-nemotron', 'meta/example-llama'] } }),+ connection(2, { kind: 'gateway:openrouter', label: 'OpenRouter', slug: 'openrouter', definitionId: 'openrouter', plan: 'free',+ transports: { openai: { baseUrl: 'https://openrouter.ai/api/v1' } }, credentials: { apiKey: 'or-key' },+ catalog: { state: 'known', models: ['example/free-model:free', 'example/paid-model'] } }),+ connection(3, { kind: 'ollama', label: 'Ollama', slug: 'ollama', definitionId: 'ollama', plan: 'local',+ transports: { openai: { baseUrl: 'http://127.0.0.1:11434/v1' }, anthropic: { baseUrl: 'http://127.0.0.1:11434' } },+ credentials: { ANTHROPIC_AUTH_TOKEN: 'ollama' }, catalog: { state: 'known', models: ['example-llama'] } }),+ connection(4, { kind: 'lmstudio', label: 'LM Studio', slug: 'lmstudio', definitionId: 'lmstudio', plan: 'local',+ transports: { openai: { baseUrl: 'http://127.0.0.1:1234/v1' } }, credentials: {}, catalog: { state: 'known', models: ['example-qwen'] } }),+ connection(5, { kind: 'api', label: 'Anthropic (corp)', slug: 'anthropic', definitionId: 'anthropic', plan: 'paid',+ transports: { anthropic: { baseUrl: 'https://api.anthropic.com' } }, credentials: {}, credentialVia: 'bootstrap' }),+ connection(6, { kind: 'gateway:nvidia-nim', label: 'NIM (off)', slug: 'nvidia-nim-off', definitionId: 'nvidia-nim', plan: 'paid',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } }, credentials: { apiKey: 'other' }, enabled: false }),+ ],+};+const BOOTSTRAPS = { 'corp-auth': { label: 'Corp auth', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } } };+const RUNTIMES = { pi: { installed: true, version: '1.0.0' }, claude: { installed: true, version: '2.0.0' }, codex: { installed: true, version: '0.5.0' }, opencode: { installed: true, version: '1.1.0' } };+const inputs = (overrides = {}) => ({ graph: GRAPH, settings: {}, bootstraps: BOOTSTRAPS, runtimes: RUNTIMES, env: {}, ...overrides });+const resolve = (id, overrides) => composite.materializeComposite(id, inputs(overrides));+const record = (id, overrides) => {+ const outcome = resolve(id, overrides);+ expect(outcome.reason, `${id}: ${outcome.reason}`).toBeNull();+ return outcome.record;+};++describe('materializeComposite — the run paths', () => {+ it('pi.tui@nvidia-nim: Pi in TUI mode with --provider/--model and the NIM key in env, with no pi-nvidia record anywhere', () => {+ const provider = record('pi.tui@nvidia-nim');+ expect(provider).toMatchObject({+ id: 'pi.tui@nvidia-nim', type: 'tui', command: 'pi', harnessId: 'pi', method: 'tui', serviceId: 'nvidia-nim', servicePlan: 'free',+ enabled: true, models: ['nvidia/example-nemotron', 'meta/example-llama'], defaultModel: 'nvidia/example-nemotron',+ envVars: { NVIDIA_API_KEY: 'nim-key' }, secretEnvVars: ['NVIDIA_API_KEY'], gatewayBacked: 'nvidia-nim',+ });+ const invocation = buildTuiInvocation(provider, provider.defaultModel);+ expect(invocation.command).toBe('pi');+ expect(invocation.args).toEqual(expect.arrayContaining(['--approve', '--provider', 'nvidia', '--model', 'nvidia/example-nemotron']));+ // The Shell page's launch line and PTY env — what `shell:start { providerId }` runs.+ const launch = buildTuiShellLaunch(provider);+ expect(launch.commandLine).toMatch(/^pi\b.*--provider nvidia.*--model nvidia\/example-nemotron/);+ expect(launch.env.NVIDIA_API_KEY).toBe('nim-key');+ });++ it('pi.cli@nvidia-nim: the headless argv the CLI runner spawns, unwrapped', () => {+ const provider = record('pi.cli@nvidia-nim');+ expect(provider).toMatchObject({ type: 'cli', command: 'pi', headlessArgs: [] });+ const args = buildCliArgs(provider);+ expect(args).toEqual(expect.arrayContaining(['--print', '--approve', '--provider', 'nvidia', '--model', 'nvidia/example-nemotron']));+ const env = buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' }, provider, cwd: process.cwd() });+ expect(env.NVIDIA_API_KEY).toBe('nim-key');+ expect(resolveCliSpawn(provider, provider.command, args, env)).toMatchObject({ command: 'pi', wrapped: false });+ });++ it('direct.api@nvidia-nim: executeApiRun posts to the service endpoint with the key as a Bearer header', async () => {+ const provider = record('direct.api@nvidia-nim');+ expect(provider).toMatchObject({ type: 'api', harnessId: 'direct', endpoint: 'https://integrate.api.nvidia.com/v1', timeout: 300000 });+ expect(provider).not.toHaveProperty('command');+ // The credential rides NON-enumerably: readable at execution, gone on serialization.+ expect(provider.apiKey).toBe('nim-key');+ expect(Object.keys(provider)).not.toContain('apiKey');+ expect(JSON.stringify(provider)).not.toContain('nim-key');+ expect({ ...provider }).not.toHaveProperty('apiKey');++ const dataDir = await mkdtemp(join(tmpdir(), 'portos-composite-api-'));+ const encoder = new TextEncoder();+ const chunks = [encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'hi' } }] })}\n`), encoder.encode('data: [DONE]\n')];+ let i = 0;+ const body = { getReader: () => ({ read: async () => (i < chunks.length ? { done: false, value: chunks[i++] } : { done: true, value: undefined }) }) };+ const fetch = vi.fn(async () => ({ ok: true, body }));+ vi.stubGlobal('fetch', fetch);+ const runner = createRunnerService({ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) } });+ let done;+ const completed = new Promise((r) => { done = r; });+ await runner.executeApiRun({ runId: 'composite-api', provider, model: null, prompt: 'hello', workspacePath: process.cwd(), screenshots: [], onComplete: done });+ await expect(completed).resolves.toMatchObject({ success: true });+ expect(fetch).toHaveBeenCalledTimes(1);+ const [url, init] = fetch.mock.calls[0];+ expect(url).toBe('https://integrate.api.nvidia.com/v1/chat/completions');+ expect(init.headers.Authorization).toBe('Bearer nim-key');+ expect(JSON.parse(init.body).model).toBe('nvidia/example-nemotron');+ vi.unstubAllGlobals();+ await rm(dataDir, { recursive: true, force: true });+ });++ it('opencode.cli@openrouter: the inline OpenCode config names the openrouter namespace, and the gateway key rides its own env var', () => {+ const provider = record('opencode.cli@openrouter');+ expect(provider).toMatchObject({ command: 'opencode', args: ['run'], gatewayBacked: 'openrouter', servicePlan: 'free', models: ['example/free-model:free'] });+ const config = JSON.parse(provider.envVars.OPENCODE_CONFIG_CONTENT);+ expect(config.provider.openrouter.options.baseURL).toBe('https://openrouter.ai/api/v1');+ expect(provider.envVars.OPENROUTER_API_KEY).toBe('or-key');+ expect(provider.secretEnvVars).toContain('OPENROUTER_API_KEY');+ const env = buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' }, provider, model: 'example/free-model:free', cwd: process.cwd() });+ expect(env.OPENROUTER_API_KEY).toBe('or-key');+ expect(JSON.parse(env.OPENCODE_CONFIG_CONTENT).provider.openrouter).toBeTruthy();+ // OpenCode takes `-m <namespace>/<model>`: the executable model name is namespaced onto the gateway.+ expect(buildCliArgs(provider)).toEqual(expect.arrayContaining(['run', '-m', 'openrouter/example/free-model:free']));+ });++ it('claude.cli@ollama: Claude Code pointed at the local daemon with the stored placeholder token', () => {+ const provider = record('claude.cli@ollama');+ expect(provider).toMatchObject({ command: 'claude', ollamaBacked: true, harnessId: 'claude', servicePlan: 'local' });+ expect(provider.envVars).toMatchObject({ ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' });+ expect(provider.secretEnvVars).toContain('ANTHROPIC_AUTH_TOKEN');+ expect(buildCliArgs(provider)).toEqual(expect.arrayContaining(['--print', '--model', 'example-llama']));+ });++ it('codex.cli@lmstudio: Codex reaches the daemon through its native --oss --local-provider flag', () => {+ const provider = record('codex.cli@lmstudio');+ expect(provider).toMatchObject({ command: 'codex', lmstudioBacked: true, endpoint: 'http://127.0.0.1:1234/v1' });+ expect(buildCliArgs(provider)).toEqual(expect.arrayContaining(['--oss', '--local-provider', 'lmstudio']));+ });++ it('claude.cli@anthropic+corp-auth: the bootstrap app wraps the spawn, and a public-review posture spawns claude unwrapped', () => {+ const provider = record('claude.cli@anthropic+corp-auth');+ expect(provider.credentialBootstrap).toEqual({ command: 'corp-auth', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' });+ const args = buildCliArgs(provider);+ const spawn = resolveCliSpawn(provider, provider.command, args, { PATH: '/usr/bin' });+ expect(spawn.command).toBe('corp-auth');+ expect(spawn.args.slice(0, 3)).toEqual(['run', 'claude-code', '--']);+ expect(spawn.args.slice(3)).toEqual(args);+ expect(spawn.wrapped).toBe(true);+ // The wrapper is the direct child, so stop/timeout must reach the harness behind it.+ expect(needsProcessGroup(spawn.wrapped, false)).toBe(true);+ expect(needsProcessGroup(spawn.wrapped, true)).toBe(false);++ const restricted = applyCredentialBootstrap(provider, provider.command, args, { safetyProfile: PUBLIC_REVIEW_EXECUTION_PROFILES[0] });+ expect(restricted).toEqual({ command: 'claude', args, wrapped: false });+ });++ it('carries the harness by name into the effort ladder, so a bootstrap-wrapped spawn still offers its rungs', async () => {+ const { effortLevelsForProvider } = await import('../lib/providerModels.js');+ expect(effortLevelsForProvider(record('claude.cli@anthropic+corp-auth'))).toEqual(['low', 'medium', 'high', 'xhigh', 'max']);+ expect(effortLevelsForProvider(record('pi.tui@nvidia-nim'))).toEqual(['low', 'medium', 'high', 'xhigh', 'max']);+ expect(effortLevelsForProvider(record('direct.api@nvidia-nim'))).toBeNull();+ });+});++describe('materializeComposite — refusals carry a reason and never substitute', () => {+ it.each([+ ['claude.cli@nvidia-nim', 'incompatible'],+ ['codex.cli@lmstudio', 'harness-disabled', { settings: { harnesses: { codex: { enabled: false } } } }],+ ['pi.tui@nvidia-nim', 'harness-disabled', { runtimes: { pi: { installed: false } } }],+ ['pi.tui@nvidia-nim-off', 'service-disabled'],+ ['pi.tui@no-such-service', 'service-unknown'],+ ['pi.api@nvidia-nim', 'method-unsupported'],+ ['gui.cli@nvidia-nim', 'harness-unknown'],+ ['claude.cli@anthropic', 'SERVICE_CREDENTIAL_BOOTSTRAP_REQUIRED'],+ ['claude.cli@anthropic+no-such-app', 'bootstrap-unknown'],+ ['direct.api@ollama+corp-auth', 'not-composite'],+ ['claude-code', 'not-composite'],+ ])('%s → %s', (id, code, overrides = {}) => {+ const outcome = resolve(id, overrides);+ expect(outcome.record).toBeNull();+ expect(outcome.code).toBe(code);+ expect(outcome.reason).toEqual(expect.any(String));+ });++ it('refuses a slug that only matches a connection UUID, so an id is never resolved by row identity', () => {+ const byUuid = { ...GRAPH, connections: [{ ...GRAPH.connections[0], slug: 'nvidia-nim-renamed' }] };+ expect(resolve('pi.tui@nvidia-nim', { graph: byUuid }).code).toBe('service-unknown');+ });++ it('re-enabling the harness restores a composite a disabled harness refused, with the same record', () => {+ const off = resolve('pi.tui@nvidia-nim', { settings: { harnesses: { pi: { enabled: false } } } });+ expect(off.code).toBe('harness-disabled');+ const on = resolve('pi.tui@nvidia-nim', { settings: { harnesses: { pi: { enabled: true } } }, runtimes: {} });+ expect(on.record).toMatchObject({ id: 'pi.tui@nvidia-nim' });+ });+});++describe('describeCompositeProvider / resolveCompositeProvider over the live stores', () => {+ beforeEach(() => {+ graphState.current = structuredClone(GRAPH);+ graphState.enabled = true;+ settingsState.current = { credentialBootstraps: BOOTSTRAPS };+ runtimeState.current = RUNTIMES;+ store.readGraph.mockClear();+ composite.invalidateCompositeCache();+ });+ afterEach(() => composite.invalidateCompositeCache());++ it('resolves through the store, reuses the graph snapshot within its TTL, and re-derives when settings move', async () => {+ const first = await composite.resolveCompositeProvider('pi.tui@nvidia-nim');+ expect(first).toMatchObject({ id: 'pi.tui@nvidia-nim', harnessId: 'pi' });+ const second = await composite.describeCompositeProvider('pi.tui@nvidia-nim');+ expect(second).toMatchObject({ eligible: true, code: null, parts: { harnessId: 'pi', method: 'tui', serviceSlug: 'nvidia-nim', bootstrapSlug: null } });+ expect(store.readGraph).toHaveBeenCalledTimes(1);+ expect(second.record).toBe(first);++ settingsState.current = { ...settingsState.current, harnesses: { pi: { enabled: false } } };+ settingsMock.settingsEvents.emit('settings:updated', settingsState.current);+ await expect(composite.describeCompositeProvider('pi.tui@nvidia-nim')).resolves.toMatchObject({ eligible: false, code: 'harness-disabled', record: null });+ });++ it('answers null (not a throw) for a composite that is not runnable, and for a preset id', async () => {+ await expect(composite.resolveCompositeProvider('claude.cli@nvidia-nim')).resolves.toBeNull();+ await expect(composite.resolveCompositeProvider('claude-code')).resolves.toBeNull();+ await expect(composite.describeCompositeProvider('claude-code')).resolves.toMatchObject({ eligible: false, code: 'not-composite' });+ const readsSoFar = store.readGraph.mock.calls.length;+ graphState.enabled = false;+ await expect(composite.describeCompositeProvider('pi.tui@nvidia-nim')).resolves.toMatchObject({ eligible: false, code: 'graph-unavailable' });+ expect(store.readGraph).toHaveBeenCalledTimes(readsSoFar);+ });++ it('admits a composite into the fallback chain only under a caller policy that allows its method', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'portos-composite-status-'));+ const status = createProviderStatusService({ dataDir, defaultFallbackPriority: [] });+ const stored = { id: 'codex', name: 'Codex', type: 'cli', command: 'codex', enabled: true, models: [] };+ const pick = async (policy) => {+ const map = await composite.withCompositeCandidates({ codex: stored }, ['pi.tui@nvidia-nim', 'codex', null]);+ expect(Object.keys(map)).toEqual(['codex', 'pi.tui@nvidia-nim']);+ return status.getFallbackProvider('codex', map, 'pi.tui@nvidia-nim', null, { allowedModes: allowedModesFor(policy) });+ };+ await expect(pick('cli-harness')).resolves.toBeNull();+ await expect(pick('agent-harness')).resolves.toMatchObject({ source: 'task', provider: { id: 'pi.tui@nvidia-nim', type: 'tui' } });+ await rm(dataDir, { recursive: true, force: true });+ });++ it('builds the catalog from cache and settings only: harness verdicts, compatibility by slug, ladders, and the presets handed in', async () => {+ const catalog = await composite.buildProviderCatalog({ presets: [{ id: 'claude-code' }] });+ expect(catalog.presets).toEqual([{ id: 'claude-code' }]);+ expect(catalog.services).toEqual([{ slug: 'nvidia-nim' }]);+ expect(catalog.harnesses.find((row) => row.id === 'pi')).toMatchObject({ enabled: true, detected: true, version: '1.0.0', modes: ['cli', 'tui'] });+ expect(catalog.harnesses.find((row) => row.id === 'direct')).toMatchObject({ enabled: true, source: 'always' });+ expect(catalog.compatibility.pi).toEqual(expect.arrayContaining(['nvidia-nim', 'openrouter', 'anthropic']));+ expect(catalog.compatibility.pi).not.toContain('ollama');+ expect(catalog.compatibility.claude).toEqual(expect.arrayContaining(['ollama', 'anthropic']));+ expect(catalog.compatibility.claude).not.toContain('nvidia-nim');+ expect(catalog.compatibility.direct).toEqual(expect.arrayContaining(['nvidia-nim', 'openrouter', 'ollama', 'lmstudio']));+ expect(catalog.bootstraps).toEqual([{ slug: 'corp-auth', label: 'Corp auth', harnessNames: { claude: 'claude-code' } }]);+ expect(catalog.effortLevels).toMatchObject({ pi: ['low', 'medium', 'high', 'xhigh', 'max'], direct: null, claude: ['low', 'medium', 'high', 'xhigh', 'max'] });+ expect(catalog.effortLevelsByModel).toMatchObject({ pi: {}, direct: {} });+ // Nothing in the catalog carries a credential.+ expect(JSON.stringify(catalog)).not.toMatch(/nim-key|or-key|corp-auth run/);+ expect(store.readGraph).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/credentialBootstrapApps.js b/server/services/credentialBootstrapApps.jsnew file mode 100644index 0000000000..28af3378d3--- /dev/null+++ b/server/services/credentialBootstrapApps.js@@ -0,0 +1,77 @@+import { credentialBootstrapsSettingsSchema } from '../lib/validation.js';+import { isPlainObject } from '../lib/objects.js';+import { getSettings, updateSettingsWith } from './settings.js';++/**+ * Credential-bootstrap APPS (#7564): the wrapper CLIs a composite id's+ * `+<bootstrap-slug>` suffix names, kept in `settings.credentialBootstraps`+ * beside the harness enablement slice (no new file, no table).+ *+ * An app is `{ label, command, args?, argsSeparator?, setupCommand?,+ * harnessNames? }` — the same fields a record's inline `credentialBootstrap`+ * carries, plus the label and the per-harness name map, because one wrapper+ * fronts many harnesses and knows each by its own name (`claude` → `claude-code`).+ * `materializeRoute` turns an app into the inline object `composeBootstrapSpawn`+ * reads at spawn: `<command> <args...> <harnessName> [<separator>] <harness args>`.+ *+ * Saving never spawns anything: `setupCommand` is advisory text the UI shows,+ * and the wrapper itself runs only when a composite naming it is executed.+ */++/** Every app, keyed by slug. Malformed entries are dropped on read, never thrown on. */+export async function listCredentialBootstraps() {+ const raw = (await getSettings()).credentialBootstraps;+ return normalizeCredentialBootstraps(raw);+}++/** One app by slug, or `null`. */+export async function credentialBootstrapBySlug(slug) {+ const apps = await listCredentialBootstraps();+ return Object.hasOwn(apps, slug) ? apps[slug] : null;+}++/**+ * Replace the whole table. Validated against the settings-slice schema so a+ * bad entry 400s here instead of surfacing as a spawn that cannot start.+ */+export async function saveCredentialBootstraps(apps) {+ const parsed = credentialBootstrapsSettingsSchema.parse(apps ?? {});+ await updateSettingsWith((current) => {+ const next = { ...current };+ if (Object.keys(parsed).length === 0) delete next.credentialBootstraps;+ else next.credentialBootstraps = parsed;+ return next;+ });+ return parsed;+}++/**+ * The stored slice with every entry the schema rejects dropped — a hand-edited+ * settings.json must not make every composite lookup throw.+ */+export function normalizeCredentialBootstraps(raw) {+ if (!isPlainObject(raw)) return {};+ return Object.fromEntries(Object.entries(raw).flatMap(([slug, app]) => {+ const result = credentialBootstrapsSettingsSchema.safeParse({ [slug]: app });+ return result.success ? [[slug, result.data[slug]]] : [];+ }));+}++/**+ * The bootstrap input `materializeRoute` takes for an app: its slug as `id`+ * (so the composite id it stamps carries `+<slug>`) plus the spawn columns.+ */+export const bootstrapInputFor = (slug, app) => ({+ id: slug,+ command: app.command,+ ...(Array.isArray(app.args) ? { args: [...app.args] } : {}),+ ...(app.argsSeparator ? { argsSeparator: app.argsSeparator } : {}),+ ...(app.harnessNames ? { harnessNames: { ...app.harnessNames } } : {}),+});++/** The catalog's sanitized view of the table: never a command line, only what a picker names. */+export const presentCredentialBootstraps = (apps) => Object.entries(apps).map(([slug, app]) => ({+ slug,+ label: app.label,+ harnessNames: { ...(app.harnessNames || {}) },+}));diff --git a/server/services/harnessEnablement.js b/server/services/harnessEnablement.jsnew file mode 100644index 0000000000..056d9345ef--- /dev/null+++ b/server/services/harnessEnablement.js@@ -0,0 +1,161 @@+import { EventEmitter } from 'node:events';+import { DIRECT_HARNESS_ID, PROVIDER_HARNESSES, harnessById } from '../lib/providerHarnesses.js';+import { isPlainObject } from '../lib/objects.js';+import { PROVIDER_RUNTIMES, peekProviderRuntimeStatuses } from './providerRuntimeInstaller.js';+import { getSettings, settingsEvents, updateSettingsWith } from './settings.js';++/**+ * Per-HARNESS enablement (#7564, epic #7561) — the harness axis of "an enabled+ * harness × an enabled service is runnable".+ *+ * A harness is enabled by, in order:+ * 1. an explicit `settings.harnesses[id].enabled` (the user's word);+ * 2. otherwise, whether its binary was DETECTED on PATH by the runtime+ * probe's cache (`peekProviderRuntimeStatuses`, cache-only: a probe that+ * has not run yet reads as "unknown", which enables — the same permissive+ * posture `providerPrerequisites.js` takes, because an un-probed harness+ * must route exactly as it did before the probe existed);+ * 3. `direct` — PortOS's own HTTP client — is always enabled: there is no+ * binary to detect and nothing to disable.+ *+ * Settings-only. Nothing here spawns a probe or contacts a provider; the+ * detection it reads is whatever the runtime installer's TTL cache already+ * holds (AGENTS.md "No cold-bootstrap LLM calls").+ */++/** Emits `changed` whenever the enablement inputs move (a settings save). */+export const harnessEnablementEvents = new EventEmitter();++/** Bumped on every settings write; the composite resolver keys its cache on it. */+let settingsRevision = 0;+settingsEvents.on('settings:updated', () => {+ settingsRevision += 1;+ harnessEnablementEvents.emit('changed');+});+settingsEvents.on('settings:invalidated', () => {+ settingsRevision += 1;+ harnessEnablementEvents.emit('changed');+});++/** The revision the composite cache compares against. */+export const harnessSettingsRevision = () => settingsRevision;++/** The runtime row a harness is installed as — `PROVIDER_RUNTIMES` keys rows by vendor, which is the harness id. */+const runtimeForHarness = (harnessId) => PROVIDER_RUNTIMES.find((row) => row.vendor === harnessId) ?? null;++/**+ * Whether `harnessId`'s binary is on PATH, per the runtime probe's CACHE:+ * `true` / `false` when probed within the TTL, `null` when not probed (or the+ * harness has no installable runtime row). `direct` is always `true`.+ *+ * @param {string} harnessId+ * @param {Record<string, {installed?: boolean, version?: string|null}>} [runtimes] — injectable for tests+ * @returns {{detected: boolean|null, version: string|null}}+ */+export function harnessDetection(harnessId, runtimes = peekProviderRuntimeStatuses()) {+ if (harnessId === DIRECT_HARNESS_ID) return { detected: true, version: null };+ const runtime = runtimeForHarness(harnessId);+ const status = runtime ? runtimes?.[runtime.id] : null;+ if (!status) return { detected: null, version: null };+ return { detected: status.installed === true, version: status.version ?? null };+}++/** The explicit setting for a harness, or `null` when the user has not said. */+const explicitEnablement = (settings, harnessId) => {+ const entry = settings?.harnesses?.[harnessId];+ return typeof entry?.enabled === 'boolean' ? entry.enabled : null;+};++/**+ * The pure verdict: enabled, and why.+ *+ * @param {string} harnessId+ * @param {{settings?: object, runtimes?: object}} [inputs]+ * @returns {{enabled: boolean, source: 'always'|'setting'|'detected'|'default', detected: boolean|null, version: string|null}|null}+ * `null` for an id the registry does not know.+ */+export function harnessEnablementFrom(harnessId, { settings = {}, runtimes = undefined } = {}) {+ if (!harnessById(harnessId)) return null;+ const { detected, version } = harnessDetection(harnessId, runtimes);+ if (harnessId === DIRECT_HARNESS_ID) return { enabled: true, source: 'always', detected, version };+ const explicit = explicitEnablement(settings, harnessId);+ if (explicit !== null) return { enabled: explicit, source: 'setting', detected, version };+ if (detected === null) return { enabled: true, source: 'default', detected, version };+ return { enabled: detected, source: 'detected', detected, version };+}++/** Whether `harnessId` may compose into a runnable composite right now. */+export async function harnessEnabled(harnessId) {+ return harnessEnablementFrom(harnessId, { settings: await getSettings() })?.enabled === true;+}++/**+ * Every registry harness with its enablement verdict — the `harnesses` half+ * of `GET /api/providers/catalog`. Cache-only detection; no probe is started.+ */+export async function listHarnessEnablement() {+ const settings = await getSettings();+ const runtimes = peekProviderRuntimeStatuses();+ return PROVIDER_HARNESSES.map((harness) => ({+ id: harness.id,+ label: harness.label,+ modes: [...harness.modes],+ ...harnessEnablementFrom(harness.id, { settings, runtimes }),+ }));+}++/**+ * Record the user's explicit word on one harness. `direct` cannot be disabled+ * (nothing to disable) and an unknown id is refused, so the slice can only+ * ever hold rules something reads.+ */+export async function setHarnessEnabled(harnessId, enabled) {+ if (!harnessById(harnessId) || harnessId === DIRECT_HARNESS_ID) {+ const err = new Error(`"${harnessId}" is not a harness whose enablement can be set`);+ err.status = 400;+ err.code = 'HARNESS_UNKNOWN';+ throw err;+ }+ await updateSettingsWith((current) => ({+ ...current,+ harnesses: { ...normalizeHarnessSettings(current.harnesses), [harnessId]: { enabled: Boolean(enabled) } },+ }));+ return harnessEnablementFrom(harnessId, { settings: await getSettings() });+}++/**+ * The slice with every entry that names no registry harness — or carries no+ * boolean — dropped. Pure; `reconcileHarnessEnablement` persists the result.+ */+export function normalizeHarnessSettings(raw) {+ if (!isPlainObject(raw)) return {};+ return Object.fromEntries(Object.entries(raw)+ .filter(([id, entry]) => harnessById(id) && id !== DIRECT_HARNESS_ID && typeof entry?.enabled === 'boolean')+ .map(([id, entry]) => [id, { enabled: entry.enabled }]));+}++/**+ * Idempotent: bring `settings.harnesses` to its normalized shape, writing only+ * when something changed. Called at boot (after the database phase, beside the+ * provider-graph reconcile) and safe to call from any path that moves the+ * gate. A second call plans nothing.+ *+ * @returns {Promise<{changed: boolean, harnesses: object}>}+ */+export async function reconcileHarnessEnablement() {+ const settings = await getSettings();+ const raw = settings.harnesses;+ const normalized = normalizeHarnessSettings(raw);+ const same = raw === undefined+ ? Object.keys(normalized).length === 0+ : isPlainObject(raw) && JSON.stringify(raw) === JSON.stringify(normalized);+ if (same) return { changed: false, harnesses: normalized };+ await updateSettingsWith((current) => {+ const next = { ...current };+ if (Object.keys(normalized).length === 0) delete next.harnesses;+ else next.harnesses = normalized;+ return next;+ });+ console.log(`🔧 Normalized harness enablement settings (${Object.keys(normalized).length} explicit)`);+ return { changed: true, harnesses: normalized };+}diff --git a/server/services/harnessEnablement.test.js b/server/services/harnessEnablement.test.jsnew file mode 100644index 0000000000..54b9c6a15b--- /dev/null+++ b/server/services/harnessEnablement.test.js@@ -0,0 +1,113 @@+/**+ * Per-harness enablement (#7564): the precedence between the user's explicit+ * setting and PATH detection, `direct` always on, and the boot reconcile that+ * prunes entries nothing reads — idempotent, so a second pass writes nothing.+ *+ * Settings and the runtime probe cache are doubled; nothing here reads disk or+ * spawns a probe.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++const settingsState = vi.hoisted(() => ({ current: {} }));+const settingsMock = vi.hoisted(() => {+ // A minimal emitter: `vi.hoisted` runs before any import, so node's EventEmitter is not in scope yet.+ const listeners = new Map();+ const settingsEvents = {+ on: (event, fn) => listeners.set(event, [...(listeners.get(event) || []), fn]),+ emit: (event, ...args) => (listeners.get(event) || []).forEach((fn) => fn(...args)),+ };+ return {+ settingsEvents,+ getSettings: vi.fn(async () => structuredClone(settingsState.current)),+ updateSettingsWith: vi.fn(async (mutate) => {+ settingsState.current = await mutate(structuredClone(settingsState.current));+ settingsEvents.emit('settings:updated', settingsState.current);+ return settingsState.current;+ }),+ };+});+vi.mock('./settings.js', () => settingsMock);++const runtimeStatuses = vi.hoisted(() => ({ current: {} }));+vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({+ ...(await importOriginal()),+ peekProviderRuntimeStatuses: () => runtimeStatuses.current,+}));++const enablement = await import('./harnessEnablement.js');++beforeEach(() => {+ settingsState.current = {};+ runtimeStatuses.current = {};+ settingsMock.updateSettingsWith.mockClear();+});++describe('harnessEnablementFrom', () => {+ it('reads the explicit setting first, then PATH detection, and enables an un-probed harness', () => {+ const runtimes = { pi: { installed: false, version: null }, claude: { installed: true, version: '2.0.0' } };+ expect(enablement.harnessEnablementFrom('pi', { settings: { harnesses: { pi: { enabled: true } } }, runtimes }))+ .toEqual({ enabled: true, source: 'setting', detected: false, version: null });+ expect(enablement.harnessEnablementFrom('claude', { settings: { harnesses: { claude: { enabled: false } } }, runtimes }))+ .toEqual({ enabled: false, source: 'setting', detected: true, version: '2.0.0' });+ expect(enablement.harnessEnablementFrom('pi', { settings: {}, runtimes })).toMatchObject({ enabled: false, source: 'detected' });+ expect(enablement.harnessEnablementFrom('claude', { settings: {}, runtimes })).toMatchObject({ enabled: true, source: 'detected' });+ // Not probed yet: route exactly as before the probe existed.+ expect(enablement.harnessEnablementFrom('codex', { settings: {}, runtimes })).toMatchObject({ enabled: true, source: 'default', detected: null });+ });++ it('keeps direct always enabled, and answers null for an unknown harness', () => {+ expect(enablement.harnessEnablementFrom('direct', { settings: { harnesses: { direct: { enabled: false } } }, runtimes: {} }))+ .toMatchObject({ enabled: true, source: 'always', detected: true });+ expect(enablement.harnessEnablementFrom('nope', { settings: {}, runtimes: {} })).toBeNull();+ });++ it('resolves the runtime by the harness id even when the binary is spelled differently', () => {+ // Antigravity's binary is `agy`; the runtime row is keyed by that binary.+ expect(enablement.harnessDetection('antigravity', { agy: { installed: true, version: '1.2.3' } }))+ .toEqual({ detected: true, version: '1.2.3' });+ });+});++describe('listHarnessEnablement / setHarnessEnabled', () => {+ it('lists every registry harness with its verdict and records an explicit flip', async () => {+ runtimeStatuses.current = { pi: { installed: true, version: '0.9.0' } };+ const before = await enablement.listHarnessEnablement();+ expect(before.map((row) => row.id)).toContain('direct');+ expect(before.find((row) => row.id === 'pi')).toMatchObject({ enabled: true, source: 'detected', version: '0.9.0', modes: ['cli', 'tui'] });++ await expect(enablement.setHarnessEnabled('pi', false)).resolves.toMatchObject({ enabled: false, source: 'setting' });+ expect(settingsState.current.harnesses).toEqual({ pi: { enabled: false } });+ expect((await enablement.listHarnessEnablement()).find((row) => row.id === 'pi')).toMatchObject({ enabled: false, source: 'setting' });+ });++ it('refuses to set direct or an unknown harness', async () => {+ await expect(enablement.setHarnessEnabled('direct', false)).rejects.toMatchObject({ status: 400, code: 'HARNESS_UNKNOWN' });+ await expect(enablement.setHarnessEnabled('gui-thing', true)).rejects.toMatchObject({ code: 'HARNESS_UNKNOWN' });+ expect(settingsMock.updateSettingsWith).not.toHaveBeenCalled();+ });+});++describe('reconcileHarnessEnablement', () => {+ it('drops entries nothing reads, keeps the rest, and is a no-op on the second pass', async () => {+ settingsState.current = { harnesses: { pi: { enabled: false, stray: 1 }, direct: { enabled: false }, bogus: { enabled: true }, codex: { enabled: 'yes' } } };+ await expect(enablement.reconcileHarnessEnablement()).resolves.toEqual({ changed: true, harnesses: { pi: { enabled: false } } });+ expect(settingsState.current.harnesses).toEqual({ pi: { enabled: false } });+ settingsMock.updateSettingsWith.mockClear();+ await expect(enablement.reconcileHarnessEnablement()).resolves.toEqual({ changed: false, harnesses: { pi: { enabled: false } } });+ expect(settingsMock.updateSettingsWith).not.toHaveBeenCalled();+ });++ it('writes nothing on an install that never set the slice, and removes an all-invalid slice', async () => {+ await expect(enablement.reconcileHarnessEnablement()).resolves.toEqual({ changed: false, harnesses: {} });+ expect(settingsMock.updateSettingsWith).not.toHaveBeenCalled();+ settingsState.current = { harnesses: { bogus: { enabled: true } }, other: 1 };+ await enablement.reconcileHarnessEnablement();+ expect(settingsState.current).toEqual({ other: 1 });+ });++ it('bumps the settings revision every time settings move, for the composite cache key', async () => {+ const before = enablement.harnessSettingsRevision();+ settingsMock.settingsEvents.emit('settings:updated', {});+ expect(enablement.harnessSettingsRevision()).toBe(before + 1);+ });+});diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex d4a103a7d7..7d16c937d4 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -29,6 +29,7 @@import { isVisionCapableCodexTuiProvider } from '../lib/codex.js';import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata, finalizeRunRecord } from './runner.js';import { getActiveProvider, getProviderById, getAllProviders } from './providers.js';+import { isCompositeProviderId } from '../lib/providerRef.js';// `./tuiPromptRunner.js` (which drags node-pty in through `./shell.js`) and// `./providerExecutionReadiness.js` are imported lazily on the branches that// actually execute a run — see their call sites below. promptRunner.js is reached@@ -1171,6 +1172,14 @@ async function pickFallbackProvider(failed, requestCapabilities) {if (!all?.providers) return null;const providersMap = {};for (const p of all.providers) providersMap[p.id] = p;+ // A composite (`harness.method@service`, #7564) never sits in the stored map;+ // the failed provider's own id may be one, and it must be in the map for the+ // toolkit's self-loop guard and `fallbackProvider` read to see it. Lazy: the+ // resolver's closure reaches the graph store, which this request-path module+ // must not drag in for the preset-only common case.+ if (isCompositeProviderId(failed.id)) {+ await (await import('./compositeProviders.js')).withCompositeCandidates(providersMap, [failed.id]);+ }const picked = providerStatus.getFallbackProvider(failed.id, providersMap, null, null, requestCapabilities);if (!picked?.provider) return null;diff --git a/server/services/providerServices.js b/server/services/providerServices.jsindex 1e98d541fc..54ba41d519 100644--- a/server/services/providerServices.js+++ b/server/services/providerServices.js@@ -6,6 +6,7 @@ import {allocateServiceSlug,applyServicePlanFilter,credentialSourceFor,+ instanceApiKeyFor,kindForDefinition,storedTransports,takenServiceSlugs,@@ -42,18 +43,6 @@ const ANTHROPIC_VERSION = '2023-06-01';// "Import scoping").const loadInstallEnvFile = async () => (await import('./credentialInventory.js')).loadInstallEnvFile();-/**- * The key an instance runs under, or `''`. A `stored` instance holds it on the- * row (under `apiKey`, or under the env var name a route-derived row kept); an- * `env` one reads the definition's conventional variable from the process.- */-function instanceApiKey(connection, definition, env) {- const firstNamed = (bag) => definition.credential.envVars.map((name) => bag[name]).find(isNonBlankStr) ?? '';- if (connection.credentialVia === 'env') return firstNamed(env);- const stored = connection.credentials || {};- return stored.apiKey ?? firstNamed(stored);-}-/*** GET `/models` on the instance's own endpoint with its own key.*@@ -67,7 +56,7 @@ function instanceApiKey(connection, definition, env) {* "answered nothing" and "could not answer" stay apart.*/async function listByProbe(connection, definition, { env, probe }) {- const apiKey = instanceApiKey(connection, definition, env);+ const apiKey = instanceApiKeyFor(connection, definition, env);const openai = connection.transports?.openai?.baseUrl;const anthropic = connection.transports?.anthropic?.baseUrl;if (!openai && !anthropic) return { refreshed: false, error: 'This service declares no endpoint to list models from' };