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): owner-boundary 期间 Claude 代理不再把占位凭证打到 LiteLLM (#3616)

Dash94a96110a5de
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 1c161a3a63..98b9a7924d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
@@ -46,6 +46,8 @@ vi.mock('../claude-fast-mode-log', () => ({
import {
createModelRoutingTransform,
setClaudeProxyGatewayKeyReader,
+ setClaudeProxyOwnerBoundaryPendingChecker,
+ setClaudeProxyOwnerScopeKeyReader,
setClaudeProxySessionIdResolver,
} from '../anthropic-compat-proxy-host';
import { setSessionProvider, clearSessionProvider } from '../session-provider-store';
@@ -81,6 +83,8 @@ describe('cc routingTransform — xAI 会话的辅助请求回落默认路由 (i
afterEach(() => {
clearSessionProvider('sess-grok');
setPendingCredentialSwitchReader(() => undefined);
+ setClaudeProxyOwnerBoundaryPendingChecker(() => false);
+ setClaudeProxyOwnerScopeKeyReader(() => '');
});
it('订阅直连目标也在进入 bridge 前拦截 pending switch', async () => {
@@ -266,6 +270,202 @@ describe('cc routingTransform — xAI 会话的辅助请求回落默认路由 (i
});
});
+describe('cc routingTransform — owner boundary 不得把占位 key fail-open 到 LiteLLM', () => {
+ const PLACEHOLDER = 'xdt-provider-auth-placeholder-key';
+ const throwingResolver = () => {
+ throw new Error('[PRECONDITION_FAILED] App session is switching; retry after the owner boundary settles.');
+ };
+
+ let gatewayKey: string | null;
+
+ beforeEach(() => {
+ resetClaudeSessionRouteRegistryForTest();
+ gatewayKey = 'sk-gw';
+ setClaudeProxyGatewayKeyReader(() => gatewayKey);
+ setClaudeProxySessionIdResolver(throwingResolver);
+ setClaudeProxyOwnerBoundaryPendingChecker(() => false);
+ setClaudeProxyOwnerScopeKeyReader(() => '');
+ setPendingCredentialSwitchReader(() => undefined);
+ });
+
+ afterEach(() => {
+ setClaudeProxyOwnerBoundaryPendingChecker(() => false);
+ setClaudeProxyOwnerScopeKeyReader(() => '');
+ setPendingCredentialSwitchReader(() => undefined);
+ resetPiProxySessionsForTest();
+ });
+
+ async function invokeLocalHandler(decision: Awaited<ReturnType<ReturnType<typeof createModelRoutingTransform>>>) {
+ const writeHead = vi.fn();
+ const end = vi.fn();
+ await decision?.localHandler?.({ res: { writeHead, end, headersSent: false } } as never);
+ return { writeHead, end };
+ }
+
+ it('resolver 抛 PRECONDITION_FAILED 时 xai/grok-4.6 仍走订阅桥/拒绝,不 passthrough', async () => {
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ { model: 'xai/grok-4.6' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }),
+ ),
+ );
+ expect(decision?.localHandler).toEqual(expect.any(Function));
+ expect(decision).not.toEqual(expect.objectContaining({
+ headerOverride: expect.anything(),
+ }));
+ });
+
+ it('boundary pending + 占位 key + 非订阅模型 → 503 Retry-After,不是 null', async () => {
+ gatewayKey = null;
+ setClaudeProxyOwnerBoundaryPendingChecker(() => true);
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ { model: 'claude-haiku-4-5-20251001' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }),
+ ),
+ );
+ expect(decision).not.toBeNull();
+ const { writeHead, end } = await invokeLocalHandler(decision);
+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({
+ 'retry-after': '1',
+ }));
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: { code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('boundary pending + 占位 key + 无 body(GET) → 503,不打默认上游', async () => {
+ gatewayKey = null;
+ setClaudeProxyOwnerBoundaryPendingChecker(() => true);
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ undefined,
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }, '/v1/models'),
+ ),
+ );
+ const { writeHead, end } = await invokeLocalHandler(decision);
+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({
+ 'retry-after': '1',
+ }));
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: { code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('boundary pending 时订阅前缀模型也 503,不把旧 owner 的 OAuth 打到 SuperGrok', async () => {
+ gatewayKey = null;
+ setClaudeProxyOwnerBoundaryPendingChecker(() => true);
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ { model: 'xai/grok-4.6' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }),
+ ),
+ );
+ const { writeHead, end } = await invokeLocalHandler(decision);
+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({
+ 'retry-after': '1',
+ }));
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: { code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('boundary pending 时 chatgpt/ 前缀同样 503,不读旧 owner 的 Codex OAuth', async () => {
+ gatewayKey = null;
+ setClaudeProxyOwnerBoundaryPendingChecker(() => true);
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ { model: 'chatgpt/gpt-5.5' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }),
+ ),
+ );
+ const { writeHead, end } = await invokeLocalHandler(decision);
+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({
+ 'retry-after': '1',
+ }));
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: { code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('boundary pending 时 PI 原生 xai 转发也 503,不读旧 owner 的 Grok OAuth', async () => {
+ gatewayKey = null;
+ setClaudeProxyOwnerBoundaryPendingChecker(() => true);
+ registerPiProxySession('sess-pi', 'session-secret', () => 'xai');
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ { model: 'grok-4.6' },
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'session-secret',
+ 'x-cindy-pi-provider-id': 'xai',
+ 'x-api-key': PLACEHOLDER,
+ }),
+ ),
+ );
+ const { writeHead, end } = await invokeLocalHandler(decision);
+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({
+ 'retry-after': '1',
+ }));
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: { code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('finalize 之后、localHandler 调用前才 pending → 503,不读旧 owner OAuth', async () => {
+ gatewayKey = null;
+ let pending = false;
+ setClaudeProxyOwnerBoundaryPendingChecker(() => pending);
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ { model: 'xai/grok-4.6' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }),
+ ),
+ );
+ expect(decision?.localHandler).toEqual(expect.any(Function));
+ pending = true;
+ const { writeHead, end } = await invokeLocalHandler(decision);
+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({
+ 'retry-after': '1',
+ }));
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: { code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('finalize 之后 owner scope 变了但 pending 仍 false → 503,不读旧 owner OAuth', async () => {
+ gatewayKey = null;
+ let scopeKey = 'cloud:owner-a:1';
+ setClaudeProxyOwnerBoundaryPendingChecker(() => false);
+ setClaudeProxyOwnerScopeKeyReader(() => scopeKey);
+ const decision = await Promise.resolve(
+ createModelRoutingTransform()(
+ { model: 'xai/grok-4.6' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }),
+ ),
+ );
+ expect(decision?.localHandler).toEqual(expect.any(Function));
+ scopeKey = 'cloud:owner-b:2';
+ const { writeHead, end } = await invokeLocalHandler(decision);
+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({
+ 'retry-after': '1',
+ }));
+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({
+ error: { code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('resolver 抛错但有网关 key 时分类器仍换 key(#831),不 passthrough 占位', () => {
+ const decision = createModelRoutingTransform()(
+ { model: 'claude-haiku-4-5-20251001' },
+ ctxWith({ ...SESSION_HEADER, 'x-api-key': PLACEHOLDER }),
+ );
+ expect(decision).toEqual({
+ headerOverride: { 'x-api-key': 'sk-gw', authorization: 'Bearer sk-gw' },
+ });
+ });
+});
+
describe('pi routingTransform — xdt session header selects the Pi provider route', () => {
afterEach(() => {
clearSessionProvider('sess-pi');
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
index e4fa0dbb1d..ff268c5909 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -1,13 +1,25 @@
import { EventEmitter } from 'node:events';
import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { createAnthropicCompatProxy } from '@cindy/anthropic-compat-proxy';
+const { ownerState } = vi.hoisted(() => ({
+ ownerState: {
+ pending: false,
+ scope: 'cloud:owner-a:1',
+ },
+}));
+
vi.mock('electron', () => ({
app: { getPath: () => '/tmp/cindy-pi-native-forwarding-test' },
}));
+vi.mock('../../appSessionState.js', () => ({
+ isAppSessionBoundaryPending: () => ownerState.pending,
+ activeOwnerScopeKey: () => ownerState.scope,
+}));
+
vi.mock('../logger-adapter.js', () => ({
createMakerLogger: () => {
const make = (): Record<string, unknown> => ({
@@ -77,6 +89,11 @@ function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativ
}
describe('PI native subscription forwarding', () => {
+ afterEach(() => {
+ ownerState.pending = false;
+ ownerState.scope = 'cloud:owner-a:1';
+ });
+
it('forwards Codex Responses bytes unchanged with host-owned ChatGPT auth', async () => {
const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {
status: 200,
@@ -805,6 +822,80 @@ describe('PI native subscription forwarding', () => {
});
});
+ it('does not fetch after ChatGPT context-profile rewrite if owner scope changed', async () => {
+ const fetchMock = vi.fn(async () => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const handler = getPiNativeSubscriptionHandler('openai', 'session-rewrite-scope', deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ getChatgptAuth: vi.fn(async () => {
+ const auth = { accessToken: 'token-owner-a', accountId: 'account-1' };
+ ownerState.scope = 'cloud:owner-b:2';
+ return auth;
+ }),
+ }));
+ const compressed = zstdCompressSync(Buffer.from(JSON.stringify({
+ model: 'gpt-5.6-sol[1m]',
+ input: 'hello',
+ })));
+ const res = responseRecorder();
+
+ await handler({
+ rawBody: compressed,
+ parsedBody: undefined,
+ ctx: {
+ reqId: 21,
+ method: 'POST',
+ url: '/codex/responses',
+ headers: {
+ 'content-type': 'application/json',
+ 'content-encoding': 'zstd',
+ },
+ },
+ res,
+ } as never);
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(res.status).toBe(503);
+ expect(JSON.parse(Buffer.concat(res.chunks).toString('utf8'))).toMatchObject({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ });
+
+ it('does not fetch xAI after sanitizing the body if owner scope changed', async () => {
+ const fetchMock = vi.fn(async () => new Response('ok', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-sanitize-scope', deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ getGrokToken: vi.fn(async () => {
+ ownerState.scope = 'cloud:owner-b:2';
+ return 'token-owner-a';
+ }),
+ }));
+ const res = responseRecorder();
+
+ await handler({
+ rawBody: Buffer.from('{"model":"grok-4.6"}'),
+ parsedBody: { model: 'grok-4.6' },
+ ctx: {
+ reqId: 22,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res,
+ } as never);
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(res.status).toBe(503);
+ expect(JSON.parse(Buffer.concat(res.chunks).toString('utf8'))).toMatchObject({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ });
+
it('rejects unsupported native paths without contacting an upstream', async () => {
const injected = deps();
const handler = getPiNativeSubscriptionHandler('openai', 'session-3', injected);
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 bfe10f1294..a6e76a58fe 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
@@ -39,6 +39,7 @@ import {
stripNonAnthropicFields,
stripToolUseProviderSpecificFields,
type ProxyHandle,
+ type RequestTransformCtx,
type RoutingDecision,
type RoutingTransform,
} from '@cindy/anthropic-compat-proxy';
@@ -50,6 +51,10 @@ import {
getPiNativeSubscriptionHandler,
getResponsesBridgeHandler,
} from './anthropic-responses-bridge-host.js';
+import {
+ OWNER_BOUNDARY_PENDING_ERROR,
+ isOwnerBoundaryPendingError,
+} from './owner-boundary-error.js';
import { getSessionEffort, getSessionFastMode } from './session-effort-store.js';
import {
isExclusiveXaiModelId,
@@ -141,13 +146,47 @@ export function setClaudeProxyOAuthSpawnChecker(fn: () => boolean): void {
// x-claude-code-session-id(= cc sdkSessionId)反解成 xdt sessionId 提供。返回 null = 该
// sdkSessionId 当前无对应活跃会话。routingTransform 据此查该会话显式选定的供应商做统一路由;
// 未注入 / 查不到 / 该会话没选供应商 → 回落 spawn-aware 默认路由(与未升级行为字节级一致)。
+//
+// 热路径必须永不抛:ipcMaker 在 owner boundary 会抛 PRECONDITION_FAILED,proxy 引擎捕获后
+// fail-open 默认 LiteLLM,provider-oauth 占位 key 原样上游 → 确定性 401。setter 内吞掉异常,
+// 当作「会话未反解」;真正的 fail-closed 在 routingTransform 收口(boundary pending → 503,
+// 含订阅桥;非 boundary 的占位透传合同不变)。
let _resolveCcSessionId: ((sdkSessionId: string) => string | null) | null = null;
export function setClaudeProxySessionIdResolver(
fn: (sdkSessionId: string) => string | null,
): void {
- _resolveCcSessionId = fn;
+ _resolveCcSessionId = (sdkSessionId) => {
+ try {
+ return fn(sdkSessionId);
+ } catch (err) {
+ log.warn('cc session resolver threw; treating as unresolved', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
+ };
+}
+
+// owner-boundary 探针 —— 由 host 注入 isAppSessionBoundaryPending。pending 期间
+// canUseCindyGateway=false,网关 key 读出来是 null;订阅桥仍会经 getGrokAccessToken /
+// getChatgptBridgeAuth 读 getActiveAppSession()(commit 前是上一任 owner)。决策、
+// localHandler 入口/catch、引擎 dispatch 再校验都读同一条探针,不豁免任何出站。
+let _isOwnerBoundaryPending: () => boolean = () => false;
+export function setClaudeProxyOwnerBoundaryPendingChecker(fn: () => boolean): void {
+ _isOwnerBoundaryPending = fn;
+}
+
+// owner scope key —— 由 host 注入 activeOwnerScopeKey。pending 布尔值挡不住
+// 「切换在 await 里完整开始并结束」:两端 pending 都是 false,但 generation 已经变了。
+// 与 pending 合成同一条 ownerBoundDispatchUnsafe;不另造 generation 子系统。
+// 未注入时恒返空串,既有 pending-only 单测行为不变。
+let _readOwnerScopeKey: () => string = () => '';
+export function setClaudeProxyOwnerScopeKeyReader(fn: () => string): void {
+ _readOwnerScopeKey = fn;
}
+const ownerScopeAtRequestStart = new WeakMap<RequestTransformCtx, string | null>();
+
// 订阅直连的 model 前缀判据(chatgpt/ / xai/)统一走 shared/subscriptionModels 的
// isSubscriptionDirectModel —— 路由(此处把这些前缀路由到 bridge)与 turn-cost 记账 gate
// 必须同源,否则漂移 = 路由当订阅直连、记账当真实计费(计费错算)。
@@ -215,6 +254,137 @@ function headerValue(headers: Readonly<Record<string, string>>, name: string): s
return null;
}
+function isOwnerBoundaryPending(): boolean {
+ try {
+ return _isOwnerBoundaryPending();
+ } catch {
+ // 探针自己抛 = 凭证/归属无法安全确定,按 pending fail-closed。
+ return true;
+ }
+}
+
+function readOwnerScopeKey(): string | null {
+ try {
+ return _readOwnerScopeKey();
+ } catch {
+ return null;
+ }
+}
+
+/** 第一次写入为准:引擎在 collectRequestBody 前就盖章,body 期间切账号不得改基线。 */
+function stampOwnerScope(ctx: RequestTransformCtx): string | null {
+ const existing = ownerScopeAtRequestStart.get(ctx);
+ if (existing !== undefined) return existing;
+ const key = readOwnerScopeKey();
+ ownerScopeAtRequestStart.set(ctx, key);
+ return key;
+}
+
+/** pending,或这条请求开始后 owner generation 已经变了。 */
+function ownerBoundDispatchUnsafe(ctx?: RequestTransformCtx): boolean {
+ if (isOwnerBoundaryPending()) return true;
+ const start = ctx ? stampOwnerScope(ctx) : readOwnerScopeKey();
+ if (start === null) return true;
+ const now = readOwnerScopeKey();
+ return now === null || now !== start;
+}
+
+function retryableLocalRoute(code: string, message: string): RoutingDecision {
+ return {
+ localHandler: async ({ res }) => {
+ const payload = JSON.stringify({
+ type: 'error',
+ error: {
+ type: code,
+ code,
+ message,
+ },
+ });
+ res.writeHead(503, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'retry-after': '1',
+ });
+ res.end(payload);
+ },
+ };
+}
+
+function ownerBoundaryPendingRoute(): RoutingDecision {
+ return retryableLocalRoute(
+ 'owner_boundary_pending',
+ OWNER_BOUNDARY_PENDING_ERROR,
+ );
+}
+
+/** localHandler 入口 + catch 再看一眼:挡 finalize 之后、真正发凭证之前的 await。 */
+function withOwnerBoundaryDispatchGate(
+ resolved: RoutingDecision | null,
+ ctx: RequestTransformCtx,
+): RoutingDecision | null {
+ if (ownerBoundDispatchUnsafe(ctx)) return ownerBoundaryPendingRoute();
+ const inner = resolved?.localHandler;
+ if (!inner) return resolved;
+ return {
+ ...resolved,
+ localHandler: async (args) => {
+ if (ownerBoundDispatchUnsafe(ctx)) {
+ await ownerBoundaryPendingRoute().localHandler?.(args);
+ return;
+ }
+ try {
+ await inner(args);
+ } catch (err) {
+ if (!args.res.headersSent && (
+ isOwnerBoundaryPendingError(err) || ownerBoundDispatchUnsafe(ctx)
+ )) {
+ await ownerBoundaryPendingRoute().localHandler?.(args);
+ return;
+ }
+ throw err;
+ }
+ },
+ };
+}
+
+function routingTemporarilyUnavailableRoute(): RoutingDecision {
+ return retryableLocalRoute(
+ 'routing_temporarily_unavailable',
+ 'Claude proxy routing is temporarily unavailable; retry shortly.',
+ );
+}
+
+function carriesProviderAuthPlaceholder(headers: Readonly<Record<string, string>>): boolean {
+ return headerValue(headers, 'x-api-key') === CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY;
+}
+
+/** null / 只删头 / 空决策 = 仍打默认 LiteLLM。订阅桥、换 key、换上游都不是这条。 */
+function isDefaultUpstreamPassthrough(decision: RoutingDecision | null): boolean {
+ if (!decision) return true;
+ if (decision.localHandler) return false;
+ if (decision.upstreamOverride) return false;
+ if (decision.headerOverride && Object.keys(decision.headerOverride).length > 0) return false;
+ return true;
+}
+
+function refuseUnsafePlaceholderPassthrough(
+ decision: RoutingDecision | null,
+ ctx: RequestTransformCtx,
+): RoutingDecision | null {
+ if (!isDefaultUpstreamPassthrough(decision)) return decision;
+ if (!carriesProviderAuthPlaceholder(ctx.headers)) return decision;
+ if (!ownerBoundDispatchUnsafe(ctx)) return decision;
+ log.warn('owner boundary pending with provider-oauth placeholder; refusing default upstream');
+ return ownerBoundaryPendingRoute();
+}
+
+function routingTransformThrew(err: unknown, ctx: RequestTransformCtx): RoutingDecision {
+ log.warn('routingTransform threw; refusing default upstream', {
+ err: err instanceof Error ? err.message : String(err),
+ });
+ return ownerBoundDispatchUnsafe(ctx) ? ownerBoundaryPendingRoute() : routingTemporarilyUnavailableRoute();
+}
+
function unavailablePiProviderRoute(providerId: string): RoutingDecision {
return {
localHandler: async ({ res }) => {
@@ -586,15 +756,15 @@ export function createModelRoutingTransform(): RoutingTransform {
}
};
return (body, ctx) => {
- const decision = route(body, ctx);
+ stampOwnerScope(ctx);
const hasInternalPiHeader =
headerValue(ctx.headers, 'x-cindy-pi-session-id') !== null
|| headerValue(ctx.headers, 'x-cindy-pi-session-token') !== null
|| headerValue(ctx.headers, 'x-cindy-pi-provider-id') !== null;
- if (!hasInternalPiHeader) return decision;
const stripInternalPiHeaders = (
resolved: RoutingDecision | null,
): RoutingDecision | null => {
+ if (!hasInternalPiHeader) return resolved;
if (resolved?.localHandler) return resolved;
return {
...(resolved ?? {}),
@@ -608,9 +778,30 @@ export function createModelRoutingTransform(): RoutingTransform {
],
};
};
- return decision instanceof Promise
- ? decision.then(stripInternalPiHeaders)
- : stripInternalPiHeaders(decision);
+ const finalize = (resolved: RoutingDecision | null): RoutingDecision | null => {
+ // beginAppSessionBoundary 的 fail-closed:teardown 期间 getActiveAppSession() 仍是
+ // 上一任 owner。订阅桥 / PI 原生转发 / oauth headerOverride 都会读那份凭证,不能
+ // 因为 localHandler 不是「默认上游透传」就放行。
+ //
+ // 决策时检查挡不住 finalize 之后的 await(token refresh / request transform /
+ // outbound resolver / 透明重试)。localHandler 在这里再包一层入口+catch;转发
+ // 路径靠引擎 revalidateBeforeDispatch(请求开始、routing 后、outbound 后、重试前)。
+ // pending 与 activeOwnerScopeKey 合成同一条 ownerBoundDispatchUnsafe:
+ // 切换在 await 里完整完成时两端 pending 都是 false。
+ if (ownerBoundDispatchUnsafe(ctx)) return ownerBoundaryPendingRoute();
+ return withOwnerBoundaryDispatchGate(
+ refuseUnsafePlaceholderPassthrough(stripInternalPiHeaders(resolved), ctx),
+ ctx,
+ );
+ };
+ try {
+ const decision = route(body, ctx);
+ return decision instanceof Promise
+ ? decision.then(finalize, (err: unknown) => routingTransformThrew(err, ctx))
+ : finalize(decision);
+ } catch (err) {
+ return routingTransformThrew(err, ctx);
+ }
};
}
@@ -640,6 +831,8 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {
// 'oauth' 模式按 model 分流(claude-* → api.anthropic.com 走订阅;其余 → gateway 换 key)。
// 'gateway' 模式恒返 null,字节级行为与扩展前一致。
routingTransform: createModelRoutingTransform(),
+ revalidateBeforeDispatch: (_decision, ctx) =>
+ ownerBoundDispatchUnsafe(ctx) ? ownerBoundaryPendingRoute() : null,
// 只读响应观察器(组合三个,互不感知):
// - fast mode 链路核验:tee SSE 抽上游 usage.speed(debug-gated);
// - 订阅余量旁路:读 anthropic-ratelimit-unified-* headers(仅订阅直连响应,
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index 311272f6ef..bc690154b8 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -43,6 +43,12 @@ import { buildChatgptBridgeHeaders } from './chatgpt-bridge-headers.js';
import { recordXaiRateLimitSnapshot } from '../usageBroadcaster.js';
import { XAI_X_SEARCH_TOOL_TYPE, xaiServerSideTools } from './xai-server-side-tools.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from '../../shared/subscriptionModels.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import {
+ OWNER_BOUNDARY_PENDING_ERROR,
+ OwnerBoundaryPendingError,
+ isOwnerBoundaryPendingError,
+} from './owner-boundary-error.js';
import { describeErrorChain } from '../utils/errorChain.js';
const zstdCompressAsync = promisify(zstdCompress);
@@ -229,10 +235,19 @@ export const invalidateChatgptBridgeAuth = createChatgptBridgeAuthInvalidator({
},
});
+function throwIfOwnerBoundDispatchUnsafe(scopeAtStart: string): void {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scopeAtStart) {
+ throw new OwnerBoundaryPendingError();
+ }
+}
+
/** 经 adapter 判连接态 → 读 codex-home/auth.json → 必要时刷新 → 返回 token 与可选 account id。 */
export async function getChatgptBridgeAuth(): Promise<{ accessToken: string; accountId: string | null }> {
+ const scopeAtStart = activeOwnerScopeKey();
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
const now = Date.now();
if (_authCache && now - _authCache.readAt < AUTH_CACHE_TTL_MS && !isExpired(_authCache.accessToken)) {
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
return _authCache;
}
// 连接态门:adapter 返回 null = 已登出 / 服务端已判失效(provider UI 显示未连接)。
@@ -240,17 +255,20 @@ export async function getChatgptBridgeAuth(): Promise<{ accessToken: string; acc
// chatgpt/ 请求会继续用被断开(甚至被判坏)的账号。非 null 时 adapter 的 reconcile 已保证
// codex-home/auth.json 是权威文件(必要时从 ~/.codex 硬链),后续读写只针对它。
const adapterToken = await desktopCodexAuthAdapter.getAccessToken();
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
if (adapterToken == null) {
_authCache = null;
throw new Error('OpenAI(ChatGPT 订阅)未连接或凭证已失效:请在「设置 → 模型供应商」登录');
}
const authPath = codexHomeAuthPath();
let obj = await readAuthFile(authPath);
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
if (!obj?.tokens?.access_token) {
_authCache = null;
throw new Error('codex auth.json 无有效 access_token:请重新登录 OpenAI');
}
obj = await refreshIfNeeded(authPath, obj);
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
const accessToken = obj.tokens?.access_token;
const accountId = obj.tokens ? accountIdFrom(obj.tokens) : null;
if (!accessToken) {
@@ -681,7 +699,9 @@ export function getPiNativeSubscriptionHandler(
const controller = new AbortController();
const abortOnClose = (): void => controller.abort();
res.once('close', abortOnClose);
+ const scopeAtStart = activeOwnerScopeKey();
try {
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
let accessToken: string;
let headers: Record<string, string>;
if (providerId === 'openai') {
@@ -726,6 +746,7 @@ export function getPiNativeSubscriptionHandler(
contentEncoding = undefined;
}
}
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
if (contentEncoding) headers['content-encoding'] = contentEncoding;
const response = await deps.fetch(upstream.url, {
@@ -765,6 +786,22 @@ export function getPiNativeSubscriptionHandler(
// which destroys the client response so PI observes a transport failure
// instead of accepting a cleanly-ended truncated stream.
if (res.headersSent) throw err;
+ if (isOwnerBoundaryPendingError(err)) {
+ res.writeHead(503, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'retry-after': '1',
+ });
+ res.end(JSON.stringify({
+ type: 'error',
+ error: {
+ type: 'owner_boundary_pending',
+ code: 'owner_boundary_pending',
+ message: OWNER_BOUNDARY_PENDING_ERROR,
+ },
+ }));
+ return;
+ }
const detail = describeErrorChain(err);
const providerLabel = providerId === 'xai' ? 'xAI/Grok' : 'OpenAI/ChatGPT';
log.warn('PI native subscription forwarding failed', {
diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
index ebeb046803..809b0de107 100644
--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts
+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
@@ -32,6 +32,8 @@ import {
import { desktopMakerLogger } from './logger-adapter.js';
import { outboundFetch } from './outbound-fetch.js';
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { OwnerBoundaryPendingError } from './owner-boundary-error.js';
import { bindNativeProviderAuth, isNativeProviderAuthBound, unbindNativeProviderAuth } from './nativeProviderAuthBinding.js';
import type { XaiBridgeAuthRecoveryOutcome } from './xai-bridge-auth-invalidation.js';
@@ -768,17 +770,29 @@ async function refreshIfNeeded(current: GrokTokenBlob): Promise<GrokTokenBlob> {
return (await refreshBlob(current, false)).blob;
}
+function throwIfOwnerBoundDispatchUnsafe(scopeAtStart: string): void {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scopeAtStart) {
+ throw new OwnerBoundaryPendingError();
+ }
+}
+
/**
* 取当前可用的 xAI access_token(过期则先刷新)。bridge 的 buildHeaders 调用。
- * 未登录 / 刷新后仍无 token → 抛错(bridge 据此回 502)。
+ * 未登录 / 刷新后仍无 token → 抛错(bridge 据此回 502 authentication_error)。
+ * owner-boundary pending 或 await 期间 owner generation 变了时抛 OwnerBoundaryPendingError:
+ * 订阅桥 catch 必须收成 503,不得写成 authentication_error。
+ * peekGrokAccessToken 只读、不抛,失效等值用。
*/
export async function getGrokAccessToken(): Promise<string> {
+ const scopeAtStart = activeOwnerScopeKey();
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
if (!isNativeProviderAuthBound('xai')) {
throw new Error('xAI OAuth is not bound to the active data owner');
}
const blob = readBlob();
if (!blob) throw new Error('xAI 未登录:请先在「设置 → 模型供应商」登录 xAI(SuperGrok)');
const fresh = await refreshIfNeeded(blob);
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
if (!fresh.access_token) throw new Error('xAI access_token 不可用,请重新登录');
return fresh.access_token;
}
diff --git a/apps/desktop/src/main/maker-host/owner-boundary-error.ts b/apps/desktop/src/main/maker-host/owner-boundary-error.ts
new file mode 100644
index 0000000000..97e70186fc
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/owner-boundary-error.ts
@@ -0,0 +1,23 @@
+/**
+ * owner-bound 出站在账号切换窗口里的唯一可重试错误。
+ * 任何 catch 都不得把它改写成 401 / 502 / authentication_error。
+ */
+export const OWNER_BOUNDARY_PENDING_ERROR =
+ 'App session is switching; retry after the owner boundary settles.';
+
+export class OwnerBoundaryPendingError extends Error {
+ readonly code = 'owner_boundary_pending' as const;
+
+ constructor(message = OWNER_BOUNDARY_PENDING_ERROR) {
+ super(message);
+ this.name = 'OwnerBoundaryPendingError';
+ }
+}
+
+export function isOwnerBoundaryPendingError(err: unknown): boolean {
+ if (err instanceof OwnerBoundaryPendingError) return true;
+ if (!(err instanceof Error)) return false;
+ if (err.name === 'OwnerBoundaryPendingError') return true;
+ if ((err as { code?: unknown }).code === 'owner_boundary_pending') return true;
+ return err.message === OWNER_BOUNDARY_PENDING_ERROR;
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index cb48d196aa..deb1b58a69 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -59,6 +59,7 @@ import {
import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';
import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';
import {
+ activeOwnerScopeKey,
getActiveAppSession,
getActiveDataOwnerPushStamp,
isAppSessionBoundaryPending,
@@ -880,7 +881,11 @@ import {
shouldApplyExclusiveProviderRerouteLive,
verdictForModelRoute,
} from '../maker-host/model-route-guard-live.js';
-import { setClaudeProxySessionIdResolver } from '../maker-host/anthropic-compat-proxy-host.js';
+import {
+ setClaudeProxyOwnerBoundaryPendingChecker,
+ setClaudeProxyOwnerScopeKeyReader,
+ setClaudeProxySessionIdResolver,
+} from '../maker-host/anthropic-compat-proxy-host.js';
import {
clearClaudeSessionBackgroundActivity,
getClaudeSessionBackgroundActivity,
@@ -7013,9 +7018,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// per-session 供应商路由:把 cc loopback proxy 看到的 x-claude-code-session-id(= sdkSessionId)
// 反解成 xdt sessionId,供其统一路由器查该会话显式选定的供应商。sdkSessionId 唯一,直接匹配活跃会话。
+ // 热路径禁止把 ipcMaker 的 PRECONDITION_FAILED 抛进 proxy:owner boundary 期间抛错会被
+ // 引擎 fail-open 成默认 LiteLLM,provider-oauth 占位 key 原样上游 → 确定性 401。
+ setClaudeProxyOwnerBoundaryPendingChecker(isAppSessionBoundaryPending);
+ setClaudeProxyOwnerScopeKeyReader(activeOwnerScopeKey);
setClaudeProxySessionIdResolver((sdkSessionId) => {
- const s = maker.listActiveSessions().find((x) => x.sdkSessionId === sdkSessionId);
- return s ? s.id : null;
+ try {
+ if (isAppSessionBoundaryPending()) return null;
+ const s = maker.listActiveSessions().find((x) => x.sdkSessionId === sdkSessionId);
+ return s ? s.id : null;
+ } catch (err) {
+ log.warn('claude proxy session resolver failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
});
// 会话移动转录迁移:活跃会话桥(查内存 sdkSessionId + 关闭 handle)。
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index e3f6c3d4f4..47d01df018 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -1078,6 +1078,221 @@ describe('anthropic-compat-proxy routingTransform', () => {
expect(custom.paths).toHaveLength(0);
});
+ it('revalidateBeforeDispatch can divert a localHandler after routingTransform', async () => {
+ let innerRan = false;
+ proxy = await createAnthropicCompatProxy({
+ upstream: () => '',
+ transformRequest: [],
+ routingTransform: () => ({
+ localHandler: async ({ res }) => {
+ innerRan = true;
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ from: 'inner' }));
+ },
+ }),
+ revalidateBeforeDispatch: () => ({
+ localHandler: async ({ res }) => {
+ res.writeHead(503, {
+ 'content-type': 'application/json',
+ 'retry-after': '1',
+ });
+ res.end(JSON.stringify({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ }));
+ },
+ }),
+ });
+
+ const result = await post(proxy.url, { model: 'subscription-direct-model' });
+ expect(result.status).toBe(503);
+ expect(JSON.parse(result.text)).toEqual({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ expect(innerRan).toBe(false);
+ });
+
+ it('revalidates after async request transforms and does not forward', async () => {
+ const custom = await startFakeUpstream((_i, _b, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('{}');
+ });
+ upstreamClose = custom.close;
+
+ let pending = false;
+ proxy = await createAnthropicCompatProxy({
+ upstream: custom.url,
+ transformRequest: [async () => {
+ pending = true;
+ return null;
+ }],
+ routingTransform: () => ({ headerOverride: { authorization: 'Bearer previous-owner' } }),
+ revalidateBeforeDispatch: () => (pending
+ ? {
+ localHandler: async ({ res }) => {
+ res.writeHead(503, {
+ 'content-type': 'application/json',
+ 'retry-after': '1',
+ });
+ res.end(JSON.stringify({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ }));
+ },
+ }
+ : null),
+ });
+
+ const result = await post(proxy.url, { model: 'claude-haiku-4-5-20251001' });
+ expect(result.status).toBe(503);
+ expect(JSON.parse(result.text)).toEqual({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ expect(custom.bodies).toHaveLength(0);
+ });
+
+ it('revalidates when owner scope changes during async transforms even if pending stays false', async () => {
+ const custom = await startFakeUpstream((_i, _b, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('{}');
+ });
+ upstreamClose = custom.close;
+
+ let ownerScope = 'cloud:owner-a:1';
+ const ownerScopeByCtx = new WeakMap<object, string>();
+ proxy = await createAnthropicCompatProxy({
+ upstream: custom.url,
+ transformRequest: [async () => {
+ ownerScope = 'cloud:owner-b:2';
+ return null;
+ }],
+ routingTransform: (_body, ctx) => {
+ ownerScopeByCtx.set(ctx, ownerScope);
+ return { headerOverride: { authorization: 'Bearer previous-owner' } };
+ },
+ revalidateBeforeDispatch: (_decision, ctx) => {
+ const start = ctx ? ownerScopeByCtx.get(ctx) : undefined;
+ if (start !== undefined && start !== ownerScope) {
+ return {
+ localHandler: async ({ res }) => {
+ res.writeHead(503, {
+ 'content-type': 'application/json',
+ 'retry-after': '1',
+ });
+ res.end(JSON.stringify({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ }));
+ },
+ };
+ }
+ return null;
+ },
+ });
+
+ const result = await post(proxy.url, { model: 'claude-haiku-4-5-20251001' });
+ expect(result.status).toBe(503);
+ expect(JSON.parse(result.text)).toEqual({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ expect(custom.bodies).toHaveLength(0);
+ });
+
+ it('stamps owner scope before collecting the body so a switch during upload cannot re-baseline', async () => {
+ const custom = await startFakeUpstream((_i, _b, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('{}');
+ });
+ upstreamClose = custom.close;
+
+ let ownerScope = 'cloud:owner-a:1';
+ const ownerScopeByCtx = new WeakMap<object, string>();
+ proxy = await createAnthropicCompatProxy({
+ upstream: custom.url,
+ transformRequest: [],
+ routingTransform: () => {
+ // collectRequestBody 已经结束;若盖章拖到这里,会把 B 当成起始 scope。
+ ownerScope = 'cloud:owner-b:2';
+ return { headerOverride: { authorization: 'Bearer previous-owner' } };
+ },
+ revalidateBeforeDispatch: (_decision, ctx) => {
+ if (ctx && !ownerScopeByCtx.has(ctx)) ownerScopeByCtx.set(ctx, ownerScope);
+ const start = ctx ? ownerScopeByCtx.get(ctx) : undefined;
+ if (start !== undefined && start !== ownerScope) {
+ return {
+ localHandler: async ({ res }) => {
+ res.writeHead(503, {
+ 'content-type': 'application/json',
+ 'retry-after': '1',
+ });
+ res.end(JSON.stringify({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ }));
+ },
+ };
+ }
+ return null;
+ },
+ });
+
+ const result = await post(proxy.url, { model: 'claude-haiku-4-5-20251001' });
+ expect(result.status).toBe(503);
+ expect(JSON.parse(result.text)).toEqual({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ expect(custom.bodies).toHaveLength(0);
+ expect(custom.headers).toHaveLength(0);
+ });
+
+ it('revalidates owner scope before a transparent recovery retry', async () => {
+ let ownerScope = 'cloud:owner-a:1';
+ const ownerScopeByCtx = new WeakMap<object, string>();
+ const custom = await startFakeUpstream((idx, _body, res) => {
+ ownerScope = 'cloud:owner-b:2';
+ if (idx === 0) {
+ res.writeHead(400, { 'content-type': 'application/json' });
+ res.end(ENC_ERROR_BODY);
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('{}');
+ });
+ upstreamClose = custom.close;
+
+ proxy = await createAnthropicCompatProxy({
+ upstream: custom.url,
+ transformRequest: [],
+ routingTransform: () => ({ headerOverride: { authorization: 'Bearer previous-owner' } }),
+ recoveryRules: [createEncryptedContentRecoveryRule({ enabled: () => true })],
+ revalidateBeforeDispatch: (_decision, ctx) => {
+ if (ctx && !ownerScopeByCtx.has(ctx)) ownerScopeByCtx.set(ctx, ownerScope);
+ const start = ctx ? ownerScopeByCtx.get(ctx) : undefined;
+ if (start !== undefined && start !== ownerScope) {
+ return {
+ localHandler: async ({ res }) => {
+ res.writeHead(503, {
+ 'content-type': 'application/json',
+ 'retry-after': '1',
+ });
+ res.end(JSON.stringify({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ }));
+ },
+ };
+ }
+ return null;
+ },
+ });
+
+ const r = await post(proxy.url, {
+ model: 'gpt-5.5',
+ input: [{ type: 'reasoning', encrypted_content: 'gAAAsecret' }],
+ });
+ expect(r.status).toBe(503);
+ expect(JSON.parse(r.text)).toEqual({
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ expect(custom.bodies).toHaveLength(1);
+ expect(custom.headers[0]?.authorization).toBe('Bearer previous-owner');
+ });
+
it('runs a local handler without resolving an unavailable default upstream', async () => {
proxy = await createAnthropicCompatProxy({
upstream: () => '',
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index e9b9ee6593..ae4c9436cd 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -599,6 +599,18 @@ function collectRequestBody(req: IncomingMessage, maxBytes: number): Promise<Buf
});
}
+/** 丢弃未读完的请求体。early 503 必须先 drain 再结束响应,否则 Node 会 RST 客户端。 */
+function drainRequest(req: IncomingMessage): Promise<void> {
+ if (req.readableEnded || req.destroyed) return Promise.resolve();
+ return new Promise((resolve) => {
+ const done = (): void => resolve();
+ req.once('end', done);
+ req.once('close', done);
+ req.once('error', done);
+ req.resume();
+ });
+}
+
/**
* 请求 body 超限的统一收尾:先把**完整的 413 响应**写回、再让连接关闭,顺序不能反。
* 历史实现是先 req.destroy() 再写 413 —— socket 已死,413 永远到不了客户端,
@@ -901,6 +913,9 @@ function forward(
// 为 true 时启用 2xx 成功响应的流式有效性门(#2242):空 2xx / 非 SSE 2xx /
// 零事件 SSE 不再原样透传给客户端,转成结构化 502。false 保持字节级透传。
requestDeclaredStream = false,
+ // 透明重试前再跑同一条 dispatch gate。返回 false = 已改道(典型 503),
+ // 不得带着旧 headerOverride 再发一次。省略 = 与扩展前一样直接重发。
+ beforeRetry?: () => Promise<boolean>,
): void {
// 客户端已断开(典型:400 缓冲期间断开后走到透明重试)——'close' 已经发过,
// 下面挂的中断传播 listener 永远不会触发,直接不发起上游请求。
@@ -1147,29 +1162,55 @@ function forward(
appliedRule.onRetry?.(threadId, model);
}
}
- forward(
- target,
- method,
- path,
- headers,
- retryBody,
- clientRes,
- logger,
- recoveryRules,
- reqId,
- false,
- overrideTarget,
- headerOverride,
- headerDelete,
- responseObserver,
- transformResponse,
- clientModel,
- outboundProxy,
- pathOverride,
- responseToolUseIds,
- threadMintedIdCache,
- requestDeclaredStream,
- );
+ const retry = (): void => {
+ forward(
+ target,
+ method,
+ path,
+ headers,
+ retryBody,
+ clientRes,
+ logger,
+ recoveryRules,
+ reqId,
+ false,
+ overrideTarget,
+ headerOverride,
+ headerDelete,
+ responseObserver,
+ transformResponse,
+ clientModel,
+ outboundProxy,
+ pathOverride,
+ responseToolUseIds,
+ threadMintedIdCache,
+ requestDeclaredStream,
+ beforeRetry,
+ );
+ };
+ if (!beforeRetry) {
+ retry();
+ return;
+ }
+ void beforeRetry().then((proceed) => {
+ if (!proceed) return;
+ if (clientRes.destroyed) return;
+ retry();
+ }).catch((err) => {
+ logger.error?.('retry dispatch gate failed', {
+ reqId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ if (clientRes.destroyed || clientRes.headersSent) return;
+ clientRes.writeHead(503, {
+ 'content-type': 'application/json',
+ 'cache-control': 'no-store',
+ 'retry-after': '1',
+ });
+ clientRes.end(JSON.stringify({
+ error: { type: 'proxy_error', message: 'dispatch revalidation failed' },
+ }));
+ });
return;
}
// 无规则命中: 把这条 400 原样回给客户端 + 记 warn 日志 (与下方非 2xx 分支同语义)。
@@ -1723,6 +1764,42 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
};
};
+ /**
+ * 凭证出站前的同步门。请求开始(读 body 前)盖章,routing 后、异步 transform /
+ * outbound 后、透明重试前再看一眼 owner-boundary:返回 localHandler 则改道本地
+ * 响应,不再 forward。hook 抛错也 fail-closed,避免把决策时选中的 headerOverride /
+ * 占位 key 打出去。
+ */
+ const applyDispatchGate = (
+ decision: RoutingDecision | null,
+ reqId: number,
+ ctx: RequestTransformCtx,
+ ): RoutingDecision | null => {
+ const hook = opts.revalidateBeforeDispatch;
+ if (!hook) return decision;
+ try {
+ return hook(decision, ctx) ?? decision;
+ } catch (err) {
+ logger.warn?.('revalidateBeforeDispatch threw; refusing dispatch', {
+ reqId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ return {
+ localHandler: async ({ res }) => {
+ if (res.headersSent) return;
+ res.writeHead(503, {
+ 'content-type': 'application/json',
+ 'cache-control': 'no-store',
+ 'retry-after': '1',
+ });
+ res.end(JSON.stringify({
+ error: { type: 'proxy_error', message: 'dispatch revalidation failed' },
+ }));
+ },
+ };
+ }
+ };
+
// 出站代理:CONNECT 隧道 agent 按代理地址缓存(keep-alive 连接池),随 dispose 销毁。
const outboundAgentPool = new OutboundProxyAgentPool();
@@ -1830,12 +1907,40 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
? oversizedIngressBytes
: maxBodyBytes;
+ // 请求一开始就盖章:collectRequestBody 是第一段 await,拖到 routingTransform
+ // 会把 body 上传期间完成的 owner 切换当成「起始」scope。
+ let decision: RoutingDecision | null = applyDispatchGate(null, reqId, requestCtx);
+ const beforeRetry = async (): Promise<boolean> => {
+ const gated = applyDispatchGate(decision, reqId, requestCtx);
+ if (gated?.localHandler) {
+ await runLocalHandler(
+ gated.localHandler,
+ { rawBody: Buffer.alloc(0), parsedBody: undefined, ctx: requestCtx, res },
+ logger,
+ reqId,
+ );
+ return false;
+ }
+ return true;
+ };
+ if (decision?.localHandler) {
+ if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
+ await drainRequest(req);
+ }
+ await runLocalHandler(
+ decision.localHandler,
+ { rawBody: Buffer.alloc(0), parsedBody: undefined, ctx: requestCtx, res },
+ logger,
+ reqId,
+ );
+ return;
+ }
+
// 非 POST / 没 body(GET / HEAD / DELETE 等)→ 不收集 stream,但仍跑一次路由决策:
// 这类请求没有 body,routingTransform 以 `undefined` body 调用,可据 method/url/headers 路由
// 控制面请求(典型: codex models-manager 的 `GET /models` 轮询)。transform 对 undefined body
// 应自行短路返回 null(= 默认上游 + 透传 headers,向后兼容)。
if (method !== 'POST' && method !== 'PUT' && method !== 'PATCH') {
- let decision: RoutingDecision | null = null;
if (opts.routingTransform) {
try {
const maybeDecision = opts.routingTransform(undefined, requestCtx);
@@ -1846,6 +1951,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
logger.warn?.('routingTransform threw, using default upstream', { reqId, err: String(err) });
}
}
+ decision = applyDispatchGate(decision, reqId, requestCtx);
// 本地 handler 命中:不转发上游,由 handler 直接写回响应(见 LocalRequestHandler 契约)。
if (decision?.localHandler) {
logger.debug?.('▶ inbound request from client', { reqId, method, upstreamBase: 'local-handler', url, bytes: 0 });
@@ -1868,6 +1974,17 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
bytes: 0,
});
}
+ const outbound = await resolveOutboundForTarget(route.target, reqId);
+ decision = applyDispatchGate(decision, reqId, requestCtx);
+ if (decision?.localHandler) {
+ await runLocalHandler(
+ decision.localHandler,
+ { rawBody: Buffer.alloc(0), parsedBody: undefined, ctx: requestCtx, res },
+ logger,
+ reqId,
+ );
+ return;
+ }
forward(
route.target,
method,
@@ -1885,8 +2002,12 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
opts.responseObserver,
opts.transformResponse,
'',
- await resolveOutboundForTarget(route.target, reqId),
+ outbound,
route.pathOverride,
+ undefined,
+ undefined,
+ false,
+ beforeRetry,
);
return;
}
@@ -1931,7 +2052,6 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
// 提前到 ▶ inbound 日志**之前**计算: 路由只依赖 rawBody / headers / contentType,与下方
// runTransforms 的输出无关,提前是安全的; 这样 inbound 日志能直接打出本请求**最终**发往的
// upstream(订阅直连 api.anthropic.com / 走网关 endpoint),而非静态默认上游。
- let decision: RoutingDecision | null = null;
let rawParsed: unknown = undefined;
if (opts.routingTransform && contentType.toLowerCase().startsWith('application/json')) {
try {
@@ -1951,6 +2071,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
logger.warn?.('routingTransform threw, using default upstream', { reqId, err: String(err) });
}
}
+ decision = applyDispatchGate(decision, reqId, requestCtx);
// 本地 handler 命中:不转发上游、不跑 transform 链,由 handler 直接消费(协议翻译场景)。
// parsedBody 复用路由阶段的解析结果,不二次 parse。
@@ -2203,6 +2324,18 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
});
}
+ const outbound = await resolveOutboundForTarget(route.target, reqId);
+ decision = applyDispatchGate(decision, reqId, requestCtx);
+ if (decision?.localHandler) {
+ await runLocalHandler(
+ decision.localHandler,
+ { rawBody, parsedBody: rawParsed, ctx: requestCtx, res },
+ logger,
+ reqId,
+ );
+ return;
+ }
+
forward(
route.target,
method,
@@ -2220,11 +2353,12 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
opts.responseObserver,
opts.transformResponse,
extractBodyModel(rawBody),
- await resolveOutboundForTarget(route.target, reqId),
+ outbound,
route.pathOverride,
responseToolUseIds,
threadMintedIdCache,
requestDeclaredStream,
+ beforeRetry,
);
});
diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.ts
index 91ebfc306c..53dbc9dc25 100644
--- a/packages/anthropic-compat-proxy/src/types.ts
+++ b/packages/anthropic-compat-proxy/src/types.ts
@@ -260,6 +260,25 @@ export interface ProxyOptions {
* 不传 = 永远走 `upstream` + 透传 headers(字节级行为与不传时完全一致,向后兼容)。
*/
routingTransform?: RoutingTransform;
+ /**
+ * 可选: 真正 dispatch 前的同步再校验。调用点:
+ * 1. 请求开始、`collectRequestBody` 之前(此时 decision 为 null)—— host 在这里
+ * 按 `ctx` 盖章 owner scope;pending 为真则直接 503,不再等 body / 跑路由;
+ * 2. `routingTransform` 之后一次;
+ * 3. 任何异步 transform / outbound 解析之后、`runLocalHandler` / `forward` 之前;
+ * 4. 可恢复 400/422 透明重试递归 `forward` 之前。
+ * 后续调用传入与 `routingTransform` 相同的 `ctx`,host 对照请求开始时捕获的
+ * owner scope / generation —— pending 布尔值挡不住「切换在 await 里完整完成」,
+ * 盖章若拖到 routingTransform,也挡不住 body 上传期间的完整切换。
+ *
+ * 返回非 null = 替换当前决策(典型:改成 localHandler 503,拒绝带着过期归属的凭证出站);
+ * 返回 null = 保持已解析的路由,包括已经算好的 forward target。不要用它改上游。
+ * 不传 = 不插入检查,与扩展前字节级一致。
+ */
+ revalidateBeforeDispatch?: (
+ decision: RoutingDecision | null,
+ ctx?: RequestTransformCtx,
+ ) => RoutingDecision | null;
/**
* 可选响应观察器。默认关闭;开启后只能 tee 响应 chunk 做轻量 metadata 解析,
* 不能改写响应或阻塞流式 pipe。
diff --git a/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts b/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
index fb0614b139..d66fbef41a 100644
--- a/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
+++ b/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
@@ -496,6 +496,44 @@ describe('createResponsesHandler', () => {
expect(r.text).toContain('authentication_error');
});
+ it('buildHeaders 抛 owner-boundary pending → 503,不是 authentication_error,也不 fetch', async () => {
+ const fetchMock = vi.fn(async () => { throw new Error('should not fetch'); });
+ vi.stubGlobal('fetch', fetchMock);
+ const pending = Object.assign(
+ new Error('App session is switching; retry after the owner boundary settles.'),
+ { name: 'OwnerBoundaryPendingError', code: 'owner_boundary_pending' },
+ );
+ const handler = createResponsesHandler({
+ providers: [providerConfig({ buildHeaders: async () => { throw pending; } })],
+ });
+ const r = await invoke(handler, { model: 'chatgpt/gpt-5.5', messages: [] });
+ expect(r.status).toBe(503);
+ expect(r.headers['retry-after']).toBe('1');
+ expect(JSON.parse(r.text)).toMatchObject({
+ type: 'error',
+ error: { type: 'owner_boundary_pending', code: 'owner_boundary_pending' },
+ });
+ expect(r.text).not.toContain('authentication_error');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('xAI buildHeaders 抛同一条 pending 错误同样 503', async () => {
+ const fetchMock = vi.fn(async () => { throw new Error('should not fetch'); });
+ vi.stubGlobal('fetch', fetchMock);
+ const pending = new Error('App session is switching; retry after the owner boundary settles.');
+ pending.name = 'OwnerBoundaryPendingError';
+ const handler = createResponsesHandler({
+ providers: [providerConfig({
+ prefix: 'xai/',
+ buildHeaders: async () => { throw pending; },
+ })],
+ });
+ const r = await invoke(handler, { model: 'xai/grok-4.6', messages: [] });
+ expect(r.status).toBe(503);
+ expect(JSON.parse(r.text).error.code).toBe('owner_boundary_pending');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('上游非 2xx → 先等待 provider 收口错误状态,再透传原始响应', async () => {
const callbackFinished = vi.fn();
const onUpstreamError = vi.fn(async () => {
diff --git a/packages/anthropic-responses-bridge/src/handler.ts b/packages/anthropic-responses-bridge/src/handler.ts
index a57da32f12..9d793b2899 100644
--- a/packages/anthropic-responses-bridge/src/handler.ts
+++ b/packages/anthropic-responses-bridge/src/handler.ts
@@ -97,6 +97,36 @@ function writeJson(res: ServerResponse, status: number, body: unknown): void {
res.end(buf);
}
+/** 与 desktop `OwnerBoundaryPendingError` 对齐:本包不能 import desktop,按 name/code/message 认。 */
+const OWNER_BOUNDARY_PENDING_MESSAGE =
+ 'App session is switching; retry after the owner boundary settles.';
+
+function isOwnerBoundaryPendingError(err: unknown): boolean {
+ if (!(err instanceof Error)) return false;
+ if (err.name === 'OwnerBoundaryPendingError') return true;
+ if ((err as { code?: unknown }).code === 'owner_boundary_pending') return true;
+ return err.message === OWNER_BOUNDARY_PENDING_MESSAGE;
+}
+
+function writeOwnerBoundaryPending(res: ServerResponse, err: unknown): void {
+ const message = err instanceof Error ? err.message : OWNER_BOUNDARY_PENDING_MESSAGE;
+ const buf = Buffer.from(JSON.stringify({
+ type: 'error',
+ error: {
+ type: 'owner_boundary_pending',
+ code: 'owner_boundary_pending',
+ message,
+ },
+ }), 'utf8');
+ res.writeHead(503, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'content-length': String(buf.length),
+ 'cache-control': 'no-store',
+ 'retry-after': '1',
+ });
+ res.end(buf);
+}
+
function writeSseEvent(res: ServerResponse, ev: AnthropicSseEvent): void {
res.write(`event: ${ev.event}\ndata: ${JSON.stringify(ev.data)}\n\n`);
}
@@ -294,6 +324,10 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
try {
providerHeaders = await provider.buildHeaders({ sessionId });
} catch (err) {
+ if (isOwnerBoundaryPendingError(err)) {
+ writeOwnerBoundaryPending(res, err);
+ return;
+ }
log.error?.('buildHeaders failed', { reqId, prefix: provider.prefix, err: err instanceof Error ? err.message : String(err) });
writeJson(res, 502, {
type: 'error',