Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

provider presets: derive a stored record's connection from the service it names (#7565)

[._.]/ Adam Eivy86bc3391fcdb
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index c1ef16685a..ac4a3c2cb7 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -1,6 +1,6 @@
import { hardwareUnavailableReason } from '../../utils/systemCapabilities';
import { useMemo, useState } from 'react';
-import { AlertTriangle, Braces, Cpu, Plug, SlidersHorizontal } from 'lucide-react';
+import { AlertTriangle, Braces, Cpu, Link2, Plug, SlidersHorizontal } from 'lucide-react';
import toast from '../ui/Toast';
import * as api from '../../services/api';
import { filterHardwareCompatibleProviderModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, mergeObservedContextWindows, withRuntimeContextWindow, modelOptionLabel, isProcessProvider, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, isCodexProvider } from '../../utils/providers';
@@ -107,6 +107,21 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
});
const [activeTab, setActiveTab] = useDrawerTab('providerTab', 'connection', PROVIDER_FORM_TAB_IDS);
+ // Preset structure (#7565). A DERIVED preset takes its program, endpoint,
+ // credential, environment and catalog from the service it names on every
+ // save; the server refuses a direct edit to one of those with a pointer at
+ // the service, so the banner says so up front. A legacy record the server
+ // reports convertible gets the one-click conversion here.
+ const isDerived = provider?.presetKind === 'derived';
+ const [converting, setConverting] = useState(false);
+ const convertToDerived = async () => {
+ setConverting(true);
+ const derived = await api.deriveProviderPreset(provider.id).catch(() => null);
+ setConverting(false);
+ if (!derived) return;
+ toast.success(`Now derived from service "${derived.serviceId}"`);
+ onSave();
+ };
const [newEnvKey, setNewEnvKey] = useState('');
const [newEnvValue, setNewEnvValue] = useState('');
@@ -509,6 +524,33 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
)}
{activeTab === 'connection' && (
<div className="space-y-4">
+ {isDerived && (
+ <Banner tone="info" icon={Link2}>
+ <p>
+ Derived from service <code className="font-mono">{provider.serviceId}</code> via{' '}
+ <code className="font-mono">{provider.harnessId}</code> ({provider.method}). The command, endpoint,
+ credential, backend environment and model catalog come from that service and are refreshed on every
+ save — edit them on the service, not here. Name, arguments, timeouts, model pins, effort and
+ generation settings are this preset's own.
+ </p>
+ </Banner>
+ )}
+ {provider && !isDerived && provider.presetDerivable && (
+ <Banner tone="info" icon={Link2}>
+ <p>
+ This preset holds its own copy of a service's endpoint and credentials. Converting it derives those
+ from the service it already runs on, so a change to the service reaches it automatically.
+ </p>
+ <button
+ type="button"
+ onClick={convertToDerived}
+ disabled={converting}
+ className="mt-2 px-3 py-1.5 text-sm rounded-lg border border-port-accent/50 text-port-accent hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ {converting ? 'Converting…' : 'Convert to derived preset'}
+ </button>
+ </Banner>
+ )}
<FormField label="Name *">
<input
type="text"
diff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsx
index 12edf36737..2ab66a3bd9 100644
--- a/client/src/components/providers/ProviderForm.test.jsx
+++ b/client/src/components/providers/ProviderForm.test.jsx
@@ -5,6 +5,7 @@ import { MemoryRouter } from 'react-router';
const api = vi.hoisted(() => ({
createProvider: vi.fn(),
updateProvider: vi.fn(),
+ deriveProviderPreset: vi.fn(),
}));
const toast = vi.hoisted(() => ({
@@ -333,4 +334,33 @@ describe('ProviderForm model access', () => {
switchTab('Models');
expect(screen.getByText(/No patterns yet/)).toBeInTheDocument();
});
+
+ // #7565: a DERIVED preset says where its connection comes from; a legacy one
+ // the server reports convertible offers the one-click conversion and closes
+ // through onSave like any other save. Neither appears on a new record.
+ describe('preset structure', () => {
+ const legacy = { id: 'claude-local', name: 'Claude', type: 'cli', command: 'claude', presetKind: 'legacy', presetDerivable: true };
+
+ it('explains a derived preset and offers no conversion', () => {
+ renderForm({ provider: { ...legacy, presetKind: 'derived', presetDerivable: false, harnessId: 'claude', method: 'cli', serviceId: 'ollama' } });
+ expect(screen.getByText(/Derived from service/)).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Convert to derived preset/ })).not.toBeInTheDocument();
+ });
+
+ it('converts a derivable legacy preset through the API and hands back to the page', async () => {
+ const onSave = vi.fn();
+ api.deriveProviderPreset.mockResolvedValue({ ...legacy, presetKind: 'derived', serviceId: 'ollama' });
+ renderForm({ provider: legacy, onSave });
+ fireEvent.click(screen.getByRole('button', { name: /Convert to derived preset/ }));
+ await waitFor(() => expect(onSave).toHaveBeenCalled());
+ expect(api.deriveProviderPreset).toHaveBeenCalledWith('claude-local');
+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('ollama'));
+ });
+
+ it('offers nothing on a record the server does not report convertible, nor on a new one', () => {
+ renderForm({ provider: { ...legacy, presetDerivable: false } });
+ expect(screen.queryByRole('button', { name: /Convert to derived preset/ })).not.toBeInTheDocument();
+ expect(screen.queryByText(/Derived from service/)).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 2a3cbe8c90..c45e9c8e75 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -28,6 +28,14 @@ export const addProviderTuiMode = (id, options = {}) => request(`/providers/${id
...options,
});
export const getSampleProviders = () => request('/providers/samples');
+// Presets (#7565): "Convert to derived preset" stamps a legacy record with the
+// service it already runs on — refused (409) when re-deriving it would change
+// how it runs. ("Save as preset", `POST /providers/presets`, gets its wrapper
+// with the compose popover that calls it, #7566.)
+export const deriveProviderPreset = (id, options = {}) => request(`/providers/${encodeURIComponent(id)}/derive`, {
+ method: 'POST',
+ ...options,
+});
export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'POST' });
export const refreshProviderModels = (id, options) => request(`/providers/${id}/refresh-models`, { method: 'POST', ...options });
// Stored model pins naming a model their provider no longer lists (#7315).
diff --git a/docs/PROVIDER_COMPOSITION.md b/docs/PROVIDER_COMPOSITION.md
index 7067648ad2..d6245d7b2a 100644
--- a/docs/PROVIDER_COMPOSITION.md
+++ b/docs/PROVIDER_COMPOSITION.md
@@ -55,7 +55,32 @@ Fallback selection admits a composite only where a stored candidate would be adm
| `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.
+`GET /api/providers` stays presets-only, so existing consumers are unaffected until the UI slices of the epic (#7561) land; each record now also carries its preset structure (see **Presets**).
+
+## Presets
+
+A **preset** is a stored `data/providers.json` record — what the flat provider list has always been — read as a named (harness, method, service) tuple plus the user's own defaults. Since #7565 a record can carry three additive structural keys, and a record carrying all three is a **derived preset**:
+
+| Key | Meaning |
+|---|---|
+| `harnessId` | The `PROVIDER_HARNESSES` row that drives it (`direct` for an `api` record) |
+| `method` | `cli` / `tui` / `api`; always equal to `type` |
+| `serviceId` | The `ai_connections` slug of the service instance it is materialized from |
+| `catalogNarrowing` | Optional: the subset of the service catalog this preset offers (`null` = the whole catalog, in the narrowing's own order) |
+| `credentialBootstrapId` | Optional (`cli` / `tui` only): the `settings.credentialBootstraps` slug it spawns through; materialization writes the inline `credentialBootstrap` object from it |
+
+On every save of a derived preset (`POST /api/providers`, `PUT /api/providers/:id`) the server re-derives its **connection-owned** values from the service through `materializeRoute` — the program, `endpoint`, `apiKey`, the transport and credential environment variables, the backend markers (`ollamaBacked`, `gatewayBacked`, …), the inline bootstrap, and `models` (the instance's plan-filtered catalog ∩ narrowing) — and writes them into the record, so **`data/providers.json` stays the fully materialized execution contract** and an older release runs the preset with no graph at all. Everything else stays the preset's own: name, `args` / `headlessArgs` / `tuiPromptDelayMs` / `timeout`, `defaultModel` and the tier pins, `effort`, fallback, generation params, consent flags, unknown custom fields, and any environment variable the service does not write (`ANTHROPIC_SMALL_FAST_MODEL` beside a service-written `ANTHROPIC_BASE_URL`). A record's own OpenCode inline config is kept when it already declares the namespaces and base URLs the service would write, because it also holds permissions and agent settings the user typed. A direct edit that would MOVE a connection-owned value is refused with `400 PRESET_FIELD_DERIVED` naming the fields and the service to edit instead; a `models` edit is read as a narrowing.
+
+A record without the three keys is a **legacy preset**: fully hand-editable and executed exactly as before. `GET /api/providers` decorates every record with `presetKind` (`derived` / `legacy`) and `presetDerivable` (a legacy record on a known harness, spawned by the recipe's own binary, with a clean connection profile).
+
+| Surface | Purpose |
+|---|---|
+| `POST /api/providers/presets` `{ compositeId, id?, name?, model?, effort? }` | "Save as preset": the record a composite resolves to, stored enabled with the selection's model and effort as defaults and the `+<bootstrap>` suffix as `credentialBootstrapId`. The id is minted from the parts (`pi-tui-nvidia-nim-free`, `claude-cli-anthropic-corp-auth`), suffixed when taken. An ineligible composite is a 400 with the resolver's code. |
+| `POST /api/providers/:id/derive` | "Convert to derived preset": stamp one legacy record with the harness, method and instance it already runs on — only when re-deriving it reproduces every connection-owned value it carries. `409 PRESET_NOT_DERIVABLE` with the reason otherwise; nothing about how it runs changes either way. |
+
+**Backfill.** The boot reconcile pass (`reconcilePass` in `server/services/providerGraph.js`) stamps every legacy record the graph already routes onto a named service instance, under the same fixpoint rule (`planPresetBackfill`, `server/lib/providerPresets.js`): additive keys only, idempotent, row-derived and never a seed — so it rides every pass rather than a numbered migration, exactly as the service-column backfill does. A record whose re-derivation would change how it runs stays legacy, with the reason logged in aggregate: a path-configured binary, a wrapper that stores no gateway key, an inline bootstrap matching no configured app, a legacy per-gateway marker, a service that has not been given the credential its harness requires. Of the 55 shipped samples, 37 are stamped on first boot.
+
+**Graph.** A derived preset is imported ONTO the connection it declares (`presetDeclaresConnection`), never as a fragment of its own, and stays there across passes even where profile containment would move it — a direct-API preset on a gateway instance reads back as kind `api`, not `gateway:<id>`. So a service edit re-projects it through the same pending/projected snapshot protocol as any route, and additionally re-runs the full materialization (`rematerializeDerivedPresets`) so the inline config, catalog and bootstrap follow the row too; a catalog refresh re-derives `models`; a link or unlink re-addresses `serviceId` to the instance the binding landed on.
## Peers
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index ac5574efa6..df01a95f7e 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -44,7 +44,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).
- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).
- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.
-- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — the AI provider connection graph (#6367, design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route.
+- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — the AI provider connection graph (#6367, design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.
- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.
**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)
diff --git a/server/lib/README.md b/server/lib/README.md
index 91e13f6e2b..8df2ba32a7 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -238,6 +238,7 @@ 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. |
+| `providerPresets.js` | PRESETS (#7565, epic #7561) — a stored `data/providers.json` record read as a (harness, method, service) tuple plus the user's own defaults and overrides. A record carrying `harnessId` + `method` + `serviceId` is a DERIVED preset (`isDerivedPreset` in `providerGraphRecords.js`, `presetKind`): `materializeDerivedPreset({record, harness, instance, catalog, bootstrap})` re-derives every connection-owned value (program, endpoint, credential, backend markers, inline bootstrap, `models` = plan-filtered catalog ∩ `catalogNarrowing`) through `materializeRoute` while keeping every per-preset field (name, argv with a binding's suffix preserved, timeouts, pins, effort, fallback, generation params, consent flags, unknown fields) and the record's own OpenCode inline config when it already reaches the service; `refusedDerivedEdits(updates, derived, ownedEnvNames)` names the connection-owned keys a direct edit would move (`DERIVED_PRESET_OWNED_KEYS`, plus env vars by name); `derivedPresetDrift` / `derivedPresetPatch` compare a record with its derivation; `presetDerivable(record)` is the editor's "offer the button" test; `matchBootstrapApp` / `bootstrapInputFor` map an inline `credentialBootstrap` to a configured app and back; `planPresetBackfill({graph, providers, bootstraps, env})` is the boot-time stamp of every routed legacy record whose re-derivation is a FIXPOINT — additive keys only, every refusal reported with a reason. Pure; the store-backed half is `services/providerPresets.js`. |
| `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.
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index f902176b03..cb48c4c07b 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -803,7 +803,15 @@ export function createProviderService(config = {}) {
secretEnvVars: providerData.secretEnvVars || [],
headlessArgs: providerData.headlessArgs || [],
tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,
- ...(providerData.tuiIdleTimeoutMs != null ? { tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs } : {})
+ ...(providerData.tuiIdleTimeoutMs != null ? { tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs } : {}),
+ // Preset structure (#7565) — only persisted when named, so every record
+ // created without it stays byte-identical and reads as a legacy preset.
+ ...(typeof providerData.harnessId === 'string' && providerData.harnessId ? { harnessId: providerData.harnessId } : {}),
+ ...(typeof providerData.method === 'string' && providerData.method ? { method: providerData.method } : {}),
+ ...(typeof providerData.serviceId === 'string' && providerData.serviceId ? { serviceId: providerData.serviceId } : {}),
+ ...(Array.isArray(providerData.catalogNarrowing) ? { catalogNarrowing: [...providerData.catalogNarrowing] } : {}),
+ ...(typeof providerData.credentialBootstrapId === 'string' && providerData.credentialBootstrapId
+ ? { credentialBootstrapId: providerData.credentialBootstrapId } : {})
};
return provider;
diff --git a/server/lib/aiToolkit/providers.presetFields.test.js b/server/lib/aiToolkit/providers.presetFields.test.js
new file mode 100644
index 0000000000..31a6f023f9
--- /dev/null
+++ b/server/lib/aiToolkit/providers.presetFields.test.js
@@ -0,0 +1,63 @@
+/**
+ * The downgrade half of the preset contract (#7565): a providers.json carrying
+ * the structural keys is executed unchanged by a release that never heard of
+ * them. Two facts make that true and both are pinned here — the record loads
+ * and round-trips with the keys intact, and the provider schema STRIPS an
+ * unknown key rather than refusing the whole record (so an older schema's
+ * `PUT /:id` keeps working against a newer file).
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createProviderService } from './providers.js';
+import { providerCreateSchema, providerSchema } from './validation.js';
+
+const PRESET = {
+ id: 'claude-local', name: 'Claude · local', type: 'cli', command: 'claude', args: ['--print'], enabled: true, models: ['example-llama'],
+ envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' }, secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],
+ harnessId: 'claude', method: 'cli', serviceId: 'ollama', catalogNarrowing: ['example-llama'], credentialBootstrapId: null,
+};
+
+describe('a providers.json carrying preset structure', () => {
+ let dataDir;
+ beforeEach(async () => {
+ dataDir = await mkdtemp(join(tmpdir(), 'portos-preset-fields-'));
+ await writeFile(join(dataDir, 'providers.json'), JSON.stringify({ activeProvider: 'claude-local', providers: { 'claude-local': PRESET } }));
+ });
+ afterEach(() => rm(dataDir, { recursive: true, force: true }));
+
+ it('loads, executes and round-trips with the keys intact', async () => {
+ const service = createProviderService({ dataDir, providersCacheTtlMs: 0 });
+ expect(await service.getProviderById('claude-local')).toMatchObject({ harnessId: 'claude', method: 'cli', serviceId: 'ollama', catalogNarrowing: ['example-llama'] });
+ expect(await service.getActiveProvider()).toMatchObject({ id: 'claude-local', command: 'claude' });
+ await service.updateProvider('claude-local', { effort: 'high' });
+ const written = JSON.parse(await readFile(join(dataDir, 'providers.json'), 'utf8')).providers['claude-local'];
+ expect(written).toMatchObject({ effort: 'high', harnessId: 'claude', method: 'cli', serviceId: 'ollama' });
+ });
+
+ it('is created with the keys only when named, so an ordinary create stays byte-identical', async () => {
+ const service = createProviderService({ dataDir, providersCacheTtlMs: 0 });
+ const derived = await service.createProvider({ ...PRESET, id: 'derived', credentialBootstrapId: 'corp-auth' });
+ expect(derived).toMatchObject({ harnessId: 'claude', method: 'cli', serviceId: 'ollama', catalogNarrowing: ['example-llama'], credentialBootstrapId: 'corp-auth' });
+ const legacy = await service.createProvider({ id: 'legacy', name: 'Legacy', type: 'cli', command: 'claude' });
+ for (const key of ['harnessId', 'method', 'serviceId', 'catalogNarrowing', 'credentialBootstrapId']) expect(legacy).not.toHaveProperty(key);
+ });
+});
+
+describe('the provider schema and a key it has never seen', () => {
+ it('accepts the preset keys, and drops rather than refuses an unknown one — the older-release contract', () => {
+ const parsed = providerSchema.safeParse({ ...PRESET, aKeyFromALaterRelease: { nested: true } });
+ expect(parsed.success).toBe(true);
+ expect(parsed.data).toMatchObject({ harnessId: 'claude', method: 'cli', serviceId: 'ollama', catalogNarrowing: ['example-llama'], credentialBootstrapId: null });
+ expect(parsed.data).not.toHaveProperty('aKeyFromALaterRelease');
+ expect(providerSchema.partial().safeParse({ aKeyFromALaterRelease: 1, effort: 'high' }).success).toBe(true);
+ expect(providerCreateSchema.safeParse(PRESET).success).toBe(true);
+ });
+
+ it('refuses a malformed structural key rather than storing it', () => {
+ expect(providerSchema.safeParse({ ...PRESET, harnessId: 'Claude Code' }).success).toBe(false);
+ expect(providerSchema.safeParse({ ...PRESET, method: 'gui' }).success).toBe(false);
+ expect(providerSchema.safeParse({ ...PRESET, serviceId: 'nim@home' }).success).toBe(false);
+ });
+});
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index d0b7f45f68..4a309df4ea 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -248,7 +248,24 @@ export const providerSchema = z.object({
secretEnvVars: z.array(z.string()).optional(),
headlessArgs: z.array(z.string()).optional(),
tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),
- tuiIdleTimeoutMs: z.number().int().min(1000).max(86400000).optional()
+ tuiIdleTimeoutMs: z.number().int().min(1000).max(86400000).optional(),
+ // PRESET structure (#7565): a record carrying all three of `harnessId`,
+ // `method` and `serviceId` is a DERIVED preset — its connection-owned values
+ // are re-materialized from the named service instance on every save by the
+ // host (`server/lib/providerPresets.js`). A record without them is a legacy
+ // preset, executed exactly as before. Additive and nullable so an editor can
+ // clear them; `method` must equal `type` (the host enforces it, since a
+ // refinement here would not survive `.partial()` / `.extend()`). The ids are
+ // slugs rather than enums because this directory stays self-contained.
+ harnessId: z.string().regex(/^[a-z0-9-]+$/, 'harnessId must be a harness id').max(64).nullable().optional(),
+ method: z.enum(['cli', 'tui', 'api']).nullable().optional(),
+ serviceId: z.string().regex(PRESET_ID_RE, 'serviceId must be a service slug').max(64).nullable().optional(),
+ // The subset of the service catalog this preset offers; `null` = the whole catalog.
+ catalogNarrowing: z.array(z.string().trim().min(1).max(512)).max(1000).nullable().optional(),
+ // The configured credential-bootstrap app (`settings.credentialBootstraps`
+ // slug) a derived cli/tui preset spawns through; materialization writes the
+ // inline `credentialBootstrap` object from it.
+ credentialBootstrapId: z.string().regex(PRESET_ID_RE, 'credentialBootstrapId must be a bootstrap slug').max(64).nullable().optional(),
});
/**
diff --git a/server/lib/index.js b/server/lib/index.js
index 4d6110ee68..f5c605aa6e 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 './providerPresets.js';
export * from './providerRef.js';
export * from './providerRouteRecipes.js';
export * from './serviceDefinitions.js';
diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.js
index 5639b6c6f2..408333bd95 100644
--- a/server/lib/providerGraphRecords.js
+++ b/server/lib/providerGraphRecords.js
@@ -402,6 +402,62 @@ export function graphFromPreview(preview, mintId = randomUUID) {
export const importGraphFromProviders = (data, mintId = randomUUID) =>
graphFromPreview(buildProviderGraphPreview(data), mintId);
+// --- derived presets (#7565) ---------------------------------------------------
+
+/**
+ * Whether a record is a DERIVED preset: one carrying the three structural keys
+ * — `harnessId`, `method`, `serviceId` — that name the service instance its
+ * connection-owned values are materialized from. Lives here (not in
+ * `providerPresets.js`, which imports this module) because reconciliation is
+ * the first reader.
+ */
+export const isDerivedPreset = (record) => Boolean(record)
+ && typeof record === 'object'
+ && typeof record.harnessId === 'string' && record.harnessId !== ''
+ && typeof record.method === 'string' && record.method !== ''
+ && typeof record.serviceId === 'string' && record.serviceId !== '';
+
+/**
+ * Whether a derived preset DECLARES it sits on this connection — its
+ * `serviceId` is the row's slug. A declaration outranks the profile
+ * containment test: "derived from service X" is a fact the record states, not
+ * one reconciliation infers, so a direct-API preset on a gateway instance
+ * (whose profile reads back as kind `api`, not `gateway:<id>`) stays on the row
+ * it names instead of being cloned onto a fragment of its own every pass.
+ */
+export const presetDeclaresConnection = (record, connection) =>
+ isDerivedPreset(record) && typeof connection?.slug === 'string' && connection.slug === record.serviceId;
+
+/**
+ * Import derived presets ONTO the connections they declare, rather than as
+ * fragments of their own. The preview's own grouping (mode siblings, identity
+ * buckets) still decides which records share one binding; only the connection
+ * edge is retargeted, and the binding takes the first free variant key on its
+ * target so the database's uniqueness rules hold.
+ *
+ * A declared preset whose profile the preview isolates (a reason on it) gets
+ * no route row, exactly as any other isolated record.
+ */
+function importDeclaredPresets(records, graph, mintId) {
+ const bySlug = new Map(graph.connections.filter((connection) => connection.slug).map((connection) => [connection.slug, connection]));
+ const byId = new Map(records.map((record) => [record.id, record]));
+ const fragment = importGraphFromProviders({ providers: records }, mintId);
+ const variantKey = (connectionId, harnessId, key) => JSON.stringify([connectionId, harnessId ?? null, key]);
+ const taken = new Set(graph.bindings.map((binding) => variantKey(binding.connectionId, binding.harnessId, binding.variantKey)));
+ const bindings = [];
+ const routes = [];
+ for (const binding of fragment.bindings) {
+ const own = fragment.routes.filter((route) => route.bindingId === binding.id);
+ const target = bySlug.get(byId.get(own[0]?.providerId)?.serviceId);
+ if (!target) continue;
+ const key = taken.has(variantKey(target.id, binding.harnessId, 'default')) ? `variant:${own[0].providerId}` : 'default';
+ taken.add(variantKey(target.id, binding.harnessId, key));
+ bindings.push({ ...binding, connectionId: target.id, variantKey: key });
+ routes.push(...own);
+ }
+ return { connections: [], bindings, routes };
+}
+
// --- reconciliation ----------------------------------------------------------
/**
@@ -504,7 +560,7 @@ export function planGraphReconciliation(graph, providers, { mintId = randomUUID
const onStored = [];
const moved = new Map();
for (const entry of entries) {
- if (routeBelongsOnConnection(entry.profile, stored)) {
+ if (presetDeclaresConnection(entry.provider, stored) || routeBelongsOnConnection(entry.profile, stored)) {
onStored.push(entry);
continue;
}
@@ -569,7 +625,20 @@ export function planGraphReconciliation(graph, providers, { mintId = randomUUID
const mapped = new Set(graph.routes.map((route) => route.providerId));
const unmapped = [...records.values()].filter((provider) => !mapped.has(provider.id));
- if (unmapped.length > 0) plan.imports = importGraphFromProviders({ providers: unmapped }, mintId);
+ // A derived preset naming an existing instance is imported ONTO it (#7565);
+ // everything else is its own fragment, never auto-linked.
+ const slugs = new Set(graph.connections.map((connection) => connection.slug).filter(Boolean));
+ const declared = unmapped.filter((provider) => isDerivedPreset(provider) && slugs.has(provider.serviceId));
+ const fragments = unmapped.filter((provider) => !declared.includes(provider));
+ if (fragments.length > 0) plan.imports = importGraphFromProviders({ providers: fragments }, mintId);
+ if (declared.length > 0) {
+ const onto = importDeclaredPresets(declared, graph, mintId);
+ plan.imports = {
+ connections: plan.imports.connections,
+ bindings: [...plan.imports.bindings, ...onto.bindings],
+ routes: [...plan.imports.routes, ...onto.routes],
+ };
+ }
return plan;
}
diff --git a/server/lib/providerGraphRecords.test.js b/server/lib/providerGraphRecords.test.js
index 38d79639d5..2b10751058 100644
--- a/server/lib/providerGraphRecords.test.js
+++ b/server/lib/providerGraphRecords.test.js
@@ -437,6 +437,72 @@ describe('a connection several harnesses share through different protocols', ()
});
});
+describe('derived presets declare the instance they sit on (#7565)', () => {
+ const SERVICE = { id: 'svc-nim', revision: 3, kind: 'gateway:nvidia-nim', label: 'NVIDIA NIM', 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'] } };
+ // A "Save as preset" of `direct.api@nvidia-nim`: its profile reads back as
+ // kind `api`, not `gateway:nvidia-nim` — containment alone would never place
+ // it on the instance it was derived from.
+ const DIRECT_PRESET = {
+ id: 'direct-api-nvidia-nim', name: 'Direct API · NVIDIA NIM', type: 'api', harnessId: 'direct', method: 'api', serviceId: 'nvidia-nim',
+ endpoint: 'https://integrate.api.nvidia.com/v1', apiKey: 'nim-key', enabled: true, models: ['nvidia/example'], envVars: {}, secretEnvVars: [],
+ };
+ const OPENCODE_PRESET = {
+ id: 'opencode-cli-nvidia-nim', name: 'OpenCode · NVIDIA NIM', type: 'cli', command: 'opencode', harnessId: 'opencode', method: 'cli', serviceId: 'nvidia-nim',
+ gatewayBacked: 'nvidia-nim', endpoint: 'https://integrate.api.nvidia.com/v1', enabled: true, models: ['nvidia/example'],
+ envVars: { OPENCODE_CONFIG_CONTENT: JSON.stringify({ permission: 'allow', provider: { 'nvidia-nim': { npm: '@ai-sdk/openai-compatible', name: 'NVIDIA NIM', options: { baseURL: 'https://integrate.api.nvidia.com/v1' } } } }), NVIDIA_API_KEY: 'nim-key' },
+ secretEnvVars: ['NVIDIA_API_KEY'],
+ };
+ const graphWith = () => ({ connections: [structuredClone(SERVICE)], bindings: [], routes: [] });
+
+ it('imports a saved preset ONTO the instance it names, never as a fragment of its own', () => {
+ const plan = planGraphReconciliation(graphWith(), [structuredClone(DIRECT_PRESET), structuredClone(OPENCODE_PRESET)], { mintId: minter('new') });
+ expect(plan.imports.connections).toEqual([]);
+ expect(plan.imports.bindings).toHaveLength(2);
+ expect(plan.imports.bindings.every((binding) => binding.connectionId === 'svc-nim')).toBe(true);
+ expect(plan.imports.bindings.map((binding) => binding.harnessId).sort()).toEqual([null, 'opencode']);
+ expect(plan.imports.routes.map((route) => route.providerId).sort()).toEqual(['direct-api-nvidia-nim', 'opencode-cli-nvidia-nim']);
+ // The projected snapshot is the record's own owned values, so the next pass is a no-op.
+ const direct = plan.imports.routes.find((route) => route.providerId === 'direct-api-nvidia-nim');
+ expect(direct.projected).toEqual(connectionOwnedSnapshot(DIRECT_PRESET));
+ });
+
+ it('takes a distinct variant key when the harness already sits on that instance', () => {
+ const graph = graphWith();
+ graph.bindings.push({ id: 'b-existing', revision: 1, connectionId: 'svc-nim', harnessId: 'opencode', variantKey: 'default', label: 'x', enabled: true, selectedModels: [] });
+ const plan = planGraphReconciliation(graph, [structuredClone(OPENCODE_PRESET)], { mintId: minter('new') });
+ expect(plan.imports.bindings[0]).toMatchObject({ connectionId: 'svc-nim', harnessId: 'opencode', variantKey: 'variant:opencode-cli-nvidia-nim' });
+ });
+
+ it('keeps a declared preset on its instance across passes even where containment would move it', () => {
+ const graph = graphWith();
+ graph.bindings.push({ id: 'b-direct', revision: 1, connectionId: 'svc-nim', harnessId: null, variantKey: 'default', label: 'x', enabled: true, selectedModels: [] });
+ graph.routes.push({ providerId: 'direct-api-nvidia-nim', bindingId: 'b-direct', mode: 'api', modelMap: {}, projected: connectionOwnedSnapshot(DIRECT_PRESET), pending: null, pendingRevision: null });
+ const plan = planGraphReconciliation(graph, [structuredClone(DIRECT_PRESET)], { mintId: minter('new') });
+ expect(reconciliationIsNoop(plan)).toBe(true);
+ expect(plan.regroups[0]).toMatchObject({ connectionAction: 'unchanged', bindingId: 'b-direct', routeIds: ['direct-api-nvidia-nim'] });
+ });
+
+ it('recovers an interrupted projection onto a derived preset like any route: retry while the file still holds the old value', () => {
+ const graph = graphWith();
+ graph.bindings.push({ id: 'b-direct', revision: 1, connectionId: 'svc-nim', harnessId: null, variantKey: 'default', label: 'x', enabled: true, selectedModels: [] });
+ const moved = connectionOwnedSnapshot({ ...DIRECT_PRESET, endpoint: 'https://nim.example.test/v1' });
+ graph.routes.push({ providerId: 'direct-api-nvidia-nim', bindingId: 'b-direct', mode: 'api', modelMap: {}, projected: connectionOwnedSnapshot(DIRECT_PRESET), pending: moved, pendingRevision: 2 });
+ const plan = planGraphReconciliation(graph, [structuredClone(DIRECT_PRESET)], { mintId: minter('new') });
+ expect(plan.retries).toEqual([{ providerId: 'direct-api-nvidia-nim', owned: moved }]);
+ expect(plan.conflicts).toEqual([]);
+ // Landed: the file already carries the new endpoint.
+ const landed = planGraphReconciliation(graph, [{ ...DIRECT_PRESET, endpoint: 'https://nim.example.test/v1' }], { mintId: minter('new') });
+ expect(landed.acknowledgements).toEqual([{ providerId: 'direct-api-nvidia-nim' }]);
+ });
+
+ it('still imports a preset naming an instance this graph does not have as its own fragment', () => {
+ const plan = planGraphReconciliation({ connections: [], bindings: [], routes: [] }, [structuredClone(DIRECT_PRESET)], { mintId: minter('new') });
+ expect(plan.imports.connections).toHaveLength(1);
+ expect(plan.imports.routes[0].providerId).toBe('direct-api-nvidia-nim');
+ });
+});
+
describe('a mode-only legacy edit stays route-scoped', () => {
it('changes no connection-owned value and plans no graph change', () => {
const providers = providersFixture();
diff --git a/server/lib/providerPresets.js b/server/lib/providerPresets.js
new file mode 100644
index 0000000000..8bd55dbf94
--- /dev/null
+++ b/server/lib/providerPresets.js
@@ -0,0 +1,402 @@
+import { isDeepStrictEqual } from 'node:util';
+import { isDerivedPreset } from './providerGraphRecords.js';
+import { providerConnectionProfile } from './providerConnections.js';
+import { harnessForProvider } from './providerHarnesses.js';
+import { parseOpencodeConfigContent } from './providerModels.js';
+import { materializeRouteOutcome } from './providerRouteRecipes.js';
+import { applyServicePlanFilter, instanceForConnection } from './providerServiceInstances.js';
+
+/**
+ * PRESETS (#7565, epic #7561): a stored `data/providers.json` record read as a
+ * named (harness, method, service) tuple plus the user's own selection
+ * defaults and overrides.
+ *
+ * A record carrying all three structural keys — `harnessId`, `method`,
+ * `serviceId` — is a DERIVED preset: on every save its connection-owned
+ * values (the program, the endpoint, the credential, the backend markers, the
+ * inline bootstrap, the catalog) are re-materialized from the service instance
+ * through `materializeRoute`, the same writer a composite id resolves through.
+ * A record without them is a LEGACY preset: fully hand-editable, executed
+ * exactly as before, and convertible only when re-deriving it reproduces what
+ * it already carries ({@link derivedPresetDrift}).
+ *
+ * `data/providers.json` stays the fully materialized execution contract: an
+ * older release runs a derived preset with no graph at all, because every
+ * derived value is written into the record, and the structural keys are
+ * additive and ignored by a schema that never saw them.
+ *
+ * Pure: no I/O, no clock, no spawn. Every input — the record, the harness row,
+ * the resolved service instance, the instance's catalog, the bootstrap app —
+ * arrives as data, so the merge rules are pinned without a store.
+ */
+
+/** The additive keys that make a record a derived preset (plus its two per-preset choices). */
+export const PRESET_STRUCTURAL_KEYS = Object.freeze(['harnessId', 'method', 'serviceId', 'catalogNarrowing', 'credentialBootstrapId']);
+
+/** The backend markers a service definition writes (`serviceMarkers` in providerRouteRecipes.js). */
+const BACKEND_MARKER_KEYS = Object.freeze(['ollamaBacked', 'lmstudioBacked', 'mtplxBacked', 'llamaBacked', 'vllmBacked', 'sglangBacked', 'gatewayBacked', 'orcarouterBacked']);
+
+/**
+ * The record keys the SERVICE owns on a derived preset — written by
+ * materialization, refused as a direct edit (`refusedDerivedEdits`). `envVars`
+ * is owned per NAME, not as a whole: the transport and credential variables
+ * the service writes are its own, while a harness-behaviour variable beside
+ * them (`ANTHROPIC_SMALL_FAST_MODEL`) stays the preset's.
+ */
+export const DERIVED_PRESET_OWNED_KEYS = Object.freeze(['type', 'command', 'endpoint', 'apiKey', 'secretEnvVars', 'credentialBootstrap', ...BACKEND_MARKER_KEYS]);
+
+/** `derived` when the three structural keys are set, else `legacy`. */
+export const presetKind = (record) => (isDerivedPreset(record) ? 'derived' : 'legacy');
+
+/**
+ * Whether a LEGACY preset is a candidate for conversion: a harness this build
+ * knows, spawned by the recipe's own binary (a path-configured `command` is a
+ * deliberate choice materialization would overwrite), and a connection profile
+ * with no isolation reason. The conversion itself still has to prove the
+ * fixpoint against the service — this is the editor's "offer the button" test.
+ */
+export function presetDerivable(record) {
+ if (!record || typeof record !== 'object' || isDerivedPreset(record)) return false;
+ const harness = harnessForProvider(record);
+ // A harness with no capability bindings (Kilo, OpenChamber) composes onto nothing.
+ if (!harness || harness.bindings.length === 0) return false;
+ if (harness.recipe && harness.recipe.command !== record.command) return false;
+ return providerConnectionProfile(record).reasons.length === 0;
+}
+
+/**
+ * The models a derived preset offers: the instance's plan-filtered catalog,
+ * narrowed to `catalogNarrowing` when the preset declares one (in the
+ * narrowing's own order, so a converted record keeps its list byte-for-byte).
+ *
+ * A catalog the service has not listed yet (`unknown`, or listed empty) falls
+ * back to the record's own models: "Save as preset" on a freshly created
+ * instance must not mint a preset with nothing to run, and a converted record
+ * must not lose the list it was running with.
+ */
+export function derivedPresetModels(record, instance, catalog) {
+ const listed = catalog?.state === 'known'
+ ? applyServicePlanFilter(instance.definition, instance.plan, Array.isArray(catalog.models) ? catalog.models : [])
+ : [];
+ if (listed.length === 0) return Array.isArray(record.models) ? [...record.models] : [];
+ if (!Array.isArray(record.catalogNarrowing)) return [...listed];
+ const known = new Set(listed);
+ return record.catalogNarrowing.filter((model) => known.has(model));
+}
+
+/**
+ * The inline OpenCode config's transport half, for comparison: which
+ * namespaces it declares and where each points. Permissions, agents and the
+ * display `name` are harness behaviour the preset owns.
+ */
+function opencodeTransportShape(raw) {
+ const parsed = parseOpencodeConfigContent(raw);
+ if (!parsed) return null;
+ const providers = parsed.provider && typeof parsed.provider === 'object' ? parsed.provider : {};
+ return Object.fromEntries(Object.keys(providers).sort().map((namespace) => [namespace, {
+ npm: providers[namespace]?.npm ?? null,
+ baseURL: providers[namespace]?.options?.baseURL ?? null,
+ }]));
+}
+
+/**
+ * The env map a derived preset carries: the record's route-owned variables
+ * with every service-written one laid over the top. The names the record's
+ * own profile reads as connection-owned are dropped unless the service writes
+ * them again — a key the service no longer supplies is not the preset's to keep.
+ *
+ * OpenCode's inline config is both transport and harness behaviour, so the
+ * record's own string is kept whenever it already declares the namespaces and
+ * base URLs the service would write: rewriting it would discard permissions
+ * and agent settings the user typed into it.
+ */
+function mergeDerivedEnv(record, materialized) {
+ const stored = record.envVars && typeof record.envVars === 'object' ? record.envVars : {};
+ const owned = providerConnectionProfile(record).owned.envVars;
+ const routeOwned = Object.fromEntries(Object.entries(stored).filter(([name]) => !Object.hasOwn(owned, name)));
+ const next = { ...routeOwned, ...materialized.envVars };
+ const keep = stored.OPENCODE_CONFIG_CONTENT;
+ const written = materialized.envVars.OPENCODE_CONFIG_CONTENT;
+ if (keep && written && isDeepStrictEqual(opencodeTransportShape(keep), opencodeTransportShape(written))) {
+ next.OPENCODE_CONFIG_CONTENT = keep;
+ }
+ return next;
+}
+
+const includesSequence = (list, sequence) => {
+ if (sequence.length === 0) return true;
+ for (let i = 0; i + sequence.length <= list.length; i += 1) {
+ if (sequence.every((token, j) => list[i + j] === token)) return true;
+ }
+ return false;
+};
+
+/**
+ * The argv a derived preset runs with. `args` is the preset's own to edit, so
+ * a stored list wins over the recipe's — but the tokens a BINDING appends
+ * (Pi's `--provider <name>`) select the service and are kept present whatever
+ * the user typed before them.
+ */
+function derivedPresetArgs(record, harness, materialized) {
+ const recipeArgs = harness.recipe?.modes?.[record.method]?.args ?? [];
+ const written = Array.isArray(materialized.args) ? materialized.args : [];
+ const suffix = written.slice(recipeArgs.length);
+ const base = Array.isArray(record.args) ? record.args : written;
+ return includesSequence(base, suffix) ? [...base] : [...base, ...suffix];
+}
+
+/** `{ command, args, harnessId, argsSeparator }` with the spawn-time defaults applied, for comparison. */
+const bootstrapShape = (bootstrap, harness) => (bootstrap?.command ? {
+ command: bootstrap.command,
+ args: Array.isArray(bootstrap.args) ? [...bootstrap.args] : [],
+ harnessId: bootstrap.harnessId ?? harness.recipe?.command ?? null,
+ argsSeparator: bootstrap.argsSeparator ?? '',
+} : null);
+
+/**
+ * The configured bootstrap app an INLINE `credentialBootstrap` object stands
+ * for, or `null`. Matched on what the spawn actually runs — command, args,
+ * separator, and the name the wrapper knows this harness by — never on the
+ * advisory `setupCommand`.
+ *
+ * @returns {{slug: string, app: object}|null}
+ */
+export function matchBootstrapApp(inline, harness, apps = {}) {
+ const wanted = bootstrapShape(inline, harness);
+ if (!wanted) return null;
+ for (const [slug, app] of Object.entries(apps || {})) {
+ const shape = bootstrapShape({ ...app, harnessId: app.harnessNames?.[harness.id] }, harness);
+ if (isDeepStrictEqual(shape, wanted)) return { slug, app };
+ }
+ return null;
+}
+
+/**
+ * The bootstrap input `materializeRoute` takes for a configured app: its slug
+ * as `id` plus the spawn columns. Shared with the composite resolver.
+ */
+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 } } : {}),
+});
+
+/**
+ * Re-derive a preset's connection-owned values from its service.
+ *
+ * `record` is the preset as stored (or as a save would store it), carrying the
+ * three structural keys; `harness` its registry row; `instance` the resolved
+ * service instance; `catalog` the instance's stored catalog; `bootstrap` the
+ * app its `credentialBootstrapId` names, already shaped by
+ * {@link bootstrapInputFor}. The result keeps every per-preset field — name,
+ * argv, timeouts, model pins, effort, fallback, generation params, consent
+ * flags, unknown custom fields — and rewrites only what the service owns.
+ *
+ * `ownedEnvNames` is the set of env variables the SERVICE wrote or the record
+ * had read as connection-owned, which is what a direct edit to the record is
+ * refused on.
+ *
+ * @returns {{record: object, error: null, ownedEnvNames: Set<string>}
+ * | {record: null, error: Error & {code: string, status: 400}, ownedEnvNames: null}}
+ */
+export function materializeDerivedPreset({ record, harness, instance, catalog = null, bootstrap = null }) {
+ const outcome = materializeRouteOutcome({
+ harness, method: record.method, serviceInstance: instance, bootstrap, providerId: record.id, name: record.name,
+ });
+ if (outcome.error) return { record: null, error: outcome.error, ownedEnvNames: null };
+ const materialized = outcome.record;
+
+ const envVars = mergeDerivedEnv(record, materialized);
+ const stored = new Set(Array.isArray(record.secretEnvVars) ? record.secretEnvVars : []);
+ const secretEnvVars = [...new Set([
+ ...materialized.secretEnvVars,
+ ...[...stored].filter((name) => Object.hasOwn(envVars, name)),
+ ])];
+
+ const derived = {
+ ...record,
+ id: record.id,
+ name: record.name ?? materialized.name,
+ type: record.method,
+ harnessId: harness.id,
+ method: record.method,
+ serviceId: instance.slug,
+ command: materialized.command ?? null,
+ // A direct API preset spawns nothing; `args` is written only where a program reads it.
+ ...(record.method === 'api' && !Array.isArray(record.args) ? {} : { args: derivedPresetArgs(record, harness, materialized) }),
+ endpoint: materialized.endpoint ?? null,
+ apiKey: materialized.apiKey ?? '',
+ envVars,
+ secretEnvVars,
+ models: derivedPresetModels(record, instance, catalog),
+ timeout: record.timeout ?? materialized.timeout,
+ };
+ for (const key of BACKEND_MARKER_KEYS) delete derived[key];
+ for (const key of BACKEND_MARKER_KEYS) if (Object.hasOwn(materialized, key)) derived[key] = materialized[key];
+ // `servicePlan` is a fact about the instance, read from it — never a stored snapshot.
+ delete derived.servicePlan;
+ if (record.method === 'cli' && !Array.isArray(record.headlessArgs)) derived.headlessArgs = materialized.headlessArgs ?? [];
+ if (record.method === 'tui' && record.tuiPromptDelayMs == null && materialized.tuiPromptDelayMs != null) {
+ derived.tuiPromptDelayMs = materialized.tuiPromptDelayMs;
+ }
+ if (materialized.credentialBootstrap) {
+ // `setupCommand` is advisory text the editor shows; the app row does not
+ // carry it into the spawn columns, so the record's own survives.
+ const setupCommand = record.credentialBootstrap?.setupCommand;
+ derived.credentialBootstrap = { ...(setupCommand ? { setupCommand } : {}), ...materialized.credentialBootstrap };
+ derived.credentialBootstrapId = bootstrap?.id ?? record.credentialBootstrapId;
+ } else {
+ delete derived.credentialBootstrap;
+ delete derived.credentialBootstrapId;
+ }
+ const ownedEnvNames = new Set([
+ ...Object.keys(providerConnectionProfile(record).owned.envVars),
+ ...Object.keys(materialized.envVars),
+ ]);
+ return { record: derived, error: null, ownedEnvNames };
+}
+
+const sameSet = (a, b) => a.length === b.length && a.every((item) => b.includes(item));
+const orNull = (value) => value ?? null;
+
+/**
+ * The connection-owned keys on which `derived` disagrees with `record` —
+ * empty when re-deriving the record is a FIXPOINT, which is the one condition
+ * under which a legacy preset may be converted without changing how it runs.
+ */
+export function derivedPresetDrift(record, derived, harness) {
+ const drift = [];
+ for (const key of ['type', 'command', ...BACKEND_MARKER_KEYS]) {
+ if (!isDeepStrictEqual(orNull(record[key]), orNull(derived[key]))) drift.push(key);
+ }
+ // A wrapper that names its endpoint only inside its env or inline config
+ // (every shipped OpenCode-on-Ollama sample) gains the field; that changes
+ // what the readiness probe reads, never what the program runs.
+ if (typeof record.endpoint === 'string' && record.endpoint !== '' && record.endpoint !== orNull(derived.endpoint)) drift.push('endpoint');
+ if ((record.apiKey ?? '') !== (derived.apiKey ?? '')) drift.push('apiKey');
+ if (!isDeepStrictEqual(record.envVars ?? {}, derived.envVars)) drift.push('envVars');
+ if (!sameSet(Array.isArray(record.secretEnvVars) ? record.secretEnvVars : [], derived.secretEnvVars)) drift.push('secretEnvVars');
+ if (!isDeepStrictEqual(bootstrapShape(record.credentialBootstrap, harness), bootstrapShape(derived.credentialBootstrap, harness))) {
+ drift.push('credentialBootstrap');
+ }
+ if (!isDeepStrictEqual(Array.isArray(record.models) ? record.models : [], derived.models)) drift.push('models');
+ return drift;
+}
+
+/**
+ * The keys of `updates` that would move a connection-owned value away from
+ * what the service derives — the edits a derived preset refuses, pointing at
+ * the service instead. Equal values are a no-op, not a refusal: the editor
+ * sends the whole record back on every save.
+ *
+ * @param {object} updates - the patch a client sent (secrets already restored)
+ * @param {object} derived - the record materialization would store
+ * @param {Set<string>} ownedEnvNames - from {@link materializeDerivedPreset}
+ * @returns {string[]}
+ */
+export function refusedDerivedEdits(updates, derived, ownedEnvNames) {
+ const refused = [];
+ for (const key of DERIVED_PRESET_OWNED_KEYS) {
+ if (!Object.hasOwn(updates, key)) continue;
+ const sent = key === 'apiKey' ? (updates[key] ?? '') : key === 'secretEnvVars' ? null : orNull(updates[key]);
+ const kept = key === 'apiKey' ? (derived[key] ?? '') : key === 'secretEnvVars' ? null : orNull(derived[key]);
+ if (key === 'secretEnvVars') {
+ if (!sameSet(Array.isArray(updates[key]) ? updates[key] : [], derived[key])) refused.push(key);
+ continue;
+ }
+ if (!isDeepStrictEqual(sent, kept)) refused.push(key);
+ }
+ if (updates.envVars && typeof updates.envVars === 'object') {
+ for (const name of ownedEnvNames) {
+ if ((updates.envVars[name] ?? null) !== (derived.envVars[name] ?? null)) refused.push(`envVars.${name}`);
+ }
+ }
+ return refused;
+}
+
+/** The keys of `derived` whose value differs from `record` — the patch a re-projection writes. */
+export function derivedPresetPatch(record, derived) {
+ const patch = {};
+ for (const [key, value] of Object.entries(derived)) {
+ if (!isDeepStrictEqual(record[key], value)) patch[key] = value;
+ }
+ for (const key of Object.keys(record)) {
+ if (!Object.hasOwn(derived, key)) patch[key] = undefined;
+ }
+ return patch;
+}
+
+/** The catalog listing a backfill compares a record's models against — the same rule as {@link derivedPresetModels}. */
+const listedModels = (instance, catalog) => (catalog?.state === 'known'
+ ? applyServicePlanFilter(instance.definition, instance.plan, Array.isArray(catalog.models) ? catalog.models : [])
+ : []);
+
+/**
+ * The boot-time backfill (#7565): every LEGACY record the graph already routes
+ * onto a named service instance, stamped with the structural keys that make it
+ * a derived preset — but ONLY when re-deriving it from that service reproduces
+ * every connection-owned value it carries today. The patch is additive
+ * (`harnessId`, `method`, `serviceId`, an optional `credentialBootstrapId` for
+ * an inline bootstrap matching a configured app, and a `catalogNarrowing` when
+ * the record lists a subset of the catalog), so the file diff is keys added
+ * and nothing rewritten.
+ *
+ * Row-derived, idempotent (a stamped record is skipped) and never a seed:
+ * it needs the graph, so it rides the reconcile pass exactly as the
+ * service-column backfill does. Everything it refuses is reported with a
+ * reason so a human can see why a record stayed legacy.
+ *
+ * @param {{graph: {connections: object[], bindings: object[], routes: object[]},
+ * providers: object[], bootstraps?: object, env?: object}} input
+ * @returns {{patches: Record<string, object>, skipped: {id: string, reason: string}[]}}
+ */
+export function planPresetBackfill({ graph, providers, bootstraps = {}, env = process.env }) {
+ const routes = new Map(graph.routes.map((route) => [route.providerId, route]));
+ const bindings = new Map(graph.bindings.map((binding) => [binding.id, binding]));
+ const connections = new Map(graph.connections.map((connection) => [connection.id, connection]));
+ const patches = {};
+ const skipped = [];
+
+ for (const record of providers) {
+ if (!record || typeof record !== 'object' || !record.id || isDerivedPreset(record)) continue;
+ const skip = (reason) => skipped.push({ id: record.id, reason });
+ const route = routes.get(record.id);
+ if (!route) { skip('unmapped'); continue; }
+ const connection = connections.get(bindings.get(route.bindingId)?.connectionId);
+ if (!connection?.slug) { skip('service-unnamed'); continue; }
+ const instance = instanceForConnection(connection, env);
+ if (!instance) { skip('service-undefined'); continue; }
+ const harness = harnessForProvider(record);
+ if (!harness) { skip('harness-unknown'); continue; }
+ if (harness.recipe && harness.recipe.command !== record.command) { skip('command-differs'); continue; }
+
+ const match = matchBootstrapApp(record.credentialBootstrap, harness, bootstraps);
+ if (record.credentialBootstrap?.command && !match) { skip('bootstrap-unmatched'); continue; }
+ const structural = {
+ harnessId: harness.id,
+ method: record.type,
+ serviceId: connection.slug,
+ ...(match ? { credentialBootstrapId: match.slug } : {}),
+ };
+ const listed = listedModels(instance, connection.catalog);
+ const models = Array.isArray(record.models) ? record.models : [];
+ if (listed.length > 0 && !isDeepStrictEqual(listed, models) && models.every((model) => listed.includes(model))) {
+ structural.catalogNarrowing = [...models];
+ }
+
+ const { record: derived, error } = materializeDerivedPreset({
+ record: { ...record, ...structural },
+ harness,
+ instance,
+ catalog: connection.catalog,
+ bootstrap: match ? bootstrapInputFor(match.slug, match.app) : null,
+ });
+ if (error) { skip(error.code); continue; }
+ const drift = derivedPresetDrift(record, derived, harness);
+ if (drift.length > 0) { skip(`drift:${drift.join(',')}`); continue; }
+ patches[record.id] = structural;
+ }
+ return { patches, skipped };
+}
diff --git a/server/lib/providerPresets.test.js b/server/lib/providerPresets.test.js
new file mode 100644
index 0000000000..25d0298c9b
--- /dev/null
+++ b/server/lib/providerPresets.test.js
@@ -0,0 +1,211 @@
+/**
+ * The preset contract (#7565): what a DERIVED preset keeps as its own, what it
+ * takes from its service on every save, which direct edits are refused, and
+ * the boot-time backfill's one rule — a legacy record is stamped only when
+ * re-deriving it is a fixpoint.
+ *
+ * The 55 shipped samples are the fixture for the backfill because they are
+ * the file every install starts from; everything else is synthetic. Nothing
+ * here is read out of a running install.
+ */
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { harnessById } from './providerHarnesses.js';
+import { importGraphFromProviders, isDerivedPreset } from './providerGraphRecords.js';
+import { instanceForConnection, planServiceColumnBackfill, takenServiceSlugs } from './providerServiceInstances.js';
+import { resolveServiceInstance } from './serviceDefinitions.js';
+import {
+ PRESET_STRUCTURAL_KEYS,
+ bootstrapInputFor,
+ derivedPresetDrift,
+ derivedPresetPatch,
+ materializeDerivedPreset,
+ matchBootstrapApp,
+ planPresetBackfill,
+ presetDerivable,
+ refusedDerivedEdits,
+} from './providerPresets.js';
+
+const SAMPLES = JSON.parse(readFileSync(
+ resolve(dirname(fileURLToPath(import.meta.url)), 'aiToolkit/defaults/providers.sample.json'), 'utf8',
+)).providers;
+
+const OLLAMA = resolveServiceInstance({
+ definitionId: 'ollama', slug: 'ollama', plan: 'local',
+ transports: { anthropic: { baseUrl: 'http://127.0.0.1:11434' }, openai: { baseUrl: 'http://127.0.0.1:11434/v1' } },
+ credentials: { apiKey: 'ollama' },
+});
+const KNOWN = { state: 'known', models: ['example-llama', 'example-qwen'] };
+
+/** A Claude-on-Ollama derived preset with per-preset choices and a route-owned env var beside the service's. */
+const claudePreset = (extra = {}) => ({
+ id: 'claude-local', name: 'Claude · local', type: 'cli', method: 'cli', harnessId: 'claude', serviceId: 'ollama',
+ command: 'claude', args: ['--print'], timeout: 42000, effort: 'high', defaultModel: 'example-qwen', someFutureField: { keep: true },
+ envVars: { ANTHROPIC_SMALL_FAST_MODEL: 'example-llama', ANTHROPIC_BASE_URL: 'http://old.example.test', ANTHROPIC_AUTH_TOKEN: 'stale' },
+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'], models: ['stale-model'], ...extra,
+});
+
+describe('materializeDerivedPreset', () => {
+ it('rewrites what the service owns and keeps every per-preset field, unknown ones included', () => {
+ const { record, error, ownedEnvNames } = materializeDerivedPreset({ record: claudePreset(), harness: harnessById('claude'), instance: OLLAMA, catalog: KNOWN });
+ expect(error).toBeNull();
+ expect(record).toMatchObject({
+ id: 'claude-local', name: 'Claude · local', type: 'cli', command: 'claude', ollamaBacked: true,
+ timeout: 42000, effort: 'high', defaultModel: 'example-qwen', someFutureField: { keep: true },
+ envVars: { ANTHROPIC_SMALL_FAST_MODEL: 'example-llama', ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' },
+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'], models: ['example-llama', 'example-qwen'],
+ });
+ expect(record).not.toHaveProperty('servicePlan');
+ expect([...ownedEnvNames].sort()).toEqual(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL']);
+ });
+
+ it('narrows the catalog in the narrowing\'s own order, and falls back to the record\'s models while the service has listed none', () => {
+ const narrowed = materializeDerivedPreset({ record: claudePreset({ catalogNarrowing: ['example-qwen', 'retired'] }), harness: harnessById('claude'), instance: OLLAMA, catalog: KNOWN });
+ expect(narrowed.record.models).toEqual(['example-qwen']);
+ const unlisted = materializeDerivedPreset({ record: claudePreset(), harness: harnessById('claude'), instance: OLLAMA, catalog: { state: 'unknown', models: [] } });
+ expect(unlisted.record.models).toEqual(['stale-model']);
+ });
+
+ it('keeps the binding\'s argv suffix present whatever the user typed before it', () => {
+ const nim = resolveServiceInstance({ definitionId: 'nvidia-nim', slug: 'nim', plan: 'free', credentials: { apiKey: 'k' } });
+ const record = { id: 'pi-nim', name: 'Pi', type: 'tui', method: 'tui', harnessId: 'pi', serviceId: 'nim', args: ['--approve', '--verbose'] };
+ expect(materializeDerivedPreset({ record, harness: harnessById('pi'), instance: nim }).record.args).toEqual(['--approve', '--verbose', '--provider', 'nvidia']);
+ });
+
+ it('keeps the record\'s own OpenCode inline config when it already reaches the service', () => {
+ const shipped = SAMPLES['opencode-ollama'];
+ const record = { ...shipped, harnessId: 'opencode', method: 'cli', serviceId: 'ollama' };
+ const local = resolveServiceInstance({ definitionId: 'ollama', slug: 'ollama', transports: { openai: { baseUrl: JSON.parse(shipped.envVars.OPENCODE_CONFIG_CONTENT).provider.ollama.options.baseURL } } });
+ const { record: derived } = materializeDerivedPreset({ record, harness: harnessById('opencode'), instance: local });
+ expect(derived.envVars.OPENCODE_CONFIG_CONTENT).toBe(shipped.envVars.OPENCODE_CONFIG_CONTENT);
+ const moved = resolveServiceInstance({ definitionId: 'ollama', slug: 'ollama', transports: { openai: { baseUrl: 'http://127.0.0.1:9999/v1' } } });
+ const rewritten = materializeDerivedPreset({ record, harness: harnessById('opencode'), instance: moved }).record;
+ expect(JSON.parse(rewritten.envVars.OPENCODE_CONFIG_CONTENT).provider.ollama.options.baseURL).toBe('http://127.0.0.1:9999/v1');
+ });
+
+ it('writes the bootstrap app as the inline object the spawner reads, and drops a stale inline one', () => {
+ const app = { label: 'Corp', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } };
+ const anthropic = resolveServiceInstance({ definitionId: 'anthropic', slug: 'anthropic', credentialVia: 'bootstrap' });
+ const record = claudePreset({ serviceId: 'anthropic', credentialBootstrapId: 'corp-auth', credentialBootstrap: { setupCommand: 'brew install corp', command: 'old' } });
+ const { record: derived } = materializeDerivedPreset({ record, harness: harnessById('claude'), instance: anthropic, bootstrap: bootstrapInputFor('corp-auth', app) });
+ expect(derived.credentialBootstrap).toEqual({ setupCommand: 'brew install corp', command: 'corp-auth', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' });
+ const without = materializeDerivedPreset({ record: { ...record, credentialBootstrapId: undefined }, harness: harnessById('claude'), instance: { ...anthropic, credentialVia: 'stored', credentials: { apiKey: 'k' } } }).record;
+ expect(without).not.toHaveProperty('credentialBootstrap');
+ expect(without).not.toHaveProperty('credentialBootstrapId');
+ });
+
+ it('carries the service\'s refusal as a typed error rather than a half record', () => {
+ const { record, error } = materializeDerivedPreset({ record: claudePreset(), harness: harnessById('claude'), instance: resolveServiceInstance({ definitionId: 'nvidia-nim', slug: 'nim' }) });
+ expect(record).toBeNull();
+ expect(error).toMatchObject({ code: 'HARNESS_SERVICE_INCOMPATIBLE', status: 400 });
+ });
+});
+
+describe('refusedDerivedEdits', () => {
+ const { record: derived, ownedEnvNames } = materializeDerivedPreset({ record: claudePreset(), harness: harnessById('claude'), instance: OLLAMA, catalog: KNOWN });
+
+ it('names a connection-owned value the client moved, and nothing it merely echoed back', () => {
+ expect(refusedDerivedEdits({ ...derived }, derived, ownedEnvNames)).toEqual([]);
+ expect(refusedDerivedEdits({ command: '/opt/bin/claude', apiKey: 'typed', envVars: { ...derived.envVars, ANTHROPIC_BASE_URL: 'http://elsewhere.test' } }, derived, ownedEnvNames))
+ .toEqual(['command', 'apiKey', 'envVars.ANTHROPIC_BASE_URL']);
+ });
+
+ it('lets the preset\'s own env vars, argv, pins and effort through', () => {
+ expect(refusedDerivedEdits({ args: ['--print', '--verbose'], effort: 'low', envVars: { ...derived.envVars, ANTHROPIC_SMALL_FAST_MODEL: 'other' } }, derived, ownedEnvNames)).toEqual([]);
+ });
+});
+
+describe('derivedPresetPatch', () => {
+ it('is only what changed, with a dropped key written as undefined', () => {
+ const before = claudePreset({ credentialBootstrap: { command: 'gone' } });
+ const { record: derived } = materializeDerivedPreset({ record: before, harness: harnessById('claude'), instance: OLLAMA, catalog: KNOWN });
+ const patch = derivedPresetPatch(before, derived);
+ expect(patch).toMatchObject({ envVars: derived.envVars, models: derived.models, ollamaBacked: true });
+ for (const kept of ['name', 'effort', 'timeout', 'someFutureField', 'harnessId']) expect(patch).not.toHaveProperty(kept);
+ expect(patch.credentialBootstrap).toBeUndefined();
+ expect(Object.hasOwn(patch, 'credentialBootstrap')).toBe(true);
+ });
+});
+
+describe('matchBootstrapApp', () => {
+ const apps = { 'corp-auth': { label: 'Corp', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } } };
+ it('matches on what the spawn runs, harness name included, and never on the advisory setup command', () => {
+ expect(matchBootstrapApp({ command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessId: 'claude-code', setupCommand: 'anything' }, harnessById('claude'), apps)?.slug).toBe('corp-auth');
+ expect(matchBootstrapApp({ command: 'corp-auth', args: ['run'], argsSeparator: '--' }, harnessById('claude'), apps)).toBeNull();
+ // No name configured for Codex means the wrapper calls it by its binary — so a bare inline matches, a renamed one does not.
+ expect(matchBootstrapApp({ command: 'corp-auth', args: ['run'], argsSeparator: '--' }, harnessById('codex'), apps)?.slug).toBe('corp-auth');
+ expect(matchBootstrapApp({ command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessId: 'codex-cli' }, harnessById('codex'), apps)).toBeNull();
+ });
+});
+
+describe('presetDerivable', () => {
+ it('offers conversion only for a legacy record on a known harness, its own binary, with a clean profile', () => {
+ expect(presetDerivable(SAMPLES['claude-ollama'])).toBe(true);
+ expect(presetDerivable({ ...SAMPLES['claude-ollama'], harnessId: 'claude', method: 'cli', serviceId: 'ollama' })).toBe(false);
+ expect(presetDerivable({ ...SAMPLES['claude-ollama'], command: '/opt/bin/claude' })).toBe(false);
+ expect(presetDerivable({ ...SAMPLES['claude-ollama'], envVars: { ...SAMPLES['claude-ollama'].envVars, ANTHROPIC_BASE_URL: '$DAEMON' } })).toBe(false);
+ expect(presetDerivable(SAMPLES['kilo-cli'])).toBe(false);
+ });
+});
+
+describe('planPresetBackfill over the shipped samples', () => {
+ const providers = Object.values(SAMPLES).map((record) => structuredClone(record));
+ let n = 0;
+ const graph = importGraphFromProviders({ providers }, () => `id-${(n += 1)}`);
+ for (const row of planServiceColumnBackfill(graph, takenServiceSlugs(graph.connections))) {
+ Object.assign(graph.connections.find((connection) => connection.id === row.id), row);
+ }
+ const { patches, skipped } = planPresetBackfill({ graph, providers, bootstraps: {}, env: {} });
+
+ it('stamps every routed record whose re-derivation is a fixpoint, with the structural keys only', () => {
+ expect(Object.keys(patches).length).toBeGreaterThanOrEqual(30);
+ for (const patch of Object.values(patches)) {
+ expect(Object.keys(patch).every((key) => PRESET_STRUCTURAL_KEYS.includes(key))).toBe(true);
+ expect(patch).toMatchObject({ harnessId: expect.any(String), method: expect.any(String), serviceId: expect.any(String) });
+ }
+ // The motivating example: a CLI/TUI pair on one daemon, and a direct API record.
+ expect(patches['claude-ollama']).toEqual({ harnessId: 'claude', method: 'cli', serviceId: 'ollama' });
+ expect(patches['claude-ollama-tui']).toEqual({ harnessId: 'claude', method: 'tui', serviceId: 'ollama' });
+ expect(patches.slotstream).toMatchObject({ harnessId: 'direct', method: 'api' });
+ });
+
+ it('turns two records sharing one endpoint into two narrowings of one instance', () => {
+ expect(patches['nvidia-nim'].serviceId).toBe(patches['nvidia-kimi'].serviceId);
+ expect(patches['nvidia-nim'].catalogNarrowing).toEqual(SAMPLES['nvidia-nim'].models);
+ expect(patches['nvidia-kimi'].catalogNarrowing).toEqual(SAMPLES['nvidia-kimi'].models);
+ });
+
+ it('leaves each unmappable or drifting record legacy with a reason, never a guess', () => {
+ const reasons = Object.fromEntries(skipped.map(({ id, reason }) => [id, reason]));
+ expect(reasons['pi-cli']).toBe('service-undefined');
+ expect(reasons['kilo-cli']).toBe('service-undefined');
+ expect(reasons['opencode-zen-cli']).toBe('SERVICE_CREDENTIAL_REQUIRED');
+ // The legacy per-gateway marker is not what a service writes.
+ expect(reasons['opencode-orcarouter']).toMatch(/^drift:.*orcarouterBacked/);
+ for (const id of Object.keys(reasons)) expect(patches).not.toHaveProperty(id);
+ });
+
+ it('is additive — a stamped file differs from the shipped one by added keys alone — and a second pass stamps nothing', () => {
+ const stamped = providers.map((record) => ({ ...record, ...(patches[record.id] || {}) }));
+ for (const record of stamped) {
+ const original = SAMPLES[record.id];
+ for (const key of Object.keys(original)) expect(record[key]).toEqual(original[key]);
+ if (patches[record.id]) expect(isDerivedPreset(record)).toBe(true);
+ }
+ expect(planPresetBackfill({ graph, providers: stamped, bootstraps: {}, env: {} }).patches).toEqual({});
+ });
+
+ it('proves the fixpoint it stamped on: re-deriving a stamped record changes no connection-owned value', () => {
+ for (const record of providers) {
+ const patch = patches[record.id];
+ if (!patch) continue;
+ const connection = graph.connections.find((row) => row.slug === patch.serviceId);
+ const instance = instanceForConnection(connection, {});
+ const harness = harnessById(patch.harnessId);
+ const { record: derived } = materializeDerivedPreset({ record: { ...record, ...patch }, harness, instance, catalog: connection.catalog });
+ expect(derivedPresetDrift(record, derived, harness), record.id).toEqual([]);
+ }
+ });
+});
diff --git a/server/lib/providerServiceInstances.js b/server/lib/providerServiceInstances.js
index 2796866604..cd628bb4fa 100644
--- a/server/lib/providerServiceInstances.js
+++ b/server/lib/providerServiceInstances.js
@@ -8,6 +8,7 @@ import {
SERVICE_FAMILIES,
SERVICE_PLANS,
SERVICE_SLUG_RE,
+ resolveServiceInstance,
serviceDefinitionById,
serviceDefinitionForLocalRuntime,
} from './serviceDefinitions.js';
@@ -105,6 +106,38 @@ export function instanceApiKeyFor(connection, definition, env) {
return firstNamed(stored, [...definition.credential.envVars, ...CONNECTION_CREDENTIAL_ENV_VARS]);
}
+/**
+ * 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).
+ *
+ * A stored row OUTLIVES the definition it names: installs upgrade on their own
+ * schedule, so a release that drops or renames a plan leaves existing rows on
+ * the old one. `resolveServiceInstance` THROWS on a plan the definition no
+ * longer sells (and on a slug that predates `SERVICE_SLUG_RE`), and the
+ * composition catalog maps this over EVERY connection — so one stale row would
+ * take down the whole surface instead of dropping the single service it
+ * describes. Answer `null` for it, exactly as for an unknown definition.
+ *
+ * @param {object} connection - a store row
+ * @param {Record<string, string|undefined>} [env]
+ */
+export function instanceForConnection(connection, env = process.env) {
+ const definition = connection?.definitionId ? serviceDefinitionById(connection.definitionId) : null;
+ if (!definition || !connection.slug) return null;
+ const plan = connection.plan ?? definition.plans[0];
+ if (!definition.plans.includes(plan) || !SERVICE_SLUG_RE.test(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,
+ });
+}
+
/** 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.js
index 602c6e3206..cc084ab751 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -19,6 +19,7 @@ import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { MODEL_ALIAS_LIMITS } from './providerModelAliases.js';
import { PROVIDER_HARNESS_IDS, ROUTE_MODES } from './providerHarnesses.js';
+import { parseProviderRef } from './providerRef.js';
import { SERVICE_CREDENTIAL_VIAS, SERVICE_PLANS, SERVICE_SLUG_RE } from './serviceDefinitions.js';
import { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';
import {
@@ -568,7 +569,15 @@ export const providerSchema = z.object({
envVars: z.record(z.string()).optional(),
headlessArgs: z.array(z.string()).optional(),
tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),
- tuiIdleTimeoutMs: z.number().int().min(1000).max(86400000).optional()
+ tuiIdleTimeoutMs: z.number().int().min(1000).max(86400000).optional(),
+ // Preset structure (#7565), in parity with the toolkit schema: the harness,
+ // method and service slug a DERIVED preset is materialized from, the
+ // optional catalog narrowing, and the bootstrap app it spawns through.
+ harnessId: z.enum(PROVIDER_HARNESS_IDS).nullable().optional(),
+ method: z.enum(ROUTE_MODES).nullable().optional(),
+ serviceId: z.string().trim().min(1).max(64).regex(SERVICE_SLUG_RE).nullable().optional(),
+ catalogNarrowing: z.array(z.string().trim().min(1).max(512)).max(1000).nullable().optional(),
+ credentialBootstrapId: z.string().trim().min(1).max(64).regex(SERVICE_SLUG_RE).nullable().optional(),
});
// POST /api/providers/:id/test-vision.
@@ -2280,6 +2289,24 @@ export const credentialBootstrapsSettingsSchema = z.record(
credentialBootstrapSchema,
);
+/**
+ * `POST /api/providers/presets` (#7565) — "Save as preset": a composite id
+ * becomes a stored, derived preset. The composite's own grammar is checked
+ * here; whether it is RUNNABLE (harness enabled, service known, compatible) is
+ * the resolver's verdict, published as a 400 with its code. `effort` is
+ * validated against the harness's ladder in the service, not against a flat
+ * enum: which rungs exist is a per-harness (and per-model) fact.
+ */
+export const providerPresetCreateSchema = z.object({
+ compositeId: providerRefSchema.refine((value) => parseProviderRef(value)?.kind === 'composite', {
+ message: 'compositeId must be a composite <harness>.<cli|tui|api>@<service-slug>[+<bootstrap-slug>]',
+ }),
+ id: presetProviderIdSchema.optional(),
+ name: z.string().trim().min(1).max(100).optional(),
+ model: z.string().trim().min(1).max(512).nullable().optional(),
+ effort: z.string().trim().min(1).max(20).nullable().optional(),
+}).strict();
+
/** `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/routes/providers.composite.test.js b/server/routes/providers.composite.test.js
index 9a7f3a7ec0..5bb55d2fae 100644
--- a/server/routes/providers.composite.test.js
+++ b/server/routes/providers.composite.test.js
@@ -1,10 +1,13 @@
/**
* 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.
+ * composite, and the preset-only refusal on `PUT /active` — plus the preset
+ * surface (#7565): "Save as preset", "Convert to derived preset", the
+ * derived-aware save on PUT /:id and POST /, and the `presetKind` /
+ * `presetDerivable` decoration. 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. One file for
+ * both because they mount the same router (server/AGENTS.md "Import scoping").
*/
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -13,7 +16,7 @@ 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 { errorMiddleware, ServerError } from '../lib/errorHandler.js';
import { request } from '../lib/testHelper.js';
const compositeService = vi.hoisted(() => ({ describeCompositeProvider: vi.fn(), buildProviderCatalog: vi.fn() }));
@@ -24,6 +27,10 @@ const bootstrapService = vi.hoisted(() => ({ listCredentialBootstraps: 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 }));
+const presetService = vi.hoisted(() => ({
+ createPresetFromComposite: vi.fn(), derivePreset: vi.fn(), materializeStoredPreset: vi.fn(), savesAsDerivedPreset: vi.fn(),
+}));
+vi.mock('../services/providerPresets.js', () => presetService);
import { createPortOSProviderRoutes } from './providers.js';
const COMPOSITE = 'pi.tui@nvidia-nim';
@@ -37,8 +44,11 @@ const materialized = () => {
return record;
};
const PRESET = { id: 'claude-code', name: 'Claude', type: 'cli', command: 'claude', enabled: true, apiKey: 'preset-secret', envVars: {}, secretEnvVars: [] };
+// A stored DERIVED preset and a LEGACY one the server reports convertible (#7565).
+const DERIVED = { id: 'pi-tui-nvidia-nim-free', name: 'Pi · NIM', type: 'tui', command: 'pi', harnessId: 'pi', method: 'tui', serviceId: 'nvidia-nim-free', enabled: true, apiKey: '', envVars: { NVIDIA_API_KEY: 'nim-key' }, secretEnvVars: ['NVIDIA_API_KEY'], models: ['nvidia/example'] };
+const LEGACY = { id: 'claude-ollama', name: 'Claude', type: 'cli', command: 'claude', ollamaBacked: true, enabled: true, apiKey: '', envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' }, secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'], models: [] };
-const providerService = { getAllProviders: vi.fn(), getProviderById: vi.fn(), setActiveProvider: vi.fn() };
+const providerService = { getAllProviders: vi.fn(), getProviderById: vi.fn(), setActiveProvider: vi.fn(), updateProvider: vi.fn(), createProvider: vi.fn() };
const app = () => {
const server = express();
server.use(express.json());
@@ -50,7 +60,11 @@ const app = () => {
beforeEach(() => {
vi.clearAllMocks();
providerService.getAllProviders.mockResolvedValue({ activeProvider: 'claude-code', providers: [PRESET] });
- providerService.getProviderById.mockImplementation(async (id) => (id === COMPOSITE ? materialized() : id === 'claude-code' ? PRESET : null));
+ providerService.getProviderById.mockImplementation(async (id) => (id === COMPOSITE ? materialized() : [PRESET, DERIVED, LEGACY].find((record) => record.id === id) ?? null));
+ providerService.updateProvider.mockImplementation(async (id, updates) => ({ ...(await providerService.getProviderById(id)), ...updates }));
+ providerService.createProvider.mockImplementation(async (body) => ({ ...body }));
+ presetService.savesAsDerivedPreset.mockImplementation((candidate) => Boolean(candidate.harnessId && candidate.method && candidate.serviceId));
+ presetService.materializeStoredPreset.mockImplementation(async (candidate) => ({ ...candidate, rederived: true }));
});
describe('PUT /api/providers/active', () => {
@@ -144,3 +158,92 @@ describe('harnesses and bootstraps', () => {
expect(bootstrapService.saveCredentialBootstraps).toHaveBeenCalledTimes(1);
});
});
+
+describe('GET /api/providers — preset structure (#7565)', () => {
+ it('decorates every record with its preset kind and whether it can be converted', async () => {
+ providerService.getAllProviders.mockResolvedValue({ activeProvider: 'claude-ollama', providers: [DERIVED, LEGACY] });
+ const res = await request(app()).get('/api/providers');
+ expect(res.status).toBe(200);
+ const byId = Object.fromEntries(res.body.providers.map((provider) => [provider.id, provider]));
+ expect(byId['pi-tui-nvidia-nim-free']).toMatchObject({ presetKind: 'derived', presetDerivable: false, serviceId: 'nvidia-nim-free', envVars: { NVIDIA_API_KEY: '***' } });
+ expect(byId['claude-ollama']).toMatchObject({ presetKind: 'legacy', presetDerivable: true });
+ expect(JSON.stringify(res.body)).not.toContain('nim-key');
+ });
+});
+
+describe('POST /api/providers/presets', () => {
+ it('validates the body, hands it to the service, and answers the created preset sanitized', async () => {
+ presetService.createPresetFromComposite.mockResolvedValue({ ...DERIVED, apiKey: 'nim-key' });
+ const res = await request(app()).post('/api/providers/presets').send({ compositeId: 'pi.tui@nvidia-nim-free', model: 'nvidia/example', effort: 'high' });
+ expect(res.status).toBe(201);
+ expect(presetService.createPresetFromComposite).toHaveBeenCalledWith({ compositeId: 'pi.tui@nvidia-nim-free', model: 'nvidia/example', effort: 'high' });
+ expect(res.body).toMatchObject({ id: 'pi-tui-nvidia-nim-free', presetKind: 'derived', hasApiKey: true, envVars: { NVIDIA_API_KEY: '***' } });
+ expect(JSON.stringify(res.body)).not.toContain('nim-key');
+ });
+
+ it('refuses a preset id where a composite is required, and a stray key, before the service is reached', async () => {
+ expect((await request(app()).post('/api/providers/presets').send({ compositeId: 'claude-code' })).status).toBe(400);
+ expect((await request(app()).post('/api/providers/presets').send({ compositeId: 'pi.tui@nvidia-nim-free', apiKey: 'x' })).status).toBe(400);
+ expect(presetService.createPresetFromComposite).not.toHaveBeenCalled();
+ });
+
+ it('publishes the resolver\'s refusal as the service raised it', async () => {
+ presetService.createPresetFromComposite.mockRejectedValue(new ServerError('Pi is switched off', { status: 400, code: 'harness-disabled' }));
+ const res = await request(app()).post('/api/providers/presets').send({ compositeId: 'pi.tui@nvidia-nim-free' });
+ expect(res.status).toBe(400);
+ expect(res.body).toMatchObject({ code: 'harness-disabled' });
+ });
+});
+
+describe('POST /api/providers/:id/derive', () => {
+ it('converts through the service and answers the stamped record', async () => {
+ presetService.derivePreset.mockResolvedValue({ ...LEGACY, harnessId: 'claude', method: 'cli', serviceId: 'ollama' });
+ const res = await request(app()).post('/api/providers/claude-ollama/derive');
+ expect(res.status).toBe(200);
+ expect(presetService.derivePreset).toHaveBeenCalledWith('claude-ollama');
+ expect(res.body).toMatchObject({ presetKind: 'derived', serviceId: 'ollama', envVars: { ANTHROPIC_AUTH_TOKEN: '***' } });
+ });
+
+ it('carries a refusal with its reason', async () => {
+ presetService.derivePreset.mockRejectedValue(new ServerError('cannot be derived (drift:command)', { status: 409, code: 'PRESET_NOT_DERIVABLE', context: { reason: 'drift:command' } }));
+ const res = await request(app()).post('/api/providers/claude-ollama/derive');
+ expect(res.status).toBe(409);
+ expect(res.body).toMatchObject({ code: 'PRESET_NOT_DERIVABLE' });
+ });
+});
+
+describe('PUT /api/providers/:id on a derived preset', () => {
+ it('stores what the service re-derives from the merged record, with redacted secrets restored first', async () => {
+ const res = await request(app()).put('/api/providers/pi-tui-nvidia-nim-free').send({ effort: 'low', envVars: { NVIDIA_API_KEY: '***' } });
+ expect(res.status).toBe(200);
+ const [candidate, { updates }] = presetService.materializeStoredPreset.mock.calls[0];
+ expect(candidate).toMatchObject({ id: 'pi-tui-nvidia-nim-free', effort: 'low', envVars: { NVIDIA_API_KEY: 'nim-key' }, serviceId: 'nvidia-nim-free' });
+ expect(updates).toMatchObject({ effort: 'low', envVars: { NVIDIA_API_KEY: 'nim-key' } });
+ expect(providerService.updateProvider).toHaveBeenCalledWith('pi-tui-nvidia-nim-free', expect.objectContaining({ rederived: true, effort: 'low' }));
+ expect(res.body).toMatchObject({ effort: 'low', presetKind: 'derived' });
+ });
+
+ it('publishes a refused connection-owned edit as the service raised it, storing nothing', async () => {
+ presetService.materializeStoredPreset.mockRejectedValue(new ServerError('command is derived', { status: 400, code: 'PRESET_FIELD_DERIVED', context: { fields: ['command'] } }));
+ const res = await request(app()).put('/api/providers/pi-tui-nvidia-nim-free').send({ command: '/opt/bin/pi' });
+ expect(res.status).toBe(400);
+ expect(res.body).toMatchObject({ code: 'PRESET_FIELD_DERIVED' });
+ expect(providerService.updateProvider).not.toHaveBeenCalled();
+ });
+
+ it('leaves a legacy preset on the plain update path', async () => {
+ await request(app()).put('/api/providers/claude-ollama').send({ effort: 'low' });
+ expect(presetService.materializeStoredPreset).not.toHaveBeenCalled();
+ expect(providerService.updateProvider).toHaveBeenCalledWith('claude-ollama', expect.objectContaining({ effort: 'low' }));
+ });
+});
+
+describe('POST /api/providers with preset structure', () => {
+ it('materializes a body naming a harness, method and service before it is stored', async () => {
+ const body = { name: 'Claude · local', type: 'cli', command: 'claude', harnessId: 'claude', method: 'cli', serviceId: 'ollama' };
+ const res = await request(app()).post('/api/providers').send(body);
+ expect(res.status).toBe(201);
+ expect(presetService.materializeStoredPreset).toHaveBeenCalledWith(expect.objectContaining(body), { updates: expect.objectContaining(body) });
+ expect(providerService.createProvider).toHaveBeenCalledWith(expect.objectContaining({ rederived: true }));
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 2424305404..7b478414b2 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -49,6 +49,7 @@ import {
providerServiceUpdateSchema,
providerRouteModelAliasSchema,
providerRouteSettingsUpdateSchema,
+ providerPresetCreateSchema,
credentialBootstrapsSettingsSchema,
harnessEnablementUpdateSchema,
harnessIdParamSchema,
@@ -82,6 +83,7 @@ import {
PUBLIC_REVIEW_ACTIONS_POSTURE,
} from '../lib/providerVendors.js';
import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';
+import { presetDerivable, presetKind } from '../lib/providerPresets.js';
import {
captureSystemCapabilities,
detectSystemCapabilities,
@@ -209,9 +211,19 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =
publicReviewEnforcedPostures: enforcedPublicReviewPosturesForProvider(provider),
publicReviewSupported: publicReviewPostures.includes(PUBLIC_REVIEW_NO_TOOL_POSTURE),
publicReviewActionsSupported: publicReviewPostures.includes(PUBLIC_REVIEW_ACTIONS_POSTURE),
+ // Preset structure (#7565): `derived` when the record names the service it
+ // is materialized from, else `legacy`; and whether a legacy record is a
+ // candidate for "Convert to derived preset" (pure over the record — the
+ // conversion itself still proves the fixpoint against the service).
+ presetKind: presetKind(provider),
+ presetDerivable: presetDerivable(provider),
});
};
+// Deferred: the preset service reaches the graph store and the composite
+// resolver, which every suite that mounts these routes would otherwise pay for.
+const presetService = () => import('../services/providerPresets.js');
+
/**
* Carry a gateway-backed wrapper's RESOLVED model-access policy from the read
* that preceded a write onto the record the write handed back.
@@ -685,6 +697,21 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json({ ...verdict, provider: record ? presentProvider(record, await detectSystemCapabilities()) : null });
}));
+ /**
+ * "Save as preset" (#7565): store the record a composite id resolves to, as
+ * an enabled derived preset the picker can name like any other. The
+ * resolver's verdict gates it — an ineligible composite is a 400 with its
+ * code and reason, never a stored record that cannot run. `model` and
+ * `effort` become the preset's defaults; a `+<bootstrap>` suffix becomes
+ * its `credentialBootstrapId`.
+ */
+ router.post('/presets', asyncHandler(async (req, res) => {
+ const input = validateRequest(providerPresetCreateSchema, req.body ?? {});
+ const { createPresetFromComposite } = await presetService();
+ const created = await createPresetFromComposite(input);
+ res.status(201).json(presentProvider(created, await detectSystemCapabilities()));
+ }));
+
/**
* Is a ChatGPT subscription signed in, and is it usable right now?
*
@@ -1044,6 +1071,19 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json(result);
}));
+ /**
+ * "Convert to derived preset" (#7565): stamp one legacy record with the
+ * harness, method and service instance it already runs on — only when
+ * re-deriving it from that service reproduces every connection-owned value
+ * it carries (the same fixpoint the boot backfill applies). Refused with the
+ * reason otherwise; nothing about how the record runs is changed either way.
+ */
+ router.post('/:id/derive', asyncHandler(async (req, res) => {
+ const { derivePreset } = await presetService();
+ const provider = await derivePreset(req.params.id);
+ res.json(presentProvider(provider, await detectSystemCapabilities()));
+ }));
+
// Sanitized GET /:id — must be after specific /:id/* routes above
router.get('/:id', asyncHandler(async (req, res) => {
const provider = await providerService.getProviderById(req.params.id);
@@ -1082,7 +1122,15 @@ export function createPortOSProviderRoutes(aiToolkit) {
}
}
- const provider = await providerService.updateProvider(req.params.id, updates);
+ // A DERIVED preset (#7565) stores what its service derives: the record is
+ // re-materialized from the instance it names, a connection-owned value the
+ // client moved is refused with a pointer at the service, and a `models`
+ // edit is read as a narrowing of the service catalog.
+ const { savesAsDerivedPreset, materializeStoredPreset } = await presetService();
+ const candidate = { ...existing, ...updates, id: req.params.id };
+ const stored = savesAsDerivedPreset(candidate) ? await materializeStoredPreset(candidate, { updates }) : updates;
+
+ const provider = await providerService.updateProvider(req.params.id, stored);
res.json(presentProvider(withResolvedModelAccess(provider, existing), await detectSystemCapabilities()));
}));
@@ -1168,7 +1216,13 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.status(201).json({ providers: created.map(provider => presentProvider(provider, capabilities)) });
return;
}
- const provider = await providerService.createProvider(validation.data);
+ // A body naming a harness, method and service is a DERIVED preset (#7565)
+ // and is stored as the service derives it — see PUT /:id.
+ const { savesAsDerivedPreset, materializeStoredPreset } = await presetService();
+ const body = savesAsDerivedPreset(validation.data)
+ ? await materializeStoredPreset(validation.data, { updates: validation.data })
+ : validation.data;
+ const provider = await providerService.createProvider(body);
res.status(201).json(presentProvider(provider, await detectSystemCapabilities()));
}));
diff --git a/server/services/compositeProviders.js b/server/services/compositeProviders.js
index aaf67f5bf0..4e5aa7eb40 100644
--- a/server/services/compositeProviders.js
+++ b/server/services/compositeProviders.js
@@ -1,10 +1,10 @@
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 { bootstrapInputFor } from '../lib/providerPresets.js';
+import { applyServicePlanFilter, instanceForConnection } from '../lib/providerServiceInstances.js';
import { effortLevelsForProvider } from '../lib/providerModels.js';
-import { SERVICE_SLUG_RE, resolveServiceInstance, serviceDefinitionById } from '../lib/serviceDefinitions.js';
-import { bootstrapInputFor, listCredentialBootstraps, presentCredentialBootstraps } from './credentialBootstrapApps.js';
+import { listCredentialBootstraps, presentCredentialBootstraps } from './credentialBootstrapApps.js';
import { harnessEnablementFrom, harnessSettingsRevision, listHarnessEnablement } from './harnessEnablement.js';
import { findConnectionByRef, providerGraphEnabled } from './providerGraph.js';
import { readGraph } from './providerGraphStore.js';
@@ -77,33 +77,9 @@ async function graphWithinTtl() {
});
}
-/**
- * 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;
- // A stored row OUTLIVES the definition it names: installs upgrade on their own
- // schedule, so a release that drops or renames a plan leaves existing rows on
- // the old one. `resolveServiceInstance` THROWS on a plan the definition no
- // longer sells (and on a slug that predates SERVICE_SLUG_RE), and the catalog
- // maps this over EVERY connection — so one stale row would take down the whole
- // composition surface instead of dropping the single service it describes.
- // Answer `null` for it, exactly as for a definition this build does not have.
- const plan = connection.plan ?? definition.plans[0];
- if (!definition.plans.includes(plan) || !SERVICE_SLUG_RE.test(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,
- });
-}
+// The instance shape behind a row lives with the other pure instance readers
+// (#7565); re-exported so the composition surface keeps one import for it.
+export { instanceForConnection };
/**
* Resolve, with the reason for a refusal. Pure over its inputs so the tests
diff --git a/server/services/credentialBootstrapApps.js b/server/services/credentialBootstrapApps.js
index 31f0fbc16d..291187a6ce 100644
--- a/server/services/credentialBootstrapApps.js
+++ b/server/services/credentialBootstrapApps.js
@@ -1,3 +1,4 @@
+import { bootstrapInputFor } from '../lib/providerPresets.js';
import { credentialBootstrapsSettingsSchema } from '../lib/validation.js';
import { isPlainObject } from '../lib/objects.js';
import { getSettings, updateSettingsWith } from './settings.js';
@@ -51,17 +52,9 @@ export function normalizeCredentialBootstraps(raw) {
}));
}
-/**
- * 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 bootstrap input `materializeRoute` takes for an app is a pure shape the
+// preset library also needs (#7565); it lives there and is re-exported here.
+export { bootstrapInputFor };
/** 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]) => ({
diff --git a/server/services/providerGraph.js b/server/services/providerGraph.js
index 19a89be489..b78ada2efd 100644
--- a/server/services/providerGraph.js
+++ b/server/services/providerGraph.js
@@ -26,6 +26,13 @@ import {
} from '../lib/providerModelAliases.js';
import { harnessById } from '../lib/providerHarnesses.js';
import { modeSiblingName } from '../lib/aiToolkit/internal/providerModes.js';
+import {
+ bootstrapInputFor,
+ derivedPresetPatch,
+ materializeDerivedPreset,
+ planPresetBackfill,
+} from '../lib/providerPresets.js';
+import { isDerivedPreset } from '../lib/providerGraphRecords.js';
import { effortLevelsForProvider } from '../lib/providerModels.js';
import {
bindingBlocker,
@@ -42,6 +49,7 @@ import {
import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';
import {
allocateServiceSlug,
+ instanceForConnection,
planServiceColumnBackfill,
serviceColumnsForConnection,
takenServiceSlugs,
@@ -118,6 +126,11 @@ export function resetProviderGraphState() {
const providerService = () => requireToolkit().services.providers;
+// Deferred: the bootstrap-app table is read only when a preset is derived, and
+// its module reaches `lib/validation.js` — a closure nothing on the graph's
+// boot path otherwise pays for (server/AGENTS.md "Import scoping").
+const bootstrapApps = async () => (await import('./credentialBootstrapApps.js')).listCredentialBootstraps();
+
/**
* A connection addressed by UUID or by service slug (#7563). Every
* `/connections/:id` route accepts either, so a client that learned the slug
@@ -186,12 +199,28 @@ async function reconcilePass(reason) {
console.log(`🔗 Provider graph: named ${backfill.length} service instance(s) (${backfill.map((row) => row.slug).join(', ')})`);
}
+ // Derived presets (#7565): every legacy record the graph now routes onto a
+ // named instance is stamped with its structural keys — when re-deriving it
+ // from that service is a fixpoint. Row-derived like the slugs above, so it
+ // rides every pass; the latch this pass holds keeps the file write from
+ // re-entering. The view it reads is the graph AS APPLIED, composed from the
+ // plan rather than re-read (one read per pass is the recursion guard the
+ // save hook relies on): the rows this pass imported and the slugs it named
+ // are eligible now, a clone or split waits for the next pass.
+ const named = new Map(backfill.map((row) => [row.id, row]));
+ const removed = new Set(plan.removals);
+ const stamped = await backfillPresets({
+ connections: [...graph.connections.map((connection) => ({ ...connection, ...(named.get(connection.id) || {}) })), ...plan.imports.connections],
+ bindings: [...graph.bindings, ...plan.imports.bindings],
+ routes: [...graph.routes.filter((route) => !removed.has(route.providerId)), ...plan.imports.routes],
+ }, providers);
+
const detached = plan.regroups.filter((regroup) => regroup.connectionAction === 'clone').length;
const split = plan.regroups.filter((regroup) => !regroup.bindingId).length;
- if (!noop || plan.conflicts.length > 0) {
+ if (!noop || plan.conflicts.length > 0 || stamped > 0) {
console.log(`🔗 Provider graph reconciled (${reason}): ${plan.imports.routes.length} imported, `
+ `${detached} detached, ${split} split, ${plan.removals.length} removed, `
- + `${plan.acknowledgements.length} acknowledged, ${plan.conflicts.length} conflicted`);
+ + `${plan.acknowledgements.length} acknowledged, ${plan.conflicts.length} conflicted, ${stamped} presets derived`);
}
for (const conflict of plan.conflicts) {
console.error(`⚠️ Provider route ${conflict.providerId} changed outside the graph mid-projection; `
@@ -200,6 +229,83 @@ async function reconcilePass(reason) {
return { activeProvider, plan, noop };
}
+/**
+ * The preset backfill half of a pass (#7565). Writes through the toolkit
+ * directly: the caller already holds the `reconciling` latch for the whole
+ * pass, so the save hook this write fires returns immediately.
+ *
+ * @returns {Promise<number>} how many records were stamped
+ */
+async function backfillPresets(graph, providers) {
+ const { patches, skipped } = planPresetBackfill({ graph, providers, bootstraps: await bootstrapApps(), env: process.env });
+ const ids = Object.keys(patches);
+ if (ids.length === 0) return 0;
+ const written = await providerService().applyProviderPatches(patches);
+ if (written.length > 0) console.log(`🔗 Provider graph: derived ${written.length} preset(s) from their services (${written.join(', ')})`);
+ // Aggregate only: a reason names a record, never a value off it.
+ const legacy = skipped.filter(({ reason }) => reason !== 'unmapped').length;
+ if (legacy > 0) console.log(`🔗 Provider graph: ${legacy} routed record(s) stay legacy presets`);
+ return written.length;
+}
+
+/**
+ * Re-derive every DERIVED preset on `connection` from the row as it now is,
+ * and write what changed (#7565). The complement of `projectRoutes`: that one
+ * carries the endpoint and credential through the pending/projected snapshot
+ * protocol, this one re-runs the whole materialization — the inline OpenCode
+ * config, the plan-filtered catalog, the bootstrap app — none of which the
+ * connection profile owns. Called from inside a serialized pass, after the row
+ * is saved; a preset whose derivation is refused (the service lost its
+ * endpoint, its bootstrap app was deleted) is left exactly as it was.
+ *
+ * @param {object} connection - the row as saved
+ * @returns {Promise<string[]>} the preset ids rewritten
+ */
+export async function rematerializeDerivedPresets(connection) {
+ const instance = instanceForConnection(connection);
+ if (!instance) return [];
+ const [{ providers }, bootstraps] = await Promise.all([providerService().getAllProviders(), bootstrapApps()]);
+ const patches = {};
+ for (const record of providers) {
+ if (!isDerivedPreset(record) || record.serviceId !== connection.slug) continue;
+ const harness = harnessById(record.harnessId);
+ if (!harness) continue;
+ const app = record.credentialBootstrapId ? bootstraps[record.credentialBootstrapId] : null;
+ if (record.credentialBootstrapId && !app) continue;
+ const { record: derived } = materializeDerivedPreset({
+ record, harness, instance, catalog: connection.catalog, bootstrap: app ? bootstrapInputFor(record.credentialBootstrapId, app) : null,
+ });
+ if (!derived) continue;
+ const patch = derivedPresetPatch(record, derived);
+ if (Object.keys(patch).length > 0) patches[record.id] = patch;
+ }
+ if (Object.keys(patches).length === 0) return [];
+ const written = await writeProviderPatches(patches);
+ if (written.length > 0) console.log(`🔗 Re-derived ${written.length} preset(s) from service ${connection.slug}`);
+ return written;
+}
+
+/**
+ * A binding moved between instances (link, unlink): the derived presets on its
+ * routes now sit on `connection` and must say so. Their `serviceId` is
+ * re-addressed, then they are re-derived from the row they landed on.
+ */
+async function repointDerivedPresets(providerIds, connection) {
+ if (!connection?.slug) return [];
+ const { providers } = await providerService().getAllProviders();
+ const moved = providers.filter((record) => providerIds.includes(record.id) && isDerivedPreset(record) && record.serviceId !== connection.slug);
+ if (moved.length === 0) return [];
+ await writeProviderPatches(Object.fromEntries(moved.map((record) => [record.id, { serviceId: connection.slug }])));
+ return rematerializeDerivedPresets(connection);
+}
+
+/**
+ * Write provider patches from a caller that runs INSIDE a serialized pass
+ * (the preset service's convert-to-derived), holding the latch exactly as a
+ * projection does. Not for use outside the queue.
+ */
+export const writeProviderPatchesInPass = (patches) => writeProviderPatches(patches);
+
/**
* Reconcile the graph against providers.json.
*
@@ -397,6 +503,7 @@ export function linkBinding(input) {
const routes = graph.routes.filter((route) => route.bindingId === binding.id);
await relinkBinding({ bindingId: binding.id, connectionId: target.id });
const applied = await projectRoutes(routes.map((route) => route.providerId), target);
+ await repointDerivedPresets(routes.map((route) => route.providerId), target);
console.log(`🔗 Linked binding ${binding.id} to connection ${target.id} (${applied.length} routes projected)`);
return { bindingId: binding.id, connectionId: target.id, affectedRouteIds: applied };
});
@@ -423,6 +530,8 @@ export function unlinkBinding(input) {
slug: allocateServiceSlug(source.slug ?? source.definitionId ?? source.kind, taken),
};
await detachBindingToConnection({ bindingId: binding.id, connection });
+ // A derived preset names its instance by slug, and the clone has a new one.
+ await repointDerivedPresets(graph.routes.filter((route) => route.bindingId === binding.id).map((route) => route.providerId), connection);
console.log(`🔗 Unlinked binding ${binding.id} onto its own connection ${connection.id}`);
return { bindingId: binding.id, connectionId: connection.id };
});
@@ -596,8 +705,11 @@ export function updateConnectionSettings({
};
const revision = await saveConnectionSettings(next);
const applied = await projectRoutes(routes.map((route) => route.providerId), next);
- console.log(`🔗 Updated connection ${connection.id} (${applied.length} routes projected)`);
- return { connectionId: connection.id, revision, affectedRouteIds: applied };
+ // The derived presets on this instance follow the whole row, not only the
+ // profile-owned half the projection carried (#7565).
+ const rederived = await rematerializeDerivedPresets({ ...next, revision: revision ?? next.revision });
+ console.log(`🔗 Updated connection ${connection.id} (${applied.length} routes projected, ${rederived.length} presets re-derived)`);
+ return { connectionId: connection.id, revision, affectedRouteIds: [...new Set([...applied, ...rederived])] };
});
}
diff --git a/server/services/providerGraph.test.js b/server/services/providerGraph.test.js
index 855d1685d3..4f9dddbe66 100644
--- a/server/services/providerGraph.test.js
+++ b/server/services/providerGraph.test.js
@@ -40,7 +40,7 @@ const CONN_A = '11111111-1111-4111-8111-111111111111';
const CONN_B = '22222222-2222-4222-8222-222222222222';
const BINDING = '33333333-3333-4333-8333-333333333333';
-const connection = (id, baseUrl) => ({
+const connection = (id, baseUrl, slug) => ({
id,
revision: 1,
kind: 'ollama',
@@ -48,6 +48,9 @@ const connection = (id, baseUrl) => ({
transports: { anthropic: { baseUrl } },
credentials: { ANTHROPIC_AUTH_TOKEN: `token-for-${id}` },
catalog: { state: 'known', models: ['example-model'] },
+ // Named service instances (#7563), so the record below can be a derived
+ // preset (#7565) declaring the one it sits on.
+ slug, definitionId: 'ollama', plan: 'local', enabled: true, credentialVia: 'stored',
});
const CLAUDE = {
@@ -62,10 +65,12 @@ const CLAUDE = {
// Matches connection CONN_A exactly, so the baseline is a settled graph.
envVars: { ANTHROPIC_BASE_URL: `http://127.0.0.1:11434`, ANTHROPIC_AUTH_TOKEN: `token-for-${CONN_A}` },
secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],
+ // Already a derived preset on CONN_A, so a settled pass has nothing to stamp.
+ harnessId: 'claude', method: 'cli', serviceId: 'ollama',
};
const graphFixture = () => ({
- connections: [connection(CONN_A, 'http://127.0.0.1:11434'), connection(CONN_B, 'http://127.0.0.1:12345')],
+ connections: [connection(CONN_A, 'http://127.0.0.1:11434', 'ollama'), connection(CONN_B, 'http://127.0.0.1:12345', 'ollama-2')],
bindings: [{
id: BINDING, revision: 1, connectionId: CONN_A, harnessId: 'claude',
variantKey: 'default', label: 'Claude', enabled: true, selectedModels: ['example-model'],
@@ -117,6 +122,33 @@ describe('reconciliation', () => {
expect(providers.applyProviderPatches).not.toHaveBeenCalled();
});
+ // #7565: the preset backfill rides the pass. A routed legacy record whose
+ // re-derivation is a fixpoint is stamped with ONLY the structural keys; the
+ // stamped record is skipped on the next pass.
+ it('stamps a routed legacy record as a derived preset, additively, once', async () => {
+ const { harnessId, method, serviceId, ...legacy } = structuredClone(CLAUDE);
+ providers.getAllProviders.mockResolvedValue({ activeProvider: 'claude-ollama', providers: [legacy] });
+
+ await graph.initProviderGraph();
+ expect(providers.applyProviderPatches).toHaveBeenCalledTimes(1);
+ expect(providers.applyProviderPatches).toHaveBeenCalledWith({ 'claude-ollama': { harnessId, method, serviceId } });
+ // Its own write fires the save hook; the latch keeps that from re-entering.
+ expect(store.readGraph).toHaveBeenCalledTimes(1);
+
+ providers.getAllProviders.mockResolvedValue({ activeProvider: 'claude-ollama', providers: [structuredClone(CLAUDE)] });
+ providers.applyProviderPatches.mockClear();
+ await graph.onProvidersSaved();
+ expect(providers.applyProviderPatches).not.toHaveBeenCalled();
+ });
+
+ it('leaves a routed record legacy when re-deriving it would change how it runs', async () => {
+ // A path-configured binary is a deliberate choice materialization would overwrite.
+ const { harnessId, method, serviceId, ...legacy } = structuredClone(CLAUDE);
+ providers.getAllProviders.mockResolvedValue({ activeProvider: 'claude-ollama', providers: [{ ...legacy, command: '/opt/bin/claude' }] });
+ await graph.initProviderGraph();
+ expect(providers.applyProviderPatches).not.toHaveBeenCalled();
+ });
+
it('retries an interrupted projection, then acknowledges it in the same plan', async () => {
const fixture = graphFixture();
fixture.routes[0].pending = {
@@ -199,13 +231,15 @@ describe('linking', () => {
expectedRevisions: { binding: 1, sourceConnection: 1, targetConnection: 1 },
});
- expect(order).toEqual(['stage', 'write', 'acknowledge']);
+ expect(order.slice(0, 3)).toEqual(['stage', 'write', 'acknowledge']);
expect(result).toEqual({ bindingId: BINDING, connectionId: CONN_B, affectedRouteIds: ['claude-ollama'] });
// The route keeps its executable id; only the backend it reaches moves.
expect(providers.applyProviderPatches.mock.calls[0][0]['claude-ollama'].envVars).toEqual({
ANTHROPIC_BASE_URL: 'http://127.0.0.1:12345',
ANTHROPIC_AUTH_TOKEN: 'token-for-22222222-2222-4222-8222-222222222222',
});
+ // The derived preset on the moved binding now names the instance it landed on (#7565).
+ expect(providers.applyProviderPatches.mock.calls[1][0]).toEqual({ 'claude-ollama': { serviceId: 'ollama-2' } });
});
it.each([
@@ -256,8 +290,11 @@ describe('unlinking', () => {
const [{ connection: clone }] = store.detachBindingToConnection.mock.calls[0];
expect(clone.transports).toEqual({ anthropic: { baseUrl: 'http://127.0.0.1:11434' } });
expect(clone.credentials).toEqual({ ANTHROPIC_AUTH_TOKEN: `token-for-${CONN_A}` });
- // Nothing about execution changes, so the provider file is not touched.
- expect(providers.applyProviderPatches).not.toHaveBeenCalled();
+ // Nothing about execution changes: the one write re-addresses the derived
+ // preset to the clone's slug (#7565) and touches no executable value.
+ expect(providers.applyProviderPatches).toHaveBeenCalledTimes(1);
+ expect(providers.applyProviderPatches).toHaveBeenCalledWith({ 'claude-ollama': { serviceId: clone.slug } });
+ expect(clone.slug).toBe('ollama-3');
});
it('refuses an unknown binding', async () => {
@@ -298,11 +335,15 @@ describe('service-instance naming (#7563)', () => {
it('names a boot-imported fragment before it is written, and backfills unnamed rows after', async () => {
const fixture = graphFixture();
// CONN_A predates the columns; CONN_B is already named.
+ for (const key of ['slug', 'definitionId', 'plan', 'enabled', 'credentialVia']) delete fixture.connections[0][key];
fixture.connections[1].slug = 'ollama';
store.readGraph.mockResolvedValue(fixture);
+ // The second record is a LEGACY one the graph has never routed: it declares
+ // no service, so it imports as its own fragment rather than onto a row.
+ const { harnessId, method, serviceId, ...legacy } = structuredClone(CLAUDE);
providers.getAllProviders.mockResolvedValue({
activeProvider: 'claude-ollama',
- providers: [structuredClone(CLAUDE), { ...structuredClone(CLAUDE), id: 'claude-other', envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:5555', ANTHROPIC_AUTH_TOKEN: 'other' } }],
+ providers: [structuredClone(CLAUDE), { ...legacy, id: 'claude-other', envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:5555', ANTHROPIC_AUTH_TOKEN: 'other' } }],
});
await graph.initProviderGraph();
const [plan] = store.applyReconciliation.mock.calls[0];
diff --git a/server/services/providerPresets.js b/server/services/providerPresets.js
new file mode 100644
index 0000000000..bdd31aebb2
--- /dev/null
+++ b/server/services/providerPresets.js
@@ -0,0 +1,204 @@
+import { ServerError } from '../lib/errorHandler.js';
+import { requireToolkit } from '../lib/aiToolkitState.js';
+import { isDerivedPreset } from '../lib/providerGraphRecords.js';
+import { harnessById } from '../lib/providerHarnesses.js';
+import { effortLevelsForProvider } from '../lib/providerModels.js';
+import {
+ bootstrapInputFor,
+ materializeDerivedPreset,
+ planPresetBackfill,
+ refusedDerivedEdits,
+} from '../lib/providerPresets.js';
+import { instanceForConnection } from '../lib/providerServiceInstances.js';
+import { listCredentialBootstraps } from './credentialBootstrapApps.js';
+import { describeCompositeProvider } from './compositeProviders.js';
+import {
+ findConnectionByRef,
+ providerGraphEnabled,
+ reconcileProviderGraph,
+ requireProviderGraph,
+ serializeProviderGraph,
+ writeProviderPatchesInPass,
+} from './providerGraph.js';
+import { readGraph } from './providerGraphStore.js';
+
+/**
+ * PRESET orchestration (#7565, epic #7561): the store-backed half of
+ * `lib/providerPresets.js`.
+ *
+ * - `materializeStoredPreset` — what `POST /api/providers` and `PUT
+ * /api/providers/:id` hand the toolkit for a DERIVED preset: the record
+ * with its connection-owned values re-derived from the service instance it
+ * names, and a direct edit to one of those values refused with a pointer
+ * at the service.
+ * - `createPresetFromComposite` — "Save as preset": a composite id the
+ * resolver already judges runnable becomes a stored record, enabled, with
+ * the selection's model and effort as its defaults.
+ * - `derivePreset` — "Convert to derived preset" for one legacy record: the
+ * same fixpoint rule the boot backfill applies, on demand.
+ *
+ * Every write lands in `data/providers.json` through the toolkit, so an older
+ * release executes a derived preset exactly as any record. Local I/O only;
+ * nothing here contacts a provider.
+ */
+
+const providerService = () => requireToolkit().services.providers;
+
+/** The graph, the bootstrap apps, and the instance a derived record names — or the typed 400 for a name nothing answers to. */
+async function presetInputs(record) {
+ requireProviderGraph();
+ const [graph, bootstraps] = await Promise.all([readGraph(), listCredentialBootstraps()]);
+ const harness = harnessById(record.harnessId);
+ if (!harness) throw new ServerError(`No harness "${record.harnessId}"`, { status: 400, code: 'PRESET_HARNESS_UNKNOWN' });
+ if (!harness.modes.includes(record.method)) {
+ throw new ServerError(`${harness.label} has no ${record.method} mode`, { status: 400, code: 'PRESET_METHOD_UNSUPPORTED' });
+ }
+ const connection = findConnectionByRef(graph, record.serviceId);
+ if (!connection || connection.slug !== record.serviceId) {
+ throw new ServerError(`No service is addressed as "${record.serviceId}"`, { status: 400, code: 'PRESET_SERVICE_UNKNOWN' });
+ }
+ const instance = instanceForConnection(connection);
+ if (!instance) {
+ throw new ServerError(`Service "${record.serviceId}" has no definition this build composes onto`, { status: 400, code: 'PRESET_SERVICE_UNDEFINED' });
+ }
+ let bootstrap = null;
+ if (record.credentialBootstrapId) {
+ const app = bootstraps[record.credentialBootstrapId];
+ if (!app) {
+ throw new ServerError(`No credential bootstrap app is addressed as "${record.credentialBootstrapId}"`, { status: 400, code: 'PRESET_BOOTSTRAP_UNKNOWN' });
+ }
+ bootstrap = bootstrapInputFor(record.credentialBootstrapId, app);
+ }
+ return { harness, connection, instance, bootstrap };
+}
+
+/**
+ * The record a save stores for a derived preset.
+ *
+ * `candidate` is the stored record with the client's updates already merged
+ * (secrets restored); `updates` is the patch itself, so a connection-owned
+ * value the client MOVED is refused while one it merely echoed back is not.
+ * A `models` edit on a derived preset is read as a narrowing of the service
+ * catalog rather than refused: which of the catalog a preset offers is the
+ * preset's own choice.
+ *
+ * @param {object} candidate
+ * @param {{updates?: object}} [options]
+ * @returns {Promise<object>} the record to hand `createProvider` / `updateProvider`
+ */
+export async function materializeStoredPreset(candidate, { updates = {} } = {}) {
+ const record = { ...candidate, method: candidate.method ?? candidate.type };
+ const { harness, connection, instance, bootstrap } = await presetInputs(record);
+ const listed = connection.catalog?.state === 'known' ? connection.catalog.models : [];
+ if (Array.isArray(updates.models) && listed.length > 0) {
+ const known = new Set(listed);
+ const narrowing = updates.models.filter((model) => known.has(model));
+ record.catalogNarrowing = narrowing.length === listed.length ? null : narrowing;
+ }
+ const { record: derived, error, ownedEnvNames } = materializeDerivedPreset({
+ record, harness, instance, catalog: connection.catalog, bootstrap,
+ });
+ if (error) throw new ServerError(error.message, { status: 400, code: error.code });
+ const refused = refusedDerivedEdits(updates, derived, ownedEnvNames);
+ if (refused.length > 0) {
+ throw new ServerError(
+ `${refused.join(', ')} ${refused.length === 1 ? 'is' : 'are'} derived from service "${record.serviceId}"; edit the service (PATCH /api/providers/services/${record.serviceId}) instead`,
+ { status: 400, code: 'PRESET_FIELD_DERIVED', context: { fields: refused, serviceId: record.serviceId } },
+ );
+ }
+ return derived;
+}
+
+/** A readable, free record id for a composite: `pi-tui-nvidia-nim-free`, `claude-cli-anthropic-corp-auth`, suffixed when taken. */
+function mintPresetId(parts, taken) {
+ const stem = [parts.harnessId, parts.method, parts.serviceSlug, parts.bootstrapSlug].filter(Boolean).join('-');
+ for (let n = 1; n < 1000; n += 1) {
+ const candidate = n === 1 ? stem : `${stem}-${n}`;
+ if (!taken.has(candidate)) return candidate;
+ }
+ throw new ServerError(`Could not mint a free preset id for ${stem}`, { status: 409, code: 'PRESET_ID_EXHAUSTED' });
+}
+
+/**
+ * "Save as preset": store the record a composite id resolves to.
+ *
+ * The resolver's verdict is the gate — an ineligible composite is a 400 with
+ * the same code and reason a picker shows beside it, never a stored record
+ * that cannot run. The stored record is the composite's materialization
+ * (so it spawns with the identical argv and env) plus the caller's model and
+ * effort as its defaults and the `+<bootstrap>` suffix as its
+ * `credentialBootstrapId`; a later save re-derives it like any derived preset.
+ *
+ * @param {{compositeId: string, id?: string, name?: string, model?: string|null, effort?: string|null}} input
+ * @returns {Promise<object>} the created record
+ */
+export async function createPresetFromComposite({ compositeId, id, name, model, effort }) {
+ const verdict = await describeCompositeProvider(compositeId);
+ if (!verdict.eligible) throw new ServerError(verdict.reason, { status: 400, code: verdict.code });
+ const { record, parts } = verdict;
+ const { providers } = await providerService().getAllProviders();
+ const taken = new Set(providers.map((provider) => provider.id));
+ if (id && taken.has(id)) throw new ServerError(`Provider "${id}" already exists`, { status: 409, code: 'PRESET_ID_TAKEN' });
+ const defaultModel = model ?? record.defaultModel ?? null;
+ if (model && record.models.length > 0 && !record.models.includes(model)) {
+ throw new ServerError(`${parts.serviceSlug} lists no model "${model}"`, { status: 400, code: 'PRESET_MODEL_UNKNOWN' });
+ }
+ if (effort) {
+ const levels = effortLevelsForProvider(record, defaultModel);
+ if (!levels || !levels.includes(effort)) {
+ throw new ServerError(levels ? `This preset accepts effort ${levels.join(', ')}` : 'This preset\'s harness takes no effort setting',
+ { status: 400, code: 'PRESET_EFFORT_UNSUPPORTED' });
+ }
+ }
+ const body = {
+ ...record,
+ // The composite's key rides non-enumerably; a stored preset carries it as any record does.
+ apiKey: record.apiKey ?? '',
+ id: id ?? mintPresetId(parts, taken),
+ name: name ?? record.name,
+ defaultModel,
+ ...(effort ? { effort } : {}),
+ ...(parts.bootstrapSlug ? { credentialBootstrapId: parts.bootstrapSlug } : {}),
+ };
+ delete body.servicePlan;
+ const created = await providerService().createProvider(body);
+ console.log(`🔗 Saved composite ${compositeId} as preset ${created.id}`);
+ return created;
+}
+
+/**
+ * Convert ONE legacy preset into a derived one, on demand.
+ *
+ * A reconcile pass runs first so a record the graph has never routed is
+ * imported (as its own fragment, named as a service instance) before the
+ * fixpoint check — the same rule the boot backfill applies, so the button and
+ * the boot pass cannot disagree about what is convertible. Refused with the
+ * reason when re-deriving the record would change how it runs.
+ *
+ * @param {string} id
+ * @returns {Promise<object>} the record as stored afterwards
+ */
+export async function derivePreset(id) {
+ requireProviderGraph();
+ const before = await providerService().getProviderById(id);
+ if (!before) throw new ServerError('Provider not found', { status: 404 });
+ if (isDerivedPreset(before)) return before;
+ await reconcileProviderGraph('derive');
+ return serializeProviderGraph(async () => {
+ const [graph, { providers }, bootstraps] = await Promise.all([readGraph(), providerService().getAllProviders(), listCredentialBootstraps()]);
+ const record = providers.find((provider) => provider.id === id);
+ if (!record) throw new ServerError('Provider not found', { status: 404 });
+ const { patches, skipped } = planPresetBackfill({ graph, providers: [record], bootstraps, env: process.env });
+ if (!patches[id]) {
+ const reason = skipped.find((entry) => entry.id === id)?.reason ?? 'not-derivable';
+ throw new ServerError(`"${id}" cannot be derived from a service as it is configured (${reason})`,
+ { status: 409, code: 'PRESET_NOT_DERIVABLE', context: { reason } });
+ }
+ await writeProviderPatchesInPass(patches);
+ console.log(`🔗 Converted ${id} into a derived preset on service ${patches[id].serviceId}`);
+ return providerService().getProviderById(id);
+ });
+}
+
+/** Whether a save has to go through {@link materializeStoredPreset}: the record is derived and the graph can answer for its service. */
+export const savesAsDerivedPreset = (candidate) => isDerivedPreset(candidate) && providerGraphEnabled();
diff --git a/server/services/providerPresets.test.js b/server/services/providerPresets.test.js
new file mode 100644
index 0000000000..f290a29268
--- /dev/null
+++ b/server/services/providerPresets.test.js
@@ -0,0 +1,148 @@
+/**
+ * The preset service (#7565): "Save as preset" stores exactly what its
+ * composite runs as, a derived preset's save re-derives from the service and
+ * refuses a moved connection-owned value, and "Convert to derived preset"
+ * stamps a legacy record only on the fixpoint the boot backfill demands.
+ *
+ * Fixtures mirror `compositeProviders.test.js`; the toolkit's provider service
+ * runs on a temp dir so the created record is the one `providers.json` holds.
+ * Nothing is spawned; nothing is read out of a running install.
+ */
+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 settingsMock = vi.hoisted(() => ({
+ settingsEvents: { on: () => {}, emit: () => {} },
+ getSettings: vi.fn(async () => structuredClone(settingsState.current)),
+ updateSettingsWith: vi.fn(async (mutate) => { settingsState.current = await mutate(structuredClone(settingsState.current)); return settingsState.current; }),
+}));
+vi.mock('./settings.js', () => settingsMock);
+const store = vi.hoisted(() => ({
+ readGraph: vi.fn(async () => structuredClone(graphState.current)),
+ applyReconciliation: vi.fn(async () => {}),
+ applyServiceColumnBackfill: vi.fn(async () => {}),
+}));
+vi.mock('./providerGraphStore.js', () => store);
+vi.mock('./providerRuntimeInstaller.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ peekProviderRuntimeStatuses: () => ({ pi: { installed: true, version: '1.0.0' }, claude: { installed: true, version: '2.0.0' } }),
+}));
+vi.mock('./providerServices.js', () => ({ listServices: vi.fn(async () => ({ services: [] })) }));
+const toolkitState = vi.hoisted(() => ({ toolkit: null }));
+vi.mock('../lib/aiToolkitState.js', () => ({ requireToolkit: () => toolkitState.toolkit }));
+
+const { createProviderService } = await import('../lib/aiToolkit/providers.js');
+const graph = await import('./providerGraph.js');
+const composite = await import('./compositeProviders.js');
+const presets = await import('./providerPresets.js');
+const { buildCliChildEnv } = await import('../lib/cliChildEnv.js');
+const { buildTuiInvocation } = await import('../lib/tuiHandshake.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 NIM = {
+ id: uuid(1), revision: 1, enabled: true, credentialVia: 'stored', kind: 'gateway:nvidia-nim', label: 'NVIDIA NIM (free)', slug: 'nvidia-nim-free', 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'] },
+};
+const OLLAMA = {
+ id: uuid(3), revision: 1, enabled: true, credentialVia: 'stored', 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'] },
+};
+
+let dataDir;
+beforeEach(async () => {
+ dataDir = await mkdtemp(join(tmpdir(), 'portos-presets-'));
+ toolkitState.toolkit = { services: { providers: createProviderService({ dataDir, providersCacheTtlMs: 0, onProvidersSaved: () => graph.onProvidersSaved(), resolveCompositeProvider: composite.resolveCompositeProvider }) } };
+ graphState.current = { connections: [structuredClone(NIM), structuredClone(OLLAMA)], bindings: [], routes: [] };
+ settingsState.current = {};
+ composite.invalidateCompositeCache();
+ graph.resetProviderGraphState();
+ await graph.initProviderGraph();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(dataDir, { recursive: true, force: true });
+});
+
+const providerService = () => toolkitState.toolkit.services.providers;
+
+describe('createPresetFromComposite', () => {
+ it('pi.tui@nvidia-nim-free → a stored, enabled preset that spawns with the composite\'s exact argv and env', async () => {
+ const source = await providerService().getProviderById('pi.tui@nvidia-nim-free');
+ const created = await presets.createPresetFromComposite({ compositeId: 'pi.tui@nvidia-nim-free', model: 'meta/example-llama', effort: 'high' });
+
+ expect(created).toMatchObject({ id: 'pi-tui-nvidia-nim-free', harnessId: 'pi', method: 'tui', serviceId: 'nvidia-nim-free', enabled: true, defaultModel: 'meta/example-llama', effort: 'high' });
+ expect(created).not.toHaveProperty('servicePlan');
+ const stored = await providerService().getProviderById('pi-tui-nvidia-nim-free');
+ // The saved effort is the one difference from the bare composite, and it is the caller's.
+ expect(buildTuiInvocation(stored, 'meta/example-llama')).toEqual(buildTuiInvocation({ ...source, effort: 'high' }, 'meta/example-llama'));
+ const env = (provider) => buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' }, provider, cwd: process.cwd() });
+ expect(env(stored).NVIDIA_API_KEY).toBe('nim-key');
+ expect(env(stored)).toEqual(env(source));
+ // A second save mints the next free id rather than colliding.
+ expect((await presets.createPresetFromComposite({ compositeId: 'pi.tui@nvidia-nim-free' })).id).toBe('pi-tui-nvidia-nim-free-2');
+ });
+
+ it('carries the +bootstrap suffix as credentialBootstrapId and writes the inline object the spawner reads', async () => {
+ settingsState.current = { credentialBootstraps: { 'corp-auth': { label: 'Corp', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } } } };
+ graphState.current.connections.push({ id: uuid(5), revision: 1, enabled: true, kind: 'api', label: 'Anthropic', slug: 'anthropic', definitionId: 'anthropic', plan: 'paid', transports: { anthropic: { baseUrl: 'https://api.anthropic.com' } }, credentials: {}, credentialVia: 'bootstrap', catalog: { state: 'unknown', models: [] } });
+ composite.invalidateCompositeCache();
+ const created = await presets.createPresetFromComposite({ compositeId: 'claude.cli@anthropic+corp-auth', name: 'Claude (corp)' });
+ expect(created).toMatchObject({ id: 'claude-cli-anthropic-corp-auth', name: 'Claude (corp)', credentialBootstrapId: 'corp-auth', credentialBootstrap: { command: 'corp-auth', harnessId: 'claude-code', argsSeparator: '--' } });
+ });
+
+ it('refuses an ineligible composite with the resolver\'s own code, a taken id, an unlisted model and an unsupported effort', async () => {
+ await expect(presets.createPresetFromComposite({ compositeId: 'pi.tui@no-such-service' })).rejects.toMatchObject({ status: 400, code: 'service-unknown' });
+ await expect(presets.createPresetFromComposite({ compositeId: 'pi.tui@nvidia-nim-free', model: 'nvidia/not-listed' })).rejects.toMatchObject({ status: 400, code: 'PRESET_MODEL_UNKNOWN' });
+ await expect(presets.createPresetFromComposite({ compositeId: 'direct.api@nvidia-nim-free', effort: 'high' })).rejects.toMatchObject({ status: 400, code: 'PRESET_EFFORT_UNSUPPORTED' });
+ await presets.createPresetFromComposite({ compositeId: 'pi.tui@nvidia-nim-free', id: 'mine' });
+ await expect(presets.createPresetFromComposite({ compositeId: 'pi.tui@nvidia-nim-free', id: 'mine' })).rejects.toMatchObject({ status: 409, code: 'PRESET_ID_TAKEN' });
+ });
+});
+
+describe('materializeStoredPreset', () => {
+ it('re-derives a derived preset from its service, reads a models edit as a narrowing, and refuses a moved connection-owned value', async () => {
+ const created = await presets.createPresetFromComposite({ compositeId: 'claude.cli@ollama' });
+ const stored = await providerService().getProviderById(created.id);
+
+ const edited = await presets.materializeStoredPreset({ ...stored, effort: 'low', args: ['--print', '--verbose'], models: ['example-llama'] }, { updates: { effort: 'low', args: ['--print', '--verbose'], models: ['example-llama'] } });
+ expect(edited).toMatchObject({ effort: 'low', args: ['--print', '--verbose'], envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' } });
+ expect(edited.catalogNarrowing).toBeNull();
+
+ await expect(presets.materializeStoredPreset({ ...stored, envVars: { ...stored.envVars, ANTHROPIC_BASE_URL: 'http://elsewhere.test' } }, { updates: { envVars: { ...stored.envVars, ANTHROPIC_BASE_URL: 'http://elsewhere.test' } } }))
+ .rejects.toMatchObject({ status: 400, code: 'PRESET_FIELD_DERIVED', context: { fields: ['envVars.ANTHROPIC_BASE_URL'], serviceId: 'ollama' } });
+ await expect(presets.materializeStoredPreset({ ...stored, serviceId: 'nowhere' })).rejects.toMatchObject({ status: 400, code: 'PRESET_SERVICE_UNKNOWN' });
+ });
+});
+
+describe('derivePreset', () => {
+ it('stamps a legacy record the graph routes onto a named instance, and refuses one whose re-derivation would change its run', async () => {
+ const legacy = { id: 'claude-ollama', name: 'Claude on Ollama', type: 'cli', command: 'claude', args: ['--print'], ollamaBacked: true, enabled: true, models: ['example-llama'],
+ envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' }, secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'] };
+ await providerService().createProvider(legacy);
+ // The record is unmapped, so the derive pass imports it first — as its own
+ // fragment, a second instance of the daemon (import never auto-links), which
+ // is the service it is then derived from. The store double records the
+ // plan and the next read serves it back.
+ store.applyReconciliation.mockImplementation(async (plan) => {
+ const imported = plan.imports;
+ graphState.current = {
+ connections: [...graphState.current.connections, ...imported.connections],
+ bindings: [...graphState.current.bindings, ...imported.bindings],
+ routes: [...graphState.current.routes, ...imported.routes],
+ };
+ });
+ const derived = await presets.derivePreset('claude-ollama');
+ expect(derived).toMatchObject({ harnessId: 'claude', method: 'cli', serviceId: 'ollama-2', command: 'claude', args: ['--print'] });
+
+ await providerService().createProvider({ ...legacy, id: 'claude-path', command: '/opt/bin/claude' });
+ await expect(presets.derivePreset('claude-path')).rejects.toMatchObject({ status: 409, code: 'PRESET_NOT_DERIVABLE' });
+ await expect(presets.derivePreset('nope')).rejects.toMatchObject({ status: 404 });
+ });
+});
diff --git a/server/services/providerServices.js b/server/services/providerServices.js
index d731bd4e7e..28a75b1b07 100644
--- a/server/services/providerServices.js
+++ b/server/services/providerServices.js
@@ -14,7 +14,13 @@ import {
} from '../lib/providerServiceInstances.js';
import { isNonBlankStr } from '../lib/textUtils.js';
import { resolveServiceInstance, serviceDefinitionById } from '../lib/serviceDefinitions.js';
-import { findConnectionByRef, requireProviderGraph, serializeProviderGraph, updateConnectionSettings } from './providerGraph.js';
+import {
+ findConnectionByRef,
+ rematerializeDerivedPresets,
+ requireProviderGraph,
+ serializeProviderGraph,
+ updateConnectionSettings,
+} from './providerGraph.js';
import { readGraph, saveConnectionSettings, writeGraph } from './providerGraphStore.js';
/**
@@ -246,6 +252,9 @@ export function refreshServiceCatalog(ref, deps = {}) {
error: outcome.error == null ? null : sanitizeCatalogError(outcome.error, connection.credentials),
}, { now });
const revision = await saveConnectionSettings({ ...connection, catalog });
+ // A derived preset's `models` is this catalog narrowed (#7565): a listing
+ // that changed reaches every preset on the instance in the same request.
+ await rematerializeDerivedPresets({ ...connection, catalog, revision: revision ?? connection.revision });
console.log(`🔗 Refreshed service ${connection.slug ?? connection.id} catalog via ${definition.catalog.strategy}: `
+ `${catalog.state}, ${catalog.models.length} models`);