Repository navigation
fix: resolve Gemini CLI 403 project-routing errors and prevent account bans #868
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
5ec8d94
d852a51
2df8b23
0b871b3
51dd7c9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,9 +1,15 @@ | ||||||||||||||||||||||||||||||||||||
| import { BaseExecutor } from "./base.ts"; | ||||||||||||||||||||||||||||||||||||
| import { PROVIDERS, OAUTH_ENDPOINTS } from "../config/constants.ts"; | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| export class GeminiCLIExecutor extends BaseExecutor { | ||||||||||||||||||||||||||||||||||||
| private _currentModel: string = ""; | ||||||||||||||||||||||||||||||||||||
| const LOAD_CODE_ASSIST_URL = "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist"; | ||||||||||||||||||||||||||||||||||||
| const PROJECT_TTL_MS = 30_000; // 30 seconds — matches native Gemini CLI | ||||||||||||||||||||||||||||||||||||
| const MAX_CACHE_SIZE = 100; | ||||||||||||||||||||||||||||||||||||
| const LOAD_CODE_ASSIST_TIMEOUT_MS = 10_000; // 10 seconds timeout | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| // Per-account cache: accessToken -> { projectId, expiresAt } | ||||||||||||||||||||||||||||||||||||
| const projectCache = new Map<string, { projectId: string; expiresAt: number }>(); | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| export class GeminiCLIExecutor extends BaseExecutor { | ||||||||||||||||||||||||||||||||||||
| constructor() { | ||||||||||||||||||||||||||||||||||||
| super("gemini-cli", PROVIDERS["gemini-cli"]); | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
@@ -18,28 +24,102 @@ export class GeminiCLIExecutor extends BaseExecutor { | |||||||||||||||||||||||||||||||||||
| "Content-Type": "application/json", | ||||||||||||||||||||||||||||||||||||
| Authorization: `Bearer ${credentials.accessToken}`, | ||||||||||||||||||||||||||||||||||||
| // Fingerprint headers matching native GeminiCLI client (prevents upstream rejection) | ||||||||||||||||||||||||||||||||||||
| "User-Agent": `GeminiCLI/0.31.0/${this._currentModel || "unknown"} (linux; x64)`, | ||||||||||||||||||||||||||||||||||||
| "User-Agent": "GeminiCLI/0.31.0/unknown (linux; x64)", | ||||||||||||||||||||||||||||||||||||
| "X-Goog-Api-Client": "google-genai-sdk/1.41.0 gl-node/v22.19.0", | ||||||||||||||||||||||||||||||||||||
| ...(stream && { Accept: "text/event-stream" }), | ||||||||||||||||||||||||||||||||||||
| ...(credentials?.projectId && { "x-goog-user-project": credentials.projectId }), | ||||||||||||||||||||||||||||||||||||
| // NOTE: x-goog-user-project removed — the stored projectId can become stale for | ||||||||||||||||||||||||||||||||||||
| // free-tier accounts, causing 403 "Cloud Code Private API has not been used in | ||||||||||||||||||||||||||||||||||||
| // project X". The API resolves the correct project from the OAuth token alone. | ||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| transformRequest(model, body, stream, credentials) { | ||||||||||||||||||||||||||||||||||||
| // Capture model so buildHeaders (called after transformRequest) can include it in User-Agent | ||||||||||||||||||||||||||||||||||||
| this._currentModel = model || ""; | ||||||||||||||||||||||||||||||||||||
| /** | ||||||||||||||||||||||||||||||||||||
| * Fetch the current cloudaicompanionProject via loadCodeAssist API. | ||||||||||||||||||||||||||||||||||||
| * Native Gemini CLI refreshes this every 30 seconds — OmniRoute stores it once | ||||||||||||||||||||||||||||||||||||
| * at OAuth connection time, so it goes stale. This method keeps it fresh. | ||||||||||||||||||||||||||||||||||||
| */ | ||||||||||||||||||||||||||||||||||||
| async refreshProject(accessToken: string): Promise<string | null> { | ||||||||||||||||||||||||||||||||||||
| // Check cache | ||||||||||||||||||||||||||||||||||||
| const cached = projectCache.get(accessToken); | ||||||||||||||||||||||||||||||||||||
| if (cached && cached.expiresAt > Date.now()) { | ||||||||||||||||||||||||||||||||||||
| return cached.projectId; | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||||||||
| const controller = new AbortController(); | ||||||||||||||||||||||||||||||||||||
| const timeoutId = setTimeout(() => controller.abort(), LOAD_CODE_ASSIST_TIMEOUT_MS); | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| let response; | ||||||||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||||||||
| response = await fetch(LOAD_CODE_ASSIST_URL, { | ||||||||||||||||||||||||||||||||||||
| method: "POST", | ||||||||||||||||||||||||||||||||||||
| headers: { | ||||||||||||||||||||||||||||||||||||
| Authorization: `Bearer ${accessToken}`, | ||||||||||||||||||||||||||||||||||||
| "Content-Type": "application/json", | ||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||
| body: JSON.stringify({ | ||||||||||||||||||||||||||||||||||||
| metadata: { | ||||||||||||||||||||||||||||||||||||
| ideType: "IDE_UNSPECIFIED", | ||||||||||||||||||||||||||||||||||||
| platform: "PLATFORM_UNSPECIFIED", | ||||||||||||||||||||||||||||||||||||
| pluginType: "GEMINI", | ||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||
| }), | ||||||||||||||||||||||||||||||||||||
| signal: controller.signal, | ||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||
| } finally { | ||||||||||||||||||||||||||||||||||||
| clearTimeout(timeoutId); | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| const allowBodyProjectOverride = process.env.OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE === "1"; | ||||||||||||||||||||||||||||||||||||
| if (!response.ok) { | ||||||||||||||||||||||||||||||||||||
| console.warn( | ||||||||||||||||||||||||||||||||||||
| `[OmniRoute] loadCodeAssist returned ${response.status} — falling back to stored projectId` | ||||||||||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||||||||||
| return null; | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| // Default: prefer OAuth-stored projectId. Incoming body.project can be stale | ||||||||||||||||||||||||||||||||||||
| // when clients cache older Cloud Code project values. | ||||||||||||||||||||||||||||||||||||
| // Opt-in escape hatch: set OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE=1. | ||||||||||||||||||||||||||||||||||||
| if (allowBodyProjectOverride && body?.project) { | ||||||||||||||||||||||||||||||||||||
| return body; | ||||||||||||||||||||||||||||||||||||
| const data = await response.json(); | ||||||||||||||||||||||||||||||||||||
| let projectId = ""; | ||||||||||||||||||||||||||||||||||||
| if (typeof data.cloudaicompanionProject === "string") { | ||||||||||||||||||||||||||||||||||||
| projectId = data.cloudaicompanionProject.trim(); | ||||||||||||||||||||||||||||||||||||
| } else if (data.cloudaicompanionProject?.id) { | ||||||||||||||||||||||||||||||||||||
| projectId = data.cloudaicompanionProject.id.trim(); | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's safer to verify that
Suggested change
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| if (!projectId) { | ||||||||||||||||||||||||||||||||||||
| console.warn("[OmniRoute] loadCodeAssist returned no project — falling back to stored projectId"); | ||||||||||||||||||||||||||||||||||||
| return null; | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| // Cache for 30 seconds (evict stale entries if cache is full) | ||||||||||||||||||||||||||||||||||||
| if (projectCache.size >= MAX_CACHE_SIZE) { | ||||||||||||||||||||||||||||||||||||
| const now = Date.now(); | ||||||||||||||||||||||||||||||||||||
| for (const [key, val] of projectCache) { | ||||||||||||||||||||||||||||||||||||
| if (val.expiresAt <= now) projectCache.delete(key); | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
Comment on lines
+110
to
+120
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The current eviction logic only removes expired entries. If the cache is full of valid (non-expired) entries, it will continue to grow beyond
Suggested change
|
||||||||||||||||||||||||||||||||||||
| projectCache.set(accessToken, { | ||||||||||||||||||||||||||||||||||||
| projectId, | ||||||||||||||||||||||||||||||||||||
| expiresAt: Date.now() + PROJECT_TTL_MS, | ||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| return projectId; | ||||||||||||||||||||||||||||||||||||
| } catch (error) { | ||||||||||||||||||||||||||||||||||||
| const msg = error instanceof Error ? error.message : String(error); | ||||||||||||||||||||||||||||||||||||
| console.warn(`[OmniRoute] loadCodeAssist failed (${msg}) — falling back to stored projectId`); | ||||||||||||||||||||||||||||||||||||
| return null; | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| if (credentials?.projectId) { | ||||||||||||||||||||||||||||||||||||
| body.project = credentials.projectId; | ||||||||||||||||||||||||||||||||||||
| async transformRequest(model, body, stream, credentials) { | ||||||||||||||||||||||||||||||||||||
| // Refresh the project ID via loadCodeAssist (cached for 30s). | ||||||||||||||||||||||||||||||||||||
| // The translator builds the envelope with the stale stored projectId — | ||||||||||||||||||||||||||||||||||||
| // we replace it here with the fresh one before sending to the API. | ||||||||||||||||||||||||||||||||||||
| if (body && typeof body === "object" && body.request && credentials.accessToken) { | ||||||||||||||||||||||||||||||||||||
| const freshProject = await this.refreshProject(credentials.accessToken); | ||||||||||||||||||||||||||||||||||||
| if (freshProject) { | ||||||||||||||||||||||||||||||||||||
| body.project = freshProject; | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| // If refresh failed, keep the stale projectId as a best-effort fallback | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| return body; | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -83,6 +83,15 @@ export function hasValuableContent(chunk, format) { | |
| return true; // Other formats: keep all chunks | ||
| } | ||
|
|
||
| /** | ||
| * Unwrap Cloud Code API envelope from a Gemini response chunk. | ||
| * The Cloud Code API wraps responses in { response: { candidates: [...] } } | ||
| * while standard Gemini returns { candidates: [...] } directly. | ||
| */ | ||
| export function unwrapGeminiChunk(parsed) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WARNING: Incorrect unwrapping logic - handles edge case incorrectly The ternary
Correct logic: Only unwrap when export function unwrapGeminiChunk(parsed) {
if (!parsed.candidates && parsed.response) {
return parsed.response;
}
return parsed;
}The test at line 96 ( |
||
| return parsed.candidates ? parsed : parsed.response || parsed; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: Use explicit Consider changing |
||
| } | ||
|
|
||
| // Fix invalid id (generic or too short) | ||
| export function fixInvalidId(parsed) { | ||
| if (parsed.id && (parsed.id === "chat" || parsed.id === "completion" || parsed.id.length < 8)) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| import { describe, it } from "node:test"; | ||
| import assert from "node:assert"; | ||
| import { hasValuableContent } from "../../open-sse/utils/streamHelpers.ts"; | ||
| import { hasValuableContent, unwrapGeminiChunk } from "../../open-sse/utils/streamHelpers.ts"; | ||
| import { FORMATS } from "../../open-sse/translator/formats.ts"; | ||
|
|
||
| describe("hasValuableContent", () => { | ||
|
|
@@ -70,3 +70,42 @@ describe("hasValuableContent", () => { | |
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe("unwrapGeminiChunk", () => { | ||
| it("returns chunk directly when candidates is at top level (standard Gemini)", () => { | ||
| const chunk = { candidates: [{ content: { parts: [{ text: "Hi" }] } }], usageMetadata: {} }; | ||
| const result = unwrapGeminiChunk(chunk); | ||
| assert.strictEqual(result, chunk); | ||
| }); | ||
|
|
||
| it("unwraps Cloud Code envelope { response: { candidates: [...] } }", () => { | ||
| const inner = { candidates: [{ content: { parts: [{ text: "Hello" }] } }] }; | ||
| const chunk = { response: inner, modelVersion: "gemini-2.5-flash" }; | ||
| const result = unwrapGeminiChunk(chunk); | ||
| assert.strictEqual(result, inner); | ||
| assert.deepEqual(result.candidates[0].content.parts[0].text, "Hello"); | ||
| }); | ||
|
|
||
| it("returns parsed directly when no candidates and no response", () => { | ||
| const chunk = { someOther: "data" }; | ||
| const result = unwrapGeminiChunk(chunk); | ||
| assert.strictEqual(result, chunk); | ||
| }); | ||
|
|
||
| it("returns parsed when response exists but is null/undefined", () => { | ||
| const chunk = { response: null, other: "data" }; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WARNING: Test may pass incorrectly due to bug in The test If the implementation is fixed to |
||
| const result = unwrapGeminiChunk(chunk); | ||
| assert.strictEqual(result, chunk); | ||
| }); | ||
|
|
||
| it("prefers top-level candidates over response when both exist", () => { | ||
| const inner = { candidates: [{ content: { parts: [{ text: "inner" }] } }] }; | ||
| const chunk = { | ||
| candidates: [{ content: { parts: [{ text: "outer" }] } }], | ||
| response: inner, | ||
| }; | ||
| const result = unwrapGeminiChunk(chunk); | ||
| assert.strictEqual(result, chunk); | ||
| assert.equal(result.candidates[0].content.parts[0].text, "outer"); | ||
| }); | ||
| }); | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This implementation is susceptible to a "thundering herd" issue. If multiple concurrent requests arrive for the same
accessTokenwhile the cache is empty or expired, they will all bypass the cache check and trigger separatefetchcalls to the Google API. This can lead to unnecessary load and potential rate limiting. Consider deduplicating in-flight requests using a sharedMapof promises.