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(desktop): 新增供应商时自动初始化 Pi runtime (#2509)

nanaco4f274001ae61
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 4f9b1995a6..265fb0028c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -4,6 +4,8 @@
*/
import { describe, expect, it, vi } from 'vitest';
+import { derivePiRuntimeFromClaudeRuntime } from '../../../shared/piRuntimeInitialization.js';
+
vi.mock('electron', () => ({
app: {
isPackaged: false,
@@ -23,6 +25,40 @@ const piRuntime = (over: Partial<NonNullable<Cfg['runtimes']['pi']>> = {}) => ({
});
describe('buildPiNativeProvidersFromConfigs', () => {
+ it('turns a Claude-derived wizard runtime and copied Pi key into a callable native provider', () => {
+ const derived = derivePiRuntimeFromClaudeRuntime({
+ baseUrl: 'https://api.example/anthropic',
+ headers: { 'x-tenant': 'acme' },
+ models: [{ id: 'model-a', name: 'Model A', contextWindow: 100_000 }],
+ });
+ expect(derived).not.toBeNull();
+
+ const { providers, env } = buildPiNativeProvidersFromConfigs(
+ [
+ {
+ id: 'wizard-provider',
+ name: 'Wizard Provider',
+ auth: { method: 'apiKey' },
+ runtimes: { pi: derived! },
+ },
+ ],
+ (providerId, agent) =>
+ providerId === 'wizard-provider' && agent === 'pi' ? 'wizard-secret' : null,
+ );
+
+ expect(providers).toHaveLength(1);
+ expect(providers[0]).toMatchObject({
+ id: 'wizard-provider',
+ name: 'Wizard Provider',
+ baseUrl: 'https://api.example/anthropic',
+ api: 'anthropic-messages',
+ models: [{ id: 'model-a', name: 'Model A', contextWindow: 100_000 }],
+ });
+ expect(env[providers[0].apiKeyEnvVar!]).toBe('wizard-secret');
+ expect(providers[0].headers?.['x-tenant']).toMatch(/^\$CINDY_PI_KEY_/);
+ expect(Object.values(env)).toContain('acme');
+ });
+
it('maps wire protocols to pi api forms (openai-chat→openai-completions, undefined→openai-completions)', () => {
const cases: Array<[string | undefined, string]> = [
['anthropic-messages', 'anthropic-messages'],
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
index 8b95276d2a..5e5fa06f76 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
@@ -147,6 +147,34 @@ const piReasoningPreset = {
},
};
+const explicitPiPreset = {
+ id: 'explicit-pi',
+ name: 'Explicit Pi',
+ runtimes: {
+ 'claude-code': {
+ baseUrl: 'https://explicit.example/anthropic',
+ models: [{ id: 'claude-model', name: 'Claude Model' }],
+ },
+ pi: {
+ baseUrl: 'https://explicit.example/pi',
+ wireProtocol: 'openai-chat' as const,
+ models: [{ id: 'pi-model', name: 'Pi Model' }],
+ },
+ },
+};
+
+const claudeRequestPathPreset = {
+ id: 'claude-request-path',
+ name: 'Claude Request Path',
+ runtimes: {
+ 'claude-code': {
+ baseUrl: 'https://path.example/anthropic',
+ requestPath: '/tenant/acme/messages',
+ models: [{ id: 'path-model', name: 'Path Model' }],
+ },
+ },
+};
+
function renderWizard(presetId: string) {
return render(
React.createElement(AddProviderWizard, {
@@ -170,6 +198,8 @@ beforeEach(() => {
openCodePreset,
dualDiscoveryPreset,
piReasoningPreset,
+ explicitPiPreset,
+ claudeRequestPathPreset,
],
})),
// 列模型失败场景兜底(Greptile P1 回归):官方 API 预设必须靠推荐模型仍可完成。
@@ -323,6 +353,16 @@ describe('AddProviderWizard — preset 直达', () => {
);
const keys = vi.mocked(createCustomProvider).mock.calls[0][1];
expect(keys).toMatchObject({ 'claude-code': 'sk-test', codex: 'sk-test' });
+ expect(config.runtimes.pi).toEqual({
+ baseUrl: 'https://api.anthropic.com',
+ wireProtocol: 'anthropic-messages',
+ models: expect.arrayContaining([
+ expect.objectContaining({ id: 'claude-opus-5', contextWindow: 1_000_000 }),
+ expect.objectContaining({ id: 'claude-sonnet-5', contextWindow: 1_000_000 }),
+ expect.objectContaining({ id: 'claude-haiku-4-5', contextWindow: 200_000 }),
+ ]),
+ });
+ expect(keys.pi).toBe('sk-test');
});
it('Pi 预设保存时保留显式 reasoning 能力与支持档位', async () => {
@@ -344,6 +384,63 @@ describe('AddProviderWizard — preset 直达', () => {
]);
});
+ it('预设已有显式 Pi runtime 时不被 Claude 自动初始化覆盖', async () => {
+ renderWizard('explicit-pi');
+
+ await waitFor(() => expect(screen.getByDisplayValue('Explicit Pi')).not.toBeNull());
+ fireEvent.change(screen.getByPlaceholderText('sk-…'), { target: { value: 'sk-test' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.next'));
+ await waitFor(() => expect(screen.getByText('Pi Model')).not.toBeNull());
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
+ const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];
+ expect(config.runtimes.pi).toEqual({
+ baseUrl: 'https://explicit.example/pi',
+ wireProtocol: 'openai-chat',
+ models: [{ id: 'pi-model', name: 'Pi Model' }],
+ });
+ expect(keys.pi).toBe('sk-test');
+ });
+
+ it('预设显式 Pi 模型全部取消后不从 Claude 重新生成 Pi runtime', async () => {
+ renderWizard('explicit-pi');
+
+ await waitFor(() => expect(screen.getByDisplayValue('Explicit Pi')).not.toBeNull());
+ fireEvent.change(screen.getByPlaceholderText('sk-…'), { target: { value: 'sk-test' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.next'));
+ const piModel = await screen.findByText('Pi Model');
+ fireEvent.click(piModel.closest('button') as HTMLButtonElement);
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
+ const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];
+ expect(config.runtimes['claude-code']).toEqual({
+ baseUrl: 'https://explicit.example/anthropic',
+ models: [{ id: 'claude-model', name: 'Claude Model' }],
+ });
+ expect(config.runtimes.pi).toBeUndefined();
+ expect(keys.pi).toBeUndefined();
+ });
+
+ it('Claude runtime 带自定义请求路径时不自动生成 Pi runtime', async () => {
+ renderWizard('claude-request-path');
+
+ await waitFor(() => expect(screen.getByDisplayValue('Claude Request Path')).not.toBeNull());
+ fireEvent.change(screen.getByPlaceholderText('sk-…'), { target: { value: 'sk-test' } });
+ fireEvent.click(screen.getByText('settings.providers.wizard.next'));
+ await waitFor(() => expect(screen.getByText('Path Model')).not.toBeNull());
+ fireEvent.click(screen.getByText('settings.providers.wizard.finish'));
+
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));
+ const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];
+ expect(config.runtimes['claude-code']).toMatchObject({
+ requestPath: '/tenant/acme/messages',
+ });
+ expect(config.runtimes.pi).toBeUndefined();
+ expect(keys.pi).toBeUndefined();
+ });
+
it('editable preset saves the edited base URL and exact request path', async () => {
const editablePreset = {
id: 'local-gateway',
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index c487fca1ac..5d3bff84b4 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -31,6 +31,7 @@ import { useProviderOAuthDeviceCode } from '@/hooks/useProviderOAuthDeviceCode';
import { hasProviderLogo, ProviderLogoMark } from '@/components/icons/ProviderLogoMark';
import { OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';
import { SettingsTextInput } from './SettingsTextInput';
+import { derivePiRuntimeFromClaudeRuntime } from '@/../shared/piRuntimeInitialization';
import {
isLoopbackProviderUrl,
@@ -809,6 +810,14 @@ export function AddProviderWizard({
if (k) keys[agent] = k;
}
}
+ const claudeRuntime = runtimes['claude-code'];
+ if (!preset.runtimes.pi && !runtimes.pi && claudeRuntime) {
+ const piRuntime = derivePiRuntimeFromClaudeRuntime(claudeRuntime);
+ if (piRuntime) {
+ runtimes.pi = piRuntime;
+ if (keys['claude-code']) keys.pi = keys['claude-code'];
+ }
+ }
if (Object.keys(runtimes).length === 0) {
toast.error(t('settings.providers.wizard.noModelSelected'));
return;
diff --git a/apps/desktop/src/renderer/lib/__tests__/piRuntimeInitialization.test.ts b/apps/desktop/src/renderer/lib/__tests__/piRuntimeInitialization.test.ts
new file mode 100644
index 0000000000..2409ce3df5
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/piRuntimeInitialization.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import { derivePiRuntimeFromClaudeRuntime } from '@/../shared/piRuntimeInitialization';
+
+describe('derivePiRuntimeFromClaudeRuntime', () => {
+ it('projects a plain Claude runtime to Pi without a request path', () => {
+ const result = derivePiRuntimeFromClaudeRuntime({
+ baseUrl: 'https://api.example/anthropic',
+ modelsUrl: 'https://api.example/v1/models',
+ headers: { 'x-provider': 'example' },
+ models: [
+ {
+ id: 'model-a',
+ name: 'Model A',
+ contextWindow: 100_000,
+ defaultEnabled: false,
+ supportsImageInput: true,
+ reasoning: true,
+ reasoningEfforts: ['high'],
+ },
+ ],
+ });
+
+ expect(result).toEqual({
+ baseUrl: 'https://api.example/anthropic',
+ wireProtocol: 'anthropic-messages',
+ models: [
+ { id: 'model-a', name: 'Model A', contextWindow: 100_000, defaultEnabled: false },
+ ],
+ headers: { 'x-provider': 'example' },
+ modelsUrl: 'https://api.example/v1/models',
+ });
+ });
+
+ it('does not project a Claude runtime with a custom request path', () => {
+ expect(
+ derivePiRuntimeFromClaudeRuntime({
+ baseUrl: 'https://api.example/anthropic',
+ requestPath: '/tenant/acme/infer',
+ models: [{ id: 'model-a', name: 'Model A' }],
+ }),
+ ).toBeNull();
+ });
+
+ it('does not override an incompatible explicit wire protocol', () => {
+ expect(
+ derivePiRuntimeFromClaudeRuntime({
+ baseUrl: 'https://api.example/v1',
+ wireProtocol: 'openai-chat',
+ models: [{ id: 'model-a', name: 'Model A' }],
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts b/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts
index aa0b6be2e4..512af5d91a 100644
--- a/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts
+++ b/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts
@@ -3,6 +3,7 @@ import type {
ProviderRuntimeModelConfig,
ProviderWireProtocol,
} from '@cindy/model-providers';
+import { savedCustomProviderModelShape } from '@/../shared/piRuntimeInitialization';
export type RuntimeFillAgent = Extract<AgentKind, 'claude-code' | 'codex' | 'pi'>;
export interface RuntimeFillHeaderRow {
@@ -122,25 +123,10 @@ function endpointBundleSupported(
return source.requestPath.trim().length === 0 || (sourceAgent !== 'pi' && targetAgent !== 'pi');
}
-function savedModelShape(model: ProviderRuntimeModelConfig, includePiCapabilities: boolean) {
- return {
- id: model.id.trim(),
- name: model.name.trim(),
- ...(model.contextWindow !== undefined ? { contextWindow: model.contextWindow } : {}),
- ...(model.defaultEnabled === false ? { defaultEnabled: false } : {}),
- ...(includePiCapabilities && model.supportsImageInput === true
- ? { supportsImageInput: true }
- : {}),
- ...(includePiCapabilities && model.reasoning === true && model.reasoningEfforts?.length
- ? { reasoning: true, reasoningEfforts: [...model.reasoningEfforts] }
- : {}),
- } satisfies ProviderRuntimeModelConfig;
-}
-
function validModels(models: ProviderRuntimeModelConfig[]) {
return models
.filter((model) => model.id.trim() && model.name.trim())
- .map((model) => savedModelShape(model, true));
+ .map((model) => savedCustomProviderModelShape(model, true));
}
function canonicalHeaders(headers: RuntimeFillHeaderRow[]) {
@@ -168,10 +154,10 @@ function modelsForTarget(
) {
const targetById = new Map(validModels(targetModels).map((model) => [model.id, model]));
return validModels(sourceModels).map((sourceModel) => {
- if (targetAgent !== 'pi') return savedModelShape(sourceModel, false);
- if (sourceAgent === 'pi') return savedModelShape(sourceModel, true);
+ if (targetAgent !== 'pi') return savedCustomProviderModelShape(sourceModel, false);
+ if (sourceAgent === 'pi') return savedCustomProviderModelShape(sourceModel, true);
- const portable = savedModelShape(sourceModel, false);
+ const portable = savedCustomProviderModelShape(sourceModel, false);
const existing = targetById.get(portable.id);
return {
...portable,
diff --git a/apps/desktop/src/shared/piRuntimeInitialization.ts b/apps/desktop/src/shared/piRuntimeInitialization.ts
new file mode 100644
index 0000000000..0d04635313
--- /dev/null
+++ b/apps/desktop/src/shared/piRuntimeInitialization.ts
@@ -0,0 +1,39 @@
+import type {
+ CustomProviderRuntimeConfig,
+ ProviderRuntimeModelConfig,
+} from '@cindy/model-providers';
+
+export function savedCustomProviderModelShape(
+ model: ProviderRuntimeModelConfig,
+ includePiCapabilities: boolean,
+): ProviderRuntimeModelConfig {
+ return {
+ id: model.id.trim(),
+ name: model.name.trim(),
+ ...(model.contextWindow !== undefined ? { contextWindow: model.contextWindow } : {}),
+ ...(model.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(includePiCapabilities && model.supportsImageInput === true
+ ? { supportsImageInput: true }
+ : {}),
+ ...(includePiCapabilities && model.reasoning === true && model.reasoningEfforts?.length
+ ? { reasoning: true, reasoningEfforts: [...model.reasoningEfforts] }
+ : {}),
+ };
+}
+
+export function derivePiRuntimeFromClaudeRuntime(
+ runtime: CustomProviderRuntimeConfig,
+): CustomProviderRuntimeConfig | null {
+ if (runtime.requestPath?.trim()) return null;
+ if (runtime.wireProtocol && runtime.wireProtocol !== 'anthropic-messages') return null;
+
+ return {
+ baseUrl: runtime.baseUrl,
+ wireProtocol: 'anthropic-messages',
+ models: runtime.models.map((model) => savedCustomProviderModelShape(model, false)),
+ ...(runtime.headers && Object.keys(runtime.headers).length > 0
+ ? { headers: { ...runtime.headers } }
+ : {}),
+ ...(runtime.modelsUrl ? { modelsUrl: runtime.modelsUrl } : {}),
+ };
+}
diff --git a/docs/provider-pi-runtime-initialization.md b/docs/provider-pi-runtime-initialization.md
new file mode 100644
index 0000000000..43de64109b
--- /dev/null
+++ b/docs/provider-pi-runtime-initialization.md
@@ -0,0 +1,84 @@
+# 自定义供应商新增时的 Pi Runtime 初始化
+
+## 背景
+
+Pi 支持自定义供应商的原生 BYOM runtime,但供应商配置需要显式存在 `runtimes.pi`。现有
+“新增供应商”向导是极简流程:用户选择预设、填写显示名称和 API Key,向导只展示预设声明
+的模型与端点,不展开各个引擎的独立配置。
+
+当前快捷预设主要声明 `claude-code` 与 `codex`,因此通过新增向导创建的供应商不会写入
+`runtimes.pi`。编辑已有供应商时,编辑器提供 Pi Tab 和 runtime 一键填充,用户可以手动
+完成相同配置,造成新增与编辑行为不一致。
+
+## 目标
+
+- 不改变新增向导的页面结构、步骤数量或用户输入项。
+- 新增供应商保存后,若预设存在 Claude Code runtime,则自动生成对应的 Pi runtime。
+- Pi runtime 初始使用 Claude Code 的端点、模型和凭证配置,并使用 `anthropic-messages`
+ 协议。
+- 保持现有编辑页的一键填充能力,继续支持用户调整 Pi 端点、协议和模型。
+- 对不具备可安全复用条件的预设不强行生成 Pi runtime。
+
+## 非目标
+
+- 不在新增向导中增加 Claude Code / Codex / Pi Tab。
+- 不把所有 Codex runtime 无条件复制给 Pi。
+- 不改变既有供应商的运行时配置,不做启动期全量数据迁移。
+- 不因为模型 ID 在 Pi 对话列表出现,就宣称某个具体供应商来源支持 Pi。
+
+## 方案
+
+### 保存阶段生成 Pi runtime
+
+新增向导继续按照预设声明的 runtime 拉取模型并收集用户选择。构造保存 payload 时:
+
+1. 先按现有逻辑写入预设声明的 runtime。
+2. 若预设有 `claude-code` runtime,且该 runtime 最终有至少一个选中模型,则基于保存后的
+ Claude Code runtime 派生 `pi` runtime。
+3. Pi runtime 使用相同的 `baseUrl`、模型发现端点和请求头;协议固定为
+ `anthropic-messages`。模型按编辑页一键填充的保存语义,只复制通用字段
+ `id`、`name`、`contextWindow` 和 `defaultEnabled`,不从 Claude runtime 猜测 Pi 专属能力。
+4. 不复制 Claude Code 的 `requestPath`,因为 Pi 原生 runtime 不支持自定义推理请求路径。
+5. API Key 同步写入 Pi runtime 对应的凭证槽,使新增后无需再次配置密钥。
+
+### 兼容门槛
+
+自动派生只允许从 Claude Code runtime 进行,且目标端点必须具备 Anthropic Messages 语义。
+原因是 Pi 原生支持 `anthropic-messages`,而 Claude Code runtime 本身已经使用该协议。
+
+没有 Claude Code runtime 的预设暂不自动补 Pi;这类预设后续应逐一验证协议、工具调用、流式
+输出、thinking、图片输入、请求路径和计费元数据后再加入专门规则。
+
+### 存量供应商
+
+本次不做启动期自动迁移,避免未经用户确认改变既有供应商路由。存量供应商继续通过编辑页
+的 Pi Tab 和 runtime 一键填充补齐;补齐后才会写入明确的 `runtimes.pi` 并参与 Pi 路由。
+
+## 数据与路由不变量
+
+- Pi host 只为存在 `runtimes.pi` 的自定义供应商生成原生 provider 配置。
+- 新增保存时把同一 API Key 写入 Pi 独立凭证槽;Pi host 读取该槽并把密钥注入子进程环境,
+ `models.json` 只持有环境变量名,不持有明文。
+- Pi 模型选择器按 `provider ID + agent + model ID` 判断来源;跨供应商同名模型不能作为
+ 具体供应商已支持 Pi 的证据。
+- 新增向导的模型发现仍按预设声明的 runtime 分开执行;自动派生 Pi 不额外发起第二次
+ 模型发现请求。
+- Pi runtime 的模型条目只继承跨 runtime 通用字段;Pi 专属 reasoning 或图片能力必须由
+ 显式 Pi 配置声明,不能从 Claude Code runtime 猜测。
+
+## 测试策略
+
+- 新增向导保存测试:含 Claude Code + Codex 的预设会生成 Pi runtime。
+- 保存测试:Pi runtime 复用 Claude Code 的端点、模型、headers 和 API Key,协议为
+ `anthropic-messages`,且不带 `requestPath`。
+- 保存测试:没有 Claude Code runtime 的预设不会凭空生成 Pi runtime。
+- Pi host 装配测试:把新增流程派生的 runtime 和 Pi 凭证交给真实装配函数,断言最终原生
+ provider 使用 `anthropic-messages`、正确端点、模型、请求头环境引用和 Pi 密钥环境变量。
+- 回归测试:编辑页已有 Pi 一键填充行为不受影响。
+- 运行相关 desktop 定向测试与 typecheck;提交前按仓库门禁运行完整 `pnpm test:unit`。
+
+## 风险与后续
+
+自动派生的前提是供应商的 Claude Code 端点确实兼容 Anthropic Messages。若某供应商只是对
+Claude Code 做了特殊代理、请求路径或能力裁剪,后续应把它从自动派生名单中排除,或为其
+增加显式的 Pi 兼容配置,而不是继续扩大通用复制规则。