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。

fix(auxiliary): support direct HTTP model selections

xuzini-xznd67fb12009dd
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
index 04cb45a5bb..846c82ba29 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts
@@ -28,9 +28,11 @@ vi.mock('../managed-skills.js', () => ({
vi.mock('@cindy/maker-core', () => ({}));
+// Load the production adapter once during collection, outside each login deadline.
+import { DesktopCodexAuthAdapter } from '../auth-adapters.js';
+
describe('DesktopCodexAuthAdapter login single-flight', () => {
it('rolls back credentials when Cancel arrives during successful-login finalization', async () => {
- const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
typeof DesktopCodexAuthAdapter
>;
@@ -79,7 +81,6 @@ describe('DesktopCodexAuthAdapter login single-flight', () => {
});
it('coalesces the same mode but cancels and serializes a different mode', async () => {
- const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
typeof DesktopCodexAuthAdapter
>;
@@ -136,7 +137,6 @@ describe('DesktopCodexAuthAdapter login single-flight', () => {
});
it('lets a later logout-style cancellation cancel a queued mode switch before it starts', async () => {
- const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
typeof DesktopCodexAuthAdapter
>;
@@ -170,7 +170,6 @@ describe('DesktopCodexAuthAdapter login single-flight', () => {
});
it('restarts a cancelled same-mode login after the cancelled operation settles', async () => {
- const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
typeof DesktopCodexAuthAdapter
>;
@@ -202,7 +201,6 @@ describe('DesktopCodexAuthAdapter login single-flight', () => {
});
it('queues a mode switch behind both the cancelled login and an active logout', async () => {
- const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
typeof DesktopCodexAuthAdapter
>;
@@ -245,7 +243,6 @@ describe('DesktopCodexAuthAdapter login single-flight', () => {
});
it('queues a new login until an in-flight logout fully settles', async () => {
- const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
typeof DesktopCodexAuthAdapter
>;
@@ -280,7 +277,6 @@ describe('DesktopCodexAuthAdapter login single-flight', () => {
});
it('lets a repeated logout cancel a login queued behind the active logout', async () => {
- const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = Object.create(DesktopCodexAuthAdapter.prototype) as InstanceType<
typeof DesktopCodexAuthAdapter
>;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index e7b63061f4..2e8ea64c7f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -14533,6 +14533,7 @@ describe('usage-limit wait (ordinary tasks)', () => {
})).mockRejectedValueOnce(quota);
const transaction = createMakerSendTransaction({
getSession: () => rehydrate ? session : undefined,
+ statDirectory: async () => ({ isDirectory: () => true }),
closeSession: async () => {}, preflightBotRuntimeResources: async () => {},
getSessionMeta: async () => ({}), ensureRemoteReadyForSessionStart: async () => {},
checkWorkDirExists: async () => true, isOrcaMcpHydrated: () => !rehydrate,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts
index 993e72735e..4bd0d31281 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
+import { BUNDLED_CATALOG, buildUserProvider } from '@cindy/model-providers';
vi.mock('electron', () => ({
ipcMain: { handle: vi.fn() },
@@ -100,6 +101,23 @@ function builtinCodexCatalog() {
}
describe('auxiliary model settings IPC helpers', () => {
+ it('round-trips a Pi-only HTTP choice while retaining old catalog pins', () => {
+ const preset = BUNDLED_CATALOG.presets!.find((entry) => entry.id === 'opencode-go')!;
+ const provider = buildUserProvider({ id: 'go', name: 'Go', runtimes: {
+ pi: { ...preset.runtimes.pi!, catalogPresetId: preset.id, models: [{ id: 'deepseek-v4.1-flash', name: 'Flash' }] },
+ } }, { presets: BUNDLED_CATALOG.presets });
+ const pin = `cat:${provider.id}:pi:deepseek-v4.1-flash`;
+ const options = buildAuxiliaryModelOptions({
+ settings: { models: [PIN] }, catalog: { ...BUNDLED_CATALOG, providers: [provider] },
+ overrides: undefined, hasCredential: () => true,
+ });
+ expect(options).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: pin, defaultEnabled: true, available: true }),
+ expect.objectContaining({ id: PIN, available: false }),
+ ]));
+ expect(parseAuxiliaryModelSettingsPatch({ models: [pin, PIN] }, new Set([pin]), new Set([PIN]))).toEqual({ models: [pin, PIN] });
+ expect(() => parseAuxiliaryModelSettingsPatch({ models: ['cat:unknown:pi:model'] }, new Set([pin]))).toThrow(/not currently routable/);
+ });
it('accepts a unique models list and empty automatic reset', () => {
const allowed = new Set([PIN]);
expect(parseAuxiliaryModelSettingsPatch({ models: [PIN] }, allowed)).toEqual({
diff --git a/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts b/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts
index 398819b7bb..6d9b59d8e6 100644
--- a/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts
+++ b/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts
@@ -43,7 +43,7 @@ import { MAKER_INVOKE } from './channels.js';
const log = createLogger('maker-ipc/auxiliary-model-settings');
function toWireOption(option: TextOneshotPinOption, available: boolean): AuxiliaryModelOption {
- if (option.agentKind !== 'codex' && option.agentKind !== 'claude-code') {
+ if (option.agentKind !== 'codex' && option.agentKind !== 'claude-code' && option.agentKind !== 'pi') {
throw new Error(`unsupported auxiliary model agent: ${option.agentKind}`);
}
return {
@@ -100,11 +100,12 @@ export function buildAuxiliaryModelOptions(args: {
args.overrides,
args.providerOrder,
args.hasCredential,
+ 'auxiliary',
);
const availableIds = new Set(available.map((option) => option.id));
const result = available.map((option) => toWireOption(option, true));
- const allRoutable = buildTextOneshotPinOptions(args.catalog, args.overrides, args.providerOrder);
+ const allRoutable = buildTextOneshotPinOptions(args.catalog, args.overrides, args.providerOrder, undefined, 'auxiliary');
const allById = new Map(allRoutable.map((option) => [option.id, option]));
for (const pin of args.settings.models) {
if (availableIds.has(pin)) continue;
@@ -124,7 +125,7 @@ export function buildAuxiliaryModelOptions(args: {
if (!decoded) continue;
result.push({
id: pin,
- label: `${decoded.agentKind === 'codex' ? 'Codex' : 'Claude Code'} · ${decoded.model} · ${decoded.providerId}`,
+ label: `${decoded.agentKind === 'pi' ? 'Pi' : decoded.agentKind === 'codex' ? 'Codex' : 'Claude Code'} · ${decoded.model} · ${decoded.providerId}`,
group: decoded.providerId,
providerId: decoded.providerId,
agentKind: decoded.agentKind,
@@ -132,7 +133,7 @@ export function buildAuxiliaryModelOptions(args: {
modelName: decoded.model,
budget: false,
subscription: false,
- agentSuffix: decoded.agentKind === 'codex' ? 'Codex' : 'Claude Code',
+ agentSuffix: decoded.agentKind === 'pi' ? 'Pi' : decoded.agentKind === 'codex' ? 'Codex' : 'Claude Code',
available: false,
});
}
@@ -204,6 +205,8 @@ export function registerAuxiliaryModelSettingsIpc(): void {
getActiveCatalog(),
readModelDisableOverrides(),
readProviderOrder(),
+ undefined,
+ 'auxiliary',
).map((option) => option.id),
);
const patch = parseAuxiliaryModelSettingsPatch(
diff --git a/apps/desktop/src/main/utility-model/__tests__/auxiliaryDirectRoutes.test.ts b/apps/desktop/src/main/utility-model/__tests__/auxiliaryDirectRoutes.test.ts
new file mode 100644
index 0000000000..13e202f338
--- /dev/null
+++ b/apps/desktop/src/main/utility-model/__tests__/auxiliaryDirectRoutes.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+import { BUNDLED_CATALOG, buildUserProvider, type AgentKind } from '@cindy/model-providers';
+import { buildTextOneshotPinOptions, decodeCatalogPin } from '../textOneshotPinOptions.js';
+import { resolveDirectTextRoute } from '../directTextRoute.js';
+import { normalizeAuxiliaryModelList } from '../../../shared/auxiliaryModelSettings.js';
+
+const modelId = 'deepseek-v4.1-flash';
+const preset = BUNDLED_CATALOG.presets!.find((entry) => entry.id === 'opencode-go')!;
+
+function go(agents: AgentKind[] = ['claude-code', 'codex', 'pi'], enabled?: boolean) {
+ return buildUserProvider({ id: 'go', name: 'OpenCode Go', runtimes: Object.fromEntries(
+ agents.map((agent) => [agent, {
+ ...preset.runtimes[agent], catalogPresetId: preset.id,
+ models: [{ id: modelId, name: 'DeepSeek', ...(enabled !== undefined ? { defaultEnabled: enabled } : {}) }],
+ }]),
+ ) }, { presets: BUNDLED_CATALOG.presets });
+}
+
+describe('auxiliary direct HTTP admission', () => {
+ it.each([['pi'], ['claude-code', 'codex', 'pi']] as AgentKind[][])(
+ 'offers Go Flash without enabling chat compatibility (%j)', (...agents) => {
+ const provider = go(agents);
+ const catalog = { ...BUNDLED_CATALOG, providers: [provider] };
+ const before = structuredClone(provider);
+ const options = buildTextOneshotPinOptions(catalog, undefined, undefined, () => true, 'auxiliary');
+ expect(options).toHaveLength(agents.length);
+ expect(options.every((option) => option.defaultEnabled)).toBe(true);
+ expect(normalizeAuxiliaryModelList(options.map((option) => option.id))).toEqual(options.map((option) => option.id));
+ expect(provider).toEqual(before);
+ if (agents.includes('codex')) expect(provider.models.codex![0].defaultEnabled).toBe(false);
+ for (const option of options) {
+ expect(resolveDirectTextRoute(provider, option.agentKind, provider.models[option.agentKind]![0])).toMatchObject({
+ upstream: 'https://opencode.ai/zen/go/v1', wireProtocol: 'openai-chat',
+ });
+ }
+ },
+ );
+
+ it('preserves explicit model defaults, disable overrides, credentials and plugin admission', () => {
+ const provider = go(['pi'], false);
+ const catalog = { ...BUNDLED_CATALOG, providers: [provider] };
+ expect(buildTextOneshotPinOptions(catalog, undefined, undefined, () => true, 'auxiliary')[0].defaultEnabled).toBe(false);
+ expect(buildTextOneshotPinOptions(catalog, undefined, undefined, () => false, 'auxiliary')).toEqual([]);
+ expect(buildTextOneshotPinOptions(catalog, { disabledModels: { [`${provider.id}:${modelId}`]: true } }, undefined, () => true, 'auxiliary')).toEqual([]);
+ expect(buildTextOneshotPinOptions(catalog, { disabledProviders: { [provider.id]: true } }, undefined, () => true, 'auxiliary')).toEqual([]);
+ expect(buildTextOneshotPinOptions(catalog, undefined)).toEqual([]);
+ expect(decodeCatalogPin('cat:go:pi:deepseek-v4.1-flash')).toBeNull();
+ });
+
+ it.each(['google-generative-ai', 'bedrock-converse-stream', 'azure-openai-responses'] as const)(
+ 'does not offer unsupported SDK API %s even when the connection defaults to Chat', (api) => {
+ const provider = go(['pi']);
+ provider.models.pi![0].api = api;
+ expect(buildTextOneshotPinOptions({ ...BUNDLED_CATALOG, providers: [provider] }, undefined, undefined, () => true, 'auxiliary')).toEqual([]);
+ },
+ );
+
+ it('pairs model protocol, address and path without inheriting the connection path', () => {
+ const provider = go(['codex']);
+ provider.routing.codex!.requestPath = '/old/chat';
+ const model = provider.models.codex![0];
+ model.api = 'anthropic-messages';
+ model.route = { baseUrl: 'https://messages.example', wireProtocol: 'anthropic-messages', requestPath: '/tenant/messages' };
+ expect(resolveDirectTextRoute(provider, 'codex', model)).toMatchObject({
+ upstream: 'https://messages.example', wireProtocol: 'anthropic-messages', requestPath: '/tenant/messages',
+ });
+ delete model.route.requestPath;
+ expect(resolveDirectTextRoute(provider, 'codex', model)?.requestPath).toBeUndefined();
+ });
+
+ it('inherits the connection path only while the effective address and protocol are unchanged', () => {
+ const provider = go(['codex']);
+ const routing = provider.routing.codex!;
+ routing.requestPath = '/tenant/completions';
+ const model = provider.models.codex![0];
+ expect(model.route?.baseUrl).toBe(routing.upstream);
+ expect(resolveDirectTextRoute(provider, 'codex', model)?.requestPath).toBe('/tenant/completions');
+ model.route!.requestPath = '/model/completions';
+ expect(resolveDirectTextRoute(provider, 'codex', model)?.requestPath).toBe('/model/completions');
+ delete model.route!.requestPath;
+ model.route!.baseUrl = 'https://other.example/v1';
+ expect(resolveDirectTextRoute(provider, 'codex', model)?.requestPath).toBeUndefined();
+ model.route!.baseUrl = routing.upstream;
+ model.route!.wireProtocol = 'openai-responses';
+ model.api = 'openai-responses';
+ expect(resolveDirectTextRoute(provider, 'codex', model)?.requestPath).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
index b826b4000b..e61e350073 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -100,11 +100,11 @@ vi.mock('../../model-access/gatewayKeyRejection.js', () => ({
}));
import type { Maker } from '@cindy/maker-core';
-import { buildUserProvider } from '@cindy/model-providers';
// model-compat's own profile table; one test adds a temporary gateway-object
// profile because the only real one (cline-pass) shares its address with a
// conflicting profile and never resolves.
import upstreamProfiles from '../../../../../../packages/model-compat/src/upstream-profiles.json';
+import { BUNDLED_CATALOG, buildUserProvider, type PiModelApi } from '@cindy/model-providers';
import { DictationDictionaryAdvisor } from '@cindy/voice-input-core';
import { DictionaryLearningTextModelClient } from '../../voice-input/DictionaryLearningTextModelClient.js';
import { fetch as undiciFetch } from 'undici';
@@ -124,6 +124,7 @@ import { readCustomProviderKey } from '../../secrets/providerSecretStore.js';
import { reportCindyGatewayKeyRejected } from '../../model-access/gatewayKeyRejection.js';
import { getUtilityModelChainProfiles } from '../UtilityModelSelection.js';
import { parseAutoPermissionReviewDecision } from '../../maker-host/auto-permission-reviewer.js';
+import { decodeCatalogPin } from '../textOneshotPinOptions.js';
import {
DEDICATED_AUTO_REVIEW_CANDIDATES,
createCustomAutoReviewFallback,
@@ -1170,6 +1171,122 @@ describe('utility one-shot candidates', () => {
});
});
+ it('dispatches a saved Pi-only Go Flash auxiliary selection without launching an agent', async () => {
+ const preset = BUNDLED_CATALOG.presets!.find((entry) => entry.id === 'opencode-go')!;
+ const provider = buildUserProvider({ id: 'go', name: 'Go', runtimes: {
+ pi: { ...preset.runtimes.pi!, catalogPresetId: preset.id, models: [{ id: 'deepseek-v4.1-flash', name: 'Flash' }] },
+ } }, { presets: BUNDLED_CATALOG.presets });
+ activeCatalog.mockReturnValue({ ...BUNDLED_CATALOG, providers: [provider] });
+ chainState.source = 'custom';
+ chainState.refs = [`cat:${provider.id}:pi:deepseek-v4.1-flash`];
+ readCustomKey.mockReturnValue('test-key');
+ fetchMock.mockResolvedValueOnce({ ok: true, text: async () => JSON.stringify({ choices: [{ message: { content: 'title' } }] }) } as never);
+ const maker = makerMock(false);
+ expect(await requestUtilityText(maker, 'hello', { maxTokens: 80 })).toMatchObject({ ok: true, text: 'title', providerId: provider.id });
+ expect(maker.oneShot).not.toHaveBeenCalled();
+ expect(readCustomKey).toHaveBeenCalledWith(provider.id, 'pi');
+ expect(fetchMock.mock.calls[0][0]).toBe('https://opencode.ai/zen/go/v1/chat/completions');
+ expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toMatchObject({ model: 'deepseek-v4.1-flash', max_tokens: 80 });
+ });
+
+ it.each([
+ ['claude-code', 'openai-completions', 'openai-chat', '/chat/completions'],
+ ['codex', 'anthropic-messages', 'anthropic-messages', '/v1/messages'],
+ ['pi', 'openai-responses', 'openai-responses', '/responses'],
+ ] as const)('uses the model API instead of the %s connection default (%s)', async (agent, api, wireProtocol, path) => {
+ const provider = {
+ id: 'mixed', name: 'Mixed', source: 'user', agents: [agent], auth: { method: 'apiKey' },
+ routing: { [agent]: { upstream: 'https://default.example', authStrategy: 'api-key-header', wireProtocol: 'openai-chat', requestPath: '/old' } },
+ models: { [agent]: [{ id: 'model', name: 'Model', mode: 'chat', api, route: { baseUrl: 'https://model.example', wireProtocol } }] },
+ };
+ activeCatalog.mockReturnValue({ providers: [provider] } as never);
+ readCustomKey.mockReturnValue('test-key');
+ fetchMock.mockResolvedValueOnce({ ok: true, text: async () => JSON.stringify({
+ choices: [{ message: { content: 'answer' } }], content: [{ type: 'text', text: 'answer' }], output_text: 'answer',
+ }) } as never);
+ const result = await requestUtilityText(makerMock(false), 'hello', { providerId: 'mixed', agentKind: agent, model: 'model' });
+ expect(result).toMatchObject({ ok: true, text: 'answer' });
+ expect(fetchMock.mock.calls[0][0]).toBe(`https://model.example${path}`);
+ const body = JSON.parse(String(fetchMock.mock.calls[0][1]?.body));
+ expect(api === 'openai-responses' ? body.input : body.messages).toBeDefined();
+ });
+
+ it.each([
+ ['codex', 'openai-chat', 'openai-completions', 'plugin-pin'],
+ ['claude-code', 'anthropic-messages', 'anthropic-messages', 'plugin-pin'],
+ ['codex', 'openai-chat', 'openai-completions', 'auxiliary-chain'],
+ ['claude-code', 'anthropic-messages', 'anthropic-messages', 'auxiliary-chain'],
+ ] as const)('retains the connection custom path for %s/%s via %s/%s', async (agent, wireProtocol, api, entry) => {
+ const baseUrl = 'https://custom-path.example';
+ const provider = buildUserProvider({ id: 'custom-path', name: 'Custom path', runtimes: {
+ [agent]: { baseUrl, wireProtocol, requestPath: '/tenant/infer?mode=fast', models: [{
+ id: 'model', name: 'Model', api, route: { baseUrl, wireProtocol },
+ }] },
+ } });
+ activeCatalog.mockReturnValue({ providers: [provider] } as never);
+ readCustomKey.mockReturnValue('test-key');
+ fetchMock.mockResolvedValueOnce({ ok: true, text: async () => JSON.stringify({
+ choices: [{ message: { content: 'answer' } }], content: [{ type: 'text', text: 'answer' }],
+ }) } as never);
+ const pin = `cat:${provider.id}:${agent}:model`;
+ chainState.source = 'custom';
+ chainState.refs = [pin];
+ // Plugin catalog pins use the decoded explicit route; unpinned plugins and
+ // host auxiliary callers follow the shared saved chain.
+ const options = entry === 'plugin-pin' ? decodeCatalogPin(pin)! : undefined;
+ expect(await requestUtilityText(makerMock(false), 'hello', options)).toMatchObject({ ok: true, text: 'answer' });
+ expect(fetchMock.mock.calls[0][0]).toBe('https://custom-path.example/tenant/infer?mode=fast');
+ });
+
+ it('continues from a failed Pi HTTP route to the saved legacy fallback', async () => {
+ const provider = buildUserProvider({ id: 'http-chain', name: 'HTTP', runtimes: {
+ pi: { baseUrl: 'https://primary.example/v1', wireProtocol: 'openai-chat', models: [{ id: 'primary', name: 'Primary' }] },
+ codex: { baseUrl: 'https://backup.example/v1', wireProtocol: 'openai-responses', models: [{ id: 'backup', name: 'Backup' }] },
+ } });
+ activeCatalog.mockReturnValue({ providers: [provider] } as never);
+ chainState.source = 'custom';
+ chainState.refs = [`cat:${provider.id}:pi:primary`, `cat:${provider.id}:codex:backup`];
+ readCustomKey.mockReturnValue('test-key');
+ fetchMock.mockResolvedValueOnce({ ok: false, status: 503, text: async () => '' } as never);
+ fetchMock.mockResolvedValueOnce({ ok: true, text: async () => JSON.stringify({ output_text: 'fallback' }) } as never);
+ expect(await requestUtilityText(makerMock(false), 'hello')).toMatchObject({ ok: true, model: 'backup', text: 'fallback' });
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(['https://primary.example/v1/chat/completions', 'https://backup.example/v1/responses']);
+ });
+
+ it.each(['model-disabled', 'provider-disabled', 'model-route-changed', 'credential-changed'] as const)(
+ 'rechecks a saved Pi HTTP choice before sending (%s)', async (change) => {
+ const provider = buildUserProvider({ id: 'live-http', name: 'HTTP', runtimes: {
+ pi: { baseUrl: 'https://original.example/v1', wireProtocol: 'openai-chat', models: [{ id: 'model', name: 'Model' }] },
+ } });
+ activeCatalog.mockReturnValue({ providers: [provider] } as never);
+ readCustomKey.mockReturnValue('test-key');
+ const result = await requestUtilityText(makerMock(false), 'hello', {
+ providerId: provider.id, agentKind: 'pi', model: 'model',
+ beforeDispatch: async () => {
+ if (change === 'model-disabled') readDisableOverrides.mockReturnValue({ disabledModels: { [`${provider.id}:model`]: true } });
+ if (change === 'provider-disabled') readDisableOverrides.mockReturnValue({ disabledProviders: { [provider.id]: true } });
+ if (change === 'model-route-changed') provider.models.pi![0].route = { baseUrl: 'https://changed.example/v1', wireProtocol: 'openai-chat' };
+ if (change === 'credential-changed') readCustomKey.mockReturnValue('different-test-key');
+ return true;
+ },
+ });
+ expect(result.ok).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['google-generative-ai', 'bedrock-converse-stream'] as PiModelApi[])(
+ 'does not dispatch an unsupported model API %s through the connection Chat default', async (api) => {
+ const provider = buildUserProvider({ id: 'sdk', name: 'SDK', runtimes: {
+ pi: { baseUrl: 'https://sdk.example/v1', wireProtocol: 'openai-chat', models: [{ id: 'model', name: 'Model', api }] },
+ } });
+ activeCatalog.mockReturnValue({ providers: [provider] } as never);
+ readCustomKey.mockReturnValue('test-key');
+ expect(await requestUtilityText(makerMock(false), 'hello', { providerId: provider.id, agentKind: 'pi', model: 'model' })).toMatchObject({ ok: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ },
+ );
+
it('rejects a retired model pinned to an explicit auxiliary route', async () => {
activeCatalog.mockReturnValue({
providers: [{
diff --git a/apps/desktop/src/main/utility-model/directTextRoute.ts b/apps/desktop/src/main/utility-model/directTextRoute.ts
new file mode 100644
index 0000000000..134a8c473c
--- /dev/null
+++ b/apps/desktop/src/main/utility-model/directTextRoute.ts
@@ -0,0 +1,38 @@
+import {
+ isOpenAiSubscriptionProvider,
+ resolvePiModelRoute,
+ type AgentKind,
+ type CatalogModel,
+ type Provider,
+ type RoutingDescriptor,
+} from '@cindy/model-providers';
+
+/** Subscription adapters own their endpoints and authentication; never treat them as BYOK. */
+export function usesDirectTextRoute(provider: Provider): boolean {
+ return provider.source !== 'builtin'
+ && !isOpenAiSubscriptionProvider(provider)
+ && provider.auth.native !== 'claude'
+ && provider.auth.native !== 'xai';
+}
+
+/** Shared by auxiliary selection and HTTP dispatch. The runtime identifies the stored
+ * connection/credential, not an agent process to launch. Reuse the portable API resolver
+ * so SDK-only APIs cannot accidentally fall through to Responses. */
+export function resolveDirectTextRoute(
+ provider: Provider,
+ agent: AgentKind,
+ model: CatalogModel | undefined,
+): RoutingDescriptor | null {
+ const routing = provider.routing[agent];
+ if (!provider.agents.includes(agent) || !routing || routing.disabled) return null;
+ if (!['api-key-header', 'oauth-token', 'none'].includes(routing.authStrategy)) return null;
+ const defaultWire = routing.wireProtocol
+ ?? (agent === 'claude-code' ? 'anthropic-messages' : agent === 'codex' ? 'openai-responses' : undefined);
+ const target = resolvePiModelRoute(model, { baseUrl: routing.upstream, wireProtocol: defaultWire });
+ if (!target?.baseUrl.trim()) return null;
+ // Retain legacy connection paths when the model restates the same target.
+ // An endpoint or protocol switch must not inherit a path for a different API.
+ const requestPath = target.requestPath
+ ?? (target.baseUrl === routing.upstream && target.wireProtocol === defaultWire ? routing.requestPath : undefined);
+ return { ...routing, upstream: target.baseUrl, wireProtocol: target.wireProtocol, requestPath };
+}
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index 9515e12378..8c7d0b1e04 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -56,6 +56,7 @@ import {
type UtilityReasoningMode,
type UtilityRequestStep,
} from './utilityReasoningPlan.js';
+import { resolveDirectTextRoute, usesDirectTextRoute } from './directTextRoute.js';
import { getUtilityModelProfile, isUtilityModelProviderKind } from '../../shared/utilityModelProfiles.js';
import type { UtilityModelProfile, UtilityModelTransport } from '../../shared/utilityModelProfiles.js';
import type {
@@ -898,12 +899,18 @@ async function requestExplicitProviderText(
// which would silently turn a Claude request into a Codex request.
const model = requestedModel || configuredModels.find((item) =>
isModelSelectableForNewRoute(item, { userProvider: provider?.source === 'user' }))?.id || '';
+ const catalogModel = configuredModels.find((item) => item.id === model);
// 预设身份随模型投影带出:从 OpenCode Go 预设创建后再改地址/复制连接时,运行时 id 与
// URL 都可能对不上,补会话头仍要认得出来(见 opencode-go-session.ts 的三路识别)。
- const catalogPresetId = configuredModels.find((item) => item.id === model)?.catalogPresetId;
- const selectedRouting = agentKind ? provider?.routing[agentKind] : undefined;
+ const catalogPresetId = catalogModel?.catalogPresetId;
+ const selectedRouting = provider && agentKind
+ ? usesDirectTextRoute(provider)
+ ? resolveDirectTextRoute(provider, agentKind, catalogModel)
+ : provider.routing[agentKind]
+ : undefined;
const transport: UtilityModelTransport =
- agentKind === 'codex' && selectedRouting?.wireProtocol !== 'openai-chat'
+ selectedRouting?.wireProtocol === 'openai-responses'
+ || (agentKind === 'codex' && selectedRouting?.wireProtocol === undefined)
? 'codex-responses'
: 'litellm-chat-completions';
@@ -966,6 +973,9 @@ async function requestExplicitProviderText(
// 见 requestBuiltinProviderText 开头)。Codex 2026-08-06。
const routeSnapshot = stableSnapshot({
routing: selectedRouting,
+ configuredRouting: provider.routing[agentKind],
+ modelRoute: catalogModel?.route,
+ modelApi: catalogModel?.api ?? catalogModel?.piApi,
auth: provider.auth,
source: provider.source,
});
@@ -981,13 +991,17 @@ async function requestExplicitProviderText(
!isModelSelectableForNewRoute(currentModel, { userProvider: currentProvider.source === 'user' })
) return false;
return stableSnapshot({
- routing: currentProvider.routing[agentKind],
+ routing: usesDirectTextRoute(currentProvider)
+ ? resolveDirectTextRoute(currentProvider, agentKind, currentModel)
+ : currentProvider.routing[agentKind],
+ configuredRouting: currentProvider.routing[agentKind],
+ modelRoute: currentModel.route,
+ modelApi: currentModel.api ?? currentModel.piApi,
auth: currentProvider.auth,
source: currentProvider.source,
}) === routeSnapshot;
};
- const catalogModel = provider.models[agentKind]?.find((m) => m.id === model);
if (opts.maxTokens !== undefined && catalogModel?.maxOutput !== undefined) {
opts = { ...opts, maxTokens: Math.min(opts.maxTokens, catalogModel.maxOutput) };
}
@@ -1012,8 +1026,8 @@ async function requestExplicitProviderText(
});
}
- const routing = provider.routing[agentKind];
- if (routing?.disabled) {
+ const routing = selectedRouting;
+ if (!routing || routing.disabled) {
return {
ok: false,
reason: 'no_candidate',
@@ -1148,6 +1162,7 @@ function inferProviderAgent(provider: ReturnType<typeof getActiveCatalog>['provi
if (!provider) return undefined;
if (provider.agents.includes('codex')) return 'codex';
if (provider.agents.includes('claude-code')) return 'claude-code';
+ if (provider.agents.includes('pi')) return 'pi';
return undefined;
}
@@ -2322,7 +2337,8 @@ async function requestCustomProviderText(input: {
'Content-Type': 'application/json',
};
const wire: ProviderWire =
- input.agentKind === 'claude-code' || input.wireProtocol === 'anthropic-messages'
+ input.wireProtocol === 'anthropic-messages'
+ || (input.wireProtocol === undefined && input.agentKind === 'claude-code')
? 'anthropic-messages'
: input.wireProtocol === 'openai-chat'
? 'chat-completions'
diff --git a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
index a00992f9cf..f77184d998 100644
--- a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
+++ b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
@@ -28,12 +28,13 @@ import {
} from '@cindy/model-providers';
import { applyProviderOrder } from '../../shared/providerOrder.js';
+import { resolveDirectTextRoute, usesDirectTextRoute } from './directTextRoute.js';
import {
decodeCatalogModelPin,
encodeCatalogModelPin,
} from '../../shared/catalogModelPin.js';
-/** oneshot 可路由的 agent(Pi 的 oneShot 未实现,不进钉档清单)。 */
+/** Legacy plugin pins retain the Agent.oneShot allowlist; auxiliary HTTP routes are resolved separately. */
const ONESHOT_ROUTE_AGENTS = ['codex', 'claude-code'] as const;
/**
@@ -66,7 +67,9 @@ export function encodeCatalogPin(providerId: string, agentKind: AgentKind, model
export function decodeCatalogPin(
raw: string,
): { providerId: string; agentKind: AgentKind; model: string } | null {
- return decodeCatalogModelPin(raw);
+ const route = decodeCatalogModelPin(raw);
+ // Plugin pins retain their existing allowlist; auxiliary settings also support Pi HTTP routes.
+ return route?.agentKind === 'pi' ? null : route;
}
/**
@@ -105,9 +108,10 @@ function isChatModel(model: CatalogModel, provider: Provider): boolean {
return isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' });
}
-const AGENT_LABEL: Record<(typeof ONESHOT_ROUTE_AGENTS)[number], string> = {
+const AGENT_LABEL: Record<AgentKind, string> = {
codex: 'Codex',
'claude-code': 'Claude Code',
+ pi: 'Pi',
};
/**
@@ -148,7 +152,7 @@ export interface TextOneshotPinOption {
subscription: boolean;
/** 供应商路由描述(渲染层厂牌图标判定用,ProviderLogoMark)。 */
routing?: Provider['routing'];
- /** 该精确路由使用的 Agent('Codex' / 'Claude Code')。 */
+ /** Configuration source of the exact route; direct auxiliary requests launch no Agent. */
agentSuffix: string;
}
@@ -194,23 +198,27 @@ export function buildTextOneshotPinOptions(
overrides: ModelDisableOverrides | undefined,
providerOrder?: readonly string[],
hasCredential?: OneshotCredentialProbe,
+ purpose: 'plugin' | 'auxiliary' = 'plugin',
): TextOneshotPinOption[] {
- const entries: { provider: Provider; agentKind: (typeof ONESHOT_ROUTE_AGENTS)[number]; model: CatalogModel }[] = [];
+ const entries: { provider: Provider; agentKind: AgentKind; model: CatalogModel; direct: boolean }[] = [];
const seenRoutes = new Set<string>();
for (const provider of orderedProviders(catalog, providerOrder)) {
if (isProviderDisabled(overrides, provider.id)) continue;
- // Agent 决定模型可见性和实际 wire。即使内置供应商的两条路由最终共享
- // 凭证或上游,也分别展示并保存,让用户选择一组确定的 Agent + Model。
- for (const agentKind of ONESHOT_ROUTE_AGENTS) {
- if (!isRoutableForOneshot(provider, agentKind)) continue;
+ // Keep the configuration source in each pin: runtimes can have different
+ // credentials or endpoints even when the provider and model ids match.
+ const direct = purpose === 'auxiliary' && usesDirectTextRoute(provider);
+ const agents: readonly AgentKind[] = direct ? ['codex', 'claude-code', 'pi'] : ONESHOT_ROUTE_AGENTS;
+ for (const agentKind of agents) {
+ if (!direct && !isRoutableForOneshot(provider, agentKind)) continue;
if (hasCredential && !hasCredential(provider, agentKind)) continue;
for (const model of displayOrderedModels(provider.models[agentKind] ?? [])) {
+ if (direct && !resolveDirectTextRoute(provider, agentKind, model)) continue;
if (!isChatModel(model, provider)) continue;
if (isModelDisabled(overrides, provider.id, model.id)) continue;
const routeKey = `${provider.id}\n${agentKind}\n${model.id}`;
if (seenRoutes.has(routeKey)) continue;
seenRoutes.add(routeKey);
- entries.push({ provider, agentKind, model });
+ entries.push({ provider, agentKind, model, direct });
}
}
}
@@ -218,14 +226,16 @@ export function buildTextOneshotPinOptions(
const providerName = displayProviderName(e.provider);
const base = `${e.model.name} · ${providerName}`;
return {
- id: encodeCatalogPin(e.provider.id, e.agentKind, e.model.id),
+ id: encodeCatalogModelPin({ providerId: e.provider.id, agentKind: e.agentKind, model: e.model.id }),
label: `${AGENT_LABEL[e.agentKind]} · ${base}`,
group: providerName,
providerId: e.provider.id,
agentKind: e.agentKind,
modelId: e.model.id,
modelName: e.model.name,
- ...(e.model.defaultEnabled !== undefined ? { defaultEnabled: e.model.defaultEnabled } : {}),
+ ...(e.direct
+ ? { defaultEnabled: e.model.userModelConfig?.defaultEnabled ?? true }
+ : e.model.defaultEnabled !== undefined ? { defaultEnabled: e.model.defaultEnabled } : {}),
...(e.model.icon !== undefined ? { icon: e.model.icon } : {}),
budget: classifyModel(e.model) === 'gpt-budget',
subscription: e.provider.access?.kind === 'subscription',
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
index 8df45f5285..a5a0e31d0d 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
@@ -74,6 +74,21 @@ describe('OneshotModelPinPicker shared A adapter', () => {
const mount = (extra = {}) => render(<OneshotModelPinPicker defaultOptionLabel="Automatic"
options={options} onChange={vi.fn()} ariaLabel="Auxiliary model" {...extra} />);
+ it('selects an approved Pi HTTP auxiliary route and retains an unavailable saved Pi route', async () => {
+ const option: OneshotPinOption = { ...options[0], id: 'cat:go:pi:deepseek-v4.1-flash',
+ providerId: 'go', group: 'OpenCode Go', agentKind: 'pi', modelId: 'deepseek-v4.1-flash', modelName: 'DeepSeek' };
+ const onChange = vi.fn();
+ const view = mount({ options: [option], onChange });
+ expect(picker.providersOverride?.[0].models.pi?.[0].id).toBe('deepseek-v4.1-flash');
+ expect(await picker.onUnifiedSelect!({ providerId: 'go', modelId: 'deepseek-v4.1-flash', engine: 'pi', fast: false, favoriteUid: null })).toBe(true);
+ expect(onChange).toHaveBeenCalledWith(option.id);
+ view.unmount();
+ mount({ options: [], value: option.id });
+ expect(picker.currentProviderId).toBe('go');
+ expect(picker.vendorKey).toBe('pi');
+ expect(picker.sourceDisconnected).toBe(true);
+ });
+
it('uses the shared picker with all host-approved routes, without a separate Agent step', () => {
mount();
expect(screen.getByTestId('shared-picker')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx
index eff4f577cc..9e0be4722b 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx
@@ -8,6 +8,7 @@ import type {
AuxiliaryModelSettingsState,
} from '../../../../shared/auxiliaryModelSettings';
import { AUTO_AUXILIARY_MODEL_CHAIN } from '../../../../shared/auxiliaryModelChain';
+import * as visibility from '@/state/modelVisibilityPrefs';
const PREFERRED_PIN = 'cat:openrouter:codex:openai/gpt-5-mini';
const FALLBACK_PIN = 'cat:anthropic:claude-code:claude-haiku-4-5';
@@ -65,7 +66,7 @@ vi.mock('@/cindy-brain/OneshotModelPinPicker', () => ({
{`${Boolean(groupByProvider)}:${options.map((option) => option.group).join(',')}`}
</span>
{options.map((option) => (
- <span key={option.id} data-testid={`${ariaLabel}:option:${option.id}`} />
+ <span key={option.id} data-testid={`${ariaLabel}:option:${option.id}`} data-available={option.available} />
))}
<button
type="button"
@@ -210,6 +211,21 @@ describe('AuxiliaryModelSection', () => {
expect(screen.queryByText('settings.auxiliaryModels.preferred.label')).toBeNull();
});
+ it.each([true, false])('keeps user visibility authoritative for a Pi HTTP choice (%s)', async (visible) => {
+ const option: AuxiliaryModelOption = { ...SUPPLIER_OPTIONS[0], id: 'cat:go:pi:deepseek-v4.1-flash',
+ providerId: 'go', agentKind: 'pi', modelId: 'deepseek-v4.1-flash', defaultEnabled: true };
+ const override = vi.spyOn(visibility, 'isModelEnabled').mockReturnValue(visible);
+ try {
+ h.get.mockResolvedValue(state({ models: [option.id], options: [option] }));
+ render(<AuxiliaryModelSection />);
+ const row = await screen.findByTestId(`settings.auxiliaryModels.preferred.ariaLabel:option:${option.id}`);
+ expect(row.getAttribute('data-available')).toBe(String(visible));
+ expect(override).toHaveBeenCalledWith('pi', 'go', { id: 'deepseek-v4.1-flash', defaultEnabled: true });
+ } finally {
+ override.mockRestore();
+ }
+ });
+
it('treats a GET payload without models as automatic instead of crashing', async () => {
h.get.mockResolvedValue({
models: [],
diff --git a/apps/desktop/src/shared/auxiliaryModelSettings.ts b/apps/desktop/src/shared/auxiliaryModelSettings.ts
index 3517829cf8..96328db470 100644
--- a/apps/desktop/src/shared/auxiliaryModelSettings.ts
+++ b/apps/desktop/src/shared/auxiliaryModelSettings.ts
@@ -6,6 +6,7 @@ import {
parseAuxiliaryModelRef,
} from './auxiliaryModelChain.js';
import { decodeCatalogModelPin } from './catalogModelPin.js';
+import type { CatalogModelPinAgentKind } from './catalogModelPin.js';
import { isUtilityModelProviderKind } from './utilityModelProfiles.js';
/** Main-owned ordered model chain for short, host-generated auxiliary text. */
@@ -31,10 +32,10 @@ export interface AuxiliaryModelOption {
label: string;
group: string;
providerId: string;
- agentKind: 'codex' | 'claude-code';
+ agentKind: CatalogModelPinAgentKind;
modelId: string;
modelName: string;
- /** Follow the same default visibility as the regular model selector. */
+ /** Auxiliary default; direct HTTP models do not inherit harness compatibility defaults. */
defaultEnabled?: boolean;
icon?: string;
budget: boolean;
@@ -115,7 +116,7 @@ export function isCustomAuxiliaryModelList(models: readonly string[]): boolean {
export function describeAuxiliaryModelRef(ref: string): {
providerId: string;
- agentKind: 'codex' | 'claude-code';
+ agentKind: CatalogModelPinAgentKind;
model: string;
} | null {
const parsed = parseAuxiliaryModelRef(ref);
diff --git a/apps/desktop/src/shared/catalogModelPin.ts b/apps/desktop/src/shared/catalogModelPin.ts
index a6c66a84f0..93d0020041 100644
--- a/apps/desktop/src/shared/catalogModelPin.ts
+++ b/apps/desktop/src/shared/catalogModelPin.ts
@@ -9,7 +9,8 @@
export const CATALOG_MODEL_PIN_PREFIX = 'cat:';
-export type CatalogModelPinAgentKind = 'codex' | 'claude-code';
+/** Pi identifies an auxiliary HTTP connection, not a supported Agent.oneShot implementation. */
+export type CatalogModelPinAgentKind = 'codex' | 'claude-code' | 'pi';
export interface CatalogModelPinRoute {
providerId: string;
@@ -17,7 +18,7 @@ export interface CatalogModelPinRoute {
model: string;
}
-const CATALOG_MODEL_PIN_AGENTS = new Set<CatalogModelPinAgentKind>(['codex', 'claude-code']);
+const CATALOG_MODEL_PIN_AGENTS = new Set<CatalogModelPinAgentKind>(['codex', 'claude-code', 'pi']);
/** Encode an exact provider × runtime × model route. */
export function encodeCatalogModelPin(route: CatalogModelPinRoute): string {
diff --git a/docs/dev-rules/configuration-and-overrides.md b/docs/dev-rules/configuration-and-overrides.md
index 4bd08b1aae..010989888f 100644
--- a/docs/dev-rules/configuration-and-overrides.md
+++ b/docs/dev-rules/configuration-and-overrides.md
@@ -61,6 +61,22 @@ token)与 [`engineering-conventions.md`](engineering-conventions.md)(i18n)
[已知实现差异](model-catalog-maintenance.md#visibility)。该说明不是对本节合同的豁免;
不得仅因代码仍在筛选就反向修改产品规则,也不能未验证便声称两者已一致。
+### 辅助模型的直接调用
+
+辅助模型的自定义 HTTP 连接按实际文本调用能力准入,不继承聊天引擎因兼容模式产生的
+默认关闭状态。候选默认可见;连接模型配置中显式保存的 `defaultEnabled` 和用户显示
+override 仍然优先。供应商/模型停用、退役、付费准入和凭证检查继续生效。
+内置及原生订阅适配器保持原有默认规则。
+
+选择记录继续使用 `cat:<连接>:<配置来源>:<模型>`;新增 `pi` 来源只标识连接与凭证,
+不启动 Pi,也不要求其实现 `Agent.oneShot`。已有 Codex / Claude Code 记录及轻量档位
+原样读取,不迁移或重排。候选和执行共用逐模型 HTTP 协议解析,未支持的 SDK 协议不列出。
+插件自行钉选的候选范围不扩大;跟随辅助模型链时使用用户已经保存的选择。
+语音润色继续遵循现有的 OpenAI / Cindy AI 白名单,不因辅助模型候选扩大而新增通道。
+
+实现与回归:`apps/desktop/src/main/utility-model/directTextRoute.ts`、
+`__tests__/auxiliaryDirectRoutes.test.ts`、`__tests__/oneShotCandidates.test.ts`。
+
## 3. 默认值演进与迁移
- 默认值变化时,分别说明新用户、未自定义老用户、已自定义老用户的行为。