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(claude-bridge): 原生适配器路径按请求传稳定会话身份,修复 OpenCode Go 400 (#5328)

FicoWangb0d1172f094f
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.ts
index 042f7ca8eb..abd9fa4d55 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.ts
@@ -2,7 +2,8 @@ import { createServer } from 'node:http';
import { once } from 'node:events';
import type { AddressInfo } from 'node:net';
import { describe, expect, it } from 'vitest';
-import { PROVIDER_MODEL_CATALOG } from '@cindy/model-providers';
+import { PROVIDER_MODEL_CATALOG, buildUserProvider } from '@cindy/model-providers';
+import { invocationModelRecord, NATIVE_BRIDGE_SESSION_HEADER } from '../pi-provider-transport.js';
import { claudeProviderReasoningNamespace, createClaudeProviderBridge } from '../claude-provider-bridge.js';
async function runBridge(
@@ -13,6 +14,7 @@ async function runBridge(
extras: Partial<Parameters<typeof createClaudeProviderBridge>[0]> = {},
effort = 'high',
fast = false,
+ inboundHeaders: Record<string, string> = {},
) {
const handler = createClaudeProviderBridge({
url: `https://supplier.example/v1/${protocol === 'openai-chat' ? 'chat/completions' : 'responses'}`,
@@ -29,7 +31,7 @@ async function runBridge(
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
void handler.handle({ parsedBody: JSON.parse(Buffer.concat(chunks).toString()),
- ctx: { reqId: 1, method: 'POST', url: req.url!, headers: {} }, res,
+ ctx: { reqId: 1, method: 'POST', url: req.url!, headers: inboundHeaders }, res,
prefs: { reasoningEffort: effort, fast },
}).catch(() => { res.statusCode = 500; res.end(); });
});
@@ -176,3 +178,54 @@ it.each(['openai-chat', 'openai-responses'] as const)('sends Fast only when enab
expect(body?.service_tier).toBe(supported && fast ? 'priority' : undefined);
}
});
+
+describe('OpenCode Go session identity through the native Claude bridge (#5325)', () => {
+ const upstream = 'https://opencode.ai/zen/go/v1';
+ function goRow() {
+ const provider = buildUserProvider({ id: 'opencode-go', name: 'OpenCode Go', runtimes: {
+ 'claude-code': { baseUrl: upstream, wireProtocol: 'openai-chat', models: [{ id: 'deepseek-v4.1-flash', name: 'DeepSeek V4.1 Flash', reasoning: false, reasoningEfforts: [] }] },
+ } });
+ return invocationModelRecord(provider.models['claude-code']![0], upstream, 'openai-completions')!;
+ }
+ /** The SDK's final HTTP request is what the upstream validates, not the handler arguments. */
+ function goUpstream(seen: Headers[]) {
+ return async (_url: string, init?: RequestInit) => {
+ const headers = new Headers(init?.headers as HeadersInit);
+ seen.push(headers);
+ if (!headers.get('x-opencode-session')?.trim()) return new Response(JSON.stringify({ error: 'MissingSessionID' }), { status: 400, headers: { 'content-type': 'application/json' } });
+ return new Response(chatStream, { headers: { 'content-type': 'text/event-stream' } });
+ };
+ }
+
+ it('carries the inbound Claude Code session as a stable x-opencode-session on the SDK request', async () => {
+ const seen: Headers[] = [];
+ const row = goRow();
+ const runs = [] as Array<{ status: number; body: string }>;
+ for (const inbound of ['cc-session-a', 'cc-session-a', 'cc-session-b']) {
+ runs.push(await runBridge('openai-chat', true, chatStream, () => {}, {
+ model: row, nativeUpstream: upstream, providerId: 'opencode-go', efforts: [],
+ fetchImpl: goUpstream(seen) as typeof fetch,
+ }, 'high', false, { 'x-claude-code-session-id': inbound }));
+ }
+ expect(runs.map(run => run.status)).toEqual([200, 200, 200]);
+ expect(runs[0]!.body).toContain('Hello');
+ const values = seen.map(headers => headers.get('x-opencode-session'));
+ expect(values[0]).toMatch(/^[0-9a-f]{32}$/);
+ expect(values[1]).toBe(values[0]);
+ expect(values[2]).not.toBe(values[0]);
+ for (const headers of seen) {
+ expect(headers.get(NATIVE_BRIDGE_SESSION_HEADER)).toBeNull();
+ expect(headers.get('x-claude-code-session-id')).toBeNull();
+ }
+ });
+
+ it('does not leak the internal session carrier to a Responses pass-through upstream', async () => {
+ let sent: Headers | undefined;
+ const result = await runBridge('openai-responses', true, 'data: {"type":"response.completed","response":{"id":"r","status":"completed","output":[],"usage":{"input_tokens":0,"output_tokens":0}}}\n\n', (_url, init) => {
+ sent = new Headers(init?.headers as HeadersInit);
+ }, {}, 'high', false, { 'x-claude-code-session-id': 'cc-session-a' });
+ expect(result.status).toBe(200);
+ expect(sent?.get(NATIVE_BRIDGE_SESSION_HEADER)).toBeNull();
+ expect(sent?.get('x-opencode-session')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
index c26ac17f86..6c44da83a3 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import * as openaiCompletions from '@earendil-works/pi-ai/api/openai-completions';
import { PROVIDER_MODEL_CATALOG, BUNDLED_CATALOG, buildUserProvider, parseModelsListResponse, mergeDiscoveredRuntimeModels } from '@cindy/model-providers';
-import { createPiProviderFetch, hostCredentialEndpointAllowed, invocationModelRecord, nativeBridgeApiKey, NATIVE_ADAPTER_ERROR_BODY_LIMIT, readBoundedResponseText } from '../pi-provider-transport.js';
+import { createPiProviderFetch, hostCredentialEndpointAllowed, invocationModelRecord, nativeBridgeApiKey, NATIVE_ADAPTER_ERROR_BODY_LIMIT, NATIVE_BRIDGE_SESSION_HEADER, readBoundedResponseText } from '../pi-provider-transport.js';
vi.mock('@earendil-works/pi-ai/api/openai-completions', async (importOriginal) => ({
...await importOriginal<typeof import('@earendil-works/pi-ai/api/openai-completions')>(),
@@ -404,3 +404,68 @@ it.each([undefined, 200, 302])('keeps iterator exceptions private after HTTP %s
stream.mockRestore();
}
});
+
+describe('OpenCode Go session header on the native transport (#5325)', () => {
+ const goUpstream = 'https://opencode.ai/zen/go/v1';
+ function rowFor(providerId: string, baseUrl: string, catalogPresetId?: string) {
+ const provider = buildUserProvider({ id: providerId, name: providerId, runtimes: {
+ codex: { baseUrl, wireProtocol: 'openai-chat', models: [{ id: 'deepseek-v4.1-flash', name: 'DeepSeek', reasoning: false, reasoningEfforts: [], ...(catalogPresetId ? { catalogPresetId } : {}) }] },
+ } });
+ return invocationModelRecord(provider.models.codex![0], baseUrl, 'openai-completions')!;
+ }
+ /** Rejects exactly like the real upstream when the conversation header is missing. */
+ function upstreamRequiringSession(seen: Headers[]) {
+ return (async (_url: unknown, init?: RequestInit) => {
+ const headers = new Headers(init?.headers as HeadersInit);
+ seen.push(headers);
+ if (!headers.get('x-opencode-session')?.trim()) return new Response(JSON.stringify({ error: 'MissingSessionID' }), { status: 400, headers: { 'content-type': 'application/json' } });
+ return new Response(reply, { headers: { 'content-type': 'text/event-stream' } });
+ }) as typeof fetch;
+ }
+ const body = JSON.stringify({ model: 'deepseek-v4.1-flash', input: 'hello', stream: true });
+
+ it('derives a stable per-conversation header from the bridge session carrier and reaches the SDK request', async () => {
+ const seen: Headers[] = [];
+ const send = createPiProviderFetch({ row: rowFor('opencode-go', goUpstream), providerId: 'opencode-go', apiKey: 'fixture-key', fetchImpl: upstreamRequiringSession(seen) });
+ const texts: string[] = [];
+ for (const session of ['cc-a', 'cc-a', 'cc-b']) {
+ texts.push(await (await send('https://unused.invalid', { body, headers: { [NATIVE_BRIDGE_SESSION_HEADER]: session } })).text());
+ }
+ for (const text of texts) { expect(text).toContain('response.completed'); expect(text).not.toContain('response.failed'); }
+ const values = seen.map(headers => headers.get('x-opencode-session'));
+ expect(values[0]).toMatch(/^[0-9a-f]{32}$/);
+ expect(values[1]).toBe(values[0]);
+ expect(values[2]).not.toBe(values[0]);
+ expect(seen.every(headers => headers.get(NATIVE_BRIDGE_SESSION_HEADER) === null)).toBe(true);
+ expect(seen[0]!.get('authorization')).toBe('Bearer fixture-key');
+ });
+
+ it('recognizes a preset-derived Go connection whose id and endpoint changed, and ignores unrelated routes', async () => {
+ const seen: Headers[] = [];
+ const relay = 'https://relay.example/v1';
+ const viaPreset = createPiProviderFetch({ row: rowFor('my-go-copy', relay, 'opencode-go'), providerId: 'my-go-copy', catalogPresetId: 'opencode-go', apiKey: 'k', fetchImpl: upstreamRequiringSession(seen) });
+ expect(await (await viaPreset('https://unused.invalid', { body, headers: { [NATIVE_BRIDGE_SESSION_HEADER]: 'cc-a' } })).text()).toContain('response.completed');
+ expect(seen[0]!.get('x-opencode-session')).toMatch(/^[0-9a-f]{32}$/);
+ const other: Headers[] = [];
+ const unrelated = createPiProviderFetch({ row: rowFor('sub2api', relay), providerId: 'sub2api', apiKey: 'k', fetchImpl: (async (_url: unknown, init?: RequestInit) => {
+ other.push(new Headers(init?.headers as HeadersInit));
+ return new Response(reply, { headers: { 'content-type': 'text/event-stream' } });
+ }) as typeof fetch });
+ await (await unrelated('https://unused.invalid', { body, headers: { [NATIVE_BRIDGE_SESSION_HEADER]: 'cc-a' } })).text();
+ expect(other[0]!.get('x-opencode-session')).toBeNull();
+ expect(other[0]!.get(NATIVE_BRIDGE_SESSION_HEADER)).toBeNull();
+ });
+
+ it('keeps an explicitly configured user session header and still accepts a carrier-less request as a one-shot', async () => {
+ const seen: Headers[] = [];
+ const configured = createPiProviderFetch({ row: rowFor('opencode-go', goUpstream), providerId: 'opencode-go', apiKey: 'k', headers: { 'X-OpenCode-Session': 'user-fixed' }, fetchImpl: upstreamRequiringSession(seen) });
+ await (await configured('https://unused.invalid', { body, headers: { [NATIVE_BRIDGE_SESSION_HEADER]: 'cc-a' } })).text();
+ expect(seen[0]!.get('x-opencode-session')).toBe('user-fixed');
+ const oneShot = createPiProviderFetch({ row: rowFor('opencode-go', goUpstream), providerId: 'opencode-go', apiKey: 'k', fetchImpl: upstreamRequiringSession(seen) });
+ const first = await (await oneShot('https://unused.invalid', { body })).text();
+ const second = await (await oneShot('https://unused.invalid', { body })).text();
+ expect(first).toContain('response.completed'); expect(second).toContain('response.completed');
+ expect(seen[1]!.get('x-opencode-session')).toMatch(/^[0-9a-f-]{36}$/);
+ expect(seen[2]!.get('x-opencode-session')).not.toBe(seen[1]!.get('x-opencode-session'));
+ });
+});
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 7caa1ca403..f09481786c 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
@@ -159,6 +159,7 @@ function attachClaudeProviderBridge(route: RoutingDecision, providerId: string,
protocol, headers: route.headerOverride ?? {}, efforts: model.efforts,
supportsFastMode: model.supportsFastMode === true,
providerId: provider.id,
+ catalogPresetId: model.catalogPresetId,
...(row && (protocol === 'openai-chat' || model.api) ? { model: row, nativeUpstream: base } : {}),
capabilities: {
...(model.supportsImageInput ? { imageInput: 'image_url' as const } : {}),
diff --git a/apps/desktop/src/main/maker-host/claude-provider-bridge.ts b/apps/desktop/src/main/maker-host/claude-provider-bridge.ts
index 9f7dcf27dc..42f4688756 100644
--- a/apps/desktop/src/main/maker-host/claude-provider-bridge.ts
+++ b/apps/desktop/src/main/maker-host/claude-provider-bridge.ts
@@ -2,7 +2,7 @@ import { normalizeProviderRequest } from '@cindy/model-compat';
import { createHash } from 'node:crypto';
import type { Effort, ProviderModelRecord } from '@cindy/model-providers';
import { reconcileOutboundReasoningEffort } from './outbound-reasoning-effort.js';
-import { createPiProviderFetch, nativeBridgeApiKey } from './pi-provider-transport.js';
+import { createPiProviderFetch, nativeBridgeApiKey, NATIVE_BRIDGE_SESSION_HEADER } from './pi-provider-transport.js';
import { createResponsesHandler, type ResponsesBridgeHandler } from '@cindy/anthropic-responses-bridge';
import { ChatSseTranslator, classifySystemOrderError, coalesceLeadingSystemMessages, shouldRetrySystemNormalization, translateResponsesRequestWithContext, type ChatBridgeCapabilities, type ResponsesRequest } from '@cindy/responses-chat-bridge';
@@ -48,6 +48,8 @@ export function createClaudeProviderBridge(options: {
capabilities?: ChatBridgeCapabilities;
model?: ProviderModelRecord;
providerId?: string;
+ /** Preset the connection derives from; lets the native route keep its provider-specific headers after edits. */
+ catalogPresetId?: string;
nativeUpstream?: string;
fetchImpl: typeof fetch;
}): ResponsesBridgeHandler {
@@ -55,6 +57,7 @@ export function createClaudeProviderBridge(options: {
...options.model, supportsFastMode: options.supportsFastMode ?? options.model.supportsFastMode,
},
providerId: options.providerId ?? 'custom',
+ catalogPresetId: options.catalogPresetId,
upstream: options.nativeUpstream,
apiKey: nativeBridgeApiKey(options.headers),
headers: Object.fromEntries(Object.entries(options.headers).filter(([name]) =>
@@ -155,8 +158,14 @@ export function createClaudeProviderBridge(options: {
return createResponsesHandler({
providers: [{
prefix: '', reasoningNamespace: claudeProviderReasoningNamespace(options.url, options.providerId), upstreamBase: options.url, wireProtocol: 'openai-responses',
- buildHeaders: async () => Object.fromEntries(Object.entries(options.headers).filter(([name]) =>
- !['x-api-key', 'anthropic-version', 'anthropic-beta'].includes(name.toLowerCase()))),
+ // The native branch rebuilds the SDK request from its own headers and never forwards
+ // `init.headers`, so the per-request session carrier only travels into
+ // createPiProviderFetch (#5325). Pass-through protocols must not receive it.
+ buildHeaders: async ({ sessionId }) => ({
+ ...Object.fromEntries(Object.entries(options.headers).filter(([name]) =>
+ !['x-api-key', 'anthropic-version', 'anthropic-beta'].includes(name.toLowerCase()))),
+ ...(nativeFetch && sessionId?.trim() ? { [NATIVE_BRIDGE_SESSION_HEADER]: sessionId.trim() } : {}),
+ }),
preserveReasoningState: !!options.model,
maxOutputTokensSupported: true,
supportsReasoning: () => options.efforts.length > 0,
diff --git a/apps/desktop/src/main/maker-host/opencode-go-session.ts b/apps/desktop/src/main/maker-host/opencode-go-session.ts
index a06927c80f..6b238a98c1 100644
--- a/apps/desktop/src/main/maker-host/opencode-go-session.ts
+++ b/apps/desktop/src/main/maker-host/opencode-go-session.ts
@@ -4,11 +4,12 @@
* OpenCode Go 自 2026-09-06 起强制要求每个请求携带稳定会话标识,缺失直接 400
* `MissingSessionID`(上游文档 https://opencode.ai/docs/go/#where-can-i-use-it)。
*
- * 会话路径不需要本模块:各客户端/桥自带的上游可识别头——Claude Code 的
- * `x-claude-code-session-id`、Codex 的 `session-id`、Pi 当前构建自己注入的
+ * 原生透传的会话路径不需要本模块:各客户端/桥自带的上游可识别头——Claude Code
+ * Messages 透传的 `x-claude-code-session-id`、Codex 的 `session-id`、Pi 当前构建自己注入的
* `x-opencode-session`,以及 Codex chat bridge 的 thread-id → x-opencode-session
- * 映射(#4073 / #4075)。本模块只服务**从零构造请求头、没有上述任何原生会话头的
- * 直连路径**:辅助模型 one-shot、供应商「测试连接」探测、视觉桥。
+ * 映射(#4073 / #4075)。本模块服务**由 host 从零构造请求头的出口**:辅助模型 one-shot、
+ * 供应商「测试连接」探测、视觉桥,以及 Claude 本地供应商桥 → Pi SDK 原生适配器
+ * (`createPiProviderFetch`,它重建出站请求、不继承入站头;sessionId 由桥按请求传入,#5325)。
*
* 路由识别有三路信号:运行时供应商 id、目录预设身份(`catalogPresetId`,从预设创建后
* 即使把地址改成自建转发、或复制连接得到新 id 也仍保留)、上游地址。三者任一命中即视为
diff --git a/apps/desktop/src/main/maker-host/pi-provider-transport.ts b/apps/desktop/src/main/maker-host/pi-provider-transport.ts
index ac4db06d05..543b72cc91 100644
--- a/apps/desktop/src/main/maker-host/pi-provider-transport.ts
+++ b/apps/desktop/src/main/maker-host/pi-provider-transport.ts
@@ -1,5 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
import { reconcileOutboundReasoningEffort } from './outbound-reasoning-effort.js';
+import { withOpenCodeGoSessionHeader } from './opencode-go-session.js';
import { once } from 'node:events';
import type { ServerResponse } from 'node:http';
import { ChatSseTranslator, translateResponsesRequestWithContext, type ResponsesRequest } from '@cindy/responses-chat-bridge';
@@ -105,6 +106,8 @@ function nativeHistory(request: ResponsesRequest, identity: string): Map<string,
export interface PiProviderTransportOptions {
row: ProviderModelRecord;
providerId: string;
+ /** Catalog preset the connection was created from; survives renames and endpoint edits. */
+ catalogPresetId?: string;
/** Account-specific destination; the catalog row still identifies its adapter. */
upstream?: string;
apiKey: string;
@@ -113,6 +116,26 @@ export interface PiProviderTransportOptions {
fetchImpl: typeof fetch;
}
+/**
+ * Internal request header that carries the caller's stable conversation identity into
+ * `createPiProviderFetch` (the Claude bridge sets it from `x-claude-code-session-id`).
+ * The SDK rebuilds the outbound request from `options.headers`, so the inbound `init.headers`
+ * never reach the upstream — this carrier is read here, handed to the adapter as `sessionId`
+ * and turned into the provider-specific conversation header (OpenCode Go: `x-opencode-session`,
+ * #5325). It is a per-request value, never shared mutable state.
+ */
+export const NATIVE_BRIDGE_SESSION_HEADER = 'x-cindy-native-bridge-session';
+
+function nativeBridgeSessionId(init: RequestInit | undefined): string | undefined {
+ const headers = init?.headers;
+ if (!headers) return undefined;
+ const value = headers instanceof Headers ? headers.get(NATIVE_BRIDGE_SESSION_HEADER)
+ : Array.isArray(headers) ? headers.find(([name]) => name.toLowerCase() === NATIVE_BRIDGE_SESSION_HEADER)?.[1]
+ : Object.entries(headers).find(([name]) => name.toLowerCase() === NATIVE_BRIDGE_SESSION_HEADER)?.[1];
+ const trimmed = typeof value === 'string' ? value.trim() : '';
+ return trimmed || undefined;
+}
+
/** Provider-specific authentication must not be bypassed by a matching harness wire. */
export function requiresNativeProviderAuth(row: ProviderModelRecord | undefined): boolean {
const identity = row && providerModelAdapterId(row);
@@ -264,9 +287,17 @@ export function createPiProviderFetch(options: PiProviderTransportOptions): type
return `Native provider request failed [phase=${phase}${status}; category=${category}; request=${responseId}]`;
};
const cloudflareGateway = model.provider === 'cloudflare-ai-gateway';
+ // Conversation identity is per request. OpenCode Go rejects requests without a stable
+ // `x-opencode-session`; without an inbound identity the route falls back to the helper's
+ // one-shot (per-request) value rather than inventing a shared or pseudo-stable id.
+ const sessionId = nativeBridgeSessionId(init);
+ const routeHeaders = withOpenCodeGoSessionHeader(options.headers, {
+ providerId: options.providerId, catalogPresetId: options.catalogPresetId, upstream: model.baseUrl, sessionId,
+ });
const events = adapter.streamSimple(model, context, {
apiKey: cloudflareGateway ? undefined : options.apiKey, env: options.env,
- headers: cloudflareGateway ? cloudflareGatewayHeaders(options.apiKey, options.headers) : options.headers,
+ headers: cloudflareGateway ? cloudflareGatewayHeaders(options.apiKey, routeHeaders) : routeHeaders,
+ ...(sessionId ? { sessionId } : {}),
// Pi's Google SDK rejects injected fetch. Its native transport must be used; all other
// adapters that support injection use Cindy's existing outbound route.
...(!['google-generative-ai', 'google-vertex', 'bedrock-converse-stream'].includes(model.api)