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(pi): BYOM maker-core 核心 —— 原生 provider 块 + provider 感知路由

zqchris2b0c48519f21
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 9adc02b4f5..cf9f51720a 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -117,6 +117,51 @@ export interface PiExtraSpawnConfig {
disposeSessionCtx?: () => void;
}
+/** pi models.json 原生 provider 的 api 形态(BYOM 用;不过 anthropic-compat 代理)。 */
+export type PiNativeApi =
+ | 'anthropic-messages'
+ | 'openai-responses'
+ | 'openai-completions'
+ | 'google-generative-ai';
+
+/** BYOM:写进 pi models.json 的一个模型(原生 provider 块内)。 */
+export interface PiNativeModelSpec {
+ id: string;
+ name?: string;
+ reasoning?: boolean;
+ contextWindow?: number;
+ maxTokens?: number;
+ input?: Array<'text' | 'image'>;
+}
+
+/**
+ * BYOM:一个**原生 pi provider**(用户自定义/本地模型)—— 直连用户端点,不经 Cindy 的
+ * anthropic-compat 代理(设计原则:pi 主导,禁双重转义)。host 从 custom-provider-store
+ * 解析产出;PiAgent 写进 models.json 的独立 provider 块,并按 model→provider 路由 set_model。
+ */
+export interface PiNativeProviderSpec {
+ /** provider id(slug,禁与网关 provider `cindy` 撞名)。 */
+ id: string;
+ name: string;
+ baseUrl: string;
+ api: PiNativeApi;
+ /**
+ * 存放该 provider api key 的 env 变量名;models.json 用 `$<envVar>` 插值引用(与网关
+ * CINDY_PI_API_KEY 同机制,密钥只进子进程 env、不落盘)。keyless(本机 Ollama 等)留空 →
+ * 写 dummy key(pi 要求有 key 才在 /model 显示)。
+ */
+ apiKeyEnvVar?: string;
+ headers?: Record<string, string>;
+ models: PiNativeModelSpec[];
+}
+
+/** host 解析出的 pi 原生 provider + 需注入子进程的 env(api keys)。 */
+export interface PiNativeProvidersResult {
+ providers: PiNativeProviderSpec[];
+ /** 注入 spawn env 的键值(通常是各 provider 的 api key,键名对应 spec.apiKeyEnvVar)。 */
+ env: Record<string, string>;
+}
+
/**
* pi MCP 桥的 per-session 身份上下文(host 用它在 bridge 上注册当前 pi 会话)。
*
@@ -233,6 +278,17 @@ export interface AgentDeps {
ctx?: PiExtraSpawnConfigContext,
) => Promise<PiExtraSpawnConfig | null>;
+ /**
+ * BYOM:host 解析出当前会话可用的 pi **原生 provider**(用户自定义/本地模型)+ 需注入的
+ * env(api keys)。PiAgent 把这些写进 models.json 的独立 provider 块(直连用户端点,不过
+ * anthropic-compat 代理),并按 model→provider 路由 set_model / 初始 --provider。
+ *
+ * 缺省 / 返回空 → 只有网关 provider `cindy`(现状,行为不变)。keyless provider 的 key 可省。
+ */
+ resolvePiNativeProviders?: (
+ ctx: { workingDir: string; remoteHostId?: string | null },
+ ) => Promise<PiNativeProvidersResult | null>;
+
/**
* Host-provided capability descriptor additions.
*
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index b127d072c8..2fc0cd1a90 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -415,6 +415,84 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it(
+ 'BYOM: a native provider model routes directly to its own endpoint, not the gateway proxy',
+ { timeout: 60_000 },
+ async () => {
+ // 独立的「原生端点」假服务器,扮演用户自建的 anthropic 兼容端点。
+ const nativeSeen: Array<{ auth: string | undefined; url: string }> = [];
+ const nativeServer = createServer((req, res) => {
+ req.on('data', () => {}); // 排空请求体(不需要正文,只看 header/路由)
+ req.on('end', () => {
+ nativeSeen.push({
+ auth: (req.headers['x-api-key'] as string | undefined) ?? (req.headers.authorization as string | undefined),
+ url: req.url ?? '',
+ });
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
+ res.end(anthropicStreamBody('pong from NATIVE endpoint'));
+ });
+ });
+ await new Promise<void>((r) => nativeServer.listen(0, '127.0.0.1', r));
+ const nativeAddr = nativeServer.address();
+ const nativeUrl = typeof nativeAddr === 'object' && nativeAddr ? `http://127.0.0.1:${nativeAddr.port}` : '';
+
+ const deps = buildDeps();
+ deps.resolvePiNativeProviders = async () => ({
+ providers: [
+ {
+ id: 'localbyom',
+ name: 'Local BYOM',
+ baseUrl: nativeUrl,
+ api: 'anthropic-messages',
+ apiKeyEnvVar: 'CINDY_PI_KEY_LOCALBYOM',
+ models: [{ id: 'byom-model', name: 'BYOM Model' }],
+ },
+ ],
+ env: { CINDY_PI_KEY_LOCALBYOM: 'byom-secret-key' },
+ });
+ const agent = new PiAgent(deps);
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-byom-cwd-'));
+ let handle: AgentSessionHandle | null = null;
+ try {
+ const gatewayBefore = seenRequests.length;
+ handle = await agent.startSession({
+ sessionId: 'byom-session',
+ workingDir,
+ model: 'byom-model', // 属于原生 provider,不是网关模型
+ });
+ // models.json 里有独立的 localbyom provider 块,baseUrl 直连原生端点。
+ const { readFileSync } = await import('node:fs');
+ const config = JSON.parse(readFileSync(path.join(agentHome, 'models.json'), 'utf8')) as {
+ providers: Record<string, { baseUrl: string; api: string; apiKey: string; models: Array<{ id: string }> }>;
+ };
+ expect(config.providers.localbyom).toBeDefined();
+ expect(config.providers.localbyom.baseUrl).toBe(nativeUrl);
+ expect(config.providers.localbyom.api).toBe('anthropic-messages');
+ expect(config.providers.localbyom.apiKey).toBe('$CINDY_PI_KEY_LOCALBYOM');
+ expect(config.providers.localbyom.models.some((m) => m.id === 'byom-model')).toBe(true);
+ // 网关 provider cindy 仍在(网关模型不受影响)。
+ expect(config.providers.cindy).toBeDefined();
+
+ const done = (async () => {
+ for await (const ev of handle!.events()) {
+ if (ev.type === 'done') break;
+ }
+ })();
+ await handle.send({ type: 'user', content: 'hi byom' });
+ await done;
+
+ // 关键:请求打到了原生端点(直连),带原生 key;网关一个请求都没多。
+ expect(nativeSeen.length).toBeGreaterThan(0);
+ expect(nativeSeen.some((r) => (r.auth ?? '').includes('byom-secret-key'))).toBe(true);
+ expect(seenRequests.length).toBe(gatewayBefore);
+ } finally {
+ await handle?.close();
+ await new Promise<void>((r) => nativeServer.close(() => r()));
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ },
+ );
+
it(
'exportSessionHtml writes a real HTML file via pi export_html (offline, no gateway)',
{ timeout: 60_000 },
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index b85334f58b..3402232a97 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -30,6 +30,7 @@ import {
type AgentDeps,
type AgentSessionHandle,
type PiExtraSpawnConfig,
+ type PiNativeProviderSpec,
type SendOptions,
type StartSessionOptions,
} from '../base-agent.js';
@@ -248,10 +249,16 @@ export class PiAgent extends BaseAgent {
}
/**
- * 生成 agentHome/models.json:host 模型清单 → provider `cindy`。
- * apiKey 用 env 插值形式,凭证本体只进子进程 env,不落盘。
+ * 生成 agentHome/models.json:
+ * - 网关模型 → 单一 provider `cindy`(baseUrl = compat proxy);
+ * - BYOM 原生 provider(nativeProviders)→ **各自独立 provider 块**,baseUrl 直连用户端点,
+ * 不过 compat 代理(设计原则:pi 主导,禁双重转义)。
+ * apiKey 一律用 `$ENV` 插值,凭证本体只进子进程 env,不落盘。
*/
- private async writeModelsJson(agentHome: string): Promise<void> {
+ private async writeModelsJson(
+ agentHome: string,
+ nativeProviders: PiNativeProviderSpec[] = [],
+ ): Promise<void> {
const endpoint = this.deps.runtimeConfig.endpoint;
if (!endpoint) {
this.deps.logger.warn('pi: runtimeConfig.endpoint missing — models.json will have no usable provider');
@@ -271,22 +278,56 @@ export class PiAgent extends BaseAgent {
cacheWrite: m.cost?.cacheWrite ?? 0,
},
}));
- const config = {
- providers: {
- [PI_PROVIDER_ID]: {
- name: 'Cindy AI',
- baseUrl: endpoint ?? 'http://127.0.0.1:0',
- api: 'anthropic-messages',
- apiKey: `$${PI_API_KEY_ENV}`,
- headers: {
- 'x-cindy-pi-session-id': `$${PI_SESSION_ID_ENV}`,
- },
- models,
+ const providers: Record<string, unknown> = {
+ [PI_PROVIDER_ID]: {
+ name: 'Cindy AI',
+ baseUrl: endpoint ?? 'http://127.0.0.1:0',
+ api: 'anthropic-messages',
+ apiKey: `$${PI_API_KEY_ENV}`,
+ headers: {
+ 'x-cindy-pi-session-id': `$${PI_SESSION_ID_ENV}`,
},
+ models,
},
};
+ for (const np of nativeProviders) {
+ if (np.id === PI_PROVIDER_ID) {
+ this.deps.logger.warn('pi: native provider id collides with gateway provider "cindy" — skipped', { id: np.id });
+ continue;
+ }
+ providers[np.id] = {
+ name: np.name,
+ baseUrl: np.baseUrl,
+ api: np.api,
+ // keyless(本机 Ollama 等)也要给 dummy key,否则 pi /model 不显示该模型。
+ apiKey: np.apiKeyEnvVar ? `$${np.apiKeyEnvVar}` : 'pi-native-keyless',
+ ...(np.headers && Object.keys(np.headers).length > 0 ? { headers: np.headers } : {}),
+ models: np.models.map((m) => ({
+ id: m.id,
+ name: m.name ?? m.id,
+ reasoning: m.reasoning ?? false,
+ input: m.input ?? ['text'],
+ contextWindow: m.contextWindow && m.contextWindow > 0 ? m.contextWindow : 128_000,
+ maxTokens: m.maxTokens && m.maxTokens > 0 ? m.maxTokens : 16_000,
+ })),
+ };
+ }
await fs.mkdir(agentHome, { recursive: true });
- await fs.writeFile(path.join(agentHome, 'models.json'), JSON.stringify(config, null, 2) + '\n');
+ await fs.writeFile(path.join(agentHome, 'models.json'), JSON.stringify({ providers }, null, 2) + '\n');
+ }
+
+ /**
+ * model id → provider id 路由表。网关模型 → `cindy`;BYOM 原生模型 → 各自 provider id
+ * (撞 id 时原生优先——用户显式配置)。setModel / 初始 --provider 据此选对 provider。
+ */
+ private buildModelProviderMap(nativeProviders: PiNativeProviderSpec[]): Map<string, string> {
+ const map = new Map<string, string>();
+ for (const m of this.capabilities.availableModels) map.set(m.id, PI_PROVIDER_ID);
+ for (const np of nativeProviders) {
+ if (np.id === PI_PROVIDER_ID) continue;
+ for (const m of np.models) map.set(m.id, np.id);
+ }
+ return map;
}
async startSession(opts: StartSessionOptions): Promise<AgentSessionHandle> {
@@ -320,8 +361,32 @@ export class PiAgent extends BaseAgent {
providerId: authProviderId,
});
+ // BYOM:host 解析当前会话可用的原生 provider(用户自定义/本地模型)+ 需注入的 env(keys)。
+ // 缺省 → 空,只有网关 provider `cindy`(现状不变)。失败不致命,降级为无原生 provider。
+ let nativeProviders: PiNativeProviderSpec[] = [];
+ let nativeEnv: Record<string, string> = {};
+ if (this.deps.resolvePiNativeProviders) {
+ try {
+ const resolved = await this.deps.resolvePiNativeProviders({
+ workingDir: opts.workingDir,
+ remoteHostId: opts.remoteHostId,
+ });
+ nativeProviders = resolved?.providers ?? [];
+ nativeEnv = resolved?.env ?? {};
+ } catch (err) {
+ this.deps.logger.warn('pi resolvePiNativeProviders failed, continuing gateway-only', {
+ message: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ const modelProviderMap = this.buildModelProviderMap(nativeProviders);
+ // 选定模型所属 provider(BYOM 模型 → 其原生 provider;其余 → 网关 cindy)。
+ const resolveProviderForModel = (model: string): string =>
+ modelProviderMap.get(model) ?? PI_PROVIDER_ID;
+ const initialProvider = resolveProviderForModel(opts.model);
+
const agentHome = this.resolveAgentHome();
- await this.writeModelsJson(agentHome);
+ await this.writeModelsJson(agentHome, nativeProviders);
const sessionDir = path.join(agentHome, 'sessions');
await fs.mkdir(sessionDir, { recursive: true });
@@ -430,7 +495,7 @@ export class PiAgent extends BaseAgent {
const args = [
'--mode', 'rpc',
'--session-dir', sessionDir,
- '--provider', PI_PROVIDER_ID,
+ '--provider', initialProvider,
'--model', opts.model,
...(appendSystemPrompt.length > 0 ? ['--append-system-prompt', appendSystemPrompt] : []),
...(planModeExtAvailable ? ['--extension', planModeExtPath] : []),
@@ -453,6 +518,8 @@ export class PiAgent extends BaseAgent {
const spawnEnv: NodeJS.ProcessEnv = {
...process.env,
...authEnv,
+ // BYOM 原生 provider 的 api keys(键名对应 spec.apiKeyEnvVar,models.json 用 $ENV 引用)。
+ ...nativeEnv,
[PI_SESSION_ID_ENV]: opts.sessionId ?? '',
PI_CODING_AGENT_DIR: agentHome,
CINDY_PI_PERMISSION_FILE: permissionFile,
@@ -673,7 +740,9 @@ export class PiAgent extends BaseAgent {
},
async setModel(model: string): Promise<void> {
- const resp = await proc.request({ type: 'set_model', provider: PI_PROVIDER_ID, modelId: model });
+ // BYOM:按 model→provider 路由(原生模型走其 provider,其余走网关 cindy)。
+ const provider = resolveProviderForModel(model);
+ const resp = await proc.request({ type: 'set_model', provider, modelId: model });
if (!resp.success) throw new Error(`pi set_model failed: ${resp.error ?? 'unknown'}`);
const data = (resp.data ?? {}) as { contextWindow?: number };
if (typeof data.contextWindow === 'number' && data.contextWindow > 0) {