Skip to content

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

fix: carry gateway sibling key through provider clones and fallback picks

[._.]/ Adam Eivy7d4cd5d1c43c
diff --git a/server/lib/README.md b/server/lib/README.md
index ce8367ab61..e277c1b566 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -221,7 +221,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, idPattern, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)`, `familyForProviderId(id)` (the weaker id-only classifier a Zod schema can use, null when the id names no family) → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |
| `fleetQuotas.js` | Unifies subscription-quota readings across federated instances — one plan, several machines, each able to read only its own local CLI. `sanitizeQuotaCards` bounds a peer-supplied payload to the wire shape; `mergeFleetQuotaCards(localCards, peerEntries)` folds every peer's reading into this install's cards, taking the FRESHEST reading per limit key (the meters are account-wide, so summing them would multiply one allowance) and SUMMING activity counts (those are per-machine, which is why the provider captions them "does not include other devices"); `fleetNote` writes the caption naming what was combined. `metrics[]` is left local — its values are prose, not addends. Fed by `services/providerQuotaShare.js` (this machine's readings, persisted) and `services/peerUsage.js` (the `usage` sync category that carries them). |
| `harnessOutput.js` | Parsers for what a coding-agent HARNESS prints about itself: `parseHarnessVersion(stdout)` (the one semver run in a `--version` banner, `null` when unparseable), `compareHarnessVersions(a, b)` (the null-guarding wrapper around `versionUtils.js#compareSemver` — `null` when either side is unparseable, so a version that did not parse never reads as "out of date"), `parseHarnessModels(harnessId, stdout)` + `HARNESS_MODEL_PARSER_IDS` (OpenCode's `provider/model` lines and Grok's bulleted list are parsed here; Antigravity and Cursor DELEGATE to `antigravity.js#parseAntigravityModelList` / `aiToolkit/internal/cursor.js#parseCursorModelList`, which the provider-card refresh has used for far longer), `MAX_MODELS`, and `parseNpmLatestVersion`. Pure: the service layer runs the child and hands the captured stdout here, so the vendor output shapes are pinned by table-driven tests instead of by running six real binaries in CI. Model ids come back in the exact spelling `--model` takes — namespaces kept where the vendor keeps them. Consumed by `services/providerRuntimeInstaller.js` and `services/harnesses.js`. |
-| `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`, `nvidia-nim`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, and `isGatewayBackedProvider(config)`. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) — `providerGateways.parity.test.js` fails when the two drift; `client/src/utils/providerGateways.js` re-exports this leaf rather than copying it. Dependency-light: imports nothing. |
+| `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`, `nvidia-nim`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)`, `gatewayForProvider(config)` → row or null, `isGatewayBackedProvider(config)`, and `attachGatewaySiblingKey(provider, providers)` — the synchronous twin of the toolkit's `withGatewayApiKey` for callers holding an already-loaded (RAW, keyless) collection: a fallback pick armed from such a map executes with its sibling's key instead of going out with no Authorization header. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) — `providerGateways.parity.test.js` fails when the two drift; `client/src/utils/providerGateways.js` re-exports this leaf rather than copying it. Dependency-light: imports nothing. |
| `providerHarnesses.js` | Provider HARNESS identity for the connection graph (#6366) — `PROVIDER_HARNESSES` (one row per agent program PortOS drives: claude/opencode/codex/antigravity/cursor/grok/kimi/pi, each with its supported `modes`, wire `protocol` and the existing `is*Provider` predicate as its matcher), `PROVIDER_HARNESS_IDS`, `harnessById`, `harnessForProvider` (null for an `api` record AND for an unknown harness — use `providerRouteMode` to tell them apart), `harnessSupportsMode`, `ROUTE_MODES`, plus the model-name adapters `toExecutableModelName` / `toCanonicalModelName` (the verified inverse of `prefixOpencodeModel`: a stored alias is canonicalized only when it maps back to the exact stored string, so import never rewrites a saved model by heuristically stripping a prefix). Distinct from `providerVendors.js` (argv-shaped), `providerFamilies.js` (subscription quota) and `providerGateways.js` (hosted backend). Pure leaf — `client/src/utils/providerHarnesses.js` names a binding's harness through `harnessById`. |
| `providerContextWindows.js` | The context-window ladder for provider/model planning, split out of `services/stageRunner.js` so the browser shares it: the vendor constants (`DEFAULT_LARGE_CONTEXT_WINDOW` / `CODEX_CONTEXT_WINDOW` / `GEMINI_CONTEXT_WINDOW` / `GROK_CONTEXT_WINDOW` / `KIMI_CONTEXT_WINDOW`), `knownModelContextWindow(model)` (the known-model regex table), `knownProviderContextWindow(provider)` (the vendor window for a configured-default CLI/TUI provider) and `catalogModelContextWindow(provider, model)` (the window the provider's own `/models` catalog reported, which outranks the table). `stageRunner.js` builds `effectiveContextWindow` on them; `client/src/utils/providerContextWindows.js` re-exports them for the provider-card budget meter, so the two ends can't resolve a different window. Pure. |
| `providerConnections.js` | Provider CONNECTION identity for the connection graph (#6366) — `providerConnectionProfile(provider)` reads one record as the backend it describes (`kind`, `protocol`, `transports`, RAW server-only `credentials`, the `owned` field/env split, and `reasons` from `CONNECTION_ISOLATION_REASONS` when the config is dynamic, external, unparsable or endpoint-less). `sameConnectionIdentity` compares real credential values and refuses once any is the `REDACTED_CREDENTIAL` sentinel, so a sanitized record can never merge two connections; `compareBackendEndpoints` is the looser same-daemon test that only ever produces a link SUGGESTION, applying the recognized OpenAI-compatible `/v1` conversion (never DNS resolution, loopback/remote equivalence or arbitrary path trimming). `projectConnectionOwnedFields(provider, connection)` projects a stored backend through the reader's protocol and env-ownership rules for the graph service; `withoutConnectionOwnedFields` / `withConnectionOwnedFields` are the lossless split/materialize pair that keeps a downgraded install runnable from `data/providers.json` alone. Pure: no I/O. |
diff --git a/server/lib/providerGateways.js b/server/lib/providerGateways.js
index 45fbaf24be..a4af62ad65 100644
--- a/server/lib/providerGateways.js
+++ b/server/lib/providerGateways.js
@@ -109,3 +109,35 @@ export const gatewayIdForProvider = (provider) => gatewayForProvider(provider)?.
/** True when a provider is an OpenCode wrapper front-ending any hosted gateway. */
export const isGatewayBackedProvider = (provider) => gatewayForProvider(provider) !== null;
+
+/**
+ * Attach a gateway-backed wrapper's sibling API key for execution, from an
+ * already-loaded provider collection.
+ *
+ * The synchronous twin of `withGatewayApiKey` in `lib/aiToolkit/providers.js`
+ * (which reads the live store): `getAllProviders` returns RAW records with no
+ * inherited key, and a fallback pick taken from such a map would otherwise
+ * execute with no Authorization header — NVIDIA NIM 401s "Header of type
+ * `authorization` was missing" despite a stored key. Same contract: the key
+ * lands as a NON-ENUMERABLE property so it never persists, leaks into
+ * responses, or survives a spread/JSON round-trip (callers that clone must
+ * re-carry it — see `providerForRun` in `services/promptRunner.js`).
+ *
+ * Pure: returns the input untouched when there is nothing to attach (not
+ * gateway-backed, own key already set, or sibling keyless/missing).
+ *
+ * @param {object|null|undefined} provider — the wrapper to arm for execution
+ * @param {Record<string, object>|Array<object>|null|undefined} providers — the sibling collection
+ * @returns {object|null|undefined} the key-carrying copy, or the input
+ */
+export function attachGatewaySiblingKey(provider, providers) {
+ if (!provider || typeof provider !== 'object' || provider.apiKey) return provider;
+ const gateway = gatewayForProvider(provider);
+ if (!gateway) return provider;
+ const siblings = Array.isArray(providers) ? providers : Object.values(providers || {});
+ const siblingKey = siblings.find((entry) => entry?.id === gateway.id)?.apiKey || null;
+ if (!siblingKey) return provider;
+ const armed = { ...provider };
+ Object.defineProperty(armed, 'apiKey', { value: siblingKey, enumerable: false, configurable: true });
+ return armed;
+}
diff --git a/server/lib/providerGateways.test.js b/server/lib/providerGateways.test.js
index 6912ade404..461a4d1622 100644
--- a/server/lib/providerGateways.test.js
+++ b/server/lib/providerGateways.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
PROVIDER_GATEWAYS,
PROVIDER_GATEWAY_IDS,
+ attachGatewaySiblingKey,
gatewayById,
gatewayForProvider,
gatewayIdForProvider,
@@ -54,6 +55,44 @@ describe('providerGateways', () => {
expect(isGatewayNamespace('ollama')).toBe(false);
expect(isGatewayNamespace(null)).toBe(false);
});
+
+ describe('attachGatewaySiblingKey', () => {
+ const sibling = { id: 'nvidia-nim', type: 'api', apiKey: 'nvapi-test-key' };
+ const wrapper = {
+ id: 'opencode-nvidia-nim',
+ type: 'cli',
+ command: 'opencode',
+ gatewayBacked: 'nvidia-nim',
+ };
+
+ it('attaches the sibling key as non-enumerable', () => {
+ const armed = attachGatewaySiblingKey(wrapper, [sibling, wrapper]);
+ expect(armed.apiKey).toBe('nvapi-test-key');
+ expect(Object.keys(armed)).not.toContain('apiKey');
+ expect(JSON.parse(JSON.stringify(armed)).apiKey).toBeUndefined();
+ // The stored record is untouched.
+ expect(wrapper.apiKey).toBeUndefined();
+ });
+
+ it('accepts a map keyed by id', () => {
+ const armed = attachGatewaySiblingKey(wrapper, { 'nvidia-nim': sibling });
+ expect(armed.apiKey).toBe('nvapi-test-key');
+ });
+
+ it('returns the input untouched when there is nothing to attach', () => {
+ // Not gateway-backed.
+ const local = { id: 'x', ollamaBacked: true };
+ expect(attachGatewaySiblingKey(local, [sibling])).toBe(local);
+ // Own key wins over the sibling.
+ const ownKey = { ...wrapper, apiKey: 'own-key' };
+ expect(attachGatewaySiblingKey(ownKey, [sibling])).toBe(ownKey);
+ // Sibling keyless or missing.
+ expect(attachGatewaySiblingKey(wrapper, [{ ...sibling, apiKey: '' }])).toBe(wrapper);
+ expect(attachGatewaySiblingKey(wrapper, [])).toBe(wrapper);
+ expect(attachGatewaySiblingKey(wrapper, null)).toBe(wrapper);
+ expect(attachGatewaySiblingKey(null, [sibling])).toBeNull();
+ });
+ });
});
describe('prefixOpencodeModel — gateway namespacing', () => {
diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.js
index ffcd0d4de6..edff634804 100644
--- a/server/services/agentProviderResolution.js
+++ b/server/services/agentProviderResolution.js
@@ -24,6 +24,7 @@ import { isProviderAvailable, getFallbackProvider, getProviderStatus } from './p
import { selectModelForRole, selectModelForTask } from './agentModelSelection.js';
import { modelPinIsOffered } from '../lib/localProviderRuntime.js';
import { allowedModesFor, callerModeRejection } from '../lib/callerModePolicy.js';
+import { attachGatewaySiblingKey } from '../lib/providerGateways.js';
import { PRIMARY_ORCHESTRATION_ROLE, roleAssignment } from '../lib/orchestrationProfile.js';
import { publicReviewPostureForTask, resolvePublicReviewProvider } from './publicReviewProviderSelection.js';
@@ -235,7 +236,12 @@ async function resolveOrdinaryProviderAndModel(task) {
fallbackProvider: fallbackResult.provider.id,
fallbackSource: fallbackResult.source
});
- provider = fallbackResult.provider;
+ // The fallback comes from the RAW provider map (`getAllProviders`), which
+ // carries no gateway-inherited key — a gateway-backed wrapper picked here
+ // would spawn without its sibling's apiKey and fail auth (NVIDIA NIM 401s
+ // "Header of type `authorization` was missing") despite a stored key.
+ // Attach it from the same map (synchronous — no re-read to go stale).
+ provider = attachGatewaySiblingKey(fallbackResult.provider, providersMap);
fallbackModelPin = fallbackResult.model || null;
} else {
const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;
diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.js
index 37367a0b30..efd625db4d 100644
--- a/server/services/agentProviderResolution.test.js
+++ b/server/services/agentProviderResolution.test.js
@@ -157,6 +157,50 @@ describe('resolveAgentProviderAndModel', () => {
expect(r.selectedModel).toBe('fb-model');
});
+ it('attaches the sibling key when a fallback pick is a gateway wrapper', async () => {
+ // The fallback pick comes from the RAW provider map, which carries no
+ // gateway-inherited key. Without the attach the wrapper spawns with no
+ // Authorization header (NVIDIA NIM 401s "Header of type `authorization`
+ // was missing") despite a stored key.
+ const primary = { id: 'p1', type: 'cli' };
+ const sibling = { id: 'nvidia-nim', type: 'api', apiKey: 'nvapi-test-key' };
+ const rawWrapper = {
+ id: 'opencode-nvidia-nim',
+ type: 'cli',
+ command: 'opencode',
+ gatewayBacked: 'nvidia-nim',
+ models: ['poolside/laguna-xs-2.1'],
+ defaultModel: 'poolside/laguna-xs-2.1',
+ };
+ getActiveProvider.mockResolvedValue(primary);
+ isProviderAvailable.mockReturnValue(false);
+ getProviderStatus.mockReturnValue({ message: 'rate-limit', reason: 'rl' });
+ getAllProviders.mockResolvedValue({ providers: [primary, sibling, rawWrapper] });
+ getFallbackProvider.mockResolvedValue({ provider: rawWrapper, model: null, source: 'provider' });
+
+ const r = await resolveAgentProviderAndModel(TASK);
+ expect(r.ok).toBe(true);
+ expect(r.provider.id).toBe('opencode-nvidia-nim');
+ expect(r.provider.apiKey).toBe('nvapi-test-key');
+ // Execution-only: the key must not leak as an enumerable property.
+ expect(Object.keys(r.provider)).not.toContain('apiKey');
+ });
+
+ it('keeps the raw fallback pick when no sibling key exists', async () => {
+ const primary = { id: 'p1', type: 'cli' };
+ const fallback = { id: 'p2', type: 'cli', models: ['fb-model'] };
+ getActiveProvider.mockResolvedValue(primary);
+ isProviderAvailable.mockReturnValue(false);
+ getProviderStatus.mockReturnValue({ message: 'rate-limit', reason: 'rl' });
+ getAllProviders.mockResolvedValue({ providers: [primary, fallback] });
+ getFallbackProvider.mockResolvedValue({ provider: fallback, model: 'fb-model', source: 'provider' });
+
+ const r = await resolveAgentProviderAndModel(TASK);
+ expect(r.ok).toBe(true);
+ expect(r.provider).toBe(fallback);
+ expect(r.selectedModel).toBe('fb-model');
+ });
+
it('falls back from an unavailable Ultra mapping to an offered Heavy model', async () => {
getActiveProvider.mockResolvedValue({ id: 'p1', type: 'cli', models: ['heavy'], ultraModel: 'unavailable', heavyModel: 'heavy' });
selectModelForTask.mockResolvedValue({ model: 'unavailable', tier: 'ultra', reason: 'user-preference' });
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index 80804e39e3..d7ff7d49e5 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -45,6 +45,7 @@ import { extractJson } from '../lib/jsonExtract.js';
import { isCreativeRunSource, withCreativeLatitude } from '../lib/creativeLatitude.js';
import { DEFAULT_OUTPUT_RESERVE_TOKENS, estimateTokens } from '../lib/contextBudget.js';
import { allowedModesFor, callerModeRejection } from '../lib/callerModePolicy.js';
+import { attachGatewaySiblingKey } from '../lib/providerGateways.js';
// The fallback-lifecycle notifiers live in services/autoFixer.js, which
// transitively pulls in services/cos.js (PM2 + fs + sockets). Importing it
@@ -1093,7 +1094,12 @@ async function pickFallbackProvider(failed, requestCapabilities) {
const picked = providerStatus.getFallbackProvider(failed.id, providersMap, null, null, requestCapabilities);
if (!picked?.provider) return null;
- return { provider: picked.provider, model: picked.model ?? null };
+ // The pick comes from the RAW provider map (`getAllProviders`), which carries
+ // no gateway-inherited key — a gateway-backed wrapper picked here would execute
+ // without its sibling's apiKey and fail auth (NVIDIA NIM 401s "Header of type
+ // `authorization` was missing") despite a stored key. Attach it from the same
+ // map (synchronous — no re-read to go stale).
+ return { provider: attachGatewaySiblingKey(picked.provider, providersMap), model: picked.model ?? null };
}
/**
@@ -1425,6 +1431,19 @@ async function executeProviderRunOnce({
...(effort ? { effort } : {}),
}
: effectiveProvider;
+ // `withGatewayApiKey` attaches a gateway-backed wrapper's sibling key as a
+ // NON-ENUMERABLE property (so it never persists or leaks) — which the spread
+ // above drops. A model-pinned or effort-overridden CLI/TUI run would then go
+ // out with no Authorization header (NVIDIA NIM 401s "Header of type
+ // `authorization` was missing") despite a stored key. Re-carry it with the
+ // same enumerability so the clone executes with identical credentials.
+ if (providerForRun !== effectiveProvider && !providerForRun.apiKey && effectiveProvider?.apiKey) {
+ Object.defineProperty(providerForRun, 'apiKey', {
+ value: effectiveProvider.apiKey,
+ enumerable: false,
+ configurable: true,
+ });
+ }
if (effectiveProvider.type === PROVIDER_TYPES.CLI) {
executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, screenshots, onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);
diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.js
index fba459fbac..f3c060b4e2 100644
--- a/server/services/promptRunner.test.js
+++ b/server/services/promptRunner.test.js
@@ -818,6 +818,110 @@ describe('promptRunner — TUI provider routing', () => {
});
});
+// =============================================================================
+// Gateway-inherited credentials — a gateway-backed OpenCode wrapper (OrcaRouter,
+// OpenRouter, NVIDIA NIM) stores no key; `withGatewayApiKey` attaches the
+// sibling API record's key as a NON-ENUMERABLE property at read time. Anything
+// that clones or re-resolves the provider must carry that key along, or the
+// run goes out with no Authorization header (NVIDIA NIM 401s "Header of type
+// `authorization` was missing") despite a stored key.
+// =============================================================================
+
+describe('promptRunner — gateway sibling-key preservation', () => {
+ // Mirror of `withGatewayApiKey`: the key is readable but invisible to
+ // spread/JSON, which is exactly what made the clone below drop it.
+ const gatewayAttached = (record, apiKey) => {
+ const attached = { ...record };
+ Object.defineProperty(attached, 'apiKey', { value: apiKey, enumerable: false, configurable: true });
+ return attached;
+ };
+ const nimCli = () => gatewayAttached({
+ id: 'opencode-nvidia-nim',
+ type: 'cli',
+ command: 'opencode',
+ gatewayBacked: 'nvidia-nim',
+ models: ['google/gemma-4-31b-it', 'poolside/laguna-xs-2.1'],
+ defaultModel: 'poolside/laguna-xs-2.1',
+ timeout: 5000,
+ }, 'nvapi-test-key');
+ const nimTui = () => gatewayAttached({
+ id: 'opencode-nvidia-nim-tui',
+ type: 'tui',
+ command: 'opencode',
+ gatewayBacked: 'nvidia-nim',
+ models: ['google/gemma-4-31b-it', 'poolside/laguna-xs-2.1'],
+ defaultModel: 'poolside/laguna-xs-2.1',
+ timeout: 5000,
+ }, 'nvapi-test-key');
+
+ it('carries the sibling key onto the model-pinned CLI provider clone', async () => {
+ runner.executeCliRun.mockImplementation(async ({ provider, onComplete }) => {
+ expect(provider.apiKey).toBe('nvapi-test-key');
+ expect(provider.defaultModel).toBe('google/gemma-4-31b-it');
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: nimCli(),
+ model: 'google/gemma-4-31b-it',
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);
+ expect(out.model).toBe('google/gemma-4-31b-it');
+ });
+
+ it('carries the sibling key onto the model-pinned TUI provider clone', async () => {
+ tuiRunner.executeTuiRun.mockImplementation(async ({ provider, onComplete }) => {
+ expect(provider.apiKey).toBe('nvapi-test-key');
+ expect(provider.defaultModel).toBe('google/gemma-4-31b-it');
+ onComplete({ success: true, text: 'done' });
+ });
+
+ await runPromptThroughProvider({
+ provider: nimTui(),
+ model: 'google/gemma-4-31b-it',
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(tuiRunner.executeTuiRun).toHaveBeenCalledTimes(1);
+ });
+
+ it('carries the sibling key when only an effort override forces the clone', async () => {
+ runner.executeCliRun.mockImplementation(async ({ provider, onComplete }) => {
+ expect(provider.apiKey).toBe('nvapi-test-key');
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: nimCli(),
+ prompt: 'p',
+ source: 'test',
+ effort: 'high',
+ });
+
+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves the provider untouched when no clone is needed', async () => {
+ const wrapper = nimCli();
+ runner.executeCliRun.mockImplementation(async ({ provider, onComplete }) => {
+ expect(provider).toBe(wrapper);
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: wrapper,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);
+ });
+});
+
// =============================================================================
// API timeout enforcement — executeApiRun now owns the primary wall-clock
// timeout (it aborts + finalizes as TIMEOUT and fires onComplete). promptRunner
@@ -1355,6 +1459,52 @@ describe('promptRunner — retry-with-fallback', () => {
expect(mapPassed).toHaveProperty('primary-cli');
});
+ it('attaches the sibling key when a Tier-3 fallback pick is a gateway wrapper', async () => {
+ // The fallback pick comes from the RAW provider map, which carries no
+ // gateway-inherited key. Without the attach the wrapper executes with
+ // no Authorization header (NVIDIA NIM 401s "Header of type `authorization`
+ // was missing") despite a stored key.
+ const sibling = { id: 'nvidia-nim', type: 'api', apiKey: 'nvapi-test-key' };
+ const rawWrapper = {
+ id: 'opencode-nvidia-nim',
+ name: 'OpenCode NVIDIA NIM',
+ type: 'cli',
+ command: 'opencode',
+ gatewayBacked: 'nvidia-nim',
+ models: ['poolside/laguna-xs-2.1'],
+ defaultModel: 'poolside/laguna-xs-2.1',
+ };
+ const status = mockToolkitWithFallback(rawWrapper);
+ providers.getAllProviders.mockResolvedValue({
+ activeProvider: null,
+ providers: [primaryCli, primaryApi, sibling, rawWrapper],
+ });
+
+ const executedProviders = [];
+ runner.executeCliRun
+ .mockImplementationOnce(async ({ onComplete }) => {
+ onComplete({ success: false, error: 'primary boom' });
+ })
+ .mockImplementationOnce(async ({ provider, onData, onComplete }) => {
+ executedProviders.push(provider);
+ onData('recovered');
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ });
+
+ expect(out.usedFallback).toBe(true);
+ expect(out.fallbackProvider).toMatchObject({ id: 'opencode-nvidia-nim' });
+ expect(out.fallbackProvider.apiKey).toBe('nvapi-test-key');
+ expect(executedProviders).toHaveLength(1);
+ expect(executedProviders[0].apiKey).toBe('nvapi-test-key');
+ expect(status.markUnavailable).toHaveBeenCalledWith('primary-cli', expect.any(Object));
+ });
+
it('does not turn a successful fallback into a failure when noteFallbackHandled itself throws (best-effort suppression)', async () => {
mockToolkitWithFallback();
autoFixer.noteFallbackHandled.mockImplementation(() => {