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): authorize compressed remote GPT requests after decoding

zqchris63990fb478c5
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts
index 50213faada..de914ad136 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyGuestRoute.test.ts
@@ -331,6 +331,28 @@ describe('Claude proxy routing for shared-provider guests', () => {
}
});
+ // Remote Pi's native ChatGPT adapter sends zstd. The proxy cannot read body.model
+ // until the native handler decodes it; an empty parsed body is not an empty model.
+ it.each(['guest', 'owner'])('routes $0 compressed Pi subscription requests to the decoding handler', async trust => {
+ const model = 'chatgpt/gpt-6.1-sol';
+ const binding = trust === 'guest'
+ ? registerGuestProviderRoute('pi-compressed', 'openai', candidate => candidate === model)
+ : bindHostedSessionProvider('pi-compressed', 'openai', (provider, candidate) => provider === 'openai' && candidate === model);
+ const dispose = registerPiProxySession('pi-compressed', 'compressed-token', () => 'openai');
+ try {
+ const decision = await transform(undefined, {
+ ...ctxWith({
+ 'x-cindy-pi-session-id': 'pi-compressed',
+ 'x-cindy-pi-session-token': 'compressed-token',
+ 'x-cindy-pi-provider-id': 'openai',
+ 'content-encoding': 'zstd',
+ }),
+ url: '/codex/responses',
+ });
+ expect(await statusOf(decision)).toBe(204);
+ } finally { dispose(); binding.release(); }
+ });
+
it('allows an authorized owner child provider independently of the parent provider', async () => {
let childAllowed = true;
bindHostedSessionProvider('owner-parent', 'shared-a', (providerId, model) => childAllowed && providerId === 'other-b' && model === 'other-model');
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 7b9bd27fbb..08eaa79cc9 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -66,6 +66,7 @@ import { buildUserProvider } from '@cindy/model-providers';
import { setCustomProviders, setXaiDiscoveredModels } from '../active-catalog.js';
import { registerUsagePricing, clearUsagePricing } from '../model-usage-pricing.js';
import { registerGuestProviderRoute } from '../guest-provider-route-store.js';
+import { bindHostedSessionProvider } from '../session-provider-store.js';
import { setSessionFastMode } from '../session-effort-store.js';
function responseRecorder() {
@@ -116,6 +117,61 @@ function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativ
}
describe('PI native subscription forwarding', () => {
+ // provider-sharing §12: decoding cannot bypass exact model grants. The earlier
+ // forwarding tests had no hosted binding, while routing tests only sent plain JSON.
+ it.each(['guest', 'owner'].flatMap(trust => [false, true].map(compressed => ({ trust, compressed }))))(
+ 'checks the decoded model for $trust subscriptions (zstd: $compressed)', async ({ trust, compressed }) => {
+ const providerId = 'openai-codec-fixture';
+ setCustomProviders([buildUserProvider({
+ id: providerId, name: 'Codec fixture', auth: { method: 'oauth', native: 'codex' },
+ runtimes: { codex: { baseUrl: 'https://chatgpt.example', wireProtocol: 'openai-responses',
+ models: ['gpt-6.1-sol', 'gpt-6.1-sol[1m]'].map(id => ({ id, name: id })) },
+ pi: { baseUrl: 'https://chatgpt.example', wireProtocol: 'openai-responses',
+ models: ['chatgpt/gpt-6.1-sol', 'chatgpt/gpt-6.1-sol[1m]'].map(id => ({ id, name: id })) } },
+ })]);
+ let allowedModel = 'chatgpt/gpt-6.1-sol';
+ const binding = trust === 'guest'
+ ? registerGuestProviderRoute('pi-codec-grant', providerId, model => model === allowedModel)
+ : bindHostedSessionProvider('pi-codec-grant', providerId, (provider, model) => provider === providerId && model === allowedModel);
+ const injected = deps();
+ const handler = getPiNativeSubscriptionHandler(providerId, 'pi-codec-grant', injected);
+ const request = async (model: unknown) => {
+ const body = { model, input: [] };
+ const res = responseRecorder();
+ await handler({
+ rawBody: compressed ? zstdCompressSync(Buffer.from(JSON.stringify(body))) : Buffer.from(JSON.stringify(body)),
+ parsedBody: compressed ? undefined : body,
+ ctx: { reqId: 1, method: 'POST', url: '/codex/responses', headers: compressed ? { 'content-encoding': 'zstd' } : {} },
+ res: res as never,
+ });
+ return res;
+ };
+ try {
+ expect((await request('gpt-6.1-sol')).status).toBe(200);
+ vi.mocked(injected.fetch).mockClear();
+ vi.mocked(injected.getChatgptAuth).mockClear();
+ for (const model of ['gpt-6.1-sol[1m]', 'unknown-model', undefined]) {
+ expect((await request(model)).status).toBe(403);
+ expect(injected.fetch).not.toHaveBeenCalled();
+ expect(injected.getChatgptAuth).not.toHaveBeenCalled();
+ }
+ allowedModel = 'chatgpt/gpt-6.1-sol[1m]';
+ expect((await request('gpt-6.1-sol')).status).toBe(403);
+ expect(injected.fetch).not.toHaveBeenCalled();
+ expect((await request('gpt-6.1-sol[1m]')).status).toBe(200);
+ vi.mocked(injected.fetch).mockClear();
+ vi.mocked(injected.getChatgptAuth).mockImplementationOnce(async () => {
+ binding.release();
+ return { accessToken: 'fixture-token', accountId: 'fixture-account' };
+ });
+ // Removing the hosted binding during an async auth read must not turn
+ // the in-flight request into an unrestricted local request.
+ expect((await request('gpt-6.1-sol[1m]')).status).toBe(403);
+ expect(injected.fetch).not.toHaveBeenCalled();
+ } finally { binding.release(); }
+ },
+ );
+
afterEach(() => {
setCustomProviders([]);
setXaiDiscoveredModels(null);
@@ -1119,16 +1175,21 @@ it.each([false, true])('scopes independent Grok limits and drops stale token pus
// This covers the path the turn-summary tests cannot observe. Tier: unit; injected HTTP response.
it('records a shared native request once by its requested model and preserves streaming bytes', async () => {
const record = vi.fn();
- const binding = registerGuestProviderRoute('guest-meter', 'openai', undefined, undefined, undefined, record);
+ const providerId = 'openai-meter-fixture';
+ setCustomProviders([buildUserProvider({ id: providerId, name: 'Meter fixture', auth: { method: 'oauth', native: 'codex' },
+ runtimes: { codex: { baseUrl: 'https://chatgpt.example', wireProtocol: 'openai-responses', models: [{ id: 'astra', name: 'Astra' }] },
+ pi: { baseUrl: 'https://chatgpt.example', wireProtocol: 'openai-responses', models: [{ id: 'chatgpt/astra', name: 'Astra' }] } },
+ })]);
+ const binding = registerGuestProviderRoute('guest-meter', providerId, undefined, undefined, undefined, record);
const frame = { type: 'response.completed', response: { usage: { input_tokens: 120, output_tokens: 8, input_tokens_details: { cached_tokens: 100 } } } };
const wire = `data: ${JSON.stringify(frame)}\n\ndata: ${JSON.stringify(frame)}\n\n`;
const injected = deps({ fetch: vi.fn(async () => new Response(wire, { headers: { 'content-type': 'text/event-stream' } })) });
const body = { model: 'astra', input: [] };
const res = responseRecorder();
try {
- await getPiNativeSubscriptionHandler('openai', 'guest-meter', injected)({ rawBody: Buffer.from(JSON.stringify(body)), parsedBody: body,
+ await getPiNativeSubscriptionHandler(providerId, 'guest-meter', injected)({ rawBody: Buffer.from(JSON.stringify(body)), parsedBody: body,
ctx: { method: 'POST', url: '/codex/responses', headers: { 'content-type': 'application/json' } }, res } as never);
expect(Buffer.concat(res.chunks).toString()).toBe(wire);
expect(record).toHaveBeenCalledExactlyOnceWith({ model: 'astra', inputTokens: 20, outputTokens: 8, cacheReadTokens: 100, cacheCreateTokens: 0 });
- } finally { binding.release(); }
+ } finally { binding.release(); setCustomProviders([]); }
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/piSharedSubscription.e2e.test.ts b/apps/desktop/src/main/maker-host/__tests__/piSharedSubscription.e2e.test.ts
new file mode 100644
index 0000000000..260290f6f8
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/piSharedSubscription.e2e.test.ts
@@ -0,0 +1,121 @@
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { existsSync } from 'node:fs';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { zstdDecompressSync } from 'node:zlib';
+import { expect, it, vi } from 'vitest';
+import { createAnthropicCompatProxy } from '@cindy/anthropic-compat-proxy';
+import { buildUserProvider } from '@cindy/model-providers';
+
+const fixture = vi.hoisted(() => ({ fetch: vi.fn() }));
+vi.mock('../../appSessionState.js', () => ({
+ isAppSessionBoundaryPending: () => false, activeOwnerScopeKey: () => 'cloud:pi-codec-fixture',
+}));
+vi.mock('../../appCapabilities.js', () => ({ getAppCapabilities: () => ({ canUseCindyGateway: true }) }));
+vi.mock('../runtime-configs.js', () => ({ claudeUpstreamEndpoint: () => 'https://unused.example' }));
+vi.mock('../subscription-fast-policy.js', () => ({ createSubscriptionFastPolicy: () => ({ isAllowed: () => true }) }));
+vi.mock('../logger-adapter.js', () => {
+ const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, child() { return logger; } };
+ return { createMakerLogger: () => logger, desktopMakerLogger: logger };
+});
+// Account state and cloud transport use fixtures. Pi, the loopback proxy, the
+// routing transform, native decoder and live grant checks are production code.
+vi.mock('../anthropic-responses-bridge-host.js', async importOriginal => {
+ const actual = await importOriginal<typeof import('../anthropic-responses-bridge-host.js')>();
+ return { ...actual, getPiNativeSubscriptionHandler: (provider: string, session: string) =>
+ actual.getPiNativeSubscriptionHandler(provider, session, {
+ fetch: fixture.fetch,
+ getChatgptAuth: async () => ({ accessToken: 'fixture-token', accountId: 'fixture-account' }),
+ getGrokToken: async () => 'fixture-token', peekGrokToken: () => 'fixture-token',
+ invalidateChatgpt: async () => false, invalidateXai: async () => 'ignored', recordXaiRateLimit() {},
+ }),
+ };
+});
+
+import { createModelRoutingTransform } from '../anthropic-compat-proxy-host.js';
+import { setCustomProviders } from '../active-catalog.js';
+import { bindHostedSessionProvider } from '../session-provider-store.js';
+import { registerGuestProviderRoute } from '../guest-provider-route-store.js';
+import { registerPiProxySession } from '../pi-proxy-session-auth.js';
+
+const binary = path.resolve('../../apps/pi-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'pi.exe' : 'pi');
+const providerId = 'openai-native-codec-fixture';
+const wireModel = 'gpt-6.1-sol';
+const catalogModel = `chatgpt/${wireModel}`;
+
+function reply(): string {
+ const item = { id: 'msg_codec', type: 'message', status: 'completed', role: 'assistant',
+ content: [{ type: 'output_text', text: 'native-proxy-ok', annotations: [] }] };
+ const response = { id: 'resp_codec', object: 'response', status: 'completed', model: wireModel, output: [item],
+ usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } } };
+ return [
+ { type: 'response.created', response: { ...response, status: 'in_progress', output: [] } },
+ { type: 'response.output_item.added', output_index: 0, item: { ...item, status: 'in_progress', content: [] } },
+ { type: 'response.content_part.added', output_index: 0, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'native-proxy-ok' },
+ { type: 'response.output_item.done', output_index: 0, item },
+ { type: 'response.completed', response },
+ ].map((event, sequence_number) => `event: ${event.type}\ndata: ${JSON.stringify({ ...event, sequence_number })}\n\n`).join('');
+}
+
+// Regression: real Pi sends zstd while the generic proxy's parsedBody is undefined.
+// The old host rejected this authorized request as model ''. Unit tests separately
+// covered plaintext routing and compressed forwarding, never their composition.
+// Tier: e2e (real child process + loopback HTTP), no user credentials or cloud calls.
+it.skipIf(!existsSync(binary)).each(['guest', 'owner'])('replies through the real Pi/proxy path for %s and rejects a revoked grant', async trust => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'cindy-pi-shared-codec-'));
+ let allowed = true;
+ const binding = trust === 'guest'
+ ? registerGuestProviderRoute('codec-runtime', providerId, model => allowed && model === catalogModel)
+ : bindHostedSessionProvider('codec-runtime', providerId, (provider, model) => allowed && provider === providerId && model === catalogModel);
+ const disposeToken = registerPiProxySession('codec-runtime', 'fixture-route-token', () => providerId);
+ setCustomProviders([buildUserProvider({ id: providerId, name: 'Native codec fixture', auth: { method: 'oauth', native: 'codex' },
+ runtimes: { codex: { baseUrl: 'https://chatgpt.example', wireProtocol: 'openai-responses', models: [{ id: wireModel, name: 'Fixture' }] } },
+ })]);
+ fixture.fetch.mockReset().mockImplementation(async (_url, init) => {
+ expect(init.headers['content-encoding']).toBe('zstd');
+ const payload = JSON.parse(zstdDecompressSync(Buffer.from(init.body)).toString());
+ expect(payload.model).toBe(wireModel);
+ return new Response(reply(), { headers: { 'content-type': 'text/event-stream' } });
+ });
+ let proxy: Awaited<ReturnType<typeof createAnthropicCompatProxy>> | undefined;
+ let child: ReturnType<typeof spawn> | undefined;
+ try {
+ proxy = await createAnthropicCompatProxy({ upstream: 'http://127.0.0.1:9', transformRequest: [], routingTransform: createModelRoutingTransform() });
+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');
+ const key = `${encode({ alg: 'none', typ: 'JWT' })}.${encode({ 'https://api.openai.com/auth': { chatgpt_account_id: 'fixture' } })}.`;
+ await writeFile(path.join(directory, 'models.json'), JSON.stringify({ providers: { 'openai-codex': {
+ baseUrl: proxy.url, apiKey: key,
+ headers: { 'x-cindy-pi-session-id': 'codec-runtime', 'x-cindy-pi-session-token': 'fixture-route-token', 'x-cindy-pi-provider-id': providerId },
+ models: [{ id: wireModel, name: 'Fixture', api: 'openai-codex-responses', input: ['text'], reasoning: false, contextWindow: 200000, maxTokens: 4096 }],
+ } } }));
+ await writeFile(path.join(directory, 'settings.json'), JSON.stringify({ transport: 'sse', retry: { maxRetries: 0 } }));
+ const run = async () => {
+ child = spawn(binary, ['--print', '--no-session', '--no-approve', '--no-extensions', '--no-skills', '--no-prompt-templates', '--no-context-files',
+ '--provider', 'openai-codex', '--model', wireModel, 'Reply briefly.'], {
+ cwd: directory, env: { ...process.env, PI_CODING_AGENT_DIR: directory }, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = ''; let stderr = '';
+ child.stdout!.on('data', chunk => { stdout += chunk; });
+ child.stderr!.on('data', chunk => { stderr += chunk; });
+ // real-wait: bound the actual Pi child lifetime; normal completion clears the deadline.
+ const timer = setTimeout(() => child?.kill(), 15000);
+ try { const [code] = await once(child, 'close'); return { code, stdout, stderr }; }
+ finally { clearTimeout(timer); }
+ };
+ const success = await run();
+ expect(success.code, success.stderr).toBe(0);
+ expect(success.stdout).toContain('native-proxy-ok');
+ expect(fixture.fetch).toHaveBeenCalledTimes(1);
+ allowed = false;
+ const denied = await run();
+ expect(denied.code).not.toBe(0);
+ expect(denied.stderr).toContain('not available');
+ expect(fixture.fetch).toHaveBeenCalledTimes(1);
+ } finally {
+ child?.kill(); await proxy?.dispose(); disposeToken(); binding.release(); setCustomProviders([]);
+ await rm(directory, { recursive: true, force: true });
+ }
+}, 30000);
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 5b9308fcea..3cbfbb50f7 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
@@ -697,7 +697,14 @@ export function createModelRoutingTransform(): RoutingTransform {
if (piGuest && !piRequestStaysOnGuestProvider(piGuest, piProviderId, registeredPiProviderId)) {
return refuseGuestProviderRoute(403, 'shared_provider_only', 'This request is outside the provider shared with you.');
}
- if (piGuest || hasHostedSessionModelAccess(piSessionId)) {
+ // Pi's native ChatGPT transport sends zstd JSON. The generic proxy keeps
+ // those bytes opaque; the native handler decodes and checks the live grant
+ // before forwarding. An unparsed compressed body is not a missing model.
+ const nativeCompressedPiRequest = piSessionId && piProviderId
+ && isOpenAiSubscriptionProviderId(piProviderId)
+ && ctx.headers['content-encoding']?.toLowerCase() === 'zstd'
+ && !isPlainObject(body);
+ if ((piGuest || hasHostedSessionModelAccess(piSessionId)) && !nativeCompressedPiRequest) {
const providerId = piGuest?.providerId ?? piProviderId ?? selectedPiProviderId;
// Check the live member grant before native handlers and all other Pi routing branches.
// Google's native API puts the authoritative model in the URL instead of body.model.
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 cf288e85d2..bd09325fdd 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
@@ -1,4 +1,11 @@
-import { captureGuestRequestUsage } from './guest-provider-route-store.js';
+import {
+ captureGuestRequestUsage,
+ guestProviderModelDenial,
+ guestProviderOffersModel,
+ guestProviderRouteForSession,
+ hostedProviderOffersModel,
+} from './guest-provider-route-store.js';
+import { hasHostedSessionModelAccess } from './session-provider-store.js';
import { fastModelId, rewriteFastModel } from './model-fast-mode.js';
import { captureUsagePricing, createUsagePricingObserver } from './model-usage-pricing.js';
import type { ResponseObserverSink } from '@cindy/anthropic-compat-proxy';
@@ -745,24 +752,30 @@ export function getPiNativeSubscriptionHandler(
res.once('close', abortOnClose);
const scopeAtStart = activeOwnerScopeKey();
const fastAtStart = getSessionFastMode(sessionId);
+ const guest = guestProviderRouteForSession(sessionId);
+ const hostedModelAccess = hasHostedSessionModelAccess(sessionId);
+ // Preserve the original catalog profile across wire rewrites (e.g. [1m])
+ // and recheck after asynchronous codecs/auth before any upstream request.
+ let requestedModel = '';
+ const modelAllowed = async (): Promise<boolean> => {
+ if (!guest && !hostedModelAccess) return true;
+ const allowed = guest
+ ? guest.providerId === providerId && await guestProviderOffersModel(providerId, 'pi', requestedModel, sessionId)
+ : hasHostedSessionModelAccess(sessionId) && hostedProviderOffersModel(sessionId, providerId, 'pi', requestedModel);
+ if (allowed) return true;
+ const denial = guest && requestedModel ? guestProviderModelDenial(sessionId, requestedModel, 'pi') : null;
+ res.writeHead(403, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
+ res.end(JSON.stringify({ type: 'error', error: {
+ type: 'authorization_error',
+ code: denial?.code ?? (guest ? 'shared_provider_only' : 'remote_model_not_allowed'),
+ message: denial?.message ?? (guest
+ ? `model '${requestedModel}' is not available from the provider shared with you`
+ : 'This model is not available for this remote task.'),
+ } }));
+ return false;
+ };
try {
throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
- let accessToken: string;
- let headers: Record<string, string>;
- if (isOpenAiSubscriptionProviderId(providerId)) {
- const auth = providerId === 'openai' ? await deps.getChatgptAuth() : await deps.getChatgptAuth(providerId);
- accessToken = auth.accessToken;
- headers = buildChatgptBridgeHeaders({
- accessToken,
- accountId: auth.accountId,
- sessionId,
- });
- } else {
- accessToken = providerId === 'xai' ? await deps.getGrokToken() : await deps.getGrokToken(providerId);
- headers = { authorization: `Bearer ${accessToken}` };
- }
- headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';
- headers.accept = ctx.headers.accept ?? 'text/event-stream';
let recordUsage: ReturnType<typeof captureUsagePricing> | undefined;
let recordGuestUsage: ReturnType<typeof captureGuestRequestUsage>;
let outboundBody = rawBody;
@@ -782,6 +795,8 @@ export function getPiNativeSubscriptionHandler(
} catch (error) {
decodeError = error;
}
+ requestedModel = isPlainRecord(current) && typeof current.model === 'string' ? current.model : '';
+ if (!await modelAllowed()) return;
recordGuestUsage = captureGuestRequestUsage(sessionId, isPlainRecord(current) && typeof current.model === 'string' ? current.model : '');
const profile = withOpenaiContextProfileModel(current);
current = profile ?? current;
@@ -812,6 +827,8 @@ export function getPiNativeSubscriptionHandler(
const parsed = isPlainRecord(parsedBody)
? parsedBody
: parseJsonRecord(rawBody);
+ requestedModel = parsed && typeof parsed.model === 'string' ? parsed.model : '';
+ if (!await modelAllowed()) return;
const sanitized = parsed ? sanitizeXaiModelInputBody(parsed) : null;
const withFast = parsed ? rewriteFastModel(providerId, 'pi', sanitized ?? parsed, fastAtStart) : null;
const current = withFast ?? sanitized ?? parsed;
@@ -827,8 +844,27 @@ export function getPiNativeSubscriptionHandler(
contentEncoding = undefined;
}
}
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
+ let accessToken: string;
+ let headers: Record<string, string>;
+ if (isOpenAiSubscriptionProviderId(providerId)) {
+ const auth = providerId === 'openai' ? await deps.getChatgptAuth() : await deps.getChatgptAuth(providerId);
+ accessToken = auth.accessToken;
+ headers = buildChatgptBridgeHeaders({
+ accessToken,
+ accountId: auth.accountId,
+ sessionId,
+ });
+ } else {
+ accessToken = providerId === 'xai' ? await deps.getGrokToken() : await deps.getGrokToken(providerId);
+ headers = { authorization: `Bearer ${accessToken}` };
+ }
+ headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';
+ headers.accept = ctx.headers.accept ?? 'text/event-stream';
if (contentEncoding) headers['content-encoding'] = contentEncoding;
+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
+ if (!await modelAllowed()) return;
throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
const response = await deps.fetch(upstream.url, {
method: 'POST',