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(pi): bind implicit native provider routes

Chris7d6db17625c1
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
index ead1c67a09..f984981add 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
@@ -191,12 +191,13 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
setProviderOAuthTokenReader((providerId, agent) =>
providerId === 'anthropic' && agent === 'pi' ? Promise.resolve('pi-claude-token') : null,
);
- registerPiProxySession('sess-pi', 'session-secret');
+ registerPiProxySession('sess-pi', 'session-secret', () => 'anthropic');
const decision = createModelRoutingTransform()(
{ model: 'claude-opus-5' },
ctxWith({
'x-cindy-pi-session-id': 'sess-pi',
'x-cindy-pi-session-token': 'session-secret',
+ 'x-cindy-pi-provider-id': 'anthropic',
'x-api-key': 'cindy-pi-provider-auth-placeholder',
}),
);
@@ -222,7 +223,7 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
['xai', '/v1/chat/completions'],
] as const)('routes native %s PI requests to a local raw forwarder at %s', (providerId, url) => {
setSessionProvider('sess-pi', providerId);
- registerPiProxySession('sess-pi', 'session-secret');
+ registerPiProxySession('sess-pi', 'session-secret', () => providerId);
const decision = createModelRoutingTransform()(
undefined,
ctxWith({
@@ -235,9 +236,51 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
expect(decision).toEqual({ localHandler: expect.any(Function) });
});
+ it.each([
+ ['openai', '/codex/responses'],
+ ['xai', '/v1/responses'],
+ ] as const)('trusts the host-resolved implicit %s PI source when persistence is empty', (providerId, url) => {
+ clearSessionProvider('sess-pi');
+ registerPiProxySession('sess-pi', 'session-secret', () => providerId);
+ const decision = createModelRoutingTransform()(
+ undefined,
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'session-secret',
+ 'x-cindy-pi-provider-id': providerId,
+ }, url),
+ );
+
+ expect(decision).toEqual({ localHandler: expect.any(Function) });
+ });
+
+ it('rejects an implicit native header that differs from the host-resolved PI source', async () => {
+ clearSessionProvider('sess-pi');
+ registerPiProxySession('sess-pi', 'session-secret', () => 'xai');
+ const decision = await createModelRoutingTransform()(
+ undefined,
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'session-secret',
+ 'x-cindy-pi-provider-id': 'openai',
+ }, '/codex/responses'),
+ );
+ const response = {
+ status: 0,
+ body: '',
+ writeHead(status: number) { this.status = status; },
+ end(body: string) { this.body = body; },
+ };
+
+ await decision?.localHandler?.({ res: response } as never);
+
+ expect(response.status).toBe(403);
+ expect(response.body).toContain('pi_provider_mismatch');
+ });
+
it('rejects a native provider header that does not match the Cindy session provider', async () => {
setSessionProvider('sess-pi', 'anthropic');
- registerPiProxySession('sess-pi', 'session-secret');
+ registerPiProxySession('sess-pi', 'session-secret', () => 'anthropic');
const decision = await createModelRoutingTransform()(
undefined,
ctxWith({
@@ -261,7 +304,7 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
it('rejects a missing native provider header for an OpenAI PI session', async () => {
setSessionProvider('sess-pi', 'openai');
- registerPiProxySession('sess-pi', 'session-secret');
+ registerPiProxySession('sess-pi', 'session-secret', () => 'openai');
const decision = await createModelRoutingTransform()(
undefined,
ctxWith({
@@ -285,7 +328,7 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
it('does not send an authenticated Anthropic PI request through the legacy prefix bridge', async () => {
setClaudeProxyGatewayKeyReader(() => 'sk-gw');
setSessionProvider('sess-pi', 'anthropic');
- registerPiProxySession('sess-pi', 'session-secret');
+ registerPiProxySession('sess-pi', 'session-secret', () => 'anthropic');
setProviderOAuthTokenReader((providerId, agent) =>
providerId === 'anthropic' && agent === 'pi' ? Promise.resolve('pi-claude-token') : null,
);
@@ -306,7 +349,7 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
it('rejects a forged session id before provider credentials can be selected', async () => {
setSessionProvider('sess-pi', 'anthropic');
- registerPiProxySession('sess-pi', 'real-secret');
+ registerPiProxySession('sess-pi', 'real-secret', () => 'anthropic');
const decision = await createModelRoutingTransform()(
{ model: 'claude-opus-5' },
ctxWith({
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
index 057c5b5917..eb6be096f6 100644
--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
@@ -90,7 +90,10 @@ import {
createClaudeSessionActivityResponseObserver,
recordClaudeApiActivity,
} from './claude-session-background-activity.js';
-import { authenticatePiProxySession } from './pi-proxy-session-auth.js';
+import {
+ authenticatePiProxySession,
+ getPiProxySessionProvider,
+} from './pi-proxy-session-auth.js';
// scope = 'cc-proxy' → logger.ts 的 emit() 路由把这条流量并入统一 agent 流
// (agent-*.ndjson, source=proxy)。child(sub) 会继续保持 'cc-proxy/sub' 前缀, routing 一致。
@@ -195,20 +198,29 @@ export function createModelRoutingTransform(): RoutingTransform {
const piProviderId = piSessionId
? headerValue(ctx.headers, 'x-cindy-pi-provider-id')
: null;
+ const registeredPiProviderId = piSessionId
+ ? getPiProxySessionProvider(piSessionId)
+ : null;
const selectedPiProviderId = piSessionId ? getSessionProvider(piSessionId) : null;
if (
piSessionId
&& (
- (piProviderId !== null && piProviderId !== selectedPiProviderId)
+ piProviderId !== registeredPiProviderId
+ || (
+ piProviderId !== null
+ && selectedPiProviderId !== null
+ && piProviderId !== selectedPiProviderId
+ )
|| (
(selectedPiProviderId === 'openai' || selectedPiProviderId === 'xai')
&& piProviderId !== selectedPiProviderId
)
)
) {
- // A valid loopback session token authorizes only the provider selected by
- // that Cindy session. Do not let a child process/extension swap this
- // internal header and borrow another connected subscription credential.
+ // A valid loopback session token authorizes only the provider that the
+ // host resolved for this exact Pi process. The persisted session choice
+ // remains a second constraint when present. Do not let a child process or
+ // extension swap this header and borrow another subscription credential.
return {
localHandler: async ({ res }) => {
const payload = JSON.stringify({
diff --git a/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts
index 6ef57baf6c..8d33141485 100644
--- a/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts
+++ b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts
@@ -9,18 +9,27 @@
import { timingSafeEqual } from 'node:crypto';
-const activeTokens = new Map<string, string>();
+interface ActivePiProxySession {
+ token: string;
+ resolveProviderId: () => string | null;
+}
+
+const activeSessions = new Map<string, ActivePiProxySession>();
-export function registerPiProxySession(sessionId: string, token: string): () => void {
+export function registerPiProxySession(
+ sessionId: string,
+ token: string,
+ resolveProviderId: () => string | null = () => null,
+): () => void {
if (!sessionId || !token) throw new Error('Pi proxy session registration requires an id and token');
- activeTokens.set(sessionId, token);
+ activeSessions.set(sessionId, { token, resolveProviderId });
return () => {
- if (activeTokens.get(sessionId) === token) activeTokens.delete(sessionId);
+ if (activeSessions.get(sessionId)?.token === token) activeSessions.delete(sessionId);
};
}
export function authenticatePiProxySession(sessionId: string, candidate: string | null): boolean {
- const expected = activeTokens.get(sessionId);
+ const expected = activeSessions.get(sessionId)?.token;
if (!expected || !candidate) return false;
const expectedBytes = Buffer.from(expected);
const candidateBytes = Buffer.from(candidate);
@@ -28,7 +37,15 @@ export function authenticatePiProxySession(sessionId: string, candidate: string
&& timingSafeEqual(expectedBytes, candidateBytes);
}
+/**
+ * Host-resolved provider bound to the authenticated Pi process. Callers must
+ * authenticate the same session immediately before reading this value.
+ */
+export function getPiProxySessionProvider(sessionId: string): string | null {
+ return activeSessions.get(sessionId)?.resolveProviderId() ?? null;
+}
+
/** Test isolation only. */
export function resetPiProxySessionsForTest(): void {
- activeTokens.clear();
+ activeSessions.clear();
}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 340d847c13..01b93b783a 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -464,9 +464,15 @@ export interface AgentDeps {
/**
* Pi-only: authenticate a child process to the host's loopback model proxy.
* PiAgent creates a high-entropy token per session, registers it before spawn,
- * and disposes the exact registration when startup fails or the session closes.
- */
- registerPiProxySession?: (sessionId: string, token: string) => (() => void) | void;
+ * binds the currently resolved native provider, and disposes the exact
+ * registration when startup fails or the session closes. The provider reader
+ * follows confirmed set_model changes without trusting a child-supplied header.
+ */
+ registerPiProxySession?: (
+ sessionId: string,
+ token: string,
+ resolveProviderId: () => string | null,
+ ) => (() => void) | void;
/**
* BYOM:host 解析出当前会话可用的 pi **原生 provider**(用户自定义/本地模型)+ 需注入的
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index fd67bd6e6e..9a97be4d74 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -205,6 +205,7 @@ describe('Pi provider-aware model routing', () => {
it('routes host subscriptions through PI native providers and wire model ids', async () => {
const authProviderIds: Array<string | null | undefined> = [];
+ let resolveProxyProviderId: (() => string | null) | undefined;
const availableModels: ModelDescriptor[] = [
{
id: 'chatgpt/gpt-cindy-daily-test', displayName: 'GPT Daily', contextWindow: 272_000,
@@ -239,6 +240,9 @@ describe('Pi provider-aware model routing', () => {
capabilityAdditions: { availableModels },
resolvePiAgentHome: () => agentHome,
resolvePiGatewayModelApi: () => 'openai-responses',
+ registerPiProxySession: (_sessionId, _token, resolveProviderId) => {
+ resolveProxyProviderId = resolveProviderId;
+ },
resolvePiNativeProviders: async () => ({
providers: [
{
@@ -280,11 +284,11 @@ describe('Pi provider-aware model routing', () => {
sessionId: 'native-subscription-routing',
workingDir: cwd,
model: 'chatgpt/gpt-cindy-daily-test',
- providerId: 'openai',
effort: 'high',
});
expect(authProviderIds).toEqual(['openai']);
+ expect(resolveProxyProviderId?.()).toBe('openai');
expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 4))
.toEqual(['--provider', 'openai-codex', '--model', 'gpt-cindy-daily-test']);
const configHome = captured.env.PI_CODING_AGENT_DIR as string;
@@ -316,6 +320,7 @@ describe('Pi provider-aware model routing', () => {
expect(captured.requests).toContainEqual({
type: 'set_model', provider: 'xai', modelId: 'grok-4.5',
});
+ expect(resolveProxyProviderId?.()).toBe('xai');
expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'native-subscription-routing'), 'utf8')))
.toEqual({ model: 'grok-4.5', provider: 'xai' });
@@ -323,6 +328,7 @@ describe('Pi provider-aware model routing', () => {
expect(captured.requests).toContainEqual({
type: 'set_model', provider: 'anthropic', modelId: 'claude-opus-5',
});
+ expect(resolveProxyProviderId?.()).toBe('anthropic');
await handle.close();
});
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index b12cea73a4..7cfce5f4ff 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -1807,7 +1807,13 @@ export class PiAgent extends BaseAgent {
this.deps.runtimeConfig.managedExecutablePaths?.ripgrep,
);
if (proxySessionToken && opts.sessionId && this.deps.registerPiProxySession) {
- const disposer = this.deps.registerPiProxySession(opts.sessionId, proxySessionToken);
+ const disposer = this.deps.registerPiProxySession(
+ opts.sessionId,
+ proxySessionToken,
+ () => mutablePiProviderId === PI_PROVIDER_ID
+ ? null
+ : resolveSourceProvider(mutablePiProviderId),
+ );
if (typeof disposer === 'function') disposeProxySession = disposer;
}
// 视觉桥后端 env(层 C):host 解析后注入,cindy-bridge 的 vision 工具读取。