Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(byok): integrate enterprise-managed providers (#4764)

jk625xae389f6d2440
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index b6ddecfe08..db4a55e3fb 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -1026,7 +1026,9 @@ describe('maker:event hot path ordering', () => {
expect(claudeCostFallback).toMatch(
/buildClaudeTurnUsageDetails\(\s*undefined,\s*undefined,\s*resolvedModel,/,
);
- expect(claudeCostFallback).toContain("if (route !== 'provider-api')");
+ expect(claudeCostFallback).toContain(
+ "if (route !== 'provider-api' || turnContext.accessKind === 'managed')",
+ );
});
it('pi subscription turns estimate value from the shared reference-price helper', () => {
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index b2ce152cd4..caa3d208f8 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -353,6 +353,35 @@ describe('serverApiFetch', () => {
expect(logged).toContain('code=SKILL_NOT_FOUND'); // 业务 code 仍记(它不是身份)
});
+ it.each(['providers', 'credentials'])('logs the BYOK %s endpoint and allowed upstream code without response details', async (endpoint) => {
+ mocks.netFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 502,
+ json: async () => ({
+ error: { code: 'ORG_AI_GATEWAY_ERROR', message: 'private upstream body' },
+ apiKey: 'invalid-test-secret',
+ }),
+ });
+ const path = `/api/model-access/byok/${endpoint}`;
+ await expect(serverApiFetch(`${path}?schemaVersion=1`, {
+ baseUrl: 'https://model-access.example.com',
+ redactErrorDetails: true,
+ logLabel: path,
+ allowedRedactedErrorCodes: ['ORG_AI_GATEWAY_ERROR'],
+ })).rejects.toMatchObject({ code: 'ORG_AI_GATEWAY_ERROR', message: '请求失败 (502)' });
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ 'serverApiFetch.redacted_not_ok',
+ `path=${path}`,
+ 'method=GET',
+ 'status=502',
+ 'code=ORG_AI_GATEWAY_ERROR',
+ );
+ const logged = JSON.stringify(mocks.logger.warn.mock.calls);
+ expect(logged).not.toContain('private upstream body');
+ expect(logged).not.toContain('invalid-test-secret');
+ expect(logged).not.toContain('schemaVersion');
+ });
+
it('surfaces only explicitly allowed business codes on redacted requests', async () => {
mocks.getAccessToken.mockReturnValue('token-a');
mocks.netFetch
@@ -401,6 +430,7 @@ describe('serverApiFetch', () => {
});
const logged = JSON.stringify(mocks.logger.warn.mock.calls);
+ expect(logged).toContain('code=PLAN_CHANGE_NOT_AVAILABLE');
expect(logged).not.toContain('private subscription detail');
expect(logged).not.toContain('PRIVATE_SUBSCRIPTION_STATE');
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts
new file mode 100644
index 0000000000..53f60a6938
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts
@@ -0,0 +1,328 @@
+import { readFileSync } from 'node:fs';
+
+import { describe, expect, it, vi } from 'vitest';
+import { isOrganizationManagedProvider, type Provider } from '@cindy/model-providers';
+
+import { createByokImageChannel, pruneDynamicImageChannels, registerByokImageChannels } from '../byokImageChannel.js';
+import { ImageChannelRegistry, type ImageChannel } from '../imageChannelRegistry.js';
+
+const PROVIDER_ID = 'byok-a';
+const MODEL = 'byok-a/gpt-image-2';
+const ORIGIN = 'https://gateway.example.invalid';
+
+const okImageResponse = () =>
+ new Response(JSON.stringify({ created: 1, data: [{ b64_json: 'aGk=' }] }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+function fetchMock() {
+ return vi.fn<(url: string, init?: RequestInit) => Promise<Response>>(async () =>
+ okImageResponse(),
+ );
+}
+
+function orgProvider(
+ imageModels?: Array<{
+ id: string;
+ name: string;
+ modalities?: { input: string[]; output: string[] };
+ }>,
+) {
+ return {
+ id: PROVIDER_ID,
+ name: 'Enterprise Draw',
+ source: 'organization' as const,
+ ...(imageModels ? { imageModels } : {}),
+ };
+}
+
+function stubChannel(ready = true, supportsEdit = true): ImageChannel {
+ return {
+ ready: () => ready,
+ supportsEdit,
+ generateImage: vi.fn(async () => ({ data: [{ b64_json: 'aGk=' }] })),
+ editImage: vi.fn(async () => ({ data: [{ b64_json: 'aGk=' }] })),
+ };
+}
+
+describe('registerByokImageChannels', () => {
+ it('registers an organization provider with imageModels and follows the live key', () => {
+ const registry = new ImageChannelRegistry();
+ const registered = new Set<string>();
+ let key: string | null = 'member-key';
+ registerByokImageChannels(
+ registry,
+ [orgProvider([{ id: MODEL, name: 'GPT Image 2' }])],
+ registered,
+ (provider) =>
+ createByokImageChannel({
+ brandLabel: provider.name,
+ getApiKey: () => key,
+ getBaseUrl: () => ORIGIN,
+ getSupportsEdit: () => true,
+ }),
+ );
+ expect(registered.has(PROVIDER_ID)).toBe(true);
+ expect(registry.isProviderReady(PROVIDER_ID)).toBe(true);
+ key = null;
+ expect(registry.isProviderReady(PROVIDER_ID)).toBe(false);
+ });
+
+ it('skips chat-only organization providers, personal providers, and built-in image sources', () => {
+ const registry = new ImageChannelRegistry();
+ const registered = new Set<string>();
+ registerByokImageChannels(
+ registry,
+ [
+ orgProvider(),
+ {
+ id: 'mine',
+ name: 'Personal',
+ source: 'user',
+ imageModels: [{ id: 'mine/gpt-image-2', name: 'Mine' }],
+ },
+ {
+ id: 'openai',
+ name: 'OpenAI',
+ source: 'builtin',
+ imageModels: [{ id: 'openai/gpt-image-2', name: 'GPT Image 2' }],
+ },
+ {
+ id: 'xd',
+ name: 'Cindy',
+ source: 'builtin',
+ imageModels: [{ id: 'gpt-image-2', name: 'GPT Image 2' }],
+ },
+ ],
+ registered,
+ () => stubChannel(),
+ );
+ expect(registered.size).toBe(0);
+ expect(registry.isProviderReady(PROVIDER_ID)).toBe(false);
+ expect(registry.isProviderReady('openai')).toBe(false);
+ expect(registry.isProviderReady('xd')).toBe(false);
+ });
+
+ it('registers later if a chat-only provider grows imageModels, without duplicating', () => {
+ const registry = new ImageChannelRegistry();
+ const registered = new Set<string>();
+ const createChannel = vi.fn(() => stubChannel());
+ registerByokImageChannels(registry, [orgProvider()], registered, createChannel);
+ expect(createChannel).not.toHaveBeenCalled();
+ const withImages = orgProvider([{ id: MODEL, name: 'GPT Image 2' }]);
+ registerByokImageChannels(registry, [withImages], registered, createChannel);
+ registerByokImageChannels(registry, [withImages], registered, createChannel);
+ expect(createChannel).toHaveBeenCalledTimes(1);
+ expect(registry.isProviderReady(PROVIDER_ID)).toBe(true);
+ });
+});
+
+describe('createByokImageChannel', () => {
+ it('does not dispatch through a captured channel after its member key is revoked', async () => {
+ const doFetch = fetchMock();
+ let key: string | null = 'invalid-test-member-key';
+ const channel = createByokImageChannel({
+ getApiKey: () => key,
+ getBaseUrl: () => ORIGIN,
+ getSupportsEdit: () => true,
+ fetchImplementation: doFetch as unknown as typeof fetch,
+ });
+ expect(channel.ready()).toBe(true);
+ key = null;
+ expect(channel.ready()).toBe(false);
+ await expect(channel.generateImage({ model: MODEL, prompt: 'test' })).rejects.toThrow(/凭证未就绪/);
+ expect(doFetch).not.toHaveBeenCalled();
+ });
+
+ it('posts the catalog alias to the live inference origin with the member key', async () => {
+ const doFetch = fetchMock();
+ let origin = ORIGIN;
+ const channel = createByokImageChannel({
+ brandLabel: 'Enterprise Draw',
+ getApiKey: () => 'member-key',
+ getBaseUrl: () => origin,
+ getSupportsEdit: () => true,
+ fetchImplementation: doFetch as unknown as typeof fetch,
+ });
+ expect(channel.imageProtocol).toBe('openai');
+ await channel.generateImage({ model: MODEL, prompt: '一只猫', aspectRatio: '3:2' });
+ expect(doFetch).toHaveBeenCalledTimes(1);
+ const [url, init] = doFetch.mock.calls[0] ?? [];
+ expect(url).toBe(`${ORIGIN}/v1/images/generations`);
+ expect(init?.headers).toMatchObject({
+ Authorization: 'Bearer member-key',
+ 'Content-Type': 'application/json',
+ });
+ expect(JSON.parse(String(init?.body))).toMatchObject({
+ model: MODEL,
+ prompt: '一只猫',
+ size: '1536x1024',
+ });
+
+ origin = 'https://gateway-rotated.example.invalid';
+ await channel.generateImage({
+ model: MODEL,
+ prompt: '一只猫',
+ size: '1024x1536',
+ quality: 'high',
+ });
+ expect(doFetch.mock.calls[1]?.[0]).toBe(
+ 'https://gateway-rotated.example.invalid/v1/images/generations',
+ );
+ expect(JSON.parse(String(doFetch.mock.calls[1]?.[1]?.body))).toMatchObject({
+ size: '1024x1536',
+ quality: 'high',
+ });
+ });
+
+ it('rejects edit when the provider is generate-only and does not send a request', async () => {
+ const doFetch = fetchMock();
+ const channel = createByokImageChannel({
+ getApiKey: () => 'member-key',
+ getBaseUrl: () => ORIGIN,
+ getSupportsEdit: () => false,
+ fetchImplementation: doFetch as unknown as typeof fetch,
+ });
+ expect(channel.supportsEdit).toBe(false);
+ await expect(
+ channel.editImage({ model: MODEL, prompt: '改图', imagePaths: ['/tmp/x.png'] }),
+ ).rejects.toThrow(/不支持改图/);
+ expect(doFetch).not.toHaveBeenCalled();
+ });
+
+ it('is not ready without a member key or inference origin', () => {
+ expect(
+ createByokImageChannel({
+ getApiKey: () => null,
+ getBaseUrl: () => ORIGIN,
+ getSupportsEdit: () => true,
+ }).ready(),
+ ).toBe(false);
+ expect(
+ createByokImageChannel({
+ getApiKey: () => 'member-key',
+ getBaseUrl: () => null,
+ getSupportsEdit: () => true,
+ }).ready(),
+ ).toBe(false);
+ });
+});
+
+describe('dynamic image channel lifecycle', () => {
+ const enterprise: Provider = {
+ ...orgProvider([{ id: MODEL, name: 'Enterprise image' }]),
+ auth: { method: 'managed' }, agents: [], routing: {}, models: {},
+ };
+ const personal: Provider = {
+ id: PROVIDER_ID, name: 'Personal Codex', source: 'user',
+ auth: { method: 'oauth', native: 'codex' }, agents: ['codex'],
+ routing: {}, models: {}, imageModels: [{ id: 'personal-image', name: 'Personal image' }],
+ };
+
+ function harness() {
+ const registry = new ImageChannelRegistry();
+ const registeredCodex = new Set<string>();
+ const registeredByok = new Set<string>();
+ const createEnterprise = vi.fn(() => stubChannel());
+ const createPersonal = vi.fn(() => stubChannel());
+ // Match the host order: remove both stale kinds before adding either kind.
+ const refresh = (providers: Provider[]) => {
+ pruneDynamicImageChannels(registry, providers, registeredCodex, registeredByok);
+ for (const provider of providers) {
+ if (isOrganizationManagedProvider(provider) || provider.auth.native !== 'codex' || registeredCodex.has(provider.id)) continue;
+ registry.register(provider.id, createPersonal());
+ registeredCodex.add(provider.id);
+ }
+ registerByokImageChannels(registry, providers, registeredByok, createEnterprise);
+ };
+ return { registry, registeredCodex, registeredByok, createEnterprise, createPersonal, refresh };
+ }
+
+ it.each(['enterprise-first', 'personal-first'] as const)('switches the same ID in both directions (%s)', (order) => {
+ const h = harness();
+ const sequence = order === 'enterprise-first'
+ ? [enterprise, personal, enterprise]
+ : [personal, enterprise, personal];
+ for (const provider of sequence) {
+ h.refresh([provider]);
+ const managed = isOrganizationManagedProvider(provider);
+ const factory = managed ? h.createEnterprise : h.createPersonal;
+ expect(h.registry.resolve(PROVIDER_ID)).toBe(factory.mock.results.at(-1)?.value);
+ expect(h.registeredByok.has(PROVIDER_ID)).toBe(managed);
+ expect(h.registeredCodex.has(PROVIDER_ID)).toBe(!managed);
+ }
+ expect(h.createEnterprise.mock.calls.length + h.createPersonal.mock.calls.length).toBe(3);
+ });
+
+ it('removes image execution for chat-only providers and restores it when images return', () => {
+ const h = harness();
+ h.refresh([enterprise]);
+ const previous = h.registry.resolve(PROVIDER_ID);
+ h.refresh([{ ...enterprise, imageModels: [] }]);
+ expect(h.registry.isProviderReady(PROVIDER_ID)).toBe(false);
+ expect(h.registry.isProviderEditReady(PROVIDER_ID)).toBe(false);
+ expect(h.registeredByok.has(PROVIDER_ID)).toBe(false);
+ h.refresh([enterprise]);
+ expect(h.registry.resolve(PROVIDER_ID)).not.toBe(previous);
+ expect(h.createEnterprise).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([enterprise, personal])('removes the $source channel on logout without disturbing static channels', (provider) => {
+ const h = harness();
+ const statics = new Map(['xd', 'openai', 'gemini', 'xai'].map((id) => [id, stubChannel()]));
+ for (const [id, channel] of statics) h.registry.register(id, channel);
+ h.refresh([provider]);
+ h.refresh([]);
+ expect(h.registeredByok.size).toBe(0);
+ expect(h.registeredCodex.size).toBe(0);
+ expect(h.registry.isProviderReady(PROVIDER_ID)).toBe(false);
+ expect(() => h.registry.resolve(PROVIDER_ID)).toThrow(/没有可用的执行通道/);
+ for (const [id, channel] of statics) expect(h.registry.resolve(id)).toBe(channel);
+ });
+
+ it.each([enterprise, personal])('keeps unchanged $source channels registered only once', (provider) => {
+ const h = harness();
+ h.refresh([provider]);
+ const channel = h.registry.resolve(PROVIDER_ID);
+ h.refresh([provider]);
+ expect(h.registry.resolve(PROVIDER_ID)).toBe(channel);
+ expect(h.createEnterprise.mock.calls.length + h.createPersonal.mock.calls.length).toBe(1);
+ expect(() => h.registry.register(PROVIDER_ID, stubChannel())).toThrow(/already registered/);
+ });
+});
+
+describe('Art BYOK image channel host wiring', () => {
+ const source = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');
+ const start = source.indexOf('function getImageChannelRegistry()');
+ const end = source.indexOf('\nfunction resolveImageChannelForModel', start);
+ const body = source.slice(start, end);
+
+ it('registers a live BYOK channel without reusing xd/openai/gemini/xai', () => {
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ expect(body).toContain('registerByokImageChannels');
+ expect(body).toContain("readByokCredential(providerId, 'image')");
+ expect(body).toContain('readByokInferenceBase(providerId)');
+ expect(body).toContain("registry.register('xd'");
+ expect(body).toContain("registry.register('openai'");
+ expect(body).toMatch(/registry\.register\(\s*'gemini'/);
+ expect(body).toMatch(/registry\.register\(\s*'xai'/);
+ expect(body).not.toContain('stripByok');
+ expect(body).not.toContain("startsWith('byok-') ? id.slice");
+ });
+
+ it('keeps dynamic BYOK registration on singleton refreshes', () => {
+ expect(body).toContain('registeredByokImageAccounts');
+ expect(body).toMatch(
+ /imageChannelRegistrySingleton = registry;[\s\S]*registerByokImageChannels/,
+ );
+ });
+
+ it('prunes stale accounts before either dynamic registration loop runs', () => {
+ const prune = body.indexOf('pruneDynamicImageChannels(');
+ expect(prune).toBeGreaterThan(body.indexOf('imageChannelRegistrySingleton = registry;'));
+ expect(prune).toBeLessThan(body.indexOf('imageChannelRegistrySingleton.register(providerId'));
+ expect(prune).toBeLessThan(body.indexOf('registerByokImageChannels('));
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts
index be98be1261..d47b292a3b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts
@@ -52,6 +52,22 @@ describe('ImageChannelRegistry', () => {
expect(registry.isProviderEditReady('unknown')).toBe(false);
});
+ it('unregister releases only the selected provider and allows a new channel for that ID', () => {
+ const registry = new ImageChannelRegistry();
+ const xd = channel(true);
+ registry.register('xd', xd);
+ registry.register('dynamic', channel(true));
+ registry.unregister('dynamic');
+ registry.unregister('dynamic');
+ expect(registry.isProviderReady('dynamic')).toBe(false);
+ expect(registry.isProviderEditReady('dynamic')).toBe(false);
+ expect(() => registry.resolve('dynamic')).toThrow(/没有可用的执行通道/);
+ expect(registry.resolve('xd')).toBe(xd);
+ const replacement = channel(true);
+ registry.register('dynamic', replacement);
+ expect(registry.resolve('dynamic')).toBe(replacement);
+ });
+
it('supportsEdit: false 的通道 resolve 后仍携带该标记,供派发层拒改图请求', () => {
const registry = new ImageChannelRegistry();
const generateOnly: ImageChannel = { ...channel(true), supportsEdit: false };
diff --git a/apps/desktop/src/main/cindy-brain/byokImageChannel.ts b/apps/desktop/src/main/cindy-brain/byokImageChannel.ts
new file mode 100644
index 0000000000..0154034abf
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/byokImageChannel.ts
@@ -0,0 +1,149 @@
+/**
+ * Organization BYOK image channel.
+ *
+ * Art only executes providers that have a registered image channel. Independent
+ * enterprise image models already appear in the catalog as `imageModels`, but
+ * BYOK ids are not xd/openai/gemini/xai, so they need their own runtime
+ * registration. One channel per organization provider that actually declares
+ * imageModels; chat-only BYOK stays unregistered. Closures read the live
+ * member key and inference origin so rotate/logout flip ready() without
+ * re-registering. Removed accounts are unregistered before either dynamic
+ * channel type is added, so a reused ID cannot retain the previous route.
+ * The catalog alias is sent as `model` — do not strip the
+ * `byok-<uuid>/` prefix.
+ */
+
+import { isOrganizationManagedProvider, type Provider } from '@cindy/model-providers';
+
+import type { GhostImageAspectRatio } from '../../shared/ghost.js';
+import {
+ createGatewayImageClient,
+ type CreateGatewayImageClientOptions,
+} from '../cindy-proxy-media/api/gatewayImageClient.js';
+import type { ImageChannel, ImageChannelRegistry } from './imageChannelRegistry.js';
+
+/**
+ * Consciousness aspect → gpt-image size enum. Mirrors LEGACY_SIZES in
+ * cindy-media/imageParameters.ts.
+ */
+const GHOST_ASPECT_TO_GATEWAY_SIZE: Record<GhostImageAspectRatio, string> = {
+ '1:1': '1024x1024',
+ '3:2': '1536x1024',
+ '2:3': '1024x1536',
+};
+
+type ByokImageProviderSlice = Pick<Provider, 'id' | 'name' | 'source'> & {
+ imageModels?: Provider['imageModels'];
+};
+
+export interface CreateByokImageChannelOptions {
+ brandLabel?: string;
+ getApiKey(): string | null;
+ getBaseUrl(): string | null;
+ getSupportsEdit(): boolean;
+ fetchImplementation?: typeof fetch;
+ logger?: CreateGatewayImageClientOptions['logger'];
+ beforeDispatch?(model: string): void;
+}
+
+export function createByokImageChannel(opts: CreateByokImageChannelOptions): ImageChannel {
+ const brandLabel = opts.brandLabel?.trim() || '企业模型';
+
+ const client = () => {
+ const baseUrl = opts.getBaseUrl()?.trim() ?? '';
+ if (!baseUrl) {
+ throw new Error(`${brandLabel} 图像通道的推理地址未就绪,请重新登录后重试`);
+ }
+ return createGatewayImageClient({
+ getApiKey: opts.getApiKey,
+ logger: opts.logger,
+ fetchImplementation: opts.fetchImplementation,
+ proxy: {
+ baseUrl,
+ generatePath: '/v1/images/generations',
+ editPath: '/v1/images/edits',
+ },
+ brandLabel,
+ supportsEdit: opts.getSupportsEdit(),
+ missingKeyMessage: `${brandLabel} 图像凭证未就绪,请重新登录或在设置中刷新组织模型`,
+ beforeDispatch: opts.beforeDispatch,
+ });
+ };
+
+ const size = (aspectRatio?: string) =>
+ aspectRatio && aspectRatio in GHOST_ASPECT_TO_GATEWAY_SIZE
+ ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[aspectRatio as GhostImageAspectRatio] }
+ : {};
+
+ return {
+ imageProtocol: 'openai',
+ ready: () => Boolean(opts.getApiKey()?.trim() && opts.getBaseUrl()?.trim()),
+ get supportsEdit() {
+ return opts.getSupportsEdit();
+ },
+ generateImage: ({ model, prompt, aspectRatio, size: requestedSize, quality, signal }) =>
+ client().generateImage(
+ {
+ model,
+ prompt,
+ ...(requestedSize ? { size: requestedSize } : size(aspectRatio)),
+ ...(quality ? { quality } : {}),
+ },
+ signal,
+ ),
+ editImage: ({ model, prompt, imagePaths, aspectRatio, size: requestedSize, quality, signal }) =>
+ client().editImage(
+ {
+ model,
+ prompt,
+ imagePaths,
+ ...(requestedSize ? { size: requestedSize } : size(aspectRatio)),
+ ...(quality ? { quality } : {}),
+ },
+ signal,
+ ),
+ };
+}
+
+/** Release obsolete dynamic channels before registering either kind of account. */
+export function pruneDynamicImageChannels(
+ registry: ImageChannelRegistry,
+ providers: readonly Provider[],
+ registeredCodex: Set<string>,
+ registeredByok: Set<string>,
+): void {
+ const codexIds = new Set(providers.filter((provider) =>
+ !isOrganizationManagedProvider(provider) && provider.auth.native === 'codex',
+ ).map((provider) => provider.id));
+ const byokIds = new Set(providers.filter((provider) =>
+ isOrganizationManagedProvider(provider) && provider.imageModels?.length,
+ ).map((provider) => provider.id));
+ // Prune both kinds before registering either: their IDs can collide across owners.
+ for (const [registered, current] of [[registeredCodex, codexIds], [registeredByok, byokIds]]) {
+ for (const id of registered) {
+ if (current.has(id)) continue;
+ registry.unregister(id);
+ registered.delete(id);
+ }
+ }
+}
+
+/** Register one Art channel per organization provider that currently has imageModels. */
+export function registerByokImageChannels(
+ registry: ImageChannelRegistry,
+ providers: readonly ByokImageProviderSlice[],
+ registered: Set<string>,
+ createChannel: (provider: ByokImageProviderSlice) => ImageChannel,
+): void {
+ for (const provider of providers) {
+ if (
+ !isOrganizationManagedProvider(provider) ||
+ registered.has(provider.id) ||
+ !provider.imageModels?.length
+ ) {
+ continue;
+ }
+ registry.register(provider.id, createChannel(provider));
+ registered.add(provider.id);
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
index 859dd9a7f8..36a472ddec 100644
--- a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
+++ b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
@@ -14,7 +14,8 @@
* providerId 归属取通道;**未注册的 providerId 视为不就绪**——即使目录数据
* 先于通道代码合入(多 PR 乱序),新模型也只是不出现,不会错发到别家通道。
*
- * 注册发生在 host 装配期(cindy-brain/index.ts);本模块零 IO、零 electron 依赖
+ * 注册发生在 host 装配期(cindy-brain/index.ts);动态账号退出目录时解除注册。
+ * 本模块零 IO、零 electron 依赖
* (规则 14),单测直测。
*/
@@ -101,6 +102,10 @@ export class ImageChannelRegistry {
this.channels.set(providerId, channel);
}
+ unregister(providerId: string): void {
+ this.channels.delete(providerId);
+ }
+
/** 白名单派生用:未注册 = 不就绪(目录数据先行时的乱序安全兜底)。 */
isProviderReady(providerId: string): boolean {
return this.channels.get(providerId)?.ready() === true;
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 29ed3e9dd4..bb4b3c78c0 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -387,6 +387,7 @@ import { invalidateXaiBridgeAuth } from '../maker-host/xai-auth-invalidation-hos
import {
isModelDisabled,
isModelDisabledWithUniqueLegacyBasename,
+ isOrganizationManagedProvider,
isProviderDisabled,
type MediaCapability,
xaiApiOfficialRuntimeAgents,
@@ -438,6 +439,8 @@ import { createGeminiImageChannel } from './geminiImageClient.js';
import { createCodexImageChannel } from './codexImageClient.js';
import { getCodexImageAuthBinding } from './codexImageAuthBinding.js';
import { createGatewayImageClient } from '../cindy-proxy-media/api/gatewayImageClient.js';
+import { createByokImageChannel, pruneDynamicImageChannels, registerByokImageChannels } from './byokImageChannel.js';
+import { readByokCredential, readByokInferenceBase } from '../model-access/byokCredentials.js';
import { createXaiVideoProvider } from '../cindy-proxy-media/video/providers/xai.js';
import * as blobStore from '../cindy-media/blobStore.js';
import {
@@ -4120,6 +4123,7 @@ function getGhostImageCapabilities(
* 后续来源(gemini / openai / xai)在各自 PR 里追加注册。
*/
const registeredCodexImageAccounts = new Set<string>();
+const registeredByokImageAccounts = new Set<string>();
let imageChannelRegistrySingleton: ImageChannelRegistry | null = null;
function getImageChannelRegistry(): ImageChannelRegistry {
if (!imageChannelRegistrySingleton) {
@@ -4260,8 +4264,10 @@ function getImageChannelRegistry(): ImageChannelRegistry {
});
imageChannelRegistrySingleton = registry;
}
- for (const provider of getActiveCatalog().providers) {
- if (provider.auth.native !== 'codex' || registeredCodexImageAccounts.has(provider.id)) continue;
+ const imageProviders = getActiveCatalog().providers;
+ pruneDynamicImageChannels(imageChannelRegistrySingleton, imageProviders, registeredCodexImageAccounts, registeredByokImageAccounts);
+ for (const provider of imageProviders) {
+ if (isOrganizationManagedProvider(provider) || provider.auth.native !== 'codex' || registeredCodexImageAccounts.has(provider.id)) continue;
const providerId = provider.id;
imageChannelRegistrySingleton.register(providerId, createCodexImageChannel({
providerId,
@@ -4273,6 +4279,30 @@ function getImageChannelRegistry(): ImageChannelRegistry {
}));
registeredCodexImageAccounts.add(providerId);
}
+ // Organization BYOK image models get their own channel. Do not reuse xd /
+ // openai / gemini / xai: those stay personal or gateway routes. Chat-only
+ // BYOK is skipped until the catalog grows imageModels. Closures read the
+ // live member key and inference origin so rotate/logout flip ready().
+ registerByokImageChannels(
+ imageChannelRegistrySingleton,
+ imageProviders,
+ registeredByokImageAccounts,
+ (provider) => {
+ const providerId = provider.id;
+ return createByokImageChannel({
+ brandLabel: provider.name,
+ getApiKey: () => readByokCredential(providerId, 'image'),
+ getBaseUrl: () => readByokInferenceBase(providerId),
+ getSupportsEdit: () => {
+ const current = getActiveCatalog().providers.find((candidate) => candidate.id === providerId);
+ return (current?.imageModels ?? []).some((model) => model.modalities?.input.includes('image') === true);
+ },
+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', model, providerId),
+ logger: log,
+ });
+ },
+ );
return imageChannelRegistrySingleton;
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.ts
index 9709bf475f..6533221eef 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogRevision.test.ts
@@ -4,13 +4,17 @@ import { BUNDLED_CATALOG, providerMediaField } from '@cindy/model-providers';
import {
commitModelPlaneFromCatalog,
+ clearDiscoveredProviderModels,
getActiveCatalog,
getActiveCatalogRevision,
setActiveCatalog,
+ setManagedProviders,
setActiveCatalogChangedListener,
setAnthropicDiscoveredModels,
setCustomProviderConfigs,
setDiscoveredCodexModels,
+ setDiscoveredProviderMediaModels,
+ setDiscoveredProviderModels,
setXaiDiscoveredModels,
} from '../active-catalog.js';
@@ -20,8 +24,11 @@ describe('active catalog revision', () => {
setActiveCatalog(BUNDLED_CATALOG);
setAnthropicDiscoveredModels([]);
setDiscoveredCodexModels([]);
+ clearDiscoveredProviderModels();
+ setDiscoveredProviderMediaModels('byok-collision', null);
setXaiDiscoveredModels(null);
setCustomProviderConfigs([]);
+ setManagedProviders([]);
});
it('invalidates the merged catalog before notifying one monotonic revision', () => {
@@ -253,4 +260,52 @@ describe('active catalog revision', () => {
currentOpenAi.models.codex,
);
});
+ it('retains a pending enterprise Provider without inventing a runnable route', () => {
+ setManagedProviders([{ id: 'byok-pending', name: 'Enterprise',
+ source: 'organization', auth: { method: 'managed' }, access: { kind: 'managed' }, agents: [], models: {}, routing: {},
+ }]);
+ expect(getActiveCatalog().providers.find((provider) => provider.id === 'byok-pending')).toMatchObject({
+ agents: [], models: {}, routing: {}, source: 'organization',
+ });
+ setManagedProviders([]);
+ expect(getActiveCatalog().providers.some((provider) => provider.id === 'byok-pending')).toBe(false);
+ });
+
+ it('temporarily gives a managed Provider precedence over a legacy personal id collision', () => {
+ setCustomProviderConfigs([{
+ id: 'byok-collision', name: 'Legacy personal', runtimes: {
+ pi: { baseUrl: 'https://personal.example/v1', models: [{ id: 'chat', name: 'Chat' }] },
+ },
+ }]);
+ setDiscoveredProviderModels('byok-collision', 'pi', [{
+ id: 'personal-discovered', name: 'Personal discovered', contextWindow: 8_000,
+ efforts: [], defaultEffort: null,
+ }]);
+ setDiscoveredProviderMediaModels('byok-collision', {
+ imageModels: [{ id: 'personal-image', name: 'Personal image' }],
+ });
+ setManagedProviders([{
+ id: 'byok-collision', name: 'Enterprise', source: 'organization',
+ auth: { method: 'managed' }, access: { kind: 'managed' }, agents: ['pi'],
+ models: { pi: [{ id: 'enterprise-chat', name: 'Enterprise chat', contextWindow: 8_000,
+ efforts: [], defaultEffort: null }] }, routing: {},
+ imageModels: [{ id: 'enterprise-image', name: 'Enterprise image' }],
+ }]);
+ const enterprise = getActiveCatalog().providers.filter(
+ (provider) => provider.id === 'byok-collision',
+ );
+ expect(enterprise).toHaveLength(1);
+ expect(enterprise[0]).toMatchObject({
+ name: 'Enterprise', source: 'organization',
+ models: { pi: [{ id: 'enterprise-chat' }] },
+ imageModels: [{ id: 'enterprise-image' }],
+ });
+
+ setManagedProviders([]);
+ expect(getActiveCatalog().providers.find((provider) => provider.id === 'byok-collision')).toMatchObject({
+ name: 'Legacy personal', source: 'user',
+ models: { pi: expect.arrayContaining([expect.objectContaining({ id: 'personal-discovered' })]) },
+ });
+ });
+
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexImageModelRewrite.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexImageModelRewrite.test.ts
new file mode 100644
index 0000000000..cbfcfb5162
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/codexImageModelRewrite.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import { createCodexImageModelRewrite } from '../codex-image-model-rewrite.js';
+
+const binding = {
+ wireModel: 'gpt-image-2',
+ litellmModel: 'byok-a/image-alias',
+ supportsEdit: true,
+};
+const rewrite = createCodexImageModelRewrite(binding);
+const ctx = {
+ reqId: 1,
+ method: 'POST',
+ url: '/images/generations',
+ headers: { 'content-type': 'application/json' },
+};
+
+describe('Codex Provider image model binding', () => {
+ it.each(['{}', 'null', '[]', '{"model":"other-provider/image"}', '{"prompt":"private-prompt"'])(
+ 'rejects invalid input without including the payload: %s',
+ async (input) => {
+ await expect(rewrite(Buffer.from(input), ctx)).rejects.toThrow();
+ try {
+ await rewrite(Buffer.from(input), ctx);
+ } catch (error) {
+ expect(String(error)).not.toContain('private-prompt');
+ }
+ },
+ );
+
+ it('rejects duplicate multipart model fields and invalid multipart bodies', async () => {
+ const form = new FormData();
+ form.append('model', 'gpt-image-2');
+ form.append('model', 'other-model');
+ const encoded = new Response(form);
+ await expect(
+ rewrite(Buffer.from(await encoded.arrayBuffer()), {
+ ...ctx,
+ headers: { 'content-type': encoded.headers.get('content-type')! },
+ }),
+ ).rejects.toThrow('Provider binding');
+ await expect(
+ rewrite(Buffer.from('invalid'), {
+ ...ctx,
+ headers: { 'content-type': 'multipart/form-data' },
+ }),
+ ).rejects.toThrow('Invalid image request multipart body');
+ });
+
+ it('rejects unsupported encodings and content types', async () => {
+ await expect(
+ rewrite(Buffer.from('{}'), {
+ ...ctx,
+ headers: { ...ctx.headers, 'content-encoding': 'gzip' },
+ }),
+ ).rejects.toThrow('encoding');
+ await expect(
+ rewrite(Buffer.from('{}'), {
+ ...ctx,
+ headers: { 'content-type': 'application/octet-stream' },
+ }),
+ ).rejects.toThrow('content type');
+ });
+
+ it('rejects edits locally when the Provider binding is generate-only', async () => {
+ const generateOnly = createCodexImageModelRewrite({ ...binding, supportsEdit: false });
+ await expect(
+ generateOnly(Buffer.from('{"model":"gpt-image-2"}'), {
+ ...ctx,
+ url: '/_cindy/custom-provider/route/images/edits',
+ }),
+ ).rejects.toThrow('not supported');
+ await expect(
+ generateOnly(Buffer.from('{"model":"gpt-image-2"}'), {
+ ...ctx,
+ url: '/_cindy/custom-provider/route/images/generations',
+ }),
+ ).resolves.toEqual({ body: Buffer.from('{"model":"byok-a/image-alias"}') });
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 9d6616b0ec..67fd2158e7 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -7956,6 +7956,119 @@ describe('createModelRoutingTransform —— custom Provider native imagegen pre
}
});
+ it('rewrites BYOK image aliases per Provider over HTTP, including multipart and frozen hosts', async () => {
+ const received: Array<{ path: string; body: Buffer; headers: Record<string, string | string[] | undefined> }> = [];
+ const upstream = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on('data', (chunk: Buffer) => chunks.push(chunk));
+ req.on('end', () => {
+ received.push({ path: req.url ?? '', body: Buffer.concat(chunks), headers: req.headers });
+ res.writeHead(200, { 'content-type': 'application/json' }).end('{}');
+ });
+ });
+ await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));
+ const host = await freshCodexProxyHost();
+ const actualProxy = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>(
+ '@cindy/anthropic-compat-proxy',
+ );
+ mockState.createAnthropicCompatProxy.mockImplementation(actualProxy.createAnthropicCompatProxy);
+ const { BUNDLED_CATALOG } = await import('@cindy/model-providers');
+ const { buildByokProvider } = await import('../../model-access/byokProvider.js');
+ const { setCustomProviderKeyReader } = await import('../provider-route.js');
+ const { setActiveCatalog } = await import('../active-catalog.js');
+ const { deriveCodexCustomProviderRoutes } = await import('../codex-custom-provider-route.js');
+ const providers = ['byok-a', 'byok-b'].map((id) => buildByokProvider({
+ provider: {
+ id, name: id, connectionRevision: 1,
+ models: [{ id: `${id}/chat`, mode: 'chat', agents: ['codex'], currency: 'CNY',
+ perAgent: { codex: { wireProtocol: 'openai-responses' } } }],
+ imageBinding: { enabled: true, modelId: 'gpt-image-2', wireModel: 'gpt-image-2',
+ litellmModel: `${id}/gpt-image-2`, supportsEdit: true },
+ },
+ credential: { providerId: id, status: 'ready', connectionRevision: 1,
+ endpoint: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}/v1`,
+ apiKey: `fake-${id}` },
+ }));
+ const catalog = { ...BUNDLED_CATALOG, providers: [...BUNDLED_CATALOG.providers, ...providers] };
+ setActiveCatalog(catalog);
+ setCustomProviderKeyReader((id) => providers.some((p) => p.id === id) ? `fake-${id}` : null);
+ const routes = deriveCodexCustomProviderRoutes(catalog);
+ host.setCodexAppliedCustomProviderRoutes(routes);
+ expect(routes.every((route) => route.routing.imageModel)).toBe(true);
+ const payload = { model: 'gpt-image-2', prompt: 'draw', quality: 'auto', vendor_field: 'retain',
+ input: [{ type: 'custom_tool_call', id: 'fc_original', call_id: 'call_original' }] };
+ try {
+ await host.ensureCodexProxyReady();
+ await host.ensureCodexCustomContextProxyReady('byok-image-test', 'env-key', routes);
+ // A frozen Host must use its own binding even after the global snapshot changes.
+ host.setCodexAppliedCustomProviderRoutes(routes.map((route) => ({ ...route,
+ routing: { ...route.routing, imageModel: { ...route.routing.imageModel!, litellmModel: 'wrong-global-alias' } },
+ })));
+ for (const route of routes) {
+ const endpoint = host.getCodexCustomContextProxyEndpoint('byok-image-test');
+ for (const operation of ['generations', 'edits']) {
+ const response = await fetch(`${endpoint}/_cindy/custom-provider/${route.routeId}/images/${operation}`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload),
+ });
+ expect(response.status).toBe(200);
+ await response.text();
+ const request = received.at(-1)!;
+ expect(request.path).toBe(`/v1/images/${operation}`);
+ expect(request.headers.authorization).toBe(`Bearer fake-${route.providerId}`);
+ expect(JSON.parse(request.body.toString())).toEqual({ ...payload, model: `${route.providerId}/gpt-image-2` });
+ expect(request.headers['content-length']).toBe(String(request.body.length));
+ }
+ const pixels = new Uint8Array([0, 255, 128, 13, 10, 77]);
+ const form = new FormData();
+ form.set('model', 'gpt-image-2');
+ form.set('prompt', 'edit');
+ form.append('image[]', new Blob([pixels], { type: 'image/png' }), 'input.png');
+ form.append('image[]', new Blob([pixels], { type: 'image/png' }), 'input-2.png');
+ form.set('mask', new Blob([pixels], { type: 'image/png' }), 'mask.png');
+ const response = await fetch(`${endpoint}/_cindy/custom-provider/${route.routeId}/images/edits`, {
+ method: 'POST', body: form,
+ });
+ expect(response.status).toBe(200);
+ await response.text();
+ const request = received.at(-1)!;
+ const uploaded = await new Response(new Uint8Array(request.body), {
+ headers: { 'content-type': String(request.headers['content-type']) },
+ }).formData();
+ expect(uploaded.get('model')).toBe(`${route.providerId}/gpt-image-2`);
+ expect(uploaded.get('prompt')).toBe('edit');
+ expect(uploaded.getAll('image[]')).toHaveLength(2);
+ const file = uploaded.getAll('image[]')[0] as File;
+ expect(file.name).toBe('input.png');
+ expect(file.type).toBe('image/png');
+ expect(new Uint8Array(await file.arrayBuffer())).toEqual(pixels);
+ expect(new Uint8Array(await (uploaded.get('mask') as File).arrayBuffer())).toEqual(pixels);
+ expect(request.headers.authorization).toBe(`Bearer fake-${route.providerId}`);
+ expect(request.headers['content-length']).toBe(String(request.body.length));
+ }
+ host.setCodexAppliedCustomProviderRoutes(routes);
+ const response = await fetch(`${host.getCodexProxyEndpoint()}/_cindy/custom-provider/${routes[0]!.routeId}/images/generations`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload),
+ });
+ expect(response.status).toBe(200);
+ await response.text();
+ expect(JSON.parse(received.at(-1)!.body.toString()).model).toBe('byok-a/gpt-image-2');
+ const count = received.length;
+ const rejected = await fetch(`${host.getCodexProxyEndpoint()}/_cindy/custom-provider/${routes[0]!.routeId}/images/generations`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ...payload, model: 'byok-b/gpt-image-2' }),
+ });
+ expect(rejected.status).toBe(502);
+ await rejected.text();
+ expect(received).toHaveLength(count);
+ } finally {
+ await host.disposeCodexProxy();
+ host.setCodexAppliedCustomProviderRoutes([]);
+ setCustomProviderKeyReader(() => null);
+ setActiveCatalog(BUNDLED_CATALOG);
+ await new Promise<void>((resolve) => upstream.close(() => resolve()));
+ }
+ });
+
it.each([{ efforts: [] }, { efforts: ['high'] }, { efforts: ['high', 'max'] }] as const)('reconciles frozen namespaced Responses capabilities $efforts over HTTP without rewriting native fields or image JSON', async ({ efforts }) => {
const received: Array<{ path: string; body: string }> = [];
const upstream = createServer((req, res) => {
@@ -7984,6 +8097,13 @@ describe('createModelRoutingTransform —— custom Provider native imagegen pre
models: [{ id: 'codex/native-model', name: 'Native model', reasoning: true, reasoningEfforts: [...efforts] }],
} },
});
+ // A local custom Provider must keep image requests opaque even if a stale or
+ // experimental config happens to carry the BYOK-only binding shape.
+ provider.routing.codex!.imageModel = {
+ wireModel: 'gpt-image-2',
+ litellmModel: 'local/should-not-rewrite',
+ supportsEdit: true,
+ };
const catalog = { ...BUNDLED_CATALOG, providers: [...BUNDLED_CATALOG.providers, provider] };
setActiveCatalog(catalog);
setCustomProviderKeyReader(() => 'fake-native-key');
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index c0c7d2642b..f7c6e28aa6 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -2747,3 +2747,22 @@ it('launches a new Azure deployment with the bound connection API and configured
{ ...BUNDLED_CATALOG, providers: [provider] });
expect(result.providers[0]?.models[0]).toMatchObject({ id: 'deployment-new', api: 'azure-openai-responses', contextWindow: 64000 });
});
+
+it('serializes mixed-protocol enterprise models with their own gateway base URLs', async () => {
+ const { buildByokProvider, byokNativeConfigs } = await import('../../model-access/byokProvider.js');
+ const protocols = ['openai-completions', 'openai-responses', 'anthropic-messages'] as const;
+ const provider = buildByokProvider({ provider: {
+ id: 'byok-mixed', name: 'Enterprise', connectionRevision: 1,
+ models: protocols.map((protocol) => ({ id: `byok-mixed/${protocol}`, name: protocol, agents: ['pi'], currency: 'CNY', contextWindow: 128000,
+ perAgent: { pi: { wireProtocol: protocol } } })),
+ }, credential: { providerId: 'byok-mixed', connectionRevision: 1, status: 'ready', endpoint: 'https://gateway.example/gateway/v1/', apiKey: 'test-only' } });
+ const result = buildPiNativeProvidersFromConfigs(byokNativeConfigs([provider]), () => 'test-only');
+ expect(result.providers).toHaveLength(1);
+ for (const [index, api] of protocols.entries()) {
+ const model = result.providers[0]!.models![index]!;
+ expect(model.api).toBe(api);
+ expect(model.baseUrl ?? result.providers[0]!.baseUrl).toBe(
+ api === 'anthropic-messages' ? 'https://gateway.example/gateway' : 'https://gateway.example/gateway/v1',
+ );
+ }
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerConnectionState.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerConnectionState.test.ts
index f2d50c6754..e736d32b8a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerConnectionState.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerConnectionState.test.ts
@@ -37,4 +37,20 @@ describe('custom provider credential readiness', () => {
provider.routing.codex!.authStrategy = 'none';
expect(hasCustomProviderCredential(provider, () => null)).toBe(true);
});
+ it('recognizes an organization image-only provider through its image credential', () => {
+ const provider = {
+ ...custom(),
+ id: 'byok-images',
+ source: 'organization' as const,
+ agents: [],
+ routing: {},
+ imageModels: [{ id: 'byok-images/model', name: 'Model' }],
+ };
+ expect(hasCustomProviderCredential(provider, () => null)).toBe(false);
+ expect(
+ hasCustomProviderCredential(provider, (id, agent) =>
+ id === 'byok-images' && agent === 'image' ? 'member-key' : null,
+ ),
+ ).toBe(true);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts
index b89b00b3d0..5cae6f878c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts
@@ -46,6 +46,7 @@ import {
setAnthropicDiscoveredModels,
setCustomProviders,
setDiscoveredCodexModels,
+ setManagedProviders,
setXdGatewayModels,
} from '../active-catalog.js';
import { setSessionProvider, clearSessionProvider } from '../session-provider-store.js';
@@ -1429,6 +1430,44 @@ describe('resolveSessionRouteDecision — 自定义供应商(resolve 时注入 k
expect(newDecision?.routing).not.toHaveProperty('headerOverride');
});
+ it('does not inject stale personal headers into organization-managed routes', async () => {
+ const providerId = 'byok-header-isolation';
+ const routing: RoutingDescriptor = {
+ upstream: 'https://gateway.example.invalid/v1',
+ authStrategy: 'api-key-header',
+ wireProtocol: 'openai-responses',
+ };
+ setManagedProviders([{
+ id: providerId, name: 'Enterprise', source: 'organization',
+ auth: { method: 'managed' }, access: { kind: 'managed' }, agents: ['codex'],
+ models: { codex: [] }, routing: { codex: routing },
+ }]);
+ setCustomProviderKeyReader(() => 'managed-member-key');
+ setCustomProviderHeaderReader(() => ({
+ Authorization: 'Bearer stale-personal-key',
+ 'x-personal-tenant': 'must-not-leak',
+ }));
+
+ try {
+ const resolved = await resolveFrozenProviderRouteDecision(
+ providerId,
+ routing,
+ getProviderRouteCredentialRevision(providerId),
+ 'codex',
+ KEY,
+ );
+ expect(resolved?.decision).toMatchObject({
+ upstreamOverride: 'https://gateway.example.invalid/v1',
+ headerOverride: { authorization: 'Bearer managed-member-key' },
+ });
+ expect(resolved?.decision?.headerOverride).not.toHaveProperty('x-personal-tenant');
+ } finally {
+ setManagedProviders([]);
+ setCustomProviderKeyReader(() => null);
+ setCustomProviderHeaderReader(() => null);
+ }
+ });
+
it('精确请求路径只覆盖带 model 的推理请求,不改写无 body 的控制面请求', () => {
setCustomProviders([
buildUserProvider({
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 431ada2870..c484c3b240 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -1,4 +1,8 @@
-import { projectProviderMediaModels } from '@cindy/model-providers';
+import {
+ projectProviderMediaModels,
+ isCustomRoutedProvider,
+ isOrganizationManagedProvider,
+} from '@cindy/model-providers';
import {
applyExistingModelLocalPatch,
applyLocalModelCatalogOverrides,
@@ -115,6 +119,7 @@ let baseUnverifiedXdMediaKinds: ReadonlySet<CatalogXdMediaKind> = new Set([
let trustedCustomProviderRegistry: Catalog['modelRegistry'] = BUNDLED_CATALOG.modelRegistry;
/** 用户自定义供应商(已 buildUserProvider 展开的标准 Provider),追加在 base 之后。 */
let custom: Provider[] = [];
+let managed: Provider[] = [];
/** 当前 owner 的原始配置;仅用于 Registry 热更新后的运行时重投影。 */
let customConfigs: CustomProviderConfig[] | null = null;
/**
@@ -1178,29 +1183,36 @@ function computeMerged(): Catalog {
// Bind the public image definition before applying any account discovery or overrides.
// Copying the final builtin connection would leak its Platform-key membership/preferences.
const openaiDefinition = providerSources.find((provider) => provider.id === 'openai');
- const accounts = custom.map((provider) => {
- if (!isOpenAiSubscriptionProvider(provider)) return provider;
- const bindId = (id: string): string => id.replace(/^openai\//, `${provider.id}/`);
- const defaults = openaiDefinition?.imageDefaults;
- return {
- ...provider,
- imageModels: openaiDefinition?.imageModels?.map((model) => ({
- ...model,
- id: bindId(model.id),
- })),
- imageDefaults: defaults ? {
- standard: bindId(defaults.standard),
- ...(defaults.draft ? { draft: bindId(defaults.draft) } : {}),
- ...(defaults.best ? { best: bindId(defaults.best) } : {}),
- } : undefined,
- };
- });
+ const managedIds = new Set(managed.map((provider) => provider.id));
+ const accounts = custom
+ .filter((provider) => !managedIds.has(provider.id))
+ .map((provider) => {
+ if (!isOpenAiSubscriptionProvider(provider)) return provider;
+ const bindId = (id: string): string => id.replace(/^openai\//, `${provider.id}/`);
+ const defaults = openaiDefinition?.imageDefaults;
+ return {
+ ...provider,
+ imageModels: openaiDefinition?.imageModels?.map((model) => ({
+ ...model,
+ id: bindId(model.id),
+ })),
+ imageDefaults: defaults
+ ? {
+ standard: bindId(defaults.standard),
+ ...(defaults.draft ? { draft: bindId(defaults.draft) } : {}),
+ ...(defaults.best ? { best: bindId(defaults.best) } : {}),
+ }
+ : undefined,
+ };
+ });
providers = [...providers, ...accounts];
}
+ if (managed.length > 0) providers = [...providers, ...managed];
// 通用 OAuth 供应商的发现模型(additions-only,per provider × agent;内置与自定义同待遇)。
if (discoveredByProvider.size > 0) {
providers = providers.map((p) => {
+ if (isOrganizationManagedProvider(p)) return p;
const byAgent = discoveredByProvider.get(p.id);
if (!byAgent) return p;
let next = p;
@@ -1212,6 +1224,7 @@ function computeMerged(): Catalog {
}
if (discoveredMediaByProvider.size > 0) {
providers = providers.map((provider) => {
+ if (isOrganizationManagedProvider(provider)) return provider;
const snapshot = discoveredMediaByProvider.get(provider.id);
if (!snapshot) return provider;
let next = provider;
@@ -1575,7 +1588,7 @@ function computeMerged(): Catalog {
// Per-Harness declarations own membership; Registry metadata contributes
// shared model intent without manufacturing another Harness route.
const entry =
- agent === 'pi' && (provider.source !== 'user' || !!provider.auth.native) && provider.id !== 'xd'
+ agent === 'pi' && (!isCustomRoutedProvider(provider) || !!provider.auth.native) && provider.id !== 'xd'
? findModelRegistryRoute(
b.modelRegistry,
metadataProviderId,
@@ -1596,7 +1609,7 @@ function computeMerged(): Catalog {
// Apply to each built-in GPT route, including subscription and discount aliases.
// Never enlarge smaller models or overwrite BYOM / explicit preference overrides.
const conservativeGptDefault =
- (provider.source !== 'user' || !!provider.auth.native) &&
+ (!isCustomRoutedProvider(provider) || !!provider.auth.native) &&
['openai', 'xd'].includes(metadataProviderId) &&
/^(?:(?:codex|openai|chatgpt)\/)?gpt-/.test(model.id) &&
model.contextWindow > 272_000 &&
@@ -1673,7 +1686,7 @@ function computeMerged(): Catalog {
const metadataProviderId = providerCatalogId(provider);
if (
(b.modelRegistry?.schemaVersion ?? 0) >= 4 &&
- (provider.source !== 'user' || !!provider.auth.native) &&
+ (!isCustomRoutedProvider(provider) || !!provider.auth.native) &&
(provider.id === 'xd' || agent === 'pi')
) {
next = applyModelMetadata(
@@ -1691,7 +1704,7 @@ function computeMerged(): Catalog {
);
}
if (
- (provider.source !== 'user' || !!provider.auth.native) &&
+ (!isCustomRoutedProvider(provider) || !!provider.auth.native) &&
['openai', 'xd'].includes(metadataProviderId) &&
/^(?:(?:codex|openai|chatgpt)\/)?gpt-/.test(next.id) &&
next.contextWindow > 272_000 &&
@@ -2035,6 +2048,12 @@ export function getModelPlaneWarnings(): readonly ModelPlaneWarning[] {
return lastPlanWarnings;
}
+/** Complete directory for the current authenticated enterprise. */
+export function setManagedProviders(providers: Provider[]): void {
+ managed = [...providers];
+ markChanged();
+}
+
/**
* 注入 / 刷新用户自定义供应商(CRUD 后、或换账号 DB 重开后调用)。
* 传入的是已 `buildUserProvider` 展开的标准 `Provider[]`(**不含 API key**)。
diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
index 9dfee42f9c..772d0df8c0 100644
--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
@@ -27,6 +27,7 @@ import {
type Catalog,
type CatalogModel,
type AgentKind,
+ isCustomRoutedProvider,
} from '@cindy/model-providers';
import type { ModelDescriptor } from '@cindy/maker-core';
import type { ModelCatalogOverrides } from './model-plane/localCatalogOverrides.js';
@@ -38,7 +39,7 @@ interface ModelCapabilitiesTarget {
interface SeenModelProjection {
index: number;
- includesUserProvider: boolean;
+ includesCustomRoutedProvider: boolean;
}
/** CatalogModel → ModelDescriptor。仅透传 ModelDescriptor 需要的字段;可选字段缺省时不写键。 */
@@ -129,15 +130,16 @@ export function deriveAvailableModels(catalog: Catalog, agent: AgentKind): Model
// availableModels 是旧 mobile / device-link 等消费方的新选择清单,不能依赖下游
// 再理解 retired。运行中会话仍从持久化 model + 完整 catalog 解析实际路由。
const userProvider = provider.source === 'user';
+ const customRoutedProvider = isCustomRoutedProvider(provider);
if (isLegacyGptContextProfile(provider, m.id)) continue;
if (!isModelSelectableForNewRoute(m, { userProvider })) continue;
const descriptor = toDescriptor(m);
const previous = seen.get(m.id);
if (previous) {
let merged = out[previous.index];
- if (agent === 'pi' && (previous.includesUserProvider || userProvider)) {
+ if (agent === 'pi' && (previous.includesCustomRoutedProvider || customRoutedProvider)) {
merged = intersectPiEffortCapabilities(merged, descriptor);
- previous.includesUserProvider ||= userProvider;
+ previous.includesCustomRoutedProvider ||= customRoutedProvider;
}
// 只有鉴权后的 XD /models 会被 active-catalog 投影成区域默认;公共 Registry 与
// user provider 均不能借同 id 碰撞改变默认策略。
@@ -147,7 +149,7 @@ export function deriveAvailableModels(catalog: Catalog, agent: AgentKind): Model
out[previous.index] = merged;
continue;
}
- seen.set(m.id, { index: out.length, includesUserProvider: userProvider });
+ seen.set(m.id, { index: out.length, includesCustomRoutedProvider: customRoutedProvider });
out.push(descriptor);
}
}
@@ -168,7 +170,7 @@ export function resolvePiRuntimeModelDescriptor(
): ModelDescriptor | null {
const providers =
providerId === 'cindy'
- ? catalog.providers.filter((provider) => provider.source !== 'user')
+ ? catalog.providers.filter((provider) => !isCustomRoutedProvider(provider))
: providerId
? catalog.providers.filter((provider) => provider.id === providerId)
: catalog.providers;
diff --git a/apps/desktop/src/main/maker-host/codex-custom-provider-route.ts b/apps/desktop/src/main/maker-host/codex-custom-provider-route.ts
index 705c226d87..9f66d2ccb4 100644
--- a/apps/desktop/src/main/maker-host/codex-custom-provider-route.ts
+++ b/apps/desktop/src/main/maker-host/codex-custom-provider-route.ts
@@ -1,13 +1,16 @@
import { createHash } from 'node:crypto';
-import type {
- Catalog,
- CustomProviderConfig,
- Effort,
- Provider,
- RoutingDescriptor,
+import {
+ buildUserProvider,
+ isCustomRoutedProvider,
+ isOrganizationManagedProvider,
+ storedCustomProviderId,
+ type Catalog,
+ type CustomProviderConfig,
+ type Effort,
+ type Provider,
+ type RoutingDescriptor,
} from '@cindy/model-providers';
-import { buildUserProvider, storedCustomProviderId } from '@cindy/model-providers';
import {
CODEX_GATEWAY_ENV_KEY,
@@ -88,8 +91,15 @@ function effectiveModelWireProtocol(
return model.route?.wireProtocol ?? routing.wireProtocol ?? 'openai-responses';
}
-function frozenRoutingDescriptor(routing: RoutingDescriptor): RoutingDescriptor {
- const frozen = { ...routing };
+function frozenRoutingDescriptor(
+ routing: RoutingDescriptor,
+ keepImageModel: boolean,
+): RoutingDescriptor {
+ const frozen = {
+ ...routing,
+ ...(keepImageModel && routing.imageModel ? { imageModel: { ...routing.imageModel } } : {}),
+ };
+ if (!keepImageModel) delete frozen.imageModel;
// Custom headers are credentials. Keep them out of the Host snapshot; values are read at request
// time behind provider-route's credential generation gate.
delete frozen.headerOverride;
@@ -101,7 +111,7 @@ function frozenRoutingDescriptor(routing: RoutingDescriptor): RoutingDescriptor
}
function routeForProvider(provider: Provider): CodexCustomProviderRoute | null {
- if (provider.source !== 'user' || !provider.agents.includes('codex')) return null;
+ if (!isCustomRoutedProvider(provider) || !provider.agents.includes('codex')) return null;
const routing = provider.routing.codex;
if (!routing || routing.disabled) return null;
const capabilities: CodexCustomProviderCapabilities = {
@@ -114,7 +124,7 @@ function routeForProvider(provider: Provider): CodexCustomProviderRoute | null {
const responseModelIds = responseModels.map((model) => model.id);
if (responseModelIds.length === 0) return null;
const routeId = stableRouteId(storedCustomProviderId(provider.id));
- const frozenRouting = frozenRoutingDescriptor(routing);
+ const frozenRouting = frozenRoutingDescriptor(routing, isOrganizationManagedProvider(provider));
return {
providerId: provider.id,
routeId,
diff --git a/apps/desktop/src/main/maker-host/codex-image-model-rewrite.ts b/apps/desktop/src/main/maker-host/codex-image-model-rewrite.ts
new file mode 100644
index 0000000000..925c3fbc49
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/codex-image-model-rewrite.ts
@@ -0,0 +1,58 @@
+import type { RoutingDecision } from '@cindy/anthropic-compat-proxy';
+import type { RoutingDescriptor } from '@cindy/model-providers';
+
+/** Bind both JSON and multipart image requests to the selected Provider's deployment. */
+export function createCodexImageModelRewrite(
+ binding: NonNullable<RoutingDescriptor['imageModel']>,
+): NonNullable<RoutingDecision['transformRequestBody']> {
+ const { wireModel, litellmModel, supportsEdit } = binding;
+ return async (body, ctx) => {
+ if (!supportsEdit && ctx.url.split('?', 1)[0]?.endsWith('/images/edits')) {
+ throw new Error('Image editing is not supported by this Provider binding');
+ }
+ const encoding = ctx.headers['content-encoding'];
+ if (encoding && encoding.toLowerCase() !== 'identity') {
+ throw new Error('Unsupported image request encoding');
+ }
+ const contentType = ctx.headers['content-type'] ?? '';
+ const mediaType = contentType.split(';', 1)[0].trim().toLowerCase();
+ if (mediaType === 'application/json') {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(body.toString('utf8'));
+ } catch {
+ throw new Error('Invalid image request JSON');
+ }
+ if (
+ !parsed ||
+ typeof parsed !== 'object' ||
+ Array.isArray(parsed) ||
+ !('model' in parsed) ||
+ parsed.model !== wireModel
+ ) {
+ throw new Error('Image request does not match the Provider binding');
+ }
+ return { body: Buffer.from(JSON.stringify({ ...parsed, model: litellmModel })) };
+ }
+ if (mediaType === 'multipart/form-data') {
+ let form: FormData;
+ try {
+ form = await new Response(new Uint8Array(body), {
+ headers: { 'content-type': contentType },
+ }).formData();
+ } catch {
+ throw new Error('Invalid image request multipart body');
+ }
+ if (form.getAll('model').length !== 1 || form.get('model') !== wireModel) {
+ throw new Error('Image request does not match the Provider binding');
+ }
+ form.set('model', litellmModel);
+ const encoded = new Response(form);
+ return {
+ body: Buffer.from(await encoded.arrayBuffer()),
+ contentType: encoded.headers.get('content-type')!,
+ };
+ }
+ throw new Error('Unsupported image request content type');
+ };
+}
diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
index a3d9f44c7b..c6d79bfe20 100644
--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
@@ -1,7 +1,18 @@
import { createAttachmentRecovery } from './oversized-attachment-recovery.js';
import { clearCodexTextOnlyPolicies, codexTextOnlyRequestGuard, codexTextOnlyWebSocketTransforms, isCodexTextOnly } from './codex-text-only-policy.js';
-import { resolveConversationSessionHeaders, withChatBridgeUserAgent, overrideHeadersCaseInsensitive } from '@cindy/responses-chat-bridge';
-import { providerCatalogId, providerModelRecord, type CatalogModel, type Effort, type Provider } from '@cindy/model-providers';
+import {
+ resolveConversationSessionHeaders,
+ withChatBridgeUserAgent,
+ overrideHeadersCaseInsensitive,
+} from '@cindy/responses-chat-bridge';
+import {
+ isCustomRoutedProvider,
+ providerCatalogId,
+ providerModelRecord,
+ type CatalogModel,
+ type Effort,
+ type Provider,
+} from '@cindy/model-providers';
import { reconcileOutboundReasoningEffort } from './outbound-reasoning-effort.js';
import { createPiProviderFetch, handlePiProviderRequest, invocationModelRecord, nativeBridgeApiKey, readBoundedResponseText, requiresNativeProviderAuth } from './pi-provider-transport.js';
import { normalizeProviderRequest, normalizeMiniMaxResponsesReasoning } from '@cindy/model-compat';
@@ -124,6 +135,7 @@ import { outboundFetch } from './outbound-fetch.js';
import { desktopAnthropicImageCodec } from './anthropic-image-codec.js';
import { readSilentEncryptedRetrySettings } from './silent-encrypted-retry-store.js';
import { getLogDir } from '../logger.js';
+import { createCodexImageModelRewrite } from './codex-image-model-rewrite.js';
import { recordXaiRateLimitSnapshot } from '../usageBroadcaster.js';
import {
CODEX_IMAGE_GENERATION_ACTOR_HEADER,
@@ -1108,10 +1120,10 @@ function createChatBridgeDecision(
const { headers } = buildLocalHandlerHeaders(route, 'codex');
const stripPrefix = route.routing.modelIdRewrite?.stripPrefix;
const realModel = rewriteChatBridgeModel(wireModel, stripPrefix);
- // localHandler 绕过 proxy 的 responseObserver,自定义(user)供应商的上游错误不会被
+ // localHandler 绕过 proxy 的 responseObserver,自定义(user/organization)供应商的上游错误不会被
// createProviderUpstreamErrorObserver 看到。这里显式把非 2xx 上游错误喂回同一广播通道,
// 让 Chat 桥接会话与透明自定义供应商一样弹结构化 providerError.* 提示。内置来源不广播
- // (与 observer 的 user-only 语义一致)。
+ // (与 observer 的 custom-routed 语义一致)。
const providerId = route.providerId;
const providerName = getActiveCatalog().providers.find((p) => p.id === providerId)?.name ?? providerId;
const baseCapabilities: ChatBridgeCapabilities = isGoogleGeminiChatUpstream(
@@ -1139,7 +1151,7 @@ function createChatBridgeDecision(
const capabilities = systemMessagePolicy
? { ...routedCapabilities, systemMessagePolicy }
: routedCapabilities;
- const onUpstreamError = route.providerSource === 'user'
+ const onUpstreamError = isCustomRoutedProvider({ source: route.providerSource })
? ({ status, body }: { status: number; body: string }): void => {
reportProviderUpstreamError({ agent: 'codex', providerId, providerName, status, bodyText: body });
}
@@ -1463,7 +1475,7 @@ function createAnthropicBridgeDecision(
const stripPrefix = route.routing.modelIdRewrite?.stripPrefix;
const supportsPromptCaching =
isXdGatewayBridge || isOfficialAnthropicUpstream(upstreamBase);
- const onUpstreamError = route.providerSource === 'user'
+ const onUpstreamError = isCustomRoutedProvider({ source: route.providerSource })
? ({ status, body }: { status: number; body: string }): void => {
reportProviderUpstreamError({ agent: 'codex', providerId, providerName, status, bodyText: body });
}
@@ -2757,6 +2769,9 @@ function resolveCodexCustomProviderRoutingDecision(
...(headerDelete.size > 0 ? { headerDelete: [...headerDelete] } : {}),
...(parsed.pathKind === 'images'
? {
+ ...(frozenRouting.imageModel ? {
+ transformRequestBody: createCodexImageModelRewrite(frozenRouting.imageModel),
+ } : {}),
forwardLifecycle: createCodexImageGenerationForwardLifecycleObserver(
parsed.routeId,
imagePathClass,
@@ -3188,7 +3203,7 @@ function createCodexProxyHandle(
routeOpaqueRequestBody: (ctx) => isCodexCustomProviderNamespacePath(ctx.url),
bypassRequestTransforms: (_body, ctx) => {
const path = parseCodexCustomProviderPath(ctx.url);
- // Image payloads (including JSON) retain their byte-for-byte bypass.
+ // Images skip chat transforms. Only a route-bound deployment alias may rewrite them.
return path.kind !== 'not-custom-provider-route'
&& !(path.kind === 'route' && path.pathKind === 'responses');
},
diff --git a/apps/desktop/src/main/maker-host/model-route-guard.ts b/apps/desktop/src/main/maker-host/model-route-guard.ts
index 552681bfba..fff9f6c60e 100644
--- a/apps/desktop/src/main/maker-host/model-route-guard.ts
+++ b/apps/desktop/src/main/maker-host/model-route-guard.ts
@@ -189,7 +189,7 @@ export function shouldApplyExclusiveProviderReroute(
if (providerId === 'xai') return false;
if (!views) return true;
const source = views.find((provider) => provider.id === providerId)?.source;
- if (source === 'user') return false;
+ if (source === 'user' || source === 'organization') return false;
if (source) return true;
return false;
}
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 033e9ed51e..e2fbad3e79 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -1,5 +1,6 @@
import { readCachedGenericOAuthAccessToken } from './generic-oauth.js';
import { providerPresetModelRecord, providerModelAdapterId } from '@cindy/model-providers';
+import { mergeByokNativeConfigs } from '../model-access/byokProvider.js';
import { readDisabledSkillPaths } from '../skillhub/activationPreferences';
import { subscriptionAccountKind, subscriptionAccountState, isXaiSubscriptionProviderId } from './subscription-account-auth.js';
/**
@@ -784,7 +785,10 @@ class DesktopPiAuthAdapter implements AuthAdapter {
if (providerId) {
const storageProviderId = storedCustomProviderId(providerId);
try {
- const custom = (await listCustomProvidersWithSecureHeaders()).find(
+ const custom = mergeByokNativeConfigs(
+ await listCustomProvidersWithSecureHeaders(),
+ getActiveCatalog().providers,
+ ).find(
(provider) => provider.id === storageProviderId && provider.runtimes.pi,
);
if (custom) {
@@ -1767,7 +1771,7 @@ export async function resolvePiNativeProviders(ctx: {
}
}
const custom = buildPiNativeProvidersFromConfigs(
- configs,
+ mergeByokNativeConfigs(configs, getActiveCatalog().providers),
readCustomProviderKey,
(id, reason) => log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason }),
bundledModels ?? undefined,
diff --git a/apps/desktop/src/main/maker-host/provider-connection-state.ts b/apps/desktop/src/main/maker-host/provider-connection-state.ts
index 1531eb6bbb..ff933f8c2f 100644
--- a/apps/desktop/src/main/maker-host/provider-connection-state.ts
+++ b/apps/desktop/src/main/maker-host/provider-connection-state.ts
@@ -3,8 +3,13 @@ import type { AgentKind, Provider } from '@cindy/model-providers';
/** Same secure-key / legacy-header alternatives as provider-route. Never exports a credential. */
export function hasCustomProviderCredential(
provider: Provider,
- readKey: (providerId: string, agent: AgentKind) => string | null,
+ readKey: (providerId: string, agent: AgentKind | 'image') => string | null,
): boolean {
+ // BYOK image-only providers have no chat agent, but their image credential
+ // still determines whether the provider can execute media requests.
+ if (provider.source === 'organization' && provider.imageModels?.length) {
+ if (readKey(provider.id, 'image')?.trim()) return true;
+ }
return provider.agents.some((agent) => {
const route = provider.routing[agent];
if (!route || route.disabled) return false;
diff --git a/apps/desktop/src/main/maker-host/provider-route.ts b/apps/desktop/src/main/maker-host/provider-route.ts
index 96fd33d48f..064b522fb0 100644
--- a/apps/desktop/src/main/maker-host/provider-route.ts
+++ b/apps/desktop/src/main/maker-host/provider-route.ts
@@ -29,8 +29,10 @@ import {
XAI_MODEL_PREFIX,
type AgentKind,
type Provider,
+ type ProviderSource,
type ProviderView,
type RoutingDescriptor,
+ isCustomRoutedProvider,
} from '@cindy/model-providers';
import type { RoutingDecision } from '@cindy/anthropic-compat-proxy';
@@ -625,7 +627,7 @@ export function getProviderRoutingDescriptor(
export interface ResolvedSessionRoute {
providerId: string;
- providerSource: 'builtin' | 'user';
+ providerSource: ProviderSource;
routing: RoutingDescriptor;
apiKey: string | null;
oauthToken: string | null;
@@ -721,14 +723,14 @@ export interface ResolvedProviderRouteDecision {
* 自定义 key、两种 OAuth 策略的读取器与容错)是同一份逻辑,分写会漂移。
*/
async function readProviderRouteCredentials(
- provider: { id: string; source: 'builtin' | 'user' },
+ provider: Pick<Provider, 'id' | 'source'>,
routing: RoutingDescriptor,
agent: AgentKind,
): Promise<{ apiKey: string | null; oauthToken: string | null }> {
const credentialProviderId =
- provider.source === 'user' ? storedCustomProviderId(provider.id) : provider.id;
+ isCustomRoutedProvider(provider) ? storedCustomProviderId(provider.id) : provider.id;
const apiKey =
- provider.source === 'user' ? customProviderKeyReader(credentialProviderId, agent) : null;
+ isCustomRoutedProvider(provider) ? customProviderKeyReader(credentialProviderId, agent) : null;
let oauthToken: string | null = null;
if (routing.authStrategy === 'oauth-token') {
oauthToken = oauthTokenReader(credentialProviderId);
@@ -791,10 +793,14 @@ export async function resolveFrozenProviderRouteDecision(
if (!id || isProviderRouteMutationInProgress(id)) return null;
if (getProviderRouteCredentialRevision(id) !== credentialRevision) return null;
const provider = getActiveCatalog().providers.find((candidate) => candidate.id === id);
- if (!provider || provider.source !== 'user' || !provider.agents.includes(agent)) return null;
+ if (!provider || !isCustomRoutedProvider(provider) || !provider.agents.includes(agent)) return null;
if (!routingServesWireModel(routing, wireModel)) return null;
const { apiKey, oauthToken } = await readProviderRouteCredentials(provider, routing, agent);
- const customHeaders = customProviderHeaderReader(storedCustomProviderId(provider.id), agent);
+ // Header overrides are user-owned configuration. Organization routes use only the trusted
+ // directory descriptor and managed credential, even if stale local data shares an id.
+ const customHeaders = provider.source === 'user'
+ ? customProviderHeaderReader(storedCustomProviderId(provider.id), agent)
+ : null;
// A provider-OAuth reader may await refresh. Recheck both guards after the credential read so a
// concurrent endpoint/key/token mutation can only yield the old coherent decision or fail closed.
if (
@@ -812,7 +818,7 @@ export async function resolveFrozenProviderRouteDecision(
if (getProviderRouteCredentialRevision(id) !== credentialRevision) return false;
return getActiveCatalog().providers.some(
(candidate) =>
- candidate.id === id && candidate.source === 'user' && candidate.agents.includes(agent),
+ candidate.id === id && isCustomRoutedProvider(candidate) && candidate.agents.includes(agent),
);
};
return {
@@ -843,9 +849,9 @@ export function resolveSessionRouteDecision(
if (!routingServesWireModel(routing, wireModel)) return null;
// 自定义供应商:resolve 时按 provider_key_<id>_<agent> 读出该 runtime 的 API key 注入鉴权头(不在 catalog)。
const credentialProviderId =
- provider?.source === 'user' ? storedCustomProviderId(providerId) : providerId;
+ isCustomRoutedProvider(provider) ? storedCustomProviderId(providerId) : providerId;
const apiKey =
- provider?.source === 'user' ? customProviderKeyReader(credentialProviderId, agent) : null;
+ isCustomRoutedProvider(provider) ? customProviderKeyReader(credentialProviderId, agent) : null;
const withRequestPath = (decision: RoutingDecision | null): RoutingDecision | null =>
decision && wireModel && routing.requestPath
? { ...decision, pathOverride: routing.requestPath }
@@ -1005,7 +1011,7 @@ export function resolveImplicitProviderOAuthRouteDecision(
const provider = uniqueProviderForModel(modelId, agent);
const routing = provider?.routing[agent];
if (!provider || !routing || routing.authStrategy !== 'provider-oauth-header') return null;
- const apiKey = provider.source === 'user' ? customProviderKeyReader(provider.id, agent) : null;
+ const apiKey = isCustomRoutedProvider(provider) ? customProviderKeyReader(provider.id, agent) : null;
const withRequestPath = (decision: RoutingDecision | null): RoutingDecision | null =>
decision && routing.requestPath ? { ...decision, pathOverride: routing.requestPath } : decision;
return Promise.resolve(providerOAuthTokenReader(provider.id, agent))
@@ -1040,7 +1046,7 @@ export function resolveProviderOAuthControlRouteDecision(
const provider = providers[0];
const routing = provider.routing[agent];
if (!routing) return null;
- const apiKey = provider.source === 'user' ? customProviderKeyReader(provider.id, agent) : null;
+ const apiKey = isCustomRoutedProvider(provider) ? customProviderKeyReader(provider.id, agent) : null;
return Promise.resolve(providerOAuthTokenReader(provider.id, agent))
.then((token) => buildRouteDecision(routing, gatewayKey, agent, apiKey, token))
.catch(() => buildRouteDecision(routing, gatewayKey, agent, apiKey, null));
@@ -1105,23 +1111,23 @@ export function rewriteImplicitModelIdForRoute(
}
/**
- * 该会话是否显式选了**自定义(user)供应商**。
+ * 该会话是否显式选了需要 Host 自行注入凭证的供应商(个人自定义或企业下发)。
* codex 路由用:env-key 注入态默认全量走网关、per-session 无意义(内置三家保持该旧行为),
- * 但自定义供应商必须按其 baseUrl + 用户 key 路由,故对 user 供应商放行 per-session 解析。
+ * 但这两类供应商必须按各自 baseUrl + key 路由,故放行 per-session 解析。
*/
export function isUserProviderSession(sessionId: string): boolean {
return getUserProviderIdForSession(sessionId) !== null;
}
/**
- * 该会话显式选定的**自定义(user)供应商 id**;非 user 供应商 / 未选 → null。
+ * 该会话显式选定的自定义路由供应商 id;其他供应商 / 未选 → null。
* 上游错误观察器(provider-upstream-error-observer)用它把 4xx/5xx 归属到具体自定义供应商。
*/
export function getUserProviderIdForSession(sessionId: string): string | null {
const providerId = getSessionProvider(sessionId);
if (!providerId) return null;
const provider = getActiveCatalog().providers.find((p) => p.id === providerId);
- return provider?.source === 'user' ? providerId : null;
+ return isCustomRoutedProvider(provider) ? providerId : null;
}
/** 该会话是否使用 host/proxy 注入供应商鉴权的路由策略(provider-oauth-header / oauth-token)。 */
diff --git a/apps/desktop/src/main/maker-host/provider-service.ts b/apps/desktop/src/main/maker-host/provider-service.ts
index dfd3c7e1d6..e4d9cd9565 100644
--- a/apps/desktop/src/main/maker-host/provider-service.ts
+++ b/apps/desktop/src/main/maker-host/provider-service.ts
@@ -24,6 +24,7 @@ import {
type ProviderModelDiscoveryFailure,
type ProviderView,
type Provider,
+ isCustomRoutedProvider,
} from '@cindy/model-providers';
const log = createLogger('provider-service');
@@ -167,7 +168,7 @@ export function createProviderService(deps: ProviderServiceDeps): ProviderServic
connected[p.id] = deps.codexAccountConnected?.(p.id) ?? false;
} else if (p.auth.method === 'oauth' && p.auth.oauth && !(p.id in connected)) {
connected[p.id] = deps.genericOAuthConnected?.(p.id) ?? false;
- } else if (p.source === 'user') {
+ } else if (isCustomRoutedProvider(p)) {
connected[p.id] = deps.customApiKeyConnected?.(p) ?? false;
}
// 内置 API-key 供应商(如 Gemini 图像来源):连接 = key 已存。与自定义供应商
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 43d8de7d6b..31aed4b9be 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -114,6 +114,7 @@ function mountDb(): void {
function makeDeps(over: Partial<ProviderHandlerDeps> = {}): ProviderHandlerDeps {
return {
listProviders: async () => [],
+ isOrganizationManagedProviderId: () => false,
getModelVisibilityOverrides: () => ({}),
refreshCatalog: vi.fn(async () => {}),
codexCustomProviderConfigSignature,
@@ -2430,6 +2431,95 @@ describe('provider:custom:* CRUD handlers', () => {
expect(await listCustomProviders()).toEqual([]);
});
+ it('reserves an active enterprise connection across every local mutation surface', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const managed = {
+ id: 'byok-reserved', name: 'Enterprise', source: 'organization' as const,
+ auth: { method: 'managed' as const }, access: { kind: 'managed' as const },
+ agents: [], models: {}, routing: {},
+ };
+ const deps = makeDeps({
+ listProviders: async () => [{ ...managed, connected: false } as ProviderView],
+ currentOwnerSession: () => ({ dataOwnerId: 'owner-a', generation: 1 }),
+ });
+ registerProviderHandlers(harness, deps);
+ const config = { ...validConfig, id: managed.id };
+ deps.isOrganizationManagedProviderId = (providerId) => providerId === managed.id;
+
+ try {
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, config),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, config.id),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DISCONNECT, config.id),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, config.id),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, config.id),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_PRESENTATION_SET, {
+ providerId: config.id,
+ action: 'rename',
+ name: 'Must not persist',
+ dataOwnerId: 'owner-a',
+ ownerGeneration: 1,
+ }),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ const priceTarget = {
+ providerId: config.id,
+ agent: 'codex' as const,
+ modelId: 'managed-model',
+ };
+ await expect(
+ harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_SET, priceTarget, {
+ currency: 'USD',
+ inputPerMtok: 1,
+ outputPerMtok: 2,
+ }),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ await expect(
+ harness.invoke(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_RESET, priceTarget),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ expect(await listCustomProviders()).toEqual([]);
+ expect(deps.refreshCatalog).not.toHaveBeenCalled();
+ expect(deps.oauthLogin).not.toHaveBeenCalled();
+ expect(deps.oauthLogout).not.toHaveBeenCalled();
+ expect(deps.writeModelPriceOverride).not.toHaveBeenCalled();
+ expect(deps.clearModelPriceOverride).not.toHaveBeenCalled();
+ } finally {
+ deps.isOrganizationManagedProviderId = () => false;
+ }
+ });
+
+ it('keeps a legacy personal byok-prefixed Provider editable and removable', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+ const legacy = { ...validConfig, id: 'byok-legacy-personal' };
+ await createCustomProvider(legacy);
+
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...legacy,
+ name: 'Updated legacy Provider',
+ })).resolves.toEqual({ ok: true });
+ expect((await getCustomProvider(legacy.id))?.name).toBe('Updated legacy Provider');
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, legacy.id),
+ ).resolves.toEqual({ ok: true });
+ expect(await getCustomProvider(legacy.id)).toBeNull();
+ });
+
it('reserves xai for new providers while preserving edits to an existing legacy row', async () => {
mountDb();
const harness = new IpcHarness();
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index a7e3cb72da..463a9730fc 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -18,6 +18,7 @@ import { setProviderPresentation, retainProviderPresentationAfterAuthChange } fr
import type { CodexContextWindowInfo } from '@cindy/maker-core';
import {
PI_MODEL_APIS,
+ isByokProviderId,
isLoopbackProviderUrl,
isProviderRequestPath,
runtimeCustomProviderId,
@@ -258,6 +259,8 @@ export interface ProviderHandlerDeps {
* 是本机主页面时才放行副作用(PR #548 review)。
*/
listProviders(opts?: { allowSideEffects?: boolean }): Promise<ProviderView[]>;
+ /** Synchronous catalog ownership check; injected to keep this IPC module free of Host cycles. */
+ isOrganizationManagedProviderId(providerId: string): boolean;
/**
* 「模型显示/隐藏」override 快照(renderer → main 镜像,生产 = getModelVisibilityMirrorSnapshot)。
* PROVIDER_LIST 附带回传,供 device-link 控制端(手机)按被控端用户开关过滤模型列表;
@@ -1364,6 +1367,9 @@ export function registerProviderHandlers(
if (!provider || provider.id === 'xd') {
throwIpcError('INVALID_PARAMS', 'Provider does not support presentation overrides');
}
+ if (provider.source === 'organization') {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');
+ }
if (value.action === 'rename' && typeof value.name === 'string' && value.name.trim() && value.name.length <= 128) {
if (provider.source === 'builtin') {
await setProviderPresentation(providerId, { name: value.name });
@@ -1664,6 +1670,9 @@ export function registerProviderHandlers(
if (target.providerId === 'xd') {
throwIpcError('INVALID_PARAMS', 'Cindy AI Gateway pricing is server-controlled');
}
+ if (deps.isOrganizationManagedProviderId(target.providerId)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise pricing is managed by your organization');
+ }
if (desired.currency === 'CNY' && deps.getLedgerCurrency() === 'USD') {
throwIpcError('INVALID_PARAMS', 'CNY price overrides cannot project into a USD ledger');
}
@@ -1696,6 +1705,9 @@ export function registerProviderHandlers(
registry.handle(MAKER_INVOKE.MODEL_PRICE_OVERRIDE_RESET, async (event, input: unknown) => {
assertTrustedProviderMutationSender(event);
const target = parsePriceTarget(input);
+ if (deps.isOrganizationManagedProviderId(target.providerId)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise pricing is managed by your organization');
+ }
const ownerAtIngress = captureProviderOwnerSession();
return withProviderConfigMutation(target.providerId, () =>
enqueuePriceMutation(async () => {
@@ -1871,6 +1883,9 @@ export function registerProviderHandlers(
const options = parseCustomProviderUpdateOptions(optionsInput);
if (!options) throwIpcError('INVALID_PARAMS', 'invalid custom provider create options');
const config = input as CustomProviderConfig;
+ if (isByokProviderId(config.id) || deps.isOrganizationManagedProviderId(config.id)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');
+ }
if (config.id === MANAGED_OLLAMA_PROVIDER_ID) {
throwIpcError(
'PERMISSION_DENIED',
@@ -1944,6 +1959,9 @@ export function registerProviderHandlers(
const options = parseCustomProviderUpdateOptions(optionsInput);
if (!options) throwIpcError('INVALID_PARAMS', 'invalid custom provider update options');
let config = input as CustomProviderConfig;
+ if (deps.isOrganizationManagedProviderId(config.id)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');
+ }
if (config.id === MANAGED_OLLAMA_PROVIDER_ID) {
throwIpcError(
'PERMISSION_DENIED',
@@ -2086,6 +2104,9 @@ export function registerProviderHandlers(
if (typeof providerId !== 'string' || providerId.length === 0) {
throwIpcError('INVALID_PARAMS', 'providerId required');
}
+ if (deps.isOrganizationManagedProviderId(providerId)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');
+ }
const runtimeProviderId = runtimeCustomProviderId(providerId);
const ownerAtIngress = captureProviderOwnerSession();
return withProviderConfigMutation(providerId, async (commitRouteMutation) => {
@@ -2311,6 +2332,9 @@ export function registerProviderHandlers(
async (event, providerId: unknown, rawOptions?: unknown) => {
assertTrustedProviderMutationSender(event);
const id = requireProviderId(providerId);
+ if (deps.isOrganizationManagedProviderId(id)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');
+ }
const { ownerId } = requireProviderOAuthLoginOptions(rawOptions);
const sender = providerOAuthRendererSender(event);
if (ownerId && !sender) {
@@ -2388,6 +2412,9 @@ export function registerProviderHandlers(
const options = parseCustomProviderUpdateOptions(optionsInput);
if (!options) throwIpcError('INVALID_PARAMS', 'Invalid provider change options');
const id = storedCustomProviderId(requireProviderId(providerId));
+ if (deps.isOrganizationManagedProviderId(id)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');
+ }
const owner = captureProviderOwnerSession();
return withProviderConfigMutation(id, async (commitRouteMutation) => {
assertProviderMutationOwner(owner);
@@ -2420,6 +2447,9 @@ export function registerProviderHandlers(
const options = parseCustomProviderUpdateOptions(optionsInput);
if (!options) throwIpcError('INVALID_PARAMS', 'Invalid provider change options');
const id = requireProviderId(providerId);
+ if (deps.isOrganizationManagedProviderId(id)) {
+ throwIpcError('PERMISSION_DENIED', 'Enterprise connections are managed by your organization');
+ }
const ownerAtIngress = captureProviderOwnerSession();
let generation: symbol | null = null;
try {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ab4fab2287..37968902ce 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -72,6 +72,7 @@ import {
findCatalogModel,
storedCustomProviderId,
isLocalOnlyProviderForAgent,
+ isOrganizationManagedProvider,
} from '@cindy/model-providers';
import { createId } from '@paralleldrive/cuid2';
import {
@@ -5610,6 +5611,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
registerProviderHandlers(createElectronIpcHandlerRegistry(), {
listProviders: (opts) => getDesktopProviderService().listProviders(opts),
+ isOrganizationManagedProviderId: (providerId) =>
+ getActiveCatalog().providers.some(
+ (provider) => provider.id === providerId && isOrganizationManagedProvider(provider),
+ ),
getModelVisibilityOverrides: async (providers, trusted) => {
if (!trusted) await waitForModelVisibilityMirror();
return getModelVisibilityMirrorSnapshot(providers, trusted);
diff --git a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
index c92fbdc861..f8e1a6acb2 100644
--- a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
@@ -252,7 +252,12 @@ export function recordSessionClaudeTurnUsage(
const { turnMoney, estimatedTurnMoney, perModel } = resolveClaudeTurnCostSinks(
deltas,
pricing,
- { providerId: sessionProviderForBilling, billingRoute, region: CURRENT_CINDY_REGION },
+ {
+ providerId: sessionProviderForBilling,
+ billingRoute,
+ region: CURRENT_CINDY_REGION,
+ accessKind: turnContext.accessKind,
+ },
claudeUsageSegments,
claudeUsageSegmentsComplete,
);
@@ -447,7 +452,7 @@ export function recordSessionClaudeTurnUsage(
// A cumulative SDK dollar value is authoritative only for an
// explicitly selected provider API. Remote/unknown routing cannot
// be attributed to this local account and must stay usage-only.
- if (route !== 'provider-api') {
+ if (route !== 'provider-api' || turnContext.accessKind === 'managed') {
await recordUsageOnly();
return;
}
diff --git a/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts b/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts
index f189fd49fc..0e4ac00a68 100644
--- a/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts
@@ -223,6 +223,7 @@ export function recordSessionPiTurnUsage(
providerId: sessionProvider,
billingRoute,
region: CURRENT_CINDY_REGION,
+ accessKind: turnContext.accessKind,
},
segments: pricingSegments,
}).money;
diff --git a/apps/desktop/src/main/model-access/__tests__/byokCache.test.ts b/apps/desktop/src/main/model-access/__tests__/byokCache.test.ts
new file mode 100644
index 0000000000..012a1ea1bf
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/byokCache.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createByokCache } from '../byokCache.js';
+import { createByokSync } from '../byokSync.js';
+const owner = { scope: 'generation-1', cacheScope: 'member-a:cn:org-a', organizationId: 'org-a' };
+const provider = {
+ id: 'byok-a',
+ name: 'Enterprise',
+ connectionRevision: 1,
+ models: [
+ {
+ id: 'byok/a/chat',
+ name: 'Chat',
+ agents: ['pi'] as const,
+ mode: 'chat',
+ currency: 'CNY',
+ contextWindow: 128000,
+ perAgent: { pi: { wireProtocol: 'openai-completions' } },
+ },
+ ],
+};
+const directory = {
+ schemaVersion: 1,
+ organizationId: 'org-a',
+ revision: '1',
+ providers: [provider],
+};
+const credentials = {
+ schemaVersion: 1,
+ organizationId: 'org-a',
+ credentials: [
+ {
+ providerId: 'byok-a',
+ connectionRevision: 1,
+ status: 'ready',
+ endpoint: 'https://gateway.example.invalid/v1',
+ apiKey: 'invalid-test-key',
+ },
+ ],
+};
+function fixture() {
+ const values = new Map<string, string>();
+ let now = 100000;
+ const io = {
+ read: (key: string) => values.get(key) ?? null,
+ write: vi.fn((key: string, value: string) => {
+ values.set(key, value);
+ return true;
+ }),
+ };
+ const cache = createByokCache(io, () => now);
+ const fetch = vi.fn().mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ const sync = createByokSync({ fetch, replace: vi.fn(), cache });
+ sync.setOwner(owner);
+ return {
+ values,
+ io,
+ cache,
+ sync,
+ advance: () => {
+ now += 86400001;
+ },
+ };
+}
+describe('encrypted BYOK snapshot contract', () => {
+ it('restores matching keys across process generations, but never across identities or regions', async () => {
+ const h = fixture();
+ await h.sync.sync();
+ expect(h.cache.load({ ...owner, scope: 'generation-2' })?.connections).toHaveLength(1);
+ expect(h.cache.load({ ...owner, cacheScope: 'member-b:cn:org-a' })).toBeNull();
+ expect(h.cache.load({ ...owner, cacheScope: 'member-a:global:org-a' })).toBeNull();
+ expect(h.cache.load({ ...owner, organizationId: 'org-b' })).toBeNull();
+ });
+ it('does not extend offline validity on restart', async () => {
+ const h = fixture();
+ await h.sync.sync();
+ const writes = h.io.write.mock.calls.length;
+ const runtime = createByokSync({
+ cache: h.cache,
+ replace: vi.fn(),
+ fetch: vi.fn().mockRejectedValue(new Error('offline')),
+ });
+ runtime.setOwner({ ...owner, scope: 'generation-2' });
+ expect(h.io.write).toHaveBeenCalledTimes(writes);
+ h.advance();
+ expect(h.cache.load(owner)).toBeNull();
+ });
+ it('ignores corrupt snapshots and removes cached routes after an authoritative empty directory', async () => {
+ const h = fixture();
+ await h.sync.sync();
+ const runtime = createByokSync({
+ cache: h.cache,
+ replace: vi.fn(),
+ fetch: vi.fn().mockResolvedValue({ ...directory, revision: '2', providers: [] }),
+ });
+ runtime.setOwner(owner);
+ await runtime.sync();
+ expect(h.cache.load(owner)?.catalog.providers).toEqual([]);
+ for (const key of h.values.keys()) h.values.set(key, '{bad');
+ expect(h.cache.load(owner)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/model-access/__tests__/byokCredentials.test.ts b/apps/desktop/src/main/model-access/__tests__/byokCredentials.test.ts
new file mode 100644
index 0000000000..d52e806588
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/byokCredentials.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ readByokCredential,
+ readByokInferenceBase,
+ isInstalledByokProvider,
+ setByokCredentialReader,
+ setByokEndpointReader,
+ setByokManagedProviderReader,
+} from '../byokCredentials.js';
+import { isExternalOrganizationByokUser } from '../organizationManaged.js';
+
+afterEach(() => {
+ setByokCredentialReader(() => null);
+ setByokEndpointReader(() => null);
+ setByokManagedProviderReader(() => false);
+});
+
+describe('BYOK live credential readers', () => {
+ it('enables managed BYOK only for external organization identities', () => {
+ expect(isExternalOrganizationByokUser(null)).toBe(false);
+ expect(
+ isExternalOrganizationByokUser({
+ membershipKind: 'personal',
+ orgId: null,
+ orgSlug: null,
+ orgName: null,
+ }),
+ ).toBe(false);
+ expect(
+ isExternalOrganizationByokUser({
+ membershipKind: 'org',
+ orgId: 'org-xd',
+ orgSlug: 'xd',
+ orgName: 'XD',
+ }),
+ ).toBe(false);
+ expect(
+ isExternalOrganizationByokUser({
+ membershipKind: 'org',
+ orgId: null,
+ orgSlug: 'acme',
+ orgName: 'Acme',
+ }),
+ ).toBe(false);
+ expect(
+ isExternalOrganizationByokUser({
+ membershipKind: 'org',
+ orgId: 'org-acme',
+ orgSlug: 'acme',
+ orgName: 'Acme',
+ }),
+ ).toBe(true);
+ });
+
+ it('does not require a chat engine to read the image key', () => {
+ setByokCredentialReader((id, agent) =>
+ id === 'byok-a' && agent === 'image' ? 'member-key' : null,
+ );
+ expect(readByokCredential('byok-a', 'image')).toBe('member-key');
+ expect(readByokCredential('byok-a', 'pi')).toBeNull();
+ });
+
+ it('does not turn a legacy personal prefix into a live managed connection', () => {
+ expect(isInstalledByokProvider('byok-legacy-personal')).toBe(false);
+ setByokManagedProviderReader((id) => id === 'byok-live');
+ expect(isInstalledByokProvider('byok-live')).toBe(true);
+ });
+
+ it.each([
+ ['https://gateway.example.invalid/v1', 'https://gateway.example.invalid'],
+ ['https://gateway.example.invalid/v1/', 'https://gateway.example.invalid'],
+ ['https://gateway.example.invalid', 'https://gateway.example.invalid'],
+ ['https://gateway.example.invalid/', 'https://gateway.example.invalid'],
+ ] as const)('normalizes %s to the OpenAI-images origin', (endpoint, origin) => {
+ setByokEndpointReader(() => endpoint);
+ expect(readByokInferenceBase('byok-a')).toBe(origin);
+ expect(readByokInferenceBase('byok-missing')).toBe(origin);
+ });
+
+ it('returns null after the installed connection disappears', () => {
+ setByokEndpointReader((id) => (id === 'byok-a' ? 'https://gateway.example.invalid/v1' : null));
+ expect(readByokInferenceBase('byok-a')).toBe('https://gateway.example.invalid');
+ expect(readByokInferenceBase('byok-b')).toBeNull();
+ setByokEndpointReader(() => null);
+ expect(readByokInferenceBase('byok-a')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/model-access/__tests__/byokIpc.test.ts b/apps/desktop/src/main/model-access/__tests__/byokIpc.test.ts
new file mode 100644
index 0000000000..40552fdd23
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/byokIpc.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { IpcMain, IpcMainInvokeEvent } from 'electron';
+import { registerByokIpc } from '../byokIpc.js';
+function harness(trusted = true) {
+ const handlers = new Map<string, Parameters<IpcMain['handle']>[1]>();
+ const control = {
+ getStatus: vi.fn(() => ({
+ state: 'ready' as const,
+ providers: [{ providerId: 'byok-company', state: 'ready' as const }],
+ })),
+ sync: vi.fn(async () => undefined),
+ };
+ const assertSender = vi.fn(() => {
+ if (!trusted) throw new Error('untrusted renderer');
+ });
+ registerByokIpc(
+ {
+ handle: (name, handler) => {
+ handlers.set(name, handler);
+ },
+ } as Pick<IpcMain, 'handle'>,
+ control,
+ assertSender,
+ );
+ const call = (name: string, value?: unknown) =>
+ handlers.get(`model-access:byok-${name}`)!({} as IpcMainInvokeEvent, value);
+ return { call, control, assertSender };
+}
+describe('enterprise BYOK IPC boundary', () => {
+ it('rejects untrusted status reads and mutations before calling the runtime', async () => {
+ const { call, control } = harness(false);
+ expect(() => call('status')).toThrow('untrusted');
+ await expect(call('retry')).rejects.toThrow('untrusted');
+ expect(control.getStatus).not.toHaveBeenCalled();
+ expect(control.sync).not.toHaveBeenCalled();
+ });
+ it('refresh returns only the runtime status', async () => {
+ const { call, control } = harness();
+ expect(await call('retry')).toEqual(control.getStatus());
+ expect(control.sync).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/model-access/__tests__/byokPricing.test.ts b/apps/desktop/src/main/model-access/__tests__/byokPricing.test.ts
new file mode 100644
index 0000000000..af3f99577a
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/byokPricing.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+import type { ByokModel, ByokProvider } from '@cindy/model-providers';
+import { buildByokPricing } from '../byokPricing.js';
+import { gatewayModelPriceQuote, modelPricingKey } from '../../../shared/modelPriceQuote.js';
+const model: ByokModel = {
+ id: 'byok/a/chat',
+ agents: ['pi', 'codex'],
+ currency: 'CNY',
+ perAgent: {
+ pi: { wireProtocol: 'openai-completions' },
+ codex: { wireProtocol: 'openai-responses' },
+ },
+ inputCostPerToken: 0.000002,
+ outputCostPerToken: 0.000006,
+ cacheReadInputTokenCost: 0,
+ cacheCreationInputTokenCost: 0.000001,
+ costDiscount: 0.5,
+};
+const provider = (entry: ByokModel, id = 'byok-a'): ByokProvider => ({
+ id,
+ name: 'Enterprise',
+ connectionRevision: 1,
+ models: [entry],
+});
+describe('enterprise reference price projection', () => {
+ it('keeps provider and engine identity, currency and cache rates without the retail discount', () => {
+ const catalog = buildByokPricing([
+ provider(model),
+ provider({ ...model, currency: 'USD' }, 'byok-b'),
+ ]);
+ const quote = catalog['byok-a'][modelPricingKey(model.id, 'pi')];
+ expect(quote).toMatchObject({
+ providerId: 'byok-a',
+ currency: 'CNY',
+ source: 'provider-reference',
+ approximate: true,
+ inputPerMtok: 2,
+ outputPerMtok: 6,
+ cacheReadPerMtok: 0,
+ cacheCreatePerMtok: 1,
+ });
+ expect(quote).not.toHaveProperty('costDiscount');
+ expect(catalog['byok-a'][modelPricingKey(model.id, 'codex')]).toEqual(quote);
+ expect(catalog['byok-b'][modelPricingKey(model.id, 'pi')].currency).toBe('USD');
+ });
+ it('preserves explicit free models without changing the legacy gateway zero-price behavior', () => {
+ const free = {
+ ...model,
+ inputCostPerToken: 0,
+ outputCostPerToken: 0,
+ cacheCreationInputTokenCost: 0,
+ };
+ expect(
+ buildByokPricing([provider(free)])['byok-a'][modelPricingKey(model.id, 'pi')].inputPerMtok,
+ ).toBe(0);
+ expect(gatewayModelPriceQuote(free, 'CNY')).toBeUndefined();
+ });
+ it('does not infer currency or replace unknown prices with zero', () => {
+ expect(buildByokPricing([provider({ ...model, currency: undefined })])['byok-a']).toEqual({});
+ expect(
+ buildByokPricing([provider({ ...model, outputCostPerToken: undefined })])['byok-a'],
+ ).toEqual({});
+ });
+});
diff --git a/apps/desktop/src/main/model-access/__tests__/byokProvider.test.ts b/apps/desktop/src/main/model-access/__tests__/byokProvider.test.ts
new file mode 100644
index 0000000000..d4b652ffd7
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/byokProvider.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from 'vitest';
+import { buildByokProvider, byokNativeConfigs, mergeByokNativeConfigs } from '../byokProvider.js';
+
+const credential = {
+ providerId: 'byok-a',
+ connectionRevision: 1,
+ status: 'ready' as const,
+ endpoint: 'https://gateway.example.invalid/v1',
+ apiKey: 'invalid-test-key',
+};
+
+const chatModel = {
+ id: 'byok-a/chat',
+ name: 'Chat',
+ agents: ['pi'] as Array<'pi'>,
+ mode: 'chat' as const,
+ currency: 'CNY' as const,
+ icon: 'sparkles',
+ contextWindow: 128000,
+ nativeApi: 'openai-completions' as const,
+ perAgent: { pi: { wireProtocol: 'openai-completions' as const } },
+};
+
+const imageModel = {
+ id: 'byok-a/gpt-image-2',
+ name: 'GPT Image 2',
+ agents: [] as Array<'pi'>,
+ mode: 'image_generation' as const,
+ currency: 'CNY' as const,
+ perAgent: {},
+ nativeApi: 'openai-images' as const,
+ modalities: { input: ['text', 'image'], output: ['image'] },
+};
+
+describe('buildByokProvider model types', () => {
+ it('projects image-generation models into imageModels instead of chat engines', () => {
+ const result = buildByokProvider({
+ provider: {
+ id: 'byok-a',
+ name: 'Enterprise',
+ connectionRevision: 1,
+ models: [chatModel, imageModel],
+ },
+ credential,
+ });
+ expect(result.source).toBe('organization');
+ expect(result.models.pi?.map((model) => model.id)).toEqual(['byok-a/chat']);
+ expect(result.models.pi?.[0]?.nativeApi).toBe('openai-completions');
+ expect(result.models.pi?.[0]?.icon).toBe('sparkles');
+ expect(result.imageModels).toEqual([
+ expect.objectContaining({
+ id: 'byok-a/gpt-image-2',
+ name: 'GPT Image 2',
+ mode: 'image_generation',
+ nativeApi: 'openai-images',
+ }),
+ ]);
+ expect(result.imageDefaults).toEqual({ standard: 'byok-a/gpt-image-2' });
+ expect(result.agents).toEqual(['pi']);
+ expect(byokNativeConfigs([result])[0]?.runtimes.pi?.models.map((model) => model.id)).toEqual([
+ 'byok-a/chat',
+ ]);
+ });
+
+ it('can project an image-only enterprise Provider without chat engines', () => {
+ const result = buildByokProvider({
+ provider: { id: 'byok-a', name: 'Enterprise', connectionRevision: 1, models: [imageModel] },
+ credential,
+ });
+ expect(result.agents).toEqual([]);
+ expect(result.models).toEqual({});
+ expect(result.imageModels?.map((model) => model.id)).toEqual(['byok-a/gpt-image-2']);
+ expect(byokNativeConfigs([result])).toEqual([]);
+ });
+
+ it('gives a managed Pi config precedence over a legacy personal id collision', () => {
+ const managed = buildByokProvider({
+ provider: {
+ id: 'byok-a',
+ name: 'Enterprise',
+ connectionRevision: 1,
+ models: [chatModel],
+ },
+ credential,
+ });
+ const configs = mergeByokNativeConfigs(
+ [
+ {
+ id: 'byok-a',
+ name: 'Legacy personal',
+ runtimes: { pi: { baseUrl: 'https://personal.example.invalid/v1', models: [] } },
+ },
+ {
+ id: 'personal-other',
+ name: 'Personal other',
+ runtimes: { pi: { baseUrl: 'https://other.example.invalid/v1', models: [] } },
+ },
+ ],
+ [managed],
+ );
+ expect(configs.map((provider) => provider.id)).toEqual(['personal-other', 'byok-a']);
+ expect(configs[1]?.runtimes.pi?.baseUrl).toBe('https://gateway.example.invalid');
+ expect(configs[1]?.runtimes.pi?.models[0]?.route?.baseUrl).toBe(
+ 'https://gateway.example.invalid/v1',
+ );
+ });
+
+ it('does not fall back to a personal Pi config while the managed credential is pending', () => {
+ const configs = mergeByokNativeConfigs(
+ [
+ {
+ id: 'byok-a',
+ name: 'Legacy personal',
+ auth: { method: 'none' },
+ runtimes: { pi: { baseUrl: 'http://127.0.0.1:11434/v1', models: [] } },
+ },
+ ],
+ [
+ {
+ id: 'byok-a',
+ name: 'Enterprise pending',
+ source: 'organization',
+ auth: { method: 'managed' },
+ access: { kind: 'managed' },
+ agents: [],
+ models: {},
+ routing: {},
+ },
+ ],
+ );
+
+ expect(configs).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/model-access/__tests__/byokRuntime.test.ts b/apps/desktop/src/main/model-access/__tests__/byokRuntime.test.ts
new file mode 100644
index 0000000000..7483567b76
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/byokRuntime.test.ts
@@ -0,0 +1,474 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ByokProvidersResponse } from '@cindy/model-providers';
+const state = vi.hoisted(() => ({
+ reader: null as null | ((id: string, agent: string) => string | null),
+ endpointReader: null as null | ((id: string) => string | null),
+ managedProviderReader: null as null | ((id: string) => boolean),
+ publish: vi.fn(),
+ fetch: vi.fn(),
+ gate: vi.fn(),
+ debug: vi.fn(),
+}));
+vi.mock('../../maker-host/active-catalog.js', () => ({ setManagedProviders: state.publish }));
+vi.mock('../../maker-host/provider-route.js', () => ({
+ beginProviderRouteMutation: state.gate,
+}));
+vi.mock('../byokCredentials.js', () => ({
+ setByokCredentialReader: (reader: NonNullable<typeof state.reader>) => {
+ state.reader = reader;
+ },
+ setByokEndpointReader: (reader: NonNullable<typeof state.endpointReader>) => {
+ state.endpointReader = reader;
+ },
+ setByokManagedProviderReader: (reader: NonNullable<typeof state.managedProviderReader>) => {
+ state.managedProviderReader = reader;
+ },
+}));
+vi.mock('../../serverApiClient.js', () => ({ serverApiFetch: state.fetch }));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ debug: state.debug, warn: vi.fn() }) }));
+vi.mock('../../clientEndpointsService.js', () => ({
+ getClientEndpoint: () => 'https://api.example.invalid',
+}));
+import { createByokRuntime } from '../byokRuntime.js';
+import { getByokPricing, setByokPricing } from '../byokPricing.js';
+const provider = {
+ id: 'byok-a',
+ name: 'Enterprise',
+ connectionRevision: 1,
+ models: [
+ {
+ id: 'byok/a/chat',
+ name: 'Chat',
+ agents: ['pi'],
+ mode: 'chat',
+ currency: 'CNY',
+ contextWindow: 128000,
+ efforts: ['low', 'high'],
+ defaultEffort: 'low',
+ perAgent: { pi: { wireProtocol: 'openai-completions', defaultEffort: 'high' } },
+ },
+ ],
+};
+const directory = {
+ schemaVersion: 1,
+ organizationId: 'org-a',
+ revision: '1',
+ providers: [provider],
+};
+const credentials = {
+ schemaVersion: 1,
+ organizationId: 'org-a',
+ credentials: [
+ {
+ providerId: 'byok-a',
+ connectionRevision: 1,
+ status: 'ready',
+ endpoint: 'https://gateway.example.invalid/v1',
+ apiKey: 'invalid-test-key',
+ },
+ ],
+};
+beforeEach(() => {
+ vi.resetAllMocks();
+ setByokPricing({});
+ state.gate.mockImplementation(() => Object.assign(vi.fn(), { commit: vi.fn() }));
+});
+describe('BYOK Main runtime', () => {
+ it('labels both sync requests and logs success without credentials', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ for (const [index, endpoint] of ['providers', 'credentials'].entries()) {
+ const path = `/api/model-access/byok/${endpoint}`;
+ expect(state.fetch).toHaveBeenNthCalledWith(index + 1, `${path}?schemaVersion=1`, expect.objectContaining({
+ logLabel: path,
+ redactErrorDetails: true,
+ allowedRedactedErrorCodes: expect.arrayContaining(['ORG_AI_GATEWAY_ERROR', 'BYOK_UNAVAILABLE']),
+ }));
+ expect(state.debug).toHaveBeenCalledWith('byok.sync.request_succeeded', `path=${path}`, expect.stringMatching(/^elapsedMs=\d+$/));
+ }
+ expect(runtime.getStatus().state).toBe('ready');
+ const logged = JSON.stringify(state.debug.mock.calls);
+ expect(logged).not.toContain('invalid-test-key');
+ expect(logged).not.toContain('org-a');
+ expect(logged).not.toContain('gateway.example.invalid');
+ });
+ it.each([
+ 'https://gateway.example.invalid',
+ 'https://gateway.example.invalid/v1',
+ 'https://gateway.example.invalid/v1/',
+ ])('normalizes the three SDK paths from %s', async (endpoint) => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ const next = structuredClone(directory);
+ Object.assign(next.providers[0].models[0], {
+ nativeApi: 'openai-completions',
+ agents: ['pi', 'codex', 'claude-code'],
+ perAgent: {
+ pi: { wireProtocol: 'openai-completions' },
+ codex: { wireProtocol: 'openai-responses' },
+ 'claude-code': { wireProtocol: 'anthropic-messages' },
+ },
+ });
+ const connection = structuredClone(credentials);
+ connection.credentials[0].endpoint = endpoint;
+ state.fetch.mockResolvedValueOnce(next).mockResolvedValueOnce(connection);
+ await runtime.sync();
+ const projected = state.publish.mock.lastCall?.[0][0];
+ expect(projected.routing['claude-code'].upstream).toBe('https://gateway.example.invalid');
+ expect(projected.routing.codex.upstream).toBe('https://gateway.example.invalid/v1');
+ expect(projected.models.pi[0].nativeApi).toBe('openai-completions');
+ });
+ it('only offers Pi reasoning levels which its runtime can execute', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ const next = structuredClone(directory);
+ Object.assign(next.providers[0].models[0], {
+ efforts: ['high', 'ultra'],
+ defaultEffort: 'ultra',
+ });
+ Object.assign(next.providers[0].models[0].perAgent.pi, { defaultEffort: 'ultra' });
+ state.fetch.mockResolvedValueOnce(next).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(state.publish.mock.lastCall?.[0][0].models.pi[0]).toMatchObject({
+ efforts: ['high'],
+ defaultEffort: null,
+ });
+ });
+ it('publishes no secrets, reuses the route shape and clears keys on owner change', async () => {
+ const notify = vi.fn();
+ const runtime = createByokRuntime(notify);
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(state.reader?.('byok-a', 'pi')).toBe('invalid-test-key');
+ expect(state.reader?.('byok-other', 'pi')).toBeNull();
+ const catalog = state.publish.mock.lastCall?.[0];
+ expect(JSON.stringify(catalog)).not.toContain('invalid-test-key');
+ expect(catalog[0]).toMatchObject({
+ source: 'organization',
+ auth: { method: 'managed' },
+ models: {
+ pi: [
+ {
+ id: 'byok/a/chat',
+ defaultEffort: 'high',
+ contextWindow: 128000,
+ piApi: 'openai-completions',
+ },
+ ],
+ },
+ });
+ runtime.setOwner(null);
+ expect(state.reader?.('byok-a', 'pi')).toBeNull();
+ expect(state.managedProviderReader?.('byok-a')).toBe(false);
+ expect(state.publish.mock.lastCall?.[0]).toEqual([]);
+ expect(getByokPricing()).toEqual({});
+ expect(notify).toHaveBeenCalledTimes(3);
+ });
+ it('does not advance credentials when publishing the matching catalog fails', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ state.publish.mockImplementationOnce(() => {
+ throw new Error('publish failed');
+ });
+ await runtime.sync();
+ expect(state.reader?.('byok-a', 'pi')).toBeNull();
+ expect(runtime.getStatus().state).toBe('failed');
+ expect(getByokPricing()).toEqual({ 'byok-a': {} });
+ const gate = state.gate.mock.results[0]?.value;
+ expect(gate).toHaveBeenCalled();
+ expect(gate.commit).toHaveBeenCalled();
+ });
+ it('keeps a pending Provider visible without usable routes or credentials', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce({
+ ...credentials,
+ credentials: [{ providerId: 'byok-a', connectionRevision: 1, status: 'pending' }],
+ });
+ await runtime.sync();
+ expect(state.publish.mock.lastCall?.[0]).toEqual([
+ expect.objectContaining({
+ id: 'byok-a',
+ name: 'Enterprise',
+ agents: [],
+ models: {},
+ routing: {},
+ source: 'organization',
+ }),
+ ]);
+ expect(state.reader?.('byok-a', 'pi')).toBeNull();
+ expect(state.managedProviderReader?.('byok-a')).toBe(true);
+ expect(runtime.getStatus().providers).toEqual([{ providerId: 'byok-a', state: 'pending' }]);
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(state.publish.mock.lastCall?.[0]).toHaveLength(1);
+ expect(state.publish.mock.lastCall?.[0][0].agents).toContain('pi');
+ expect(state.reader?.('byok-a', 'pi')).toBe('invalid-test-key');
+ });
+
+ it('does not restore the old enterprise key if logout catalog notification fails', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ state.publish.mockImplementationOnce(() => {
+ throw new Error('renderer unavailable');
+ });
+ expect(() => runtime.setOwner(null)).not.toThrow();
+ expect(state.reader?.('byok-a', 'pi')).toBeNull();
+ expect(getByokPricing()).toEqual({});
+ expect(runtime.getStatus()).toEqual({ state: 'idle', providers: [] });
+ expect(state.gate.mock.results.at(-1)?.value.commit).toHaveBeenCalled();
+ });
+
+ it('never rolls a revoked key back after a catalog notification failure', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce({
+ ...credentials,
+ credentials: [
+ { providerId: 'byok-a', connectionRevision: 1, status: 'error', code: 'REVOKED' },
+ ],
+ });
+ state.publish.mockImplementationOnce(() => {
+ throw new Error('renderer unavailable');
+ });
+ await runtime.sync();
+ expect(state.reader?.('byok-a', 'pi')).toBeNull();
+ expect(runtime.getStatus().state).toBe('failed');
+ expect(runtime.getStatus().providers[0].state).toBe('unavailable');
+ });
+
+ it('exposes the member key and endpoint to Art for image-only enterprise providers', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ const next = {
+ schemaVersion: 1,
+ organizationId: 'org-a',
+ revision: '1',
+ providers: [
+ {
+ id: 'byok-a',
+ name: 'Enterprise',
+ connectionRevision: 1,
+ models: [
+ {
+ nativeApi: 'openai-images',
+ id: 'byok-a/gpt-image-2',
+ name: 'GPT Image 2',
+ currency: 'CNY',
+ mode: 'image_generation',
+ agents: [],
+ perAgent: {},
+ modalities: { input: ['text', 'image'], output: ['image'] },
+ },
+ ],
+ },
+ ],
+ };
+ state.fetch.mockResolvedValueOnce(next).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(state.reader?.('byok-a', 'image')).toBe('invalid-test-key');
+ expect(state.reader?.('byok-a', 'pi')).toBeNull();
+ expect(state.endpointReader?.('byok-a')).toBe('https://gateway.example.invalid/v1');
+ expect(state.publish.mock.lastCall?.[0][0]).toMatchObject({
+ agents: [],
+ imageModels: [expect.objectContaining({ id: 'byok-a/gpt-image-2' })],
+ });
+ runtime.setOwner(null);
+ expect(state.reader?.('byok-a', 'image')).toBeNull();
+ expect(state.endpointReader?.('byok-a')).toBeNull();
+ });
+
+ it('keeps the shared member key available to both chat engines and Art', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ const next = {
+ ...directory,
+ providers: [
+ {
+ ...directory.providers[0],
+ models: [
+ directory.providers[0].models[0],
+ {
+ nativeApi: 'openai-images',
+ id: 'byok-a/gpt-image-2',
+ name: 'GPT Image 2',
+ currency: 'CNY',
+ mode: 'image_generation',
+ agents: [],
+ perAgent: {},
+ modalities: { input: ['text', 'image'], output: ['image'] },
+ },
+ ],
+ },
+ ],
+ };
+ state.fetch.mockResolvedValueOnce(next).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(state.reader?.('byok-a', 'pi')).toBe('invalid-test-key');
+ expect(state.reader?.('byok-a', 'image')).toBe('invalid-test-key');
+ expect(state.reader?.('byok-a', 'codex')).toBeNull();
+ });
+
+ it('does not advertise an image key for chat-only enterprise providers', async () => {
+ const runtime = createByokRuntime();
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ state.fetch.mockResolvedValueOnce(directory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(state.reader?.('byok-a', 'pi')).toBe('invalid-test-key');
+ expect(state.reader?.('byok-a', 'image')).toBeNull();
+ expect(state.endpointReader?.('byok-a')).toBe('https://gateway.example.invalid/v1');
+ });
+
+ it.each(['add-pi', 'pi-protocol', 'remove-pi', 'add-claude', 'add-image'] as const)(
+ 'publishes %s changes under the lock without expiring the Codex snapshot', async (change) => {
+ const reloadCodex = vi.fn();
+ const runtime = createByokRuntime(undefined, undefined, reloadCodex);
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ const initial: ByokProvidersResponse = {
+ schemaVersion: 1, organizationId: 'org-a', revision: '1',
+ providers: [{
+ id: 'byok-a', name: 'Enterprise', connectionRevision: 1,
+ imageBinding: {
+ enabled: true, modelId: 'gpt-image-2', wireModel: 'gpt-image-2',
+ litellmModel: 'byok-a/gpt-image-2', supportsEdit: true,
+ },
+ models: [{
+ id: 'byok-a/chat', name: 'Chat', contextWindow: 128000,
+ agents: ['codex', 'pi'], perAgent: {
+ codex: { wireProtocol: 'openai-responses' },
+ pi: { wireProtocol: 'openai-completions' },
+ },
+ }],
+ }],
+ };
+ state.fetch.mockResolvedValueOnce(initial).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(reloadCodex).toHaveBeenCalledOnce();
+ state.gate.mockClear();
+ reloadCodex.mockClear();
+
+ const next = structuredClone(initial);
+ next.revision = '2';
+ const model = next.providers[0].models[0];
+ if (change === 'add-pi') {
+ next.providers[0].models.push({
+ id: 'byok-a/pi-only', name: 'Pi', contextWindow: 128000,
+ agents: ['pi'], perAgent: { pi: { wireProtocol: 'openai-completions' } },
+ });
+ } else if (change === 'pi-protocol') {
+ model.perAgent.pi!.wireProtocol = 'anthropic-messages';
+ } else if (change === 'remove-pi') {
+ model.agents = ['codex'];
+ delete model.perAgent.pi;
+ } else if (change === 'add-claude') {
+ model.agents!.push('claude-code');
+ model.perAgent['claude-code'] = { wireProtocol: 'anthropic-messages' };
+ } else {
+ next.providers[0].models.push({
+ id: 'byok-a/image', name: 'Image', mode: 'image_generation', agents: [], perAgent: {},
+ });
+ }
+ state.fetch.mockResolvedValueOnce(next).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(runtime.getStatus().state).toBe('ready');
+ expect(state.gate).toHaveBeenCalledOnce();
+ const lock = state.gate.mock.results[0].value;
+ expect(lock).toHaveBeenCalledOnce();
+ expect(lock.commit).not.toHaveBeenCalled();
+ expect(reloadCodex).not.toHaveBeenCalled();
+ const published = state.publish.mock.lastCall![0][0];
+ if (change === 'add-pi') expect(published.models.pi).toHaveLength(2);
+ if (change === 'pi-protocol') expect(published.models.pi[0].piApi).toBe('anthropic-messages');
+ if (change === 'remove-pi') expect(state.reader?.('byok-a', 'pi')).toBeNull();
+ if (change === 'add-claude') expect(published.models['claude-code']).toHaveLength(1);
+ if (change === 'add-image') expect(published.imageModels).toHaveLength(1);
+
+ // The same unchanged Codex snapshot must still expire when the shared key rotates.
+ state.gate.mockClear();
+ const rotated = structuredClone(credentials);
+ rotated.credentials[0].apiKey = 'invalid-rotated-test-key';
+ state.fetch.mockResolvedValueOnce(next).mockResolvedValueOnce(rotated);
+ await runtime.sync();
+ expect(state.gate.mock.results[0].value.commit).toHaveBeenCalledOnce();
+ expect(reloadCodex).toHaveBeenCalledOnce();
+ },
+ );
+
+ it('reloads Codex only when an applied enterprise image route or key changes', async () => {
+ const reloadCodex = vi.fn();
+ const runtime = createByokRuntime(undefined, undefined, reloadCodex);
+ runtime.setOwner({ scope: 'a:cn:1', organizationId: 'org-a' });
+ const codexDirectory = structuredClone(directory);
+ Object.assign(codexDirectory.providers[0].models[0], {
+ agents: ['codex'],
+ perAgent: { codex: { wireProtocol: 'openai-responses' } },
+ });
+ state.fetch.mockResolvedValueOnce(codexDirectory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(reloadCodex).not.toHaveBeenCalled();
+
+ const imageDirectory = structuredClone(codexDirectory);
+ imageDirectory.revision = '2';
+ Object.assign(imageDirectory.providers[0], {
+ imageBinding: {
+ enabled: true,
+ modelId: 'gpt-image-2',
+ wireModel: 'gpt-image-2',
+ litellmModel: 'byok-a/gpt-image-2',
+ supportsEdit: true,
+ },
+ });
+ state.fetch.mockResolvedValueOnce(imageDirectory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(reloadCodex).toHaveBeenCalledOnce();
+
+ state.fetch.mockResolvedValueOnce(imageDirectory).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(reloadCodex).toHaveBeenCalledOnce();
+
+ const metadataOnly = structuredClone(imageDirectory);
+ metadataOnly.revision = '3';
+ metadataOnly.providers[0].name = 'Renamed enterprise connection';
+ Object.assign(metadataOnly.providers[0].models[0], { inputCostPerToken: 0.123 });
+ const gatesBeforeMetadata = state.gate.mock.calls.length;
+ state.fetch.mockResolvedValueOnce(metadataOnly).mockResolvedValueOnce(credentials);
+ await runtime.sync();
+ expect(reloadCodex).toHaveBeenCalledOnce();
+ expect(state.gate).toHaveBeenCalledTimes(gatesBeforeMetadata);
+
+ const rotated = structuredClone(credentials);
+ rotated.credentials[0].apiKey = 'rotated-test-key';
+ state.fetch.mockResolvedValueOnce(metadataOnly).mockResolvedValueOnce(rotated);
+ await runtime.sync();
+ expect(reloadCodex).toHaveBeenCalledTimes(2);
+
+ const moved = structuredClone(rotated);
+ moved.credentials[0].endpoint = 'https://replacement.example.invalid/v1';
+ state.fetch.mockResolvedValueOnce(metadataOnly).mockResolvedValueOnce(moved);
+ await runtime.sync();
+ expect(state.gate.mock.results.at(-1)?.value.commit).toHaveBeenCalledOnce();
+ expect(reloadCodex).toHaveBeenCalledTimes(3);
+
+ const codexModelAdded = structuredClone(metadataOnly);
+ codexModelAdded.revision = '4';
+ codexModelAdded.providers[0].models.push({
+ ...codexModelAdded.providers[0].models[0], id: 'byok-a/another-codex-model',
+ });
+ state.fetch.mockResolvedValueOnce(codexModelAdded).mockResolvedValueOnce(moved);
+ await runtime.sync();
+ expect(state.gate.mock.results.at(-1)?.value.commit).toHaveBeenCalledOnce();
+ expect(reloadCodex).toHaveBeenCalledTimes(4);
+
+ runtime.setOwner(null);
+ expect(state.gate.mock.results.at(-1)?.value.commit).toHaveBeenCalledOnce();
+ expect(reloadCodex).toHaveBeenCalledTimes(5);
+ });
+});
diff --git a/apps/desktop/src/main/model-access/__tests__/byokSync.test.ts b/apps/desktop/src/main/model-access/__tests__/byokSync.test.ts
new file mode 100644
index 0000000000..4ad640cb2a
--- /dev/null
+++ b/apps/desktop/src/main/model-access/__tests__/byokSync.test.ts
@@ -0,0 +1,306 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ createByokSync,
+ PENDING_RETRY_DELAY_MS,
+ PENDING_RETRY_LIMIT,
+ type ByokConnection,
+} from '../byokSync.js';
+
+function provider(id = 'byok-a', connectionRevision = 1) {
+ return {
+ id,
+ name: id,
+ connectionRevision,
+ models: [
+ {
+ id: 'byok/a/chat',
+ name: 'Chat',
+ mode: 'chat',
+ agents: ['pi'],
+ currency: 'CNY',
+ contextWindow: 128000,
+ perAgent: { pi: { wireProtocol: 'openai-completions' } },
+ },
+ ],
+ };
+}
+function directory(providers = [provider()], revision = '1') {
+ return { schemaVersion: 1, organizationId: 'org-a', revision, providers };
+}
+function credentials(ids = ['byok-a'], connectionRevision = 1) {
+ return {
+ schemaVersion: 1,
+ organizationId: 'org-a',
+ credentials: ids.map((providerId) => ({
+ providerId,
+ connectionRevision,
+ status: 'ready',
+ apiKey: 'invalid-test-key-' + providerId,
+ endpoint: 'https://gateway.example.invalid/v1',
+ })),
+ };
+}
+function setup() {
+ let active: readonly ByokConnection[] = [];
+ const fetch = vi.fn();
+ const replace = vi.fn((_owner, connections) => {
+ active = connections;
+ });
+ const sync = createByokSync({ fetch, replace });
+ sync.setOwner({ scope: 'membership-a:cn:1', organizationId: 'org-a' });
+ return { sync, fetch, replace, active: () => active };
+}
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
+describe('enterprise BYOK sync', () => {
+ it('fetches directory then batch credentials once and never exposes keys in status', async () => {
+ const h = setup();
+ h.fetch
+ .mockResolvedValueOnce(directory([provider(), provider('byok-b')]))
+ .mockResolvedValueOnce(credentials(['byok-a', 'byok-b']));
+ const first = h.sync.sync();
+ expect(h.sync.sync()).toBe(first);
+ await first;
+ expect(h.fetch).toHaveBeenCalledTimes(2);
+ expect(h.active()).toHaveLength(2);
+ expect(JSON.stringify(h.sync.getStatus())).not.toContain('invalid-test-key');
+ expect(h.fetch.mock.calls.every(([, options]) => options.cache === 'no-store')).toBe(true);
+ });
+
+ it('retains valid routes on a network failure but removes them on a successful empty directory', async () => {
+ const h = setup();
+ h.fetch.mockResolvedValueOnce(directory()).mockResolvedValueOnce(credentials());
+ await h.sync.sync();
+ h.fetch.mockRejectedValueOnce(new Error('offline'));
+ await h.sync.sync();
+ expect(h.active()).toHaveLength(1);
+ expect(h.sync.getStatus().state).toBe('failed');
+ h.fetch.mockResolvedValueOnce(directory([], '2'));
+ await h.sync.sync();
+ expect(h.active()).toEqual([]);
+ expect(h.sync.getStatus().state).toBe('ready');
+ expect(h.fetch).toHaveBeenCalledTimes(4);
+ });
+
+ it('never combines a new connection revision with an old key', async () => {
+ const h = setup();
+ h.fetch.mockResolvedValueOnce(directory()).mockResolvedValueOnce(credentials());
+ await h.sync.sync();
+ h.fetch
+ .mockResolvedValueOnce(directory([provider('byok-a', 2)], '2'))
+ .mockResolvedValueOnce(credentials());
+ await h.sync.sync();
+ expect(h.active()).toEqual([]);
+ });
+
+ it('persists only the current directory revision during a refresh', async () => {
+ const cache = { load: vi.fn(() => null), save: vi.fn() };
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(directory())
+ .mockResolvedValueOnce(credentials())
+ .mockResolvedValueOnce(directory([provider()], '2'))
+ .mockResolvedValueOnce(credentials());
+ const sync = createByokSync({ fetch, replace: vi.fn(), cache });
+ sync.setOwner({
+ scope: 'membership-a:cn:1',
+ cacheScope: 'membership-a:cn:org-a',
+ organizationId: 'org-a',
+ });
+ await sync.sync();
+ cache.save.mockClear();
+
+ await sync.sync();
+
+ expect(cache.save).toHaveBeenCalledTimes(2);
+ expect(cache.save.mock.calls.map(([, catalog]) => catalog.revision)).toEqual(['2', '2']);
+ });
+
+ it('discards a late old-account response without blocking the new account', async () => {
+ const h = setup();
+ const late = deferred<unknown>();
+ h.fetch.mockReturnValueOnce(late.promise);
+ const old = h.sync.sync();
+ await Promise.resolve();
+ h.sync.setOwner({ scope: 'membership-b:cn:2', organizationId: 'org-a' });
+ h.fetch.mockResolvedValueOnce(directory([], '2'));
+ await h.sync.sync();
+ late.resolve(directory());
+ await old;
+ expect(h.active()).toEqual([]);
+ expect(h.fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('isolates pending/revoked providers and rejects cross-organization credentials', async () => {
+ const h = setup();
+ h.fetch
+ .mockResolvedValueOnce(directory([provider(), provider('byok-b')]))
+ .mockResolvedValueOnce({
+ ...credentials(),
+ credentials: [
+ ...credentials().credentials,
+ { providerId: 'byok-b', connectionRevision: 1, status: 'pending' },
+ ],
+ });
+ await h.sync.sync();
+ expect(h.active().map((entry) => entry.provider.id)).toEqual(['byok-a']);
+ expect(h.sync.getStatus().providers[1].state).toBe('pending');
+ h.fetch
+ .mockResolvedValueOnce(directory())
+ .mockResolvedValueOnce({ ...credentials(), organizationId: 'org-b' });
+ await h.sync.sync();
+ expect(h.sync.getStatus().state).toBe('failed');
+ expect(h.active()).toHaveLength(1);
+ });
+
+ it('refuses conflicting same-revision snapshots and never writes credentials to xd', async () => {
+ const h = setup();
+ h.fetch.mockResolvedValueOnce(directory()).mockResolvedValueOnce(credentials());
+ await h.sync.sync();
+ h.fetch.mockResolvedValueOnce(directory([provider('byok-b')]));
+ await h.sync.sync();
+ expect(h.sync.getStatus().state).toBe('failed');
+ expect(h.active()[0].provider.id).toBe('byok-a');
+ expect(h.fetch).toHaveBeenCalledTimes(3);
+ });
+
+ describe('pending self-heal', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ /** 第一轮目录 + pending 凭据;之后每次凭据重读由 `next` 决定。 */
+ function pendingHarness(next: () => unknown) {
+ vi.useFakeTimers();
+ const h = setup();
+ h.fetch
+ .mockResolvedValueOnce(directory([provider(), provider('byok-b')]))
+ .mockResolvedValueOnce({
+ ...credentials(['byok-a']),
+ credentials: [
+ credentials(['byok-a']).credentials[0],
+ { providerId: 'byok-b', connectionRevision: 1, status: 'pending' },
+ ],
+ });
+ h.fetch.mockImplementation(async (path: string) =>
+ path === '/api/model-access/byok/providers?schemaVersion=1'
+ ? directory([provider(), provider('byok-b')])
+ : next(),
+ );
+ return h;
+ }
+ const readyBoth = () => credentials(['byok-a', 'byok-b']);
+
+ it('retries the credentials endpoint only, and converges without a directory refetch', async () => {
+ const h = pendingHarness(readyBoth);
+ await h.sync.sync();
+ // 间隔必须大于服务端 20 秒的签发宽限期,否则 recover 分支会白白空转一次。
+ expect(PENDING_RETRY_DELAY_MS).toBeGreaterThan(20_000);
+ expect(h.sync.getStatus().providers[1].state).toBe('pending');
+ expect(h.active().map((entry) => entry.provider.id)).toEqual(['byok-a']);
+ const callsAfterFirstSync = h.fetch.mock.calls.length;
+
+ await vi.advanceTimersByTimeAsync(PENDING_RETRY_DELAY_MS);
+
+ expect(h.sync.getStatus().providers[1].state).toBe('ready');
+ expect(h.active().map((entry) => entry.provider.id)).toEqual(['byok-a', 'byok-b']);
+ // 目录此时已发布且未变,重试只允许再读凭据端点。
+ const retryCalls = h.fetch.mock.calls.slice(callsAfterFirstSync);
+ expect(retryCalls).toHaveLength(1);
+ expect(retryCalls[0]![0]).toBe('/api/model-access/byok/credentials?schemaVersion=1');
+ });
+
+ it('stops after three attempts while the server keeps answering pending', async () => {
+ const pendingOnly = () => ({
+ ...credentials(['byok-a']),
+ credentials: [
+ credentials(['byok-a']).credentials[0],
+ { providerId: 'byok-b', connectionRevision: 1, status: 'pending' },
+ ],
+ });
+ const h = pendingHarness(pendingOnly);
+ await h.sync.sync();
+ const callsAfterFirstSync = h.fetch.mock.calls.length;
+
+ // 远超 3 个重试间隔;有界重试不应演变成常驻轮询。
+ await vi.advanceTimersByTimeAsync(PENDING_RETRY_DELAY_MS * 10);
+
+ // 字面量而非常量:上限是产品契约,常量漂移必须让这条用例失败。
+ expect(PENDING_RETRY_LIMIT).toBe(3);
+ expect(h.fetch.mock.calls.length - callsAfterFirstSync).toBe(3);
+ expect(h.sync.getStatus().providers[1].state).toBe('pending');
+ });
+
+ it('schedules nothing when every provider is ready', async () => {
+ vi.useFakeTimers();
+ const h = setup();
+ h.fetch.mockResolvedValueOnce(directory()).mockResolvedValueOnce(credentials());
+ await h.sync.sync();
+ const callsAfterFirstSync = h.fetch.mock.calls.length;
+
+ await vi.advanceTimersByTimeAsync(PENDING_RETRY_DELAY_MS * 4);
+
+ expect(h.fetch.mock.calls.length).toBe(callsAfterFirstSync);
+ });
+
+ it('cancels the pending retry when the account changes', async () => {
+ const h = pendingHarness(readyBoth);
+ await h.sync.sync();
+ const callsAfterFirstSync = h.fetch.mock.calls.length;
+
+ h.sync.setOwner({ scope: 'membership-b:cn:2', organizationId: 'org-b' });
+ await vi.advanceTimersByTimeAsync(PENDING_RETRY_DELAY_MS * 4);
+
+ // 旧世代的重试不得以新身份继续打网络。
+ expect(h.fetch.mock.calls.length).toBe(callsAfterFirstSync);
+ });
+
+ it('keeps the pending overlay after a mid-retry fetch failure and still converges', async () => {
+ let retries = 0;
+ const h = pendingHarness(() => {
+ retries += 1;
+ if (retries === 1) throw new Error('BYOK_SYNC_TIMEOUT');
+ return readyBoth();
+ });
+ await h.sync.sync();
+ const callsAfterFirstSync = h.fetch.mock.calls.length;
+ expect(h.sync.getStatus().providers[1].state).toBe('pending');
+ expect(h.sync.getStatus().state).toBe('ready');
+
+ await vi.advanceTimersByTimeAsync(PENDING_RETRY_DELAY_MS);
+
+ expect(h.fetch.mock.calls.length - callsAfterFirstSync).toBe(1);
+ expect(h.sync.getStatus().providers[1].state).toBe('pending');
+ expect(h.sync.getStatus().state).toBe('ready');
+ expect(h.active().map((entry) => entry.provider.id)).toEqual(['byok-a']);
+
+ await vi.advanceTimersByTimeAsync(PENDING_RETRY_DELAY_MS);
+
+ expect(h.fetch.mock.calls.length - callsAfterFirstSync).toBe(2);
+ expect(h.sync.getStatus().providers[1].state).toBe('ready');
+ expect(h.sync.getStatus().state).toBe('ready');
+ expect(h.active().map((entry) => entry.provider.id)).toEqual(['byok-a', 'byok-b']);
+ });
+
+ it('counts fetch failures toward the retry budget without marking the provider unavailable', async () => {
+ const h = pendingHarness(() => {
+ throw new Error('offline');
+ });
+ await h.sync.sync();
+ const callsAfterFirstSync = h.fetch.mock.calls.length;
+
+ await vi.advanceTimersByTimeAsync(PENDING_RETRY_DELAY_MS * 10);
+
+ expect(h.fetch.mock.calls.length - callsAfterFirstSync).toBe(3);
+ expect(h.sync.getStatus().providers[1].state).toBe('pending');
+ expect(h.sync.getStatus().state).toBe('ready');
+ expect(h.active().map((entry) => entry.provider.id)).toEqual(['byok-a']);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/model-access/byokCache.ts b/apps/desktop/src/main/model-access/byokCache.ts
new file mode 100644
index 0000000000..95cace3e24
--- /dev/null
+++ b/apps/desktop/src/main/model-access/byokCache.ts
@@ -0,0 +1,85 @@
+import { createHash } from 'node:crypto';
+import {
+ parseByokProvidersResponse,
+ parseByokCredentialsResponse,
+ type ByokProvidersResponse,
+} from '@cindy/model-providers';
+import type { ByokOwner, ByokConnection } from './byokSync.js';
+
+export interface ByokCache {
+ load(owner: ByokOwner): { catalog: ByokProvidersResponse; connections: ByokConnection[] } | null;
+ save(
+ owner: ByokOwner,
+ catalog: ByokProvidersResponse,
+ connections: readonly ByokConnection[],
+ ): void;
+}
+/** One encrypted snapshot binds the identity, directory, endpoint and keys atomically. */
+export function createByokCache(
+ io: { read(key: string): string | null; write(key: string, value: string): boolean },
+ now = Date.now,
+): ByokCache {
+ const key = (owner: ByokOwner) =>
+ `byok_cache_${createHash('sha256')
+ .update(JSON.stringify([owner.cacheScope, owner.organizationId]))
+ .digest('hex')}`;
+ return {
+ load(owner) {
+ if (!owner.cacheScope) return null;
+ try {
+ const raw = io.read(key(owner));
+ if (!raw) return null;
+ const saved = JSON.parse(raw);
+ if (
+ saved.scope !== owner.cacheScope ||
+ saved.organizationId !== owner.organizationId ||
+ !Number.isFinite(saved.savedAt) ||
+ now() - saved.savedAt > 86400000 ||
+ saved.savedAt > now()
+ )
+ return null;
+ const catalog = parseByokProvidersResponse(saved.catalog);
+ const credentials = parseByokCredentialsResponse(saved.credentials);
+ if (
+ !catalog.ok ||
+ !credentials.ok ||
+ catalog.value.organizationId !== owner.organizationId ||
+ credentials.value.organizationId !== owner.organizationId
+ )
+ return null;
+ const connections = catalog.value.providers.flatMap((provider) => {
+ const credential = credentials.value.credentials.find(
+ (item) =>
+ item.providerId === provider.id &&
+ item.connectionRevision === provider.connectionRevision,
+ );
+ return credential?.status === 'ready' ? [{ provider, credential }] : [];
+ });
+ return { catalog: catalog.value, connections };
+ } catch {
+ return null;
+ }
+ },
+ save(owner, catalog, connections) {
+ if (!owner.cacheScope) return;
+ try {
+ io.write(
+ key(owner),
+ JSON.stringify({
+ scope: owner.cacheScope,
+ organizationId: owner.organizationId,
+ savedAt: now(),
+ catalog,
+ credentials: {
+ schemaVersion: 1,
+ organizationId: owner.organizationId,
+ credentials: connections.map((entry) => entry.credential),
+ },
+ }),
+ );
+ } catch {
+ /* Network synchronization remains authoritative when local encryption is unavailable. */
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/model-access/byokCredentials.ts b/apps/desktop/src/main/model-access/byokCredentials.ts
new file mode 100644
index 0000000000..0384f5fe8a
--- /dev/null
+++ b/apps/desktop/src/main/model-access/byokCredentials.ts
@@ -0,0 +1,32 @@
+/** Main-only ephemeral credentials. The owner-scoped synchronizer supplies the readers. */
+let keyReader: (providerId: string, agent: string) => string | null = () => null;
+let endpointReader: (providerId: string) => string | null = () => null;
+let managedProviderReader: (providerId: string) => boolean = () => false;
+
+export function setByokCredentialReader(next: typeof keyReader): void {
+ keyReader = next;
+}
+
+export function setByokEndpointReader(next: typeof endpointReader): void {
+ endpointReader = next;
+}
+
+export function setByokManagedProviderReader(next: typeof managedProviderReader): void {
+ managedProviderReader = next;
+}
+
+export function readByokCredential(providerId: string, agent: string): string | null {
+ return keyReader(providerId, agent);
+}
+
+/** Includes pending directory entries, so a personal same-id connection cannot be revived. */
+export function isInstalledByokProvider(providerId: string): boolean {
+ return managedProviderReader(providerId);
+}
+
+/** Live OpenAI-images origin: no trailing slash, no trailing `/v1`. */
+export function readByokInferenceBase(providerId: string): string | null {
+ const endpoint = endpointReader(providerId)?.trim();
+ if (!endpoint) return null;
+ return endpoint.replace(/\/+$/, '').replace(/\/v1$/, '');
+}
diff --git a/apps/desktop/src/main/model-access/byokIpc.ts b/apps/desktop/src/main/model-access/byokIpc.ts
new file mode 100644
index 0000000000..a8151cac52
--- /dev/null
+++ b/apps/desktop/src/main/model-access/byokIpc.ts
@@ -0,0 +1,22 @@
+import type { IpcMain, IpcMainInvokeEvent } from 'electron';
+import type { ByokStatus } from '../../shared/modelAccess.js';
+
+interface ByokControl {
+ getStatus(): ByokStatus;
+ sync(): Promise<void>;
+}
+export function registerByokIpc(
+ ipc: Pick<IpcMain, 'handle'>,
+ control: ByokControl,
+ assertSender: (event: IpcMainInvokeEvent) => void,
+): void {
+ ipc.handle('model-access:byok-status', (event) => {
+ assertSender(event);
+ return control.getStatus();
+ });
+ ipc.handle('model-access:byok-retry', async (event) => {
+ assertSender(event);
+ await control.sync();
+ return control.getStatus();
+ });
+}
diff --git a/apps/desktop/src/main/model-access/byokPricing.ts b/apps/desktop/src/main/model-access/byokPricing.ts
new file mode 100644
index 0000000000..9735a5d1af
--- /dev/null
+++ b/apps/desktop/src/main/model-access/byokPricing.ts
@@ -0,0 +1,42 @@
+import type { ByokProvider } from '@cindy/model-providers';
+import { gatewayModelPriceQuote, modelPricingKey } from '../../shared/modelPriceQuote.js';
+import type { ModelPricingCatalog } from '../../shared/regionalMoney.js';
+
+let pricing: ModelPricingCatalog = {};
+
+/** Enterprise reference prices are separate from Cindy retail prices and discounts. */
+export function buildByokPricing(providers: readonly ByokProvider[]): ModelPricingCatalog {
+ const result: ModelPricingCatalog = {};
+ for (const provider of providers) {
+ const quotes = (result[provider.id] = {} as ModelPricingCatalog[string]);
+ for (const model of provider.models) {
+ // Missing currency is unknown, not a reason to guess from the client's region.
+ if (!model.currency) continue;
+ const quote = gatewayModelPriceQuote(
+ { ...model, costDiscount: undefined },
+ model.currency,
+ false,
+ {
+ allowFreeModel: true,
+ },
+ );
+ if (!quote) continue;
+ for (const agent of model.agents ?? []) {
+ quotes[modelPricingKey(model.id, agent)] = {
+ ...quote,
+ providerId: provider.id,
+ source: 'provider-reference',
+ approximate: true,
+ };
+ }
+ }
+ }
+ return result;
+}
+
+export function setByokPricing(value: ModelPricingCatalog): void {
+ pricing = value;
+}
+export function getByokPricing(): ModelPricingCatalog {
+ return structuredClone(pricing);
+}
diff --git a/apps/desktop/src/main/model-access/byokProvider.ts b/apps/desktop/src/main/model-access/byokProvider.ts
new file mode 100644
index 0000000000..5d0754862d
--- /dev/null
+++ b/apps/desktop/src/main/model-access/byokProvider.ts
@@ -0,0 +1,160 @@
+import {
+ isByokImageMode,
+ isOrganizationManagedProvider,
+ type AgentKind,
+ type CatalogModel,
+ type CustomProviderConfig,
+ type Provider,
+} from '@cindy/model-providers';
+import type { ByokConnection } from './byokSync.js';
+
+/** Project trusted directory metadata into the existing routing/catalog shape. No secrets. */
+export function buildByokProvider({ provider, credential }: ByokConnection): Provider {
+ const inferenceBase = credential.endpoint.replace(/\/+$/, '').replace(/\/v1$/, '');
+ const models: Provider['models'] = {};
+ const routing: Provider['routing'] = {};
+ const agents: AgentKind[] = [];
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ const entries = provider.models.filter(
+ (model) => !isByokImageMode(model.mode) && model.agents?.includes(agent),
+ );
+ if (!entries.length) continue;
+ agents.push(agent);
+ routing[agent] = {
+ // Anthropic SDK appends /v1/messages, while Codex expects a /v1 base.
+ upstream: agent === 'codex' ? `${inferenceBase}/v1` : inferenceBase,
+ authStrategy: 'api-key-header',
+ // Pi consumes per-model piApi; the gateway accepts all declared protocols.
+ wireProtocol: agent === 'claude-code' ? 'anthropic-messages' : 'openai-responses',
+ ...(agent === 'codex' && provider.imageBinding
+ ? {
+ supportsImageGeneration: true,
+ imageModel: {
+ wireModel: provider.imageBinding.wireModel,
+ litellmModel: provider.imageBinding.litellmModel,
+ supportsEdit: provider.imageBinding.supportsEdit,
+ },
+ }
+ : {}),
+ };
+ models[agent] = entries.map((model): CatalogModel => {
+ const defaults = model.perAgent[agent]!;
+ const declaredEfforts = defaults.efforts ?? model.efforts ?? [];
+ const efforts =
+ agent === 'pi' ? declaredEfforts.filter((effort) => effort !== 'ultra') : declaredEfforts;
+ const defaultEffort =
+ defaults.defaultEffort !== undefined ? defaults.defaultEffort : model.defaultEffort;
+ const price = (value: number | undefined) =>
+ value === undefined ? undefined : value * 1_000_000;
+ return {
+ id: model.id,
+ name: model.name ?? model.id,
+ mode: model.mode ?? 'chat',
+ nativeApi: model.nativeApi === 'openai-images' ? undefined : model.nativeApi,
+ description: model.description,
+ group: model.group,
+ icon: model.icon,
+ sortOrder: model.sortOrder,
+ modalities: model.modalities,
+ newSessionDefault: model.newSessionDefault,
+ contextWindow: defaults.contextWindow ?? model.contextWindow ?? 200_000,
+ contextWindowMax: model.contextWindow,
+ contextWindowVerified:
+ defaults.contextWindow !== undefined || model.contextWindow !== undefined,
+ maxOutput: model.maxOutputTokens,
+ efforts: [...efforts],
+ defaultEffort: defaultEffort && efforts.includes(defaultEffort) ? defaultEffort : null,
+ supportsFastMode: defaults.supportsFastMode ?? model.supportsFastMode ?? false,
+ defaultEnabled: defaults.defaultEnabled ?? model.defaultEnabled ?? true,
+ supportsImageInput: model.modalities?.input.includes('image') ?? false,
+ ...(agent === 'pi'
+ ? {
+ piApi: defaults.wireProtocol,
+ route: {
+ baseUrl:
+ defaults.wireProtocol === 'anthropic-messages'
+ ? inferenceBase
+ : `${inferenceBase}/v1`,
+ wireProtocol:
+ defaults.wireProtocol === 'openai-completions'
+ ? ('openai-chat' as const)
+ : defaults.wireProtocol,
+ },
+ }
+ : {}),
+ cost: {
+ input: price(model.inputCostPerToken),
+ output: price(model.outputCostPerToken),
+ cacheRead: price(model.cacheReadInputTokenCost),
+ cacheWrite: price(model.cacheCreationInputTokenCost),
+ },
+ };
+ });
+ }
+ const imageModels = provider.models
+ .filter((model) => isByokImageMode(model.mode))
+ .map((model) => ({
+ id: model.id,
+ name: model.name ?? model.id,
+ mode: 'image_generation' as const,
+ nativeApi: model.nativeApi,
+ description: model.description,
+ modalities: model.modalities ?? { input: ['text'], output: ['image'] },
+ defaultEnabled: model.defaultEnabled ?? true,
+ }));
+ return {
+ id: provider.id,
+ name: provider.name,
+ source: 'organization',
+ auth: { method: 'managed' },
+ access: { kind: 'managed' },
+ agents,
+ routing,
+ models,
+ ...(imageModels.length ? { imageModels, imageDefaults: { standard: imageModels[0]!.id } } : {}),
+ };
+}
+
+/** Ephemeral native-runtime input, never saved into the user's custom Provider table. */
+export function byokNativeConfigs(providers: readonly Provider[]): CustomProviderConfig[] {
+ return providers
+ .filter((provider) => isOrganizationManagedProvider(provider) && provider.agents.includes('pi'))
+ .map((provider) => ({
+ id: provider.id,
+ name: provider.name,
+ auth: { method: 'apiKey' },
+ runtimes: {
+ pi: {
+ baseUrl: provider.routing.pi!.upstream,
+ wireProtocol: provider.routing.pi!.wireProtocol,
+ models: (provider.models.pi ?? []).map((model) => ({
+ id: model.id,
+ name: model.name,
+ contextWindow: model.contextWindow,
+ piApi: model.piApi,
+ ...(model.route ? { route: model.route } : {}),
+ supportsImageInput: model.supportsImageInput,
+ reasoning: model.efforts.length > 0,
+ reasoningEfforts: model.efforts.filter((effort) => effort !== 'ultra'),
+ reasoningDefaultEffort:
+ model.defaultEffort === 'ultra' ? undefined : (model.defaultEffort ?? undefined),
+ })),
+ },
+ },
+ }));
+}
+
+/** Managed connections win an id collision without mixing a personal endpoint with a member key. */
+export function mergeByokNativeConfigs(
+ personal: readonly CustomProviderConfig[],
+ providers: readonly Provider[],
+): CustomProviderConfig[] {
+ const managed = byokNativeConfigs(providers);
+ // The organization directory owns its ids even while a credential is pending.
+ // Falling back to a same-id personal native config would combine the enterprise
+ // catalog selection with a personal endpoint or a keyless local runtime.
+ const managedIds = new Set(
+ providers.filter(isOrganizationManagedProvider).map((provider) => provider.id),
+ );
+ return [...personal.filter((provider) => !managedIds.has(provider.id)), ...managed];
+}
diff --git a/apps/desktop/src/main/model-access/byokRuntime.ts b/apps/desktop/src/main/model-access/byokRuntime.ts
new file mode 100644
index 0000000000..d1ef7f4847
--- /dev/null
+++ b/apps/desktop/src/main/model-access/byokRuntime.ts
@@ -0,0 +1,254 @@
+import type { ByokCache } from './byokCache.js';
+import { BYOK_PROVIDERS_PATH, BYOK_CREDENTIALS_PATH, isByokImageMode, type ByokProvider, type Provider } from '@cindy/model-providers';
+import {
+ setByokCredentialReader,
+ setByokEndpointReader,
+ setByokManagedProviderReader,
+} from './byokCredentials.js';
+import { isDeepStrictEqual } from 'node:util';
+import { setManagedProviders } from '../maker-host/active-catalog.js';
+import { beginProviderRouteMutation } from '../maker-host/provider-route.js';
+import { serverApiFetch } from '../serverApiClient.js';
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import { createByokSync, type ByokConnection } from './byokSync.js';
+import { buildByokProvider } from './byokProvider.js';
+import { buildByokPricing, setByokPricing } from './byokPricing.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('byokRuntime');
+// Only service-defined codes may leave the sensitive response boundary.
+const BYOK_ERROR_CODES = [
+ 'ORG_AI_GATEWAY_ERROR',
+ 'BYOK_UNAVAILABLE',
+ 'ORG_AI_MANAGEMENT_DISABLED',
+ 'ORG_AI_NOT_ENABLED',
+ 'ORG_AI_UNSUPPORTED',
+ 'ORG_NOT_SUPPORTED',
+ 'ORGANIZATION_BASELINE_NOT_READY',
+ 'ORGANIZATION_SEAT_REQUIRED',
+ 'MEMBERSHIP_INACTIVE',
+ 'INVALID_PARAMS',
+ 'UNAUTHORIZED',
+ 'TOKEN_EXPIRED',
+ 'INVALID_TOKEN',
+ 'ACCOUNT_UNAVAILABLE',
+ 'FORBIDDEN',
+ 'RATE_LIMITED',
+ 'INTERNAL_ERROR',
+] as const;
+
+// Only Codex freezes this generation. Pi/Claude/Art read live configuration;
+// their model changes still take the mutation lock, but must not expire an
+// unchanged Codex snapshot. Credentials and provider identity remain shared.
+function credentialRevisionState(state: ReturnType<typeof dispatchState>[number] | undefined) {
+ if (!state) return undefined;
+ return {
+ providerId: state.providerId,
+ credential: state.credential,
+ responseModels: state.chatModels.filter((model) => model.agents.includes('codex')).map((model) => model.id),
+ imageBinding: state.imageBinding,
+ };
+}
+
+function dispatchState(entries: readonly ByokProvider[], ready: readonly ByokConnection[]) {
+ return entries
+ .map((provider) => {
+ const connection = ready.find((entry) => entry.provider.id === provider.id);
+ const chatModels = provider.models
+ .filter((model) => !isByokImageMode(model.mode))
+ .map((model) => {
+ const agents = [...(model.agents ?? [])].sort();
+ return {
+ id: model.id,
+ agents,
+ protocols: Object.fromEntries(
+ agents.map((agent) => [agent, model.perAgent[agent]?.wireProtocol]),
+ ),
+ };
+ })
+ .sort((left, right) => left.id.localeCompare(right.id));
+ const imageModels = provider.models
+ .filter((model) => isByokImageMode(model.mode))
+ .map((model) => model.id)
+ .sort();
+ return {
+ providerId: provider.id,
+ credential: connection
+ ? {
+ connectionRevision: connection.credential.connectionRevision,
+ endpoint: connection.credential.endpoint.replace(/\/+$/, '').replace(/\/v1$/, ''),
+ apiKey: connection.credential.apiKey,
+ }
+ : null,
+ chatModels,
+ imageModels,
+ imageBinding: provider.imageBinding
+ ? {
+ wireModel: provider.imageBinding.wireModel,
+ litellmModel: provider.imageBinding.litellmModel,
+ supportsEdit: provider.imageBinding.supportsEdit,
+ }
+ : null,
+ };
+ })
+ .sort((left, right) => left.providerId.localeCompare(right.providerId));
+}
+
+/** Secrets stay in Main; an optional encrypted identity-scoped snapshot supports cold starts. */
+export function createByokRuntime(
+ onPricingChanged?: () => void,
+ cache?: ByokCache,
+ onCodexRoutesChanged?: () => void,
+) {
+ let installed: readonly ByokConnection[] = [];
+ let installedDirectory: readonly ByokProvider[] = [];
+ setByokCredentialReader((providerId, agent) => {
+ const connection = installed.find((entry) => entry.provider.id === providerId);
+ if (!connection) return null;
+ if (agent === 'image') {
+ return connection.provider.models.some((model) => isByokImageMode(model.mode))
+ ? connection.credential.apiKey
+ : null;
+ }
+ if (agent !== 'pi' && agent !== 'codex' && agent !== 'claude-code') return null;
+ return connection.provider.models.some((model) => model.agents?.includes(agent))
+ ? connection.credential.apiKey
+ : null;
+ });
+ setByokEndpointReader((providerId) => {
+ const connection = installed.find((entry) => entry.provider.id === providerId);
+ return connection?.credential.endpoint ?? null;
+ });
+ setByokManagedProviderReader((providerId) =>
+ installedDirectory.some((provider) => provider.id === providerId),
+ );
+ const project = (
+ entries: readonly ByokProvider[],
+ ready: readonly ByokConnection[],
+ ): Provider[] =>
+ entries.map((provider) => {
+ const connection = ready.find((entry) => entry.provider.id === provider.id);
+ return connection
+ ? buildByokProvider(connection)
+ : {
+ id: provider.id,
+ name: provider.name,
+ source: 'organization',
+ auth: { method: 'managed' },
+ access: { kind: 'managed' },
+ agents: [],
+ routing: {},
+ models: {},
+ };
+ });
+ const codexHostState = (entries: readonly ByokProvider[], ready: readonly ByokConnection[]) =>
+ dispatchState(entries, ready).flatMap((provider) => {
+ const responseModels = provider.chatModels
+ .filter((model) => model.agents.includes('codex'))
+ .map((model) => model.id);
+ if (!provider.credential || !provider.imageBinding || responseModels.length === 0) return [];
+ return [
+ {
+ providerId: provider.providerId,
+ credential: provider.credential,
+ responseModels,
+ imageBinding: provider.imageBinding,
+ },
+ ];
+ });
+ return createByokSync({
+ cache,
+ fetch: async (path, options) => {
+ const logLabel = path === BYOK_PROVIDERS_PATH
+ ? '/api/model-access/byok/providers'
+ : path === BYOK_CREDENTIALS_PATH
+ ? '/api/model-access/byok/credentials'
+ : '/api/model-access/byok';
+ const startedAt = Date.now();
+ const response = await serverApiFetch(path, {
+ ...options,
+ baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),
+ redactErrorDetails: true,
+ logLabel,
+ allowedRedactedErrorCodes: BYOK_ERROR_CODES,
+ // 与 byokSync 的 TIMEOUT_MS=20s 对齐:deadline 只赛跑不中止,这里让底层请求在同样时限真正 abort,不留悬挂连接
+ timeoutMs: 20_000,
+ });
+ log.debug('byok.sync.request_succeeded', 'path=' + logLabel, 'elapsedMs=' + (Date.now() - startedAt));
+ return response;
+ },
+ replace: (_owner, connections, directory = connections.map((entry) => entry.provider)) => {
+ if (
+ isDeepStrictEqual(installed, connections) &&
+ isDeepStrictEqual(installedDirectory, directory)
+ )
+ return;
+ const previousDispatchState = dispatchState(installedDirectory, installed);
+ const nextDispatchState = dispatchState(directory, connections);
+ const previousCodexState = codexHostState(installedDirectory, installed);
+ const nextProviders = project(directory, connections);
+ const nextPricing = buildByokPricing(directory);
+
+ const previousDispatchById = new Map(
+ previousDispatchState.map((state) => [state.providerId, state]),
+ );
+ const nextDispatchById = new Map(nextDispatchState.map((state) => [state.providerId, state]));
+ const ids = new Set([...previousDispatchById.keys(), ...nextDispatchById.keys()]);
+ const changedIds = [...ids].filter(
+ (id) => !isDeepStrictEqual(previousDispatchById.get(id), nextDispatchById.get(id)),
+ );
+ const gates = changedIds.map(beginProviderRouteMutation);
+ const previous = installed;
+
+ try {
+ installed = structuredClone(connections);
+ installedDirectory = structuredClone(directory);
+ setByokPricing(nextPricing);
+ setManagedProviders(nextProviders);
+ for (const [index, gate] of gates.entries()) {
+ const id = changedIds[index]!;
+ if (!isDeepStrictEqual(
+ credentialRevisionState(previousDispatchById.get(id)),
+ credentialRevisionState(nextDispatchById.get(id)),
+ )) gate.commit();
+ }
+ } catch (error) {
+ if (directory.length === 0 && connections.length === 0) {
+ // Logout and a successfully empty directory must never resurrect secrets
+ // merely because a catalog listener failed while notifying a renderer.
+ installed = [];
+ installedDirectory = [];
+ setByokPricing({});
+ for (const gate of gates) gate.commit();
+ log.warn('cleared credentials despite a catalog notification failure');
+ } else {
+ // Retain only wholly unchanged connections. A revoked or rotated key
+ // must not be resurrected as part of rolling back a display failure.
+ installed = previous.filter((entry) =>
+ connections.some((next) => isDeepStrictEqual(entry, next)),
+ );
+ installedDirectory = structuredClone(directory);
+ setByokPricing(nextPricing);
+ for (const gate of gates) gate.commit();
+ setManagedProviders(project(directory, installed));
+ throw error;
+ }
+ } finally {
+ for (const gate of gates) gate();
+ if (!isDeepStrictEqual(previousCodexState, codexHostState(installedDirectory, installed))) {
+ try {
+ onCodexRoutesChanged?.();
+ } catch {
+ log.warn('Codex Host refresh notification failed');
+ }
+ }
+ }
+ // A closed renderer must not roll back an already installed credential generation.
+ try {
+ onPricingChanged?.();
+ } catch {
+ log.warn('reference price notification failed');
+ }
+ },
+ });
+}
diff --git a/apps/desktop/src/main/model-access/byokSync.ts b/apps/desktop/src/main/model-access/byokSync.ts
new file mode 100644
index 0000000000..6a7d00a090
--- /dev/null
+++ b/apps/desktop/src/main/model-access/byokSync.ts
@@ -0,0 +1,273 @@
+import type { ByokCache } from './byokCache.js';
+import { isDeepStrictEqual } from 'node:util';
+import {
+ BYOK_CREDENTIALS_PATH,
+ BYOK_PROVIDERS_PATH,
+ parseByokCredentialsResponse,
+ parseByokProvidersResponse,
+ type ByokCredential,
+ type ByokProvider,
+ type ByokProvidersResponse,
+} from '@cindy/model-providers';
+
+export interface ByokOwner {
+ /** Include the auth generation and region, not just a membership ID. */
+ scope: string;
+ /** Stable identity + region for encrypted restart snapshots, excluding the process generation. */
+ cacheScope?: string;
+ organizationId: string;
+}
+type ReadyCredential = Extract<ByokCredential, { status: 'ready' }>;
+export interface ByokConnection {
+ provider: ByokProvider;
+ credential: ReadyCredential;
+}
+export interface ByokSyncDependencies {
+ cache?: ByokCache;
+ fetch(path: string, options: { method: 'GET'; cache: 'no-store' }): Promise<unknown>;
+ /** Synchronous, Main-only transaction: stage secrets, then publish matching routes.
+ * On failure leave no partially updated route/secret pair; never forward this payload to IPC.
+ */
+ replace(
+ owner: ByokOwner | null,
+ connections: readonly ByokConnection[],
+ directory?: readonly ByokProvider[],
+ ): void;
+}
+import type { ByokStatus as ByokSyncStatus } from '../../shared/modelAccess.js';
+
+const TIMEOUT_MS = 20_000;
+/**
+ * `pending` 是服务端明确表示的中间态(旧 Key 已撤销、新 Key 尚未签发,见
+ * MAS byok/credentials.ts 的 revoke / recover 分支),不是失败。这一轮不会安装路由,
+ * 所以需要一个有界的自愈重试把连接补回来。
+ *
+ * 间隔取 30 秒:大于服务端签发宽限期 `ISSUE_RECOVERY_GRACE_MS`(默认
+ * `MODEL_GATEWAY_TIMEOUT_MS × 2` = 20 秒),所以每次重试都已越过宽限期,不会被
+ * 宽限期空转掉。recover 分支需要「先撤销再签发」两次请求才能收敛,3 次预算足够。
+ * 重试有上限,不构成常驻轮询;定时器 unref,不阻止进程退出。
+ *
+ * 重试只重读凭据端点:目录此时已发布且未变,重拉目录只会多占一次
+ * `byok-member-access` 限流额度(默认 60 秒 10 次,含用户手动刷新)。
+ */
+export const PENDING_RETRY_DELAY_MS = 30_000;
+export const PENDING_RETRY_LIMIT = 3;
+function deadline<T>(promise: Promise<T>): Promise<T> {
+ let timer: ReturnType<typeof setTimeout>;
+ return Promise.race([
+ promise,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('BYOK_SYNC_TIMEOUT')), TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]).finally(() => clearTimeout(timer));
+}
+
+/** Identity-scoped synchronization. The caller owns persistence and active-catalog publication. */
+export function createByokSync(deps: ByokSyncDependencies) {
+ let owner: ByokOwner | null = null;
+ let epoch = 0;
+ let catalog: ByokProvidersResponse | null = null;
+ let connections: ByokConnection[] = [];
+ let status: ByokSyncStatus = { state: 'idle', providers: [] };
+ let queue = Promise.resolve();
+ let inflight: Promise<void> | null = null;
+ let pendingRetryTimer: ReturnType<typeof setTimeout> | null = null;
+ let pendingRetryAttempts = 0;
+
+ function current(generation: number) {
+ return generation === epoch && owner !== null;
+ }
+ function publish(next: ByokConnection[], directory = catalog?.providers ?? [], persist = true) {
+ try {
+ deps.replace(owner, next, directory);
+ } catch (error) {
+ connections = [];
+ throw error;
+ }
+ connections = next;
+ if (persist && owner && catalog)
+ deps.cache?.save(owner, { ...catalog, providers: [...directory] }, next);
+ }
+ function updateStatus(state: ByokSyncStatus['state']) {
+ status = {
+ state,
+ providers: (catalog?.providers ?? []).map((provider) => ({
+ providerId: provider.id,
+ state: connections.some((entry) => entry.provider.id === provider.id)
+ ? 'ready'
+ : 'unavailable',
+ })),
+ };
+ }
+ function enqueue(operation: () => Promise<void>) {
+ const run = queue.then(operation);
+ queue = run.catch(() => undefined);
+ return run;
+ }
+ function clearPendingRetry() {
+ if (pendingRetryTimer) clearTimeout(pendingRetryTimer);
+ pendingRetryTimer = null;
+ }
+ /** 只在服务端明确返回 pending 时排自愈重试;其他状态(含 failed)都不排。 */
+ function hasPendingProvider(): boolean {
+ return status.providers.some((item) => item.state === 'pending');
+ }
+ /**
+ * 重试只重读凭据端点:目录已发布且未变,重拉目录既无意义也会多占限流额度。
+ * 预算由最近一次 sync 重置,重试自身递增,所以每轮最多补 3 次,
+ * 既不会累积成无限轮询,也不会把不同一轮的 pending 累加成一个上限。
+ */
+ function schedulePendingRetry(generation: number) {
+ clearPendingRetry();
+ if (
+ !current(generation) ||
+ !hasPendingProvider() ||
+ pendingRetryAttempts >= PENDING_RETRY_LIMIT
+ )
+ return;
+ pendingRetryTimer = setTimeout(() => {
+ pendingRetryTimer = null;
+ if (!current(generation)) return;
+ pendingRetryAttempts++;
+ void enqueue(async () => {
+ if (!current(generation) || !hasPendingProvider()) return;
+ try {
+ const raw = await deadline(
+ deps.fetch(BYOK_CREDENTIALS_PATH, { method: 'GET', cache: 'no-store' }),
+ );
+ if (!current(generation)) return;
+ applyCredentials(raw);
+ // 仍然 pending 就继续用剩余预算补;已收敛则不再排。
+ if (hasPendingProvider()) schedulePendingRetry(generation);
+ } catch {
+ // 瞬时失败不能走 updateStatus('failed'):它只重建 ready|unavailable,
+ // 会把 pending 叠层抹掉,hasPendingProvider() 变 false,剩余预算作废。
+ // 已有可用连接这条路径本来就不会被 publish 掉。
+ if (current(generation) && hasPendingProvider()) schedulePendingRetry(generation);
+ }
+ }).catch(() => undefined);
+ }, PENDING_RETRY_DELAY_MS);
+ pendingRetryTimer.unref?.();
+ }
+ async function refresh(generation: number) {
+ if (!current(generation)) return;
+ status = { ...status, state: 'syncing' };
+ try {
+ const raw = await deadline(
+ deps.fetch(BYOK_PROVIDERS_PATH, { method: 'GET', cache: 'no-store' }),
+ );
+ if (!current(generation)) return;
+ const parsed = parseByokProvidersResponse(raw);
+ if (!parsed.ok || parsed.value.organizationId !== owner!.organizationId)
+ throw new Error('BYOK_INVALID_DIRECTORY');
+ if (
+ catalog?.revision === parsed.value.revision &&
+ !isDeepStrictEqual(catalog, parsed.value)
+ ) {
+ throw new Error('BYOK_DIRECTORY_REVISION_CONFLICT');
+ }
+ const nextCatalog = parsed.value;
+ // Revoke removed routes and invalidate changed connections before fetching any new key.
+ const retained = nextCatalog.providers.flatMap((provider) => {
+ const existing = connections.find(
+ (entry) =>
+ entry.provider.id === provider.id &&
+ entry.provider.connectionRevision === provider.connectionRevision,
+ );
+ return existing ? [{ provider, credential: existing.credential }] : [];
+ });
+ // Publish the new directory atomically, then persist it after `catalog` points at the same
+ // snapshot. Otherwise `publish` briefly writes the old revision with the new provider list.
+ publish(retained, nextCatalog.providers, false);
+ catalog = nextCatalog;
+ if (owner) deps.cache?.save(owner, catalog, connections);
+ if (catalog.providers.length === 0) {
+ updateStatus('ready');
+ return;
+ }
+ const rawCredentials = await deadline(
+ deps.fetch(BYOK_CREDENTIALS_PATH, { method: 'GET', cache: 'no-store' }),
+ );
+ if (!current(generation)) return;
+ applyCredentials(rawCredentials);
+ schedulePendingRetry(generation);
+ } catch {
+ if (current(generation)) updateStatus('failed');
+ }
+ }
+ function applyCredentials(raw: unknown) {
+ const parsed = parseByokCredentialsResponse(raw);
+ if (!parsed.ok || parsed.value.organizationId !== owner!.organizationId)
+ throw new Error('BYOK_INVALID_CREDENTIALS');
+ const next: ByokConnection[] = [];
+ for (const provider of catalog!.providers) {
+ const credential = parsed.value.credentials.find((entry) => entry.providerId === provider.id);
+ if (credential?.connectionRevision !== provider.connectionRevision) continue;
+ if (credential.status === 'ready') next.push({ provider, credential });
+ // A declared failure or missing item is not permission to keep using an old key.
+ }
+ publish(next);
+ updateStatus('ready');
+ status.providers = status.providers.map((item) => {
+ const credential = parsed.value.credentials.find(
+ (entry) => entry.providerId === item.providerId,
+ );
+ return item.state !== 'ready' && credential?.status === 'pending'
+ ? { ...item, state: 'pending' }
+ : item;
+ });
+ }
+
+ return {
+ /** Call on logout/account/region generation changes before any new network request. */
+ setOwner(next: ByokOwner | null) {
+ if (owner?.scope === next?.scope && owner?.organizationId === next?.organizationId) return;
+ epoch++;
+ // Clear the old routes while the old owner is still installed.
+ deps.replace(owner, []);
+ owner = next;
+ catalog = null;
+ connections = [];
+ status = { state: 'idle', providers: [] };
+ queue = Promise.resolve();
+ inflight = null;
+ // 旧身份的 pending 重试预算不能带到新身份;定时器也必须停掉。
+ clearPendingRetry();
+ pendingRetryAttempts = 0;
+ if (next) {
+ const cached = deps.cache?.load(next);
+ if (cached) {
+ catalog = cached.catalog;
+ try {
+ publish(cached.connections, cached.catalog.providers, false);
+ updateStatus('idle');
+ } catch {
+ catalog = null;
+ connections = [];
+ updateStatus('failed');
+ }
+ }
+ }
+ },
+ sync(): Promise<void> {
+ if (!owner) return Promise.resolve();
+ if (inflight) return inflight;
+ const generation = epoch;
+ // 每次显式同步重置 pending 重试预算,并作废上一轮尚未触发的重试。
+ clearPendingRetry();
+ pendingRetryAttempts = 0;
+ const run = enqueue(() => refresh(generation));
+ inflight = run;
+ void run
+ .finally(() => {
+ if (inflight === run) inflight = null;
+ })
+ .catch(() => undefined);
+ return run;
+ },
+ getStatus(): ByokSyncStatus {
+ return structuredClone(status);
+ },
+ };
+}
diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.ts
index 47f1557cc5..d30b1be075 100644
--- a/apps/desktop/src/main/model-access/index.ts
+++ b/apps/desktop/src/main/model-access/index.ts
@@ -1,13 +1,21 @@
+import { createByokCache } from './byokCache.js';
+import { byokSnapshotSecretIo } from '../secrets/providerSecretStore.js';
+import { registerByokIpc } from './byokIpc.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { createByokRuntime } from './byokRuntime.js';
+import { broadcastReferenceModelPricing } from '../usage/referenceModelPricing.js';
import { app, BrowserWindow, ipcMain } from 'electron';
import { createLogger } from '../logger.js';
import * as authManager from '../authManager.js';
+import { isExternalOrganizationByokUser } from './organizationManaged.js';
import { serverApiFetch, ServerApiError } from '../serverApiClient.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
import { getCodexProxyAuthInjectionState } from '../maker-host/codex-proxy-host.js';
import {
prepareCodexForAuthModeChange,
+ prepareCodexForCustomProviderHostChange,
finalizeCodexAfterAuthModeChange,
cancelCodexAuthModeChange,
} from '../maker-host/index.js';
@@ -343,6 +351,51 @@ function scheduleModelsSync(): void {
let syncInstance: CredentialsSync | null = null;
let foregroundRefreshListener: (() => void) | null = null;
+/**
+ * 企业 Provider 目录的刷新形态与 Cindy 自有目录一致:窗口聚焦触发 + 5 分钟节流,
+ * 不挂后台定时轮询。登录 / 冷启动 / 换号 / 换区域不受节流约束(见 noteAuthState)。
+ */
+export const BYOK_FOREGROUND_REFRESH_INTERVAL_MS = 5 * 60_000;
+let lastByokSyncStartedAt = 0;
+type ByokRuntime = ReturnType<typeof createByokRuntime>;
+let byokCodexHostRefreshQueued = false;
+let byokCodexHostRefreshRunning = false;
+
+/** Coalesce directory/key changes and retire only the local Codex Host. */
+function scheduleByokCodexHostRefresh(): void {
+ byokCodexHostRefreshQueued = true;
+ if (byokCodexHostRefreshRunning) return;
+ byokCodexHostRefreshRunning = true;
+ void (async () => {
+ try {
+ while (byokCodexHostRefreshQueued) {
+ byokCodexHostRefreshQueued = false;
+ let prepared = false;
+ try {
+ await prepareCodexForCustomProviderHostChange();
+ prepared = true;
+ await finalizeCodexAfterAuthModeChange();
+ } catch (error) {
+ log.warn('enterprise Codex Host refresh failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ if (prepared) cancelCodexAuthModeChange();
+ }
+ }
+ } finally {
+ byokCodexHostRefreshRunning = false;
+ }
+ })();
+}
+
+function scheduleByokSync(byok: ByokRuntime, force = false): void {
+ const now = Date.now();
+ if (!force && now - lastByokSyncStartedAt < BYOK_FOREGROUND_REFRESH_INTERVAL_MS) return;
+ lastByokSyncStartedAt = now;
+ void byok.sync();
+}
+
function getSync(): CredentialsSync {
if (!syncInstance) {
syncInstance = createCredentialsSync({
@@ -457,6 +510,11 @@ function mapServerError(err: unknown): never {
*/
export function initModelAccess(): void {
const sync = getSync();
+ const byok = createByokRuntime(
+ broadcastReferenceModelPricing,
+ createByokCache(byokSnapshotSecretIo),
+ scheduleByokCodexHostRefresh,
+ );
const noteAuthState = (
isAuthenticated: boolean,
@@ -479,6 +537,14 @@ export function initModelAccess(): void {
lastAuthUserId = isAuthenticated ? (userId ?? lastAuthUserId) : null;
lastAuthRealm = isAuthenticated ? (realm ?? lastAuthRealm) : null;
sync.handleAuthChange({ isAuthenticated, userId, realm });
+ const user = authManager.getAuthState().user;
+ byok.setOwner(isAuthenticated && userId && isExternalOrganizationByokUser(user) ? {
+ scope: JSON.stringify([authGeneration, userId, realm, user.orgId]),
+ cacheScope: JSON.stringify([userId, realm, user.orgId]),
+ organizationId: user.orgId,
+ } : null);
+ // 身份切换/登录是显式事件,不受聚焦节流约束。
+ scheduleByokSync(byok, true);
};
authManager.onAuthStateChange((state) => {
@@ -494,12 +560,21 @@ export function initModelAccess(): void {
noteAuthState(true, initial.user?.id ?? null, authManager.getActiveAuthRealm());
}
foregroundRefreshListener = () => {
+ scheduleByokSync(byok);
if (!lastAuthUserId || getSync().getStatus().state !== 'ok') return;
if (Date.now() - lastModelsSyncStartedAt < XD_MODELS_FOREGROUND_REFRESH_INTERVAL_MS) return;
scheduleModelsSync();
};
app.on('browser-window-focus', foregroundRefreshListener);
ipcMain.handle('model-access:get-status', () => getModelAccessStatus());
+ registerByokIpc(ipcMain, {
+ getStatus: () => byok.getStatus(),
+ // 设置页的显式刷新不受节流限制,但要记时间戳,避免紧接着的聚焦再拉一轮。
+ sync: () => {
+ lastByokSyncStartedAt = Date.now();
+ return byok.sync();
+ },
+ }, assertTrustedAppRendererEvent);
ipcMain.handle('model-access:retry', async (): Promise<ModelAccessStatus> => {
if (!getAppCapabilities().canUseCindyGateway) {
@@ -522,6 +597,8 @@ export function initModelAccess(): void {
/** 仅测试:重置单例。 */
export function resetModelAccessForTest(): void {
+ lastByokSyncStartedAt = 0;
+ byokCodexHostRefreshQueued = false;
if (foregroundRefreshListener) {
app.removeListener('browser-window-focus', foregroundRefreshListener);
foregroundRefreshListener = null;
diff --git a/apps/desktop/src/main/model-access/organizationManaged.ts b/apps/desktop/src/main/model-access/organizationManaged.ts
new file mode 100644
index 0000000000..ead602952a
--- /dev/null
+++ b/apps/desktop/src/main/model-access/organizationManaged.ts
@@ -0,0 +1,13 @@
+import { isXdOrgUser, type XdOrgBetaUser } from '../xdOrgBetaDefault.js';
+
+/** Client BYOK is scoped to signed-in external organizations with a stable organization id. */
+export function isExternalOrganizationByokUser(
+ user: (XdOrgBetaUser & { orgId: string | null }) | null | undefined,
+): user is XdOrgBetaUser & { orgId: string } {
+ return Boolean(
+ user?.membershipKind === 'org' &&
+ typeof user.orgId === 'string' &&
+ user.orgId.trim().length > 0 &&
+ !isXdOrgUser(user),
+ );
+}
diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.ts
index dc3b48bc8d..c7a931b935 100644
--- a/apps/desktop/src/main/secrets/providerSecretStore.ts
+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts
@@ -1,3 +1,7 @@
+import {
+ isInstalledByokProvider,
+ readByokCredential,
+} from '../model-access/byokCredentials.js';
import { app, safeStorage } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
@@ -78,6 +82,7 @@ function secretDir(): string {
}
const DYNAMIC_SECRET_PREFIXES = [
+ 'byok_cache_',
CUSTOM_MCP_SECRET_PREFIX,
CUSTOM_PROVIDER_HEADER_SECRET_PREFIX,
'provider_key_',
@@ -392,6 +397,9 @@ export function getProviderSecretStore(): ProviderSecretStore {
* 与 renderer 经通用 safe-storage IPC 写入的 .enc 文件字节级互通。
*/
export function readCustomProviderKey(providerId: string, agent: string): string | null {
+ const byok = readByokCredential(providerId, agent);
+ if (byok) return byok;
+ if (isInstalledByokProvider(providerId)) return null;
const storageProviderId = storedCustomProviderId(providerId);
try {
return electronSecretIo.read(customProviderSecretStorageKey(storageProviderId, agent));
@@ -903,3 +911,15 @@ export const genericOAuthSecretIo = {
}
},
};
+
+/** Main-only BYOK snapshot storage; key names are fixed SHA-256 identities. */
+export const byokSnapshotSecretIo = {
+ read(key: string): string | null {
+ if (!/^byok_cache_[a-f0-9]{64}$/.test(key)) return null;
+ return electronSecretIo.read(key);
+ },
+ write(key: string, value: string): boolean {
+ if (!/^byok_cache_[a-f0-9]{64}$/.test(key)) return false;
+ return electronSecretIo.write(key, value);
+ },
+};
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 084b1665c3..91e334ab62 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -67,7 +67,7 @@ export interface ApiFetchOptions {
/**
* Upstream business codes that may cross a redacted boundary. Messages and
* response bodies remain hidden; every code must be explicitly allowlisted
- * by the caller.
+ * by the caller. These codes are also safe to include in redacted logs.
*/
allowedRedactedErrorCodes?: readonly string[];
}
@@ -151,6 +151,10 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
if (!result.ok) {
const errCode = readErrorCode(result.data) ?? statusToCode(result.status);
const errMsg = readErrorMessage(result.data) ?? `请求失败 (${result.status})`;
+ const publicCode =
+ opts.redactErrorDetails && !opts.allowedRedactedErrorCodes?.includes(errCode)
+ ? statusToCode(result.status)
+ : errCode;
if (
!opts.skipSessionInvalidation && result.status === 401 &&
(errCode === 'ACCOUNT_UNAVAILABLE' ||
@@ -170,7 +174,7 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
'path=' + (opts.logLabel ?? redactedLogPath(apiPath)),
'method=' + (opts.method ?? 'GET'),
'status=' + result.status,
- 'code=' + statusToCode(result.status),
+ 'code=' + publicCode,
);
} else {
// logLabel 表示 path 里带身份;上游 `msg` 同样可能回显身份(如「skill <name> not found」),
@@ -187,9 +191,7 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
log.warn(...fields);
}
throw new ServerApiError(
- opts.redactErrorDetails && !opts.allowedRedactedErrorCodes?.includes(errCode)
- ? statusToCode(result.status)
- : errCode,
+ publicCode,
result.status,
opts.redactErrorDetails ? `请求失败 (${result.status})` : errMsg,
);
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
index f24000e170..a4657c9558 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
@@ -1092,3 +1092,21 @@ describe('subscription value and usage details', () => {
expect(details).toMatchObject({ durationMs: 1_250, turnDurationMs: 8_500 });
});
});
+describe('enterprise BYOK reported SDK costs', () => {
+ it('keeps a captured managed turn out of actual spend after logout clears the catalog', () => {
+ expect(
+ resolveTurnCost({
+ rawModel: 'deepseek-flash',
+ tokens: { inputTokens: 10, outputTokens: 5, cacheReadTokens: 0, cacheCreateTokens: 0 },
+ sdkCostDelta: 0.23,
+ pricing: {},
+ context: {
+ providerId: 'byok-removed-provider',
+ billingRoute: 'provider-api',
+ region: 'global',
+ accessKind: 'managed',
+ },
+ }),
+ ).toEqual({ model: 'deepseek-flash', money: null, source: 'reference' });
+ });
+});
diff --git a/apps/desktop/src/main/usage/referenceModelPricing.ts b/apps/desktop/src/main/usage/referenceModelPricing.ts
index 996680c70f..f9ad2994e2 100644
--- a/apps/desktop/src/main/usage/referenceModelPricing.ts
+++ b/apps/desktop/src/main/usage/referenceModelPricing.ts
@@ -15,6 +15,7 @@ import {
subscriptionDirectPriceQuote,
} from '../../shared/modelPriceQuote.js';
import type { ModelPriceQuote, ModelPricingCatalog } from '../../shared/regionalMoney.js';
+import { getByokPricing } from '../model-access/byokPricing.js';
import { getActiveCatalog } from '../maker-host/active-catalog.js';
import { accountReferencePriceQuote as providerReferencePriceQuote } from './accountReferencePrice.js';
import {
@@ -60,7 +61,7 @@ export function getReferenceModelPricing(): ModelPricingCatalog {
}
}
}
- return applyModelPriceOverrides(pricing, registry);
+ return { ...applyModelPriceOverrides(pricing, registry), ...getByokPricing() };
}
export function broadcastReferenceModelPricing(): void {
diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.ts
index d0656e1ee7..3918ecc9ce 100644
--- a/apps/desktop/src/main/usage/turnCostCalculator.ts
+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts
@@ -112,6 +112,8 @@ export interface TurnPricingContext {
providerId: string | null;
billingRoute: BillingRoute;
region: CindyRegion;
+ /** Captured when the request starts, so logout cannot reclassify an in-flight enterprise turn. */
+ accessKind?: 'subscription' | 'api' | 'managed' | null;
}
export type TurnCostSource = 'sdk' | 'gateway' | 'reference' | 'sdk-fallback' | 'subscription';
@@ -317,6 +319,13 @@ export function resolveTurnCost(args: {
context.billingRoute === 'provider-api'
? getModelPriceQuote(pricing, context.providerId, model, 'claude-code')
: undefined;
+ if (context.accessKind === 'managed') {
+ return {
+ model,
+ money: providerQuote ? computePriceQuoteTurnMoney(tokens, providerQuote, ledgerCurrency, segments) : null,
+ source: 'reference',
+ };
+ }
const hasTokenDeltas =
tokens.inputTokens > 0 ||
tokens.outputTokens > 0 ||
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index a84e63dec9..cf9dc71701 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2,6 +2,7 @@ import type { WorktreeRecycleAction, WorktreeRecycleStatus } from '../shared/wor
import { FAVORITE_HOST_READY, FAVORITE_HOST_REQUEST, FAVORITE_HOST_REPLY, FAVORITE_HOST_CHANGED, type ModelFavoritesHostApi } from '../shared/modelFavoritesSync';
import { invokeOpenPath } from './openPath';
import { COPY_PNG_TO_CLIPBOARD_CHANNEL, type CopyPngToClipboardParams } from '../shared/pngClipboard';
+import type { ByokStatus } from '../shared/modelAccess.js';
import type { LocalPluginOauthRequest, LocalPluginSecretRequest } from '../shared/pluginOauth';
import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';
import type { RoutineInput } from '@cindy/maker-scheduler';
@@ -2008,6 +2009,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ── 网关凭据自动下发(model-access,shared/modelAccess.ts) ──
modelAccess: {
+ getByokStatus: (): Promise<ByokStatus> => ipcRenderer.invoke('model-access:byok-status'),
+ retryByok: (): Promise<ByokStatus> => ipcRenderer.invoke('model-access:byok-retry'),
getStatus: (): Promise<ModelAccessStatusPayload> =>
ipcRenderer.invoke('model-access:get-status'),
retry: (): Promise<ModelAccessStatusPayload> => ipcRenderer.invoke('model-access:retry'),
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
index 0fd51c41a0..b2b8e3491d 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
@@ -835,6 +835,32 @@ describe('ProvidersSection — 深链定位', () => {
await waitFor(() => expect(screen.getByTestId('search').textContent).toBe('?tab=providers'));
});
+ it('keeps enterprise models visible inside the unified detail layout without connection editing', async () => {
+ const status = { state: 'ready', providers: [{ providerId: 'byok-team', state: 'ready' }] } as const;
+ const retryByok = vi.fn(async () => status);
+ Object.assign(window.electronAPI, {
+ modelAccess: { getByokStatus: vi.fn(async () => status), retryByok },
+ });
+ providersState.providers = [makeProvider('byok-team', {
+ name: 'Enterprise Provider', source: 'organization',
+ connected: true, agents: ['codex'], auth: { method: 'managed' },
+ models: { codex: [{
+ id: 'byok-team/company-chat', name: 'Company Chat', contextWindow: 128000,
+ efforts: [], defaultEffort: null,
+ }] },
+ })];
+ renderAt('?tab=providers&connect=byok-team&model=byok-team%2Fcompany-chat&agent=codex');
+
+ await screen.findByRole('switch', { name: 'Company Chat' });
+ await waitFor(() => expect(document.querySelector('[data-deep-link-target="true"]')).not.toBeNull());
+ expect(customDialogSpy).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'settings.providers.models.refreshAria' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'settings.providers.custom.editAria' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.byok.refresh' }));
+ await waitFor(() => expect(retryByok).toHaveBeenCalledOnce());
+ expect(updateCustomProvider).not.toHaveBeenCalled();
+ });
+
it('connect=<目录外 id> → 视为 preset id,向导 preset entry 打开', async () => {
renderAt('?tab=providers&connect=deepseek');
diff --git a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
index 5563c42534..b6e446181c 100644
--- a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
@@ -71,7 +71,7 @@ describe('remote Orca Worker creation context', () => {
// 任一远程路径都不得回退到 controller key 判定。
expect(selector).toContain('if (!deviceId) {');
expect(selector).toContain('if (subscriptionDirectDisabledReason(id)) return true;');
- expect(selector).toContain("if (provider?.source === 'user') return false;");
+ expect(selector).toContain("if (isCustomRoutedProvider(provider)) return false;");
expect(selector).toContain("return id.startsWith('codex/') && !hasSavedKey;");
expect(selector).toContain("if (remoteModelListStatus !== 'ready') return true;");
expect(selector).toContain(
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index 5250cac91b..e7dd51a891 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -108,6 +108,7 @@ import {
findCatalogModel,
nativeDefaultSourceId,
getModel,
+ isCustomRoutedProvider,
modelSupportsFastMode,
providerOffersModel,
resolveModelIconKind,
@@ -1581,7 +1582,7 @@ function ModelSelectorContentView({
// 同前缀模型由该供应商自身配置路由(codex-proxy-host 按会话显式供应商解析,
// 不按前缀落网关),不依赖 Cindy 登录/网关 key(#1568)。flat 列表(provider
// 为 null,无供应商概念)与内置来源保持原前缀判定。
- if (provider?.source === 'user') return false;
+ if (isCustomRoutedProvider(provider)) return false;
return id.startsWith('codex/') && !hasSavedKey;
}
if (remoteModelListStatus !== 'ready') return true;
diff --git a/apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts b/apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts
index a2acd2a676..e25cfd0239 100644
--- a/apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts
+++ b/apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts
@@ -1,4 +1,5 @@
import type { AgentKind, ProviderView } from '@cindy/model-providers';
+import { isCustomRoutedProvider } from '@cindy/model-providers';
import { extractIpcError } from '@/utils/ipcError';
@@ -40,7 +41,7 @@ export function buildModelWindowRecoveryToast(input: {
const model = modelDisplayName(provider, input.modelId, input.agent);
const messageKey =
- provider.source === 'user'
+ isCustomRoutedProvider(provider)
? 'newChat.chatInput.modelWindowUnknown.custom'
: 'newChat.chatInput.modelWindowUnknown.builtin';
const params = new URLSearchParams({
diff --git a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
index 91a7c1dd8b..3d3e51a393 100644
--- a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
+++ b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
@@ -60,6 +60,7 @@ import {
clampEffortToSupported,
EFFORT_VALUES,
isAgentSelectableModel,
+ isOrganizationManagedProvider,
modelProtocolComparison,
pickRecommendedAgent,
} from '@cindy/model-providers';
@@ -888,7 +889,7 @@ export function ModelAdvancedDrawer({
)}
{/* 自定义报价:原「⋯」菜单的一项,搬到它真正相关的段落里。
XD 网关的价格由服务端定,不给覆盖入口(与 IPC 侧的拒绝一致)。 */}
- {provider.id !== 'xd' && !paymentRequired && (
+ {provider.id !== 'xd' && !isOrganizationManagedProvider(provider) && !paymentRequired && (
<button
type="button"
onClick={() => setPriceDialogOpen(true)}
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 1a0843c3bf..6c19b92fe2 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -105,6 +105,7 @@ import { localCliDisplayName, type LocalCliDetection } from '../../../shared/loc
import { isBuiltinRefreshableProviderId } from '../../../shared/providerModelRefresh';
import { applyProviderOrder } from '../../../shared/providerOrder';
import type { AgentKind, CustomProviderConfig, ProviderView } from '@cindy/model-providers';
+import { isCustomRoutedProvider, isOrganizationManagedProvider } from '@cindy/model-providers';
// ---------------------------------------------------------------------------
// 工具
@@ -392,6 +393,83 @@ function useProviderManagement(provider?: ProviderView) {
return { busy, rename, removeBuiltin };
}
+function ManagedProviderHeader({
+ provider,
+ children,
+}: {
+ provider: ProviderView;
+ children?: ReactNode;
+}) {
+ const { t } = useTranslation();
+ const [busy, setBusy] = useState(false);
+ const busyRef = useRef(false);
+ const alive = useRef(true);
+ const [state, setState] = useState<'ready' | 'pending' | 'unavailable'>(
+ provider.agents.length ? 'ready' : 'pending',
+ );
+ useEffect(() => {
+ let disposed = false;
+ alive.current = true;
+ const refresh = () =>
+ void window.electronAPI.modelAccess
+ .getByokStatus()
+ .then((status) => {
+ if (!disposed) {
+ setState(
+ status.providers.find((item) => item.providerId === provider.id)?.state ??
+ 'unavailable',
+ );
+ }
+ })
+ .catch(() => undefined);
+ refresh();
+ const timer = setInterval(refresh, 5_000);
+ return () => {
+ disposed = true;
+ alive.current = false;
+ clearInterval(timer);
+ };
+ }, [provider.id]);
+ const refresh = async () => {
+ if (busyRef.current) return;
+ busyRef.current = true;
+ setBusy(true);
+ try {
+ const status = await window.electronAPI.modelAccess.retryByok();
+ if (!alive.current) return;
+ setState(
+ status.providers.find((item) => item.providerId === provider.id)?.state ?? 'unavailable',
+ );
+ if (status.state === 'failed') toast.error(t('settings.providers.byok.refreshFailed'));
+ } catch {
+ if (alive.current) toast.error(t('settings.providers.byok.refreshFailed'));
+ } finally {
+ busyRef.current = false;
+ if (alive.current) setBusy(false);
+ }
+ };
+ return (
+ <DetailHeader
+ icon={providerIcon(provider, 18)}
+ title={provider.name}
+ subtitle={t('settings.providers.byok.managed')}
+ provider={provider}
+ status={
+ state === 'ready'
+ ? { kind: 'connected' }
+ : { kind: 'neutral', label: t(`settings.providers.byok.${state}`) }
+ }
+ primaryAction={{
+ label: t('settings.providers.byok.refresh'),
+ onClick: () => void refresh(),
+ disabled: busy,
+ }}
+ >
+ {children}
+ </DetailHeader>
+ );
+}
+
function DetailHeader({
children,
icon,
@@ -434,7 +512,7 @@ function DetailHeader({
}) {
const { t } = useTranslation();
const management = useProviderManagement(provider);
- const canRename = !!provider && provider.id !== 'xd';
+ const canRename = !!provider && provider.id !== 'xd' && !isOrganizationManagedProvider(provider);
const resolvedDelete =
deleteAction ??
(provider && supportsBuiltinConnectionManagement(provider)
@@ -2208,6 +2286,10 @@ export function ProvidersSection() {
}
continue;
}
+ if (isOrganizationManagedProvider(p)) {
+ rows.push(p);
+ continue;
+ }
if (
p.source === 'user' &&
(p.id === MANAGED_OLLAMA_PROVIDER_ID ||
@@ -2597,6 +2679,7 @@ export function ProvidersSection() {
// 详情头部按供应商类型分派(鉴权逻辑与重构前一致)。
const renderDetailHeader = (p: ProviderView, children: ReactNode): ReactNode => {
+ if (isOrganizationManagedProvider(p)) return <ManagedProviderHeader key={p.id} provider={p} children={children} />;
if (p.id === 'xd')
return <XdGatewayHeader children={children} provider={p} onChanged={refetch} />;
if (p.id === 'anthropic')
@@ -2867,7 +2950,7 @@ export function ProvidersSection() {
)}
{!effectiveSelected.suspended &&
(providerHasModels(effectiveSelected) ||
- effectiveSelected.source === 'user' ||
+ isCustomRoutedProvider(effectiveSelected) ||
(isBuiltinRefreshableProviderId(effectiveSelected.id) &&
!effectiveSelected.modelDiscoveryFailure) ||
effectiveSelected.id === MANAGED_OLLAMA_PROVIDER_ID) && (
@@ -2926,7 +3009,7 @@ export function ProvidersSection() {
)}
{!effectiveSelected.suspended &&
!providerHasModels(effectiveSelected) &&
- effectiveSelected.source !== 'user' &&
+ !isCustomRoutedProvider(effectiveSelected) &&
effectiveSelected.id !== MANAGED_OLLAMA_PROVIDER_ID &&
(Boolean(effectiveSelected.modelDiscoveryFailure) ||
!isBuiltinRefreshableProviderId(effectiveSelected.id)) && (
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx
index bfb4738f99..764ff1b2f8 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx
@@ -596,3 +596,15 @@ it('limits context and effort reads, writes and resets to the chat runtime', ()
expect(mocks.setLimit).toHaveBeenCalledWith(128_000);
expect(mocks.target).toHaveBeenLastCalledWith(expect.objectContaining({ agent: 'codex', relatedTargets: [] }));
});
+it('keeps enterprise reference prices read-only in the model drawer', () => {
+ render(
+ drawer(model, model.defaultEffort, model.efforts, {
+ ...provider,
+ id: 'byok-example',
+ source: 'organization',
+ }),
+ );
+ expect(
+ screen.queryByRole('button', { name: 'settings.providers.models.priceOverride.menu' }),
+ ).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3b291cf2bc..500b3f2910 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2565,6 +2565,13 @@
"modelCount": "{{count}} models configured",
"modelsAutomatic": "Model details are imported automatically. Adjust individual models in the model list.",
"manualModel": "Model IDs (if discovery is unavailable)"
+ },
+ "byok": {
+ "managed": "Managed by your organization",
+ "refresh": "Refresh enterprise settings",
+ "refreshFailed": "Enterprise settings could not be refreshed. Try again later.",
+ "pending": "Preparing credentials",
+ "unavailable": "Temporarily unavailable"
}
},
"experimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 8c3312fba6..c152fc2624 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2564,6 +2564,13 @@
"modelCount": "{{count}} 個のモデルを設定済み",
"modelsAutomatic": "モデル情報は自動取得されます。個別の設定はモデル一覧から変更できます。",
"manualModel": "モデル ID(自動取得できない場合)"
+ },
+ "byok": {
+ "managed": "組織が接続とモデルを管理",
+ "refresh": "組織設定を更新",
+ "refreshFailed": "組織設定を更新できませんでした。しばらくしてから再試行してください。",
+ "pending": "認証情報を準備中",
+ "unavailable": "一時的に利用できません"
}
},
"experimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 97bad67dce..2c5d0cf448 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2564,6 +2564,13 @@
"modelCount": "모델 {{count}}개 설정됨",
"modelsAutomatic": "모델 정보는 자동으로 가져옵니다. 개별 설정은 모델 목록에서 변경하세요.",
"manualModel": "모델 ID (자동으로 가져올 수 없는 경우)"
+ },
+ "byok": {
+ "managed": "조직에서 연결 및 모델 관리",
+ "refresh": "조직 설정 새로고침",
+ "refreshFailed": "조직 설정을 새로고침하지 못했습니다. 나중에 다시 시도하세요.",
+ "pending": "인증 정보 준비 중",
+ "unavailable": "일시적으로 사용할 수 없음"
}
},
"experimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index f4af884334..ebc96e7212 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2564,6 +2564,13 @@
"modelCount": "已配置 {{count}} 个模型",
"modelsAutomatic": "模型资料自动获取。单个模型的设置在模型列表中调整。",
"manualModel": "模型 ID(无法自动获取时填写)"
+ },
+ "byok": {
+ "managed": "由企业管理连接与模型",
+ "refresh": "刷新企业配置",
+ "refreshFailed": "企业配置暂时无法刷新,请稍后重试。",
+ "pending": "凭据准备中",
+ "unavailable": "暂时不可用"
}
},
"experimental": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 905123c5ea..de0d450bfa 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2564,6 +2564,13 @@
"modelCount": "已設定 {{count}} 個模型",
"modelsAutomatic": "模型資料自動取得。個別模型的設定請在模型清單調整。",
"manualModel": "模型 ID(無法自動取得時填寫)"
+ },
+ "byok": {
+ "managed": "由企業管理連線與模型",
+ "refresh": "重新整理企業設定",
+ "refreshFailed": "暫時無法重新整理企業設定,請稍後再試。",
+ "pending": "憑證準備中",
+ "unavailable": "暫時無法使用"
}
},
"experimental": {
diff --git a/apps/desktop/src/renderer/lib/draftModelCalibration.ts b/apps/desktop/src/renderer/lib/draftModelCalibration.ts
index f26fd381c4..cf8491d270 100644
--- a/apps/desktop/src/renderer/lib/draftModelCalibration.ts
+++ b/apps/desktop/src/renderer/lib/draftModelCalibration.ts
@@ -14,6 +14,7 @@
import {
connectedProvidersForAgent,
effectiveSourceIdForModel,
+ isCustomRoutedProvider,
isModelSelectableForNewRoute,
nativeDefaultSourceId,
type AgentKind,
@@ -287,7 +288,7 @@ export function resolveDraftSessionProviderId({
// BYOM 来源。省略后 UI 虽显示该来源,首轮 auth gate 却会去读 gateway key,最终报
// `not authenticated: no_key`。用户来源必须始终显式钉住,保证其代理路由与密钥生效。
const effectiveProvider = providers.find((provider) => provider.id === effectiveProviderId);
- if (effectiveProvider?.source === 'user') return effectiveProviderId;
+ if (isCustomRoutedProvider(effectiveProvider)) return effectiveProviderId;
const modelDefaultProviderId = effectiveSourceIdForModel([...providers], null, model, agent);
// main 收到 providerId=null 后按 agent 的原生来源选择启动链路,而不是只在“提供当前
// 模型”的来源里重算。典型分叉:XD 与 Anthropic 都已连接,只有 Anthropic 目录含
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 7b10847929..8b2cb15d4e 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2128,6 +2128,8 @@ interface ElectronAPI {
ccSetDebugNet: (enabled: boolean) => Promise<{ ok: true }>;
/** 网关凭据自动下发(model-access,类型见 shared/modelAccess.ts)。 */
modelAccess: {
+ getByokStatus: () => Promise<import('../shared/modelAccess').ByokStatus>;
+ retryByok: () => Promise<import('../shared/modelAccess').ByokStatus>;
getStatus: () => Promise<ModelAccessStatusPayload>;
retry: () => Promise<ModelAccessStatusPayload>;
/** 轮换密钥;失败 reject(IPC 错误经 extractIpcError 解码)。 */
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index 56727a4931..883de37856 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -233,3 +233,9 @@ export interface ModelAccessModelsResponse {
accountTier?: ModelAccessAccountTier;
models: ModelAccessGatewayModel[];
}
+
+/** Secret-free enterprise connection status exposed to Settings. */
+export interface ByokStatus {
+ state: 'idle' | 'syncing' | 'ready' | 'failed';
+ providers: { providerId: string; state: 'ready' | 'pending' | 'unavailable' }[];
+}
diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.ts
index 9ce8aca250..6bd57a3b5c 100644
--- a/apps/desktop/src/shared/modelPriceQuote.ts
+++ b/apps/desktop/src/shared/modelPriceQuote.ts
@@ -122,6 +122,7 @@ export function gatewayModelPriceQuote(
model: ModelAccessGatewayModel,
fallbackCurrency: MoneyCurrency,
fallbackIsInferred = false,
+ options: { allowFreeModel?: boolean } = {},
): ModelPriceQuote | undefined {
const modelId = model.id.trim();
const inputPerMtok = perMtok(model.inputCostPerToken);
@@ -136,6 +137,7 @@ export function gatewayModelPriceQuote(
const priorityCacheReadPerMtok = perMtok(model.cacheReadInputTokenCostPriority);
const priorityInputTokenPriceBands = gatewayPriorityInputTokenPriceBands(model);
if (
+ !options.allowFreeModel &&
inputPerMtok === 0 &&
outputPerMtok === 0 &&
(cacheReadPerMtok === undefined || cacheReadPerMtok === 0) &&
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index 5b3dc95940..6114b9f7cf 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -253,6 +253,27 @@ describe('anthropic-compat-proxy loopback port guard', () => {
expect(transformResponse).toHaveBeenCalledOnce();
});
+ it.each(['reject', 'oversize', 'stale'])('does not forward a route body rewrite that is %s', async (mode) => {
+ const upstream = await startFakeUpstream((_idx, _body, res) => res.end('{}'));
+ upstreamClose = upstream.close;
+ let current = true;
+ const rewrite = vi.fn(async () => {
+ if (mode === 'reject') throw new Error('Invalid request');
+ if (mode === 'stale') current = false;
+ return { body: Buffer.from('x'.repeat(mode === 'oversize' ? 200 : 2)) };
+ });
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ maxRequestBodyBytes: 100,
+ bypassRequestTransforms: () => true,
+ routingTransform: () => ({ transformRequestBody: rewrite, dispatchGenerationValid: () => current }),
+ });
+ const result = await post(proxy.url, { model: 'test' });
+ expect(result.status).toBe(mode === 'reject' ? 502 : mode === 'oversize' ? 413 : 503);
+ expect(rewrite).toHaveBeenCalledOnce();
+ expect(upstream.bodies).toEqual([]);
+ });
+
it('can preserve an image request body without changing normal response transforms', async () => {
const upstream = await startFakeUpstream((_idx, _body, res) => {
res.writeHead(200, { 'content-type': 'application/json' });
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index af06b26d2d..bfe5690581 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -2453,6 +2453,16 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
logger,
parsedForTransforms,
);
+ if (decision?.transformRequestBody) {
+ const rewritten = await decision.transformRequestBody(
+ transformed ?? bodyForTransforms,
+ transformCtx,
+ );
+ transformed = rewritten.body;
+ if (rewritten.contentType) {
+ route.headerOverride = { ...route.headerOverride, 'content-type': rewritten.contentType };
+ }
+ }
} catch (err) {
transformsCompleted = true;
notifyTransformSettlement();
diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.ts
index ca15da6038..d7677d247f 100644
--- a/packages/anthropic-compat-proxy/src/types.ts
+++ b/packages/anthropic-compat-proxy/src/types.ts
@@ -102,6 +102,16 @@ export interface RoutingDecision {
* classifications and an HTTP status after the real upstream request starts.
*/
forwardLifecycle?: ForwardLifecycleObserver;
+ /**
+ * Optional body rewrite bound to this route, including opaque multipart requests.
+ * Runs after the JSON transform chain (even when that chain is bypassed). A rejection
+ * fails the request locally; dispatch-generation and body-size checks still apply.
+ * contentType must describe the returned bytes, including any new multipart boundary.
+ */
+ transformRequestBody?: (
+ body: Buffer,
+ ctx: RequestTransformCtx,
+ ) => { body: Buffer; contentType?: string } | Promise<{ body: Buffer; contentType?: string }>;
}
/**
diff --git a/packages/model-providers/src/__tests__/byok.test.ts b/packages/model-providers/src/__tests__/byok.test.ts
new file mode 100644
index 0000000000..880de30b7b
--- /dev/null
+++ b/packages/model-providers/src/__tests__/byok.test.ts
@@ -0,0 +1,303 @@
+import { describe, expect, it } from "vitest";
+import {
+ parseByokCredentialsResponse,
+ parseByokProvidersResponse,
+} from "../byok.js";
+
+const directory = {
+ schemaVersion: 1,
+ organizationId: "org-a",
+ revision: "1",
+ providers: [
+ {
+ id: "byok-provider-a",
+ name: "企业模型",
+ connectionRevision: 1,
+ models: [
+ {
+ nativeApi: "openai-completions",
+ id: "byok/a/chat",
+ name: "Chat",
+ currency: "CNY",
+ mode: "chat",
+ agents: ["pi"],
+ perAgent: { pi: { wireProtocol: "openai-completions" } },
+ contextWindow: 128000,
+ inputCostPerToken: 0,
+ outputCostPerToken: 0.000002,
+ },
+ ],
+ },
+ ],
+};
+const ready = {
+ providerId: "byok-provider-a",
+ connectionRevision: 1,
+ status: "ready",
+ endpoint: "https://gateway.example.invalid/v1",
+ apiKey: "invalid-test-key",
+};
+const credentials = {
+ schemaVersion: 1,
+ organizationId: "org-a",
+ credentials: [ready],
+};
+
+describe("BYOK wire contract", () => {
+ it("preserves a full Provider-prefixed model ID and rejects oversized IDs", () => {
+ const providerId = "byok-" + "p".repeat(186);
+ const id = providerId + "/" + "m".repeat(256);
+ const response = (modelId: string) => ({
+ ...directory,
+ providers: [
+ {
+ ...directory.providers[0],
+ id: providerId,
+ models: [{ ...directory.providers[0].models[0], id: modelId }],
+ },
+ ],
+ });
+ const parsed = parseByokProvidersResponse(response(id));
+ expect(parsed.ok).toBe(true);
+ if (parsed.ok) expect(parsed.value.providers[0].models[0].id).toBe(id);
+ expect(parseByokProvidersResponse(response(id + "m")).ok).toBe(false);
+ expect(parseByokProvidersResponse(response("m".repeat(257))).ok).toBe(
+ false,
+ );
+ });
+
+ it("reuses model metadata and preserves an explicit zero price", () => {
+ const result = parseByokProvidersResponse(directory);
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.value.providers[0].models[0].nativeApi).toBe(
+ "openai-completions",
+ );
+ expect(result.value.providers[0].models[0].inputCostPerToken).toBe(0);
+ expect(
+ result.value.providers[0].models[0].perAgent.pi?.wireProtocol,
+ ).toBe("openai-completions");
+ }
+ });
+ it("accepts only the strict image binding contract", () => {
+ const imageBinding = {
+ enabled: true,
+ modelId: "gpt-image-2",
+ name: "Enterprise Images",
+ supportsEdit: true,
+ wireModel: "gpt-image-2",
+ litellmModel: "byok-provider-a/gpt-image-2",
+ };
+ const response = {
+ ...directory,
+ providers: [{ ...directory.providers[0], imageBinding }],
+ };
+ const parsed = parseByokProvidersResponse(response);
+ expect(parsed.ok).toBe(true);
+ if (parsed.ok)
+ expect(parsed.value.providers[0].imageBinding).toEqual(imageBinding);
+
+ for (const malformed of [
+ { ...imageBinding, enabled: false },
+ { ...imageBinding, supportsEdit: "yes" },
+ { ...imageBinding, extra: true },
+ ]) {
+ expect(
+ parseByokProvidersResponse({
+ ...directory,
+ providers: [{ ...directory.providers[0], imageBinding: malformed }],
+ }).ok,
+ ).toBe(false);
+ }
+ });
+ it("accepts an authoritative empty directory", () => {
+ expect(parseByokProvidersResponse({ ...directory, providers: [] }).ok).toBe(
+ true,
+ );
+ });
+ it("rejects duplicate providers, reserved identities and secrets in the directory", () => {
+ expect(
+ parseByokProvidersResponse({
+ ...directory,
+ providers: [...directory.providers, ...directory.providers],
+ }).ok,
+ ).toBe(false);
+ for (const extra of [
+ { id: "xd" },
+ { apiKey: "invalid-test-key" },
+ { connectionRevision: 0 },
+ { models: [] },
+ ]) {
+ expect(
+ parseByokProvidersResponse({
+ ...directory,
+ providers: [{ ...directory.providers[0], ...extra }],
+ }).ok,
+ ).toBe(false);
+ }
+ });
+ it("rejects malformed model metadata instead of accepting a partial snapshot", () => {
+ expect(
+ parseByokProvidersResponse({
+ ...directory,
+ providers: [
+ {
+ ...directory.providers[0],
+ models: [
+ { ...directory.providers[0].models[0], currency: "UNKNOWN" },
+ ],
+ },
+ ],
+ }).ok,
+ ).toBe(false);
+ });
+ it("requires an explicit Pi protocol and rejects duplicate model IDs", () => {
+ const model = directory.providers[0].models[0];
+ for (const models of [
+ [{ ...model, perAgent: { pi: {} } }],
+ [model, model],
+ ]) {
+ expect(
+ parseByokProvidersResponse({
+ ...directory,
+ providers: [{ ...directory.providers[0], models }],
+ }).ok,
+ ).toBe(false);
+ }
+ });
+ it("accepts standalone image-generation models without chat engines", () => {
+ const result = parseByokProvidersResponse({
+ ...directory,
+ providers: [
+ {
+ ...directory.providers[0],
+ models: [
+ directory.providers[0].models[0],
+ {
+ nativeApi: "openai-images",
+ id: "byok/a/gpt-image-2",
+ name: "Draw",
+ currency: "CNY",
+ mode: "image_generation",
+ agents: [],
+ perAgent: {},
+ modalities: { input: ["text", "image"], output: ["image"] },
+ },
+ ],
+ },
+ ],
+ });
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(
+ result.value.providers[0].models.map((model) => model.mode),
+ ).toEqual(["chat", "image_generation"]);
+ expect(result.value.providers[0].models[1]?.agents).toEqual([]);
+ expect(result.value.providers[0].models[1]?.nativeApi).toBe(
+ "openai-images",
+ );
+ }
+ });
+ it("rejects image-generation models that still declare chat engines", () => {
+ expect(
+ parseByokProvidersResponse({
+ ...directory,
+ providers: [
+ {
+ ...directory.providers[0],
+ models: [
+ { ...directory.providers[0].models[0], mode: "image_generation" },
+ ],
+ },
+ ],
+ }).ok,
+ ).toBe(false);
+ });
+ it("rejects video and other gateway-unready standalone modes", () => {
+ const model = directory.providers[0].models[0];
+ for (const mode of [
+ "video_generation",
+ "audio_speech",
+ "embedding",
+ "realtime",
+ ]) {
+ expect(
+ parseByokProvidersResponse({
+ ...directory,
+ providers: [
+ {
+ ...directory.providers[0],
+ models: [{ ...model, mode, agents: [], perAgent: {} }],
+ },
+ ],
+ }).ok,
+ ).toBe(false);
+ }
+ });
+ it("accepts independently ready, pending and failed credential items", () => {
+ expect(
+ parseByokCredentialsResponse({
+ ...credentials,
+ credentials: [
+ ready,
+ {
+ providerId: "byok-provider-b",
+ connectionRevision: 2,
+ status: "pending",
+ },
+ {
+ providerId: "byok-provider-c",
+ connectionRevision: 3,
+ status: "error",
+ code: "REVOKED",
+ },
+ ],
+ }).ok,
+ ).toBe(true);
+ });
+ it("allows HTTP only for loopback inference endpoints", () => {
+ for (const endpoint of [
+ "http://127.0.0.1:32769",
+ "http://localhost:32769",
+ "http://[::1]:32769",
+ ]) {
+ expect(
+ parseByokCredentialsResponse({
+ ...credentials,
+ credentials: [{ ...ready, endpoint }],
+ }).ok,
+ ).toBe(true);
+ }
+ expect(
+ parseByokCredentialsResponse({
+ ...credentials,
+ credentials: [
+ { ...ready, endpoint: "http://gateway.example.invalid/v1" },
+ ],
+ }).ok,
+ ).toBe(false);
+ });
+ it("rejects duplicate, incomplete, ambiguous and unsafe credentials without echoing secrets", () => {
+ expect(
+ parseByokCredentialsResponse({
+ ...credentials,
+ credentials: [ready, ready],
+ }).ok,
+ ).toBe(false);
+ for (const patch of [
+ { apiKey: "" },
+ { connectionRevision: 1.5 },
+ { status: "pending" },
+ { endpoint: "http://gateway.example.invalid" },
+ { endpoint: "https://user:[email protected]/v1" },
+ { endpoint: "https://example.invalid/v1?key=secret" },
+ ]) {
+ const result = parseByokCredentialsResponse({
+ ...credentials,
+ credentials: [{ ...ready, ...patch }],
+ });
+ expect(result.ok).toBe(false);
+ expect(JSON.stringify(result)).not.toContain("invalid-test-key");
+ }
+ });
+});
diff --git a/packages/model-providers/src/__tests__/provider-identity.test.ts b/packages/model-providers/src/__tests__/provider-identity.test.ts
index 80627b3c23..17db308dff 100644
--- a/packages/model-providers/src/__tests__/provider-identity.test.ts
+++ b/packages/model-providers/src/__tests__/provider-identity.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { isLocalOnlyProviderForAgent, isOpenAiSubscriptionProvider, providerCatalogId } from '../provider-identity.js';
+import { isLocalOnlyProviderForAgent, isOpenAiSubscriptionProvider, providerCatalogId, isCustomRoutedProvider, isOrganizationManagedProvider } from '../provider-identity.js';
import type { Provider } from '../types.js';
describe('connection identity vs public catalog identity', () => {
@@ -37,3 +37,17 @@ describe('connection identity vs public catalog identity', () => {
}
});
});
+
+describe('organization vs user provider source', () => {
+ it('treats enterprise connections as custom-routed, not user-owned', () => {
+ const org = { source: 'organization' as const };
+ const user = { source: 'user' as const };
+ const builtin = { source: 'builtin' as const };
+ expect(isCustomRoutedProvider(org)).toBe(true);
+ expect(isCustomRoutedProvider(user)).toBe(true);
+ expect(isCustomRoutedProvider(builtin)).toBe(false);
+ expect(isOrganizationManagedProvider(org)).toBe(true);
+ expect(isOrganizationManagedProvider(user)).toBe(false);
+ expect(isOrganizationManagedProvider(builtin)).toBe(false);
+ });
+});
diff --git a/packages/model-providers/src/byok.ts b/packages/model-providers/src/byok.ts
new file mode 100644
index 0000000000..0be80049a2
--- /dev/null
+++ b/packages/model-providers/src/byok.ts
@@ -0,0 +1,385 @@
+import type { ModelCatalogEntry as ModelAccessGatewayModel } from "./modelAccessBean.js";
+import { parseListModelsResponse } from "./modelAccessValidator.js";
+
+export const BYOK_PROVIDERS_PATH =
+ "/api/model-access/byok/providers?schemaVersion=1";
+export const BYOK_CREDENTIALS_PATH =
+ "/api/model-access/byok/credentials?schemaVersion=1";
+
+export type ByokWireProtocol =
+ "anthropic-messages" | "openai-responses" | "openai-completions";
+export type ByokNativeApi = ByokWireProtocol | "openai-images";
+export const BYOK_IMAGE_MODE = "image_generation";
+export function isByokImageMode(mode: unknown): mode is typeof BYOK_IMAGE_MODE {
+ return mode === BYOK_IMAGE_MODE;
+}
+export function isByokSupportedMode(mode: unknown): boolean {
+ return mode === undefined || mode === "chat" || isByokImageMode(mode);
+}
+type ModelOverride = NonNullable<ModelAccessGatewayModel["perAgent"]>["pi"];
+export type ByokModel = Omit<ModelAccessGatewayModel, "perAgent"> & {
+ nativeApi?: ByokNativeApi;
+ perAgent: Partial<
+ Record<
+ "claude-code" | "codex" | "pi",
+ Omit<NonNullable<ModelOverride>, "wireProtocol"> & {
+ wireProtocol: ByokWireProtocol;
+ }
+ >
+ >;
+};
+
+export interface ByokProvider {
+ id: string;
+ name: string;
+ connectionRevision: number;
+ models: ByokModel[];
+ imageBinding?: {
+ enabled: true;
+ modelId: string;
+ name?: string;
+ supportsEdit: boolean;
+ wireModel: string;
+ litellmModel: string;
+ };
+}
+export interface ByokProvidersResponse {
+ schemaVersion: 1;
+ organizationId: string;
+ revision: string;
+ providers: ByokProvider[];
+}
+export type ByokCredential =
+ | {
+ providerId: string;
+ connectionRevision: number;
+ status: "ready";
+ endpoint: string;
+ apiKey: string;
+ }
+ | { providerId: string; connectionRevision: number; status: "pending" }
+ | {
+ providerId: string;
+ connectionRevision: number;
+ status: "error";
+ code: "UNAVAILABLE" | "REVOKED";
+ };
+/** Main-process HTTP payload. Never publish this object through IPC or a catalog. */
+export interface ByokCredentialsResponse {
+ schemaVersion: 1;
+ organizationId: string;
+ credentials: ByokCredential[];
+}
+type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };
+const fail = (error: string): Parsed<never> => ({ ok: false, error });
+const record = (value: unknown): value is Record<string, unknown> =>
+ value !== null && typeof value === "object" && !Array.isArray(value);
+const text = (value: unknown, max = 191): value is string =>
+ typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= max &&
+ value.trim() === value &&
+ !/[\u0000-\u001f\u007f]/.test(value);
+const revision = (value: unknown): value is number =>
+ typeof value === "number" && Number.isSafeInteger(value) && value > 0;
+export const isByokProviderId = (value: unknown): value is string =>
+ typeof value === "string" && /^byok-[a-z0-9][a-z0-9-]{0,185}$/.test(value);
+const fields = (value: Record<string, unknown>, allowed: string[]) =>
+ Object.keys(value).every((key) => allowed.includes(key));
+
+function envelope(
+ value: unknown,
+): value is Record<string, unknown> & { organizationId: string } {
+ return (
+ record(value) && value.schemaVersion === 1 && text(value.organizationId)
+ );
+}
+
+export function parseByokProvidersResponse(
+ value: unknown,
+): Parsed<ByokProvidersResponse> {
+ if (
+ !envelope(value) ||
+ !fields(value, [
+ "schemaVersion",
+ "organizationId",
+ "revision",
+ "providers",
+ ]) ||
+ !text(value.revision, 256) ||
+ !Array.isArray(value.providers) ||
+ value.providers.length > 100
+ ) {
+ return fail("Invalid BYOK provider directory");
+ }
+ const ids = new Set<string>();
+ const providers: ByokProvider[] = [];
+ for (const item of value.providers) {
+ if (
+ !record(item) ||
+ !fields(item, [
+ "id",
+ "name",
+ "connectionRevision",
+ "models",
+ "imageBinding",
+ ]) ||
+ !isByokProviderId(item.id) ||
+ ids.has(item.id) ||
+ !text(item.name, 128) ||
+ !revision(item.connectionRevision) ||
+ !Array.isArray(item.models) ||
+ item.models.length === 0 ||
+ item.models.length > 2000
+ ) {
+ return fail("Invalid or duplicate BYOK provider");
+ }
+ const modelInputs = item.models;
+ const transports = new Map<string, ByokWireProtocol>();
+ const nativeApis = new Map<string, ByokNativeApi>();
+ const modelIds = new Set<string>();
+ for (const model of modelInputs) {
+ if (!record(model) || !Array.isArray(model.agents)) {
+ return fail("BYOK chat models require explicit engine protocols");
+ }
+ const modelIdLimit =
+ typeof model.id === "string" && model.id.startsWith(`${item.id}/`)
+ ? 448
+ : 256;
+ if (
+ !text(model.id, modelIdLimit) ||
+ modelIds.has(model.id) ||
+ model.id.includes("*")
+ )
+ return fail("Invalid or duplicate BYOK model ID");
+ modelIds.add(model.id);
+ if (!isByokSupportedMode(model.mode))
+ return fail("BYOK only supports chat and image_generation models");
+ if (isByokImageMode(model.mode)) {
+ if (model.agents.length !== 0)
+ return fail("BYOK image models must not declare chat engines");
+ if (
+ model.perAgent !== undefined &&
+ (!record(model.perAgent) || Object.keys(model.perAgent).length !== 0)
+ ) {
+ return fail("BYOK image models must not declare engine protocols");
+ }
+ if (model.nativeApi !== undefined) {
+ if (model.nativeApi !== "openai-images")
+ return fail("Invalid BYOK image native protocol");
+ nativeApis.set(model.id, "openai-images");
+ }
+ continue;
+ }
+ if (model.agents.length === 0 || !record(model.perAgent)) {
+ return fail("BYOK chat models require explicit engine protocols");
+ }
+ if (model.nativeApi !== undefined) {
+ if (
+ ![
+ "anthropic-messages",
+ "openai-responses",
+ "openai-completions",
+ ].includes(String(model.nativeApi))
+ )
+ return fail("Invalid BYOK native protocol");
+ nativeApis.set(model.id, model.nativeApi as ByokWireProtocol);
+ }
+ for (const agent of model.agents) {
+ if (typeof agent !== "string" || !record(model.perAgent[agent]))
+ return fail("Invalid BYOK engine");
+ const protocol = (model.perAgent[agent] as Record<string, unknown>)
+ .wireProtocol;
+ const supported =
+ agent === "pi"
+ ? ["anthropic-messages", "openai-responses", "openai-completions"]
+ : agent === "claude-code"
+ ? ["anthropic-messages"]
+ : agent === "codex"
+ ? ["openai-responses"]
+ : [];
+ if (typeof protocol !== "string" || !supported.includes(protocol))
+ return fail("Unsupported BYOK engine protocol");
+ if (typeof model.id === "string")
+ transports.set(agent + ":" + model.id, protocol as ByokWireProtocol);
+ }
+ }
+ // Reuse legacy metadata validation without changing its fixed Pi transport contract.
+ // Restore the independently validated BYOK protocol after parsing.
+ const models = parseListModelsResponse({
+ schemaVersion: 4,
+ models: modelInputs.map((value, index) => {
+ const model = value as Record<string, unknown>;
+ const perAgent = record(model.perAgent) ? model.perAgent : {};
+ const { nativeApi: _nativeApi, ...metadata } = model;
+ // The shared catalog contract caps ids at 256 characters. BYOK ids may contain both a
+ // provider namespace and a full upstream id, so validate that id above and use a local
+ // surrogate while reusing the shared metadata validator.
+ return {
+ ...metadata,
+ id: `byok-model-${index}`,
+ perAgent: {
+ ...perAgent,
+ ...(perAgent.pi
+ ? {
+ pi: {
+ ...(perAgent.pi as Record<string, unknown>),
+ wireProtocol: "openai-responses",
+ },
+ }
+ : {}),
+ },
+ };
+ }),
+ });
+ if (!models.ok) return fail("Invalid BYOK model metadata");
+ ids.add(item.id);
+ const parsedModels: ByokModel[] = models.value.models.map(
+ (model, index) => {
+ const modelId = (modelInputs[index] as Record<string, unknown>)
+ .id as string;
+ const perAgent: ByokModel["perAgent"] = {};
+ for (const agent of ["claude-code", "codex", "pi"] as const) {
+ const override = model.perAgent?.[agent];
+ const wireProtocol = transports.get(agent + ":" + modelId);
+ if (override && wireProtocol)
+ perAgent[agent] = { ...override, wireProtocol };
+ }
+ return {
+ ...model,
+ id: modelId,
+ ...(nativeApis.has(modelId)
+ ? { nativeApi: nativeApis.get(modelId)! }
+ : {}),
+ perAgent,
+ };
+ },
+ );
+ let imageBinding: ByokProvider["imageBinding"];
+ if (item.imageBinding !== undefined) {
+ const binding = item.imageBinding as Record<string, unknown>;
+ if (
+ !record(binding) ||
+ !fields(binding, [
+ "enabled",
+ "modelId",
+ "name",
+ "supportsEdit",
+ "wireModel",
+ "litellmModel",
+ ]) ||
+ binding.enabled !== true ||
+ !text(binding.modelId, 256) ||
+ !text(binding.wireModel, 256) ||
+ !text(binding.litellmModel, 448) ||
+ typeof binding.supportsEdit !== "boolean" ||
+ (binding.name !== undefined && !text(binding.name, 128))
+ )
+ return fail("Invalid BYOK image binding");
+ imageBinding = {
+ enabled: true,
+ modelId: binding.modelId,
+ ...(binding.name ? { name: binding.name } : {}),
+ supportsEdit: binding.supportsEdit,
+ wireModel: binding.wireModel,
+ litellmModel: binding.litellmModel,
+ };
+ }
+ providers.push({
+ id: item.id,
+ name: item.name,
+ connectionRevision: item.connectionRevision,
+ models: parsedModels,
+ ...(imageBinding ? { imageBinding } : {}),
+ });
+ }
+ return {
+ ok: true,
+ value: {
+ schemaVersion: 1,
+ organizationId: value.organizationId,
+ revision: value.revision,
+ providers,
+ },
+ };
+}
+
+function validEndpoint(value: unknown): value is string {
+ if (!text(value, 2048)) return false;
+ try {
+ const url = new URL(value);
+ const loopbackHttp =
+ url.protocol === "http:" &&
+ (url.hostname === "localhost" ||
+ url.hostname === "127.0.0.1" ||
+ url.hostname === "[::1]");
+ return (
+ (url.protocol === "https:" || loopbackHttp) &&
+ !url.username &&
+ !url.password &&
+ !url.search &&
+ !url.hash
+ );
+ } catch {
+ return false;
+ }
+}
+
+export function parseByokCredentialsResponse(
+ value: unknown,
+): Parsed<ByokCredentialsResponse> {
+ if (
+ !envelope(value) ||
+ !fields(value, ["schemaVersion", "organizationId", "credentials"]) ||
+ !Array.isArray(value.credentials) ||
+ value.credentials.length > 100
+ ) {
+ return fail("Invalid BYOK credentials response");
+ }
+ const ids = new Set<string>();
+ const credentials: ByokCredential[] = [];
+ for (const item of value.credentials) {
+ if (
+ !record(item) ||
+ !isByokProviderId(item.providerId) ||
+ ids.has(item.providerId) ||
+ !revision(item.connectionRevision)
+ )
+ return fail("Invalid or duplicate BYOK credential");
+ const common = {
+ providerId: item.providerId,
+ connectionRevision: item.connectionRevision,
+ };
+ const allowed = ["providerId", "connectionRevision", "status"];
+ if (
+ item.status === "ready" &&
+ fields(item, [...allowed, "endpoint", "apiKey"]) &&
+ validEndpoint(item.endpoint) &&
+ text(item.apiKey, 8192)
+ ) {
+ credentials.push({
+ ...common,
+ status: "ready",
+ endpoint: item.endpoint,
+ apiKey: item.apiKey,
+ });
+ } else if (item.status === "pending" && fields(item, allowed)) {
+ credentials.push({ ...common, status: "pending" });
+ } else if (
+ item.status === "error" &&
+ fields(item, [...allowed, "code"]) &&
+ (item.code === "UNAVAILABLE" || item.code === "REVOKED")
+ ) {
+ credentials.push({ ...common, status: "error", code: item.code });
+ } else return fail("Invalid BYOK credential state");
+ ids.add(item.providerId);
+ }
+ return {
+ ok: true,
+ value: {
+ schemaVersion: 1,
+ organizationId: value.organizationId,
+ credentials,
+ },
+ };
+}
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index f96bba4fd2..a85ff9a1e6 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -7,6 +7,21 @@
* - registry:连接状态合成、按 agent 算可见性、resolveRoute 解析路由素材
*/
+export {
+ BYOK_CREDENTIALS_PATH,
+ BYOK_PROVIDERS_PATH,
+ isByokImageMode,
+ isByokProviderId,
+ parseByokCredentialsResponse,
+ parseByokProvidersResponse,
+} from './byok.js';
+export type {
+ ByokCredential,
+ ByokModel,
+ ByokProvider,
+ ByokProvidersResponse,
+} from './byok.js';
+
export type {
AgentKind,
ProviderWireProtocol,
@@ -38,7 +53,7 @@ export type {
} from "./types.js";
export { PI_MODEL_APIS, PI_REASONING_EFFORTS } from "./types.js";
-export { isLocalOnlyProviderForAgent, isOpenAiSubscriptionProvider, providerCatalogId } from './provider-identity.js';
+export { isLocalOnlyProviderForAgent, isOpenAiSubscriptionProvider, providerCatalogId, isCustomRoutedProvider, isOrganizationManagedProvider } from './provider-identity.js';
export { sourceProviderForPreset } from './providerPresetIdentity.js';
export { isMimoTokenPlanPreset } from './mimoPresentation.js';
diff --git a/packages/model-providers/src/provider-identity.ts b/packages/model-providers/src/provider-identity.ts
index f9d1d89166..ed96b7c214 100644
--- a/packages/model-providers/src/provider-identity.ts
+++ b/packages/model-providers/src/provider-identity.ts
@@ -27,3 +27,15 @@ export function providerCatalogId(provider: Pick<Provider, 'id' | 'auth'>): stri
: provider.auth.native === 'xai' ? 'xai'
: isOpenAiSubscriptionProvider(provider) ? 'openai' : provider.id;
}
+
+/** Custom-routed providers share Pi/Codex/Claude native routing and credential injection. */
+export function isCustomRoutedProvider(provider: Pick<Provider, 'source'> | null | undefined): boolean {
+ return provider?.source === 'user' || provider?.source === 'organization';
+}
+
+/** Enterprise-owned connection; only local model preferences are editable. */
+export function isOrganizationManagedProvider(
+ provider: Pick<Provider, 'source'> | null | undefined,
+): boolean {
+ return provider?.source === 'organization';
+}
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 019f199025..2e1e7ab89a 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -65,8 +65,8 @@ export type CodexCompatibilityWireProtocol = Extract<
"anthropic-messages" | "openai-chat"
>;
-/** 供应商来源:内置 vs 用户自定义(自定义本轮不实现,类型先留位)。 */
-export type ProviderSource = "builtin" | "user";
+/** 供应商来源:内置 / 用户自定义 / 企业下发。企业连接走自定义路由,但不能当个人连接编辑。 */
+export type ProviderSource = "builtin" | "user" | "organization";
/** 用户连接该供应商的鉴权方式(决定设置页的连接 UI)。
* - oauth : 走 OAuth 登录(Claude.ai 订阅 / Codex 订阅)
@@ -185,6 +185,8 @@ export interface RoutingDescriptor {
* 缺省按 false 处理;它与模型图片输入能力独立,也不得从模型名推断。
*/
supportsImageGeneration?: boolean;
+ /** Enterprise BYOK image model binding used by the Codex Images route. */
+ imageModel?: { wireModel: string; litellmModel: string; supportsEdit: boolean };
/** 真实上游 base URL(direct 时是供应商自家;gateway 时是 XD 网关 base)。 */
upstream: string;
/**
@@ -497,7 +499,7 @@ export interface Provider {
id: string;
/** 展示名。 */
name: string;
- /** 内置 vs 用户自定义。 */
+ /** 内置 / 用户自定义 / 企业下发。企业连接走自定义路由,但不能当个人连接编辑。 */
source: ProviderSource;
/** ★这家能用在哪些 agent;决定它出现在哪个 agent 的来源列表里 + 路由按哪个 agent 取。 */
agents: AgentKind[];