Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
give PROVIDER_HARNESSES a command recipe, so a backend and a harness can be created rather than only imported (#6369)
[._.]/ Adam Eivy17f60c9411fd
diff --git a/client/src/components/providers/ProviderConnectionForm.jsx b/client/src/components/providers/ProviderConnectionForm.jsxnew file mode 100644index 0000000000..3b98ee8231--- /dev/null+++ b/client/src/components/providers/ProviderConnectionForm.jsx@@ -0,0 +1,120 @@+import { Plus } from 'lucide-react';+import { transportProtocolOptions } from '../../lib/providerManagement';++/**+ * Add a backend (#6369) — mock flow 3 in the design record: a new endpoint with+ * its own credentials, created as its own identity even when its models match a+ * backend already configured. Nothing is contacted when it saves.+ *+ * ONE transport, which is the server's rule too: a provider record names one+ * endpoint, so a backend declaring two could never be the backend its own+ * routes describe.+ *+ * The kind and protocol options come from the graph response+ * (`creatableConnectionKinds`, `creatableHarnesses`) rather than a table+ * mirrored into the browser — which backends a minted route can honestly+ * describe is a server decision.+ */+export default function ProviderConnectionForm({ graph, draft, onChange, onSubmit, open, onToggle, busy }) {+ const field = (key) => (event) => onChange({ ...draft, [key]: event.target.value });++ return (+ <div className="rounded-lg border border-dashed border-port-border p-3">+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={open}+ className="flex items-center gap-1 text-sm font-medium"+ >+ <Plus size={14} aria-hidden="true" /> Add a backend+ </button>++ {open && (+ <div className="mt-3 space-y-3">+ <div className="grid gap-3 sm:grid-cols-2">+ <label className="block text-sm" htmlFor="new-backend-label">+ <span className="mb-1 block text-port-muted">Backend name</span>+ <input+ id="new-backend-label"+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1"+ value={draft.label}+ onChange={field('label')}+ />+ </label>+ <label className="block text-sm" htmlFor="new-backend-kind">+ <span className="mb-1 block text-port-muted">Backend</span>+ <select+ id="new-backend-kind"+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1"+ value={draft.kind}+ onChange={field('kind')}+ >+ {(graph?.creatableConnectionKinds || []).map((kind) => (+ <option key={kind.id} value={kind.id}>{kind.label}</option>+ ))}+ </select>+ </label>+ <label className="block text-sm" htmlFor="new-backend-protocol">+ <span className="mb-1 block text-port-muted">Wire protocol</span>+ <select+ id="new-backend-protocol"+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1"+ value={draft.protocol}+ onChange={field('protocol')}+ >+ {transportProtocolOptions(graph).map((option) => (+ <option key={option.protocol} value={option.protocol}>+ {option.protocol} — {option.drivers.join(', ')}+ </option>+ ))}+ </select>+ </label>+ <label className="block text-sm" htmlFor="new-backend-url">+ <span className="mb-1 block text-port-muted">Base URL</span>+ <input+ id="new-backend-url"+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1"+ value={draft.baseUrl}+ onChange={field('baseUrl')}+ placeholder="http://127.0.0.1:11434"+ />+ </label>+ <label className="block text-sm" htmlFor="new-backend-credential-key">+ <span className="mb-1 block text-port-muted">Credential name (optional)</span>+ <input+ id="new-backend-credential-key"+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1"+ value={draft.credentialKey}+ onChange={field('credentialKey')}+ placeholder="apiKey"+ />+ </label>+ <label className="block text-sm" htmlFor="new-backend-credential">+ <span className="mb-1 block text-port-muted">Credential value (optional)</span>+ <input+ id="new-backend-credential"+ type="password"+ autoComplete="off"+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1"+ value={draft.credential}+ onChange={field('credential')}+ />+ </label>+ </div>+ <p className="text-xs text-port-muted">+ Claude Code speaks <code>anthropic</code> and needs an <code>ANTHROPIC_AUTH_TOKEN</code> credential —+ any non-empty value works for a local daemon that ignores it. Nothing is contacted when you save this.+ </p>+ <button+ type="button"+ disabled={busy || !draft.label.trim() || !draft.baseUrl.trim()}+ onClick={onSubmit}+ className="rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50"+ >+ Add backend+ </button>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/providers/ProviderConnections.jsx b/client/src/components/providers/ProviderConnections.jsxindex 6a06880757..5f45182088 100644--- a/client/src/components/providers/ProviderConnections.jsx+++ b/client/src/components/providers/ProviderConnections.jsx@@ -4,6 +4,8 @@ import toast from '../ui/Toast';import Drawer from '../Drawer';import Banner from '../ui/Banner';import EmptyState from '../EmptyState';+import ProviderConnectionForm from './ProviderConnectionForm';+import ProviderHarnessForm from './ProviderHarnessForm';import ProviderRouteRow from './ProviderRouteRow';import * as api from '../../services/api';import { harnessLabel } from '../../utils/providerHarnesses';@@ -43,6 +45,15 @@ import {* shareable, bookmarkable and reachable from ⌘K and voice.*/+/**+ * A blank "add a backend" form. `openai` is the default protocol because it is+ * the one every OpenAI-compatible daemon, gateway and direct API route speaks;+ * Claude Code is the exception, and the field says so.+ */+const EMPTY_BACKEND_DRAFT = Object.freeze({+ label: '', kind: 'ollama', protocol: 'openai', baseUrl: '', credentialKey: '', credential: '',+});+/** How each catalog state reads at a glance — the four are deliberately distinct. */const CATALOG_TONE_CLASS = {error: 'text-port-error',@@ -85,6 +96,13 @@ export default function ProviderConnections({const [linkTarget, setLinkTarget] = useState({});const [linkPreview, setLinkPreview] = useState(null);+ // Creating a backend, and adding a harness to one (#6369). Both drafts live+ // here for the same reason the edit drafts above do: a graph reload after any+ // write must not silently discard a half-typed create.+ const [addingBackend, setAddingBackend] = useState(false);+ const [backendDraft, setBackendDraft] = useState(EMPTY_BACKEND_DRAFT);+ const [harnessDraft, setHarnessDraft] = useState({});+const loadGraph = useCallback(async () => {setLoading(true);const next = await api.getProviderManagementGraph({ silent: true }).catch((err) => ({ err }));@@ -158,6 +176,46 @@ export default function ProviderConnections({return result;}, [loadGraph, onGraphChanged]);+ /**+ * Add a backend. One transport only, which is the server's rule too: a+ * provider record names one endpoint, so a backend declaring two could never+ * be the backend its own routes describe.+ */+ const createBackend = useCallback(async () => {+ const draft = backendDraft;+ const credentialKey = draft.credentialKey.trim() || 'apiKey';+ const created = await run('Adding the backend', () => api.createProviderConnection({+ kind: draft.kind,+ label: draft.label.trim(),+ transports: { [draft.protocol]: { baseUrl: draft.baseUrl.trim() } },+ ...(draft.credential.trim() ? { credentials: { [credentialKey]: draft.credential.trim() } } : {}),+ }, { silent: true }));+ if (!created) return;+ setBackendDraft(EMPTY_BACKEND_DRAFT);+ setAddingBackend(false);+ // Open what was just made: the next step is adding a harness to it, and+ // that control lives inside the panel.+ onSelectConnection(created.connection.id);+ toast.success('Backend added. Nothing was contacted — add a harness to give it a route.');+ }, [backendDraft, run, onSelectConnection]);++ /**+ * Add a harness to a backend, minting one route per checked mode.+ *+ * Every minted route arrives disabled: this creates the configuration, it+ * does not grant it permission to run.+ */+ const addHarness = useCallback(async (connection, draft) => {+ const created = await run('Adding the harness', () => api.createProviderBinding({+ connectionId: connection.id,+ harnessId: draft.harnessId ?? null,+ modes: draft.modes,+ }, { silent: true }));+ if (!created) return;+ setHarnessDraft(({ [connection.id]: _cleared, ...rest }) => rest);+ toast.success(`Added ${created.routeIds.join(', ')} — disabled, so nothing runs until you enable it.`);+ }, [run]);+const saveConnection = useCallback(async () => {if (!selected) return;const credentials = credentialDraft.trim().length > 0@@ -321,10 +379,20 @@ export default function ProviderConnections({<div className="space-y-4">{loading && <p className="text-sm text-port-muted">Loading connections…</p>}+ <ProviderConnectionForm+ graph={graph}+ draft={backendDraft}+ onChange={setBackendDraft}+ onSubmit={createBackend}+ open={addingBackend}+ onToggle={() => setAddingBackend((isOpen) => !isOpen)}+ busy={busy}+ />+{!loading && groups.length === 0 && (<EmptyStatetitle="No managed connections yet"- message="Connections are imported from your existing provider routes the first time the graph runs. Configure a provider and it will appear here."+ message="Connections are imported from your existing provider routes the first time the graph runs — or add one above and give it a harness."/>)}@@ -422,6 +490,15 @@ export default function ProviderConnections({)}</div>+ <ProviderHarnessForm+ graph={graph}+ connection={group.connection}+ draft={harnessDraft[group.connection.id]}+ onChange={(next) => setHarnessDraft((prev) => ({ ...prev, [group.connection.id]: next }))}+ onSubmit={(input) => addHarness(group.connection, input)}+ busy={busy}+ />+{group.bindings.map(({ binding, label, routes }) => {const offer = bindingModelOffer(group.connection, binding);const stale = staleSelectedModels(group.connection, binding);diff --git a/client/src/components/providers/ProviderConnections.test.jsx b/client/src/components/providers/ProviderConnections.test.jsxindex 886f50fed3..0ec768c7c3 100644--- a/client/src/components/providers/ProviderConnections.test.jsx+++ b/client/src/components/providers/ProviderConnections.test.jsx@@ -23,6 +23,8 @@ const api = vi.hoisted(() => ({linkProviderBinding: vi.fn(),unlinkProviderBinding: vi.fn(),deleteProviderConnection: vi.fn(),+ createProviderConnection: vi.fn(),+ createProviderBinding: vi.fn(),updateProviderRouteSettings: vi.fn(),updateProviderRouteModelAliases: vi.fn(),setActiveProvider: vi.fn(),@@ -42,6 +44,13 @@ const CLAUDE_BINDING = '33333333-3333-4333-8333-333333333333';const graphFixture = () => ({schemaVersion: 1,activeProvider: 'claude-ollama',+ // The static create surface the server publishes, so the browser never has to+ // mirror which harnesses carry a command recipe.+ creatableHarnesses: [+ { id: 'claude', label: 'Claude Code', modes: ['cli', 'tui'], protocol: 'anthropic', credentialKey: 'ANTHROPIC_AUTH_TOKEN', credentialRequired: true },+ { id: 'opencode', label: 'OpenCode', modes: ['cli', 'tui'], protocol: 'openai', credentialKey: 'apiKey', credentialRequired: false },+ ],+ creatableConnectionKinds: [{ id: 'ollama', label: 'Ollama' }, { id: 'api', label: 'Direct API' }],connections: [{id: CONNECTION,@@ -124,7 +133,7 @@ describe('backend connection management', () => {expect(await screen.findByText('Example local daemon')).toBeInTheDocument();// The harness label comes from the mirrored registry, not a raw id.- expect(screen.getByText('Claude Code')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Claude Code' })).toBeInTheDocument();// Both executable routes on that one backend are listed and deep-linkable.expect(screen.getByRole('link', { name: 'claude-ollama' })).toHaveAttribute('href', '/ai/edit/claude-ollama');expect(screen.getByRole('link', { name: 'claude-ollama-tui' })).toBeInTheDocument();@@ -410,3 +419,67 @@ describe('hand-authored model aliases', () => {expect(screen.getByLabelText('Backend model name')).toHaveValue('example-model');});});++describe('adding a backend and a harness (#6369)', () => {+ it('sends exactly one transport and no probe, then opens what it made', async () => {+ const onSelectConnection = vi.fn();+ api.createProviderConnection.mockResolvedValue({ connection: { id: OTHER, label: 'Remote example' } });+ renderPanel({ onSelectConnection });++ fireEvent.click(await screen.findByRole('button', { name: /add a backend/i }));+ fireEvent.change(screen.getByLabelText('Backend name'), { target: { value: 'Remote example' } });+ fireEvent.change(screen.getByLabelText('Base URL'), { target: { value: 'https://ollama.example.com/v1' } });+ fireEvent.change(screen.getByLabelText('Backend'), { target: { value: 'api' } });+ fireEvent.click(screen.getByRole('button', { name: 'Add backend' }));++ await waitFor(() => expect(api.createProviderConnection).toHaveBeenCalled());+ const [body] = api.createProviderConnection.mock.calls[0];+ expect(body).toMatchObject({+ kind: 'api',+ label: 'Remote example',+ transports: { openai: { baseUrl: 'https://ollama.example.com/v1' } },+ });+ // No credential typed, so none is sent — an empty string would be stored as+ // a real (and broken) secret.+ expect(body).not.toHaveProperty('credentials');+ expect(Object.keys(body.transports)).toHaveLength(1);+ expect(api.refreshProviderConnectionModels).not.toHaveBeenCalled();+ // The next step is adding a harness, and that control lives in the panel.+ await waitFor(() => expect(onSelectConnection).toHaveBeenCalledWith(OTHER));+ });++ it('offers only harnesses that speak the backend it is on', async () => {+ renderPanel();+ const select = await screen.findByLabelText('Program');+ // The fixture backend declares the anthropic transport; OpenCode speaks+ // openai and is not offered, because an option whose only outcome is a 409+ // is not an option.+ expect([...select.options].map((option) => option.textContent)).toEqual(['Claude Code']);+ });++ it('creates a disabled binding for the checked modes only', async () => {+ api.createProviderBinding.mockResolvedValue({ routeIds: ['claude-ollama-2'], enabled: false });+ renderPanel();++ fireEvent.click(await screen.findByLabelText('tui'));+ fireEvent.click(screen.getByRole('button', { name: /^Add$/ }));++ await waitFor(() => expect(api.createProviderBinding).toHaveBeenCalled());+ expect(api.createProviderBinding.mock.calls[0][0]).toEqual({+ connectionId: CONNECTION, harnessId: 'claude', modes: ['cli'],+ });+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('disabled'));+ });++ it('refuses to add a harness that needs a credential the backend has not got', async () => {+ api.getProviderManagementGraph.mockResolvedValue({+ ...graphFixture(),+ connections: graphFixture().connections.map((connection) => ({ ...connection, hasCredentials: false })),+ });+ renderPanel();++ expect(await screen.findByText(/ANTHROPIC_AUTH_TOKEN/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /^Add$/ })).toBeDisabled();+ expect(api.createProviderBinding).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/providers/ProviderHarnessForm.jsx b/client/src/components/providers/ProviderHarnessForm.jsxnew file mode 100644index 0000000000..ea50ad35ce--- /dev/null+++ b/client/src/components/providers/ProviderHarnessForm.jsx@@ -0,0 +1,99 @@+import { Plus } from 'lucide-react';+import { connectionProtocol, harnessOptionsFor } from '../../lib/providerManagement';++/**+ * Add a harness to a backend (#6369) — mock flow 2: the same daemon, driven by+ * a second program, as an independent binding with its own executable routes.+ *+ * Two rules the control is built around:+ *+ * - **Only harnesses that speak this backend are offered.** The server+ * refuses one that does not, and an option whose only outcome is a 409 is+ * not an option. A program that needs a credential the backend has not got+ * is shown and disabled WITH the reason, rather than hidden.+ * - **Nothing created here is enabled.** New routes arrive disabled with no+ * model pins; granting execution stays an explicit edit on the route+ * editor. The copy says so, because the button does not.+ */+export default function ProviderHarnessForm({ graph, connection, draft, onChange, onSubmit, busy }) {+ const options = harnessOptionsFor(graph, connection);+ if (options.length === 0) {+ return (+ <p className="text-xs text-port-muted">+ No harness PortOS can point at a {connectionProtocol(connection) || 'transport-less'} backend.+ </p>+ );+ }++ const current = draft || { harnessId: options[0].harnessId, modes: options[0].modes };+ const chosen = options.find((option) => option.harnessId === current.harnessId) || options[0];++ return (+ <div className="rounded border border-dashed border-port-border p-3">+ <h4 className="mb-2 text-sm font-medium">Add a harness</h4>+ <div className="flex flex-wrap items-end gap-3">+ <label className="block text-sm" htmlFor={`add-harness-${connection.id}`}>+ <span className="mb-1 block text-port-muted">Program</span>+ <select+ id={`add-harness-${connection.id}`}+ className="rounded border border-port-border bg-port-bg px-2 py-1"+ value={chosen.harnessId ?? ''}+ disabled={busy}+ onChange={(event) => {+ const next = options.find((option) => (option.harnessId ?? '') === event.target.value);+ onChange({ harnessId: next?.harnessId ?? null, modes: next?.modes ?? [] });+ }}+ >+ {options.map((option) => (+ <option key={option.harnessId ?? 'api'} value={option.harnessId ?? ''}>{option.label}</option>+ ))}+ </select>+ </label>++ <fieldset>+ <legend className="mb-1 text-xs text-port-muted">Modes</legend>+ <div className="flex flex-wrap gap-2">+ {chosen.modes.map((mode) => (+ <label key={mode} className="flex items-center gap-1 text-sm" htmlFor={`add-mode-${connection.id}-${mode}`}>+ <input+ id={`add-mode-${connection.id}-${mode}`}+ type="checkbox"+ checked={current.modes.includes(mode)}+ disabled={busy}+ onChange={(event) => onChange({+ harnessId: chosen.harnessId,+ // Kept in the harness's own mode order, so a route set always+ // reads cli-then-tui however it was clicked.+ modes: chosen.modes.filter((entry) => (entry === mode+ ? event.target.checked+ : current.modes.includes(entry))),+ })}+ />+ {mode}+ </label>+ ))}+ </div>+ </fieldset>++ <button+ type="button"+ disabled={busy || current.modes.length === 0 || Boolean(chosen.needsCredential)}+ onClick={() => onSubmit({ harnessId: chosen.harnessId, modes: current.modes })}+ className="flex items-center gap-1 rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50"+ >+ <Plus size={14} aria-hidden="true" /> Add+ </button>+ </div>++ {chosen.needsCredential && (+ <p className="mt-2 text-xs text-port-warning">+ {chosen.label} will not start without a <code>{chosen.needsCredential}</code>.+ Set one on this backend above first.+ </p>+ )}+ <p className="mt-2 text-xs text-port-muted">+ New routes arrive disabled with no model pins. Enable one on its route editor when you want it to run.+ </p>+ </div>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 86c3b79032..daa2ef872a 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -156,7 +156,7 @@ grep -i "what you want to do" client/src/lib/README.md| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. || `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. || `ports.js` | `PORTS` + `DEFAULT_PEER_PORT`, re-exported from the pure leaf `server/lib/ports.js` (which `ports.test.js` pins against `ecosystem.config.cjs`, the source of truth — see docs/PORTS.md). Use these instead of re-hardcoding a port literal in a form default, a copy-paste help string, or a cross-machine URL. |-| `providerManagement.js` | Joins the `GET /api/providers/management` graph into one row per connection (`groupGraphByConnection`, `findConnectionGroup`), and reads a binding's shared-model state honestly: `bindingModelOffer` (empty `selectedModels` = the whole catalog, not none), `staleSelectedModels` (pins the catalog no longer offers — reported, never repaired), `catalogSummary` (keeps `unknown` / `known`-and-empty / `failed` distinct). `routeOverrideDraft` / `routeOverridePatch` are the mode-override form pair: they walk whatever settings the server published for a route rather than naming fields, send only CHANGED keys, read a blank text field as `null` (unpinned) and a blank timeout as no change. `routeModelAliasRows` renders a route’s canonical→executable aliases with the hand-authored ones marked, and a manual alias naming a spelling the route no longer lists flagged stale rather than dropped. |+| `providerManagement.js` | Joins the `GET /api/providers/management` graph into one row per connection (`groupGraphByConnection`, `findConnectionGroup`), and reads a binding's shared-model state honestly: `bindingModelOffer` (empty `selectedModels` = the whole catalog, not none), `staleSelectedModels` (pins the catalog no longer offers — reported, never repaired), `catalogSummary` (keeps `unknown` / `known`-and-empty / `failed` distinct). `routeOverrideDraft` / `routeOverridePatch` are the mode-override form pair: they walk whatever settings the server published for a route rather than naming fields, send only CHANGED keys, read a blank text field as `null` (unpinned) and a blank timeout as no change. `routeModelAliasRows` renders a route’s canonical→executable aliases with the hand-authored ones marked, and a manual alias naming a spelling the route no longer lists flagged stale rather than dropped. `connectionProtocol` / `transportProtocolOptions` / `harnessOptionsFor` drive the create controls from what the SERVER published (`creatableHarnesses`, `creatableConnectionKinds`) rather than a mirrored table — offering only harnesses that speak a backend’s transport, and naming the credential one still needs. || `morsePractice.js` | Pure deterministic adaptive Morse sampler — `selectMorsePrompt` combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; `canAdvanceMorseLevel` guards level advancement on sample count, accuracy, and effective speed. || `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. || `rapidReaderPosition.js` | Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text. |diff --git a/client/src/lib/providerManagement.js b/client/src/lib/providerManagement.jsindex 0e2fb08fbc..654cfd2c50 100644--- a/client/src/lib/providerManagement.js+++ b/client/src/lib/providerManagement.js@@ -214,3 +214,60 @@ export function routeModelAliasRows(route) {})).sort((a, b) => a.canonical.localeCompare(b.canonical));}++// --- creating a backend and a harness on it (#6369) --------------------------+//+// The two questions the create controls ask of a graph response. Both are+// answered from what the SERVER published (`creatableHarnesses`,+// `creatableConnectionKinds`), never from a table mirrored into the browser:+// which harnesses carry a command recipe, and which backend kinds a minted+// route can honestly describe, are server decisions.++/** The one transport protocol a connection declares, or `null`. */+export const connectionProtocol = (connection) => Object.keys(connection?.transports || {})[0] || null;++/**+ * Transport protocols a new backend may declare, each with the programs that+ * speak it, so the form can say what the choice is FOR.+ *+ * @returns {{protocol:string, drivers:string[]}[]}+ */+export function transportProtocolOptions(graph) {+ const harnesses = Array.isArray(graph?.creatableHarnesses) ? graph.creatableHarnesses : [];+ const byProtocol = new Map();+ for (const harness of harnesses) {+ byProtocol.set(harness.protocol, [...(byProtocol.get(harness.protocol) || []), harness.label]);+ }+ // A direct API route has no harness and speaks the OpenAI-compatible wire, so+ // that protocol is offerable even on a build shipping no OpenAI harness.+ byProtocol.set('openai', [...(byProtocol.get('openai') || []), 'Direct API']);+ return [...byProtocol.entries()]+ .map(([protocol, drivers]) => ({ protocol, drivers }))+ .sort((a, b) => a.protocol.localeCompare(b.protocol));+}++/**+ * The harnesses that can be added to THIS backend, plus the direct API option.+ *+ * Filtered by the backend's declared protocol rather than offered and then+ * refused: the server rejects a harness that does not speak it, and an option+ * whose only outcome is a 409 is not an option. `needsCredential` is why an+ * otherwise-valid choice will still be refused, so the row can say so before+ * the click rather than after it.+ *+ * @returns {{harnessId:string|null, label:string, modes:string[], needsCredential:string|null}[]}+ */+export function harnessOptionsFor(graph, connection) {+ const protocol = connectionProtocol(connection);+ const harnesses = (Array.isArray(graph?.creatableHarnesses) ? graph.creatableHarnesses : [])+ .filter((harness) => harness.protocol === protocol)+ .map((harness) => ({+ harnessId: harness.id,+ label: harness.label,+ modes: harness.modes,+ needsCredential: harness.credentialRequired && !connection?.hasCredentials ? harness.credentialKey : null,+ }));+ return protocol === 'openai'+ ? [...harnesses, { harnessId: null, label: 'Direct API', modes: ['api'], needsCredential: null }]+ : harnesses;+}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 6c55d93151..a33a6da4d5 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -53,7 +53,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiPorts.js` | Port scan/detect wrappers (no current UI callers; module kept for the catalog). || `apiHarnesses.js` | Coding-agent harness (CLI/TUI) inventory for Models → Harnesses: installed vs latest version, the providers riding on each, and the model-catalog refresh. Install/update/remove is an SSE stream driven by `RuntimeInstallModal`, not a call here. || `apiModelComparison.js` | Sourced model comparison catalog, provider discovery and validated observation import. |-| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. |+| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. Also the connection-graph management calls, including `createProviderConnection` / `createProviderBinding`, which add a backend and mint its (disabled) executable routes. || `apiPrompts.js` | Prompt Manager: stage templates, variables, and job-skill templates (providers list reuses `apiProviders.getProviders`). || `apiReferenceRepos.js` | Per-app reference-repo registry. || `apiReview.js` | Review hub. |diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex a906e71461..3d9732dea9 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -111,6 +111,26 @@ export const isManagementUnsupported = (error) =>/** The durable graph: connections, harness bindings and executable routes. */export const getProviderManagementGraph = (options) => request('/providers/management', options);+/**+ * Create a new backend. Nothing is probed and no route is minted — a+ * connection with no binding is a legitimate row you then attach a harness to.+ */+export const createProviderConnection = (body, options) => request('/providers/connections', {+ method: 'POST', body: JSON.stringify(body), ...options,+});++/**+ * Add a harness to an existing backend, minting one executable route per+ * requested mode from that harness's command recipe.+ *+ * Every minted route arrives DISABLED with no model pins: creating a route is a+ * management act, and granting it execution stays a separate, explicit edit on+ * the route editor.+ */+export const createProviderBinding = (body, options) => request('/providers/bindings', {+ method: 'POST', body: JSON.stringify(body), ...options,+});+/** What linking this binding onto another connection would change. Read-only. */export const previewProviderBindingLink = (bindingId, body, options) => request(`/providers/bindings/${encodeURIComponent(bindingId)}/link/preview`,diff --git a/server/lib/README.md b/server/lib/README.mdindex 3fa1b4198b..96345240b1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -198,6 +198,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerGraphPreview.js` | READ-ONLY import preview for the provider connection graph (#6366) — `buildProviderGraphPreview({providers, activeProvider})` projects the records an install already runs into proposed connections, harness bindings and executable routes, grouping ONLY the proven same-harness CLI/TUI siblings from `providerModeGroups` and surfacing a cross-harness daemon match as a `suggestedLinks` entry requiring an explicit link. `toManagementPreviewDto` sanitizes and validates the version-1 DTOs (`managementPreviewSchema`, `PROVIDER_GRAPH_SCHEMA_VERSION`) that `GET /api/providers/management/preview` returns; `projectPreviewToProviders` re-materializes every original record (pins, secrets, consent flags and unknown custom fields included) as the import-fidelity and downgrade proof; `providerGraphUniquenessViolations` checks the UNIQUE constraints #6367 will enforce; `routeModeEligibility` is the pure declarative half of mode eligibility (harness support + enabled + caller-allowed mode + text-transport consent), with the prerequisite/fallback policy left to #6368. Persists nothing and makes no generation call or runtime launch. || `providerGraphRecords.js` | The DURABLE half of the provider connection graph (#6367) — the pure record layer over `ai_connections` / `ai_harness_bindings` / `ai_route_bindings`. `graphFromPreview` / `importGraphFromProviders` mint UUID-keyed rows from a #6366 preview while every executable `providerId` stays untouched; `toManagementGraphDto` (`managementGraphSchema`) sanitizes them for `GET /api/providers/management` (credential PRESENCE only, no projection snapshots); `connectionOwnedSnapshot` / `applyProjections` materialize connection-owned values back into providers.json so a downgraded install still runs; and `planGraphReconciliation` / `reconciliationIsNoop` are the reconciliation contract shared by boot, legacy provider writes and downgrade-edit-reupgrade — acknowledging a landed projection, retrying an interrupted one, REFUSING a third externally changed value, dropping deleted records without resurrecting them, and detaching or splitting a binding whose backend moved. Pure: no DB handle, no file I/O, no provider call. || `providerModelAliases.js` | HAND-AUTHORED canonical→executable model aliases for one provider route (#6369) — the correction surface for a `modelMap` a refresh could only fill with what it could VERIFY. Observed aliases (`ai_route_bindings.model_map`) and user overrides (`model_alias_overrides`) are stored apart and merged on READ by `effectiveModelAliases` (`{ ...observed, ...overrides }`), which is what lets a hand-authored alias outlast the next refresh; `applyModelAliasPatch` is the three-valued edit (absent preserves, a string sets, `null` is the only thing that removes); `staleModelAliases` reports — never repairs — an override naming a spelling the record no longer lists, and makes no claim at all about a route listing no models; `connectionCatalogModels` is the union an alias write re-derives the shared catalog from, so a correction actually reaches the model menus; `modelAliasRevision` is the stale-edit fingerprint, reusing `routeSettingsRevision` because `ai_route_bindings` has no revision column. Pure: no I/O. |+| `providerRouteRecipes.js` | Minting a FRESH executable route from a connection and a harness command recipe (#6369) — the reverse of `providerConnections.js`, which reads an existing record. `buildRouteRecord({harnessId, mode, providerId, name, connection})` materializes a connection's endpoint, credentials and backend marker into a DISABLED `data/providers.json` record through `PROVIDER_HARNESSES[].recipe`; `mintRouteIds` allocates readable ids keeping the `<stem>` / `<stem>-tui` pairing `providerModeGroups` recognizes; `bindingBlocker` is the pre-write refusal (no recipe, unsupported mode, a transport the harness does not speak or is not the backend's only one, a credential the program requires); `CREATABLE_CONNECTION_KINDS` / `connectionKindLabel` / `connectionKindMarkers` bound the backends a route can honestly describe (`slotstream` and `vendor` deliberately excluded); `bindingProtocol` names the wire a binding needs. Pure: no I/O, no spawn, no provider call.| `providerRouteSettings.js` | The MODE-OVERRIDE half of a provider route (#6369) — the route-owned fields a human tunes per execution mode (`args`, `timeout`, `effort` and the `defaultModel`/`lightModel`/`mediumModel`/`heavyModel`/`ultraModel` pins), mirroring what the toolkit's `sharedModeUpdates` already declares mode-specific. `ROUTE_SETTING_FIELDS` / `ROUTE_SETTING_KEYS` / `routeSettingKeys(mode)` name the set (`args` reaches cli/tui only); `routeSettingsFor(provider)` reads it off a record with absent and cleared collapsing to `null`; `routeSettingsSchema` is the wire shape `GET /api/providers/management` publishes; `unsupportedRouteSettings` rejects a key the route's mode does not accept; and `routeSettingsRevision` is the stale-edit fingerprint — a hash of the values as they are in providers.json rather than a graph row revision, so an edit made through `/ai/edit/:providerId` is caught too. Connection-owned values and execution consent (`enabled`) are deliberately absent. Pure: no I/O.| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex bf6f541d9e..0b88e27924 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -13912,6 +13912,14 @@"server/routes/providers.js"]},+ {+ "method": "POST",+ "path": "/api/providers/bindings",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },{"method": "PATCH","path": "/api/providers/bindings/:id",@@ -14016,6 +14024,14 @@"server/routes/modelComparison.js"]},+ {+ "method": "POST",+ "path": "/api/providers/connections",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },{"method": "DELETE","path": "/api/providers/connections/:id",@@ -17972,8 +17988,8 @@],"stats": {"mounts": 150,- "operations": 2226,- "declarations": 2234,+ "operations": 2228,+ "declarations": 2236,"sourceFiles": 233}}diff --git a/server/lib/index.js b/server/lib/index.jsindex 16ad27195d..afd544b695 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -421,6 +421,7 @@ export * from './providerConnections.js';export * from './providerGraphPreview.js';export * from './providerGraphRecords.js';export * from './providerModelAliases.js';+export * from './providerRouteRecipes.js';export * from './providerRouteSettings.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';diff --git a/server/lib/providerConnections.js b/server/lib/providerConnections.jsindex 8f528f0b77..176f9e8fc5 100644--- a/server/lib/providerConnections.js+++ b/server/lib/providerConnections.js@@ -60,8 +60,15 @@ const TRANSPORT_ENV_VARS = Object.freeze({OPENAI_BASE_URL: 'openai',});-/** Env vars that carry connection CREDENTIALS, including each gateway's key var. */-const CREDENTIAL_ENV_VARS = Object.freeze([+/**+ * Env vars that carry connection CREDENTIALS, including each gateway's key var.+ *+ * Exported because it is also the set a freshly MINTED route may materialize a+ * connection's credentials into (`providerRouteRecipes.js`): an env var outside+ * this list is not read back as a credential here, so writing one would make a+ * new route describe a connection it is not actually on.+ */+export const CONNECTION_CREDENTIAL_ENV_VARS = Object.freeze(['ANTHROPIC_AUTH_TOKEN','ANTHROPIC_API_KEY','OPENAI_API_KEY',@@ -187,7 +194,7 @@ export function providerConnectionProfile(provider) {ownedFields.apiKey = record.apiKey;if (isNonEmptyString(record.apiKey)) credentials.apiKey = record.apiKey;}- for (const name of CREDENTIAL_ENV_VARS) {+ for (const name of CONNECTION_CREDENTIAL_ENV_VARS) {if (!Object.hasOwn(envVars, name)) continue;ownedEnvVars[name] = envVars[name];if (isNonEmptyString(envVars[name])) credentials[name] = envVars[name];diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsindex e73668d4e8..35716c0d8b 100644--- a/server/lib/providerGraphRecords.js+++ b/server/lib/providerGraphRecords.js@@ -6,7 +6,7 @@ import {PROVIDER_GRAPH_SCHEMA_VERSION,buildProviderGraphPreview,} from './providerGraphPreview.js';-import { PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './providerHarnesses.js';+import { PROVIDER_HARNESSES, PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './providerHarnesses.js';import {effectiveModelAliases,modelAliasRevision,@@ -14,6 +14,7 @@ import {staleModelAliases,} from './providerModelAliases.js';import { routeSettingsRevision, routeSettingsSchema } from './providerRouteSettings.js';+import { CREATABLE_CONNECTION_KINDS, connectionKindLabel } from './providerRouteRecipes.js';// `PROVIDER_GRAPH_SCHEMA_VERSION` is deliberately NOT re-exported: it is one// wire version shared with the preview, and two flat `export *` modules in this@@ -117,6 +118,41 @@ const routeDtoSchema = z.object({tuiCommandLine: z.string().optional(),}).strict();+// What a client may CREATE (#6369). Both are constants derived from the code+// registries, published rather than mirrored into the browser: which harnesses+// carry a command recipe, and which backend kinds a minted route can honestly+// describe, are server decisions with no rendered value the browser could+// recompute. Additive, so `PROVIDER_GRAPH_SCHEMA_VERSION` stays at 1 and an+// older client simply ignores them.+const creatableHarnessSchema = z.object({+ id: z.enum(PROVIDER_HARNESS_IDS),+ label: z.string().min(1),+ modes: z.array(z.enum(ROUTE_MODES)).min(1),+ protocol: z.string().min(1),+ // The credential key this program needs on the connection, and whether it+ // refuses to start without one — so the form can say so BEFORE the create.+ credentialKey: z.string().min(1),+ credentialRequired: z.boolean(),+}).strict();++const creatableKindSchema = z.object({+ id: z.string().min(1),+ label: z.string().min(1),+}).strict();++/** The static half of the create surface. Derived from code, never from rows. */+const CREATABLE = Object.freeze({+ harnesses: Object.freeze(PROVIDER_HARNESSES.filter((harness) => harness.recipe).map((harness) => Object.freeze({+ id: harness.id,+ label: harness.label,+ modes: [...harness.modes],+ protocol: harness.protocol,+ credentialKey: harness.recipe.credential.via === 'env' ? harness.recipe.credential.name : 'apiKey',+ credentialRequired: harness.recipe.credential.required === true,+ }))),+ kinds: Object.freeze(CREATABLE_CONNECTION_KINDS.map((id) => Object.freeze({ id, label: connectionKindLabel(id) }))),+});+/** The full `GET /api/providers/management` body. */export const managementGraphSchema = z.object({schemaVersion: z.literal(PROVIDER_GRAPH_SCHEMA_VERSION),@@ -124,6 +160,8 @@ export const managementGraphSchema = z.object({connections: z.array(connectionDtoSchema),bindings: z.array(bindingDtoSchema),routes: z.array(routeDtoSchema),+ creatableHarnesses: z.array(creatableHarnessSchema),+ creatableConnectionKinds: z.array(creatableKindSchema),}).strict();/**@@ -153,6 +191,8 @@ export function toManagementGraphDto({ connections, bindings, routes, activeProvreturn managementGraphSchema.parse({schemaVersion: PROVIDER_GRAPH_SCHEMA_VERSION,activeProvider: typeof activeProvider === 'string' ? activeProvider : null,+ creatableHarnesses: CREATABLE.harnesses,+ creatableConnectionKinds: CREATABLE.kinds,connections: connections.map(({ id, revision, kind, label, transports, credentials, catalog }) => ({id,revision,@@ -190,6 +230,17 @@ export function toManagementGraphDto({ connections, bindings, routes, activeProv});}+/**+ * One connection row, sanitized exactly as `GET /api/providers/management`+ * sanitizes it (#6369).+ *+ * Routed through {@link toManagementGraphDto} rather than mapped separately, so+ * the create response and the graph response cannot drift into publishing+ * different things — there is one strict schema and one mapper.+ */+export const toConnectionDto = (connection) =>+ toManagementGraphDto({ connections: [connection], bindings: [], routes: [] }).connections[0];+// --- import ------------------------------------------------------------------/** The connection-owned half of one provider record, as stored in a snapshot. */diff --git a/server/lib/providerHarnesses.js b/server/lib/providerHarnesses.jsindex cf4ec315a0..5abf91300c 100644--- a/server/lib/providerHarnesses.js+++ b/server/lib/providerHarnesses.js@@ -39,7 +39,48 @@ export const ROUTE_MODES = Object.freeze(['cli', 'tui', 'api']);const CLI_TUI_MODES = Object.freeze(['cli', 'tui']);/**- * @type {readonly {id:string,label:string,modes:readonly string[],protocol:string,matches:(p:object)=>boolean}[]}+ * The COMMAND RECIPE half of a harness row (#6369).+ *+ * Everything above classifies a provider record that already exists. A recipe+ * answers the opposite question — **how do you spawn a fresh one?** — which is+ * what minting a new executable route for a connection needs and what this+ * registry could not describe before.+ *+ * Each recipe is the shipped, proven configuration for that program, lifted+ * from its `defaults/providers.sample.json` entry rather than invented here;+ * `providerRouteRecipes.sampleParity.test.js` fails when the two drift, so a+ * minted route can never quietly become one the harness will not run.+ *+ * Columns:+ *+ * - `command` / `modes[mode]` — the binary and its per-mode argv. `cli`+ * carries `headlessArgs`, `tui` carries `tuiPromptDelayMs`; neither is+ * meaningful for the other mode, so neither is declared for it.+ * - `baseUrl` — where a connection's endpoint lands on the record:+ * `{ via: 'env', name }` an environment variable, `{ via: 'field' }` the+ * record's own `endpoint`, or `{ via: 'opencodeConfig' }` the inline+ * provider JSON OpenCode reads.+ * - `credential` — the key the connection must carry for this program, and+ * whether it REFUSES to start without one. Claude Code does (it sends an+ * Anthropic auth token even to a local daemon that ignores it), which is why+ * the create endpoint refuses rather than minting a route that cannot run.+ *+ * A harness with **no** recipe is not an oversight: `native`-protocol programs+ * talk only to their own vendor service, so there is no user-supplied backend to+ * point one at. Adding one of those stays `/ai/new`.+ */++/** Claude Code's headless argv, shared by every Claude recipe mode. */+const CLAUDE_HEADLESS_ARGS = Object.freeze(['--no-session-persistence', '--disable-slash-commands', '--tools', '']);++/** The delay a TUI harness needs before its first prompt, matching every shipped TUI sample. */+const TUI_PROMPT_DELAY_MS = 2500;++/** A local agent run is long; every shipped CLI/TUI sample uses this timeout. */+const HARNESS_TIMEOUT_MS = 600000;++/**+ * @type {readonly {id:string,label:string,modes:readonly string[],protocol:string,recipe:object|null,matches:(p:object)=>boolean}[]}*/export const PROVIDER_HARNESSES = Object.freeze([Object.freeze({@@ -47,6 +88,18 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'Claude Code',modes: CLI_TUI_MODES,protocol: 'anthropic',+ recipe: Object.freeze({+ command: 'claude',+ timeout: HARNESS_TIMEOUT_MS,+ baseUrl: { via: 'env', name: 'ANTHROPIC_BASE_URL' },+ // Claude Code will not start without a token, even against a local daemon+ // that ignores it — so a backend carrying none cannot mint a Claude route.+ credential: { via: 'env', name: 'ANTHROPIC_AUTH_TOKEN', required: true },+ modes: {+ cli: { args: ['--print'], headlessArgs: CLAUDE_HEADLESS_ARGS },+ tui: { args: ['--dangerously-skip-permissions'], tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },+ },+ }),matches: isClaudeProvider,}),Object.freeze({@@ -54,6 +107,18 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'OpenCode',modes: CLI_TUI_MODES,protocol: 'openai',+ recipe: Object.freeze({+ command: 'opencode',+ timeout: HARNESS_TIMEOUT_MS,+ // OpenCode reads its backend out of an inline provider JSON rather than an+ // environment variable, which is also why that string stays route-owned.+ baseUrl: { via: 'opencodeConfig' },+ credential: { via: 'field', required: false },+ modes: {+ cli: { args: ['run'], headlessArgs: [] },+ tui: { args: [], tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },+ },+ }),matches: isOpencodeProvider,}),Object.freeze({@@ -61,6 +126,16 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'Codex',modes: CLI_TUI_MODES,protocol: 'openai',+ recipe: Object.freeze({+ command: 'codex',+ timeout: HARNESS_TIMEOUT_MS,+ baseUrl: { via: 'field' },+ credential: { via: 'field', required: false },+ modes: {+ cli: { args: [], headlessArgs: [] },+ tui: { args: [], tuiPromptDelayMs: TUI_PROMPT_DELAY_MS },+ },+ }),matches: isCodexProvider,}),Object.freeze({@@ -68,6 +143,9 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'Antigravity',modes: CLI_TUI_MODES,protocol: 'native',+ // No recipe: this program reaches only its own vendor service, so+ // there is no connection to point a freshly minted route at.+ recipe: null,matches: isAntigravityProvider,}),Object.freeze({@@ -75,6 +153,9 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'Cursor Agent',modes: CLI_TUI_MODES,protocol: 'native',+ // No recipe: this program reaches only its own vendor service, so+ // there is no connection to point a freshly minted route at.+ recipe: null,matches: isCursorProvider,}),Object.freeze({@@ -82,6 +163,9 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'Grok',modes: CLI_TUI_MODES,protocol: 'native',+ // No recipe: this program reaches only its own vendor service, so+ // there is no connection to point a freshly minted route at.+ recipe: null,matches: isGrokProvider,}),Object.freeze({@@ -89,6 +173,9 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'Kimi Code',modes: CLI_TUI_MODES,protocol: 'native',+ // No recipe: this program reaches only its own vendor service, so+ // there is no connection to point a freshly minted route at.+ recipe: null,matches: isKimiProvider,}),Object.freeze({@@ -96,6 +183,9 @@ export const PROVIDER_HARNESSES = Object.freeze([label: 'Pi',modes: CLI_TUI_MODES,protocol: 'native',+ // No recipe: this program reaches only its own vendor service, so+ // there is no connection to point a freshly minted route at.+ recipe: null,// No `isPiProvider` predicate exists — `pi` has no vendor module of its own// beyond `aiToolkit/internal/pi.js`, so match its binary basename directly.matches: (provider) => commandBasename(provider?.command) === 'pi',@@ -108,6 +198,18 @@ export const PROVIDER_HARNESS_IDS = Object.freeze(PROVIDER_HARNESSES.map((h) =>/** The registry row for a harness id, or `null` for anything else. */export const harnessById = (id) => PROVIDER_HARNESSES.find((h) => h.id === id) || null;+/**+ * The harnesses a fresh route can be MINTED for — the ones carrying a command+ * recipe. Everything else stays classifiable but not creatable, which is a+ * property of the program, not a gap in this table.+ */+export const CREATABLE_HARNESS_IDS = Object.freeze(+ PROVIDER_HARNESSES.filter((h) => h.recipe).map((h) => h.id),+);++/** The command recipe for a harness id, or `null` when it has none. */+export const harnessRecipe = (id) => harnessById(id)?.recipe || null;+/*** The harness a provider record is driven by, or `null`.*diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.jsnew file mode 100644index 0000000000..3eac26f465--- /dev/null+++ b/server/lib/providerRouteRecipes.js@@ -0,0 +1,270 @@+import { CONNECTION_CREDENTIAL_ENV_VARS, CONNECTION_PROTOCOLS } from './providerConnections.js';+import { PROVIDER_GATEWAYS } from './providerGateways.js';+import { CREATABLE_HARNESS_IDS, harnessById, harnessRecipe } from './providerHarnesses.js';+import { LOCAL_RUNTIMES } from './localProviderRuntime.js';++/**+ * Minting a FRESH executable route from a connection and a harness recipe+ * (#6369) — the half of the connection graph that creates rather than+ * classifies.+ *+ * `providerConnections.js` reads an existing record and answers what backend it+ * describes. This module runs that in reverse: given a connection row and a+ * harness's command recipe, it produces the `data/providers.json` record that+ * would reach that backend through that program. `POST /api/providers/bindings`+ * is its only caller, and it verifies the result by feeding it straight back+ * through `providerConnectionProfile` — a minted route that does not describe+ * the connection it was minted for is refused rather than stored, because the+ * reconciler would otherwise clone it onto a connection of its own.+ *+ * Pure: no I/O, no clock, no spawn. Nothing here contacts an AI provider or+ * launches anything — a created route arrives DISABLED and is executed only+ * after the human enables it on the route editor.+ */++/**+ * Backend kinds a connection may be created for, and the record marker that+ * makes a minted route resolve to each one.+ *+ * These markers are what the spawner itself keys on (`localRuntimeNamespace`,+ * `gatewayIdForProvider`), so setting the right one is what gives an OpenCode+ * route its `<namespace>/` model prefix and points a model refresh at the+ * daemon instead of the harness.+ *+ * `slotstream` is deliberately absent: it carries no `*Backed` marker of its+ * own and is resolved by id, name or port, so a minted route could not be made+ * to describe it honestly. `vendor` is absent for the opposite reason — a+ * vendor's own hosted service is not a backend the user supplies.+ */+const LOCAL_RUNTIME_MARKERS = Object.freeze({+ ollama: 'ollamaBacked',+ lmstudio: 'lmstudioBacked',+ mtplx: 'mtplxBacked',+ llama: 'llamaBacked',+ vllm: 'vllmBacked',+ sglang: 'sglangBacked',+});++/** Every `kind` `POST /api/providers/connections` accepts. */+export const CREATABLE_CONNECTION_KINDS = Object.freeze([+ ...Object.keys(LOCAL_RUNTIME_MARKERS),+ ...PROVIDER_GATEWAYS.map((gateway) => `gateway:${gateway.id}`),+ // A bare OpenAI-compatible endpoint with no local daemon and no gateway row+ // behind it — the "separate remote API" case in the design record.+ 'api',+]);++/** A human label for a connection kind, for the picker and for minted route names. */+export const connectionKindLabel = (kind) => LOCAL_RUNTIMES[kind]?.label+ || PROVIDER_GATEWAYS.find((gateway) => `gateway:${gateway.id}` === kind)?.label+ || (kind === 'api' ? 'Direct API' : kind);++/** The record markers a route on this connection kind must carry, or `null` for an unknown kind. */+export function connectionKindMarkers(kind) {+ if (LOCAL_RUNTIME_MARKERS[kind]) return { [LOCAL_RUNTIME_MARKERS[kind]]: true };+ const gateway = PROVIDER_GATEWAYS.find((candidate) => `gateway:${candidate.id}` === kind);+ if (gateway) return { gatewayBacked: gateway.id };+ return kind === 'api' ? {} : null;+}++/**+ * The OpenCode provider namespace a connection kind maps to.+ *+ * The same key space `getOpencodeLocalProviderNamespace` reads back off the+ * markers above, so the inline config this module writes and the model prefix+ * the spawner applies can never name different namespaces.+ */+const opencodeNamespace = (kind) => (kind.startsWith('gateway:') ? kind.slice('gateway:'.length) : kind);++/**+ * The wire protocol a binding needs the connection to speak.+ *+ * A direct API binding has no harness and talks the OpenAI-compatible wire,+ * which is exactly what `providerConnectionProfile` reports for a bare `api`+ * record — so the two agree by construction rather than by coincidence.+ */+export const bindingProtocol = (harnessId) => (harnessId ? harnessById(harnessId)?.protocol ?? null : 'openai');++/**+ * Why this backend cannot be created, or `null`.+ *+ * The counterpart of {@link bindingBlocker}, and the reason both live here+ * rather than in a Zod schema: the registries these answers come from are the+ * same ones a minted record is built from, and `lib/validation.js` is imported+ * by nearly every route in PortOS.+ *+ * @returns {{code:string, message:string}|null}+ */+export function connectionBlocker({ kind, transports }) {+ if (!CREATABLE_CONNECTION_KINDS.includes(kind)) {+ return {+ code: 'PROVIDER_GRAPH_KIND_UNSUPPORTED',+ message: `A route cannot describe a "${kind}" backend. Choose one of: ${CREATABLE_CONNECTION_KINDS.join(', ')}.`,+ };+ }+ const [protocol] = Object.keys(transports || {});+ if (!CONNECTION_PROTOCOLS.includes(protocol)) {+ return {+ code: 'PROVIDER_GRAPH_PROTOCOL_UNSUPPORTED',+ message: `"${protocol}" is not a transport protocol PortOS speaks. Choose one of: ${CONNECTION_PROTOCOLS.join(', ')}.`,+ };+ }+ return null;+}++/**+ * Why this connection cannot carry a route for this harness, or `null`.+ *+ * The transport rule is stricter than "declares the protocol": the connection+ * must declare that protocol and NOTHING else. A minted record's own profile+ * always names exactly one transport (a provider record has one endpoint), so a+ * connection declaring two would not be the connection its own routes describe+ * — and `planGraphReconciliation` would clone each binding onto a fresh+ * single-transport row on the next pass, silently undoing the create.+ *+ * @returns {{code:string, message:string}|null}+ */+export function bindingBlocker({ harnessId, modes, connection }) {+ if (harnessId !== null && !CREATABLE_HARNESS_IDS.includes(harnessId)) {+ return {+ code: 'PROVIDER_HARNESS_NOT_CREATABLE',+ message: `${harnessById(harnessId)?.label || harnessId} reaches only its own vendor service, so it cannot be pointed at a backend connection. Add it from the provider editor instead.`,+ };+ }+ const harness = harnessId ? harnessById(harnessId) : null;+ const unsupported = modes.filter((mode) => (harness ? !harness.modes.includes(mode) : mode !== 'api'));+ if (unsupported.length > 0) {+ return {+ code: 'PROVIDER_HARNESS_MODE_UNSUPPORTED',+ message: `${harness?.label || 'A direct API binding'} has no ${unsupported.join(', ')} mode.`,+ };+ }++ const protocol = bindingProtocol(harnessId);+ const declared = Object.keys(connection.transports || {});+ if (declared.length !== 1 || declared[0] !== protocol) {+ return {+ code: 'PROVIDER_GRAPH_TRANSPORT_MISMATCH',+ message: `This backend declares ${declared.length > 0 ? declared.join(', ') : 'no'} transport(s); a ${harness?.label || 'direct API'} route needs a backend that declares ${protocol} and nothing else.`,+ };+ }++ const credential = harnessId ? harnessRecipe(harnessId)?.credential : null;+ const key = credential?.via === 'env' ? credential.name : 'apiKey';+ if (credential?.required && !connection.credentials?.[key]) {+ return {+ code: 'PROVIDER_GRAPH_CREDENTIAL_REQUIRED',+ message: `${harness.label} will not start without a ${key}. Set one on this backend first — any non-empty value works for a local daemon that ignores it.`,+ };+ }+ return null;+}++/** The base URL a connection declares for `protocol`. */+const connectionBaseUrl = (connection, protocol) => connection.transports?.[protocol]?.baseUrl ?? null;++/** OpenCode's inline provider declaration for one namespace and base URL. */+const opencodeConfigContent = (kind, baseUrl) => JSON.stringify({+ permission: 'allow',+ provider: {+ [opencodeNamespace(kind)]: {+ npm: '@ai-sdk/openai-compatible',+ name: connectionKindLabel(kind),+ options: { baseURL: baseUrl },+ },+ },+});++/**+ * The executable record for one freshly minted route.+ *+ * Every connection-owned value is materialized into the record, exactly as a+ * later projection would write it, so the row this create stores as `projected`+ * is already true of the file and the next reconciliation pass is a no-op.+ *+ * The record arrives **disabled and unpinned**: no `defaultModel`, no models,+ * no transport consent. Creating a route is a management act; executing one is+ * a separate, explicit grant on the route editor.+ *+ * @param {{harnessId:string|null, mode:'cli'|'tui'|'api', providerId:string,+ * name:string, connection:{kind:string, transports:object, credentials:object}}} input+ * @returns {object} the record to hand `createProvider`+ */+export function buildRouteRecord({ harnessId, mode, providerId, name, connection }) {+ const recipe = harnessId ? harnessRecipe(harnessId) : null;+ const baseUrl = connectionBaseUrl(connection, bindingProtocol(harnessId));+ const credentials = connection.credentials || {};+ const envVars = {};+ const secretEnvVars = [];++ if (recipe?.baseUrl.via === 'env') envVars[recipe.baseUrl.name] = baseUrl;+ if (recipe?.baseUrl.via === 'opencodeConfig') {+ envVars.OPENCODE_CONFIG_CONTENT = opencodeConfigContent(connection.kind, baseUrl);+ }+ // Every credential the connection holds is materialized, not just the one+ // the recipe names: the connection is the source of truth, and a minted route+ // that carried a SUBSET would no longer describe the backend it was minted+ // for. Keys outside the recognized set are skipped rather than written as+ // stray env vars, because `providerConnectionProfile` would not read one back+ // as a credential — the two halves have to name the same thing.+ for (const [key, value] of Object.entries(credentials)) {+ if (key === 'apiKey' || !CONNECTION_CREDENTIAL_ENV_VARS.includes(key)) continue;+ envVars[key] = value;+ secretEnvVars.push(key);+ }+ // Claude Code refuses to start without its auth token, so a recipe that+ // declares one always declares the variable — empty only if the guard above+ // let a credential-less connection through, which it does not for a required+ // credential.+ if (recipe?.credential.via === 'env' && !Object.hasOwn(envVars, recipe.credential.name)) {+ envVars[recipe.credential.name] = '';+ }++ return {+ id: providerId,+ name,+ type: mode,+ // `endpoint` is connection-owned on every record shape a projection can+ // write, so setting it here keeps the minted record identical to what the+ // first `PATCH /connections/:id` would produce.+ endpoint: baseUrl,+ apiKey: credentials.apiKey ?? '',+ // `null` for a kind no marker describes — an imported legacy connection can+ // carry one. The record then simply has no marker, and the caller's identity+ // check is what decides whether it still describes this backend.+ ...(connectionKindMarkers(connection.kind) || {}),+ ...(recipe ? { command: recipe.command, timeout: recipe.timeout } : { timeout: 300000 }),+ ...(recipe ? recipe.modes[mode] : {}),+ models: [],+ defaultModel: null,+ enabled: false,+ envVars,+ secretEnvVars,+ };+}++/**+ * Route ids for a new binding's modes: readable, stable and free.+ *+ * The TUI id is the CLI id plus `-tui` because that is the pairing+ * `providerModeGroups` recognizes — mint them any other way and the toolkit+ * stops treating the two modes as one harness on one backend. The whole set is+ * suffixed together for the same reason: uniquifying each id on its own would+ * break the stem relationship the moment one half collided.+ *+ * @param {{harnessId:string|null, kind:string, modes:string[], taken:Set<string>}} input+ * @returns {Record<string,string>} mode → provider id+ */+export function mintRouteIds({ harnessId, kind, modes, taken }) {+ const slug = (value) => String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+ const stem = [harnessId, kind].filter(Boolean).map(slug).join('-') || 'route';+ const idsFor = (base) => Object.fromEntries(modes.map((mode) => [mode, mode === 'tui' ? `${base}-tui` : base]));++ for (let suffix = 0; suffix < 1000; suffix += 1) {+ const ids = idsFor(suffix === 0 ? stem : `${stem}-${suffix + 1}`);+ if (Object.values(ids).every((id) => !taken.has(id))) return ids;+ }+ // Unreachable with any realistic install; a bounded loop beats an unbounded+ // one, and an explicit throw beats returning a colliding id.+ throw new Error(`Could not mint a free route id for ${stem}`);+}diff --git a/server/lib/providerRouteRecipes.sampleParity.test.js b/server/lib/providerRouteRecipes.sampleParity.test.jsnew file mode 100644index 0000000000..278b7f1aad--- /dev/null+++ b/server/lib/providerRouteRecipes.sampleParity.test.js@@ -0,0 +1,99 @@+/**+ * A minted route must run the command line PortOS already ships (#6369).+ *+ * `PROVIDER_HARNESSES[].recipe` is not an invented configuration: each one is+ * the shipped `defaults/providers.sample.json` entry for that program, which is+ * the argv PortOS is known to drive it with. Nothing else in the system checks+ * that, so a recipe edited without its sample (or a sample updated without its+ * recipe) would silently start minting routes that do not run — a failure the+ * user only meets at spawn time, on a route they just created.+ *+ * This pins the FUNCTIONAL half only: the binary, its per-mode argv, the+ * headless/TUI mode fields, and the transport/credential materialization.+ * Display names, model pins and timeouts a user is expected to tune are not+ * part of the contract and are deliberately not compared.+ */++import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { CREATABLE_HARNESS_IDS } from './providerHarnesses.js';+import { buildRouteRecord } from './providerRouteRecipes.js';++const SAMPLES = JSON.parse(readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), 'aiToolkit/defaults/providers.sample.json'),+ 'utf8',+)).providers;++/** The local Ollama daemon the samples below are all configured against. */+const ANTHROPIC_CONNECTION = {+ kind: 'ollama',+ transports: { anthropic: { baseUrl: 'http://localhost:11434' } },+ credentials: { ANTHROPIC_AUTH_TOKEN: 'ollama' },+};+const OPENAI_CONNECTION = {+ kind: 'ollama',+ transports: { openai: { baseUrl: 'http://localhost:11434/v1' } },+ credentials: {},+};++const CASES = [+ { harnessId: 'claude', mode: 'cli', sample: 'claude-ollama', connection: ANTHROPIC_CONNECTION },+ { harnessId: 'claude', mode: 'tui', sample: 'claude-ollama-tui', connection: ANTHROPIC_CONNECTION },+ { harnessId: 'opencode', mode: 'cli', sample: 'opencode-ollama', connection: OPENAI_CONNECTION },+ { harnessId: 'opencode', mode: 'tui', sample: 'opencode-ollama-tui', connection: OPENAI_CONNECTION },+ { harnessId: 'codex', mode: 'cli', sample: 'codex-ollama', connection: OPENAI_CONNECTION },+];++const mint = ({ harnessId, mode, connection, sample }) =>+ buildRouteRecord({ harnessId, mode, providerId: sample, name: 'Example', connection });++describe('harness command recipes match the shipped provider samples', () => {+ it('covers every creatable harness, so a new one cannot ship unpinned', () => {+ expect([...new Set(CASES.map((entry) => entry.harnessId))].sort())+ .toEqual([...CREATABLE_HARNESS_IDS].sort());+ });++ it.each(CASES)('mints $harnessId $mode like $sample', ({ sample, ...input }) => {+ const shipped = SAMPLES[sample];+ expect(shipped, `${sample} is missing from providers.sample.json`).toBeDefined();+ const minted = mint({ ...input, sample });++ expect(minted.command).toBe(shipped.command);+ expect(minted.args).toEqual(shipped.args);+ expect(minted.type).toBe(shipped.type);+ if (input.mode === 'cli') expect(minted.headlessArgs).toEqual(shipped.headlessArgs);+ if (input.mode === 'tui') expect(minted.tuiPromptDelayMs).toBe(shipped.tuiPromptDelayMs);+ expect(minted.secretEnvVars).toEqual(shipped.secretEnvVars);+ });++ it('materializes the backend the same way the Claude sample does', () => {+ const minted = mint(CASES[0]);+ const shipped = SAMPLES['claude-ollama'];+ expect(minted.envVars.ANTHROPIC_BASE_URL).toBe(shipped.envVars.ANTHROPIC_BASE_URL);+ expect(minted.envVars.ANTHROPIC_AUTH_TOKEN).toBe(shipped.envVars.ANTHROPIC_AUTH_TOKEN);+ expect(minted.ollamaBacked).toBe(true);+ });++ it('declares the OpenCode provider the same way its sample does, name aside', () => {+ const minted = JSON.parse(mint(CASES[2]).envVars.OPENCODE_CONFIG_CONTENT);+ const shipped = JSON.parse(SAMPLES['opencode-ollama'].envVars.OPENCODE_CONFIG_CONTENT);+ expect(minted.permission).toBe(shipped.permission);+ // `name` is the label OpenCode shows; everything else is what makes the+ // provider resolve, so only those are the contract.+ expect(minted.provider.ollama.npm).toBe(shipped.provider.ollama.npm);+ expect(minted.provider.ollama.options.baseURL).toBe(shipped.provider.ollama.options.baseURL);+ });++ it('mints nothing enabled, pinned or consented, whatever the recipe', () => {+ for (const entry of CASES) {+ const minted = mint(entry);+ expect(minted.enabled).toBe(false);+ expect(minted.models).toEqual([]);+ expect(minted.defaultModel).toBeNull();+ expect(minted).not.toHaveProperty('textTransportEnabled');+ expect(minted).not.toHaveProperty('allowCustomEndpoint');+ }+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 6ff88a22f4..d323bccdb1 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -14,6 +14,7 @@ import {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 { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';import {FEDERATED_MEDIA_ASSET_MAX_COUNT,@@ -582,6 +583,53 @@ export const providerBindingUnlinkSchema = z.object({}).strict().optional().default({}),}).strict();+// POST /api/providers/connections (#6369) — a NEW backend.+//+// This schema bounds the SHAPE only. Which backend kinds and transport+// protocols are real is checked by `connectionBlocker` in the service, which+// already owns the harness/transport registries — importing them here would+// pull that subtree into the one module nearly every route validates through+// (`lib/importScoping.test.js`), for two enum lists and no extra safety.+//+// Exactly ONE transport, and this is the load-bearing rule: a provider record+// names one endpoint, so the profile a minted route reports always declares one+// transport. A connection declaring two would not be the connection its own+// routes describe, and reconciliation would clone each binding onto a fresh+// single-transport row on the next pass — silently undoing the create.+//+// Credentials take no `null` here, unlike the PATCH above: there is nothing yet+// to clear, so a null would only be a typo with a destructive reading.+export const providerConnectionCreateSchema = z.object({+ kind: z.string().trim().min(1).max(64),+ label: z.string().trim().min(1).max(200),+ transports: z.record(+ z.string().trim().min(1).max(64),+ z.object({ baseUrl: z.string().trim().min(1).max(2048) }).strict(),+ ).refine((value) => Object.keys(value).length === 1, {+ message: 'Declare exactly one transport protocol for this backend',+ }),+ credentials: z.record(+ z.string().trim().min(1).max(128),+ z.string().min(1).max(4096),+ ).optional().default({}),+}).strict();++// POST /api/providers/bindings (#6369) — a NEW harness configuration on an+// existing backend, and the executable routes it owns.+//+// `harnessId` accepts every registry id, not only the creatable ones: a harness+// with no command recipe gets the service's explanation of WHY it cannot be+// pointed at a backend, which is more useful than a schema enum error. `null`+// is the direct API binding and is spelled explicitly rather than by omission,+// because "no harness" is a real choice here, not a missing field.+export const providerBindingCreateSchema = z.object({+ connectionId: z.string().uuid(),+ harnessId: z.enum(PROVIDER_HARNESS_IDS).nullable(),+ modes: z.array(z.enum(ROUTE_MODES)).min(1).max(ROUTE_MODES.length)+ .refine((value) => new Set(value).size === value.length, { message: 'Name each mode once' }),+ label: z.string().trim().min(1).max(200).optional(),+}).strict();+// PATCH /api/providers/connections/:id (#6369).//// `expectedRevision` is REQUIRED, unlike the link schemas where a preview maydiff --git a/server/routes/providers.connectionCreate.test.js b/server/routes/providers.connectionCreate.test.jsnew file mode 100644index 0000000000..75d782340a--- /dev/null+++ b/server/routes/providers.connectionCreate.test.js@@ -0,0 +1,357 @@+/**+ * Creating a backend and a harness on it, end to end (#6369): real Express+ * route → real Zod schema → the real `providerGraph` service → a doubled store+ * and toolkit.+ *+ * This is the half of connection management that ADDS rather than edits, and it+ * was blocked until `PROVIDER_HARNESSES` carried a command recipe — the+ * registry could classify a record it was handed but not describe how to spawn+ * a fresh one. The regressions worth pinning are therefore about what a minted+ * route IS:+ *+ * - it runs the harness's shipped, proven command line;+ * - it reaches the backend it was created on, and DESCRIBES that backend, so+ * the next reconciliation pass does not clone it onto a connection of its+ * own;+ * - it arrives disabled, unpinned and unconsented — creating a route is not+ * granting execution;+ * - nothing is probed, generated or launched by any of it.+ *+ * Fixtures are synthetic. Nothing here is read out of a running install.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express, { Router } from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { providerConnectionProfile, sameConnectionIdentity } from '../lib/providerConnections.js';++const store = {+ readGraph: vi.fn(),+ writeGraph: vi.fn().mockResolvedValue(undefined),+ applyReconciliation: vi.fn().mockResolvedValue(undefined),+ commitPendingProjection: vi.fn().mockResolvedValue(undefined),+ acknowledgeProjection: vi.fn().mockResolvedValue(undefined),+ relinkBinding: vi.fn().mockResolvedValue(undefined),+ deleteConnection: vi.fn(),+ detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+ saveConnectionSettings: vi.fn().mockResolvedValue(2),+ saveBindingSettings: vi.fn().mockResolvedValue(2),+ saveRouteModelMap: vi.fn().mockResolvedValue(undefined),+ saveRouteModelAliases: vi.fn().mockResolvedValue(undefined),+};+vi.mock('../services/providerGraphStore.js', () => store);++const providerService = {+ getAllProviders: vi.fn(),+ createProvider: vi.fn(),+ applyProviderPatches: vi.fn(),+ refreshProviderModelsBatch: vi.fn(),+};+vi.mock('../lib/aiToolkitState.js', async (importOriginal) => ({+ ...(await importOriginal()),+ requireToolkit: () => ({ services: { providers: providerService } }),+}));++const graph = await import('../services/providerGraph.js');+const { createPortOSProviderRoutes } = await import('./providers.js');++const OLLAMA_ANTHROPIC = '11111111-1111-4111-8111-111111111111';+const OLLAMA_OPENAI = '22222222-2222-4222-8222-222222222222';+const KEYLESS = '33333333-3333-4333-8333-333333333333';+const MULTI = '44444444-4444-4444-8444-444444444444';+const BLOCKED = '66666666-6666-4666-8666-666666666666';+const BLOCKED_BINDING = '77777777-7777-4777-8777-777777777777';++const DAEMON = 'http://127.0.0.1:11434';+const DAEMON_OPENAI = 'http://127.0.0.1:11434/v1';+const TOKEN = 'example-local-token';++const connection = (id, overrides) => ({+ id,+ revision: 1,+ kind: 'ollama',+ label: 'Example local daemon',+ transports: { anthropic: { baseUrl: DAEMON } },+ credentials: { ANTHROPIC_AUTH_TOKEN: TOKEN },+ catalog: { state: 'known', models: ['example-model'] },+ ...overrides,+});++const graphFixture = () => ({+ connections: [+ connection(OLLAMA_ANTHROPIC),+ connection(OLLAMA_OPENAI, { transports: { openai: { baseUrl: DAEMON_OPENAI } }, credentials: {} }),+ connection(KEYLESS, { credentials: {} }),+ connection(MULTI, {+ transports: { anthropic: { baseUrl: DAEMON }, openai: { baseUrl: DAEMON_OPENAI } },+ }),+ connection(BLOCKED),+ ],+ bindings: [{+ id: BLOCKED_BINDING, revision: 1, connectionId: BLOCKED, harnessId: 'claude',+ variantKey: 'default', label: 'Claude', enabled: false, selectedModels: [],+ }],+ // A route whose projection was committed but not yet acknowledged: the graph+ // and providers.json disagree about this backend until it settles.+ routes: [{+ providerId: EXISTING.id, bindingId: BLOCKED_BINDING, mode: 'cli', modelMap: {}, modelAliasOverrides: {},+ projected: {}, pending: { fields: {}, envVars: {}, hasEnvVars: true }, pendingRevision: 2,+ }],+});++// One record already on the install, so id minting has something to collide with.+const EXISTING = {+ id: 'claude-ollama',+ name: 'Claude',+ type: 'cli',+ command: 'claude',+ ollamaBacked: true,+ enabled: true,+ models: [],+ envVars: { ANTHROPIC_BASE_URL: DAEMON, ANTHROPIC_AUTH_TOKEN: TOKEN },+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],+};++function app() {+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };+ const server = express();+ server.use(express.json());+ server.use('/api/providers', createPortOSProviderRoutes(toolkit));+ server.use(errorMiddleware);+ return server;+}++/** The records `createProvider` was handed, keyed by id. */+const created = () => new Map(providerService.createProvider.mock.calls.map(([record]) => [record.id, record]));++beforeEach(async () => {+ vi.clearAllMocks();+ graph.resetProviderGraphState();+ store.readGraph.mockResolvedValue(graphFixture());+ // The toolkit persists what it is handed; the service reads the file back to+ // build its `projected` snapshot, so the double has to behave that way too.+ const persisted = new Map([[EXISTING.id, structuredClone(EXISTING)]]);+ providerService.createProvider.mockImplementation(async (record) => {+ persisted.set(record.id, structuredClone(record));+ return record;+ });+ providerService.getAllProviders.mockImplementation(async () => ({+ activeProvider: EXISTING.id,+ providers: [...persisted.values()].map((provider) => structuredClone(provider)),+ }));+ providerService.applyProviderPatches.mockImplementation(async (patches) => Object.keys(patches));+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await graph.initProviderGraph();+ store.writeGraph.mockClear();+ providerService.createProvider.mockClear();+});++afterEach(() => vi.restoreAllMocks());++describe('POST /api/providers/connections', () => {+ it('stores a backend with an unknown catalog and no route, and publishes no secret', async () => {+ const res = await request(app()).post('/api/providers/connections').send({+ kind: 'api',+ label: 'Remote example daemon',+ transports: { openai: { baseUrl: 'https://ollama.example.com/v1' } },+ credentials: { apiKey: 'example-remote-key' },+ });++ expect(res.status).toBe(201);+ expect(res.body.connection).toMatchObject({+ kind: 'api',+ label: 'Remote example daemon',+ hasCredentials: true,+ // Never asked, so never claimed: `[]` would say the backend has no models.+ catalog: { state: 'unknown', models: [] },+ });+ expect(JSON.stringify(res.body)).not.toContain('example-remote-key');++ const [written] = store.writeGraph.mock.calls.at(-1);+ expect(written.connections).toHaveLength(1);+ expect(written.bindings).toHaveLength(0);+ expect(written.routes).toHaveLength(0);+ // Creating a backend contacts nothing and mints nothing.+ expect(providerService.refreshProviderModelsBatch).not.toHaveBeenCalled();+ expect(providerService.createProvider).not.toHaveBeenCalled();+ });++ it('refuses a backend kind no minted route could honestly describe', async () => {+ const res = await request(app()).post('/api/providers/connections').send({+ kind: 'vendor',+ label: 'Anything',+ transports: { openai: { baseUrl: 'https://example.com/v1' } },+ });+ expect(res.status).toBe(400);+ expect(store.writeGraph).not.toHaveBeenCalled();+ });++ it('refuses a backend declaring two transports, which its own routes could never match', async () => {+ const res = await request(app()).post('/api/providers/connections').send({+ kind: 'ollama',+ label: 'Two ports',+ transports: { anthropic: { baseUrl: DAEMON }, openai: { baseUrl: DAEMON_OPENAI } },+ });+ expect(res.status).toBe(400);+ expect(store.writeGraph).not.toHaveBeenCalled();+ });+});++describe('POST /api/providers/bindings', () => {+ it('mints both modes from the harness recipe, disabled, on ids that keep the CLI/TUI pairing', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: OLLAMA_ANTHROPIC, harnessId: 'claude', modes: ['cli', 'tui'] });++ expect(res.status).toBe(201);+ // `claude-ollama` is already taken, so the whole set moves together rather+ // than each id being uniquified on its own — otherwise the `-tui` stem+ // relationship the toolkit pairs modes by would break.+ expect(res.body.routeIds).toEqual(['claude-ollama-2', 'claude-ollama-2-tui']);+ expect(res.body.enabled).toBe(false);++ const records = created();+ expect(records.get('claude-ollama-2')).toMatchObject({+ type: 'cli',+ command: 'claude',+ args: ['--print'],+ headlessArgs: ['--no-session-persistence', '--disable-slash-commands', '--tools', ''],+ enabled: false,+ models: [],+ defaultModel: null,+ // The backend marker is what gives the route its model refresh and, for+ // OpenCode, its namespace prefix.+ ollamaBacked: true,+ envVars: { ANTHROPIC_BASE_URL: DAEMON, ANTHROPIC_AUTH_TOKEN: TOKEN },+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],+ });+ expect(records.get('claude-ollama-2-tui')).toMatchObject({+ type: 'tui',+ args: ['--dangerously-skip-permissions'],+ tuiPromptDelayMs: 2500,+ enabled: false,+ });+ // Creating a route is not granting execution: no consent flag is set here,+ // and no mode opt-in rides along.+ for (const record of records.values()) {+ expect(record).not.toHaveProperty('textTransportEnabled');+ expect(record).not.toHaveProperty('allowCustomEndpoint');+ }+ // Nothing is probed, generated or launched by a create.+ expect(providerService.refreshProviderModelsBatch).not.toHaveBeenCalled();+ });++ it('stores a disabled binding whose routes already describe the backend they were minted on', async () => {+ await request(app()).post('/api/providers/bindings')+ .send({ connectionId: OLLAMA_ANTHROPIC, harnessId: 'claude', modes: ['cli', 'tui'] });++ const [written] = store.writeGraph.mock.calls.at(-1);+ expect(written.bindings[0]).toMatchObject({+ connectionId: OLLAMA_ANTHROPIC, harnessId: 'claude', variantKey: 'default', enabled: false, selectedModels: [],+ });+ expect(written.routes.map((route) => route.mode)).toEqual(['cli', 'tui']);+ // `projected` is read back off what the toolkit actually wrote, so the row+ // and providers.json start in agreement and the reconcile this write+ // triggers has nothing to repair.+ for (const route of written.routes) {+ expect(route.pending).toBeNull();+ expect(route.projected.envVars).toEqual({ ANTHROPIC_BASE_URL: DAEMON, ANTHROPIC_AUTH_TOKEN: TOKEN });+ }+ // The load-bearing invariant: a minted route reports the SAME connection+ // identity as the row it was created on. Anything else and reconciliation+ // clones the binding onto a connection of its own on the next pass.+ const record = created().get(written.routes[0].providerId);+ expect(sameConnectionIdentity(+ providerConnectionProfile(record),+ { kind: 'ollama', transports: { anthropic: { baseUrl: DAEMON } }, credentials: { ANTHROPIC_AUTH_TOKEN: TOKEN } },+ )).toBe(true);+ });++ it('mints an OpenCode route whose inline config names the backend and namespace', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: OLLAMA_OPENAI, harnessId: 'opencode', modes: ['cli'] });++ expect(res.status).toBe(201);+ const record = created().get(res.body.routeIds[0]);+ expect(record.command).toBe('opencode');+ expect(record.args).toEqual(['run']);+ const config = JSON.parse(record.envVars.OPENCODE_CONFIG_CONTENT);+ expect(config.provider.ollama.options.baseURL).toBe(DAEMON_OPENAI);+ });++ it('mints a direct API route with no harness and no command', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: OLLAMA_OPENAI, harnessId: null, modes: ['api'] });++ expect(res.status).toBe(201);+ const record = created().get(res.body.routeIds[0]);+ expect(record).toMatchObject({ type: 'api', endpoint: DAEMON_OPENAI, enabled: false });+ expect(record.command).toBeUndefined();+ });++ it('refuses a harness that reaches only its own vendor service', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: OLLAMA_ANTHROPIC, harnessId: 'cursor', modes: ['cli'] });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('PROVIDER_HARNESS_NOT_CREATABLE');+ expect(providerService.createProvider).not.toHaveBeenCalled();+ expect(store.writeGraph).not.toHaveBeenCalled();+ });++ it('refuses a backend whose transport the harness does not speak', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: OLLAMA_OPENAI, harnessId: 'claude', modes: ['cli'] });++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PROVIDER_GRAPH_TRANSPORT_MISMATCH');+ expect(providerService.createProvider).not.toHaveBeenCalled();+ });++ it('refuses a backend a minted route could not describe, before anything is written', async () => {+ // Two transports: a provider record names one endpoint, so no minted route+ // could ever report this connection's identity back.+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: MULTI, harnessId: 'claude', modes: ['cli'] });++ expect(res.status).toBe(409);+ expect(providerService.createProvider).not.toHaveBeenCalled();+ expect(store.writeGraph).not.toHaveBeenCalled();+ });++ it('refuses a Claude route on a backend with no auth token rather than minting one that cannot start', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: KEYLESS, harnessId: 'claude', modes: ['cli'] });++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PROVIDER_GRAPH_CREDENTIAL_REQUIRED');+ expect(res.body.error).toContain('ANTHROPIC_AUTH_TOKEN');+ expect(providerService.createProvider).not.toHaveBeenCalled();+ });++ it('refuses a mode the harness has no support for', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: OLLAMA_ANTHROPIC, harnessId: 'claude', modes: ['api'] });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('PROVIDER_HARNESS_MODE_UNSUPPORTED');+ });++ it('refuses to add to a backend with an unresolved projection', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: BLOCKED, harnessId: 'claude', modes: ['cli'] });++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PROVIDER_GRAPH_BINDING_BLOCKED');+ expect(providerService.createProvider).not.toHaveBeenCalled();+ });++ it('404s an unknown backend', async () => {+ const res = await request(app()).post('/api/providers/bindings')+ .send({ connectionId: '55555555-5555-4555-8555-555555555555', harnessId: 'claude', modes: ['cli'] });++ expect(res.status).toBe(404);+ expect(res.body.code).toBe('CONNECTION_NOT_FOUND');+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 526ca33dc1..b19327945d 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -1,6 +1,8 @@import { providerModeGroups } from '../lib/aiToolkit/internal/providerModes.js';import { buildProviderGraphPreview, toManagementPreviewDto } from '../lib/providerGraphPreview.js';import {+ createBinding,+ createConnection,getManagementGraph,linkBinding,previewBindingLink,@@ -26,9 +28,11 @@ import {codexLoginStartSchema,providerVisionTestSchema,providerVisionSuiteSchema,+ providerBindingCreateSchema,providerBindingLinkSchema,providerBindingUnlinkSchema,providerBindingUpdateSchema,+ providerConnectionCreateSchema,providerConnectionUpdateSchema,providerRouteModelAliasSchema,providerRouteSettingsUpdateSchema,@@ -323,6 +327,39 @@ export function createPortOSProviderRoutes(aiToolkit) {res.set('Cache-Control', 'no-store').json(await getManagementGraph());}));+ /**+ * Add a NEW backend to the graph (#6369) — mock flow 3 in the decision+ * record: a distinct remote endpoint with its own credentials, created as its+ * own identity even when its model names match a backend already configured.+ *+ * Creation only. Nothing is probed, no model list is fetched, no route is+ * minted and `activeProvider` does not move: a connection with no binding is+ * a legitimate row the user then attaches a harness to.+ */+ router.post('/connections', asyncHandler(async (req, res) => {+ const input = validateRequest(providerConnectionCreateSchema, req.body ?? {});+ res.status(201).json(await createConnection(input));+ }));++ /**+ * Add a harness to an existing backend (#6369) — mock flow 2: the same+ * daemon, driven by a second program, as an INDEPENDENT binding with its own+ * executable route ids.+ *+ * The route records are minted from the harness's command recipe+ * (`PROVIDER_HARNESSES[].recipe`), which is what this endpoint waited on: the+ * registry could classify an existing record but not describe how to spawn a+ * fresh one.+ *+ * Every minted route arrives DISABLED with no model pins. Creating a route is+ * a management act; executing one is a separate grant on `PATCH+ * /api/providers/:id`, and nothing here launches, probes or generates.+ */+ router.post('/bindings', asyncHandler(async (req, res) => {+ const input = validateRequest(providerBindingCreateSchema, req.body ?? {});+ res.status(201).json(await createBinding(input));+ }));+/*** What linking this binding into another connection WOULD change: which* executable route ids move, how the two backends differ, and which variantdiff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex 7c76048238..7a492441c6 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -1,6 +1,11 @@import { randomUUID } from 'node:crypto';import { ServerError } from '../lib/errorHandler.js';-import { compareBackendEndpoints, withConnectionOwnedFields } from '../lib/providerConnections.js';+import {+ compareBackendEndpoints,+ providerConnectionProfile,+ sameConnectionIdentity,+ withConnectionOwnedFields,+} from '../lib/providerConnections.js';import {connectionOwnedSnapshot,mergeConnectionCredentials,@@ -8,6 +13,7 @@ import {planGraphReconciliation,reconciliationIsNoop,sanitizeCatalogError,+ toConnectionDto,toManagementGraphDto,} from '../lib/providerGraphRecords.js';import { resolveRouteModels } from '../lib/providerGraphPreview.js';@@ -17,7 +23,15 @@ import {effectiveModelAliases,modelAliasRevision,} from '../lib/providerModelAliases.js';+import { harnessById } from '../lib/providerHarnesses.js';import { effortLevelsForProvider } from '../lib/providerModels.js';+import {+ bindingBlocker,+ buildRouteRecord,+ connectionBlocker,+ connectionKindLabel,+ mintRouteIds,+} from '../lib/providerRouteRecipes.js';import {routeSettingsFor,routeSettingsRevision,@@ -37,6 +51,7 @@ import {saveConnectionSettings,saveRouteModelAliases,saveRouteModelMap,+ writeGraph,} from './providerGraphStore.js';/**@@ -407,8 +422,20 @@ async function projectRoutes(providerIds, connection) {* @returns {Promise<string[]>} the ids that existed and were written*/function writeProviderPatches(patches) {+ return duringProviderWrite(() => providerService().applyProviderPatches(patches));+}++/**+ * Hold the re-entrancy latch across any provider-file write made from inside a+ * serialized pass — a projection patch, or a freshly minted route.+ *+ * See {@link writeProviderPatches} for why this is load-bearing rather than+ * defensive: the toolkit's post-save hook calls back into the graph, and+ * without the latch that call would queue behind the pass awaiting this write.+ */+function duringProviderWrite(work) {reconciling = true;- return providerService().applyProviderPatches(patches).finally(() => { reconciling = false; });+ return Promise.resolve().then(work).finally(() => { reconciling = false; });}/**@@ -755,3 +782,169 @@ export function updateRouteModelAliases({ providerId, expectedRevision, aliases};});}++// --- creating a backend and a harness on it (#6369) ---------------------------+//+// The two writes that ADD to the graph rather than editing it. Both are local+// I/O only: creating a backend probes nothing, and creating a harness binding+// mints DISABLED routes — configuration never generates, never launches and+// never grants execution consent (AGENTS.md "No cold-bootstrap LLM calls").++/**+ * Create a new backend connection.+ *+ * Deliberately NOT deduplicated against the connections already stored. Two+ * backends that look identical — same vendor, same model names, even the same+ * URL reached differently — are still two backends until a human says+ * otherwise, and inferring otherwise is exactly what the identity rules in+ * `providerConnections.js` exist to forbid. Linking stays an explicit,+ * previewed act.+ *+ * The catalog starts `unknown`, not empty: nothing has been asked yet, and+ * `[]` would claim a backend with no models. Discovery is the separate,+ * explicitly requested `POST /connections/:id/refresh-models`.+ */+export function createConnection({ kind, label, transports, credentials }) {+ return serialize(async () => {+ requireGraph();+ const blocker = connectionBlocker({ kind, transports });+ if (blocker) throw new ServerError(blocker.message, { status: 400, code: blocker.code });+ const connection = {+ id: randomUUID(),+ revision: 1,+ kind,+ label,+ transports,+ credentials: credentials || {},+ catalog: { state: 'unknown', models: [] },+ };+ await writeGraph({ connections: [connection], bindings: [], routes: [] });+ console.log(`🔗 Created provider connection ${connection.id} (${kind}, no routes yet)`);+ return { connection: toConnectionDto(connection) };+ });+}++/**+ * Create a harness binding on an existing backend, plus one executable route+ * per requested mode.+ *+ * This is the create the whole registry work was blocked on: minting a route+ * needs a per-harness COMMAND RECIPE (`PROVIDER_HARNESSES[].recipe`), because+ * the graph could previously only classify records it was handed, never+ * describe how to spawn a fresh one.+ *+ * Three guarantees, in the order they are enforced:+ *+ * 1. **Refuse before writing.** `bindingBlocker` rejects a harness with no+ * recipe, a mode it has no support for, a backend whose transport it does+ * not speak, and a backend missing a credential the program requires.+ * 2. **A minted route must describe the connection it was minted for.** The+ * record is fed straight back through `providerConnectionProfile` and+ * compared with `sameConnectionIdentity`. A mismatch is refused rather+ * than stored, because reconciliation would otherwise clone the binding+ * onto a connection of its own on the very next pass.+ * 3. **Nothing is enabled.** The binding and every route arrive disabled with+ * no model pins and no transport consent. Enabling stays an explicit act+ * on the route editor, which is where granting execution belongs.+ *+ * The `projected` snapshot is read back off the records the toolkit actually+ * wrote, so the graph starts in agreement with `providers.json` and the+ * reconcile this write triggers is a no-op.+ */+export function createBinding({ connectionId, harnessId, modes, label }) {+ return serialize(async () => {+ requireGraph();+ const graph = await readGraph();+ const connection = requireRow(graph.connections, connectionId, 'Connection', 'CONNECTION_NOT_FOUND');++ // A backend mid-projection is precisely where the graph and providers.json+ // disagree about the endpoint and credentials this route would be built+ // from, so a new route decided against it would be built from values still+ // in dispute. Same guard every other mutation on a connection applies.+ requireSettledRoutes(connectionFanout(graph, connection.id).routes);++ const blocker = bindingBlocker({ harnessId, modes, connection });+ if (blocker) {+ const badRequest = blocker.code === 'PROVIDER_HARNESS_NOT_CREATABLE'+ || blocker.code === 'PROVIDER_HARNESS_MODE_UNSUPPORTED';+ throw new ServerError(blocker.message, { status: badRequest ? 400 : 409, code: blocker.code });+ }++ const { providers, activeProvider } = await providerService().getAllProviders();+ const taken = new Set([...providers.map((provider) => provider.id), ...graph.routes.map((route) => route.providerId)]);+ const ids = mintRouteIds({ harnessId, kind: connection.kind, modes, taken });+ const harnessLabel = harnessId ? harnessById(harnessId).label : 'Direct API';+ const name = label || `${harnessLabel} · ${connection.label || connectionKindLabel(connection.kind)}`;++ const records = modes.map((mode) => buildRouteRecord({+ harnessId,+ mode,+ providerId: ids[mode],+ name: mode === 'tui' ? `${name} TUI` : name,+ connection,+ }));+ for (const record of records) {+ if (!sameConnectionIdentity(providerConnectionProfile(record), asProfile(connection))) {+ throw new ServerError(+ `A ${harnessLabel} route cannot describe this backend as it is configured; adjust the backend's transport or credentials first`,+ { status: 409, code: 'PROVIDER_GRAPH_CONNECTION_INCOMPATIBLE' });+ }+ }++ const bindingId = randomUUID();+ const binding = {+ id: bindingId,+ revision: 1,+ connectionId: connection.id,+ harnessId,+ // `default` when this harness is not already on the backend, a labeled+ // variant otherwise — two configurations of one program on one backend+ // are both legitimate and must not collapse into each other.+ variantKey: allocateVariantKey(graph, connection.id, { id: bindingId, harnessId }),+ label: name,+ enabled: false,+ selectedModels: [],+ };++ // If a create fails part-way, the records that landed simply have no graph+ // row yet — the next reconciliation pass imports them as their own fragment+ // rather than losing them. That is the same path a legacy write takes.+ await duringProviderWrite(async () => {+ for (const record of records) await providerService().createProvider(record);+ });++ const { providers: written, activeProvider: activeAfter } = await providerService().getAllProviders();+ const byId = new Map(written.map((provider) => [provider.id, provider]));+ const routes = modes+ .filter((mode) => byId.has(ids[mode]))+ .map((mode) => ({+ providerId: ids[mode],+ bindingId: binding.id,+ mode,+ modelMap: {},+ modelAliasOverrides: {},+ projected: connectionOwnedSnapshot(byId.get(ids[mode])),+ pending: null,+ pendingRevision: null,+ }));+ await writeGraph({ connections: [], bindings: [binding], routes });++ console.log(`🔗 Created ${harnessLabel} binding ${binding.id} on connection ${connection.id}: `+ + `${routes.map((route) => route.providerId).join(', ')} (disabled)`);+ return {+ connectionId: connection.id,+ bindingId: binding.id,+ harnessId,+ variantKey: binding.variantKey,+ label: binding.label,+ enabled: false,+ routeIds: routes.map((route) => route.providerId),+ // Reported rather than hidden: the toolkit adopts the first route as the+ // system default on an install that has none, and a disabled route being+ // named the default grants no execution — but the caller should still be+ // told its default moved.+ activeProvider: activeAfter ?? null,+ activeProviderChanged: (activeAfter ?? null) !== (activeProvider ?? null),+ };+ });+}