Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(gateway): add protected credentials

Darren Kattan59140388cb4d
diff --git a/docs/copilot-agent.md b/docs/copilot-agent.md
index da22fd51e..4ab1d28a5 100644
--- a/docs/copilot-agent.md
+++ b/docs/copilot-agent.md
@@ -29,8 +29,13 @@ Primary references:
## Model gateway mapping
-The user enters one Bifrost-compatible root and virtual key. Discovery calls `<root>/v1/models`.
-For a selected Copilot model:
+The user enters one gateway root and chooses either an environment-variable name (persisted as
+`${env:VAR}`) or a write-only literal key held in protected local storage. Discovery calls the
+OpenAI-compatible `<root>/v1/models` endpoint—the OpenAI Models API convention adopted by both
+LiteLLM and Bifrost—and sends both bearer auth and Bifrost's `x-bf-vk` compatibility header.
+An unavailable credential fails before any authenticated request. The
+provider launch routes below are specifically the current Bifrost layout. For a selected Copilot
+model:
- `anthropic/<model>` uses provider type `anthropic`, base URL `<root>/anthropic`, internal model id
`<model>`, and wire model `anthropic/<model>`.
diff --git a/src/core/agent-env-ipc.test.ts b/src/core/agent-env-ipc.test.ts
new file mode 100644
index 000000000..abff3ec2f
--- /dev/null
+++ b/src/core/agent-env-ipc.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { IPC } from '../shared/ipc'
+import { MODEL_GATEWAY_SECRET_REF } from '../shared/agents/model-gateway'
+import { registerAgentEnvIpc } from './agent-env-ipc'
+import { ModelGatewayCredentialService } from './model-gateway-credentials'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { initPlatform, resetPlatformForTests } from './platform'
+
+describe('model gateway discovery API-key expansion', () => {
+ let fake: FakePlatform
+ let fetchMock: ReturnType<typeof vi.fn>
+ let inheritedKey: string | undefined
+ let credentials: ModelGatewayCredentialService
+ let storedKey: string | null
+
+ beforeEach(async () => {
+ inheritedKey = process.env.NODETERM_TEST_GATEWAY_KEY
+ fake = fakePlatform()
+ initPlatform(fake)
+ fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ data: [{ id: 'openai/gpt-5.5' }] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' }
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+ storedKey = null
+ credentials = new ModelGatewayCredentialService({
+ availability: 'encrypted',
+ readForHost: async () => storedKey,
+ save: async (value) => {
+ storedKey = value
+ },
+ clear: async () => {
+ storedKey = null
+ }
+ })
+ await credentials.init()
+ registerAgentEnvIpc(credentials)
+ })
+
+ afterEach(() => {
+ if (inheritedKey === undefined) delete process.env.NODETERM_TEST_GATEWAY_KEY
+ else process.env.NODETERM_TEST_GATEWAY_KEY = inheritedKey
+ vi.unstubAllGlobals()
+ resetPlatformForTests()
+ })
+
+ it('expands the key in core before authenticating model discovery', async () => {
+ process.env.NODETERM_TEST_GATEWAY_KEY = 'vk-from-env'
+
+ const result = await fake.handlers[IPC.agentDiscoverModels]({
+ baseUrl: 'https://bifrost.example.test',
+ apiKey: '${env:NODETERM_TEST_GATEWAY_KEY}'
+ })
+
+ expect(result).toEqual({
+ models: [{ id: 'openai/gpt-5.5', provider: 'openai' }]
+ })
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://bifrost.example.test/v1/models',
+ expect.objectContaining({
+ headers: {
+ Authorization: 'Bearer vk-from-env',
+ 'x-bf-vk': 'vk-from-env',
+ Accept: 'application/json'
+ }
+ })
+ )
+ })
+
+ it('does not make a request when the referenced variable is unset', async () => {
+ delete process.env.NODETERM_TEST_GATEWAY_KEY
+
+ const result = await fake.handlers[IPC.agentDiscoverModels]({
+ baseUrl: 'https://bifrost.example.test',
+ apiKey: '${env:NODETERM_TEST_GATEWAY_KEY}'
+ })
+
+ expect(result).toEqual({
+ models: [],
+ error:
+ 'Gateway API key environment variable is unset: ${env:NODETERM_TEST_GATEWAY_KEY}.'
+ })
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('keeps a literal key write-only and uses it for discovery', async () => {
+ await expect(
+ fake.handlers[IPC.agentGatewayCredentialSave]('stored-gateway-key')
+ ).resolves.toEqual({ hasStoredKey: true, storage: 'encrypted' })
+
+ const result = await fake.handlers[IPC.agentDiscoverModels]({
+ baseUrl: 'https://gateway.example.test',
+ apiKey: MODEL_GATEWAY_SECRET_REF
+ })
+
+ expect(result).toEqual({
+ models: [{ id: 'openai/gpt-5.5', provider: 'openai' }]
+ })
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://gateway.example.test/v1/models',
+ expect.objectContaining({
+ headers: {
+ Authorization: 'Bearer stored-gateway-key',
+ 'x-bf-vk': 'stored-gateway-key',
+ Accept: 'application/json'
+ }
+ })
+ )
+ await expect(fake.handlers[IPC.agentGatewayCredentialClear]()).resolves.toEqual({
+ hasStoredKey: false,
+ storage: 'encrypted'
+ })
+ })
+})
diff --git a/src/core/agent-env-ipc.ts b/src/core/agent-env-ipc.ts
index 936a85b4e..cacc11b13 100644
--- a/src/core/agent-env-ipc.ts
+++ b/src/core/agent-env-ipc.ts
@@ -1,6 +1,6 @@
-// Main/server IPC handlers for the custom-agent preview: env-var expansion and command assembly
-// run here (against the real `process.env`) because the renderer has no `process.env` of its own.
-// The preview is therefore guaranteed to match what `pty-manager` will actually type into the shell.
+// Main/server IPC handlers for custom-agent previews and model-gateway credentials. Env expansion
+// runs here (against the real `process.env`) because the renderer has no process environment of
+// its own; literal gateway keys cross this boundary write-only and are read back only by core.
import { IPC } from '../shared/ipc'
import { platform } from './platform'
@@ -8,9 +8,11 @@ import { assembleLaunchCommand, type LaunchInputs } from '../shared/agents/launc
import {
modelGatewayRoutes,
parseGatewayModels,
+ resolveModelGatewayApiKey,
type ModelDiscoveryResult,
type ModelGatewaySettings
} from '../shared/agents/model-gateway'
+import type { ModelGatewayCredentialService } from './model-gateway-credentials'
const DISCOVERY_TIMEOUT_MS = 10_000
@@ -19,17 +21,41 @@ const DISCOVERY_TIMEOUT_MS = 10_000
* and the API key should never be interpolated into a terminal command. Every failure is returned
* as data so opening Settings or a context menu cannot create an unhandled rejection.
*/
-async function discoverModels(settings: ModelGatewaySettings): Promise<ModelDiscoveryResult> {
+async function discoverModels(
+ settings: ModelGatewaySettings,
+ storedSecret: string | null
+): Promise<ModelDiscoveryResult> {
const routes = modelGatewayRoutes(settings?.baseUrl ?? '')
- const apiKey = settings?.apiKey?.trim() ?? ''
+ const resolvedKey = resolveModelGatewayApiKey(
+ settings?.apiKey ?? '',
+ process.env,
+ storedSecret
+ )
+ const apiKey = resolvedKey.value
if (!routes) return { models: [], error: 'Enter a valid HTTP(S) gateway URL.' }
+ if (resolvedKey.missing.length) {
+ const refs = resolvedKey.missing.map((name) => `\${env:${name}}`).join(', ')
+ return {
+ models: [],
+ error: `Gateway API key environment ${resolvedKey.missing.length === 1 ? 'variable is' : 'variables are'} unset: ${refs}.`
+ }
+ }
+ if (resolvedKey.storedSecretMissing) {
+ return { models: [], error: 'Save a gateway API key or select an environment variable.' }
+ }
if (!apiKey) return { models: [], error: 'Enter an API key.' }
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), DISCOVERY_TIMEOUT_MS)
try {
const response = await fetch(routes.discovery, {
- headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },
+ headers: {
+ // Authorization is the OpenAI-compatible convention used by LiteLLM and
+ // modern Bifrost keys. Older Bifrost virtual keys require x-bf-vk.
+ Authorization: `Bearer ${apiKey}`,
+ 'x-bf-vk': apiKey,
+ Accept: 'application/json'
+ },
signal: controller.signal
})
if (!response.ok) {
@@ -62,14 +88,24 @@ function envSnapshot(): Record<string, string> {
return out
}
-/** Register the env-snapshot + preview-command handlers. Call once at startup, beside the other
- * `registerIpc()` calls (main: src/main/index.ts; server: src/server/index.ts). */
-export function registerAgentEnvIpc(): void {
+/** Register env snapshot, preview, discovery, and write-only gateway-credential handlers. */
+export function registerAgentEnvIpc(credentials?: ModelGatewayCredentialService): void {
platform().handle(IPC.envSnapshot, () => envSnapshot())
platform().handle(IPC.agentPreviewCommand, (inputs: LaunchInputs) =>
assembleLaunchCommand(inputs, envSnapshot())
)
platform().handle(IPC.agentDiscoverModels, (settings: ModelGatewaySettings) =>
- discoverModels(settings)
+ discoverModels(settings, credentials?.readForHost() ?? null)
+ )
+ platform().handle(IPC.agentGatewayCredentialStatus, () =>
+ credentials?.status() ?? { hasStoredKey: false, storage: 'unavailable' as const }
)
+ platform().handle(IPC.agentGatewayCredentialSave, (apiKey: string) => {
+ if (!credentials) throw new Error('gateway-secret-storage-unavailable')
+ return credentials.save(apiKey)
+ })
+ platform().handle(IPC.agentGatewayCredentialClear, () => {
+ if (!credentials) throw new Error('gateway-secret-storage-unavailable')
+ return credentials.clear()
+ })
}
diff --git a/src/core/model-gateway-credentials.test.ts b/src/core/model-gateway-credentials.test.ts
new file mode 100644
index 000000000..7eb305d7c
--- /dev/null
+++ b/src/core/model-gateway-credentials.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it, vi } from 'vitest'
+import { MODEL_GATEWAY_SECRET_REF } from '../shared/agents/model-gateway'
+import {
+ migrateLegacyModelGatewayKey,
+ ModelGatewayCredentialService
+} from './model-gateway-credentials'
+
+function store(initial: string | null = null) {
+ let value = initial
+ return {
+ availability: 'encrypted' as const,
+ readForHost: vi.fn(async () => value),
+ save: vi.fn(async (next: string) => {
+ value = next
+ }),
+ clear: vi.fn(async () => {
+ value = null
+ })
+ }
+}
+
+describe('ModelGatewayCredentialService', () => {
+ it('loads, saves, and clears without exposing the value through status', async () => {
+ const backing = store('saved-key')
+ const service = new ModelGatewayCredentialService(backing)
+ await service.init()
+ expect(service.status()).toEqual({ hasStoredKey: true, storage: 'encrypted' })
+ expect(service.readForHost()).toBe('saved-key')
+
+ await service.save(' replacement-key ')
+ expect(backing.save).toHaveBeenCalledWith('replacement-key')
+ expect(service.readForHost()).toBe('replacement-key')
+
+ await service.clear()
+ expect(service.status().hasStoredKey).toBe(false)
+ })
+
+ it('migrates only legacy literals after the secret write succeeds', async () => {
+ const backing = store()
+ const service = new ModelGatewayCredentialService(backing)
+ await service.init()
+
+ await expect(
+ migrateLegacyModelGatewayKey(
+ { baseUrl: 'https://gateway.example.test', apiKey: 'legacy-key' },
+ service
+ )
+ ).resolves.toEqual({
+ baseUrl: 'https://gateway.example.test',
+ apiKey: MODEL_GATEWAY_SECRET_REF
+ })
+ expect(backing.save).toHaveBeenCalledWith('legacy-key')
+
+ await expect(
+ migrateLegacyModelGatewayKey(
+ { baseUrl: 'https://gateway.example.test', apiKey: '${env:GATEWAY_KEY}' },
+ service
+ )
+ ).resolves.toBeNull()
+ })
+})
diff --git a/src/core/model-gateway-credentials.ts b/src/core/model-gateway-credentials.ts
new file mode 100644
index 000000000..0274a28c1
--- /dev/null
+++ b/src/core/model-gateway-credentials.ts
@@ -0,0 +1,66 @@
+import type { SecretStore } from './secret-store'
+import {
+ MODEL_GATEWAY_SECRET_REF,
+ modelGatewayCredentialKind,
+ type ModelGatewayCredentialStatus,
+ type ModelGatewaySettings
+} from '../shared/agents/model-gateway'
+
+export const MODEL_GATEWAY_SECRET_FILE = 'model-gateway-api-key.json'
+
+/**
+ * Process-local facade over the platform's secret store. PTY creation is synchronous at the point
+ * where its environment is assembled, so the secret is loaded once during shell startup and kept
+ * in memory; saves/clears update disk first and only then publish the new cached value.
+ */
+export class ModelGatewayCredentialService {
+ private key: string | null = null
+
+ constructor(private readonly store: SecretStore) {}
+
+ async init(): Promise<void> {
+ this.key = await this.store.readForHost()
+ }
+
+ readForHost(): string | null {
+ return this.key
+ }
+
+ status(): ModelGatewayCredentialStatus {
+ return {
+ hasStoredKey: this.key !== null,
+ storage: this.store.availability
+ }
+ }
+
+ async save(key: string): Promise<ModelGatewayCredentialStatus> {
+ const value = key.trim()
+ if (!value || value.length > 4096 || /[\r\n\0]/.test(value)) {
+ throw new Error('invalid-api-key')
+ }
+ await this.store.save(value)
+ this.key = value
+ return this.status()
+ }
+
+ async clear(): Promise<ModelGatewayCredentialStatus> {
+ await this.store.clear()
+ this.key = null
+ return this.status()
+ }
+}
+
+/**
+ * One-time migration for builds that wrote a literal gateway key into settings.json. Environment
+ * references and the new secret sentinel stay untouched. The caller persists the returned
+ * settings only after `save` succeeds, so a locked keyring or disk failure never destroys the sole
+ * copy of a legacy credential.
+ */
+export async function migrateLegacyModelGatewayKey(
+ settings: ModelGatewaySettings,
+ credentials: ModelGatewayCredentialService
+): Promise<ModelGatewaySettings | null> {
+ if (modelGatewayCredentialKind(settings.apiKey) !== 'legacy-literal') return null
+ await credentials.save(settings.apiKey)
+ return { ...settings, apiKey: MODEL_GATEWAY_SECRET_REF }
+}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 5092ccf9e..a8c29a226 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -653,6 +653,8 @@ export class PtyManager {
private tmuxPath: string | null = null
private confPath = ''
private getSettings: () => Settings = () => DEFAULT_SETTINGS
+ /** Literal model-gateway key loaded by the shell's secret service during startup. */
+ private getModelGatewaySecret: () => string | null = () => null
/** ONE shared snapshot interval for all persisted sessions — a per-session interval spawned
* one tmux/ssh capture subprocess per session per tick, forever, even for idle terminals. */
private snapshotTimer: ReturnType<typeof setInterval> | null = null
@@ -1191,8 +1193,12 @@ export class PtyManager {
}
/** Must run after app is ready (needs userData path). */
- init(getSettings: () => Settings): void {
+ init(
+ getSettings: () => Settings,
+ getModelGatewaySecret: () => string | null = () => null
+ ): void {
this.getSettings = getSettings
+ this.getModelGatewaySecret = getModelGatewaySecret
// Register the custom-id → baseAgent resolver so the capability predicates in
// shared/agents/config (hasHooks, canResume, mintsSessionId, hasPermissionMode,
// canControlCanvas, …) resolve a custom agent's INHERITED harness. config.ts takes only an id
@@ -2012,7 +2018,13 @@ export class PtyManager {
// historical Claude fallback does not apply here: gateway access is an explicit agent
// capability, not a terminal default.
const gatewayEnv = options.agentId
- ? modelGatewayEnv(this.getSettings().modelGateway, options.agentId, options.agentModel)
+ ? modelGatewayEnv(
+ this.getSettings().modelGateway,
+ options.agentId,
+ options.agentModel,
+ process.env as Record<string, string | undefined>,
+ this.getModelGatewaySecret()
+ )
: {}
if (!options.sshRemote) {
for (const [k, v] of Object.entries(gatewayEnv)) env[k] = v
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index be2f98af8..0d2ff654c 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -6,6 +6,7 @@ import { initPlatform, resetPlatformForTests } from './platform'
import { fakePlatform, type FakePlatform } from './platform-fake'
import { IPC } from '../shared/ipc'
import { DEFAULT_SETTINGS } from '../shared/types'
+import { MODEL_GATEWAY_SECRET_REF } from '../shared/agents/model-gateway'
import { TMUX_SOCKET, sessionName } from './tmux-naming'
/**
@@ -229,28 +230,39 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
})
it('injects the shared gateway into both the PTY and its tmux session environment', async () => {
- const { PtyManager } = await import('./pty-manager')
- const m = new PtyManager()
- m.init(() => ({
- ...DEFAULT_SETTINGS,
- modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-secret' }
- }))
- m.registerIpc()
-
- await create(80, 24, 'gateway-node', { agentId: 'claude' })
+ const inherited = process.env.NODETERM_TEST_GATEWAY_KEY
+ process.env.NODETERM_TEST_GATEWAY_KEY = 'vk-secret'
+ try {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: {
+ baseUrl: 'https://bifrost.example.test',
+ apiKey: '${env:NODETERM_TEST_GATEWAY_KEY}'
+ }
+ }))
+ m.registerIpc()
- expect(spawnArgs[0].env.ANTHROPIC_BASE_URL).toBe(
- 'https://bifrost.example.test/anthropic'
- )
- expect(spawnArgs[0].env.ANTHROPIC_AUTH_TOKEN).toBe('vk-secret')
- expect(spawnArgs[0].args).toEqual(
- expect.arrayContaining([
- '-e',
- 'ANTHROPIC_BASE_URL=https://bifrost.example.test/anthropic',
- '-e',
- 'ANTHROPIC_AUTH_TOKEN=vk-secret'
- ])
- )
+ await create(80, 24, 'gateway-node', { agentId: 'claude' })
+
+ expect(spawnArgs[0].env.ANTHROPIC_BASE_URL).toBe(
+ 'https://bifrost.example.test/anthropic'
+ )
+ expect(spawnArgs[0].env.ANTHROPIC_AUTH_TOKEN).toBe('vk-secret')
+ expect(spawnArgs[0].args).toEqual(
+ expect.arrayContaining([
+ '-e',
+ 'ANTHROPIC_BASE_URL=https://bifrost.example.test/anthropic',
+ '-e',
+ 'ANTHROPIC_AUTH_TOKEN=vk-secret'
+ ])
+ )
+ expect(spawnArgs[0].args.join(' ')).not.toContain('${env:')
+ } finally {
+ if (inherited === undefined) delete process.env.NODETERM_TEST_GATEWAY_KEY
+ else process.env.NODETERM_TEST_GATEWAY_KEY = inherited
+ }
})
it('maps a selected Copilot model into its BYOK environment, never a model flag', async () => {
@@ -286,6 +298,32 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
expect(spawnArgs[0].args.join(' ')).not.toContain('--model')
})
+ it('reads a stored gateway key through the shell-owned secret cache', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(
+ () => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: {
+ baseUrl: 'https://bifrost.example.test',
+ apiKey: MODEL_GATEWAY_SECRET_REF
+ }
+ }),
+ () => 'stored-gateway-key'
+ )
+ m.registerIpc()
+
+ await create(80, 24, 'stored-gateway-node', { agentId: 'codex' })
+
+ expect(spawnArgs[0].env).toMatchObject({
+ OPENAI_BASE_URL: 'https://bifrost.example.test/openai/v1',
+ OPENAI_API_KEY: 'stored-gateway-key'
+ })
+ expect(spawnArgs[0].args).toEqual(
+ expect.arrayContaining(['-e', 'OPENAI_API_KEY=stored-gateway-key'])
+ )
+ })
+
it('never exposes gateway credentials to a plain terminal', async () => {
const inherited = process.env.ANTHROPIC_AUTH_TOKEN
process.env.ANTHROPIC_AUTH_TOKEN = 'preexisting-shell-token'
diff --git a/src/core/settings-store.ts b/src/core/settings-store.ts
index 5ebf3e0aa..3b0598e11 100644
--- a/src/core/settings-store.ts
+++ b/src/core/settings-store.ts
@@ -1,8 +1,8 @@
-import { promises as fs, readFileSync } from 'fs'
-import path from 'path'
-import { IPC } from '../shared/ipc'
-import { platform } from './platform'
-import { DEFAULT_SETTINGS, type Settings } from '../shared/types'
+import { promises as fs, readFileSync } from "fs";
+import path from "path";
+import { IPC } from "../shared/ipc";
+import { platform } from "./platform";
+import { DEFAULT_SETTINGS, type Settings } from "../shared/types";
/**
* Merge a possibly-partial/legacy `Settings` object over `DEFAULT_SETTINGS`. A plain
@@ -13,9 +13,12 @@ import { DEFAULT_SETTINGS, type Settings } from '../shared/types'
* merged one level deeper so old files still pick up new defaults.
*/
function mergeSettings(saved: Partial<Settings> | null | undefined): Settings {
- const merged = { ...DEFAULT_SETTINGS, ...saved }
- merged.speech = { ...DEFAULT_SETTINGS.speech, ...saved?.speech }
- merged.modelGateway = { ...DEFAULT_SETTINGS.modelGateway, ...saved?.modelGateway }
+ const merged = { ...DEFAULT_SETTINGS, ...saved };
+ merged.speech = { ...DEFAULT_SETTINGS.speech, ...saved?.speech };
+ merged.modelGateway = {
+ ...DEFAULT_SETTINGS.modelGateway,
+ ...saved?.modelGateway,
+ };
// Legacy `terminalGpuRendering` was a boolean whose default (true) was merged into every saved
// file — so a stored `true` is indistinguishable from "never touched" and maps to the new
// 'auto' (platform-aware) default, while a stored `false` was always an explicit escape-hatch
@@ -25,104 +28,111 @@ function mergeSettings(saved: Partial<Settings> | null | undefined): Settings {
// normalizes to the DEFAULT: settings.json is hand-editable, and an unrecognised mode must not
// be handed to the renderer's resolver to interpret.
const gpu = (saved as { terminalGpuRendering?: unknown } | null | undefined)
- ?.terminalGpuRendering
- if (gpu === false) merged.terminalGpuRendering = 'off'
- else if (gpu !== 'on' && gpu !== 'off' && gpu !== 'auto' && gpu !== 'shared')
- merged.terminalGpuRendering = 'auto'
- return merged
+ ?.terminalGpuRendering;
+ if (gpu === false) merged.terminalGpuRendering = "off";
+ else if (gpu !== "on" && gpu !== "off" && gpu !== "auto" && gpu !== "shared")
+ merged.terminalGpuRendering = "auto";
+ return merged;
}
/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this
* process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one). Same
* scheme as agent-status-mirror's local write. */
-let writeSeq = 0
+let writeSeq = 0;
/**
* Stores user settings in settings.json. Keeps a synchronous cache so the PtyManager
* can read shell/tmux preferences immediately at terminal creation.
*/
export class SettingsStore {
- private cache: Settings = DEFAULT_SETTINGS
- private listeners = new Set<(s: Settings) => void>()
+ private cache: Settings = DEFAULT_SETTINGS;
+ private listeners = new Set<(s: Settings) => void>();
/** In-flight save chain: saves run FIFO (same idiom as WorkspaceStore.saveChain). The handler
* has overlapping callers in both builds (the renderer's coalesced timer save, the
* `beforeunload` flush, concurrent WS frames on the Server Edition); unordered, the last RENAME
* wins the disk while the last CALL wins the cache — and they can disagree until next boot.
* Each caller still sees only ITS OWN save's failure. */
- private saveChain: Promise<unknown> = Promise.resolve()
+ private saveChain: Promise<unknown> = Promise.resolve();
private get filePath(): string {
- return path.join(platform().userDataDir, 'settings.json')
+ return path.join(platform().userDataDir, "settings.json");
}
/** Subscribe to saves (fires after each successful `settings:save`). Additive; used by the
* desktop shell to create/destroy runtime-toggled subsystems (e.g. the Notch HUD). Returns an
* unsubscribe. Never throws into a save. */
onChange(cb: (s: Settings) => void): () => void {
- this.listeners.add(cb)
- return () => this.listeners.delete(cb)
+ this.listeners.add(cb);
+ return () => this.listeners.delete(cb);
}
/** Load synchronously into cache (call after app is ready). */
init(): void {
try {
- const raw = readFileSync(this.filePath, 'utf-8')
- this.cache = mergeSettings(JSON.parse(raw))
+ const raw = readFileSync(this.filePath, "utf-8");
+ this.cache = mergeSettings(JSON.parse(raw));
} catch {
- this.cache = DEFAULT_SETTINGS
+ this.cache = DEFAULT_SETTINGS;
}
}
get(): Settings {
- return this.cache
+ return this.cache;
+ }
+
+ /** Persist a full settings snapshot. Public so startup migrations can use the exact same atomic
+ * FIFO writer as renderer IPC instead of reaching into the cache or duplicating disk semantics. */
+ save(settings: Settings): Promise<void> {
+ const run = this.saveChain.then(() => this.saveNow(settings));
+ this.saveChain = run.catch(() => {});
+ return run;
}
registerIpc(): void {
- platform().handle(IPC.settingsLoad, () => this.cache)
- platform().handle(IPC.settingsSave, (settings: Settings) => {
- const run = this.saveChain.then(() => this.saveNow(settings))
- this.saveChain = run.catch(() => {})
- return run
- })
+ platform().handle(IPC.settingsLoad, () => this.cache);
+ platform().handle(IPC.settingsSave, (settings: Settings) =>
+ this.save(settings),
+ );
}
private async saveNow(settings: Settings): Promise<void> {
- {
- this.cache = mergeSettings(settings)
- // Atomic write (temp + rename) so a mid-write crash can't corrupt settings.json. The temp
- // name is unique per call because nothing serializes this handler and its callers overlap:
- // on the desktop the renderer's coalesced timer save, the `beforeunload` flush that fires
- // outside that window, and any still-in-flight earlier save are all fire-and-forget
- // (src/renderer/state/settings.ts); on the Server Edition every WS frame is dispatched
- // concurrently (src/server/ws.ts), so even one browser tab can have two saves in the air.
- // With a shared name, one writer's rename publishes the other's half-written bytes, or moves
- // the file out from under it entirely. The pid covers the other direction: two
- // `nodeterm-server --data-dir X` processes share the dir with no lock, and their counters
- // both start at 0.
- const tmp = `${this.filePath}.${process.pid}.${++writeSeq}.tmp`
+ this.cache = mergeSettings(settings);
+ // Atomic write (temp + rename) so a mid-write crash can't corrupt settings.json. The temp
+ // name is unique per call because nothing serializes this handler and its callers overlap:
+ // on the desktop the renderer's coalesced timer save, the `beforeunload` flush that fires
+ // outside that window, and any still-in-flight earlier save are all fire-and-forget
+ // (src/renderer/state/settings.ts); on the Server Edition every WS frame is dispatched
+ // concurrently (src/server/ws.ts), so even one browser tab can have two saves in the air.
+ // With a shared name, one writer's rename publishes the other's half-written bytes, or moves
+ // the file out from under it entirely. The pid covers the other direction: two
+ // `nodeterm-server --data-dir X` processes share the dir with no lock, and their counters
+ // both start at 0.
+ const tmp = `${this.filePath}.${process.pid}.${++writeSeq}.tmp`;
+ try {
+ // 0600 at open(2), before any bytes land, and the rename carries it onto settings.json.
+ // Two reasons: the temp name is predictable (`<file>.<pid>.<seq>.tmp`), so a same-uid
+ // process could pre-create it as a symlink for this write to follow; and every other
+ // writer in this family already creates owner-only — this one was the outlier, which is
+ // exactly what CodeQL's js/insecure-temporary-file was pointing at.
+ await fs.writeFile(tmp, JSON.stringify(this.cache, null, 2), {
+ encoding: "utf-8",
+ mode: 0o600,
+ });
+ await fs.rename(tmp, this.filePath);
+ } catch (e) {
+ // A unique name never self-heals the way the fixed one did (the next save just reused it),
+ // so a failed write has to remove its own temp. The error still propagates, so a failed
+ // save stays a failed save — and the listeners below still only run on success. There is
+ // deliberately no sweep of orphans from killed processes as provider-cookie does: an
+ // orphaned settings temp is config litter, not a live credential.
+ await fs.rm(tmp, { force: true }).catch(() => {});
+ throw e;
+ }
+ for (const cb of this.listeners) {
try {
- // 0600 at open(2), before any bytes land, and the rename carries it onto settings.json.
- // Two reasons: the temp name is predictable (`<file>.<pid>.<seq>.tmp`), so a same-uid
- // process could pre-create it as a symlink for this write to follow; and every other
- // writer in this family already creates owner-only — this one was the outlier, which is
- // exactly what CodeQL's js/insecure-temporary-file was pointing at.
- await fs.writeFile(tmp, JSON.stringify(this.cache, null, 2), { encoding: 'utf-8', mode: 0o600 })
- await fs.rename(tmp, this.filePath)
- } catch (e) {
- // A unique name never self-heals the way the fixed one did (the next save just reused it),
- // so a failed write has to remove its own temp. The error still propagates, so a failed
- // save stays a failed save — and the listeners below still only run on success. There is
- // deliberately no sweep of orphans from killed processes as provider-cookie does: an
- // orphaned settings temp is config litter, not a live credential.
- await fs.rm(tmp, { force: true }).catch(() => {})
- throw e
- }
- for (const cb of this.listeners) {
- try {
- cb(this.cache)
- } catch {
- // A listener must never break a settings save (or its siblings).
- }
+ cb(this.cache);
+ } catch {
+ // A listener must never break a settings save (or its siblings).
}
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index acf200d79..a218a9d0c 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -28,7 +28,16 @@ import { SshStore } from './ssh-store'
import { GitService } from '../core/git-service'
import { registerGitHubIntegration } from '../core/github/integration'
import { runGitHubCliCommand } from '../core/github/credentials'
-import { ElectronGitHubSecretStore, registerElectronGitHubControl } from './github-control'
+import {
+ ElectronGitHubSecretStore,
+ ElectronSecretStore,
+ registerElectronGitHubControl
+} from './github-control'
+import {
+ migrateLegacyModelGatewayKey,
+ MODEL_GATEWAY_SECRET_FILE,
+ ModelGatewayCredentialService
+} from '../core/model-gateway-credentials'
import { generateCommitMessage, generateGroupName, generateTerminalName } from '../core/commit-message'
import { initUpdater } from './updater'
import { fetchCheck } from '../core/check'
@@ -644,11 +653,32 @@ app.whenReady().then(async () => {
})
settingsStore.init()
+ const gatewayCredentials = new ModelGatewayCredentialService(
+ new ElectronSecretStore(app.getPath('userData'), safeStorage, MODEL_GATEWAY_SECRET_FILE)
+ )
+ await gatewayCredentials.init()
+ try {
+ const migratedGateway = await migrateLegacyModelGatewayKey(
+ settingsStore.get().modelGateway,
+ gatewayCredentials
+ )
+ if (migratedGateway) {
+ await settingsStore.save({ ...settingsStore.get(), modelGateway: migratedGateway })
+ }
+ } catch (error) {
+ // Preserve the legacy literal in settings when the keyring/file write fails; migration can
+ // retry next launch, and the user never loses their only copy of the credential.
+ console.warn('[model-gateway] could not migrate the legacy API key to secret storage', error)
+ }
settingsStore.registerIpc()
sshStore.registerIpc()
- // Custom-agent preview/expansion IPC (renderer has no process.env; expansion runs here).
- registerAgentEnvIpc()
- ptyManager.init(() => settingsStore.get())
+ // Custom-agent preview/expansion + gateway discovery/credential IPC (renderer has no
+ // process.env and never receives a stored literal key).
+ registerAgentEnvIpc(gatewayCredentials)
+ ptyManager.init(
+ () => settingsStore.get(),
+ () => gatewayCredentials.readForHost()
+ )
ptyManager.registerIpc()
workspaceStore.registerIpc()
gitService.registerIpc()
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b0c8dfde5..a23ae3124 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -440,7 +440,11 @@ const api: NodeTerminalApi = {
agent: {
envSnapshot: () => ipcRenderer.invoke(IPC.envSnapshot),
previewCommand: (inputs) => ipcRenderer.invoke(IPC.agentPreviewCommand, inputs),
- discoverModels: (settings) => ipcRenderer.invoke(IPC.agentDiscoverModels, settings)
+ discoverModels: (settings) => ipcRenderer.invoke(IPC.agentDiscoverModels, settings),
+ gatewayCredentialStatus: () => ipcRenderer.invoke(IPC.agentGatewayCredentialStatus),
+ saveGatewayCredential: (apiKey) =>
+ ipcRenderer.invoke(IPC.agentGatewayCredentialSave, apiKey),
+ clearGatewayCredential: () => ipcRenderer.invoke(IPC.agentGatewayCredentialClear)
},
chat: {
readTranscript: (sessionId, cwd, accountId, nodeId) =>
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 1180dc18e..6b8ad2ba6 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -278,7 +278,11 @@ export function buildStubApi(): Omit<
// env + unexpanded command so the preview degrades to "unavailable" rather than throwing.
envSnapshot: () => Promise.resolve({}),
previewCommand: U('agent.previewCommand'),
- discoverModels: () => Promise.resolve({ models: [], error: 'Model discovery is unavailable.' })
+ discoverModels: () => Promise.resolve({ models: [], error: 'Model discovery is unavailable.' }),
+ gatewayCredentialStatus: () =>
+ Promise.resolve({ hasStoredKey: false, storage: 'unavailable' }),
+ saveGatewayCredential: U('agent.saveGatewayCredential'),
+ clearGatewayCredential: U('agent.clearGatewayCredential')
},
chat: {
readTranscript: U('chat.readTranscript')
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 22bbb8c74..4cff76a7a 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -297,6 +297,18 @@ export function buildRealApi(
discoverModels: (gateway) =>
client.request(IPC.agentDiscoverModels, gateway) as ReturnType<
NodeTerminalApi['agent']['discoverModels']
+ >,
+ gatewayCredentialStatus: () =>
+ client.request(IPC.agentGatewayCredentialStatus) as ReturnType<
+ NodeTerminalApi['agent']['gatewayCredentialStatus']
+ >,
+ saveGatewayCredential: (apiKey) =>
+ client.request(IPC.agentGatewayCredentialSave, apiKey) as ReturnType<
+ NodeTerminalApi['agent']['saveGatewayCredential']
+ >,
+ clearGatewayCredential: () =>
+ client.request(IPC.agentGatewayCredentialClear) as ReturnType<
+ NodeTerminalApi['agent']['clearGatewayCredential']
>
}
diff --git a/src/renderer/components/settings/sections/ModelGatewaySection.test.tsx b/src/renderer/components/settings/sections/ModelGatewaySection.test.tsx
new file mode 100644
index 000000000..6f48e0348
--- /dev/null
+++ b/src/renderer/components/settings/sections/ModelGatewaySection.test.tsx
@@ -0,0 +1,114 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { MODEL_GATEWAY_SECRET_REF } from '@shared/agents/model-gateway'
+import { DEFAULT_SETTINGS } from '@shared/types'
+import { useSettings } from '../../../state/settings'
+import { useModelGateway } from '../../../state/modelGateway'
+import { ModelGatewaySection } from './ModelGatewaySection'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+describe('ModelGatewaySection credential modes', () => {
+ let host: HTMLElement
+ let root: Root
+ let saveCredential: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ saveCredential = vi.fn(async () => ({ hasStoredKey: true, storage: 'encrypted' as const }))
+ ;(window as unknown as { nodeTerminal: any }).nodeTerminal = {
+ settings: { save: vi.fn() },
+ agent: {
+ discoverModels: vi.fn(),
+ gatewayCredentialStatus: vi.fn(async () => ({
+ hasStoredKey: false,
+ storage: 'encrypted' as const
+ })),
+ saveGatewayCredential: saveCredential,
+ clearGatewayCredential: vi.fn(async () => ({
+ hasStoredKey: false,
+ storage: 'encrypted' as const
+ }))
+ }
+ }
+ useSettings.setState({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ modelGateway: {
+ baseUrl: 'https://gateway.example.test',
+ apiKey: '${env:BIFROST_VK}'
+ }
+ },
+ hydrated: true
+ })
+ useModelGateway.setState({ models: [], status: 'idle', error: '' })
+ })
+
+ afterEach(() => {
+ act(() => root?.unmount())
+ host.remove()
+ })
+
+ const mount = async (): Promise<void> => {
+ root = createRoot(host)
+ await act(async () => {
+ root.render(<ModelGatewaySection isActive />)
+ })
+ }
+
+ it('shows an environment name as ordinary text while persisting the expansion token', async () => {
+ await mount()
+ const input = host.querySelector<HTMLInputElement>('#model-gateway-env-name')!
+ expect(input.type).toBe('text')
+ expect(input.value).toBe('BIFROST_VK')
+ expect(host.querySelector('#model-gateway-key')).toBeNull()
+
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(
+ input,
+ 'GATEWAY_KEY'
+ )
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+
+ expect(useSettings.getState().settings.modelGateway.apiKey).toBe('${env:GATEWAY_KEY}')
+ })
+
+ it('keeps a literal key write-only and stores only the secret sentinel in settings', async () => {
+ await mount()
+ const source = host.querySelector<HTMLSelectElement>('#model-gateway-credential-source')!
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(
+ source,
+ 'stored'
+ )
+ source.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+
+ const input = host.querySelector<HTMLInputElement>('#model-gateway-key')!
+ expect(input.type).toBe('password')
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(
+ input,
+ 'literal-secret'
+ )
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ const save = [...host.querySelectorAll('button')].find(
+ (button) => button.textContent === 'Save key'
+ )!
+ await act(async () => {
+ save.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ })
+
+ expect(saveCredential).toHaveBeenCalledWith('literal-secret')
+ expect(useSettings.getState().settings.modelGateway.apiKey).toBe(
+ MODEL_GATEWAY_SECRET_REF
+ )
+ expect(input.value).toBe('')
+ expect(host.textContent).not.toContain('literal-secret')
+ })
+})
diff --git a/src/renderer/components/settings/sections/ModelGatewaySection.tsx b/src/renderer/components/settings/sections/ModelGatewaySection.tsx
index f30fba514..94b4b4888 100644
--- a/src/renderer/components/settings/sections/ModelGatewaySection.tsx
+++ b/src/renderer/components/settings/sections/ModelGatewaySection.tsx
@@ -1,9 +1,16 @@
-import { useState } from 'react'
-import { modelGatewayRoutes } from '@shared/agents/model-gateway'
+import { useEffect, useState } from 'react'
+import {
+ MODEL_GATEWAY_SECRET_REF,
+ modelGatewayCredentialKind,
+ modelGatewayRoutes,
+ parseModelGatewayEnvReference,
+ type ModelGatewayCredentialStatus
+} from '@shared/agents/model-gateway'
import { useModelGateway } from '../../../state/modelGateway'
import { useSettings } from '../../../state/settings'
import { Button } from '@renderer/ui/Button'
import { Input } from '@renderer/ui/Input'
+import { Select } from '@renderer/ui/Select'
import { FieldRow } from '../FieldRow'
import { SearchableRow } from '../SearchableRow'
import { SettingsSection } from '../SettingsSection'
@@ -11,13 +18,13 @@ import { SettingsSection } from '../SettingsSection'
const ROWS = {
endpoint: {
title: 'Gateway URL',
- description: 'One Bifrost-compatible root URL for model discovery and agent routes.',
- keywords: ['bifrost', 'model', 'provider', 'base url', 'endpoint']
+ description: 'One gateway root URL for OpenAI-compatible discovery and agent routes.',
+ keywords: ['openai compatible', 'bifrost', 'litellm', 'model', 'provider', 'base url', 'endpoint']
},
key: {
title: 'API key',
- description: 'A Bifrost virtual key or compatible bearer key.',
- keywords: ['token', 'secret', 'virtual key', 'authentication']
+ description: 'A gateway bearer key from protected storage or an environment variable.',
+ keywords: ['token', 'secret', 'virtual key', 'authentication', 'environment variable', 'env']
},
discovery: {
title: 'Available models',
@@ -26,6 +33,18 @@ const ROWS = {
}
}
const ENTRIES = Object.values(ROWS)
+const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
+type CredentialMode = 'environment' | 'stored'
+
+function credentialMessage(error: unknown): string {
+ const message = error instanceof Error ? error.message : String(error)
+ if (message.includes('invalid-api-key') || message.includes('invalid-token')) {
+ return 'Enter a non-empty API key without line breaks.'
+ }
+ if (message.includes('keyring-locked')) return 'Unlock the OS keyring and try again.'
+ if (message.includes('unavailable')) return 'Secret storage is unavailable in this session.'
+ return 'The API key could not be saved. Please try again.'
+}
export function ModelGatewaySection({ isActive }: { isActive: boolean }): React.JSX.Element {
const gateway = useSettings((s) => s.settings.modelGateway)
@@ -34,31 +53,138 @@ export function ModelGatewaySection({ isActive }: { isActive: boolean }): React.
const status = useModelGateway((s) => s.status)
const error = useModelGateway((s) => s.error)
const discover = useModelGateway((s) => s.discover)
- const [showKey, setShowKey] = useState(false)
+ const clearModels = useModelGateway((s) => s.clear)
+ const initialReference = parseModelGatewayEnvReference(gateway.apiKey)
+ const [credentialMode, setCredentialMode] = useState<CredentialMode>(() =>
+ modelGatewayCredentialKind(gateway.apiKey) === 'stored' ||
+ modelGatewayCredentialKind(gateway.apiKey) === 'legacy-literal'
+ ? 'stored'
+ : 'environment'
+ )
+ const [envName, setEnvName] = useState(initialReference?.name ?? '')
+ const [literalKey, setLiteralKey] = useState('')
+ const [credentialStatus, setCredentialStatus] =
+ useState<ModelGatewayCredentialStatus | null>(null)
+ const [credentialBusy, setCredentialBusy] = useState(false)
+ const [credentialNotice, setCredentialNotice] = useState('')
const routes = modelGatewayRoutes(gateway.baseUrl)
- const patchGateway = (patch: Partial<typeof gateway>): void =>
- update({ modelGateway: { ...gateway, ...patch } })
+ const patchGateway = (patch: Partial<typeof gateway>): void => {
+ const current = useSettings.getState().settings.modelGateway
+ update({ modelGateway: { ...current, ...patch } })
+ }
+
+ useEffect(() => {
+ const reference = parseModelGatewayEnvReference(gateway.apiKey)
+ if (reference) {
+ setCredentialMode('environment')
+ setEnvName(reference.name)
+ } else {
+ const kind = modelGatewayCredentialKind(gateway.apiKey)
+ if (kind === 'stored' || kind === 'legacy-literal') setCredentialMode('stored')
+ }
+ }, [gateway.apiKey])
+
+ useEffect(() => {
+ if (!isActive) return
+ let cancelled = false
+ void window.nodeTerminal.agent
+ .gatewayCredentialStatus()
+ .then((status) => {
+ if (!cancelled) setCredentialStatus(status)
+ })
+ .catch(() => {
+ if (!cancelled) setCredentialStatus({ hasStoredKey: false, storage: 'unavailable' })
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [isActive])
+
+ const changeCredentialMode = (mode: CredentialMode): void => {
+ setCredentialMode(mode)
+ setCredentialNotice('')
+ if (mode === 'environment') {
+ patchGateway({ apiKey: ENV_NAME.test(envName) ? `\${env:${envName}}` : '' })
+ } else {
+ patchGateway({
+ apiKey: credentialStatus?.hasStoredKey ? MODEL_GATEWAY_SECRET_REF : ''
+ })
+ }
+ }
+
+ const updateEnvName = (value: string): void => {
+ setEnvName(value)
+ setCredentialNotice('')
+ patchGateway({ apiKey: ENV_NAME.test(value) ? `\${env:${value}}` : '' })
+ }
+
+ const saveLiteralKey = async (): Promise<void> => {
+ setCredentialBusy(true)
+ setCredentialNotice('')
+ try {
+ const status = await window.nodeTerminal.agent.saveGatewayCredential(literalKey)
+ setCredentialStatus(status)
+ setLiteralKey('')
+ const replacingStoredKey =
+ useSettings.getState().settings.modelGateway.apiKey === MODEL_GATEWAY_SECRET_REF
+ patchGateway({ apiKey: MODEL_GATEWAY_SECRET_REF })
+ const current = useSettings.getState().settings.modelGateway
+ // Replacing a key leaves the settings sentinel unchanged, so Canvas's value-based effect has
+ // no dependency change to observe. A first save does change it and gets the normal debounce.
+ if (replacingStoredKey && modelGatewayRoutes(current.baseUrl)) {
+ void discover({ ...current, apiKey: MODEL_GATEWAY_SECRET_REF })
+ }
+ setCredentialNotice('API key saved securely.')
+ } catch (saveError) {
+ setCredentialNotice(credentialMessage(saveError))
+ } finally {
+ setCredentialBusy(false)
+ }
+ }
+
+ const clearLiteralKey = async (): Promise<void> => {
+ setCredentialBusy(true)
+ setCredentialNotice('')
+ try {
+ const status = await window.nodeTerminal.agent.clearGatewayCredential()
+ setCredentialStatus(status)
+ setLiteralKey('')
+ patchGateway({ apiKey: '' })
+ clearModels()
+ setCredentialNotice('Saved API key cleared.')
+ } catch (clearError) {
+ setCredentialNotice(credentialMessage(clearError))
+ } finally {
+ setCredentialBusy(false)
+ }
+ }
+
+ const envNameValid = ENV_NAME.test(envName)
+ const credentialReady =
+ credentialMode === 'environment'
+ ? envNameValid && gateway.apiKey.trim() !== ''
+ : credentialStatus?.hasStoredKey === true && gateway.apiKey === MODEL_GATEWAY_SECRET_REF
return (
<SettingsSection
id="model-gateway"
title="Model gateway"
- description="Configure one Bifrost-compatible endpoint, discover its models, and switch a supported agent node without creating a custom agent for every model."
+ description="Configure one gateway, discover models through the OpenAI-compatible Models API, and switch a supported agent node without creating a custom agent for every model."
isActive={isActive}
searchEntries={ENTRIES}
>
<SearchableRow {...ROWS.endpoint}>
<FieldRow
label="Gateway URL"
- description="Enter the server root; nodeterm derives /v1/models, /openai/v1, and /anthropic."
+ description="Enter the server root. Discovery uses the OpenAI-compatible /v1/models endpoint; agent launches use the configured provider routes."
htmlFor="model-gateway-url"
control={
<Input
id="model-gateway-url"
className="w-80"
type="url"
- placeholder="https://bifrost.example.com"
+ placeholder="https://gateway.example.com"
value={gateway.baseUrl}
onChange={(e) => patchGateway({ baseUrl: e.target.value })}
/>
@@ -78,27 +204,100 @@ export function ModelGatewaySection({ isActive }: { isActive: boolean }): React.
</SearchableRow>
<SearchableRow {...ROWS.key}>
- <FieldRow
- label="API key"
- description="Saved locally in the owner-only settings file and never placed in restart commands."
- htmlFor="model-gateway-key"
- control={
- <div className="flex items-center gap-2">
- <Input
- id="model-gateway-key"
- className="w-64"
- type={showKey ? 'text' : 'password'}
- autoComplete="off"
- placeholder="virtual key"
- value={gateway.apiKey}
- onChange={(e) => patchGateway({ apiKey: e.target.value })}
- />
- <Button onClick={() => setShowKey((value) => !value)}>
- {showKey ? 'Hide' : 'Show'}
- </Button>
- </div>
- }
- />
+ <div className="space-y-3">
+ <FieldRow
+ label="Credential source"
+ description="Reference an environment variable or save a literal key in protected local storage."
+ htmlFor="model-gateway-credential-source"
+ control={
+ <Select
+ id="model-gateway-credential-source"
+ value={credentialMode}
+ onChange={(event) =>
+ changeCredentialMode(event.target.value as CredentialMode)
+ }
+ >
+ <option value="environment">Environment variable</option>
+ <option value="stored">Stored API key</option>
+ </Select>
+ }
+ />
+
+ {credentialMode === 'environment' ? (
+ <FieldRow
+ label="Environment variable"
+ description="Enter the variable name only. settings.json stores it as ${env:VAR}; the secret itself is never saved."
+ note={
+ envName && !envNameValid
+ ? 'Use letters, numbers, and underscores; the first character cannot be a number.'
+ : undefined
+ }
+ htmlFor="model-gateway-env-name"
+ control={
+ <Input
+ id="model-gateway-env-name"
+ className="w-64 font-mono"
+ type="text"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="GATEWAY_API_KEY"
+ value={envName}
+ onChange={(event) => updateEnvName(event.target.value)}
+ />
+ }
+ />
+ ) : (
+ <FieldRow
+ label="API key"
+ description="The key is write-only here and never appears in settings.json or restart commands."
+ note={
+ credentialStatus?.storage === 'restricted-file'
+ ? 'Encrypted key storage is unavailable. The key is protected in a mode 0600 local file.'
+ : credentialStatus?.storage === 'unavailable'
+ ? 'Secret storage is unavailable in this session.'
+ : undefined
+ }
+ htmlFor="model-gateway-key"
+ control={
+ <div className="flex items-center gap-2">
+ <Input
+ id="model-gateway-key"
+ className="w-56"
+ type="password"
+ autoComplete="off"
+ placeholder={credentialStatus?.hasStoredKey ? 'API key saved' : 'API key'}
+ value={literalKey}
+ onChange={(event) => {
+ setLiteralKey(event.target.value)
+ setCredentialNotice('')
+ }}
+ />
+ <Button
+ disabled={
+ !literalKey ||
+ credentialBusy ||
+ credentialStatus?.storage === 'unavailable'
+ }
+ onClick={() => void saveLiteralKey()}
+ >
+ Save key
+ </Button>
+ {credentialStatus?.hasStoredKey ? (
+ <Button
+ disabled={credentialBusy}
+ onClick={() => void clearLiteralKey()}
+ >
+ Clear
+ </Button>
+ ) : null}
+ </div>
+ }
+ />
+ )}
+ {credentialNotice ? (
+ <p className="text-right text-xs text-muted">{credentialNotice}</p>
+ ) : null}
+ </div>
</SearchableRow>
<SearchableRow {...ROWS.discovery}>
@@ -115,7 +314,7 @@ export function ModelGatewaySection({ isActive }: { isActive: boolean }): React.
{error ? <p className="mt-1 text-xs text-[color:var(--warn)]">{error}</p> : null}
</div>
<Button
- disabled={!routes || !gateway.apiKey.trim() || status === 'loading'}
+ disabled={!routes || !credentialReady || status === 'loading'}
onClick={() => void discover(gateway)}
>
{status === 'loading' ? 'Discovering…' : models.length ? 'Refresh' : 'Discover models'}
diff --git a/src/server/index.ts b/src/server/index.ts
index c84528935..f8a03ecd8 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -19,7 +19,16 @@ import { PtyManager } from '../core/pty-manager'
import { registerCoreHandlers } from './handlers'
import { registerGitHubIntegration } from '../core/github/integration'
import { runGitHubCliCommand } from '../core/github/credentials'
-import { registerServerGitHubControl, ServerGitHubSecretStore } from './github-control'
+import {
+ registerServerGitHubControl,
+ ServerGitHubSecretStore,
+ ServerSecretStore
+} from './github-control'
+import {
+ migrateLegacyModelGatewayKey,
+ MODEL_GATEWAY_SECRET_FILE,
+ ModelGatewayCredentialService
+} from '../core/model-gateway-credentials'
import { DownloadTickets } from '../core/download-tickets'
import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'
import os from 'os'
@@ -160,10 +169,29 @@ export async function startServer(
const workspaceStore = new WorkspaceStore()
settingsStore.init()
+ const gatewayCredentials = new ModelGatewayCredentialService(
+ new ServerSecretStore(config.dataDir, MODEL_GATEWAY_SECRET_FILE)
+ )
+ await gatewayCredentials.init()
+ try {
+ const migratedGateway = await migrateLegacyModelGatewayKey(
+ settingsStore.get().modelGateway,
+ gatewayCredentials
+ )
+ if (migratedGateway) {
+ await settingsStore.save({ ...settingsStore.get(), modelGateway: migratedGateway })
+ }
+ } catch (error) {
+ console.warn('[model-gateway] could not migrate the legacy API key to secret storage', error)
+ }
settingsStore.registerIpc()
- // Custom-agent preview/expansion IPC (browser has no process.env; expansion runs server-side).
- registerAgentEnvIpc()
- ptyManager.init(() => settingsStore.get())
+ // Custom-agent preview/expansion + gateway discovery/credential IPC (browser has no process.env
+ // and never receives a stored literal key).
+ registerAgentEnvIpc(gatewayCredentials)
+ ptyManager.init(
+ () => settingsStore.get(),
+ () => gatewayCredentials.readForHost()
+ )
ptyManager.registerIpc()
workspaceStore.registerIpc()
// Dictation: same construction as src/main/index.ts, with the server's data dir. onProgress
diff --git a/src/shared/agents/model-gateway.test.ts b/src/shared/agents/model-gateway.test.ts
index d9a84284d..15c872aba 100644
--- a/src/shared/agents/model-gateway.test.ts
+++ b/src/shared/agents/model-gateway.test.ts
@@ -1,9 +1,13 @@
import { describe, expect, it } from 'vitest'
import {
+ MODEL_GATEWAY_SECRET_REF,
modelGatewayEnv,
+ modelGatewayCredentialKind,
modelGatewayRoutes,
modelsForAgent,
parseGatewayModels,
+ parseModelGatewayEnvReference,
+ resolveModelGatewayApiKey,
withAgentModel
} from './model-gateway'
import {
@@ -69,6 +73,61 @@ describe('agent mappings', () => {
expect(modelGatewayEnv(gateway, 'gemini')).toEqual({})
})
+ it('expands the API key from the host environment for every mapped harness', () => {
+ const envGateway = {
+ baseUrl: gateway.baseUrl,
+ apiKey: '${env:BIFROST_API_KEY}'
+ }
+ expect(resolveModelGatewayApiKey(envGateway.apiKey, { BIFROST_API_KEY: 'vk-env' })).toEqual({
+ value: 'vk-env',
+ missing: [],
+ storedSecretMissing: false
+ })
+ expect(modelGatewayEnv(envGateway, 'claude', undefined, { BIFROST_API_KEY: 'vk-env' })).toEqual({
+ ANTHROPIC_BASE_URL: 'https://bifrost.example.test/anthropic',
+ ANTHROPIC_AUTH_TOKEN: 'vk-env'
+ })
+ })
+
+ it('fails closed when a referenced key is unset', () => {
+ expect(
+ modelGatewayEnv(
+ { baseUrl: gateway.baseUrl, apiKey: '${env:BIFROST_API_KEY}' },
+ 'codex'
+ )
+ ).toEqual({})
+ })
+
+ it('resolves a stored-key sentinel without exposing the secret in settings', () => {
+ const storedGateway = { baseUrl: gateway.baseUrl, apiKey: MODEL_GATEWAY_SECRET_REF }
+ expect(resolveModelGatewayApiKey(storedGateway.apiKey, {}, 'stored-key')).toEqual({
+ value: 'stored-key',
+ missing: [],
+ storedSecretMissing: false
+ })
+ expect(resolveModelGatewayApiKey(storedGateway.apiKey, {})).toEqual({
+ value: '',
+ missing: [],
+ storedSecretMissing: true
+ })
+ expect(modelGatewayEnv(storedGateway, 'codex', undefined, {}, 'stored-key')).toEqual({
+ OPENAI_BASE_URL: 'https://bifrost.example.test/openai/v1',
+ OPENAI_API_KEY: 'stored-key'
+ })
+ expect(modelGatewayEnv(storedGateway, 'codex')).toEqual({})
+ })
+
+ it('classifies the persisted credential forms for the settings UI and migration', () => {
+ expect(parseModelGatewayEnvReference('${env:BIFROST_VK}')).toEqual({
+ name: 'BIFROST_VK'
+ })
+ expect(parseModelGatewayEnvReference('${env:BIFROST_VK:fallback}')).toBeNull()
+ expect(modelGatewayCredentialKind('')).toBe('empty')
+ expect(modelGatewayCredentialKind('${env:BIFROST_VK}')).toBe('environment')
+ expect(modelGatewayCredentialKind(MODEL_GATEWAY_SECRET_REF)).toBe('stored')
+ expect(modelGatewayCredentialKind('legacy-key')).toBe('legacy-literal')
+ })
+
it('maps Copilot BYOK through the protocol route and separates model id from wire id', () => {
expect(modelGatewayEnv(gateway, 'copilot', 'anthropic/claude-sonnet-4.6')).toEqual({
COPILOT_PROVIDER_BASE_URL: 'https://bifrost.example.test/anthropic',
diff --git a/src/shared/agents/model-gateway.ts b/src/shared/agents/model-gateway.ts
index 4d135d9d5..7e31430c9 100644
--- a/src/shared/agents/model-gateway.ts
+++ b/src/shared/agents/model-gateway.ts
@@ -1,14 +1,48 @@
import { canSwitchModel, capabilityAgentId, type AgentId } from './config'
import { shellSingleQuote } from '../shell-quote'
+import { expandEnvVars } from './expansion'
-/** One Bifrost-compatible gateway configured once for every supported agent harness. */
+/** One model gateway configured once for every supported agent harness. */
export interface ModelGatewaySettings {
- /** Gateway root, before Bifrost's `/openai`, `/anthropic`, and `/v1/models` routes. */
+ /** Gateway root, before the OpenAI-compatible `/v1/models` discovery route. */
baseUrl: string
- /** Bifrost virtual key (or an upstream-compatible bearer key). */
+ /** Literal legacy key, `${env:VAR}` reference, or `MODEL_GATEWAY_SECRET_REF`. */
apiKey: string
}
+/** Stored in settings.json when the literal credential lives in the shell's secret store. */
+export const MODEL_GATEWAY_SECRET_REF = '${secret:model-gateway-api-key}'
+
+export type ModelGatewayCredentialStorage = 'encrypted' | 'restricted-file' | 'unavailable'
+
+export interface ModelGatewayCredentialStatus {
+ hasStoredKey: boolean
+ storage: ModelGatewayCredentialStorage
+}
+
+export interface ModelGatewayEnvReference {
+ name: string
+}
+
+const EXACT_ENV_REFERENCE = /^\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/
+
+/** Parse the JSON representation used by the environment-variable credential mode. */
+export function parseModelGatewayEnvReference(apiKey: string): ModelGatewayEnvReference | null {
+ const match = EXACT_ENV_REFERENCE.exec(apiKey.trim())
+ if (!match) return null
+ return { name: match[1] }
+}
+
+export type ModelGatewayCredentialKind = 'empty' | 'environment' | 'stored' | 'legacy-literal'
+
+export function modelGatewayCredentialKind(apiKey: string): ModelGatewayCredentialKind {
+ const value = apiKey.trim()
+ if (!value) return 'empty'
+ if (value === MODEL_GATEWAY_SECRET_REF) return 'stored'
+ if (parseModelGatewayEnvReference(value)) return 'environment'
+ return 'legacy-literal'
+}
+
/** The intentionally small model shape shared across IPC and renderer state. */
export interface GatewayModel {
id: string
@@ -28,9 +62,44 @@ export interface ModelGatewayRoutes {
}
/**
- * Derive every route from one user-entered root. Only http(s) URLs are accepted: this value is
- * later handed to `fetch` and agent CLIs, and settings.json is hand-editable. Invalid input
- * degrades to null (no discovery and no injected environment), never to a guessed endpoint.
+ * Resolve the stored gateway credential against the host process environment. Keeping this next
+ * to the route/env mapping gives model discovery and every supported harness the exact same
+ * `${env:VAR}` parser as custom agents, without ever resolving a secret in the renderer. Gateway
+ * credentials deliberately accept one exact reference rather than embedded/fallback expansion:
+ * a fallback API key would put the very secret this mode avoids back into settings.json.
+ *
+ * Whitespace around either a literal or expanded key is ignored. A caller must treat `missing` as
+ * a hard failure even when `value` is partly non-empty: sending a partial credential is both
+ * surprising and unsafe.
+ */
+export interface ModelGatewayApiKeyResolution {
+ value: string
+ missing: string[]
+ storedSecretMissing: boolean
+}
+
+export function resolveModelGatewayApiKey(
+ apiKey: string,
+ env: Record<string, string | undefined>,
+ storedSecret: string | null = null
+): ModelGatewayApiKeyResolution {
+ if (apiKey.trim() === MODEL_GATEWAY_SECRET_REF) {
+ const value = storedSecret?.trim() ?? ''
+ return { value, missing: [], storedSecretMissing: !value }
+ }
+ const reference = parseModelGatewayEnvReference(apiKey)
+ if (!reference) {
+ return { value: apiKey.trim(), missing: [], storedSecretMissing: false }
+ }
+ const result = expandEnvVars(apiKey.trim(), env)
+ return { value: result.value.trim(), missing: result.missing, storedSecretMissing: false }
+}
+
+/**
+ * Derive every route from one user-entered root. Discovery is the OpenAI Models API convention;
+ * the provider-specific paths are the Bifrost layout requested by the launch mapping. Only http(s)
+ * URLs are accepted: this value is later handed to `fetch` and agent CLIs, and settings.json is
+ * hand-editable. Invalid input degrades to null, never to a guessed endpoint.
*/
export function modelGatewayRoutes(baseUrl: string): ModelGatewayRoutes | null {
const raw = baseUrl.trim().replace(/\/+$/, '')
@@ -52,7 +121,7 @@ export function modelGatewayRoutes(baseUrl: string): ModelGatewayRoutes | null {
}
}
-/** Parse OpenAI/Bifrost model-list responses, dropping unsafe/empty/duplicate ids. */
+/** Parse OpenAI-compatible model-list responses, dropping unsafe/empty/duplicate ids. */
export function parseGatewayModels(payload: unknown): GatewayModel[] {
if (!payload || typeof payload !== 'object') return []
const data = (payload as { data?: unknown }).data
@@ -80,10 +149,10 @@ export function parseGatewayModels(payload: unknown): GatewayModel[] {
}
/**
- * Models an agent can be offered. Bifrost intentionally routes provider-prefixed models through
- * each harness protocol (including non-Anthropic models through Claude Code's Anthropic route), so
- * filtering by provider here would hide supported modes. The capability is the only UI gate;
- * custom agents inherit it from their declared base harness.
+ * Models an agent can be offered. OpenAI-compatible gateways may expose provider-prefixed or
+ * administrator-defined aliases and route them through either harness protocol, so filtering by
+ * provider here would hide supported modes. The capability is the only UI gate; custom agents
+ * inherit it from their declared base harness.
*/
export function modelsForAgent(models: GatewayModel[], agentId: AgentId): GatewayModel[] {
if (!canSwitchModel(agentId)) return []
@@ -99,11 +168,21 @@ export function modelsForAgent(models: GatewayModel[], agentId: AgentId): Gatewa
export function modelGatewayEnv(
settings: ModelGatewaySettings,
agentId: AgentId,
- model?: string
+ model?: string,
+ processEnv: Record<string, string | undefined> = {},
+ storedSecret: string | null = null
): Record<string, string> {
const routes = modelGatewayRoutes(settings.baseUrl)
- const key = settings.apiKey.trim()
- if (!routes || !key || !canSwitchModel(agentId)) return {}
+ const resolvedKey = resolveModelGatewayApiKey(settings.apiKey, processEnv, storedSecret)
+ const key = resolvedKey.value
+ if (
+ !routes ||
+ !key ||
+ resolvedKey.missing.length ||
+ resolvedKey.storedSecretMissing ||
+ !canSwitchModel(agentId)
+ )
+ return {}
switch (capabilityAgentId(agentId)) {
case 'claude':
return {
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 98af2974f..8f9916fb3 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -53,8 +53,13 @@ export const IPC = {
* live preview in Settings → Custom agents. Payload: `LaunchInputs`; resolves
* `{ command, missingEnv }`. */
agentPreviewCommand: 'agent:preview-command',
- /** Renderer → core: fetch a Bifrost/OpenAI-compatible model catalogue without browser CORS. */
+ /** Renderer → core: fetch an OpenAI-compatible model catalogue without browser CORS. */
agentDiscoverModels: 'agent:discover-models',
+ /** Renderer → core secret boundary for a literal model-gateway API key. The value is write-only;
+ * status returns only presence + storage protection. */
+ agentGatewayCredentialStatus: 'agent:gateway-credential-status',
+ agentGatewayCredentialSave: 'agent:gateway-credential-save',
+ agentGatewayCredentialClear: 'agent:gateway-credential-clear',
transcriptSearch: 'transcript:search',
appToggleMarkdown: 'app:toggle-markdown',
appCloseNode: 'app:close-node',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index dd7eaeb83..ea5f8b2c4 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -10,6 +10,7 @@ import type { WhisperModelInfo } from './speech'
import type { ProjectKanbanGitHub } from './github-issues'
import type {
ModelDiscoveryResult,
+ ModelGatewayCredentialStatus,
ModelGatewaySettings
} from './agents/model-gateway'
@@ -1015,7 +1016,7 @@ export interface Settings {
soundVolume: number
/** User-defined agents (BYO CLI) appended to the Add menus. */
customAgents: CustomAgent[]
- /** One Bifrost-compatible endpoint/key used by every model-switch-capable base harness. */
+ /** One gateway root + non-secret credential reference used by model-switch-capable harnesses. */
modelGateway: ModelGatewaySettings
/** Managed Claude accounts (config-dir isolated). See ClaudeAccount. */
claudeAccounts: ClaudeAccount[]
@@ -2061,6 +2062,10 @@ export interface AgentApi {
}): Promise<{ command: string; missingEnv: string[] }>
/** Query the configured gateway's OpenAI-compatible `/v1/models` endpoint. Never rejects. */
discoverModels(settings: ModelGatewaySettings): Promise<ModelDiscoveryResult>
+ /** Literal gateway credentials are write-only in the renderer. */
+ gatewayCredentialStatus(): Promise<ModelGatewayCredentialStatus>
+ saveGatewayCredential(apiKey: string): Promise<ModelGatewayCredentialStatus>
+ clearGatewayCredential(): Promise<ModelGatewayCredentialStatus>
}
export interface HandoffApi {