Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(pi): BYOM host 接线 —— 自定义 provider 走 pi 原生 provider
zqchris391c96ceeccc
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.tsindex 2efa2c8596..10503d3e2f 100644--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts@@ -149,6 +149,34 @@ describe('validateCustomProviderConfig (per-runtime)', () => {}).ok,).toBe(false);});++ it('accepts a pi runtime (BYOM) with any of pi wire protocols', () => {+ for (const wp of ['anthropic-messages', 'openai-responses', 'openai-chat']) {+ expect(+ validateCustomProviderConfig({+ id: 'localpi',+ name: 'Local pi',+ auth: { method: 'none' },+ runtimes: {+ pi: { baseUrl: 'http://127.0.0.1:11434/v1', wireProtocol: wp, models: [{ id: 'm', name: 'M' }] },+ },+ }).ok,+ ).toBe(true);+ }+ });++ it('rejects an invalid wireProtocol on a pi runtime', () => {+ expect(+ validateCustomProviderConfig({+ id: 'localpi',+ name: 'Local pi',+ auth: { method: 'none' },+ runtimes: {+ pi: { baseUrl: 'http://127.0.0.1:11434/v1', wireProtocol: 'bogus-proto', models: [{ id: 'm', name: 'M' }] },+ },+ }).ok,+ ).toBe(false);+ });});describe('custom-provider-store CRUD (per-runtime)', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsnew file mode 100644index 0000000000..2dc3e6dd54--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@ -0,0 +1,94 @@+/**+ * BYOM host 解析 —— 自定义 provider(pi runtime)→ pi 原生 provider spec + env。+ * 覆盖:wire protocol → pi api 映射、apiKey/none/oauth 三态、缺 key 跳过、env key 名。+ */+import { describe, expect, it } from 'vitest';++import { buildPiNativeProvidersFromConfigs, piNativeKeyEnvVar } from '../pi-host.js';++type Cfg = Parameters<typeof buildPiNativeProvidersFromConfigs>[0][number];++const piRuntime = (over: Partial<NonNullable<Cfg['runtimes']['pi']>> = {}) => ({+ baseUrl: 'http://127.0.0.1:11434/v1',+ models: [{ id: 'qwen3:8b', name: 'Qwen3 8B' }],+ ...over,+});++describe('buildPiNativeProvidersFromConfigs', () => {+ 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'],+ ['openai-responses', 'openai-responses'],+ ['openai-chat', 'openai-completions'],+ [undefined, 'openai-completions'],+ ];+ for (const [wp, api] of cases) {+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{ id: 'p', name: 'P', auth: { method: 'none' }, runtimes: { pi: piRuntime({ wireProtocol: wp as never }) } }],+ () => null,+ );+ expect(providers[0]?.api).toBe(api);+ }+ });++ it('keyless (none) → no env, no apiKeyEnvVar (models.json writes dummy)', () => {+ const { providers, env } = buildPiNativeProvidersFromConfigs(+ [{ id: 'ollama', name: 'Ollama', auth: { method: 'none' }, runtimes: { pi: piRuntime() } }],+ () => null,+ );+ expect(providers).toHaveLength(1);+ expect(providers[0].apiKeyEnvVar).toBeUndefined();+ expect(env).toEqual({});+ });++ it('apiKey → env injected under CINDY_PI_KEY_<ID>, referenced by apiKeyEnvVar', () => {+ const { providers, env } = buildPiNativeProvidersFromConfigs(+ [{ id: 'my-vllm', name: 'vLLM', auth: { method: 'apiKey' }, runtimes: { pi: piRuntime() } }],+ (id, agent) => (id === 'my-vllm' && agent === 'pi' ? 'secret-123' : null),+ );+ const envVar = piNativeKeyEnvVar('my-vllm');+ expect(envVar).toBe('CINDY_PI_KEY_MY_VLLM');+ expect(providers[0].apiKeyEnvVar).toBe(envVar);+ expect(env[envVar]).toBe('secret-123');+ });++ it('apiKey provider with no stored key is skipped (avoid half-usable)', () => {+ const skips: string[] = [];+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{ id: 'nokey', name: 'NoKey', auth: { method: 'apiKey' }, runtimes: { pi: piRuntime() } }],+ () => null,+ (id) => skips.push(id),+ );+ expect(providers).toHaveLength(0);+ expect(skips).toContain('nokey');+ });++ it('oauth custom provider is skipped for pi native', () => {+ const skips: string[] = [];+ const { providers } = buildPiNativeProvidersFromConfigs(+ [{ id: 'oauthp', name: 'OAuthP', auth: { method: 'oauth' }, runtimes: { pi: piRuntime() } }],+ () => 'k',+ (id) => skips.push(id),+ );+ expect(providers).toHaveLength(0);+ expect(skips).toContain('oauthp');+ });++ it('ignores configs without a pi runtime; passes headers + models through', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(+ [+ { id: 'codexonly', name: 'C', runtimes: {} },+ {+ id: 'withhdr',+ name: 'H',+ auth: { method: 'none' },+ runtimes: { pi: piRuntime({ headers: { 'x-org': 'acme' }, models: [{ id: 'm1', name: 'M1', contextWindow: 8000 }] }) },+ },+ ],+ () => null,+ );+ expect(providers.map((p) => p.id)).toEqual(['withhdr']);+ expect(providers[0].headers).toEqual({ 'x-org': 'acme' });+ expect(providers[0].models[0]).toMatchObject({ id: 'm1', name: 'M1', contextWindow: 8000 });+ });+});diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.tsindex e6927046e9..c0caaf8875 100644--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts@@ -33,7 +33,7 @@ import { customProviders } from '../localDb/schema.js';export const CUSTOM_PROVIDER_ID_RE = /^[a-z0-9_-]+$/;/** 不可占用的内置来源 id。 */const RESERVED_IDS = new Set(['anthropic', 'openai', 'xd']);-const VALID_AGENTS: readonly AgentKind[] = ['claude-code', 'codex'];+const VALID_AGENTS: readonly AgentKind[] = ['claude-code', 'codex', 'pi'];const MAX_ID_LEN = 40;const MAX_NAME_LEN = 60;@@ -111,6 +111,8 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {}}if (r.wireProtocol !== undefined) {+ // Pi 是多协议 harness;Codex 也具备 Responses / Chat / Anthropic bridge。+ // Claude Code 只接受原生 Anthropic Messages。const allowed = agent === 'claude-code'? ['anthropic-messages']: ['openai-responses', 'openai-chat', 'anthropic-messages'];diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 26be21b2de..c153eb9071 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -19,9 +19,18 @@ import fs from 'node:fs';import { app } from 'electron';import { PiAgent, type AgentDeps, type AuthAdapter, type AuthState } from '@cindy/maker-core';-import type { AgentRuntimeConfig, AuthAdapterOptions } from '@cindy/maker-core';+import type {+ AgentRuntimeConfig,+ AuthAdapterOptions,+ PiNativeApi,+ PiNativeProviderSpec,+ PiNativeProvidersResult,+} from '@cindy/maker-core';+import type { ProviderWireProtocol } from '@cindy/model-providers';import { getPiExtraSpawnConfig } from '../mcp-integrations/piEnvironment.js';+import { listCustomProviders } from './custom-provider-store.js';+import { readCustomProviderKey } from '../secrets/providerSecretStore.js';import { desktopCodexAuthAdapter, readClaudeApiKey } from './auth-adapters.js';import { getClaudeEndpoint } from './anthropic-compat-proxy-host.js';import { hasClaudeAiOAuth } from './claude-credentials-store.js';@@ -140,6 +149,101 @@ export interface BuildPiAgentOpts {mcpProviders?: AgentDeps['mcpProviders'];}+/** Cindy wire protocol → pi models.json api 形态。 */+function wireProtocolToPiApi(wp: ProviderWireProtocol | undefined): PiNativeApi {+ switch (wp) {+ case 'anthropic-messages':+ return 'anthropic-messages';+ case 'openai-responses':+ return 'openai-responses';+ case 'openai-chat':+ case undefined:+ default:+ // 缺省 openai-completions:BYOM 本地端点(Ollama/vLLM 的 /v1/chat/completions)最常见。+ return 'openai-completions';+ }+}++/** env 变量名(该 provider 的 api key):CINDY_PI_KEY_<ID>,ID 规整成 [A-Z0-9_]。 */+export function piNativeKeyEnvVar(providerId: string): string {+ return `CINDY_PI_KEY_${providerId.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`;+}++/**+ * 纯映射:自定义 provider 配置(含 pi runtime)→ pi 原生 provider spec + env。+ * key 读取经 `readKey` 注入(便于单测)。规则:+ * - 无 pi runtime → 跳过;+ * - oauth 形态 → 跳过(pi models.json 仅支持 radius oauth,不通用);+ * - apiKey 形态但读不到 key → 跳过(pi 无 key 不显示该模型,避免半可用);+ * - none(keyless,本机 Ollama 等)→ apiKeyEnvVar 留空,models.json 写 dummy key。+ * 直连用户端点,不过 anthropic-compat 代理(设计原则:pi 主导,禁双重转义)。+ */+export function buildPiNativeProvidersFromConfigs(+ configs: Array<{+ id: string;+ name: string;+ auth?: { method?: string };+ runtimes: {+ pi?: {+ baseUrl: string;+ wireProtocol?: ProviderWireProtocol;+ headers?: Record<string, string>;+ models: Array<{ id: string; name?: string; contextWindow?: number }>;+ };+ };+ }>,+ readKey: (providerId: string, agent: string) => string | null,+ onSkip?: (id: string, reason: string) => void,+): PiNativeProvidersResult {+ const providers: PiNativeProviderSpec[] = [];+ const env: Record<string, string> = {};+ for (const cfg of configs) {+ const rt = cfg.runtimes.pi;+ if (!rt) continue;+ const authMethod = cfg.auth?.method ?? 'apiKey';+ if (authMethod === 'oauth') {+ onSkip?.(cfg.id, 'oauth not supported for pi native');+ continue;+ }+ let apiKeyEnvVar: string | undefined;+ if (authMethod === 'apiKey') {+ const key = readKey(cfg.id, 'pi');+ if (!key) {+ onSkip?.(cfg.id, 'apiKey provider missing pi key');+ continue;+ }+ apiKeyEnvVar = piNativeKeyEnvVar(cfg.id);+ env[apiKeyEnvVar] = key;+ }+ providers.push({+ id: cfg.id,+ name: cfg.name,+ baseUrl: rt.baseUrl,+ api: wireProtocolToPiApi(rt.wireProtocol),+ apiKeyEnvVar,+ ...(rt.headers && Object.keys(rt.headers).length > 0 ? { headers: rt.headers } : {}),+ models: rt.models.map((m) => ({ id: m.id, name: m.name, contextWindow: m.contextWindow })),+ });+ }+ return { providers, env };+}++/** BYOM:读 DB 自定义 provider + safeStorage key → pi 原生 provider spec。IO 外壳,逻辑在上面。 */+async function resolvePiNativeProviders(): Promise<PiNativeProvidersResult> {+ let configs;+ try {+ configs = await listCustomProviders();+ } catch (err) {+ log.warn('resolvePiNativeProviders: listCustomProviders failed, gateway-only', {+ message: err instanceof Error ? err.message : String(err),+ });+ return { providers: [], env: {} };+ }+ return buildPiNativeProvidersFromConfigs(configs, readCustomProviderKey, (id, reason) =>+ log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason }),+ );+}+/** pi 二进制缺失时返回 null(调用方跳过注册);其余情况构造 PiAgent。 */export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {const binaryPath = resolvePiBinaryPath();@@ -157,5 +261,6 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {mcpProviders: opts.mcpProviders,resolvePiAgentHome: () => path.join(app.getPath('userData'), 'pi-agent-home'),preparePiExtraSpawnConfig: (providers, ctx) => getPiExtraSpawnConfig(providers, opts.logger, ctx),+ resolvePiNativeProviders: () => resolvePiNativeProviders(),});}diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 3402232a97..84dd889879 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -263,7 +263,12 @@ export class PiAgent extends BaseAgent {if (!endpoint) {this.deps.logger.warn('pi: runtimeConfig.endpoint missing — models.json will have no usable provider');}- const models = this.capabilities.availableModels.map((m: ModelDescriptor) => ({+ // 原生 provider 的模型只进各自 provider 块,**不进网关 cindy 块** —— 否则 catalog 派生+ // 出的自定义 pi 模型会同时出现在网关块(指向 compat 代理),造成双重路由/双重转义。+ const nativeModelIds = new Set(nativeProviders.flatMap((np) => np.models.map((m) => m.id)));+ const models = this.capabilities.availableModels+ .filter((m: ModelDescriptor) => !nativeModelIds.has(m.id))+ .map((m: ModelDescriptor) => ({id: m.id,name: m.displayName,reasoning: m.efforts.length > 0,diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex 82e315fb11..e16e3b5199 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -269,4 +269,39 @@ describe('buildUserProvider (per-runtime)', () => {expect(p.routing).toEqual({});expect(p.models).toEqual({});});++ it('derives a pi runtime (BYOM): pi in agents + models with efforts', () => {+ const p = buildUserProvider({+ id: 'localollama',+ name: 'Local Ollama',+ auth: { method: 'none' },+ runtimes: {+ pi: {+ baseUrl: 'http://127.0.0.1:11434/v1',+ wireProtocol: 'openai-chat',+ models: [{ id: 'qwen3:8b', name: 'Qwen3 8B' }],+ },+ },+ });+ expect(p.agents).toEqual(['pi']);+ expect(p.auth).toEqual({ method: 'none' });+ expect((p.models.pi ?? []).map((m) => m.id)).toEqual(['qwen3:8b']);+ // pi 自定义模型给 effort 档(与 claude 同档,默认 high)。+ expect((p.models.pi ?? [])[0]?.efforts).toEqual(['low', 'medium', 'high', 'xhigh', 'max']);+ expect((p.models.pi ?? [])[0]?.defaultEffort).toBe('high');+ expect((p.models.pi ?? [])[0]?.group).toBe('custom:localollama');+ });++ it('orders pi after claude-code and codex (AGENT_ORDER)', () => {+ const p = buildUserProvider({+ id: 'multi',+ name: 'Multi',+ runtimes: {+ pi: { baseUrl: 'http://127.0.0.1:8000/v1', models: [{ id: 'pi-m', name: 'Pi M' }] },+ codex: { baseUrl: 'https://v.ai/openai/v1', models: [{ id: 'cx-m', name: 'Cx M' }] },+ 'claude-code': { baseUrl: 'https://v.ai/anthropic', models: [{ id: 'cc-m', name: 'Cc M' }] },+ },+ });+ expect(p.agents).toEqual(['claude-code', 'codex', 'pi']);+ });});diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.tsindex 88fb1ca6b5..f9d4b14d84 100644--- a/packages/model-providers/src/user-provider.ts+++ b/packages/model-providers/src/user-provider.ts@@ -18,6 +18,7 @@ import type {Effort,Provider,ProviderRuntimeModelConfig,+ ProviderWireProtocol,RoutingDescriptor,} from './types.js';import { isLoopbackProviderUrl } from './provider-url.js';@@ -36,12 +37,15 @@ export const DEFAULT_CUSTOM_CONTEXT_WINDOW = 200_000;const CUSTOM_EFFORTS: Partial<Record<AgentKind, Effort[]>> = {'claude-code': ['low', 'medium', 'high', 'xhigh', 'max'],codex: ['low', 'medium', 'high', 'xhigh'],+ // pi 经 thinking level 表达推理强度(off/minimal/low/medium/high/xhigh/max);选择器给+ // 与 claude 同档,实际是否生效由自定义模型后端决定(BYOM 本地模型可能不支持,无害)。+ pi: ['low', 'medium', 'high', 'xhigh', 'max'],};/** 自定义模型默认选中的 effort(与内置旗舰一致)。 */const DEFAULT_CUSTOM_EFFORT: Effort = 'high';/** 固定 agent 顺序:保证派生出的 provider.agents / routing / models 顺序稳定。 */-const AGENT_ORDER: readonly AgentKind[] = ['claude-code', 'codex'];+const AGENT_ORDER: readonly AgentKind[] = ['claude-code', 'codex', 'pi'];/** 单个用户填写的模型 → CatalogModel(补默认元数据;effort 按所属 agent 参考内置默认)。 */function toCatalogModel(@@ -69,8 +73,13 @@ function toCatalogModel(};}-function defaultWireProtocol(agent: AgentKind): 'anthropic-messages' | 'openai-responses' {- return agent === 'claude-code' ? 'anthropic-messages' : 'openai-responses';+function defaultWireProtocol(agent: AgentKind): ProviderWireProtocol {+ // pi 默认 openai-chat:BYOM 本地端点(Ollama/vLLM 的 /v1/chat/completions)最常见。+ // 注:pi 走原生 provider 直连,routing.pi 不被 native 路径消费——此默认仅影响(未用的)+ // 路由描述符里是否显式记 wireProtocol,pi 实际 api 由 pi-host resolvePiNativeProviders 定。+ if (agent === 'claude-code') return 'anthropic-messages';+ if (agent === 'pi') return 'openai-chat';+ return 'openai-responses';}/** baseUrl + 自定义 headers → 路由描述符(**不含密钥**)。 */