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
create a harness's CLI and TUI provider records from one add
[._.]/ Adam Eivy9e5fa4c5457b
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsxindex 91a6af8c7e..a3f5110bc2 100644--- a/client/src/components/providers/ProviderForm.jsx+++ b/client/src/components/providers/ProviderForm.jsx@@ -45,6 +45,9 @@ const PROVIDER_FIELD_RANGES = {topP: { min: 0, max: 1 },};+/** A space-separated argv input as the array the provider schema takes. */+const argList = (text) => (text ? text.split(' ').filter(Boolean) : []);+const rangeMessage = (label, { min, max }, unit = '') =>`${label} must be between ${formatCount(min)} and ${formatCount(max)}${unit ? ` ${unit}` : ''}`;@@ -99,6 +102,23 @@ export default function ProviderForm({ provider, daemonReadiness = null, onCloseconst [newEnvValue, setNewEnvValue] = useState('');const [newEnvSecret, setNewEnvSecret] = useState(false);+ // A CLI create may declare that the same harness ALSO runs as a TUI, which+ // mints both records at once (`modes` on POST /api/providers). Neither field+ // is ever part of a provider record, so both stay out of `formData` — a+ // scratch value that rode the `...formData` spread would have to be deleted+ // back out of every payload.+ //+ // Editing never offers it: pairing describes two records being created+ // together, which a save against one existing record cannot mean.+ const canPairModes = !provider && formData.type === 'cli';+ const [alsoTui, setAlsoTui] = useState(false);+ const [tuiArgs, setTuiArgs] = useState('');++ // The CLI record stays the one this form edits; the TUI sibling is minted+ // from it, so `formData.type` remains a real type and every type-derived+ // control below behaves exactly as it does for a plain CLI provider.+ const createsModePair = canPairModes && alsoTui;+// Live installed Ollama/LM Studio models, folded into the model pickers so a// local provider shows what's actually installed — not just the stale `models`// list stored on the provider record (the "Command R+ / Gemma missing" bug).@@ -275,7 +295,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClosereturn { tab: 'connection', message: 'Endpoint must be a full URL, e.g. http://localhost:1234/v1' };}}- if (formData.type === 'tui' && outOfRange(formData.tuiPromptDelayMs, PROVIDER_FIELD_RANGES.tuiPromptDelayMs)) {+ if ((formData.type === 'tui' || createsModePair) && outOfRange(formData.tuiPromptDelayMs, PROVIDER_FIELD_RANGES.tuiPromptDelayMs)) {return { tab: 'connection', message: rangeMessage('Prompt Paste Delay', PROVIDER_FIELD_RANGES.tuiPromptDelayMs, 'ms') };}if (text(formData.timeout) !== '' && parseTimeoutMs(formData.timeout) == null) {@@ -319,8 +339,8 @@ export default function ProviderForm({ provider, daemonReadiness = null, onCloseconst timeoutInput = String(formData.timeout ?? '').trim();const data = {...formData,- args: formData.args ? formData.args.split(' ').filter(Boolean) : [],- headlessArgs: formData.headlessArgs ? formData.headlessArgs.split(' ').filter(Boolean) : [],+ args: argList(formData.args),+ headlessArgs: argList(formData.headlessArgs),contextWindow: parseOptionalIntField(formData.contextWindow),numCtx: showsNumCtx ? parseOptionalIntField(formData.numCtx) : null,// A blank generation field clears back to "let the backend pick" — `null`@@ -368,6 +388,20 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose} else {delete data.tuiPromptDelayMs;}+ // Both modes from one submit. Only what actually differs per mode is+ // declared: everything else on the body is shared by both records, which is+ // what lets the server pair them as one harness rather than two unrelated+ // routes. `cli: {}` because the body's own `args` / `headlessArgs` already+ // describe the CLI record — the key is there so the pair is declared.+ if (createsModePair) {+ data.modes = {+ cli: {},+ tui: {+ args: argList(tuiArgs),+ ...(Number.isFinite(tuiPromptDelay) ? { tuiPromptDelayMs: tuiPromptDelay } : {}),+ },+ };+ }// These controls belong only to the advertised Codex subscription// transport. Do not stamp false capability fields onto unrelated provider// records when their editor saves an ordinary connection change.@@ -393,7 +427,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose? {...(formData.credentialBootstrapSetupCommand.trim() ? { setupCommand: formData.credentialBootstrapSetupCommand.trim() } : {}),command: bootstrapCommand,- args: formData.credentialBootstrapArgs ? formData.credentialBootstrapArgs.split(' ').filter(Boolean) : [],+ args: argList(formData.credentialBootstrapArgs),...(formData.credentialBootstrapHarnessId.trim() ? { harnessId: formData.credentialBootstrapHarnessId.trim() } : {}),...(formData.credentialBootstrapArgsSeparator.trim() ? { argsSeparator: formData.credentialBootstrapArgsSeparator.trim() } : {}),}@@ -510,6 +544,44 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose/></FormField>+ {/* Most coding harnesses run both headless and interactively.+ PortOS stores one execution mode per record, so configuring+ both used to mean adding the same command twice and hoping+ the two records matched closely enough to be treated as one+ harness. Checking this mints the pair from this one form. */}+ {canPairModes && (+ <div>+ <label htmlFor="provider-also-tui" className="flex items-start gap-2 text-sm text-gray-300 cursor-pointer">+ <input+ id="provider-also-tui"+ type="checkbox"+ checked={alsoTui}+ onChange={(e) => setAlsoTui(e.target.checked)}+ className="mt-1"+ />+ <span>+ This command also runs as a TUI+ <span className="block text-xs text-gray-500">+ Creates the interactive mode alongside this one, sharing the command, endpoint,+ credentials and models. Only the arguments differ.+ </span>+ </span>+ </label>+ </div>+ )}++ {createsModePair && (+ <FormField label="TUI Arguments (space-separated)">+ <input+ type="text"+ value={tuiArgs}+ onChange={(e) => setTuiArgs(e.target.value)}+ placeholder="--dangerously-skip-permissions"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ </FormField>+ )}+{/* Generic support for a harness whose auth is provisioned by anexternal CLI at spawn time — e.g. a company-internal tool thatmints a short-lived token for a proxy and execs the harness@@ -644,7 +716,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose</FormField>)}- {formData.type === 'tui' && (+ {(formData.type === 'tui' || createsModePair) && (<div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><FormField label="Prompt Paste Delay (ms)"><inputdiff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsxindex 2e3978cefd..990326528a 100644--- a/client/src/components/providers/ProviderForm.test.jsx+++ b/client/src/components/providers/ProviderForm.test.jsx@@ -124,6 +124,54 @@ describe('ProviderForm', () => {expect(payload).not.toHaveProperty('credentialBootstrapArgs');});+ it('declares both execution modes from one create when the harness also runs as a TUI', async () => {+ // The whole point: one submit, one pair. Only what genuinely differs per+ // mode is declared — everything else on the body is shared, which is what+ // lets the server pair the two records as one harness.+ renderForm();+ fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'Example Agent' } });+ fireEvent.change(screen.getByLabelText('Command *'), { target: { value: 'example' } });+ fireEvent.change(screen.getByLabelText('Arguments (space-separated)'), { target: { value: '--print' } });+ fireEvent.click(screen.getByLabelText(/also runs as a TUI/));+ fireEvent.change(screen.getByLabelText('TUI Arguments (space-separated)'), { target: { value: '--interactive' } });+ // The interactive mode's paste delay is the form's ONE such control,+ // revealed by the same checkbox rather than rendered a second time.+ fireEvent.change(screen.getByLabelText('Prompt Paste Delay (ms)'), { target: { value: '3000' } });+ fireEvent.click(screen.getByRole('button', { name: 'Create' }));++ await waitFor(() => expect(api.createProvider).toHaveBeenCalled());+ const [payload] = api.createProvider.mock.calls[0];+ expect(payload.modes).toEqual({+ cli: {},+ tui: { args: ['--interactive'], tuiPromptDelayMs: 3000 },+ });+ // The body still describes the CLI record itself — its own `args` are the+ // CLI mode's, which is why `modes.cli` carries nothing — and the checkbox's+ // scratch state is not a provider field.+ expect(payload.type).toBe('cli');+ expect(payload.args).toEqual(['--print']);+ expect(payload).not.toHaveProperty('alsoTui');+ expect(payload).not.toHaveProperty('tuiArgs');+ expect(payload).not.toHaveProperty('tuiPromptDelayMs');+ });++ it('does not offer the pair control when editing an existing provider', () => {+ // Pairing describes two records being MINTED together; an existing+ // record's sibling is added from /ai/new like any other provider.+ renderForm({ provider: { id: 'example', name: 'Example', type: 'cli', command: 'example' } });+ expect(screen.queryByLabelText(/also runs as a TUI/)).not.toBeInTheDocument();+ });++ it('sends no modes on an ordinary single-mode create', async () => {+ renderForm();+ fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'Example Agent' } });+ fireEvent.change(screen.getByLabelText('Command *'), { target: { value: 'example' } });+ fireEvent.click(screen.getByRole('button', { name: 'Create' }));++ await waitFor(() => expect(api.createProvider).toHaveBeenCalled());+ expect(api.createProvider.mock.calls[0][0]).not.toHaveProperty('modes');+ });+it('sends no credentialBootstrap key at all for an api-type provider', async () => {renderForm({provider: { id: 'example-api', name: 'Example API', type: 'api', endpoint: 'https://api.example.com/v1' },diff --git a/docs/API.md b/docs/API.mdindex cff911c28a..d7a19df58a 100644--- a/docs/API.md+++ b/docs/API.md@@ -118,7 +118,7 @@ legacy list for local Apps/Dashboard views.| Method | Endpoint | Description ||--------|----------|-------------|| GET | `/providers` | List all AI providers. Also returns `runnerAllowedCommands` — the CoS Agent Runner's exec allowlist, read-only, so the editor can warn that a custom `command` won't spawn via `/spawn` / `/spawn-tui`. |-| POST | `/providers` | Add new provider |+| POST | `/providers` | Add new provider. A body carrying `modes` (`{ cli: {…}, tui: {…} }`) instead creates BOTH execution modes of one harness in one write — a program that runs headlessly and interactively is one program on one backend, but a record stores one `type`, so configuring both otherwise means adding the same command twice and hoping the two records satisfy the pairing rule. The pair is minted as `<id>` / `<id>-tui` with every grouped field (command, endpoint, credentials, env) shared, and answers `{ providers: [cli, tui] }`; a single-mode create still answers the bare provider object. A mode declares only `args` / `headlessArgs` / `tuiPromptDelayMs` for itself, and `cli: {}` is normal — the body's own fields already describe the CLI record, so the key is there to declare the pair. A per-mode MAP rather than the mode-name ARRAY `POST /providers/bindings` takes, because a binding mints argv from the harness's shipped recipe while a provider added here has none and the user types each mode's arguments. Create-only: `PUT /providers/:id` drops the key. || PUT | `/providers/:id` | Update provider || DELETE | `/providers/:id` | Delete provider || POST | `/providers/:id/test` | Test provider connectivity |diff --git a/server/lib/aiToolkit/internal/providerModes.js b/server/lib/aiToolkit/internal/providerModes.jsindex 0ff0857fa8..97fdaa9841 100644--- a/server/lib/aiToolkit/internal/providerModes.js+++ b/server/lib/aiToolkit/internal/providerModes.js@@ -4,6 +4,17 @@ import { isDeepStrictEqual } from 'node:util';const MODE_KEY_DEFAULTS = { endpoint: '', apiKey: '', envVars: {}, credentialBootstrap: null };+/**+ * The fields two records must AGREE on to be one harness in two modes.+ *+ * Exported because it is a constraint on writers, not just a detail of the+ * reader below: anything a pair minter varies per mode has to stay clear of+ * this list, or it mints a pair this function then refuses to group — the exact+ * failure a dual-mode create exists to prevent. `command` is checked separately+ * (it has no empty-value default).+ */+export const MODE_GROUPED_KEYS = Object.freeze(['endpoint', 'apiKey', 'envVars', 'credentialBootstrap']);+export function providerModeGroups(providers) {const byId = new Map(providers.map(provider => [provider.id, provider]));const paired = new Set();@@ -14,7 +25,7 @@ export function providerModeGroups(providers) {if (!cli || paired.has(cli.id) || !cli.command || cli.command !== tui.command) continue;// `credentialBootstrap` is the connection's auth when there is no apiKey,// so siblings that disagree on it are two connections, not one.- if (!['endpoint', 'apiKey', 'envVars', 'credentialBootstrap'].every(key =>+ if (!MODE_GROUPED_KEYS.every(key =>isDeepStrictEqual(cli[key] || MODE_KEY_DEFAULTS[key], tui[key] || MODE_KEY_DEFAULTS[key]))) continue;groups.push([cli, tui]);paired.add(cli.id);@@ -50,3 +61,49 @@ export function unifyProviderModes(data) {}return changed;}++/**+ * The id and display name a harness's TUI sibling takes.+ *+ * `providerModeGroups` above pairs `<stem>` with `<stem>-tui`, so this is the+ * WRITE side of the rule it reads: mint a sibling any other way and the two+ * records stop being one harness. Declared here, beside the reader, and used by+ * every minter — `expandModePair` below, `mintRouteIds` and `createBinding`+ * for connection-backed routes — so the convention has one spelling.+ *+ * A distinct name matters as much as a distinct id: two identically-named rows+ * in the provider list are indistinguishable.+ */+export const modeSiblingId = (stem, mode) => (mode === 'tui' ? `${stem}-tui` : stem);+export const modeSiblingName = (name, mode) => (mode === 'tui' ? `${name} TUI` : name);++/**+ * Split one dual-mode create body into its per-mode create payloads, or `null`+ * when the body declares no `modes`.+ *+ * A program that runs both headlessly and interactively is one program on one+ * backend, but a record stores exactly one `type` — so configuring both used to+ * mean adding the same command twice and hoping the two records happened to+ * satisfy the pairing rule above. This mints them in that shape by+ * construction: every {@link MODE_GROUPED_KEYS} field (and `command`) comes+ * from the shared body, and only `id`, `name`, `type` and the mode's own+ * declared overrides differ.+ *+ * @param {{modes?:Record<string,object>, id?:string, name:string}} providerData+ * @returns {object[]|null} one create payload per mode, CLI first+ */+export function expandModePair(providerData) {+ const modes = providerData?.modes;+ if (!modes || typeof modes !== 'object') return null;++ const { modes: _modes, ...shared } = providerData;+ const stem = shared.id || String(shared.name).toLowerCase().replace(/[^a-z0-9]/g, '-');++ return ['cli', 'tui'].map((mode) => ({+ ...shared,+ ...modes[mode],+ id: modeSiblingId(stem, mode),+ name: modeSiblingName(shared.name, mode),+ type: mode,+ }));+}diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 120d8fef27..8a93afe62f 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -1,4 +1,4 @@-import { providerModeGroups, sharedModeUpdates, unifyProviderModes } from './internal/providerModes.js';+import { expandModePair, providerModeGroups, sharedModeUpdates, unifyProviderModes } from './internal/providerModes.js';import { readFile, rename } from 'fs/promises';import { existsSync } from 'fs';import { join, dirname, delimiter, isAbsolute } from 'path';@@ -623,6 +623,121 @@ export function createProviderService(config = {}) {await notifyProvidersSaved(data);}+ /**+ * Build ONE record, refusing an id `existing` already holds.+ *+ * PURE — it returns the record rather than storing it, which is what makes a+ * multi-record create atomic for free: a throw on the second record cannot+ * leave the first one behind. That matters because `loadProviders` hands back+ * the WARM CACHE object, so a record written into it and then abandoned would+ * stay visible to every reader in the process despite never reaching disk.+ *+ * The explicit field list (rather than a spread of the body) is the+ * create-side contract this directory keeps — see AGENTS.md — so a new+ * provider field is added here deliberately.+ */+ function buildProviderRecord(existing, providerData) {+ const id = providerData.id || providerData.name.toLowerCase().replace(/[^a-z0-9]/g, '-');++ if (existing[id]) {+ throw new Error('Provider with this ID already exists');+ }++ const provider = {+ id,+ name: providerData.name,+ type: providerData.type || 'cli',+ command: providerData.command || null,+ args: providerData.args || [],+ endpoint: providerData.endpoint || null,+ apiKey: providerData.apiKey || '',+ models: providerData.models || [],+ ...(providerData.hardwareRequirements ? { hardwareRequirements: providerData.hardwareRequirements } : {}),+ ...(providerData.modelHardwareRequirements+ ? { modelHardwareRequirements: providerData.modelHardwareRequirements }+ : {}),+ defaultModel: providerData.defaultModel || null,+ effort: providerData.effort || null,+ lightModel: providerData.lightModel || null,+ mediumModel: providerData.mediumModel || null,+ heavyModel: providerData.heavyModel || null,+ ultraModel: providerData.ultraModel || null,+ fallbackProvider: providerData.fallbackProvider || null,+ fallbackModel: providerData.fallbackModel || null,+ numCtx: providerData.numCtx || null,+ temperature: providerData.temperature,+ topP: providerData.topP,+ thinking: providerData.thinking,+ contextWindow: providerData.contextWindow || null,+ // Per-model windows learned from the provider's own /models catalog.+ // Same non-empty rule the refresh path uses, from one implementation.+ ...modelContextWindowPatch(providerData.modelContextWindows),+ timeout: providerData.timeout || 300000,+ enabled: providerData.enabled !== false,+ // Subscription text-transport capability + its explicit opt-in. Only+ // persisted when set, so every existing HTTP/CLI record stays byte-identical+ // and an older install reading this file sees nothing new.+ ...(typeof providerData.textTransport === 'string' && providerData.textTransport+ ? { textTransport: providerData.textTransport } : {}),+ ...(providerData.textTransportEnabled === true ? { textTransportEnabled: true } : {}),+ ...(providerData.textTransportReadRiskAcknowledged === true+ ? { textTransportReadRiskAcknowledged: true } : {}),+ // Claude Ollama marker — preserve so adopting the sample via POST drives+ // ollama-backed model refresh (see isOllamaBackedProvider).+ ...(providerData.ollamaBacked === true ? { ollamaBacked: true } : {}),+ // MTPLX's native MTP runtime is a separate local OpenAI-compatible+ // backend. Preserve this marker so OpenCode receives the `mtplx/`+ // namespace and model refresh probes its local endpoint.+ // LM Studio is a local backend PortOS already manages; preserve the+ // marker so OpenCode receives the `lmstudio/` namespace and model+ // refresh probes the LM Studio server rather than the harness.+ ...(providerData.lmstudioBacked === true ? { lmstudioBacked: true } : {}),+ ...(providerData.mtplxBacked === true ? { mtplxBacked: true } : {}),+ ...(providerData.llamaBacked === true ? { llamaBacked: true } : {}),+ // The local vLLM container is a third distinct local backend: preserve+ // the marker so OpenCode receives the `vllm/` namespace and model+ // refresh probes the container rather than the OpenCode harness.+ ...(providerData.vllmBacked === true ? { vllmBacked: true } : {}),+ // The SGLang container is a fourth distinct local backend (Hopper/Blackwell,+ // PortOS-owned launch line): preserve the marker so OpenCode receives the+ // `sglang/` namespace and model refresh probes the container.+ ...(providerData.sglangBacked === true ? { sglangBacked: true } : {}),+ // Hosted gateway markers: the generic one plus the legacy per-gateway+ // boolean, both preserved so a record written by any version keeps+ // resolving through internal/gateways.js.+ ...(typeof providerData.gatewayBacked === 'string' && providerData.gatewayBacked+ ? { gatewayBacked: providerData.gatewayBacked } : {}),+ ...(providerData.orcarouterBacked === true ? { orcarouterBacked: true } : {}),+ // Explicit opt-in to send the API key to an arbitrary (non-local,+ // non-allowlisted) endpoint — see endpointGuard.js. Only+ // persisted when true so existing keyless/local providers stay clean.+ ...(providerData.allowCustomEndpoint === true ? { allowCustomEndpoint: true } : {}),+ // Codex 'ignore my ~/.codex/config.toml' pin. Only persisted when true so+ // every existing record stays byte-identical and an older install+ // reading this file sees nothing new.+ ...(providerData.ignoreUserConfig === true ? { ignoreUserConfig: true } : {}),+ // Generic credential-bootstrap wrapper — only persisted when a bootstrap+ // command is actually named, so every existing record stays byte-identical.+ ...(providerData.credentialBootstrap?.command ? { credentialBootstrap: providerData.credentialBootstrap } : {}),+ envVars: providerData.envVars || {},+ secretEnvVars: providerData.secretEnvVars || [],+ headlessArgs: providerData.headlessArgs || [],+ tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,+ ...(providerData.tuiIdleTimeoutMs != null ? { tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs } : {})+ };++ return provider;+ }++ /** Store freshly built records and adopt the first as active on an empty install. */+ function storeProviderRecords(data, records) {+ for (const record of records) {+ data.providers[record.id] = record;+ if (!data.activeProvider) data.activeProvider = record.id;+ }+ unifyProviderModes(data);+ }+return {async getAllProviders() {const data = await loadProviders();@@ -657,104 +772,40 @@ export function createProviderService(config = {}) {async createProvider(providerData) {const data = await loadProviders();- const id = providerData.id || providerData.name.toLowerCase().replace(/[^a-z0-9]/g, '-');-- if (data.providers[id]) {- throw new Error('Provider with this ID already exists');- }-- const provider = {- id,- name: providerData.name,- type: providerData.type || 'cli',- command: providerData.command || null,- args: providerData.args || [],- endpoint: providerData.endpoint || null,- apiKey: providerData.apiKey || '',- models: providerData.models || [],- ...(providerData.hardwareRequirements ? { hardwareRequirements: providerData.hardwareRequirements } : {}),- ...(providerData.modelHardwareRequirements- ? { modelHardwareRequirements: providerData.modelHardwareRequirements }- : {}),- defaultModel: providerData.defaultModel || null,- effort: providerData.effort || null,- lightModel: providerData.lightModel || null,- mediumModel: providerData.mediumModel || null,- heavyModel: providerData.heavyModel || null,- ultraModel: providerData.ultraModel || null,- fallbackProvider: providerData.fallbackProvider || null,- fallbackModel: providerData.fallbackModel || null,- numCtx: providerData.numCtx || null,- temperature: providerData.temperature,- topP: providerData.topP,- thinking: providerData.thinking,- contextWindow: providerData.contextWindow || null,- // Per-model windows learned from the provider's own /models catalog.- // Same non-empty rule the refresh path uses, from one implementation.- ...modelContextWindowPatch(providerData.modelContextWindows),- timeout: providerData.timeout || 300000,- enabled: providerData.enabled !== false,- // Subscription text-transport capability + its explicit opt-in. Only- // persisted when set, so every existing HTTP/CLI record stays byte-identical- // and an older install reading this file sees nothing new.- ...(typeof providerData.textTransport === 'string' && providerData.textTransport- ? { textTransport: providerData.textTransport } : {}),- ...(providerData.textTransportEnabled === true ? { textTransportEnabled: true } : {}),- ...(providerData.textTransportReadRiskAcknowledged === true- ? { textTransportReadRiskAcknowledged: true } : {}),- // Claude Ollama marker — preserve so adopting the sample via POST drives- // ollama-backed model refresh (see isOllamaBackedProvider).- ...(providerData.ollamaBacked === true ? { ollamaBacked: true } : {}),- // MTPLX's native MTP runtime is a separate local OpenAI-compatible- // backend. Preserve this marker so OpenCode receives the `mtplx/`- // namespace and model refresh probes its local endpoint.- // LM Studio is a local backend PortOS already manages; preserve the- // marker so OpenCode receives the `lmstudio/` namespace and model- // refresh probes the LM Studio server rather than the harness.- ...(providerData.lmstudioBacked === true ? { lmstudioBacked: true } : {}),- ...(providerData.mtplxBacked === true ? { mtplxBacked: true } : {}),- ...(providerData.llamaBacked === true ? { llamaBacked: true } : {}),- // The local vLLM container is a third distinct local backend: preserve- // the marker so OpenCode receives the `vllm/` namespace and model- // refresh probes the container rather than the OpenCode harness.- ...(providerData.vllmBacked === true ? { vllmBacked: true } : {}),- // The SGLang container is a fourth distinct local backend (Hopper/Blackwell,- // PortOS-owned launch line): preserve the marker so OpenCode receives the- // `sglang/` namespace and model refresh probes the container.- ...(providerData.sglangBacked === true ? { sglangBacked: true } : {}),- // Hosted gateway markers: the generic one plus the legacy per-gateway- // boolean, both preserved so a record written by any version keeps- // resolving through internal/gateways.js.- ...(typeof providerData.gatewayBacked === 'string' && providerData.gatewayBacked- ? { gatewayBacked: providerData.gatewayBacked } : {}),- ...(providerData.orcarouterBacked === true ? { orcarouterBacked: true } : {}),- // Explicit opt-in to send the API key to an arbitrary (non-local,- // non-allowlisted) endpoint — see endpointGuard.js. Only- // persisted when true so existing keyless/local providers stay clean.- ...(providerData.allowCustomEndpoint === true ? { allowCustomEndpoint: true } : {}),- // Codex 'ignore my ~/.codex/config.toml' pin. Only persisted when true so- // every existing record stays byte-identical and an older install- // reading this file sees nothing new.- ...(providerData.ignoreUserConfig === true ? { ignoreUserConfig: true } : {}),- // Generic credential-bootstrap wrapper — only persisted when a bootstrap- // command is actually named, so every existing record stays byte-identical.- ...(providerData.credentialBootstrap?.command ? { credentialBootstrap: providerData.credentialBootstrap } : {}),- envVars: providerData.envVars || {},- secretEnvVars: providerData.secretEnvVars || [],- headlessArgs: providerData.headlessArgs || [],- tuiPromptDelayMs: providerData.tuiPromptDelayMs || 2500,- ...(providerData.tuiIdleTimeoutMs != null ? { tuiIdleTimeoutMs: providerData.tuiIdleTimeoutMs } : {})- };-- data.providers[id] = provider;- unifyProviderModes(data);+ const provider = buildProviderRecord(data.providers, providerData);+ storeProviderRecords(data, [provider]);+ await saveProviders(data);+ return provider;+ },- if (!data.activeProvider) {- data.activeProvider = id;- }+ /**+ * Create BOTH execution modes of one harness from a single body, in one+ * `providers.json` write.+ *+ * A program that can be driven headlessly and interactively is one program+ * on one backend, but a record stores exactly one `type` — so configuring+ * both used to mean adding the provider twice and hoping the two records+ * happened to satisfy the pairing rule. `expandModePair` mints them in the+ * `<stem>` / `<stem>-tui` shape {@link providerModeGroups} recognizes with+ * every grouped field shared, so the pair arrives already unified instead of+ * as two unrelated routes.+ *+ * Either record colliding with an existing id aborts the whole create with+ * nothing stored — see {@link buildProviderRecord} on why that has to hold+ * against the warm cache and not just against the file.+ *+ * @param {object} providerData - a create body carrying `modes`+ * @returns {Promise<object[]>} the created records, CLI first+ */+ async createProviderModes(providerData) {+ const split = expandModePair(providerData);+ if (!split) throw new Error('createProviderModes requires a modes declaration');+ const data = await loadProviders();+ const created = split.map((modeData) => buildProviderRecord(data.providers, modeData));+ storeProviderRecords(data, created);await saveProviders(data);- return provider;+ return created;},async updateProvider(id, updates) {diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex 00a18d32d1..7b58fd6d8d 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -46,6 +46,45 @@ describe('Provider Service', () => {expect((await providerService.getActiveProvider()).id).toBe('remote');});+ it('creates both execution modes of one harness as a pair the toolkit already groups', async () => {+ // The point of a dual-mode create is not that two records exist — it is+ // that they satisfy the pairing rule, which is what makes the two modes ONE+ // provider for enablement, models and the mode pickers. Minting them with+ // any other id shape, or letting a grouped field differ, silently produces+ // two unrelated routes instead, and nothing would report it.+ const [cli, tui] = await providerService.createProviderModes({+ name: 'Example Agent',+ type: 'cli',+ command: 'example',+ enabled: false,+ modes: {+ cli: { args: ['--print'], headlessArgs: ['--quiet'] },+ tui: { args: ['--interactive'], tuiPromptDelayMs: 3000 },+ },+ });+ expect([cli.id, tui.id]).toEqual(['example-agent', 'example-agent-tui']);+ expect([cli.args, tui.args]).toEqual([['--print'], ['--interactive']]);+ expect(tui.tuiPromptDelayMs).toBe(3000);++ // Grouped: enabling either mode enables the harness.+ await providerService.updateProvider('example-agent-tui', { enabled: true });+ expect((await providerService.getProviderById('example-agent')).enabled).toBe(true);+ });++ it('lands no half-made pair when the second record collides with an existing id', async () => {+ await providerService.createProvider({ name: 'Example Agent TUI', id: 'example-agent-tui', type: 'tui', command: 'example' });+ await expect(providerService.createProviderModes({+ name: 'Example Agent',+ type: 'cli',+ command: 'example',+ modes: { cli: {}, tui: {} },+ })).rejects.toThrow(/already exists/);+ // `loadProviders` hands back the WARM CACHE object, so a CLI half+ // materialized before the collision threw would stay visible to every+ // reader in the process even though nothing reached disk.+ expect(await providerService.getProviderById('example-agent')).toBeNull();+ });+it('persists a credential bootstrap only while one is named, and drops the key on an explicit clear', async () => {const created = await providerService.createProvider({ name: 'Bootstrap CLI', type: 'cli', command: 'claude' });expect(created).not.toHaveProperty('credentialBootstrap');diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex c52dfbb7fd..114c83105d 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -223,6 +223,55 @@ export const providerSchema = z.object({tuiIdleTimeoutMs: z.number().int().min(1000).max(86400000).optional()});+/**+ * What ONE mode of a dual-mode create may set for itself.+ *+ * Every rule is taken from `providerSchema`'s own shape rather than restated,+ * so a bound the single-mode create enforces cannot quietly differ from the one+ * a pair create enforces. The set is deliberately small: anything NOT here is+ * shared by both records, which is what keeps the pair groupable+ * (`providerModeGroups` refuses siblings that disagree on command, endpoint,+ * credentials or env — the disjointness test in `validation.test.js` pins that+ * these keys stay clear of {@link MODE_GROUPED_KEYS}).+ */+const providerModeOverrideSchema = z.object({+ args: providerSchema.shape.args,+ headlessArgs: providerSchema.shape.headlessArgs,+ tuiPromptDelayMs: providerSchema.shape.tuiPromptDelayMs,+}).strict();++/** The keys {@link providerModeOverrideSchema} lets a mode vary. */+export const PROVIDER_MODE_OVERRIDE_KEYS = Object.freeze(Object.keys(providerModeOverrideSchema.shape));++/**+ * POST /api/providers — the create body, which may declare BOTH execution modes+ * of one harness instead of forcing the user to add the CLI and the TUI+ * separately and hope the two records happen to pair.+ *+ * Both keys are required: declaring a single mode is what `type` is for, so the+ * map's presence IS the "make me a pair" request. An empty `cli: {}` is the+ * normal case — the body's own `args` / `headlessArgs` already describe the CLI+ * record, and the key is there so the pair is declared rather than inferred.+ *+ * This `modes` is a per-mode MAP, where `POST /api/providers/bindings` takes a+ * plain array of mode names, because the two creates get their argv from+ * different places: a binding mints from the harness's shipped command recipe,+ * while a provider added here has no recipe at all — the user types each mode's+ * arguments, and they need somewhere to land.+ *+ * Create-only, and deliberately absent from `providerSchema` itself: pairing+ * describes two records being MINTED together, which a PATCH against one+ * existing record cannot mean, so the PATCH route's `providerSchema.partial()`+ * drops the key instead of half-acting on it.+ */+export const providerCreateSchema = providerSchema.extend({+ modes: z.object({+ cli: providerModeOverrideSchema,+ tui: providerModeOverrideSchema,+ }).strict().optional(),+});++// PUT /api/providers/active — set the active provider by id. Constrain to the// same slug shape createProvider assigns (`providerSchema.id`) so a reserved// key like `__proto__` can't reach the `data.providers[id]` lookup indiff --git a/server/lib/aiToolkit/validation.test.js b/server/lib/aiToolkit/validation.test.jsindex 9292c2b2bc..954d6cbf34 100644--- a/server/lib/aiToolkit/validation.test.js+++ b/server/lib/aiToolkit/validation.test.js@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest';-import { sanitizeScreenshotRefs, providerSchema, providerActiveSchema, validate } from './validation.js';+import { sanitizeScreenshotRefs, providerCreateSchema, providerSchema, providerActiveSchema, PROVIDER_MODE_OVERRIDE_KEYS, validate } from './validation.js';+import { MODE_GROUPED_KEYS } from './internal/providerModes.js';describe('sanitizeScreenshotRefs — POST /api/runs screenshot hardening (#1870)', () => {it('keeps an in-dir image basename unchanged', () => {@@ -259,3 +260,30 @@ describe('providerSchema.partial() — PUT /api/providers/:id (#2521)', () => {expect(validate(providerSchema.partial(), { timeout: 'soon' }).success).toBe(false);});});++describe('providerCreateSchema — declaring both execution modes of one harness', () => {+ const body = { name: 'Example Agent', type: 'cli', command: 'example' };++ it('never lets a mode vary a field the pairing rule compares', () => {+ // The invariant the whole feature rests on: a minted pair has to be one+ // `providerModeGroups` will GROUP. Widen the per-mode overrides to a key+ // that grouping compares — `envVars`, say — and each create silently mints+ // two unrelated routes instead of one harness, with nothing to report it.+ expect(PROVIDER_MODE_OVERRIDE_KEYS.filter(key => MODE_GROUPED_KEYS.includes(key))).toEqual([]);+ expect(PROVIDER_MODE_OVERRIDE_KEYS).not.toContain('command');+ });++ it('holds each mode to the same field rules as a single-mode create', () => {+ // Derived from `providerSchema.shape`, so a bound can only change for both.+ const withDelay = (tuiPromptDelayMs) =>+ validate(providerCreateSchema, { ...body, modes: { cli: {}, tui: { tuiPromptDelayMs } } }).success;+ expect(withDelay(3000)).toBe(true);+ expect(withDelay(10)).toBe(validate(providerSchema, { ...body, tuiPromptDelayMs: 10 }).success);+ expect(validate(providerCreateSchema, { ...body, modes: { cli: {}, tui: { endpoint: 'http://x' } } }).success).toBe(false);+ });++ it('requires both modes — declaring one is what `type` is for', () => {+ expect(validate(providerCreateSchema, { ...body, modes: { cli: {} } }).success).toBe(false);+ expect(validate(providerCreateSchema, body).success).toBe(true);+ });+});diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.jsindex 2f006eeb68..7f6de94b08 100644--- a/server/lib/providerRouteRecipes.js+++ b/server/lib/providerRouteRecipes.js@@ -1,4 +1,5 @@import { CONNECTION_CREDENTIAL_ENV_VARS, CONNECTION_PROTOCOLS } from './providerConnections.js';+import { modeSiblingId } from './aiToolkit/internal/providerModes.js';import { PROVIDER_GATEWAYS } from './providerGateways.js';import { CREATABLE_HARNESS_IDS, harnessById, harnessRecipe } from './providerHarnesses.js';import { LOCAL_RUNTIMES } from './localProviderRuntime.js';@@ -257,11 +258,11 @@ export function buildRouteRecord({ harnessId, mode, providerId, name, connection/*** 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.+ * The sibling id comes from `modeSiblingId`, declared beside the+ * `providerModeGroups` reader that pairs on it — mint one 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@@ -269,7 +270,7 @@ export function buildRouteRecord({ harnessId, mode, providerId, name, connectionexport 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]));+ const idsFor = (base) => Object.fromEntries(modes.map((mode) => [mode, modeSiblingId(base, mode)]));for (let suffix = 0; suffix < 1000; suffix += 1) {const ids = idsFor(suffix === 0 ? stem : `${stem}-${suffix + 1}`);diff --git a/server/routes/providers.js b/server/routes/providers.jsindex f2ec01da1e..44a66abbaf 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -18,7 +18,7 @@ import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';import { auditModelPins, clearModelPin } from '../services/modelPinAudit.js';-import { providerSchema, providerActiveSchema, validate } from '../lib/aiToolkit/validation.js';+import { providerCreateSchema, providerSchema, providerActiveSchema, validate } from '../lib/aiToolkit/validation.js';import { withRefreshCapability } from '../lib/aiToolkit/internal/modelFetchers.js';import { ALLOWED_COMMANDS } from '../cos-runner/allowedCommands.js';import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';@@ -930,16 +930,29 @@ export function createPortOSProviderRoutes(aiToolkit) {res.json(presentProvider(provider, await detectSystemCapabilities()));}));- // POST / — intercept to (a) validate the body against providerSchema so+ // POST / — intercept to (a) validate the body against providerCreateSchema so// invalid fields like `timeout: "abc"` or non-object `envVars` don't// persist and later break runner behavior, and (b) sanitize the created// provider before responding so apiKey/secret envVar values don't echo// back to the client (the toolkit's POST returns the raw provider).+ //+ // A body declaring `modes` creates BOTH execution modes of one harness and+ // responds with `{ providers: [cli, tui] }` — a distinct shape rather than a+ // polymorphic one, so a caller reading `.id` off a single-mode create keeps+ // working and a pair create cannot silently hide the id of the second record.router.post('/', asyncHandler(async (req, res) => {- const validation = validate(providerSchema, req.body);+ const validation = validate(providerCreateSchema, req.body);if (!validation.success) {throw new ServerError('Invalid provider data', { status: 400, code: 'VALIDATION_ERROR', context: { details: validation.errors } });}+ if (validation.data.modes) {+ const created = await providerService.createProviderModes(validation.data);+ // One snapshot for the pair — the probe is per-host, not per-record, and+ // it stays BEHIND the create so a refused one never pays for it.+ const capabilities = await detectSystemCapabilities();+ res.status(201).json({ providers: created.map(provider => presentProvider(provider, capabilities)) });+ return;+ }const provider = await providerService.createProvider(validation.data);res.status(201).json(presentProvider(provider, await detectSystemCapabilities()));}));diff --git a/server/routes/providers.management.test.js b/server/routes/providers.management.test.jsindex 053719eb4f..2d2aa63942 100644--- a/server/routes/providers.management.test.js+++ b/server/routes/providers.management.test.js@@ -130,3 +130,67 @@ describe('the preview contacts no AI provider and launches no runtime', () => {expect(closure.files.has(abs('lib/providerConnections.js'))).toBe(true);});});++// A harness that runs both headlessly and interactively is ONE program on one+// backend, but `providers.json` stores one execution mode per record — so+// configuring both used to mean adding the same command twice from /ai/new and+// hoping the two records matched closely enough for `providerModeGroups` to+// pair them. `modes` on the create body mints the pair from one submit; what+// the ROUTE owns is dispatching on it, the response envelope, and sanitizing+// every record in it. The ids, names and per-mode fields the split produces are+// pinned where they are decided, in `lib/aiToolkit/providers.test.js`.+describe('POST /api/providers — creating both execution modes at once', () => {+ const PAIR = [+ { id: 'example-agent', name: 'Example Agent', type: 'cli', command: 'example', apiKey: 'sk-secret' },+ { id: 'example-agent-tui', name: 'Example Agent TUI', type: 'tui', command: 'example', apiKey: 'sk-secret' },+ ];+ const BODY = {+ name: 'Example Agent',+ type: 'cli',+ command: 'example',+ args: ['--print'],+ modes: { cli: {}, tui: { args: ['--interactive'], tuiPromptDelayMs: 3000 } },+ };+ const pairService = () => ({+ createProvider: vi.fn().mockResolvedValue(PAIR[0]),+ createProviderModes: vi.fn().mockResolvedValue(PAIR),+ });++ it('answers with every created record, sanitized', async () => {+ const service = pairService();+ const res = await request(appWith(service)).post('/api/providers').send(BODY);++ expect(res.status).toBe(201);+ expect(service.createProviderModes).toHaveBeenCalledWith(expect.objectContaining({ modes: BODY.modes }));+ expect(service.createProvider).not.toHaveBeenCalled();+ expect(res.body.providers.map((provider) => provider.id)).toEqual(['example-agent', 'example-agent-tui']);+ // Redaction has to cover the SECOND record too — it carries the same key.+ expect(res.body.providers.every((provider) => provider.apiKey === undefined)).toBe(true);+ expect(res.body.providers.every((provider) => provider.hasApiKey === true)).toBe(true);+ });++ it('leaves the single-mode response a bare provider object', async () => {+ // A caller reading `.id` off a create must not have to know about `modes`,+ // which is why the pair answer is a distinct shape rather than always-array.+ const service = pairService();+ const { modes: _modes, ...single } = BODY;+ const res = await request(appWith(service)).post('/api/providers').send(single);++ expect(res.status).toBe(201);+ expect(res.body.providers).toBeUndefined();+ expect(res.body.id).toBe('example-agent');+ expect(service.createProviderModes).not.toHaveBeenCalled();+ });++ it('never lets `modes` reach the service through an update', async () => {+ // Pairing describes two records being MINTED together, which a PATCH+ // against one existing record cannot mean — so the key is dropped rather+ // than half-acted on.+ const updateProvider = vi.fn().mockResolvedValue(PAIR[0]);+ const app = appWith({ getProviderById: vi.fn().mockResolvedValue(PAIR[0]), updateProvider });++ const res = await request(app).put('/api/providers/example-agent').send({ enabled: true, modes: BODY.modes });+ expect(res.status).toBe(200);+ expect(updateProvider.mock.calls[0][1]).not.toHaveProperty('modes');+ });+});diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex 177a6779ea..bbcd2ba183 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -25,6 +25,7 @@ import {modelAliasRevision,} from '../lib/providerModelAliases.js';import { harnessById } from '../lib/providerHarnesses.js';+import { modeSiblingName } from '../lib/aiToolkit/internal/providerModes.js';import { effortLevelsForProvider } from '../lib/providerModels.js';import {bindingBlocker,@@ -858,7 +859,7 @@ export function createBinding({ connectionId, harnessId, modes, label }) {harnessId,mode,providerId: ids[mode],- name: mode === 'tui' ? `${name} TUI` : name,+ name: modeSiblingName(name, mode),connection,}));for (const record of records) {