one-model-router 0.0.10 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
@@ -1,1721 +1,1721 @@
1
- /**
2
- * Gemini 渠道 —— 对接 Google Cloud Code Assist 免费线(antigravity 客户端伪装)。
3
- *
4
- * 协议要点确认:
5
- * - 通道:Google Cloud Code Assist 免费线(antigravity 客户端伪装)。
6
- * 端点 daily-cloudcode-pa.googleapis.com(主)/ *.sandbox.googleapis.com(备),
7
- * 流式推理 POST /v1internal:streamGenerateContent?alt=sse;
8
- * 项目探测 POST /v1internal:loadCodeAssist(sandbox 优先,daily 兜底),
9
- * 请求体固定为 `{"metadata":{"ideType":"ANTIGRAVITY"}}`(多一个字段就可能被
10
- * 上游识别成非官方客户端)。
11
- * - 身份五头写死不许随机:User-Agent `antigravity/4.3.0 (cmdc-pak)`、
12
- * x-client-name/x-client-version/x-machine-id/x-vscode-sessionid;
13
- * ⚠️ 不带 x-goog-api-key / x-goog-api-client;流式请求**刻意不带 Accept**。
14
- * - 信封 {model, project, request, requestId, userAgent} 必须**逐层按键名
15
- * 字母序**序列化 —— 服务端(Go)对 map 自动字母序,JSON.stringify 是插入序,
16
- * 不排序与上游看到的字节不同。
17
- * - 模型名是准入钥匙:发裸 `gemini-3.8-flash` 上游 404,必须带档位后缀
18
- * (-low/-medium/-high/-tiered);lite 已整体移除(恒 404);
19
- * 「关闭思考」是假关(关 includeThoughts 照样思考照样计费)⇒ includeThoughts
20
- * **恒 true**,不提供 none 档;tiered 档只发 includeThoughts 不发 thinkingBudget。
21
- * - sessionId **不是常量**:= f(project, 首条 user 文本, lane)(FNV-1a 派生依赖维度)。
22
- * 上游按 sessionId 在**服务端**累计对话输入,
23
- * 长工具循环推过 1M 后该会话每个请求都 400 —— 唯一出路是「升代」换新
24
- * sessionId(判据:400 + "exceeds the maximum number of tokens")。
25
- * - 登录:浏览器回调式 OAuth(authorization_code + client_secret,无 PKCE)。
26
- * ⚠️ token 端点强制校验客户端身份,表单**必须**带 client_secret;
27
- * ⚠️ 必须「先监听再拼 URL」(端口被占回退别的端口,先拼 URL 就
28
- * redirect_uri_mismatch);回调路径 /oauth-callback 与 client 注册值一致;
29
- * loopback 重定向(RFC 8252)允许任意端口;同时听 127.0.0.1 与 [::1]
30
- * (浏览器常把 localhost 解析成 IPv6);授权总预算 6 分钟(Google 常带二次验证)。
31
- * - 续期:refresh_token grant;Google **偶尔轮换 refresh_token**,响应给了新的
32
- * 必须回写;Google 有重放检测。终态判据只看**令牌端点的 error 码**
33
- * (invalid_grant/invalid_client/expired/revoked/unauthorized),网络错误的
34
- * 文案(TLS CERT_HAS_EXPIRED 含 "expired")**不能**判终态。
35
- * - project 探测三级缓存:内存 → 凭据 cloudaicompanionProject → 现探 LCA。
36
- * LCA 200 但 project 为空 = 免费档常态 → 回落 `aicode-consumers` 照常发推理;
37
- * LCA **失败**(网络/非 2xx)→ 不发推理。
38
- * - thoughtSignature:functionCall part 上的签名按「工具名 + 字母序参数」
39
- * 记缓存,下一轮回填(思考分片上的签名刻意不存);上游拒签名时**去签重试
40
- * 一次**。签名键 = sha256("tool:"+name+"\0"+args[:512])[:16]。
41
- * - 消息转换:role 只有 user/model(assistant→model,其余→user);历史 thinking
42
- * 不回传;functionResponse 只认 name(按 tool_use.id→name 映射回填),空 name
43
- * 整块丢弃;一批 tool_calls 只有**全部**拿到结果才保留(无结果的 tool_call
44
- * 上游 400);图片内联失败**显式抛错**不静默丢图。
45
- * - SSE:每帧 `{"response":{…}}` 或裸 Response,只有 candidates 非空才算内容帧
46
- * (纯 usageMetadata 收尾帧继续读);`data: [DONE]` 结束;`:` 开头是注释行;
47
- * 收尾余量必须按整行再走一遍(否则末帧 finishReason/usage 被丢);用量取
48
- * 「见过的最大 totalTokenCount」那一份;上游生成大 functionCall 参数期间可能
49
- * 长时间不 flush,读取必须带空闲超时。
50
- * - 错误分类:签名错误→去签重试;会话 1M→升代;上下文超限→request(不换端点
51
- * 不换号);400+quota 文案→quota 可换号;403/404/429→先换端点一次(零成本
52
- * 无害但救不了 quota,主救场是换账号);401→auth 可换号。
53
- */
54
-
55
- import { createHash, randomBytes } from 'node:crypto'
56
- import { createServer } from 'node:http'
57
- import { httpFetch, readBodyText, mergeSseChunks, roundCredits } from '../util.js'
58
-
59
- // ── 端点与路径 ───────────────────────────────────────────────────────────────
60
-
61
- const ENDPOINT_DAILY = 'https://daily-cloudcode-pa.googleapis.com'
62
- const ENDPOINT_SANDBOX = 'https://daily-cloudcode-pa.sandbox.googleapis.com'
63
- /** 推理端点轮换顺序(初始 endpoints)。 */
64
- const ENDPOINTS = [ENDPOINT_DAILY, ENDPOINT_SANDBOX]
65
- /** 探测端点顺序:sandbox 优先(LCA 固定路由到 sandbox)。 */
66
- const PROBE_ENDPOINTS = [ENDPOINT_SANDBOX, ENDPOINT_DAILY]
67
-
68
- const STREAM_PATH = '/v1internal:streamGenerateContent?alt=sse'
69
- const LOAD_CODE_ASSIST_PATH = '/v1internal:loadCodeAssist'
70
- /** 档位探测请求体(content-length 恰为 38)。 */
71
- const LOAD_CODE_ASSIST_BODY = '{"metadata":{"ideType":"ANTIGRAVITY"}}'
72
-
73
- // ── 身份伪装(常量,不许随机)───────────────────────────────────────────────
74
-
75
- /** 身份五头。⚠️ 写死;⚠️ 不带 x-goog-api-key / x-goog-api-client。 */
76
- const IDENTITY_HEADERS = Object.freeze({
77
- 'User-Agent': 'antigravity/4.3.0 (cmdc-pak)',
78
- 'x-client-name': 'antigravity',
79
- 'x-client-version': '4.3.0',
80
- 'x-machine-id': 'cmdc-pak',
81
- 'x-vscode-sessionid': 'proxy',
82
- })
83
- /** 信封里的 userAgent 字段(与 x-client-name 同值)。 */
84
- const UPSTREAM_USER_AGENT = 'antigravity'
85
-
86
- // ── OAuth ───────────────────────────────────────────────────────────────────────
87
-
88
- const AUTH_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth'
89
- const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
90
- const USERINFO_ENDPOINT = 'https://www.googleapis.com/oauth2/v2/userinfo'
91
-
92
- /** 上游 Cloud Code 客户端的公开 client(env 可覆盖)。 */
93
- const DEFAULT_CLIENT_ID = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com'
94
- const DEFAULT_CLIENT_SECRET = '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'
95
- /** 回调路径(与 client 注册值一致)。 */
96
- const CALLBACK_PATH = '/oauth-callback'
97
- /** 重定向 URI 主机名。⚠️ 必须是 localhost 而不是 127.0.0.1。 */
98
- const REDIRECT_HOST = 'localhost'
99
-
100
- /** 六项 scope(cloud-platform 必需,后两项是 Cloud Code 自己的通道)。 */
101
- const SCOPES = [
102
- 'openid',
103
- 'https://www.googleapis.com/auth/cloud-platform',
104
- 'https://www.googleapis.com/auth/userinfo.email',
105
- 'https://www.googleapis.com/auth/userinfo.profile',
106
- 'https://www.googleapis.com/auth/cclog',
107
- 'https://www.googleapis.com/auth/experimentsandconfigs',
108
- ]
109
-
110
- /** 授权流程总预算 6 分钟(Google 账号常带二次验证,3 分钟会把正常用户掐掉)。 */
111
- const AUTH_FLOW_TIMEOUT_MS = 360_000
112
- /** OAuth 端点请求超时。 */
113
- const OAUTH_TIMEOUT_MS = 20_000
114
-
115
- /** 回调成功后展示的页面。 */
116
- const CALLBACK_HTML = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>授权完成</title><style>body{font:15px/1.7 -apple-system,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#0f1115;color:#e6e8eb}.b{text-align:center}.k{font-size:34px;margin-bottom:8px}</style></head><body><div class="b"><div class="k">✓</div><div>授权已完成,可以关闭此页回到面板。</div></div></body></html>`
117
-
118
- // ── 模型档表 ───────────────────────────────────────────────────────────────────
119
-
120
- /** 主模型上游名(不带档位后缀,后缀由 modelSpec 拼)。 */
121
- const UPSTREAM_FLASH = 'gemini-3.8-flash'
122
- const BUDGET_LOW = 1_000
123
- const BUDGET_MEDIUM = 4_000
124
- const BUDGET_HIGH = 10_000
125
- /** tiered 档:只发 includeThoughts,不发 thinkingBudget。 */
126
- const BUDGET_TIERED = -1
127
- /** 上下文窗口(用户拍板填 1_000_000)。 */
128
- const CONTEXT_WINDOW = 1_000_000
129
- const EFFORT_IDS = ['low', 'medium', 'high', 'tiered']
130
- const DEFAULT_EFFORT = 'medium'
131
- /** 默认最大输出 token(用户拍板 64000)。 */
132
- const MAX_OUTPUT_TOKENS = 64_000
133
-
134
- /** 兜底模型目录(用户拍板静态表,不拉远端目录)。 */
135
- /** ⚠️ 不暴露 lite(上游恒 404,暴露即坑);档位走 efforts 下拉框,不拆成 4 个模型名。 */
136
- export const fallbackModels = [
137
- {
138
- id: UPSTREAM_FLASH,
139
- name: 'Gemini 3.8 Flash',
140
- contextWindow: CONTEXT_WINDOW,
141
- maxTokens: MAX_OUTPUT_TOKENS,
142
- supportsImage: true,
143
- efforts: EFFORT_IDS,
144
- defaultEffort: DEFAULT_EFFORT,
145
- },
146
- ]
147
-
148
- /** 匿名即可获取模型清单:fetchModels 返回本地静态 fallbackModels(零网络),不依赖任何账号凭据。 */
149
- export const meta = { id: 'gemini', label: 'Gemini Code Assist', loginMode: 'oauth-callback', anonymousModels: true }
150
-
151
- // ── 项目与会话 ──────────────────────────────────────────────────────────────────
152
-
153
- /** LCA 探测为空/失败时的兜底项目号(免费档常态)。 */
154
- const DEFAULT_PROJECT = 'aicode-consumers'
155
- /** 会话派生标签(推理 / 冒烟),只区分派生路径(lane 进哈希),不参与取值。 */
156
- const SESSION_LANE_INFER = 'infer'
157
-
158
- // ── 超时与限额 ──────────────────────────────────────────────────────────────
159
-
160
- /** 推理请求头超时。 */
161
- const REQUEST_TIMEOUT_MS = 120_000
162
- /** LCA/配额类请求超时。 */
163
- const PROBE_TIMEOUT_MS = 30_000
164
- /** SSE 空闲超时:上游生成大 functionCall 参数期间可能长时间不 flush,必须主动掐。 */
165
- const IDLE_TIMEOUT_MS = 120_000
166
- /** BODY 读超时。 */
167
- const BODY_READ_TIMEOUT_MS = 15_000
168
- /** 续期提前量(OMR 口径:过期前 1 小时)。 */
169
- const REFRESH_LEAD_MS = 60 * 60_000
170
- /** 上游单张内联图片体积上限(超出整请求被拒)。 */
171
- const MAX_IMAGE_BYTES_INLINE = 10 * 1024 * 1024
172
- /** 请求体上限(发送前真实检查)。 */
173
- const MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024
174
- /** 一次请求内最多升几代(必须有界,否则无界升代变死循环)。 */
175
- const MAX_SESSION_BUMPS = 1
176
- /** 429 命中后原账号的冷却时长。 */
177
- const RATE_LIMIT_COOLDOWN_MS = 60_000
178
- /** 401 命中后原账号的冷却时长。 */
179
- const AUTH_COOLDOWN_MS = 300_000
180
- /** 签名缓存条数上限(签名串平均 300~800 字节,2000 条约 1MB 量级)。 */
181
- const SIG_MAX_ENTRIES = 2_000
182
- /** 算签名键时只取正文前 512 字符(长回答尾部每次都不一样,用全文命中率趋 0)。 */
183
- const SIG_KEY_BODY_LIMIT = 512
184
-
185
- /** 额度/限流文案标记(小写比对)。 */
186
- const QUOTA_MARKERS = ['quota', 'resource_exhausted', 'resource exhausted', 'rate limit', 'exceeded']
187
- /** 可换端点的 400 文案标记(quota/permission/unsupported/project)。 */
188
- const SWITCHABLE_MARKERS = ['quota', 'permission', 'unsupported', 'project']
189
-
190
- /** 上下文超限判据:要求「token count」+「exceeds the maximum」同时出现(实测报文)。 */
191
- const TOKEN_COUNT_OVERFLOW = /\btoken\s+count\b[\s\S]{0,60}?\bexceeds?\s+the\s+maximum\b/i
192
- /** 服务端会话累计超 1M 判据(实测报文)。 */
193
- const SESSION_OVERFLOW_MARKER = 'exceeds the maximum number of tokens'
194
-
195
- // ── 小工具 ──────────────────────────────────────────────────────────────────
196
-
197
- function readStringField(source, key) {
198
- const value = source?.[key]
199
- if (typeof value === 'string' && value.trim().length > 0) return value.trim()
200
- return ''
201
- }
202
-
203
- /**
204
- * 递归按键名升序重建值(数组保持顺序)。
205
- * ⚠️ 不是为了好看 —— 服务端(Go)对 map 自动按字母序序列化,
206
- * 服务端看到的是字节;键全为 ASCII 时 sort() 的码元序与 Go 字节序一致。
207
- */
208
- function sortValue(value) {
209
- if (Array.isArray(value)) return value.map(sortValue)
210
- if (value === null || typeof value !== 'object') return value
211
- const out = {}
212
- for (const key of Object.keys(value).sort()) out[key] = sortValue(value[key])
213
- return out
214
- }
215
-
216
- /** 字母序信封序列化。 */
217
- function marshalAlphabetical(value) {
218
- return JSON.stringify(sortValue(value))
219
- }
220
-
221
- /** 参数规范化:按键名升序的紧凑 JSON。签名键两侧必须用同一个规范化。 */
222
- function canonicalArgs(args) {
223
- if (args === undefined || args === null) return '{}'
224
- return marshalAlphabetical(args)
225
- }
226
-
227
- /** 每请求随机的 requestId。 */
228
- function newRequestId(nowMs = Date.now()) {
229
- return `agent/${nowMs}/${randomBytes(4).toString('hex')}`
230
- }
231
-
232
- /**
233
- * 按 (project, 首条 user 文本,lane) 确定性派生 sessionId(FNV-1a)。
234
- * generation > 0 时拼进输入(会话升代自愈);=== 0 时不拼。
235
- */
236
- function deriveSessionId(project, firstUserText, lane, generation = 0) {
237
- let hash = 0xcbf29ce484222325n
238
- const prime = 0x100000001b3n
239
- const mask = 0xffffffffffffffffn
240
- const base = `${project}\u0000${lane}\u0000${firstUserText}`
241
- const input = generation > 0 ? `${base}\u0000${generation}` : base
242
- for (const byte of Buffer.from(input, 'utf8')) {
243
- hash = (hash ^ BigInt(byte)) & mask
244
- hash = (hash * prime) & mask
245
- }
246
- return BigInt.asIntN(64, hash).toString()
247
- }
248
-
249
- /** 从错误体抽人可读消息(JSON error.message/message → 原文截断)。 */
250
- function extractMessage(bodyText) {
251
- const text = String(bodyText ?? '').trim()
252
- if (text === '') return ''
253
- try {
254
- const parsed = JSON.parse(text)
255
- const found = [parsed?.error?.message ?? (typeof parsed?.error === 'string' ? parsed.error : ''), parsed?.message]
256
- .filter(v => typeof v === 'string' && v.length > 0)
257
- if (found.length > 0) return found.join(' ').slice(0, 300)
258
- } catch { /* 非 JSON */ }
259
- return text.slice(0, 300)
260
- }
261
-
262
- function hasMarker(text, markers) {
263
- const lower = String(text ?? '').toLowerCase()
264
- return markers.some(m => lower.includes(m))
265
- }
266
-
267
- /** 判定「签名被上游拒绝」。必须宽:漏判=用户看到莫名 400,误判=多发一次无签名请求。 */
268
- function isSignatureError(text) {
269
- const lower = String(text ?? '').toLowerCase()
270
- return lower.includes('signature') || (lower.includes('thought') && lower.includes('invalid'))
271
- }
272
-
273
- /** 非负整数提取。 */
274
- function nonNegativeInt(value) {
275
- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : undefined
276
- }
277
-
278
- /** 睡眠(可被 signal 中断)。 */
279
- function sleep(ms, signal) {
280
- return new Promise((resolve, reject) => {
281
- if (signal?.aborted) { reject(new Error('已取消')); return }
282
- const timer = setTimeout(() => {
283
- signal?.removeEventListener('abort', onAbort)
284
- resolve()
285
- }, ms)
286
- const onAbort = () => { clearTimeout(timer); reject(new Error('已取消')) }
287
- signal?.addEventListener('abort', onAbort, { once: true })
288
- })
289
- }
290
-
291
- // ── 模型规格 ────────────────────────────────────────────────────────────────
292
-
293
- /** 档位 id 归一(未知/缺省一律 medium,同默认分支)。 */
294
- function effortToTier(effort) {
295
- if (effort === 'low' || effort === 'medium' || effort === 'high' || effort === 'tiered') return effort
296
- return 'medium'
297
- }
298
-
299
- /** 档位 → 思考预算(tiered = -1 只发 includeThoughts)。 */
300
- function thinkingBudget(tier) {
301
- if (tier === 'low') return BUDGET_LOW
302
- if (tier === 'high') return BUDGET_HIGH
303
- if (tier === 'tiered') return BUDGET_TIERED
304
- return BUDGET_MEDIUM
305
- }
306
-
307
- /**
308
- * 归一化模型 id:剥掉已知档位后缀(-low/-medium/-high/-tiered)得到目录裸名。
309
- * ⚠️ 只剥已知档位:限流标记/探测链路传来的是带档位的名字,先归一化再查表。
310
- */
311
- function canonicalModelId(modelId) {
312
- for (const tier of EFFORT_IDS) {
313
- if (modelId.endsWith(`-${tier}`)) return modelId.slice(0, modelId.length - tier.length - 1)
314
- }
315
- return modelId
316
- }
317
-
318
- /**
319
- * 由「模型 id + 用户选的档位」得出上游模型规格。
320
- * ⚠️ 模型名必须带档位后缀 —— 它是上游的准入钥匙(裸名 404)。
321
- * ⚠️ 严格校验:未知 id 直接拒绝不发上游(宽容的代价是用户写错模型名时静默
322
- * 跑出 3.8 的答案且无任何征兆 —— 实测假名 200 正常作答,名字不参与上游路由)。
323
- */
324
- function modelSpec(modelId, effort) {
325
- if (canonicalModelId(String(modelId ?? '')) !== UPSTREAM_FLASH) {
326
- throw { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message: `gemini: 模型 "${modelId}" 不在本渠道目录中(仅支持 ${UPSTREAM_FLASH})` }
327
- }
328
- const tier = effortToTier(typeof effort === 'string' ? effort : undefined)
329
- return { upstream: `${UPSTREAM_FLASH}-${tier}`, tier, thinkingBudget: thinkingBudget(tier), includeThoughts: true }
330
- }
331
-
332
- // ── 凭据 ────────────────────────────────────────────────────────────────────
333
-
334
- function credentialExpiresAtMs(credential) {
335
- const expiry = credential?.expiry
336
- if (typeof expiry === 'string' && expiry !== '') {
337
- const parsed = Date.parse(expiry)
338
- if (Number.isFinite(parsed)) return parsed
339
- }
340
- const ms = credential?.expire_time
341
- return typeof ms === 'number' && Number.isFinite(ms) && ms > 0 ? ms : undefined
342
- }
343
-
344
- function isRefreshable(credential) {
345
- return typeof credential?.refresh_token === 'string' && credential.refresh_token !== ''
346
- }
347
-
348
- /** 过期前 1 小时即需续期;取不到过期时刻返回 false。 */
349
- export function needsRefresh(credential) {
350
- if (!isRefreshable(credential)) return false
351
- const expiresAt = credentialExpiresAtMs(credential)
352
- if (expiresAt === undefined) return false
353
- return Date.now() >= expiresAt - REFRESH_LEAD_MS
354
- }
355
-
356
- export function describeCredential(credential) {
357
- const email = readStringField(credential, 'email')
358
- const sub = readStringField(credential, 'sub')
359
- return {
360
- label: email || sub || 'Gemini 账号',
361
- expiresAt: credentialExpiresAtMs(credential) ?? 0,
362
- refreshable: isRefreshable(credential),
363
- }
364
- }
365
-
366
- /** 稳定去重键:email/sub(sub 是 OIDC 稳定标识,邮箱可改 sub 不变)。 */
367
- export function credentialIdentity(credential) {
368
- return readStringField(credential, 'email') || readStringField(credential, 'sub') || ''
369
- }
370
-
371
- /** 手动粘贴凭据的规范化:接受 JSON 对象/字符串,字段名与 OAuth 响应一致。 */
372
- export function normalizeCredential(raw) {
373
- let value = raw
374
- if (typeof value === 'string') {
375
- try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
376
- }
377
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
378
- throw new Error('凭据必须是 JSON 对象')
379
- }
380
- const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken')
381
- if (!accessToken) throw new Error('凭据缺少 access_token')
382
- const out = { ...value, access_token: accessToken }
383
- const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken')
384
- if (refreshToken) out.refresh_token = refreshToken
385
- if (readStringField(value, 'token_type')) out.token_type = readStringField(value, 'token_type')
386
- if (readStringField(value, 'scope')) out.scope = readStringField(value, 'scope')
387
- if (readStringField(value, 'sub')) out.sub = readStringField(value, 'sub')
388
- if (readStringField(value, 'email')) out.email = readStringField(value, 'email')
389
- if (readStringField(value, 'cloudaicompanionProject')) out.cloudaicompanionProject = readStringField(value, 'cloudaicompanionProject')
390
- const expiresAt = credentialExpiresAtMs(value)
391
- if (expiresAt !== undefined) out.expiry = new Date(expiresAt).toISOString()
392
- return out
393
- }
394
-
395
- // ── 令牌载荷 ──────────────────────────────────────────────────────────────────────
396
-
397
- function clientId() {
398
- const fromEnv = process.env.CMDC_PAK_GOOGLE_CLIENT_ID?.trim()
399
- return fromEnv ? fromEnv : DEFAULT_CLIENT_ID
400
- }
401
-
402
- function clientSecret() {
403
- const fromEnv = process.env.CMDC_PAK_GOOGLE_CLIENT_SECRET?.trim()
404
- return fromEnv ? fromEnv : DEFAULT_CLIENT_SECRET
405
- }
406
-
407
- /**
408
- * 解析令牌端点响应。三种失败形态都给能定位问题的文案:
409
- * error 字段 / 缺 access_token / 非 JSON。
410
- * ⚠️ Google 偶尔轮换 refresh_token:响应没给新的就沿用 previousRefreshToken。
411
- */
412
- function parseTokenGrant(payload, previousRefreshToken) {
413
- if (payload === null || typeof payload !== 'object') {
414
- throw new Error('令牌端点返回无法解析(非 JSON 对象)')
415
- }
416
- const errorCode = typeof payload.error === 'string' ? payload.error : ''
417
- if (errorCode !== '') {
418
- const description = typeof payload.error_description === 'string' ? payload.error_description : ''
419
- throw new Error(description === '' ? errorCode : `${errorCode}: ${description}`)
420
- }
421
- const accessToken = typeof payload.access_token === 'string' ? payload.access_token : ''
422
- if (accessToken === '') throw new Error('令牌端点未返回 access_token')
423
- const rawRefresh = typeof payload.refresh_token === 'string' ? payload.refresh_token : ''
424
- const refreshToken = rawRefresh !== '' ? rawRefresh : previousRefreshToken
425
- const rawTokenType = typeof payload.token_type === 'string' ? payload.token_type : ''
426
- const expiresIn = typeof payload.expires_in === 'number' && Number.isFinite(payload.expires_in) && payload.expires_in > 0
427
- ? Math.floor(payload.expires_in)
428
- : 3600
429
- return {
430
- access_token: accessToken,
431
- token_type: rawTokenType === '' ? 'Bearer' : rawTokenType,
432
- expires_in: expiresIn,
433
- ...(refreshToken ? { refresh_token: refreshToken } : {}),
434
- ...(typeof payload.scope === 'string' && payload.scope !== '' ? { scope: payload.scope } : {}),
435
- ...(typeof payload.id_token === 'string' && payload.id_token !== '' ? { id_token: payload.id_token } : {}),
436
- }
437
- }
438
-
439
- /**
440
- * 从 id_token 解出身份(sub/email)。
441
- * ⚠️ 不验签:只用于展示名与稳定标识,不作为鉴权依据;失败返回 {} 不抛错。
442
- */
443
- function identityFromIdToken(idToken) {
444
- if (typeof idToken !== 'string' || idToken === '') return {}
445
- const parts = idToken.split('.')
446
- if (parts.length < 2) return {}
447
- let payload
448
- try {
449
- payload = JSON.parse(Buffer.from(parts[1] ?? '', 'base64url').toString('utf8'))
450
- } catch {
451
- return {}
452
- }
453
- if (payload === null || typeof payload !== 'object') return {}
454
- const out = {}
455
- if (typeof payload.sub === 'string' && payload.sub !== '') out.sub = payload.sub
456
- if (typeof payload.email === 'string' && payload.email !== '') out.email = payload.email
457
- return out
458
- }
459
-
460
- /** 把令牌授予结果并成一条凭据(保留既有 sub/email/project/refresh_token)。 */
461
- function credentialFromGrant(grant, previous = {}) {
462
- const credential = {
463
- access_token: grant.access_token,
464
- token_type: grant.token_type,
465
- expires_in: grant.expires_in,
466
- expiry: new Date(Date.now() + (grant.expires_in > 0 ? grant.expires_in : 3600) * 1000).toISOString(),
467
- }
468
- const refreshToken = grant.refresh_token ?? previous.refresh_token
469
- if (refreshToken) credential.refresh_token = refreshToken
470
- const scope = grant.scope ?? previous.scope
471
- if (scope) credential.scope = scope
472
- // 身份优先取 id_token(与 access_token 同一次响应自带,零额外请求),退到既有凭据。
473
- const identity = grant.id_token === undefined ? {} : identityFromIdToken(grant.id_token)
474
- const sub = identity.sub ?? previous.sub
475
- if (sub) credential.sub = sub
476
- const email = identity.email ?? previous.email
477
- if (email) credential.email = email
478
- if (previous.cloudaicompanionProject) credential.cloudaicompanionProject = previous.cloudaicompanionProject
479
- return credential
480
- }
481
-
482
- /**
483
- * POST 表单到 Google OAuth 端点。
484
- * ⚠️ 刻意不设 User-Agent:antigravity 伪装只用在 Cloud Code 的推理/配额端点,
485
- * 令牌与 userinfo 端点是标准 Google OAuth,加伪装反而多一个可疑特征。
486
- */
487
- async function postForm(endpoint, form, signal) {
488
- const response = await httpFetch(endpoint, {
489
- method: 'POST',
490
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
491
- body: new URLSearchParams(form).toString(),
492
- signal,
493
- }, OAUTH_TIMEOUT_MS)
494
- const text = await response.text().catch(() => '')
495
- let parsed
496
- try {
497
- parsed = JSON.parse(text)
498
- } catch {
499
- throw new Error(`令牌端点返回无法解析(HTTP ${response.status})`)
500
- }
501
- if (!response.ok) {
502
- const code = typeof parsed?.error === 'string' ? parsed.error : `HTTP ${response.status}`
503
- const description = typeof parsed?.error_description === 'string' ? parsed.error_description : ''
504
- throw new Error(description === '' ? code : `${code}: ${description}`)
505
- }
506
- return parsed
507
- }
508
-
509
- /** 拉账号身份(id_token 缺席时的兜底)。失败返回 {} 不抛错。 */
510
- async function fetchUserInfo(accessToken, signal) {
511
- try {
512
- const response = await httpFetch(USERINFO_ENDPOINT, {
513
- method: 'GET',
514
- headers: { Authorization: `Bearer ${accessToken}` },
515
- signal,
516
- }, OAUTH_TIMEOUT_MS)
517
- if (!response.ok) return {}
518
- const payload = await response.json().catch(() => null)
519
- if (payload === null || typeof payload !== 'object') return {}
520
- const out = {}
521
- if (typeof payload.id === 'string' && payload.id !== '') out.sub = payload.id
522
- if (typeof payload.email === 'string' && payload.email !== '') out.email = payload.email
523
- return out
524
- } catch {
525
- return {}
526
- }
527
- }
528
-
529
- // ── 登录(浏览器回调式 OAuth,先监听再拼 URL)───────────────────────────────
530
-
531
- /** 构造授权 URL(参数顺序无关紧要,Google 不校验)。 */
532
- function buildAuthUrl(state, redirectUri) {
533
- const query = new URLSearchParams({
534
- client_id: clientId(),
535
- response_type: 'code',
536
- redirect_uri: redirectUri,
537
- scope: SCOPES.join(' '),
538
- state,
539
- access_type: 'offline',
540
- include_granted_scopes: 'true',
541
- prompt: 'consent',
542
- })
543
- return `${AUTH_ENDPOINT}?${query.toString()}`
544
- }
545
-
546
- /** 先占一个空闲端口再释放 —— 让 v4/v6 两个监听器落在同一个端口上。 */
547
- function pickFreePort() {
548
- return new Promise((resolve, reject) => {
549
- const probe = createServer()
550
- probe.once('error', reject)
551
- probe.listen(0, '127.0.0.1', () => {
552
- const address = probe.address()
553
- const port = typeof address === 'object' && address !== null ? address.port : 0
554
- probe.close(() => {
555
- if (port > 0) resolve(port)
556
- else reject(new Error('无法分配回调端口'))
557
- })
558
- })
559
- })
560
- }
561
-
562
- /**
563
- * 在指定端口上同时监听 127.0.0.1 与 [::1]。
564
- * ⚠️ 必须两个都听:浏览器把 localhost 解析成 ::1 时只绑 v4 会「页面打不开」。
565
- * IPv6 监听失败可容忍;127.0.0.1 失败才是真失败。首选端口被占时换空闲端口重试
566
- * (**不能**先拼 URL,见文件头)。
567
- */
568
- function listenCallback(handler, preferredPort, servers) {
569
- const attempt = port => new Promise((resolve, reject) => {
570
- const primary = createServer(handler)
571
- servers.push(primary)
572
- primary.once('error', error => {
573
- if (error?.code === 'EADDRINUSE' && port !== 0) {
574
- pickFreePort().then(next => resolve(attempt(next)), reject)
575
- return
576
- }
577
- reject(error)
578
- })
579
- primary.listen(port, '127.0.0.1', () => {
580
- const address = primary.address()
581
- const assigned = typeof address === 'object' && address !== null ? address.port : 0
582
- const secondary = createServer(handler)
583
- servers.push(secondary)
584
- // IPv6 监听失败可容忍(localhost 解析到 v4 时仍然可用);首个错误用于降级,
585
- // 之后的错误静默吞掉(once 之外还要有常驻 handler,否则 uncaught exception)。
586
- let settled6 = false
587
- secondary.on('error', () => { if (!settled6) { settled6 = true; resolve(assigned) } })
588
- secondary.listen(assigned, '::1', () => { if (!settled6) { settled6 = true; resolve(assigned) } })
589
- })
590
- })
591
- return attempt(preferredPort)
592
- }
593
-
594
- /**
595
- * 启动浏览器回调式 OAuth 登录。两步式:服务器就绪后立即回填 loginUrl
596
- * (浏览器只在用户点击后的短暂窗口内允许 window.open,阻塞式流程会过期)。
597
- * 返回 `{ loginUrl: '', loginUrlReady, promise, cancel }`。
598
- */
599
- export function startLogin({ port } = {}) {
600
- const controller = new AbortController()
601
- const signal = controller.signal
602
- const state = randomBytes(16).toString('hex')
603
-
604
- let resolveCode = () => {}
605
- let rejectCode = () => {}
606
- const codePromise = new Promise((resolve, reject) => {
607
- resolveCode = resolve
608
- rejectCode = reject
609
- })
610
- const onAbort = () => rejectCode(new Error('登录已取消'))
611
- signal.addEventListener('abort', onAbort, { once: true })
612
-
613
- const servers = []
614
- let closed = false
615
- const closeServers = () => {
616
- if (closed) return
617
- closed = true
618
- for (const server of servers) {
619
- try { server.close(() => {}) } catch { /* 已关闭 */ }
620
- }
621
- }
622
-
623
- /** 回调处理器:state 必须校验(防伪造回调);error 参数 = 用户点了取消。 */
624
- const handler = (req, res) => {
625
- let url
626
- try { url = new URL(req.url ?? '/', `http://${REDIRECT_HOST}`) } catch { res.writeHead(400).end('Bad request'); return }
627
- if (url.pathname !== CALLBACK_PATH) {
628
- res.writeHead(404).end('Not found')
629
- return
630
- }
631
- const failure = url.searchParams.get('error')
632
- if (failure !== null && failure !== '') {
633
- const description = url.searchParams.get('error_description') ?? ''
634
- res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }).end(`授权被拒绝: ${failure}`)
635
- rejectCode(new Error(description === '' ? failure : `${failure}: ${description}`))
636
- return
637
- }
638
- if (url.searchParams.get('state') !== state) {
639
- res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }).end('state 校验失败')
640
- rejectCode(new Error('state 校验失败,可能是伪造的回调'))
641
- return
642
- }
643
- const code = url.searchParams.get('code')
644
- if (code === null || code === '') {
645
- res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }).end('缺少 authorization code')
646
- rejectCode(new Error('回调缺少 authorization code'))
647
- return
648
- }
649
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(CALLBACK_HTML)
650
- resolveCode(code)
651
- }
652
-
653
- let redirectUri = ''
654
- const loginUrlReady = (async () => {
655
- // ⚠️ 先监听、再拼 URL:端口被占回退别的端口,先拼 URL 就 redirect_uri_mismatch。
656
- const assigned = await listenCallback(handler, Number(port) || 0, servers)
657
- redirectUri = `http://${REDIRECT_HOST}:${assigned}${CALLBACK_PATH}`
658
- return buildAuthUrl(state, redirectUri)
659
- })()
660
-
661
- const promise = (async () => {
662
- await loginUrlReady
663
- const code = await Promise.race([
664
- codePromise,
665
- new Promise((_, reject) => {
666
- const timer = setTimeout(() => reject(new Error('Google 授权超时,请重新发起')), AUTH_FLOW_TIMEOUT_MS)
667
- timer.unref?.()
668
- }),
669
- ])
670
- // ⚠️ token 端点强制校验客户端身份:只发 client_id 会回
671
- // invalid_request: client_secret is missing(症状是「浏览器显示授权成功,
672
- // 但面板里账号一直不出现」)。
673
- const payload = await postForm(TOKEN_ENDPOINT, {
674
- client_id: clientId(),
675
- client_secret: clientSecret(),
676
- code,
677
- grant_type: 'authorization_code',
678
- redirect_uri: redirectUri,
679
- }, signal)
680
- const grant = parseTokenGrant(payload)
681
- const credential = credentialFromGrant(grant)
682
- if (credential.sub !== undefined && credential.email !== undefined) return credential
683
- // 兜底:id_token 缺席或解不出身份时才补一次 userinfo(失败不阻塞登录)。
684
- const user = await fetchUserInfo(credential.access_token, signal)
685
- if (credential.sub === undefined && user.sub !== undefined) credential.sub = user.sub
686
- if (credential.email === undefined && user.email !== undefined) credential.email = user.email
687
- return credential
688
- })()
689
- // 结果可能早于调用方 await 而落定:挂处理器避免「未处理的拒绝」告警,
690
- // 错误仍会传给真正的消费者;无论成败都关闭回调服务器(用完即关)。
691
- promise.then(closeServers, closeServers)
692
-
693
- return {
694
- loginUrl: '',
695
- loginUrlReady,
696
- promise,
697
- cancel: () => {
698
- try { controller.abort() } catch { /* 已取消 */ }
699
- },
700
- }
701
- }
702
-
703
- // ── 续期(refresh_token grant;终态判据只看令牌端点的 error 码)──────────────
704
-
705
- /** 令牌端点的 error 码命中即终态(文案正则一致)。 */
706
- const TERMINAL_REFRESH_PATTERN = /invalid_grant|invalid_client|expired|revoked|unauthorized/i
707
-
708
- export async function refreshCredential(credential) {
709
- const refreshToken = credential?.refresh_token
710
- if (typeof refreshToken !== 'string' || refreshToken === '') {
711
- throw { kind: 'auth', retryable: false, terminal: true, message: 'Gemini 凭据缺少 refresh_token,请重新登录' }
712
- }
713
- let response
714
- try {
715
- response = await httpFetch(TOKEN_ENDPOINT, {
716
- method: 'POST',
717
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
718
- body: new URLSearchParams({
719
- client_id: clientId(),
720
- client_secret: clientSecret(),
721
- refresh_token: refreshToken,
722
- grant_type: 'refresh_token',
723
- }).toString(),
724
- }, OAUTH_TIMEOUT_MS)
725
- } catch (error) {
726
- // ⚠️ 传输层失败不能判终态 —— TLS 的 CERT_HAS_EXPIRED 文案也含 "expired",
727
- // 网络抖动不该让用户重新登录(ChannelNetworkError 豁免)。
728
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期网络失败:${error?.message ?? error}` }
729
- }
730
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
731
- let parsed
732
- try {
733
- parsed = JSON.parse(text)
734
- } catch {
735
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期响应不是 JSON(HTTP ${response.status})` }
736
- }
737
- const errorCode = typeof parsed?.error === 'string' ? parsed.error : ''
738
- if (errorCode !== '' || !response.ok) {
739
- const description = typeof parsed?.error_description === 'string' ? parsed.error_description : ''
740
- // ⚠️ 判终态只看令牌端点的 error 码,不看网络错误文案。
741
- if (TERMINAL_REFRESH_PATTERN.test(`${errorCode} ${description}`)) {
742
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Gemini refresh_token 已失效(${errorCode || `HTTP ${response.status}`}),请重新登录` }
743
- }
744
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期失败(HTTP ${response.status}):${(description || errorCode || text).slice(0, 200)}` }
745
- }
746
- let grant
747
- try {
748
- grant = parseTokenGrant(parsed, refreshToken)
749
- } catch (error) {
750
- const message = String(error?.message ?? error)
751
- if (TERMINAL_REFRESH_PATTERN.test(message)) {
752
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'Gemini refresh_token 已失效,请重新登录' }
753
- }
754
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期失败:${message}` }
755
- }
756
- // credentialFromGrant 保留 sub/email/cloudaicompanionProject,并在 Google
757
- // 轮换 refresh_token 时回写新值(否则下次续期用的是已作废的旧值)。
758
- return credentialFromGrant(grant, credential)
759
- }
760
-
761
- // ── 模型清单(静态表:无远端目录端点,本表即权威清单)───────────────────────
762
- // credential 被故意不读取:无论传 null/undefined/有效凭据,返回完全一致的本地清单,
763
- // 所以模型清单无需任何账号凭据即可获得(零网络请求)。上游不提供公开模型列表端点。
764
-
765
- export async function fetchModels() {
766
- return fallbackModels.map(entry => ({
767
- id: entry.id,
768
- name: entry.name,
769
- contextWindow: entry.contextWindow,
770
- maxTokens: entry.maxTokens,
771
- supportsImage: entry.supportsImage === true || undefined,
772
- efforts: entry.efforts,
773
- defaultEffort: entry.defaultEffort,
774
- }))
775
- }
776
-
777
- // ── thoughtSignature 缓存(最小:仅内存)───────────────────────────────────────
778
- // 键 = sha256("tool:"+name+"\0"+args[:512])[:16];
779
- // 换算法会让已有缓存全部失配(表现为每轮都去签重试)。
780
-
781
- function sigKey(role, text) {
782
- const body = text.length > SIG_KEY_BODY_LIMIT ? text.slice(0, SIG_KEY_BODY_LIMIT) : text
783
- return createHash('sha256').update(`${role}\u0000${body}`, 'utf8').digest('hex').slice(0, 16)
784
- }
785
-
786
- function toolSigKey(name, argsJson) {
787
- return sigKey(`tool:${name}`, argsJson)
788
- }
789
-
790
- const sigEntries = new Map()
791
-
792
- function sigGet(name, argsJson) {
793
- const entry = sigEntries.get(toolSigKey(name, argsJson))
794
- return entry && entry.sig !== '' ? entry.sig : undefined
795
- }
796
-
797
- /** 精确键 miss 时的兜底:取该工具名最近一次签名(长任务参数漂移是必然事件)。 */
798
- function sigLatestForTool(name) {
799
- let best
800
- for (const entry of sigEntries.values()) {
801
- if (entry.name === name && entry.sig !== '') best = entry.sig
802
- }
803
- return best
804
- }
805
-
806
- /** 记签名;空键/空签名一律丢弃(上游偶尔下发空串占位)。 */
807
- function sigPut(name, argsJson, signature) {
808
- const trimmed = String(signature ?? '').trim()
809
- if (trimmed === '') return
810
- const key = toolSigKey(name, argsJson)
811
- if (key === '') return
812
- sigEntries.set(key, { sig: trimmed, name })
813
- if (sigEntries.size > SIG_MAX_ENTRIES) {
814
- // 淘汰最旧的一半(Map 保插入序,删前半即最旧的一半)。
815
- const keys = [...sigEntries.keys()]
816
- for (let i = 0; i < Math.floor(keys.length / 2); i++) sigEntries.delete(keys[i])
817
- }
818
- }
819
-
820
- // ── project 三级缓存 ────────────────────────────────────────────────────────────────
821
-
822
- /** 进程内缓存(键 = email/sub/access_token;用 access_token 兜底,续期后失效只是多探一次)。 */
823
- const projectCache = new Map()
824
-
825
- /**
826
- * 从 loadCodeAssist 响应取项目号:顶层 cloudaicompanionProject →
827
- * currentTier.cloudaicompanionProject(取值顺序)。
828
- */
829
- function parseProject(payload) {
830
- if (payload === null || typeof payload !== 'object') return ''
831
- const top = payload.cloudaicompanionProject
832
- if (typeof top === 'string' && top !== '') return top
833
- const tier = payload.currentTier
834
- if (tier !== null && typeof tier === 'object') {
835
- const inner = tier.cloudaicompanionProject
836
- if (typeof inner === 'string' && inner !== '') return inner
837
- }
838
- return ''
839
- }
840
-
841
- function probeHeaders(credential) {
842
- return {
843
- Authorization: `Bearer ${credential.access_token}`,
844
- 'Content-Type': 'application/json',
845
- ...IDENTITY_HEADERS,
846
- }
847
- }
848
-
849
- /**
850
- * 解析当前凭据可用的项目号。探测失败返回 error —— 调用方**不发推理**
851
- * (实测:注入 500 后只在端点间重试 LCA,不发 streamGenerateContent)。
852
- */
853
- async function resolveProject(credential) {
854
- const identity = readStringField(credential, 'email') || readStringField(credential, 'sub') || credential.access_token
855
-
856
- const cached = projectCache.get(identity)
857
- if (cached) return { project: cached }
858
-
859
- // 二级:凭据字段(跨启动的落盘缓存)
860
- const fromCredential = typeof credential.cloudaicompanionProject === 'string' ? credential.cloudaicompanionProject : ''
861
- if (fromCredential !== '') {
862
- projectCache.set(identity, fromCredential)
863
- return { project: fromCredential }
864
- }
865
-
866
- // 三级:现探
867
- let lastError = ''
868
- for (const endpoint of PROBE_ENDPOINTS) {
869
- try {
870
- const response = await httpFetch(`${endpoint}${LOAD_CODE_ASSIST_PATH}`, {
871
- method: 'POST',
872
- headers: probeHeaders(credential),
873
- body: LOAD_CODE_ASSIST_BODY,
874
- }, PROBE_TIMEOUT_MS)
875
- if (!response.ok) {
876
- lastError = `loadCodeAssist HTTP ${response.status}`
877
- continue
878
- }
879
- const text = await response.text().catch(() => '')
880
- if (text === '') {
881
- lastError = 'loadCodeAssist 返回空响应'
882
- continue
883
- }
884
- const project = parseProject(JSON.parse(text))
885
- if (project !== '') {
886
- projectCache.set(identity, project)
887
- return { project }
888
- }
889
- // ⚠️ 探测成功但项目号为空 = 免费档常态,不是失败 —— 回落兜底串照常发推理。
890
- return { project: DEFAULT_PROJECT }
891
- } catch (error) {
892
- lastError = error instanceof Error ? error.message : String(error)
893
- }
894
- }
895
- return { project: '', error: lastError === '' ? 'loadCodeAssist 探测失败' : lastError }
896
- }
897
-
898
- /** 消息转换(请求方向)。 */
899
-
900
- /** 工具参数 JSON 解析;失败/非对象退化为 {}(不编造参数)。 */
901
- function parseToolArguments(raw) {
902
- const text = String(raw ?? '').trim()
903
- if (text === '') return {}
904
- try {
905
- const parsed = JSON.parse(text)
906
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
907
- } catch {
908
- return {}
909
- }
910
- }
911
-
912
- /** content 归一化为字符串(system/tool 结果用)。数组只拼 text 块。 */
913
- function contentText(content) {
914
- if (typeof content === 'string') return content
915
- if (Array.isArray(content)) {
916
- return content
917
- .filter(block => block !== null && typeof block === 'object' && block.type === 'text')
918
- .map(block => String(block.text ?? ''))
919
- .join('\n')
920
- }
921
- return ''
922
- }
923
-
924
- /** 校验 base64 可用(先宽松清洗换行/空格再判 —— 上游接受带换行的 base64)。 */
925
- function normalizeBase64(data) {
926
- if (data === '') return undefined
927
- const cleaned = data.replace(/[\n\r\s]/g, '')
928
- if (cleaned === '') return undefined
929
- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(cleaned)) return undefined
930
- if (cleaned.length % 4 !== 0) return undefined
931
- return cleaned
932
- }
933
-
934
- /** 内联一张图片:data: URL 直接解;http(s) 拉取转 base64。失败显式抛错不静默丢图。 */
935
- async function resolveInlineImage(url) {
936
- if (typeof url !== 'string' || url === '') {
937
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片地址为空,拒绝发出缺少图片的请求' }
938
- }
939
- if (url.startsWith('data:')) {
940
- const comma = url.indexOf(',')
941
- if (comma < 0) throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: data URL 图片格式非法' }
942
- const header = url.slice(5, comma)
943
- const raw = url.slice(comma + 1)
944
- const mimeMatch = /^([^;,]+)/.exec(header)
945
- const mimeType = mimeMatch?.[1] && mimeMatch[1] !== '' ? mimeMatch[1] : 'image/png'
946
- let payload = raw
947
- try { payload = decodeURIComponent(raw) } catch { /* 已是裸 base64 */ }
948
- const data = normalizeBase64(payload)
949
- if (data === undefined) throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片编码不是合法 base64' }
950
- if (data.length * 3 / 4 > MAX_IMAGE_BYTES_INLINE) {
951
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 图片体积超过上游内联上限 ${MAX_IMAGE_BYTES_INLINE} 字节` }
952
- }
953
- return { mimeType, data }
954
- }
955
- if (url.startsWith('http://') || url.startsWith('https://')) {
956
- const response = await httpFetch(url, { method: 'GET' }, 20_000).catch(() => null)
957
- if (response === null || !response.ok) {
958
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片下载失败,拒绝发出缺少图片的请求' }
959
- }
960
- const declared = (response.headers?.get?.('content-type') ?? '').split(';')[0].trim()
961
- const mimeType = declared.startsWith('image/') ? declared : 'image/png'
962
- const buffer = Buffer.from(await response.arrayBuffer())
963
- if (buffer.byteLength > MAX_IMAGE_BYTES_INLINE) {
964
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 图片体积 ${buffer.byteLength} 字节超过上游内联上限 ${MAX_IMAGE_BYTES_INLINE} 字节` }
965
- }
966
- const data = normalizeBase64(buffer.toString('base64'))
967
- if (data === undefined) throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片编码不是合法 base64' }
968
- return { mimeType, data }
969
- }
970
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 不支持的图片地址协议,拒绝发出缺少图片的请求` }
971
- }
972
-
973
- /** 把 OpenAI content 的文本/图片块追加进 parts(图片显式抛错,绝不静默丢图)。 */
974
- async function pushContentParts(parts, content) {
975
- if (typeof content === 'string') {
976
- if (content !== '') parts.push({ text: content })
977
- return
978
- }
979
- if (!Array.isArray(content)) return
980
- for (const block of content) {
981
- if (block === null || typeof block !== 'object') continue
982
- if (block.type === 'text') {
983
- const text = typeof block.text === 'string' ? block.text : ''
984
- if (text !== '') parts.push({ text })
985
- continue
986
- }
987
- if (block.type === 'image_url') {
988
- const url = block.image_url?.url
989
- if (typeof url !== 'string' || url === '') continue
990
- const inline = await resolveInlineImage(url)
991
- parts.push({ inlineData: { mimeType: inline.mimeType, data: inline.data } })
992
- }
993
- }
994
- }
995
-
996
- /**
997
- * 把 OpenAI wire 消息转成 Gemini contents + systemInstruction。
998
- * ⚠️ role 只有 user/model;system 单独承载进 systemInstruction(真把 system 当
999
- * user 发会让模型把它当用户指令)。
1000
- * ⚠️ tool_call/result 配对:一批 tool_calls 只有全部拿到结果才保留(部分保留会
1001
- * 留下无结果的 tool_call,上游照样拒绝);functionResponse 以 name 配对,空 name
1002
- * 整块丢弃(丢了顶多少一轮工具上下文,不会打死整轮)。
1003
- */
1004
- async function buildContents(messages) {
1005
- const systemParts = []
1006
- const toolNames = new Map()
1007
- const resultIds = new Set()
1008
- for (const message of messages) {
1009
- if (message === null || typeof message !== 'object') continue
1010
- if (message.role === 'assistant' && Array.isArray(message.tool_calls)) {
1011
- for (const call of message.tool_calls) {
1012
- const id = typeof call?.id === 'string' ? call.id : ''
1013
- const name = typeof call?.function?.name === 'string' ? call.function.name.trim() : ''
1014
- if (id !== '') toolNames.set(id, name)
1015
- }
1016
- }
1017
- if (message.role === 'tool' && typeof message.tool_call_id === 'string') resultIds.add(message.tool_call_id)
1018
- }
1019
- const keepCallIds = new Set()
1020
- for (const message of messages) {
1021
- if (message === null || typeof message !== 'object' || message.role !== 'assistant' || !Array.isArray(message.tool_calls)) continue
1022
- const usable = message.tool_calls.filter(call => call !== null && typeof call === 'object' && typeof call.function?.name === 'string' && call.function.name.trim() !== '')
1023
- if (usable.length === 0) continue
1024
- if (usable.every(call => resultIds.has(String(call.id)))) {
1025
- for (const call of usable) keepCallIds.add(String(call.id))
1026
- }
1027
- }
1028
- const keepResultIds = new Set([...keepCallIds].filter(id => resultIds.has(id)))
1029
-
1030
- const contents = []
1031
- for (const message of messages) {
1032
- if (message === null || typeof message !== 'object' || typeof message.role !== 'string') continue
1033
- // system/developer 由 systemInstruction 单独承载,显式跳过。
1034
- if (message.role === 'system' || message.role === 'developer') {
1035
- const text = contentText(message.content)
1036
- if (text !== '') systemParts.push(text)
1037
- continue
1038
- }
1039
- const role = message.role === 'assistant' ? 'model' : 'user'
1040
- const parts = []
1041
- if (message.role === 'tool') {
1042
- const id = typeof message.tool_call_id === 'string' ? message.tool_call_id : ''
1043
- if (keepResultIds.has(id)) {
1044
- const name = toolNames.get(id) ?? ''
1045
- if (name !== '') parts.push({ functionResponse: { name, response: { content: contentText(message.content) } } })
1046
- }
1047
- } else {
1048
- await pushContentParts(parts, message.content)
1049
- if (Array.isArray(message.tool_calls)) {
1050
- for (const call of message.tool_calls) {
1051
- const id = String(call?.id ?? '')
1052
- const name = typeof call?.function?.name === 'string' ? call.function.name.trim() : ''
1053
- if (!keepCallIds.has(id) || name === '') continue
1054
- const args = parseToolArguments(call.function?.arguments)
1055
- const argsJson = canonicalArgs(args)
1056
- const part = { functionCall: { name, args } }
1057
- // 签名从本地缓存查(OpenAI 消息不携带签名);查不到就不带签名发,
1058
- // 上游拒时走「去签重试一次」路径。
1059
- const signature = sigGet(name, argsJson) ?? sigLatestForTool(name)
1060
- if (signature !== undefined && signature !== '') part.thoughtSignature = signature
1061
- parts.push(part)
1062
- }
1063
- }
1064
- }
1065
- if (parts.length === 0) continue
1066
- contents.push({ role, parts })
1067
- }
1068
- return { contents, systemText: systemParts.join('\n\n') }
1069
- }
1070
-
1071
- /** 取首条 user 消息的首个文本 part(sessionId 派生的输入之一)。 */
1072
- function firstUserText(contents) {
1073
- for (const content of contents) {
1074
- if (content.role !== '' && content.role !== 'user') continue
1075
- for (const part of content.parts) {
1076
- if (typeof part.text === 'string' && part.text !== '') return part.text
1077
- }
1078
- }
1079
- return ''
1080
- }
1081
-
1082
- // ── JSON Schema 清洗(逐条规则)───────────────────────────────────────────────
1083
-
1084
- /** Gemini FunctionDeclaration.parameters 接受的键白名单(白名单外的键是硬 400)。 */
1085
- const SCHEMA_KEYS = new Set([
1086
- 'type', 'format', 'description', 'nullable', 'enum', 'items', 'minItems', 'maxItems',
1087
- 'properties', 'required', 'minProperties', 'maxProperties', 'minLength', 'maxLength',
1088
- 'pattern', 'anyOf', 'propertyOrdering', 'minimum', 'maximum',
1089
- ])
1090
-
1091
- function sanitizeGeminiSchema(schema) {
1092
- if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) return {}
1093
- const out = {}
1094
- for (const [key, value] of Object.entries(schema)) {
1095
- if (!SCHEMA_KEYS.has(key)) continue
1096
- if (key === 'properties') {
1097
- if (value === null || typeof value !== 'object' || Array.isArray(value)) continue
1098
- const properties = {}
1099
- for (const [name, child] of Object.entries(value)) {
1100
- if (child === null || typeof child !== 'object' || Array.isArray(child)) continue
1101
- properties[name] = sanitizeGeminiSchema(child)
1102
- }
1103
- out.properties = properties
1104
- continue
1105
- }
1106
- if (key === 'items') {
1107
- if (Array.isArray(value)) {
1108
- out.items = value
1109
- .filter(item => item !== null && typeof item === 'object' && !Array.isArray(item))
1110
- .map(item => sanitizeGeminiSchema(item))
1111
- continue
1112
- }
1113
- if (value !== null && typeof value === 'object') out.items = sanitizeGeminiSchema(value)
1114
- continue
1115
- }
1116
- if (key === 'anyOf') {
1117
- if (!Array.isArray(value)) continue
1118
- out.anyOf = value
1119
- .filter(item => item !== null && typeof item === 'object' && !Array.isArray(item))
1120
- .map(item => sanitizeGeminiSchema(item))
1121
- continue
1122
- }
1123
- if (key === 'type') {
1124
- if (typeof value === 'string') { out.type = value; continue }
1125
- if (Array.isArray(value)) {
1126
- const types = value.filter(item => typeof item === 'string')
1127
- const nonNull = types.filter(item => item !== 'null')
1128
- if (nonNull.length > 0) out.type = nonNull[0]
1129
- // 出现 'null' ⇒ 该字段可空,用 nullable 表达。
1130
- if (nonNull.length !== types.length) out.nullable = true
1131
- }
1132
- continue
1133
- }
1134
- if (key === 'enum') {
1135
- // enum 只要含任何非字符串值就整删(Gemini 只接受字符串枚举)。
1136
- if (Array.isArray(value) && value.every(item => typeof item === 'string')) out.enum = [...value]
1137
- continue
1138
- }
1139
- out[key] = value
1140
- }
1141
- return out
1142
- }
1143
-
1144
- /** 工具定义 → functionDeclarations(schema 清洗后下发)。 */
1145
- function buildTools(tools) {
1146
- if (!Array.isArray(tools)) return undefined
1147
- const declarations = []
1148
- for (const tool of tools) {
1149
- const fn = tool?.function
1150
- if (fn === null || typeof fn !== 'object' || typeof fn.name !== 'string' || fn.name.trim() === '') continue
1151
- declarations.push({
1152
- name: fn.name,
1153
- ...(typeof fn.description === 'string' && fn.description !== '' ? { description: fn.description } : {}),
1154
- parameters: sanitizeGeminiSchema(fn.parameters !== null && typeof fn.parameters === 'object' && !Array.isArray(fn.parameters) ? fn.parameters : {}),
1155
- })
1156
- }
1157
- return declarations.length > 0 ? [{ functionDeclarations: declarations }] : undefined
1158
- }
1159
-
1160
- /** tool_choice → toolConfig.functionCallingConfig(OpenAI 形态 + 别名)。 */
1161
- function buildToolConfig(toolChoice, hasTools) {
1162
- if (!hasTools) return undefined
1163
- let mode = 'AUTO'
1164
- let name
1165
- if (toolChoice === 'none') mode = 'NONE'
1166
- else if (toolChoice === 'any' || toolChoice === 'required') mode = 'ANY'
1167
- else if (toolChoice !== null && typeof toolChoice === 'object') {
1168
- const type = toolChoice.type
1169
- if (type === 'none') mode = 'NONE'
1170
- else if (type === 'any' || type === 'tool' || type === 'function') mode = 'ANY'
1171
- const rawName = typeof toolChoice.name === 'string' && toolChoice.name !== '' ? toolChoice.name
1172
- : typeof toolChoice.function?.name === 'string' && toolChoice.function.name !== '' ? toolChoice.function.name
1173
- : typeof toolChoice.tool?.name === 'string' && toolChoice.tool.name !== '' ? toolChoice.tool.name
1174
- : undefined
1175
- name = rawName
1176
- }
1177
- return { functionCallingConfig: { mode, ...(mode === 'ANY' && name !== undefined ? { allowedFunctionNames: [name] } : {}) } }
1178
- }
1179
-
1180
- // ── 响应翻译(Gemini 帧 → OpenAI chunk)─────────────────────────────────────
1181
-
1182
- /** usageMetadata → OpenAI usage(thoughts 是 output 子集,并入 completion_tokens)。 */
1183
- function readUsage(raw) {
1184
- if (raw === null || typeof raw !== 'object') return undefined
1185
- const prompt = nonNegativeInt(raw.promptTokenCount)
1186
- const candidates = nonNegativeInt(raw.candidatesTokenCount)
1187
- const thoughts = nonNegativeInt(raw.thoughtsTokenCount)
1188
- const total = nonNegativeInt(raw.totalTokenCount)
1189
- const cached = nonNegativeInt(raw.cachedContentTokenCount) ?? 0
1190
- if (prompt === undefined && candidates === undefined && total === undefined) return undefined
1191
- const out = {}
1192
- if (prompt !== undefined) out.prompt_tokens = prompt
1193
- if (candidates !== undefined || thoughts !== undefined) out.completion_tokens = (candidates ?? 0) + (thoughts ?? 0)
1194
- if (total !== undefined) out.total_tokens = total
1195
- if (cached > 0) out.prompt_tokens_details = { cached_tokens: cached }
1196
- return out
1197
- }
1198
-
1199
- /** 上游 finishReason → OpenAI finish_reason。未知/缺失一律 stop(不编造成 error)。 */
1200
- function mapFinishReason(reason, toolCount) {
1201
- if (toolCount > 0) return 'tool_calls'
1202
- const text = typeof reason === 'string' ? reason.toUpperCase() : ''
1203
- if (text === 'MAX_TOKENS') return 'length'
1204
- return 'stop'
1205
- }
1206
-
1207
- // ── SSE 消费(关键语义)───────────────────────────────────────────────────────────
1208
-
1209
- /** 读一块数据,带空闲超时与取消信号(裸 reader.read() 会无限期挂起)。 */
1210
- function readChunk(reader, timeoutMs, signal) {
1211
- return new Promise((resolve, reject) => {
1212
- let settled = false
1213
- const timer = setTimeout(() => finish(new Error('idle')), timeoutMs)
1214
- const onAbort = () => finish(new Error('abort'))
1215
- signal?.addEventListener('abort', onAbort, { once: true })
1216
- function finish(error) {
1217
- if (settled) return
1218
- settled = true
1219
- clearTimeout(timer)
1220
- signal?.removeEventListener('abort', onAbort)
1221
- reject(error)
1222
- }
1223
- reader.read().then(
1224
- value => {
1225
- if (settled) return
1226
- settled = true
1227
- clearTimeout(timer)
1228
- signal?.removeEventListener('abort', onAbort)
1229
- resolve(value)
1230
- },
1231
- error => finish(error),
1232
- )
1233
- })
1234
- }
1235
-
1236
- /** 处理一行 SSE,返回 data: 载荷。`:` 注释行 / event: 行跳过;单行 data(实测)。 */
1237
- function ssePayload(rawLine) {
1238
- const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
1239
- if (line === '' || line.startsWith(':') || line.startsWith('event:')) return undefined
1240
- if (!line.startsWith('data:')) return undefined
1241
- return line.slice(5).trim()
1242
- }
1243
-
1244
- /**
1245
- * 消费上游 SSE,把每个内容帧翻译成 OpenAI chunk 文本帧。
1246
- * ⚠️ 只有 candidates 非空才算内容帧(纯 usageMetadata 收尾帧继续读);
1247
- * ⚠️ 收尾余量必须按整行再走一遍(否则末帧 finishReason/usage 被静默丢弃);
1248
- * ⚠️ 用量取「见过的最大 totalTokenCount」那一份(上游多帧重复播报,早期帧偏小)。
1249
- */
1250
- async function consumeStream(body, emit, signal, idleTimeoutMs) {
1251
- const reader = body.getReader()
1252
- const decoder = new TextDecoder()
1253
- let buffer = ''
1254
- let sawContent = false
1255
- let finishReason
1256
- let toolCount = 0
1257
- let usage
1258
- let usageTotal = -1
1259
-
1260
- const noteUsage = raw => {
1261
- if (raw === null || typeof raw !== 'object') return
1262
- const total = nonNegativeInt(raw.totalTokenCount) ?? -1
1263
- if (total < usageTotal) return
1264
- usageTotal = total
1265
- usage = readUsage(raw)
1266
- }
1267
-
1268
- try {
1269
- for (;;) {
1270
- let chunk
1271
- try {
1272
- chunk = await readChunk(reader, sawContent ? idleTimeoutMs : IDLE_TIMEOUT_MS, signal)
1273
- } catch (error) {
1274
- if (signal?.aborted) throw Object.assign(new Error('已取消'), { name: 'AbortError' })
1275
- if (error instanceof Error && error.message === 'idle') {
1276
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Gemini 流空闲超时(上游长时间未输出)' }
1277
- }
1278
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Gemini 流读取失败:${error?.message ?? error}` }
1279
- }
1280
- if (chunk.done) {
1281
- // ⚠️ 收尾:先刷解码器残留,再把 buffer 余量按整行走一遍。
1282
- buffer += decoder.decode()
1283
- const tail = buffer.split('\n')
1284
- buffer = ''
1285
- for (const rawLine of tail) {
1286
- const payload = ssePayload(rawLine)
1287
- if (payload !== undefined) processFrame(payload)
1288
- }
1289
- break
1290
- }
1291
- buffer += decoder.decode(chunk.value, { stream: true })
1292
- const lines = buffer.split('\n')
1293
- buffer = lines.pop() ?? ''
1294
- for (const rawLine of lines) {
1295
- const payload = ssePayload(rawLine)
1296
- if (payload !== undefined) processFrame(payload)
1297
- }
1298
- }
1299
- } finally {
1300
- reader.cancel().catch(() => {})
1301
- }
1302
-
1303
- function processFrame(payload) {
1304
- if (payload === '' || payload === '[DONE]') return
1305
- let parsed
1306
- try { parsed = JSON.parse(payload) } catch { return }
1307
- if (parsed === null || typeof parsed !== 'object') return
1308
- // 先试信封形态 {"response":{…}},再试裸 Response(同序)。
1309
- const inner = parsed.response !== null && typeof parsed.response === 'object' ? parsed.response : parsed
1310
- const candidates = inner.candidates
1311
- noteUsage(inner.usageMetadata)
1312
- if (!Array.isArray(candidates) || candidates.length === 0) return
1313
- const candidate = candidates[0]
1314
- if (typeof candidate?.finishReason === 'string' && candidate.finishReason !== '') finishReason = candidate.finishReason
1315
- for (const part of candidate.content?.parts ?? []) {
1316
- if (part === null || typeof part !== 'object') continue
1317
- if (part.functionCall !== undefined && part.functionCall !== null) {
1318
- const name = typeof part.functionCall.name === 'string' ? part.functionCall.name : ''
1319
- const args = part.functionCall.args ?? {}
1320
- const argsJson = canonicalArgs(args)
1321
- // ⚠️ 只存 functionCall 上的签名:Gemini 校验的只有这一个,思考分片上的
1322
- // 签名回传会被忽略,存了纯属噪音。
1323
- if (typeof part.thoughtSignature === 'string' && part.thoughtSignature !== '') {
1324
- sigPut(name, argsJson, part.thoughtSignature)
1325
- }
1326
- const id = `gemini_tool_${Date.now().toString(36)}_${toolCount}`
1327
- toolCount += 1
1328
- sawContent = true
1329
- emit({
1330
- choices: [{
1331
- index: 0,
1332
- delta: { tool_calls: [{ index: toolCount - 1, id, type: 'function', function: { name, arguments: argsJson } }] },
1333
- finish_reason: null,
1334
- }],
1335
- })
1336
- continue
1337
- }
1338
- if (typeof part.text !== 'string' || part.text === '') continue
1339
- if (part.thought === true) {
1340
- sawContent = true
1341
- emit({ choices: [{ index: 0, delta: { reasoning_content: part.text }, finish_reason: null }] })
1342
- continue
1343
- }
1344
- sawContent = true
1345
- emit({ choices: [{ index: 0, delta: { content: part.text }, finish_reason: null }] })
1346
- }
1347
- }
1348
-
1349
- return { sawContent, finishReason, toolCount, usage }
1350
- }
1351
-
1352
- // ── 对话主流程(换端点 / 去签重试 / 会话升代 / 错误分类)────────────────────
1353
-
1354
- /** HTTP 失败 → OMR 错误对象(归类顺序)。 */
1355
- function failureFrom(status, bodyText) {
1356
- const message = extractMessage(bodyText) || `Gemini HTTP ${status}`
1357
- // ⚠️ 上下文超限必须先于 quota 文案判定:超限报文里的 "exceeded" 会被 quota
1358
- // 关键词吃掉去换号 —— 那是完全无效的动作(归错码的代价不对称)。
1359
- if (status === 400 && TOKEN_COUNT_OVERFLOW.test(String(bodyText ?? ''))) {
1360
- return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `Gemini 上下文超限:${message}` }
1361
- }
1362
- if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: RATE_LIMIT_COOLDOWN_MS, rotate: true, message }
1363
- if (status === 400 && hasMarker(bodyText, QUOTA_MARKERS)) {
1364
- return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
1365
- }
1366
- // ⚠️ 403/404 归 server 不归 auth:这两个码在 Cloud Code 上更多是「入口/模型
1367
- // 注册表不认」,归成 auth 会把用户引向「去重新登录」这个无效动作。
1368
- if (status === 403 || status === 404) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1369
- if (status === 401) return { kind: 'auth', retryable: false, cooldownMs: AUTH_COOLDOWN_MS, rotate: true, message }
1370
- if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1371
- if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
1372
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1373
- }
1374
-
1375
- /** 会话升代计数:按 base sessionId(不含代数)计,进程内持久(服务端按会话累计)。 */
1376
- const sessionBumps = new Map()
1377
-
1378
- /**
1379
- * 单账号一轮对话。上游恒走流式端点,本地聚合为完整 OpenAI 响应返回
1380
- * { status, json };onData 存在时逐帧发 OpenAI chunk JSON 文本。
1381
- * 调用方(providers/index.js)负责续期与换号 —— 这里只做端点轮换、去签重试、
1382
- * 会话升代三类协议内救场,并如实分类错误。
1383
- */
1384
- export async function complete(credential, body, { signal, onData, headerTimeoutMs = REQUEST_TIMEOUT_MS } = {}) {
1385
- if (!credential || typeof credential.access_token !== 'string' || credential.access_token === '') {
1386
- throw { kind: 'auth', retryable: false, terminal: true, message: 'Gemini 凭据缺少访问令牌,请重新登录' }
1387
- }
1388
- const requestedModel = typeof body.model === 'string' ? body.model : ''
1389
- // ⚠️ 模型名先查表再取凭据:未知 id 立即拒绝(上游对未知模型名静默接受并落回
1390
- // 3.8,用户选错模型时拿到错误答案且无任何征兆)。
1391
- const spec = modelSpec(requestedModel, body.reasoning_effort)
1392
- const headers = {
1393
- Authorization: `Bearer ${credential.access_token}`,
1394
- 'Content-Type': 'application/json',
1395
- ...IDENTITY_HEADERS,
1396
- // ⚠️ 流式请求刻意不带 Accept(与实际请求一致);也不注入 x-goog-api-key。
1397
- }
1398
-
1399
- const messages = Array.isArray(body.messages) ? body.messages : []
1400
- const { contents, systemText } = await buildContents(messages)
1401
- // ⚠️ 空 contents 必须抛错:发空请求上游会 400,且错误信息与真实原因毫不相干。
1402
- if (contents.length === 0) {
1403
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: messages 里没有可用内容' }
1404
- }
1405
- const tools = buildTools(body.tools)
1406
- const toolConfig = buildToolConfig(body.tool_choice, tools !== undefined)
1407
-
1408
- // project 必须按当前凭据解析;探测失败不发推理。
1409
- const probe = await resolveProject(credential)
1410
- if (probe.error !== undefined) {
1411
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `gemini: 项目号探测失败,未发推理 — ${probe.error}` }
1412
- }
1413
- const project = probe.project
1414
- const firstText = firstUserText(contents)
1415
-
1416
- const generationConfig = {
1417
- maxOutputTokens: typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0
1418
- ? Math.floor(body.max_tokens)
1419
- : MAX_OUTPUT_TOKENS,
1420
- // ⚠️ includeThoughts 恒 true(「关闭思考」是假关:关掉照样思考照样计费)。
1421
- thinkingConfig: { includeThoughts: true, ...(spec.thinkingBudget >= 0 ? { thinkingBudget: spec.thinkingBudget } : {}) },
1422
- ...(typeof body.temperature === 'number' && Number.isFinite(body.temperature) ? { temperature: body.temperature } : {}),
1423
- }
1424
-
1425
- const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
1426
- const created = Math.floor(Date.now() / 1000)
1427
-
1428
- let endpointIdx = 0
1429
- let endpointSwitched = false
1430
- let droppedSignatures = false
1431
-
1432
- for (;;) {
1433
- // sessionId 两段式派生:先算 base(不含代数),再按升代计数取值。
1434
- const baseSessionId = deriveSessionId(project, firstText, SESSION_LANE_INFER)
1435
- const generation = sessionBumps.get(baseSessionId) ?? 0
1436
- const sessionId = generation > 0 ? deriveSessionId(project, firstText, SESSION_LANE_INFER, generation) : baseSessionId
1437
-
1438
- // ⚠️ 去签重试必须真正剥离签名:buildContents 在循环外只跑一次(图片内联昂贵,
1439
- // 不能重跑),所以这里对 contents 深拷贝剥掉所有 thoughtSignature(等价于
1440
- // 查不到签名时重建信封)。直接 continue 会让
1441
- // 重试仍带原签名,白白再吃一次 400。
1442
- const effectiveContents = droppedSignatures
1443
- ? contents.map(content => ({
1444
- ...content,
1445
- parts: content.parts.map(part => {
1446
- if (part === null || typeof part !== 'object' || part.thoughtSignature === undefined) return part
1447
- const { thoughtSignature: _dropped, ...rest } = part
1448
- return rest
1449
- }),
1450
- }))
1451
- : contents
1452
-
1453
- const request = {
1454
- contents: effectiveContents,
1455
- generationConfig,
1456
- sessionId,
1457
- ...(systemText !== '' ? { systemInstruction: { role: 'system', parts: [{ text: systemText }] } } : {}),
1458
- ...(tools !== undefined ? { tools } : {}),
1459
- ...(toolConfig !== undefined ? { toolConfig } : {}),
1460
- }
1461
- const wire = marshalAlphabetical({
1462
- model: spec.upstream,
1463
- project,
1464
- request,
1465
- requestId: newRequestId(),
1466
- userAgent: UPSTREAM_USER_AGENT,
1467
- })
1468
- const wireBytes = Buffer.byteLength(wire, 'utf8')
1469
- if (wireBytes > MAX_REQUEST_BODY_BYTES) {
1470
- throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 请求体 ${wireBytes} 字节超过上限 ${MAX_REQUEST_BODY_BYTES} 字节` }
1471
- }
1472
-
1473
- let response
1474
- try {
1475
- response = await httpFetch(`${ENDPOINTS[endpointIdx] ?? ENDPOINTS[0]}${STREAM_PATH}`, {
1476
- method: 'POST',
1477
- headers,
1478
- body: wire,
1479
- signal,
1480
- }, headerTimeoutMs)
1481
- } catch (error) {
1482
- if (signal?.aborted) throw error
1483
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Gemini 请求发送失败:${error?.message ?? error}` }
1484
- }
1485
-
1486
- if (!response.ok) {
1487
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1488
- // 1. 签名被拒 → 去签重试一次(同账号同端点)。
1489
- if (isSignatureError(text) && !droppedSignatures) {
1490
- droppedSignatures = true
1491
- continue
1492
- }
1493
- // 2. 服务端会话累计超 1M → 升代换全新 sessionId 重发(削本地历史没用,
1494
- // 累计在服务端、按 sessionId 计;换端点/换号也无效)。
1495
- if (response.status === 400 && String(text).toLowerCase().includes(SESSION_OVERFLOW_MARKER)) {
1496
- const bumped = sessionBumps.get(baseSessionId) ?? 0
1497
- if (bumped < MAX_SESSION_BUMPS) {
1498
- sessionBumps.set(baseSessionId, bumped + 1)
1499
- continue
1500
- }
1501
- }
1502
- // 3. 上下文超限:不换端点不换号(请求体本身太大,白跑两轮)。
1503
- if (response.status === 400 && TOKEN_COUNT_OVERFLOW.test(text)) throw failureFrom(response.status, text)
1504
- // 4. 先换端点(廉价兜底,一次):403/404、400+quota 类文案、429。
1505
- const endpointFirst = response.status === 403
1506
- || response.status === 404
1507
- || (response.status === 400 && hasMarker(text, SWITCHABLE_MARKERS))
1508
- if ((endpointFirst || response.status === 429) && !endpointSwitched) {
1509
- endpointSwitched = true
1510
- endpointIdx = endpointIdx === 0 ? 1 : 0
1511
- continue
1512
- }
1513
- throw failureFrom(response.status, text)
1514
- }
1515
- if (!response.body) {
1516
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Gemini 返回空响应体' }
1517
- }
1518
-
1519
- // 消费 SSE:逐帧翻译成 OpenAI chunk,喂 onData 并留档聚合。
1520
- const chunks = []
1521
- let firstChunk = true
1522
- const emit = chunk => {
1523
- const full = {
1524
- id: chunkId,
1525
- object: 'chat.completion.chunk',
1526
- created,
1527
- model: requestedModel,
1528
- choices: chunk.choices.map(choice => ({
1529
- ...choice,
1530
- delta: firstChunk ? { role: 'assistant', ...choice.delta } : choice.delta,
1531
- })),
1532
- ...(chunk.usage !== undefined ? { usage: chunk.usage } : {}),
1533
- }
1534
- firstChunk = false
1535
- chunks.push(full)
1536
- onData?.(JSON.stringify(full))
1537
- }
1538
- const consumed = await consumeStream(response.body, emit, signal, IDLE_TIMEOUT_MS)
1539
-
1540
- // ⚠️ 空响应必须报错:静默结束会让上层认为「模型正常回答但没内容」,不会重试。
1541
- if (!consumed.sawContent) {
1542
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'gemini: 模型未返回任何内容块' }
1543
- }
1544
- const finalChunk = {
1545
- choices: [{ index: 0, delta: {}, finish_reason: mapFinishReason(consumed.finishReason, consumed.toolCount) }],
1546
- ...(consumed.usage !== undefined ? { usage: consumed.usage } : {}),
1547
- }
1548
- chunks.push({ id: chunkId, object: 'chat.completion.chunk', created, model: requestedModel, ...finalChunk })
1549
- onData?.(JSON.stringify(chunks[chunks.length - 1]))
1550
-
1551
- const merged = mergeSseChunks(chunks.map(chunk => JSON.stringify(chunk)))
1552
- if (!merged || !merged.choices?.[0]) {
1553
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Gemini 流结束但没有内容帧' }
1554
- }
1555
- merged.model = requestedModel
1556
- // mergeSseChunks 只在首个内容帧时快照 usage(用量帧在后会被丢),此处显式回填。
1557
- if (consumed.usage !== undefined) merged.usage = consumed.usage
1558
- return { status: response.status, json: merged }
1559
- }
1560
- }
1561
-
1562
- // ── 配额窗口余额(只做余额;Gemini 无签到)───────────────────────────────────────
1563
-
1564
- /**
1565
- * ⚠️ 这不是「充值积分」,是 Gemini 免费线的**配额窗口**(5 小时 / 周两个窗口的
1566
- * 剩余比例)。面板如实显示「5 小时窗口 99% / 周窗口 99%」,不换算成任何积分数字。
1567
- *
1568
- * ⚠️ 端点走 **sandbox**(配额查询路径固定路由到 sandbox),
1569
- * 身份头与推理请求完全一致({@link probeHeaders},含五个伪装头 + Bearer)。
1570
- *
1571
- * ⚠️ 本项目渠道契约要求返回 {@link CreditBalance} 或 null(契约无 error?/tier? 字段)。
1572
- * 「未授权」在本项目里也用 null 表达,不区分「没登录」与「查询失败」)。
1573
- */
1574
-
1575
- /** retrieveUserQuotaSummary 路径(普通 JSON,不是 protobuf)。 */
1576
- const QUOTA_PATH = '/v1internal:retrieveUserQuotaSummary'
1577
- /** 5 小时 / 周两个窗口的桶 id。⚠️ 判据是 bucketId,**不按 displayName/window** —— 显示名会被上游改文案。 */
1578
- const BUCKET_FIVE_HOUR = 'gemini-5h'
1579
- const BUCKET_WEEKLY = 'gemini-weekly'
1580
- /** 面板显示名(配额是百分比窗口,不是积分,故不写「积分」二字)。 */
1581
- const WINDOW_LABEL_FIVE_HOUR = '5 小时窗口'
1582
- const WINDOW_LABEL_WEEKLY = '周窗口'
1583
- /** 配额单位:剩余**百分比**。 */
1584
- const QUOTA_UNIT = '%'
1585
- /** 配额缓存 TTL(面板 30 秒刷一次,60 秒缓存既扛连续刷新又不至滞后太久)。 */
1586
- const QUOTA_CACHE_TTL_MS = 60_000
1587
-
1588
- /**
1589
- * 60 秒缓存。
1590
- * 键 = access_token(账号的稳定标识,配额本身按 token 归属);值 = CreditBalance | null。
1591
- * ⚠️ 缓存的是**适配后**的 null(失败结果同样缓存,避免连续刷新反复打上游)。
1592
- */
1593
- const quotaCache = new Map()
1594
-
1595
- /** 剩余比例 0..1 → 百分比整数(0..100,越界收敛)。 */
1596
- function quotaPercent(fraction) {
1597
- const clamped = Math.min(1, Math.max(0, fraction))
1598
- return Math.round(clamped * 100)
1599
- }
1600
-
1601
- /** 一个窗口 → 一个 CreditPackage(单位是百分比,不是积分)。 */
1602
- function makeQuotaPackage(label, resetTime, fraction) {
1603
- const remaining = quotaPercent(fraction)
1604
- return {
1605
- name: label,
1606
- unit: QUOTA_UNIT,
1607
- remaining,
1608
- total: 100,
1609
- used: 100 - remaining,
1610
- active: true,
1611
- cycleStartTime: '',
1612
- // 上游自报的重置时刻原样透传;其余周期字段无对应概念,留空串(不编造)。
1613
- cycleEndTime: resetTime,
1614
- expiredTime: '',
1615
- }
1616
- }
1617
-
1618
- /**
1619
- * 解析单个桶。
1620
- * ⚠️ `remainingFraction` 必须是有限 number;`resetTime` 必须是可被 `Date.parse`
1621
- * 解析的字符串,**否则整条桶丢弃**(拿不到可解析的重置时间就无法表达窗口周期,
1622
- * 编一个空串会让面板显示一个永远不过期的窗口 —— 宁可少一个包,也不伪造)。
1623
- */
1624
- function parseQuotaBucket(raw) {
1625
- if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
1626
- const bucketId = typeof raw.bucketId === 'string' ? raw.bucketId : ''
1627
- if (bucketId === '') return undefined
1628
- const fraction = raw.remainingFraction
1629
- if (typeof fraction !== 'number' || !Number.isFinite(fraction)) return undefined
1630
- const resetTime = typeof raw.resetTime === 'string' ? raw.resetTime : ''
1631
- if (resetTime === '' || Number.isNaN(Date.parse(resetTime))) return undefined
1632
- return { bucketId, resetTime, fraction }
1633
- }
1634
-
1635
- /**
1636
- * 从响应体里挑出两个 Gemini 桶(形状:`groups[].buckets[]`,普通 JSON)。
1637
- * 响应里第三组桶(`3p-*`)属于 Claude/GPT 产品线,与本 provider 无关,按 id 自然跳过。
1638
- */
1639
- function parseQuotaWindows(payload) {
1640
- let fiveHour
1641
- let weekly
1642
- if (payload === null || typeof payload !== 'object') return { fiveHour, weekly }
1643
- const groups = payload.groups
1644
- if (!Array.isArray(groups)) return { fiveHour, weekly }
1645
- for (const group of groups) {
1646
- if (group === null || typeof group !== 'object' || Array.isArray(group)) continue
1647
- const buckets = group.buckets
1648
- if (!Array.isArray(buckets)) continue
1649
- for (const bucket of buckets) {
1650
- const parsed = parseQuotaBucket(bucket)
1651
- if (parsed === undefined) continue
1652
- if (parsed.bucketId === BUCKET_FIVE_HOUR && fiveHour === undefined) fiveHour = parsed
1653
- if (parsed.bucketId === BUCKET_WEEKLY && weekly === undefined) weekly = parsed
1654
- }
1655
- }
1656
- return { fiveHour, weekly }
1657
- }
1658
-
1659
- /**
1660
- * 两个窗口 → 插件统一的 CreditBalance。
1661
- * ⚠️ 两个桶都没认出来 ⇒ null(真失败),**不伪造 100%**(空余额会被渲染成「0」,
1662
- * 让用户误以为额度用光,比「查询失败」更误导)。
1663
- * ⚠️ `total` 取两窗口剩余百分比的**平均**(取 min 会把「周 99% / 5h 20%」显示成 20%)。
1664
- * ⚠️ `expiredTotal` 恒 0:配额窗口没有「过期积分」这个概念。
1665
- */
1666
- function toQuotaBalance(fiveHour, weekly) {
1667
- const packages = []
1668
- if (fiveHour !== undefined) packages.push(makeQuotaPackage(WINDOW_LABEL_FIVE_HOUR, fiveHour.resetTime, fiveHour.fraction))
1669
- if (weekly !== undefined) packages.push(makeQuotaPackage(WINDOW_LABEL_WEEKLY, weekly.resetTime, weekly.fraction))
1670
- if (packages.length === 0) return null
1671
- const sum = packages.reduce((acc, item) => acc + item.remaining, 0)
1672
- return {
1673
- total: roundCredits(sum / packages.length),
1674
- packages,
1675
- expiredTotal: 0,
1676
- }
1677
- }
1678
-
1679
- /**
1680
- * 查询 Gemini 配额窗口余额(**只读**;Gemini 无签到端点,故不实现 claimCredits)。
1681
- *
1682
- * ⚠️ **本函数不抛错**:未授权 / 网络失败 / HTTP 非 2xx / 响应非 JSON / 两个桶都没
1683
- * 认出来 —— 一律返回 null(批量查询时单账号失败不得中断其余账号)。
1684
- * ⚠️ 请求体**必须带 `project`**(缺 project 会被上游回 403 SUBSCRIPTION_REQUIRED,
1685
- * 而凭据其实是好的);字段名是 `project`,**不是** `cloudaicompanionProject`
1686
- * (后者会 400 Unknown name)。值取凭据里的 `cloudaicompanionProject`,缺失退到
1687
- * {@link DEFAULT_PROJECT}。
1688
- */
1689
- export async function fetchCreditBalance(credential) {
1690
- const accessToken = readStringField(credential, 'access_token')
1691
- // ⚠️ 无 access_token:本项目契约用 null 表达。
1692
- if (accessToken === '') return null
1693
-
1694
- const cached = quotaCache.get(accessToken)
1695
- if (cached !== undefined && Date.now() - cached.at < QUOTA_CACHE_TTL_MS) return cached.result
1696
-
1697
- let result = null
1698
- try {
1699
- const project = readStringField(credential, 'cloudaicompanionProject') || DEFAULT_PROJECT
1700
- const response = await httpFetch(`${ENDPOINT_SANDBOX}${QUOTA_PATH}`, {
1701
- method: 'POST',
1702
- // ⚠️ 身份头与推理请求完全一致(含五个伪装头);配额是普通 JSON。
1703
- headers: probeHeaders(credential),
1704
- body: JSON.stringify({ project }),
1705
- }, PROBE_TIMEOUT_MS)
1706
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1707
- // 非 2xx 直接落 null(不解析错误体 —— 契约里失败就是 null,没有 error 字段)。
1708
- if (response.ok) {
1709
- // 普通 JSON(不是 protobuf);解析失败会被外层 catch 兜住 → null。
1710
- const { fiveHour, weekly } = parseQuotaWindows(JSON.parse(text))
1711
- result = toQuotaBalance(fiveHour, weekly)
1712
- }
1713
- } catch {
1714
- // 网络失败 / 非 JSON 等一切异常 → null(不得抛)。
1715
- result = null
1716
- }
1717
-
1718
- // 失败结果也缓存,避免连续刷新反复打上游。
1719
- quotaCache.set(accessToken, { at: Date.now(), result })
1720
- return result
1721
- }
1
+ /**
2
+ * Gemini 渠道 —— 对接 Google Cloud Code Assist 免费线(antigravity 客户端伪装)。
3
+ *
4
+ * 协议要点确认:
5
+ * - 通道:Google Cloud Code Assist 免费线(antigravity 客户端伪装)。
6
+ * 端点 daily-cloudcode-pa.googleapis.com(主)/ *.sandbox.googleapis.com(备),
7
+ * 流式推理 POST /v1internal:streamGenerateContent?alt=sse;
8
+ * 项目探测 POST /v1internal:loadCodeAssist(sandbox 优先,daily 兜底),
9
+ * 请求体固定为 `{"metadata":{"ideType":"ANTIGRAVITY"}}`(多一个字段就可能被
10
+ * 上游识别成非官方客户端)。
11
+ * - 身份五头写死不许随机:User-Agent `antigravity/4.3.0 (cmdc-pak)`、
12
+ * x-client-name/x-client-version/x-machine-id/x-vscode-sessionid;
13
+ * ⚠️ 不带 x-goog-api-key / x-goog-api-client;流式请求**刻意不带 Accept**。
14
+ * - 信封 {model, project, request, requestId, userAgent} 必须**逐层按键名
15
+ * 字母序**序列化 —— 服务端(Go)对 map 自动字母序,JSON.stringify 是插入序,
16
+ * 不排序与上游看到的字节不同。
17
+ * - 模型名是准入钥匙:发裸 `gemini-3.8-flash` 上游 404,必须带档位后缀
18
+ * (-low/-medium/-high/-tiered);lite 已整体移除(恒 404);
19
+ * 「关闭思考」是假关(关 includeThoughts 照样思考照样计费)⇒ includeThoughts
20
+ * **恒 true**,不提供 none 档;tiered 档只发 includeThoughts 不发 thinkingBudget。
21
+ * - sessionId **不是常量**:= f(project, 首条 user 文本, lane)(FNV-1a 派生依赖维度)。
22
+ * 上游按 sessionId 在**服务端**累计对话输入,
23
+ * 长工具循环推过 1M 后该会话每个请求都 400 —— 唯一出路是「升代」换新
24
+ * sessionId(判据:400 + "exceeds the maximum number of tokens")。
25
+ * - 登录:浏览器回调式 OAuth(authorization_code + client_secret,无 PKCE)。
26
+ * ⚠️ token 端点强制校验客户端身份,表单**必须**带 client_secret;
27
+ * ⚠️ 必须「先监听再拼 URL」(端口被占回退别的端口,先拼 URL 就
28
+ * redirect_uri_mismatch);回调路径 /oauth-callback 与 client 注册值一致;
29
+ * loopback 重定向(RFC 8252)允许任意端口;同时听 127.0.0.1 与 [::1]
30
+ * (浏览器常把 localhost 解析成 IPv6);授权总预算 6 分钟(Google 常带二次验证)。
31
+ * - 续期:refresh_token grant;Google **偶尔轮换 refresh_token**,响应给了新的
32
+ * 必须回写;Google 有重放检测。终态判据只看**令牌端点的 error 码**
33
+ * (invalid_grant/invalid_client/expired/revoked/unauthorized),网络错误的
34
+ * 文案(TLS CERT_HAS_EXPIRED 含 "expired")**不能**判终态。
35
+ * - project 探测三级缓存:内存 → 凭据 cloudaicompanionProject → 现探 LCA。
36
+ * LCA 200 但 project 为空 = 免费档常态 → 回落 `aicode-consumers` 照常发推理;
37
+ * LCA **失败**(网络/非 2xx)→ 不发推理。
38
+ * - thoughtSignature:functionCall part 上的签名按「工具名 + 字母序参数」
39
+ * 记缓存,下一轮回填(思考分片上的签名刻意不存);上游拒签名时**去签重试
40
+ * 一次**。签名键 = sha256("tool:"+name+"\0"+args[:512])[:16]。
41
+ * - 消息转换:role 只有 user/model(assistant→model,其余→user);历史 thinking
42
+ * 不回传;functionResponse 只认 name(按 tool_use.id→name 映射回填),空 name
43
+ * 整块丢弃;一批 tool_calls 只有**全部**拿到结果才保留(无结果的 tool_call
44
+ * 上游 400);图片内联失败**显式抛错**不静默丢图。
45
+ * - SSE:每帧 `{"response":{…}}` 或裸 Response,只有 candidates 非空才算内容帧
46
+ * (纯 usageMetadata 收尾帧继续读);`data: [DONE]` 结束;`:` 开头是注释行;
47
+ * 收尾余量必须按整行再走一遍(否则末帧 finishReason/usage 被丢);用量取
48
+ * 「见过的最大 totalTokenCount」那一份;上游生成大 functionCall 参数期间可能
49
+ * 长时间不 flush,读取必须带空闲超时。
50
+ * - 错误分类:签名错误→去签重试;会话 1M→升代;上下文超限→request(不换端点
51
+ * 不换号);400+quota 文案→quota 可换号;403/404/429→先换端点一次(零成本
52
+ * 无害但救不了 quota,主救场是换账号);401→auth 可换号。
53
+ */
54
+
55
+ import { createHash, randomBytes } from 'node:crypto'
56
+ import { createServer } from 'node:http'
57
+ import { httpFetch, readBodyText, mergeSseChunks, roundCredits } from '../util.js'
58
+
59
+ // ── 端点与路径 ───────────────────────────────────────────────────────────────
60
+
61
+ const ENDPOINT_DAILY = 'https://daily-cloudcode-pa.googleapis.com'
62
+ const ENDPOINT_SANDBOX = 'https://daily-cloudcode-pa.sandbox.googleapis.com'
63
+ /** 推理端点轮换顺序(初始 endpoints)。 */
64
+ const ENDPOINTS = [ENDPOINT_DAILY, ENDPOINT_SANDBOX]
65
+ /** 探测端点顺序:sandbox 优先(LCA 固定路由到 sandbox)。 */
66
+ const PROBE_ENDPOINTS = [ENDPOINT_SANDBOX, ENDPOINT_DAILY]
67
+
68
+ const STREAM_PATH = '/v1internal:streamGenerateContent?alt=sse'
69
+ const LOAD_CODE_ASSIST_PATH = '/v1internal:loadCodeAssist'
70
+ /** 档位探测请求体(content-length 恰为 38)。 */
71
+ const LOAD_CODE_ASSIST_BODY = '{"metadata":{"ideType":"ANTIGRAVITY"}}'
72
+
73
+ // ── 身份伪装(常量,不许随机)───────────────────────────────────────────────
74
+
75
+ /** 身份五头。⚠️ 写死;⚠️ 不带 x-goog-api-key / x-goog-api-client。 */
76
+ const IDENTITY_HEADERS = Object.freeze({
77
+ 'User-Agent': 'antigravity/4.3.0 (cmdc-pak)',
78
+ 'x-client-name': 'antigravity',
79
+ 'x-client-version': '4.3.0',
80
+ 'x-machine-id': 'cmdc-pak',
81
+ 'x-vscode-sessionid': 'proxy',
82
+ })
83
+ /** 信封里的 userAgent 字段(与 x-client-name 同值)。 */
84
+ const UPSTREAM_USER_AGENT = 'antigravity'
85
+
86
+ // ── OAuth ───────────────────────────────────────────────────────────────────────
87
+
88
+ const AUTH_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth'
89
+ const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'
90
+ const USERINFO_ENDPOINT = 'https://www.googleapis.com/oauth2/v2/userinfo'
91
+
92
+ /** 上游 Cloud Code 客户端的公开 client(env 可覆盖)。 */
93
+ const DEFAULT_CLIENT_ID = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com'
94
+ const DEFAULT_CLIENT_SECRET = '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'
95
+ /** 回调路径(与 client 注册值一致)。 */
96
+ const CALLBACK_PATH = '/oauth-callback'
97
+ /** 重定向 URI 主机名。⚠️ 必须是 localhost 而不是 127.0.0.1。 */
98
+ const REDIRECT_HOST = 'localhost'
99
+
100
+ /** 六项 scope(cloud-platform 必需,后两项是 Cloud Code 自己的通道)。 */
101
+ const SCOPES = [
102
+ 'openid',
103
+ 'https://www.googleapis.com/auth/cloud-platform',
104
+ 'https://www.googleapis.com/auth/userinfo.email',
105
+ 'https://www.googleapis.com/auth/userinfo.profile',
106
+ 'https://www.googleapis.com/auth/cclog',
107
+ 'https://www.googleapis.com/auth/experimentsandconfigs',
108
+ ]
109
+
110
+ /** 授权流程总预算 6 分钟(Google 账号常带二次验证,3 分钟会把正常用户掐掉)。 */
111
+ const AUTH_FLOW_TIMEOUT_MS = 360_000
112
+ /** OAuth 端点请求超时。 */
113
+ const OAUTH_TIMEOUT_MS = 20_000
114
+
115
+ /** 回调成功后展示的页面。 */
116
+ const CALLBACK_HTML = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>授权完成</title><style>body{font:15px/1.7 -apple-system,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#0f1115;color:#e6e8eb}.b{text-align:center}.k{font-size:34px;margin-bottom:8px}</style></head><body><div class="b"><div class="k">✓</div><div>授权已完成,可以关闭此页回到面板。</div></div></body></html>`
117
+
118
+ // ── 模型档表 ───────────────────────────────────────────────────────────────────
119
+
120
+ /** 主模型上游名(不带档位后缀,后缀由 modelSpec 拼)。 */
121
+ const UPSTREAM_FLASH = 'gemini-3.8-flash'
122
+ const BUDGET_LOW = 1_000
123
+ const BUDGET_MEDIUM = 4_000
124
+ const BUDGET_HIGH = 10_000
125
+ /** tiered 档:只发 includeThoughts,不发 thinkingBudget。 */
126
+ const BUDGET_TIERED = -1
127
+ /** 上下文窗口(用户拍板填 1_000_000)。 */
128
+ const CONTEXT_WINDOW = 1_000_000
129
+ const EFFORT_IDS = ['low', 'medium', 'high', 'tiered']
130
+ const DEFAULT_EFFORT = 'medium'
131
+ /** 默认最大输出 token(用户拍板 64000)。 */
132
+ const MAX_OUTPUT_TOKENS = 64_000
133
+
134
+ /** 兜底模型目录(用户拍板静态表,不拉远端目录)。 */
135
+ /** ⚠️ 不暴露 lite(上游恒 404,暴露即坑);档位走 efforts 下拉框,不拆成 4 个模型名。 */
136
+ export const fallbackModels = [
137
+ {
138
+ id: UPSTREAM_FLASH,
139
+ name: 'Gemini 3.8 Flash',
140
+ contextWindow: CONTEXT_WINDOW,
141
+ maxTokens: MAX_OUTPUT_TOKENS,
142
+ supportsImage: true,
143
+ efforts: EFFORT_IDS,
144
+ defaultEffort: DEFAULT_EFFORT,
145
+ },
146
+ ]
147
+
148
+ /** 匿名即可获取模型清单:fetchModels 返回本地静态 fallbackModels(零网络),不依赖任何账号凭据。 */
149
+ export const meta = { id: 'gemini', label: 'Gemini Code Assist', loginMode: 'oauth-callback', anonymousModels: true }
150
+
151
+ // ── 项目与会话 ──────────────────────────────────────────────────────────────────
152
+
153
+ /** LCA 探测为空/失败时的兜底项目号(免费档常态)。 */
154
+ const DEFAULT_PROJECT = 'aicode-consumers'
155
+ /** 会话派生标签(推理 / 冒烟),只区分派生路径(lane 进哈希),不参与取值。 */
156
+ const SESSION_LANE_INFER = 'infer'
157
+
158
+ // ── 超时与限额 ──────────────────────────────────────────────────────────────
159
+
160
+ /** 推理请求头超时。 */
161
+ const REQUEST_TIMEOUT_MS = 120_000
162
+ /** LCA/配额类请求超时。 */
163
+ const PROBE_TIMEOUT_MS = 30_000
164
+ /** SSE 空闲超时:上游生成大 functionCall 参数期间可能长时间不 flush,必须主动掐。 */
165
+ const IDLE_TIMEOUT_MS = 120_000
166
+ /** BODY 读超时。 */
167
+ const BODY_READ_TIMEOUT_MS = 15_000
168
+ /** 续期提前量(OMR 口径:过期前 1 小时)。 */
169
+ const REFRESH_LEAD_MS = 60 * 60_000
170
+ /** 上游单张内联图片体积上限(超出整请求被拒)。 */
171
+ const MAX_IMAGE_BYTES_INLINE = 10 * 1024 * 1024
172
+ /** 请求体上限(发送前真实检查)。 */
173
+ const MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024
174
+ /** 一次请求内最多升几代(必须有界,否则无界升代变死循环)。 */
175
+ const MAX_SESSION_BUMPS = 1
176
+ /** 429 命中后原账号的冷却时长。 */
177
+ const RATE_LIMIT_COOLDOWN_MS = 60_000
178
+ /** 401 命中后原账号的冷却时长。 */
179
+ const AUTH_COOLDOWN_MS = 300_000
180
+ /** 签名缓存条数上限(签名串平均 300~800 字节,2000 条约 1MB 量级)。 */
181
+ const SIG_MAX_ENTRIES = 2_000
182
+ /** 算签名键时只取正文前 512 字符(长回答尾部每次都不一样,用全文命中率趋 0)。 */
183
+ const SIG_KEY_BODY_LIMIT = 512
184
+
185
+ /** 额度/限流文案标记(小写比对)。 */
186
+ const QUOTA_MARKERS = ['quota', 'resource_exhausted', 'resource exhausted', 'rate limit', 'exceeded']
187
+ /** 可换端点的 400 文案标记(quota/permission/unsupported/project)。 */
188
+ const SWITCHABLE_MARKERS = ['quota', 'permission', 'unsupported', 'project']
189
+
190
+ /** 上下文超限判据:要求「token count」+「exceeds the maximum」同时出现(实测报文)。 */
191
+ const TOKEN_COUNT_OVERFLOW = /\btoken\s+count\b[\s\S]{0,60}?\bexceeds?\s+the\s+maximum\b/i
192
+ /** 服务端会话累计超 1M 判据(实测报文)。 */
193
+ const SESSION_OVERFLOW_MARKER = 'exceeds the maximum number of tokens'
194
+
195
+ // ── 小工具 ──────────────────────────────────────────────────────────────────
196
+
197
+ function readStringField(source, key) {
198
+ const value = source?.[key]
199
+ if (typeof value === 'string' && value.trim().length > 0) return value.trim()
200
+ return ''
201
+ }
202
+
203
+ /**
204
+ * 递归按键名升序重建值(数组保持顺序)。
205
+ * ⚠️ 不是为了好看 —— 服务端(Go)对 map 自动按字母序序列化,
206
+ * 服务端看到的是字节;键全为 ASCII 时 sort() 的码元序与 Go 字节序一致。
207
+ */
208
+ function sortValue(value) {
209
+ if (Array.isArray(value)) return value.map(sortValue)
210
+ if (value === null || typeof value !== 'object') return value
211
+ const out = {}
212
+ for (const key of Object.keys(value).sort()) out[key] = sortValue(value[key])
213
+ return out
214
+ }
215
+
216
+ /** 字母序信封序列化。 */
217
+ function marshalAlphabetical(value) {
218
+ return JSON.stringify(sortValue(value))
219
+ }
220
+
221
+ /** 参数规范化:按键名升序的紧凑 JSON。签名键两侧必须用同一个规范化。 */
222
+ function canonicalArgs(args) {
223
+ if (args === undefined || args === null) return '{}'
224
+ return marshalAlphabetical(args)
225
+ }
226
+
227
+ /** 每请求随机的 requestId。 */
228
+ function newRequestId(nowMs = Date.now()) {
229
+ return `agent/${nowMs}/${randomBytes(4).toString('hex')}`
230
+ }
231
+
232
+ /**
233
+ * 按 (project, 首条 user 文本,lane) 确定性派生 sessionId(FNV-1a)。
234
+ * generation > 0 时拼进输入(会话升代自愈);=== 0 时不拼。
235
+ */
236
+ function deriveSessionId(project, firstUserText, lane, generation = 0) {
237
+ let hash = 0xcbf29ce484222325n
238
+ const prime = 0x100000001b3n
239
+ const mask = 0xffffffffffffffffn
240
+ const base = `${project}\u0000${lane}\u0000${firstUserText}`
241
+ const input = generation > 0 ? `${base}\u0000${generation}` : base
242
+ for (const byte of Buffer.from(input, 'utf8')) {
243
+ hash = (hash ^ BigInt(byte)) & mask
244
+ hash = (hash * prime) & mask
245
+ }
246
+ return BigInt.asIntN(64, hash).toString()
247
+ }
248
+
249
+ /** 从错误体抽人可读消息(JSON error.message/message → 原文截断)。 */
250
+ function extractMessage(bodyText) {
251
+ const text = String(bodyText ?? '').trim()
252
+ if (text === '') return ''
253
+ try {
254
+ const parsed = JSON.parse(text)
255
+ const found = [parsed?.error?.message ?? (typeof parsed?.error === 'string' ? parsed.error : ''), parsed?.message]
256
+ .filter(v => typeof v === 'string' && v.length > 0)
257
+ if (found.length > 0) return found.join(' ').slice(0, 300)
258
+ } catch { /* 非 JSON */ }
259
+ return text.slice(0, 300)
260
+ }
261
+
262
+ function hasMarker(text, markers) {
263
+ const lower = String(text ?? '').toLowerCase()
264
+ return markers.some(m => lower.includes(m))
265
+ }
266
+
267
+ /** 判定「签名被上游拒绝」。必须宽:漏判=用户看到莫名 400,误判=多发一次无签名请求。 */
268
+ function isSignatureError(text) {
269
+ const lower = String(text ?? '').toLowerCase()
270
+ return lower.includes('signature') || (lower.includes('thought') && lower.includes('invalid'))
271
+ }
272
+
273
+ /** 非负整数提取。 */
274
+ function nonNegativeInt(value) {
275
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : undefined
276
+ }
277
+
278
+ /** 睡眠(可被 signal 中断)。 */
279
+ function sleep(ms, signal) {
280
+ return new Promise((resolve, reject) => {
281
+ if (signal?.aborted) { reject(new Error('已取消')); return }
282
+ const timer = setTimeout(() => {
283
+ signal?.removeEventListener('abort', onAbort)
284
+ resolve()
285
+ }, ms)
286
+ const onAbort = () => { clearTimeout(timer); reject(new Error('已取消')) }
287
+ signal?.addEventListener('abort', onAbort, { once: true })
288
+ })
289
+ }
290
+
291
+ // ── 模型规格 ────────────────────────────────────────────────────────────────
292
+
293
+ /** 档位 id 归一(未知/缺省一律 medium,同默认分支)。 */
294
+ function effortToTier(effort) {
295
+ if (effort === 'low' || effort === 'medium' || effort === 'high' || effort === 'tiered') return effort
296
+ return 'medium'
297
+ }
298
+
299
+ /** 档位 → 思考预算(tiered = -1 只发 includeThoughts)。 */
300
+ function thinkingBudget(tier) {
301
+ if (tier === 'low') return BUDGET_LOW
302
+ if (tier === 'high') return BUDGET_HIGH
303
+ if (tier === 'tiered') return BUDGET_TIERED
304
+ return BUDGET_MEDIUM
305
+ }
306
+
307
+ /**
308
+ * 归一化模型 id:剥掉已知档位后缀(-low/-medium/-high/-tiered)得到目录裸名。
309
+ * ⚠️ 只剥已知档位:限流标记/探测链路传来的是带档位的名字,先归一化再查表。
310
+ */
311
+ function canonicalModelId(modelId) {
312
+ for (const tier of EFFORT_IDS) {
313
+ if (modelId.endsWith(`-${tier}`)) return modelId.slice(0, modelId.length - tier.length - 1)
314
+ }
315
+ return modelId
316
+ }
317
+
318
+ /**
319
+ * 由「模型 id + 用户选的档位」得出上游模型规格。
320
+ * ⚠️ 模型名必须带档位后缀 —— 它是上游的准入钥匙(裸名 404)。
321
+ * ⚠️ 严格校验:未知 id 直接拒绝不发上游(宽容的代价是用户写错模型名时静默
322
+ * 跑出 3.8 的答案且无任何征兆 —— 实测假名 200 正常作答,名字不参与上游路由)。
323
+ */
324
+ function modelSpec(modelId, effort) {
325
+ if (canonicalModelId(String(modelId ?? '')) !== UPSTREAM_FLASH) {
326
+ throw { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message: `gemini: 模型 "${modelId}" 不在本渠道目录中(仅支持 ${UPSTREAM_FLASH})` }
327
+ }
328
+ const tier = effortToTier(typeof effort === 'string' ? effort : undefined)
329
+ return { upstream: `${UPSTREAM_FLASH}-${tier}`, tier, thinkingBudget: thinkingBudget(tier), includeThoughts: true }
330
+ }
331
+
332
+ // ── 凭据 ────────────────────────────────────────────────────────────────────
333
+
334
+ function credentialExpiresAtMs(credential) {
335
+ const expiry = credential?.expiry
336
+ if (typeof expiry === 'string' && expiry !== '') {
337
+ const parsed = Date.parse(expiry)
338
+ if (Number.isFinite(parsed)) return parsed
339
+ }
340
+ const ms = credential?.expire_time
341
+ return typeof ms === 'number' && Number.isFinite(ms) && ms > 0 ? ms : undefined
342
+ }
343
+
344
+ function isRefreshable(credential) {
345
+ return typeof credential?.refresh_token === 'string' && credential.refresh_token !== ''
346
+ }
347
+
348
+ /** 过期前 1 小时即需续期;取不到过期时刻返回 false。 */
349
+ export function needsRefresh(credential) {
350
+ if (!isRefreshable(credential)) return false
351
+ const expiresAt = credentialExpiresAtMs(credential)
352
+ if (expiresAt === undefined) return false
353
+ return Date.now() >= expiresAt - REFRESH_LEAD_MS
354
+ }
355
+
356
+ export function describeCredential(credential) {
357
+ const email = readStringField(credential, 'email')
358
+ const sub = readStringField(credential, 'sub')
359
+ return {
360
+ label: email || sub || 'Gemini 账号',
361
+ expiresAt: credentialExpiresAtMs(credential) ?? 0,
362
+ refreshable: isRefreshable(credential),
363
+ }
364
+ }
365
+
366
+ /** 稳定去重键:email/sub(sub 是 OIDC 稳定标识,邮箱可改 sub 不变)。 */
367
+ export function credentialIdentity(credential) {
368
+ return readStringField(credential, 'email') || readStringField(credential, 'sub') || ''
369
+ }
370
+
371
+ /** 手动粘贴凭据的规范化:接受 JSON 对象/字符串,字段名与 OAuth 响应一致。 */
372
+ export function normalizeCredential(raw) {
373
+ let value = raw
374
+ if (typeof value === 'string') {
375
+ try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
376
+ }
377
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
378
+ throw new Error('凭据必须是 JSON 对象')
379
+ }
380
+ const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken')
381
+ if (!accessToken) throw new Error('凭据缺少 access_token')
382
+ const out = { ...value, access_token: accessToken }
383
+ const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken')
384
+ if (refreshToken) out.refresh_token = refreshToken
385
+ if (readStringField(value, 'token_type')) out.token_type = readStringField(value, 'token_type')
386
+ if (readStringField(value, 'scope')) out.scope = readStringField(value, 'scope')
387
+ if (readStringField(value, 'sub')) out.sub = readStringField(value, 'sub')
388
+ if (readStringField(value, 'email')) out.email = readStringField(value, 'email')
389
+ if (readStringField(value, 'cloudaicompanionProject')) out.cloudaicompanionProject = readStringField(value, 'cloudaicompanionProject')
390
+ const expiresAt = credentialExpiresAtMs(value)
391
+ if (expiresAt !== undefined) out.expiry = new Date(expiresAt).toISOString()
392
+ return out
393
+ }
394
+
395
+ // ── 令牌载荷 ──────────────────────────────────────────────────────────────────────
396
+
397
+ function clientId() {
398
+ const fromEnv = process.env.CMDC_PAK_GOOGLE_CLIENT_ID?.trim()
399
+ return fromEnv ? fromEnv : DEFAULT_CLIENT_ID
400
+ }
401
+
402
+ function clientSecret() {
403
+ const fromEnv = process.env.CMDC_PAK_GOOGLE_CLIENT_SECRET?.trim()
404
+ return fromEnv ? fromEnv : DEFAULT_CLIENT_SECRET
405
+ }
406
+
407
+ /**
408
+ * 解析令牌端点响应。三种失败形态都给能定位问题的文案:
409
+ * error 字段 / 缺 access_token / 非 JSON。
410
+ * ⚠️ Google 偶尔轮换 refresh_token:响应没给新的就沿用 previousRefreshToken。
411
+ */
412
+ function parseTokenGrant(payload, previousRefreshToken) {
413
+ if (payload === null || typeof payload !== 'object') {
414
+ throw new Error('令牌端点返回无法解析(非 JSON 对象)')
415
+ }
416
+ const errorCode = typeof payload.error === 'string' ? payload.error : ''
417
+ if (errorCode !== '') {
418
+ const description = typeof payload.error_description === 'string' ? payload.error_description : ''
419
+ throw new Error(description === '' ? errorCode : `${errorCode}: ${description}`)
420
+ }
421
+ const accessToken = typeof payload.access_token === 'string' ? payload.access_token : ''
422
+ if (accessToken === '') throw new Error('令牌端点未返回 access_token')
423
+ const rawRefresh = typeof payload.refresh_token === 'string' ? payload.refresh_token : ''
424
+ const refreshToken = rawRefresh !== '' ? rawRefresh : previousRefreshToken
425
+ const rawTokenType = typeof payload.token_type === 'string' ? payload.token_type : ''
426
+ const expiresIn = typeof payload.expires_in === 'number' && Number.isFinite(payload.expires_in) && payload.expires_in > 0
427
+ ? Math.floor(payload.expires_in)
428
+ : 3600
429
+ return {
430
+ access_token: accessToken,
431
+ token_type: rawTokenType === '' ? 'Bearer' : rawTokenType,
432
+ expires_in: expiresIn,
433
+ ...(refreshToken ? { refresh_token: refreshToken } : {}),
434
+ ...(typeof payload.scope === 'string' && payload.scope !== '' ? { scope: payload.scope } : {}),
435
+ ...(typeof payload.id_token === 'string' && payload.id_token !== '' ? { id_token: payload.id_token } : {}),
436
+ }
437
+ }
438
+
439
+ /**
440
+ * 从 id_token 解出身份(sub/email)。
441
+ * ⚠️ 不验签:只用于展示名与稳定标识,不作为鉴权依据;失败返回 {} 不抛错。
442
+ */
443
+ function identityFromIdToken(idToken) {
444
+ if (typeof idToken !== 'string' || idToken === '') return {}
445
+ const parts = idToken.split('.')
446
+ if (parts.length < 2) return {}
447
+ let payload
448
+ try {
449
+ payload = JSON.parse(Buffer.from(parts[1] ?? '', 'base64url').toString('utf8'))
450
+ } catch {
451
+ return {}
452
+ }
453
+ if (payload === null || typeof payload !== 'object') return {}
454
+ const out = {}
455
+ if (typeof payload.sub === 'string' && payload.sub !== '') out.sub = payload.sub
456
+ if (typeof payload.email === 'string' && payload.email !== '') out.email = payload.email
457
+ return out
458
+ }
459
+
460
+ /** 把令牌授予结果并成一条凭据(保留既有 sub/email/project/refresh_token)。 */
461
+ function credentialFromGrant(grant, previous = {}) {
462
+ const credential = {
463
+ access_token: grant.access_token,
464
+ token_type: grant.token_type,
465
+ expires_in: grant.expires_in,
466
+ expiry: new Date(Date.now() + (grant.expires_in > 0 ? grant.expires_in : 3600) * 1000).toISOString(),
467
+ }
468
+ const refreshToken = grant.refresh_token ?? previous.refresh_token
469
+ if (refreshToken) credential.refresh_token = refreshToken
470
+ const scope = grant.scope ?? previous.scope
471
+ if (scope) credential.scope = scope
472
+ // 身份优先取 id_token(与 access_token 同一次响应自带,零额外请求),退到既有凭据。
473
+ const identity = grant.id_token === undefined ? {} : identityFromIdToken(grant.id_token)
474
+ const sub = identity.sub ?? previous.sub
475
+ if (sub) credential.sub = sub
476
+ const email = identity.email ?? previous.email
477
+ if (email) credential.email = email
478
+ if (previous.cloudaicompanionProject) credential.cloudaicompanionProject = previous.cloudaicompanionProject
479
+ return credential
480
+ }
481
+
482
+ /**
483
+ * POST 表单到 Google OAuth 端点。
484
+ * ⚠️ 刻意不设 User-Agent:antigravity 伪装只用在 Cloud Code 的推理/配额端点,
485
+ * 令牌与 userinfo 端点是标准 Google OAuth,加伪装反而多一个可疑特征。
486
+ */
487
+ async function postForm(endpoint, form, signal) {
488
+ const response = await httpFetch(endpoint, {
489
+ method: 'POST',
490
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
491
+ body: new URLSearchParams(form).toString(),
492
+ signal,
493
+ }, OAUTH_TIMEOUT_MS)
494
+ const text = await response.text().catch(() => '')
495
+ let parsed
496
+ try {
497
+ parsed = JSON.parse(text)
498
+ } catch {
499
+ throw new Error(`令牌端点返回无法解析(HTTP ${response.status})`)
500
+ }
501
+ if (!response.ok) {
502
+ const code = typeof parsed?.error === 'string' ? parsed.error : `HTTP ${response.status}`
503
+ const description = typeof parsed?.error_description === 'string' ? parsed.error_description : ''
504
+ throw new Error(description === '' ? code : `${code}: ${description}`)
505
+ }
506
+ return parsed
507
+ }
508
+
509
+ /** 拉账号身份(id_token 缺席时的兜底)。失败返回 {} 不抛错。 */
510
+ async function fetchUserInfo(accessToken, signal) {
511
+ try {
512
+ const response = await httpFetch(USERINFO_ENDPOINT, {
513
+ method: 'GET',
514
+ headers: { Authorization: `Bearer ${accessToken}` },
515
+ signal,
516
+ }, OAUTH_TIMEOUT_MS)
517
+ if (!response.ok) return {}
518
+ const payload = await response.json().catch(() => null)
519
+ if (payload === null || typeof payload !== 'object') return {}
520
+ const out = {}
521
+ if (typeof payload.id === 'string' && payload.id !== '') out.sub = payload.id
522
+ if (typeof payload.email === 'string' && payload.email !== '') out.email = payload.email
523
+ return out
524
+ } catch {
525
+ return {}
526
+ }
527
+ }
528
+
529
+ // ── 登录(浏览器回调式 OAuth,先监听再拼 URL)───────────────────────────────
530
+
531
+ /** 构造授权 URL(参数顺序无关紧要,Google 不校验)。 */
532
+ function buildAuthUrl(state, redirectUri) {
533
+ const query = new URLSearchParams({
534
+ client_id: clientId(),
535
+ response_type: 'code',
536
+ redirect_uri: redirectUri,
537
+ scope: SCOPES.join(' '),
538
+ state,
539
+ access_type: 'offline',
540
+ include_granted_scopes: 'true',
541
+ prompt: 'consent',
542
+ })
543
+ return `${AUTH_ENDPOINT}?${query.toString()}`
544
+ }
545
+
546
+ /** 先占一个空闲端口再释放 —— 让 v4/v6 两个监听器落在同一个端口上。 */
547
+ function pickFreePort() {
548
+ return new Promise((resolve, reject) => {
549
+ const probe = createServer()
550
+ probe.once('error', reject)
551
+ probe.listen(0, '127.0.0.1', () => {
552
+ const address = probe.address()
553
+ const port = typeof address === 'object' && address !== null ? address.port : 0
554
+ probe.close(() => {
555
+ if (port > 0) resolve(port)
556
+ else reject(new Error('无法分配回调端口'))
557
+ })
558
+ })
559
+ })
560
+ }
561
+
562
+ /**
563
+ * 在指定端口上同时监听 127.0.0.1 与 [::1]。
564
+ * ⚠️ 必须两个都听:浏览器把 localhost 解析成 ::1 时只绑 v4 会「页面打不开」。
565
+ * IPv6 监听失败可容忍;127.0.0.1 失败才是真失败。首选端口被占时换空闲端口重试
566
+ * (**不能**先拼 URL,见文件头)。
567
+ */
568
+ function listenCallback(handler, preferredPort, servers) {
569
+ const attempt = port => new Promise((resolve, reject) => {
570
+ const primary = createServer(handler)
571
+ servers.push(primary)
572
+ primary.once('error', error => {
573
+ if (error?.code === 'EADDRINUSE' && port !== 0) {
574
+ pickFreePort().then(next => resolve(attempt(next)), reject)
575
+ return
576
+ }
577
+ reject(error)
578
+ })
579
+ primary.listen(port, '127.0.0.1', () => {
580
+ const address = primary.address()
581
+ const assigned = typeof address === 'object' && address !== null ? address.port : 0
582
+ const secondary = createServer(handler)
583
+ servers.push(secondary)
584
+ // IPv6 监听失败可容忍(localhost 解析到 v4 时仍然可用);首个错误用于降级,
585
+ // 之后的错误静默吞掉(once 之外还要有常驻 handler,否则 uncaught exception)。
586
+ let settled6 = false
587
+ secondary.on('error', () => { if (!settled6) { settled6 = true; resolve(assigned) } })
588
+ secondary.listen(assigned, '::1', () => { if (!settled6) { settled6 = true; resolve(assigned) } })
589
+ })
590
+ })
591
+ return attempt(preferredPort)
592
+ }
593
+
594
+ /**
595
+ * 启动浏览器回调式 OAuth 登录。两步式:服务器就绪后立即回填 loginUrl
596
+ * (浏览器只在用户点击后的短暂窗口内允许 window.open,阻塞式流程会过期)。
597
+ * 返回 `{ loginUrl: '', loginUrlReady, promise, cancel }`。
598
+ */
599
+ export function startLogin({ port } = {}) {
600
+ const controller = new AbortController()
601
+ const signal = controller.signal
602
+ const state = randomBytes(16).toString('hex')
603
+
604
+ let resolveCode = () => {}
605
+ let rejectCode = () => {}
606
+ const codePromise = new Promise((resolve, reject) => {
607
+ resolveCode = resolve
608
+ rejectCode = reject
609
+ })
610
+ const onAbort = () => rejectCode(new Error('登录已取消'))
611
+ signal.addEventListener('abort', onAbort, { once: true })
612
+
613
+ const servers = []
614
+ let closed = false
615
+ const closeServers = () => {
616
+ if (closed) return
617
+ closed = true
618
+ for (const server of servers) {
619
+ try { server.close(() => {}) } catch { /* 已关闭 */ }
620
+ }
621
+ }
622
+
623
+ /** 回调处理器:state 必须校验(防伪造回调);error 参数 = 用户点了取消。 */
624
+ const handler = (req, res) => {
625
+ let url
626
+ try { url = new URL(req.url ?? '/', `http://${REDIRECT_HOST}`) } catch { res.writeHead(400).end('Bad request'); return }
627
+ if (url.pathname !== CALLBACK_PATH) {
628
+ res.writeHead(404).end('Not found')
629
+ return
630
+ }
631
+ const failure = url.searchParams.get('error')
632
+ if (failure !== null && failure !== '') {
633
+ const description = url.searchParams.get('error_description') ?? ''
634
+ res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }).end(`授权被拒绝: ${failure}`)
635
+ rejectCode(new Error(description === '' ? failure : `${failure}: ${description}`))
636
+ return
637
+ }
638
+ if (url.searchParams.get('state') !== state) {
639
+ res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }).end('state 校验失败')
640
+ rejectCode(new Error('state 校验失败,可能是伪造的回调'))
641
+ return
642
+ }
643
+ const code = url.searchParams.get('code')
644
+ if (code === null || code === '') {
645
+ res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' }).end('缺少 authorization code')
646
+ rejectCode(new Error('回调缺少 authorization code'))
647
+ return
648
+ }
649
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(CALLBACK_HTML)
650
+ resolveCode(code)
651
+ }
652
+
653
+ let redirectUri = ''
654
+ const loginUrlReady = (async () => {
655
+ // ⚠️ 先监听、再拼 URL:端口被占回退别的端口,先拼 URL 就 redirect_uri_mismatch。
656
+ const assigned = await listenCallback(handler, Number(port) || 0, servers)
657
+ redirectUri = `http://${REDIRECT_HOST}:${assigned}${CALLBACK_PATH}`
658
+ return buildAuthUrl(state, redirectUri)
659
+ })()
660
+
661
+ const promise = (async () => {
662
+ await loginUrlReady
663
+ const code = await Promise.race([
664
+ codePromise,
665
+ new Promise((_, reject) => {
666
+ const timer = setTimeout(() => reject(new Error('Google 授权超时,请重新发起')), AUTH_FLOW_TIMEOUT_MS)
667
+ timer.unref?.()
668
+ }),
669
+ ])
670
+ // ⚠️ token 端点强制校验客户端身份:只发 client_id 会回
671
+ // invalid_request: client_secret is missing(症状是「浏览器显示授权成功,
672
+ // 但面板里账号一直不出现」)。
673
+ const payload = await postForm(TOKEN_ENDPOINT, {
674
+ client_id: clientId(),
675
+ client_secret: clientSecret(),
676
+ code,
677
+ grant_type: 'authorization_code',
678
+ redirect_uri: redirectUri,
679
+ }, signal)
680
+ const grant = parseTokenGrant(payload)
681
+ const credential = credentialFromGrant(grant)
682
+ if (credential.sub !== undefined && credential.email !== undefined) return credential
683
+ // 兜底:id_token 缺席或解不出身份时才补一次 userinfo(失败不阻塞登录)。
684
+ const user = await fetchUserInfo(credential.access_token, signal)
685
+ if (credential.sub === undefined && user.sub !== undefined) credential.sub = user.sub
686
+ if (credential.email === undefined && user.email !== undefined) credential.email = user.email
687
+ return credential
688
+ })()
689
+ // 结果可能早于调用方 await 而落定:挂处理器避免「未处理的拒绝」告警,
690
+ // 错误仍会传给真正的消费者;无论成败都关闭回调服务器(用完即关)。
691
+ promise.then(closeServers, closeServers)
692
+
693
+ return {
694
+ loginUrl: '',
695
+ loginUrlReady,
696
+ promise,
697
+ cancel: () => {
698
+ try { controller.abort() } catch { /* 已取消 */ }
699
+ },
700
+ }
701
+ }
702
+
703
+ // ── 续期(refresh_token grant;终态判据只看令牌端点的 error 码)──────────────
704
+
705
+ /** 令牌端点的 error 码命中即终态(文案正则一致)。 */
706
+ const TERMINAL_REFRESH_PATTERN = /invalid_grant|invalid_client|expired|revoked|unauthorized/i
707
+
708
+ export async function refreshCredential(credential) {
709
+ const refreshToken = credential?.refresh_token
710
+ if (typeof refreshToken !== 'string' || refreshToken === '') {
711
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'Gemini 凭据缺少 refresh_token,请重新登录' }
712
+ }
713
+ let response
714
+ try {
715
+ response = await httpFetch(TOKEN_ENDPOINT, {
716
+ method: 'POST',
717
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
718
+ body: new URLSearchParams({
719
+ client_id: clientId(),
720
+ client_secret: clientSecret(),
721
+ refresh_token: refreshToken,
722
+ grant_type: 'refresh_token',
723
+ }).toString(),
724
+ }, OAUTH_TIMEOUT_MS)
725
+ } catch (error) {
726
+ // ⚠️ 传输层失败不能判终态 —— TLS 的 CERT_HAS_EXPIRED 文案也含 "expired",
727
+ // 网络抖动不该让用户重新登录(ChannelNetworkError 豁免)。
728
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期网络失败:${error?.message ?? error}` }
729
+ }
730
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
731
+ let parsed
732
+ try {
733
+ parsed = JSON.parse(text)
734
+ } catch {
735
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期响应不是 JSON(HTTP ${response.status})` }
736
+ }
737
+ const errorCode = typeof parsed?.error === 'string' ? parsed.error : ''
738
+ if (errorCode !== '' || !response.ok) {
739
+ const description = typeof parsed?.error_description === 'string' ? parsed.error_description : ''
740
+ // ⚠️ 判终态只看令牌端点的 error 码,不看网络错误文案。
741
+ if (TERMINAL_REFRESH_PATTERN.test(`${errorCode} ${description}`)) {
742
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Gemini refresh_token 已失效(${errorCode || `HTTP ${response.status}`}),请重新登录` }
743
+ }
744
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期失败(HTTP ${response.status}):${(description || errorCode || text).slice(0, 200)}` }
745
+ }
746
+ let grant
747
+ try {
748
+ grant = parseTokenGrant(parsed, refreshToken)
749
+ } catch (error) {
750
+ const message = String(error?.message ?? error)
751
+ if (TERMINAL_REFRESH_PATTERN.test(message)) {
752
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'Gemini refresh_token 已失效,请重新登录' }
753
+ }
754
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Gemini 续期失败:${message}` }
755
+ }
756
+ // credentialFromGrant 保留 sub/email/cloudaicompanionProject,并在 Google
757
+ // 轮换 refresh_token 时回写新值(否则下次续期用的是已作废的旧值)。
758
+ return credentialFromGrant(grant, credential)
759
+ }
760
+
761
+ // ── 模型清单(静态表:无远端目录端点,本表即权威清单)───────────────────────
762
+ // credential 被故意不读取:无论传 null/undefined/有效凭据,返回完全一致的本地清单,
763
+ // 所以模型清单无需任何账号凭据即可获得(零网络请求)。上游不提供公开模型列表端点。
764
+
765
+ export async function fetchModels() {
766
+ return fallbackModels.map(entry => ({
767
+ id: entry.id,
768
+ name: entry.name,
769
+ contextWindow: entry.contextWindow,
770
+ maxTokens: entry.maxTokens,
771
+ supportsImage: entry.supportsImage === true || undefined,
772
+ efforts: entry.efforts,
773
+ defaultEffort: entry.defaultEffort,
774
+ }))
775
+ }
776
+
777
+ // ── thoughtSignature 缓存(最小:仅内存)───────────────────────────────────────
778
+ // 键 = sha256("tool:"+name+"\0"+args[:512])[:16];
779
+ // 换算法会让已有缓存全部失配(表现为每轮都去签重试)。
780
+
781
+ function sigKey(role, text) {
782
+ const body = text.length > SIG_KEY_BODY_LIMIT ? text.slice(0, SIG_KEY_BODY_LIMIT) : text
783
+ return createHash('sha256').update(`${role}\u0000${body}`, 'utf8').digest('hex').slice(0, 16)
784
+ }
785
+
786
+ function toolSigKey(name, argsJson) {
787
+ return sigKey(`tool:${name}`, argsJson)
788
+ }
789
+
790
+ const sigEntries = new Map()
791
+
792
+ function sigGet(name, argsJson) {
793
+ const entry = sigEntries.get(toolSigKey(name, argsJson))
794
+ return entry && entry.sig !== '' ? entry.sig : undefined
795
+ }
796
+
797
+ /** 精确键 miss 时的兜底:取该工具名最近一次签名(长任务参数漂移是必然事件)。 */
798
+ function sigLatestForTool(name) {
799
+ let best
800
+ for (const entry of sigEntries.values()) {
801
+ if (entry.name === name && entry.sig !== '') best = entry.sig
802
+ }
803
+ return best
804
+ }
805
+
806
+ /** 记签名;空键/空签名一律丢弃(上游偶尔下发空串占位)。 */
807
+ function sigPut(name, argsJson, signature) {
808
+ const trimmed = String(signature ?? '').trim()
809
+ if (trimmed === '') return
810
+ const key = toolSigKey(name, argsJson)
811
+ if (key === '') return
812
+ sigEntries.set(key, { sig: trimmed, name })
813
+ if (sigEntries.size > SIG_MAX_ENTRIES) {
814
+ // 淘汰最旧的一半(Map 保插入序,删前半即最旧的一半)。
815
+ const keys = [...sigEntries.keys()]
816
+ for (let i = 0; i < Math.floor(keys.length / 2); i++) sigEntries.delete(keys[i])
817
+ }
818
+ }
819
+
820
+ // ── project 三级缓存 ────────────────────────────────────────────────────────────────
821
+
822
+ /** 进程内缓存(键 = email/sub/access_token;用 access_token 兜底,续期后失效只是多探一次)。 */
823
+ const projectCache = new Map()
824
+
825
+ /**
826
+ * 从 loadCodeAssist 响应取项目号:顶层 cloudaicompanionProject →
827
+ * currentTier.cloudaicompanionProject(取值顺序)。
828
+ */
829
+ function parseProject(payload) {
830
+ if (payload === null || typeof payload !== 'object') return ''
831
+ const top = payload.cloudaicompanionProject
832
+ if (typeof top === 'string' && top !== '') return top
833
+ const tier = payload.currentTier
834
+ if (tier !== null && typeof tier === 'object') {
835
+ const inner = tier.cloudaicompanionProject
836
+ if (typeof inner === 'string' && inner !== '') return inner
837
+ }
838
+ return ''
839
+ }
840
+
841
+ function probeHeaders(credential) {
842
+ return {
843
+ Authorization: `Bearer ${credential.access_token}`,
844
+ 'Content-Type': 'application/json',
845
+ ...IDENTITY_HEADERS,
846
+ }
847
+ }
848
+
849
+ /**
850
+ * 解析当前凭据可用的项目号。探测失败返回 error —— 调用方**不发推理**
851
+ * (实测:注入 500 后只在端点间重试 LCA,不发 streamGenerateContent)。
852
+ */
853
+ async function resolveProject(credential) {
854
+ const identity = readStringField(credential, 'email') || readStringField(credential, 'sub') || credential.access_token
855
+
856
+ const cached = projectCache.get(identity)
857
+ if (cached) return { project: cached }
858
+
859
+ // 二级:凭据字段(跨启动的落盘缓存)
860
+ const fromCredential = typeof credential.cloudaicompanionProject === 'string' ? credential.cloudaicompanionProject : ''
861
+ if (fromCredential !== '') {
862
+ projectCache.set(identity, fromCredential)
863
+ return { project: fromCredential }
864
+ }
865
+
866
+ // 三级:现探
867
+ let lastError = ''
868
+ for (const endpoint of PROBE_ENDPOINTS) {
869
+ try {
870
+ const response = await httpFetch(`${endpoint}${LOAD_CODE_ASSIST_PATH}`, {
871
+ method: 'POST',
872
+ headers: probeHeaders(credential),
873
+ body: LOAD_CODE_ASSIST_BODY,
874
+ }, PROBE_TIMEOUT_MS)
875
+ if (!response.ok) {
876
+ lastError = `loadCodeAssist HTTP ${response.status}`
877
+ continue
878
+ }
879
+ const text = await response.text().catch(() => '')
880
+ if (text === '') {
881
+ lastError = 'loadCodeAssist 返回空响应'
882
+ continue
883
+ }
884
+ const project = parseProject(JSON.parse(text))
885
+ if (project !== '') {
886
+ projectCache.set(identity, project)
887
+ return { project }
888
+ }
889
+ // ⚠️ 探测成功但项目号为空 = 免费档常态,不是失败 —— 回落兜底串照常发推理。
890
+ return { project: DEFAULT_PROJECT }
891
+ } catch (error) {
892
+ lastError = error instanceof Error ? error.message : String(error)
893
+ }
894
+ }
895
+ return { project: '', error: lastError === '' ? 'loadCodeAssist 探测失败' : lastError }
896
+ }
897
+
898
+ /** 消息转换(请求方向)。 */
899
+
900
+ /** 工具参数 JSON 解析;失败/非对象退化为 {}(不编造参数)。 */
901
+ function parseToolArguments(raw) {
902
+ const text = String(raw ?? '').trim()
903
+ if (text === '') return {}
904
+ try {
905
+ const parsed = JSON.parse(text)
906
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
907
+ } catch {
908
+ return {}
909
+ }
910
+ }
911
+
912
+ /** content 归一化为字符串(system/tool 结果用)。数组只拼 text 块。 */
913
+ function contentText(content) {
914
+ if (typeof content === 'string') return content
915
+ if (Array.isArray(content)) {
916
+ return content
917
+ .filter(block => block !== null && typeof block === 'object' && block.type === 'text')
918
+ .map(block => String(block.text ?? ''))
919
+ .join('\n')
920
+ }
921
+ return ''
922
+ }
923
+
924
+ /** 校验 base64 可用(先宽松清洗换行/空格再判 —— 上游接受带换行的 base64)。 */
925
+ function normalizeBase64(data) {
926
+ if (data === '') return undefined
927
+ const cleaned = data.replace(/[\n\r\s]/g, '')
928
+ if (cleaned === '') return undefined
929
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(cleaned)) return undefined
930
+ if (cleaned.length % 4 !== 0) return undefined
931
+ return cleaned
932
+ }
933
+
934
+ /** 内联一张图片:data: URL 直接解;http(s) 拉取转 base64。失败显式抛错不静默丢图。 */
935
+ async function resolveInlineImage(url) {
936
+ if (typeof url !== 'string' || url === '') {
937
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片地址为空,拒绝发出缺少图片的请求' }
938
+ }
939
+ if (url.startsWith('data:')) {
940
+ const comma = url.indexOf(',')
941
+ if (comma < 0) throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: data URL 图片格式非法' }
942
+ const header = url.slice(5, comma)
943
+ const raw = url.slice(comma + 1)
944
+ const mimeMatch = /^([^;,]+)/.exec(header)
945
+ const mimeType = mimeMatch?.[1] && mimeMatch[1] !== '' ? mimeMatch[1] : 'image/png'
946
+ let payload = raw
947
+ try { payload = decodeURIComponent(raw) } catch { /* 已是裸 base64 */ }
948
+ const data = normalizeBase64(payload)
949
+ if (data === undefined) throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片编码不是合法 base64' }
950
+ if (data.length * 3 / 4 > MAX_IMAGE_BYTES_INLINE) {
951
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 图片体积超过上游内联上限 ${MAX_IMAGE_BYTES_INLINE} 字节` }
952
+ }
953
+ return { mimeType, data }
954
+ }
955
+ if (url.startsWith('http://') || url.startsWith('https://')) {
956
+ const response = await httpFetch(url, { method: 'GET' }, 20_000).catch(() => null)
957
+ if (response === null || !response.ok) {
958
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片下载失败,拒绝发出缺少图片的请求' }
959
+ }
960
+ const declared = (response.headers?.get?.('content-type') ?? '').split(';')[0].trim()
961
+ const mimeType = declared.startsWith('image/') ? declared : 'image/png'
962
+ const buffer = Buffer.from(await response.arrayBuffer())
963
+ if (buffer.byteLength > MAX_IMAGE_BYTES_INLINE) {
964
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 图片体积 ${buffer.byteLength} 字节超过上游内联上限 ${MAX_IMAGE_BYTES_INLINE} 字节` }
965
+ }
966
+ const data = normalizeBase64(buffer.toString('base64'))
967
+ if (data === undefined) throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: 图片编码不是合法 base64' }
968
+ return { mimeType, data }
969
+ }
970
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 不支持的图片地址协议,拒绝发出缺少图片的请求` }
971
+ }
972
+
973
+ /** 把 OpenAI content 的文本/图片块追加进 parts(图片显式抛错,绝不静默丢图)。 */
974
+ async function pushContentParts(parts, content) {
975
+ if (typeof content === 'string') {
976
+ if (content !== '') parts.push({ text: content })
977
+ return
978
+ }
979
+ if (!Array.isArray(content)) return
980
+ for (const block of content) {
981
+ if (block === null || typeof block !== 'object') continue
982
+ if (block.type === 'text') {
983
+ const text = typeof block.text === 'string' ? block.text : ''
984
+ if (text !== '') parts.push({ text })
985
+ continue
986
+ }
987
+ if (block.type === 'image_url') {
988
+ const url = block.image_url?.url
989
+ if (typeof url !== 'string' || url === '') continue
990
+ const inline = await resolveInlineImage(url)
991
+ parts.push({ inlineData: { mimeType: inline.mimeType, data: inline.data } })
992
+ }
993
+ }
994
+ }
995
+
996
+ /**
997
+ * 把 OpenAI wire 消息转成 Gemini contents + systemInstruction。
998
+ * ⚠️ role 只有 user/model;system 单独承载进 systemInstruction(真把 system 当
999
+ * user 发会让模型把它当用户指令)。
1000
+ * ⚠️ tool_call/result 配对:一批 tool_calls 只有全部拿到结果才保留(部分保留会
1001
+ * 留下无结果的 tool_call,上游照样拒绝);functionResponse 以 name 配对,空 name
1002
+ * 整块丢弃(丢了顶多少一轮工具上下文,不会打死整轮)。
1003
+ */
1004
+ async function buildContents(messages) {
1005
+ const systemParts = []
1006
+ const toolNames = new Map()
1007
+ const resultIds = new Set()
1008
+ for (const message of messages) {
1009
+ if (message === null || typeof message !== 'object') continue
1010
+ if (message.role === 'assistant' && Array.isArray(message.tool_calls)) {
1011
+ for (const call of message.tool_calls) {
1012
+ const id = typeof call?.id === 'string' ? call.id : ''
1013
+ const name = typeof call?.function?.name === 'string' ? call.function.name.trim() : ''
1014
+ if (id !== '') toolNames.set(id, name)
1015
+ }
1016
+ }
1017
+ if (message.role === 'tool' && typeof message.tool_call_id === 'string') resultIds.add(message.tool_call_id)
1018
+ }
1019
+ const keepCallIds = new Set()
1020
+ for (const message of messages) {
1021
+ if (message === null || typeof message !== 'object' || message.role !== 'assistant' || !Array.isArray(message.tool_calls)) continue
1022
+ const usable = message.tool_calls.filter(call => call !== null && typeof call === 'object' && typeof call.function?.name === 'string' && call.function.name.trim() !== '')
1023
+ if (usable.length === 0) continue
1024
+ if (usable.every(call => resultIds.has(String(call.id)))) {
1025
+ for (const call of usable) keepCallIds.add(String(call.id))
1026
+ }
1027
+ }
1028
+ const keepResultIds = new Set([...keepCallIds].filter(id => resultIds.has(id)))
1029
+
1030
+ const contents = []
1031
+ for (const message of messages) {
1032
+ if (message === null || typeof message !== 'object' || typeof message.role !== 'string') continue
1033
+ // system/developer 由 systemInstruction 单独承载,显式跳过。
1034
+ if (message.role === 'system' || message.role === 'developer') {
1035
+ const text = contentText(message.content)
1036
+ if (text !== '') systemParts.push(text)
1037
+ continue
1038
+ }
1039
+ const role = message.role === 'assistant' ? 'model' : 'user'
1040
+ const parts = []
1041
+ if (message.role === 'tool') {
1042
+ const id = typeof message.tool_call_id === 'string' ? message.tool_call_id : ''
1043
+ if (keepResultIds.has(id)) {
1044
+ const name = toolNames.get(id) ?? ''
1045
+ if (name !== '') parts.push({ functionResponse: { name, response: { content: contentText(message.content) } } })
1046
+ }
1047
+ } else {
1048
+ await pushContentParts(parts, message.content)
1049
+ if (Array.isArray(message.tool_calls)) {
1050
+ for (const call of message.tool_calls) {
1051
+ const id = String(call?.id ?? '')
1052
+ const name = typeof call?.function?.name === 'string' ? call.function.name.trim() : ''
1053
+ if (!keepCallIds.has(id) || name === '') continue
1054
+ const args = parseToolArguments(call.function?.arguments)
1055
+ const argsJson = canonicalArgs(args)
1056
+ const part = { functionCall: { name, args } }
1057
+ // 签名从本地缓存查(OpenAI 消息不携带签名);查不到就不带签名发,
1058
+ // 上游拒时走「去签重试一次」路径。
1059
+ const signature = sigGet(name, argsJson) ?? sigLatestForTool(name)
1060
+ if (signature !== undefined && signature !== '') part.thoughtSignature = signature
1061
+ parts.push(part)
1062
+ }
1063
+ }
1064
+ }
1065
+ if (parts.length === 0) continue
1066
+ contents.push({ role, parts })
1067
+ }
1068
+ return { contents, systemText: systemParts.join('\n\n') }
1069
+ }
1070
+
1071
+ /** 取首条 user 消息的首个文本 part(sessionId 派生的输入之一)。 */
1072
+ function firstUserText(contents) {
1073
+ for (const content of contents) {
1074
+ if (content.role !== '' && content.role !== 'user') continue
1075
+ for (const part of content.parts) {
1076
+ if (typeof part.text === 'string' && part.text !== '') return part.text
1077
+ }
1078
+ }
1079
+ return ''
1080
+ }
1081
+
1082
+ // ── JSON Schema 清洗(逐条规则)───────────────────────────────────────────────
1083
+
1084
+ /** Gemini FunctionDeclaration.parameters 接受的键白名单(白名单外的键是硬 400)。 */
1085
+ const SCHEMA_KEYS = new Set([
1086
+ 'type', 'format', 'description', 'nullable', 'enum', 'items', 'minItems', 'maxItems',
1087
+ 'properties', 'required', 'minProperties', 'maxProperties', 'minLength', 'maxLength',
1088
+ 'pattern', 'anyOf', 'propertyOrdering', 'minimum', 'maximum',
1089
+ ])
1090
+
1091
+ function sanitizeGeminiSchema(schema) {
1092
+ if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) return {}
1093
+ const out = {}
1094
+ for (const [key, value] of Object.entries(schema)) {
1095
+ if (!SCHEMA_KEYS.has(key)) continue
1096
+ if (key === 'properties') {
1097
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) continue
1098
+ const properties = {}
1099
+ for (const [name, child] of Object.entries(value)) {
1100
+ if (child === null || typeof child !== 'object' || Array.isArray(child)) continue
1101
+ properties[name] = sanitizeGeminiSchema(child)
1102
+ }
1103
+ out.properties = properties
1104
+ continue
1105
+ }
1106
+ if (key === 'items') {
1107
+ if (Array.isArray(value)) {
1108
+ out.items = value
1109
+ .filter(item => item !== null && typeof item === 'object' && !Array.isArray(item))
1110
+ .map(item => sanitizeGeminiSchema(item))
1111
+ continue
1112
+ }
1113
+ if (value !== null && typeof value === 'object') out.items = sanitizeGeminiSchema(value)
1114
+ continue
1115
+ }
1116
+ if (key === 'anyOf') {
1117
+ if (!Array.isArray(value)) continue
1118
+ out.anyOf = value
1119
+ .filter(item => item !== null && typeof item === 'object' && !Array.isArray(item))
1120
+ .map(item => sanitizeGeminiSchema(item))
1121
+ continue
1122
+ }
1123
+ if (key === 'type') {
1124
+ if (typeof value === 'string') { out.type = value; continue }
1125
+ if (Array.isArray(value)) {
1126
+ const types = value.filter(item => typeof item === 'string')
1127
+ const nonNull = types.filter(item => item !== 'null')
1128
+ if (nonNull.length > 0) out.type = nonNull[0]
1129
+ // 出现 'null' ⇒ 该字段可空,用 nullable 表达。
1130
+ if (nonNull.length !== types.length) out.nullable = true
1131
+ }
1132
+ continue
1133
+ }
1134
+ if (key === 'enum') {
1135
+ // enum 只要含任何非字符串值就整删(Gemini 只接受字符串枚举)。
1136
+ if (Array.isArray(value) && value.every(item => typeof item === 'string')) out.enum = [...value]
1137
+ continue
1138
+ }
1139
+ out[key] = value
1140
+ }
1141
+ return out
1142
+ }
1143
+
1144
+ /** 工具定义 → functionDeclarations(schema 清洗后下发)。 */
1145
+ function buildTools(tools) {
1146
+ if (!Array.isArray(tools)) return undefined
1147
+ const declarations = []
1148
+ for (const tool of tools) {
1149
+ const fn = tool?.function
1150
+ if (fn === null || typeof fn !== 'object' || typeof fn.name !== 'string' || fn.name.trim() === '') continue
1151
+ declarations.push({
1152
+ name: fn.name,
1153
+ ...(typeof fn.description === 'string' && fn.description !== '' ? { description: fn.description } : {}),
1154
+ parameters: sanitizeGeminiSchema(fn.parameters !== null && typeof fn.parameters === 'object' && !Array.isArray(fn.parameters) ? fn.parameters : {}),
1155
+ })
1156
+ }
1157
+ return declarations.length > 0 ? [{ functionDeclarations: declarations }] : undefined
1158
+ }
1159
+
1160
+ /** tool_choice → toolConfig.functionCallingConfig(OpenAI 形态 + 别名)。 */
1161
+ function buildToolConfig(toolChoice, hasTools) {
1162
+ if (!hasTools) return undefined
1163
+ let mode = 'AUTO'
1164
+ let name
1165
+ if (toolChoice === 'none') mode = 'NONE'
1166
+ else if (toolChoice === 'any' || toolChoice === 'required') mode = 'ANY'
1167
+ else if (toolChoice !== null && typeof toolChoice === 'object') {
1168
+ const type = toolChoice.type
1169
+ if (type === 'none') mode = 'NONE'
1170
+ else if (type === 'any' || type === 'tool' || type === 'function') mode = 'ANY'
1171
+ const rawName = typeof toolChoice.name === 'string' && toolChoice.name !== '' ? toolChoice.name
1172
+ : typeof toolChoice.function?.name === 'string' && toolChoice.function.name !== '' ? toolChoice.function.name
1173
+ : typeof toolChoice.tool?.name === 'string' && toolChoice.tool.name !== '' ? toolChoice.tool.name
1174
+ : undefined
1175
+ name = rawName
1176
+ }
1177
+ return { functionCallingConfig: { mode, ...(mode === 'ANY' && name !== undefined ? { allowedFunctionNames: [name] } : {}) } }
1178
+ }
1179
+
1180
+ // ── 响应翻译(Gemini 帧 → OpenAI chunk)─────────────────────────────────────
1181
+
1182
+ /** usageMetadata → OpenAI usage(thoughts 是 output 子集,并入 completion_tokens)。 */
1183
+ function readUsage(raw) {
1184
+ if (raw === null || typeof raw !== 'object') return undefined
1185
+ const prompt = nonNegativeInt(raw.promptTokenCount)
1186
+ const candidates = nonNegativeInt(raw.candidatesTokenCount)
1187
+ const thoughts = nonNegativeInt(raw.thoughtsTokenCount)
1188
+ const total = nonNegativeInt(raw.totalTokenCount)
1189
+ const cached = nonNegativeInt(raw.cachedContentTokenCount) ?? 0
1190
+ if (prompt === undefined && candidates === undefined && total === undefined) return undefined
1191
+ const out = {}
1192
+ if (prompt !== undefined) out.prompt_tokens = prompt
1193
+ if (candidates !== undefined || thoughts !== undefined) out.completion_tokens = (candidates ?? 0) + (thoughts ?? 0)
1194
+ if (total !== undefined) out.total_tokens = total
1195
+ if (cached > 0) out.prompt_tokens_details = { cached_tokens: cached }
1196
+ return out
1197
+ }
1198
+
1199
+ /** 上游 finishReason → OpenAI finish_reason。未知/缺失一律 stop(不编造成 error)。 */
1200
+ function mapFinishReason(reason, toolCount) {
1201
+ if (toolCount > 0) return 'tool_calls'
1202
+ const text = typeof reason === 'string' ? reason.toUpperCase() : ''
1203
+ if (text === 'MAX_TOKENS') return 'length'
1204
+ return 'stop'
1205
+ }
1206
+
1207
+ // ── SSE 消费(关键语义)───────────────────────────────────────────────────────────
1208
+
1209
+ /** 读一块数据,带空闲超时与取消信号(裸 reader.read() 会无限期挂起)。 */
1210
+ function readChunk(reader, timeoutMs, signal) {
1211
+ return new Promise((resolve, reject) => {
1212
+ let settled = false
1213
+ const timer = setTimeout(() => finish(new Error('idle')), timeoutMs)
1214
+ const onAbort = () => finish(new Error('abort'))
1215
+ signal?.addEventListener('abort', onAbort, { once: true })
1216
+ function finish(error) {
1217
+ if (settled) return
1218
+ settled = true
1219
+ clearTimeout(timer)
1220
+ signal?.removeEventListener('abort', onAbort)
1221
+ reject(error)
1222
+ }
1223
+ reader.read().then(
1224
+ value => {
1225
+ if (settled) return
1226
+ settled = true
1227
+ clearTimeout(timer)
1228
+ signal?.removeEventListener('abort', onAbort)
1229
+ resolve(value)
1230
+ },
1231
+ error => finish(error),
1232
+ )
1233
+ })
1234
+ }
1235
+
1236
+ /** 处理一行 SSE,返回 data: 载荷。`:` 注释行 / event: 行跳过;单行 data(实测)。 */
1237
+ function ssePayload(rawLine) {
1238
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
1239
+ if (line === '' || line.startsWith(':') || line.startsWith('event:')) return undefined
1240
+ if (!line.startsWith('data:')) return undefined
1241
+ return line.slice(5).trim()
1242
+ }
1243
+
1244
+ /**
1245
+ * 消费上游 SSE,把每个内容帧翻译成 OpenAI chunk 文本帧。
1246
+ * ⚠️ 只有 candidates 非空才算内容帧(纯 usageMetadata 收尾帧继续读);
1247
+ * ⚠️ 收尾余量必须按整行再走一遍(否则末帧 finishReason/usage 被静默丢弃);
1248
+ * ⚠️ 用量取「见过的最大 totalTokenCount」那一份(上游多帧重复播报,早期帧偏小)。
1249
+ */
1250
+ async function consumeStream(body, emit, signal, idleTimeoutMs) {
1251
+ const reader = body.getReader()
1252
+ const decoder = new TextDecoder()
1253
+ let buffer = ''
1254
+ let sawContent = false
1255
+ let finishReason
1256
+ let toolCount = 0
1257
+ let usage
1258
+ let usageTotal = -1
1259
+
1260
+ const noteUsage = raw => {
1261
+ if (raw === null || typeof raw !== 'object') return
1262
+ const total = nonNegativeInt(raw.totalTokenCount) ?? -1
1263
+ if (total < usageTotal) return
1264
+ usageTotal = total
1265
+ usage = readUsage(raw)
1266
+ }
1267
+
1268
+ try {
1269
+ for (;;) {
1270
+ let chunk
1271
+ try {
1272
+ chunk = await readChunk(reader, sawContent ? idleTimeoutMs : IDLE_TIMEOUT_MS, signal)
1273
+ } catch (error) {
1274
+ if (signal?.aborted) throw Object.assign(new Error('已取消'), { name: 'AbortError' })
1275
+ if (error instanceof Error && error.message === 'idle') {
1276
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Gemini 流空闲超时(上游长时间未输出)' }
1277
+ }
1278
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Gemini 流读取失败:${error?.message ?? error}` }
1279
+ }
1280
+ if (chunk.done) {
1281
+ // ⚠️ 收尾:先刷解码器残留,再把 buffer 余量按整行走一遍。
1282
+ buffer += decoder.decode()
1283
+ const tail = buffer.split('\n')
1284
+ buffer = ''
1285
+ for (const rawLine of tail) {
1286
+ const payload = ssePayload(rawLine)
1287
+ if (payload !== undefined) processFrame(payload)
1288
+ }
1289
+ break
1290
+ }
1291
+ buffer += decoder.decode(chunk.value, { stream: true })
1292
+ const lines = buffer.split('\n')
1293
+ buffer = lines.pop() ?? ''
1294
+ for (const rawLine of lines) {
1295
+ const payload = ssePayload(rawLine)
1296
+ if (payload !== undefined) processFrame(payload)
1297
+ }
1298
+ }
1299
+ } finally {
1300
+ reader.cancel().catch(() => {})
1301
+ }
1302
+
1303
+ function processFrame(payload) {
1304
+ if (payload === '' || payload === '[DONE]') return
1305
+ let parsed
1306
+ try { parsed = JSON.parse(payload) } catch { return }
1307
+ if (parsed === null || typeof parsed !== 'object') return
1308
+ // 先试信封形态 {"response":{…}},再试裸 Response(同序)。
1309
+ const inner = parsed.response !== null && typeof parsed.response === 'object' ? parsed.response : parsed
1310
+ const candidates = inner.candidates
1311
+ noteUsage(inner.usageMetadata)
1312
+ if (!Array.isArray(candidates) || candidates.length === 0) return
1313
+ const candidate = candidates[0]
1314
+ if (typeof candidate?.finishReason === 'string' && candidate.finishReason !== '') finishReason = candidate.finishReason
1315
+ for (const part of candidate.content?.parts ?? []) {
1316
+ if (part === null || typeof part !== 'object') continue
1317
+ if (part.functionCall !== undefined && part.functionCall !== null) {
1318
+ const name = typeof part.functionCall.name === 'string' ? part.functionCall.name : ''
1319
+ const args = part.functionCall.args ?? {}
1320
+ const argsJson = canonicalArgs(args)
1321
+ // ⚠️ 只存 functionCall 上的签名:Gemini 校验的只有这一个,思考分片上的
1322
+ // 签名回传会被忽略,存了纯属噪音。
1323
+ if (typeof part.thoughtSignature === 'string' && part.thoughtSignature !== '') {
1324
+ sigPut(name, argsJson, part.thoughtSignature)
1325
+ }
1326
+ const id = `gemini_tool_${Date.now().toString(36)}_${toolCount}`
1327
+ toolCount += 1
1328
+ sawContent = true
1329
+ emit({
1330
+ choices: [{
1331
+ index: 0,
1332
+ delta: { tool_calls: [{ index: toolCount - 1, id, type: 'function', function: { name, arguments: argsJson } }] },
1333
+ finish_reason: null,
1334
+ }],
1335
+ })
1336
+ continue
1337
+ }
1338
+ if (typeof part.text !== 'string' || part.text === '') continue
1339
+ if (part.thought === true) {
1340
+ sawContent = true
1341
+ emit({ choices: [{ index: 0, delta: { reasoning_content: part.text }, finish_reason: null }] })
1342
+ continue
1343
+ }
1344
+ sawContent = true
1345
+ emit({ choices: [{ index: 0, delta: { content: part.text }, finish_reason: null }] })
1346
+ }
1347
+ }
1348
+
1349
+ return { sawContent, finishReason, toolCount, usage }
1350
+ }
1351
+
1352
+ // ── 对话主流程(换端点 / 去签重试 / 会话升代 / 错误分类)────────────────────
1353
+
1354
+ /** HTTP 失败 → OMR 错误对象(归类顺序)。 */
1355
+ function failureFrom(status, bodyText) {
1356
+ const message = extractMessage(bodyText) || `Gemini HTTP ${status}`
1357
+ // ⚠️ 上下文超限必须先于 quota 文案判定:超限报文里的 "exceeded" 会被 quota
1358
+ // 关键词吃掉去换号 —— 那是完全无效的动作(归错码的代价不对称)。
1359
+ if (status === 400 && TOKEN_COUNT_OVERFLOW.test(String(bodyText ?? ''))) {
1360
+ return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `Gemini 上下文超限:${message}` }
1361
+ }
1362
+ if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: RATE_LIMIT_COOLDOWN_MS, rotate: true, message }
1363
+ if (status === 400 && hasMarker(bodyText, QUOTA_MARKERS)) {
1364
+ return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
1365
+ }
1366
+ // ⚠️ 403/404 归 server 不归 auth:这两个码在 Cloud Code 上更多是「入口/模型
1367
+ // 注册表不认」,归成 auth 会把用户引向「去重新登录」这个无效动作。
1368
+ if (status === 403 || status === 404) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1369
+ if (status === 401) return { kind: 'auth', retryable: false, cooldownMs: AUTH_COOLDOWN_MS, rotate: true, message }
1370
+ if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1371
+ if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
1372
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1373
+ }
1374
+
1375
+ /** 会话升代计数:按 base sessionId(不含代数)计,进程内持久(服务端按会话累计)。 */
1376
+ const sessionBumps = new Map()
1377
+
1378
+ /**
1379
+ * 单账号一轮对话。上游恒走流式端点,本地聚合为完整 OpenAI 响应返回
1380
+ * { status, json };onData 存在时逐帧发 OpenAI chunk JSON 文本。
1381
+ * 调用方(providers/index.js)负责续期与换号 —— 这里只做端点轮换、去签重试、
1382
+ * 会话升代三类协议内救场,并如实分类错误。
1383
+ */
1384
+ export async function complete(credential, body, { signal, onData, headerTimeoutMs = REQUEST_TIMEOUT_MS } = {}) {
1385
+ if (!credential || typeof credential.access_token !== 'string' || credential.access_token === '') {
1386
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'Gemini 凭据缺少访问令牌,请重新登录' }
1387
+ }
1388
+ const requestedModel = typeof body.model === 'string' ? body.model : ''
1389
+ // ⚠️ 模型名先查表再取凭据:未知 id 立即拒绝(上游对未知模型名静默接受并落回
1390
+ // 3.8,用户选错模型时拿到错误答案且无任何征兆)。
1391
+ const spec = modelSpec(requestedModel, body.reasoning_effort)
1392
+ const headers = {
1393
+ Authorization: `Bearer ${credential.access_token}`,
1394
+ 'Content-Type': 'application/json',
1395
+ ...IDENTITY_HEADERS,
1396
+ // ⚠️ 流式请求刻意不带 Accept(与实际请求一致);也不注入 x-goog-api-key。
1397
+ }
1398
+
1399
+ const messages = Array.isArray(body.messages) ? body.messages : []
1400
+ const { contents, systemText } = await buildContents(messages)
1401
+ // ⚠️ 空 contents 必须抛错:发空请求上游会 400,且错误信息与真实原因毫不相干。
1402
+ if (contents.length === 0) {
1403
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'gemini: messages 里没有可用内容' }
1404
+ }
1405
+ const tools = buildTools(body.tools)
1406
+ const toolConfig = buildToolConfig(body.tool_choice, tools !== undefined)
1407
+
1408
+ // project 必须按当前凭据解析;探测失败不发推理。
1409
+ const probe = await resolveProject(credential)
1410
+ if (probe.error !== undefined) {
1411
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `gemini: 项目号探测失败,未发推理 — ${probe.error}` }
1412
+ }
1413
+ const project = probe.project
1414
+ const firstText = firstUserText(contents)
1415
+
1416
+ const generationConfig = {
1417
+ maxOutputTokens: typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0
1418
+ ? Math.floor(body.max_tokens)
1419
+ : MAX_OUTPUT_TOKENS,
1420
+ // ⚠️ includeThoughts 恒 true(「关闭思考」是假关:关掉照样思考照样计费)。
1421
+ thinkingConfig: { includeThoughts: true, ...(spec.thinkingBudget >= 0 ? { thinkingBudget: spec.thinkingBudget } : {}) },
1422
+ ...(typeof body.temperature === 'number' && Number.isFinite(body.temperature) ? { temperature: body.temperature } : {}),
1423
+ }
1424
+
1425
+ const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
1426
+ const created = Math.floor(Date.now() / 1000)
1427
+
1428
+ let endpointIdx = 0
1429
+ let endpointSwitched = false
1430
+ let droppedSignatures = false
1431
+
1432
+ for (;;) {
1433
+ // sessionId 两段式派生:先算 base(不含代数),再按升代计数取值。
1434
+ const baseSessionId = deriveSessionId(project, firstText, SESSION_LANE_INFER)
1435
+ const generation = sessionBumps.get(baseSessionId) ?? 0
1436
+ const sessionId = generation > 0 ? deriveSessionId(project, firstText, SESSION_LANE_INFER, generation) : baseSessionId
1437
+
1438
+ // ⚠️ 去签重试必须真正剥离签名:buildContents 在循环外只跑一次(图片内联昂贵,
1439
+ // 不能重跑),所以这里对 contents 深拷贝剥掉所有 thoughtSignature(等价于
1440
+ // 查不到签名时重建信封)。直接 continue 会让
1441
+ // 重试仍带原签名,白白再吃一次 400。
1442
+ const effectiveContents = droppedSignatures
1443
+ ? contents.map(content => ({
1444
+ ...content,
1445
+ parts: content.parts.map(part => {
1446
+ if (part === null || typeof part !== 'object' || part.thoughtSignature === undefined) return part
1447
+ const { thoughtSignature: _dropped, ...rest } = part
1448
+ return rest
1449
+ }),
1450
+ }))
1451
+ : contents
1452
+
1453
+ const request = {
1454
+ contents: effectiveContents,
1455
+ generationConfig,
1456
+ sessionId,
1457
+ ...(systemText !== '' ? { systemInstruction: { role: 'system', parts: [{ text: systemText }] } } : {}),
1458
+ ...(tools !== undefined ? { tools } : {}),
1459
+ ...(toolConfig !== undefined ? { toolConfig } : {}),
1460
+ }
1461
+ const wire = marshalAlphabetical({
1462
+ model: spec.upstream,
1463
+ project,
1464
+ request,
1465
+ requestId: newRequestId(),
1466
+ userAgent: UPSTREAM_USER_AGENT,
1467
+ })
1468
+ const wireBytes = Buffer.byteLength(wire, 'utf8')
1469
+ if (wireBytes > MAX_REQUEST_BODY_BYTES) {
1470
+ throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: `gemini: 请求体 ${wireBytes} 字节超过上限 ${MAX_REQUEST_BODY_BYTES} 字节` }
1471
+ }
1472
+
1473
+ let response
1474
+ try {
1475
+ response = await httpFetch(`${ENDPOINTS[endpointIdx] ?? ENDPOINTS[0]}${STREAM_PATH}`, {
1476
+ method: 'POST',
1477
+ headers,
1478
+ body: wire,
1479
+ signal,
1480
+ }, headerTimeoutMs)
1481
+ } catch (error) {
1482
+ if (signal?.aborted) throw error
1483
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Gemini 请求发送失败:${error?.message ?? error}` }
1484
+ }
1485
+
1486
+ if (!response.ok) {
1487
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1488
+ // 1. 签名被拒 → 去签重试一次(同账号同端点)。
1489
+ if (isSignatureError(text) && !droppedSignatures) {
1490
+ droppedSignatures = true
1491
+ continue
1492
+ }
1493
+ // 2. 服务端会话累计超 1M → 升代换全新 sessionId 重发(削本地历史没用,
1494
+ // 累计在服务端、按 sessionId 计;换端点/换号也无效)。
1495
+ if (response.status === 400 && String(text).toLowerCase().includes(SESSION_OVERFLOW_MARKER)) {
1496
+ const bumped = sessionBumps.get(baseSessionId) ?? 0
1497
+ if (bumped < MAX_SESSION_BUMPS) {
1498
+ sessionBumps.set(baseSessionId, bumped + 1)
1499
+ continue
1500
+ }
1501
+ }
1502
+ // 3. 上下文超限:不换端点不换号(请求体本身太大,白跑两轮)。
1503
+ if (response.status === 400 && TOKEN_COUNT_OVERFLOW.test(text)) throw failureFrom(response.status, text)
1504
+ // 4. 先换端点(廉价兜底,一次):403/404、400+quota 类文案、429。
1505
+ const endpointFirst = response.status === 403
1506
+ || response.status === 404
1507
+ || (response.status === 400 && hasMarker(text, SWITCHABLE_MARKERS))
1508
+ if ((endpointFirst || response.status === 429) && !endpointSwitched) {
1509
+ endpointSwitched = true
1510
+ endpointIdx = endpointIdx === 0 ? 1 : 0
1511
+ continue
1512
+ }
1513
+ throw failureFrom(response.status, text)
1514
+ }
1515
+ if (!response.body) {
1516
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Gemini 返回空响应体' }
1517
+ }
1518
+
1519
+ // 消费 SSE:逐帧翻译成 OpenAI chunk,喂 onData 并留档聚合。
1520
+ const chunks = []
1521
+ let firstChunk = true
1522
+ const emit = chunk => {
1523
+ const full = {
1524
+ id: chunkId,
1525
+ object: 'chat.completion.chunk',
1526
+ created,
1527
+ model: requestedModel,
1528
+ choices: chunk.choices.map(choice => ({
1529
+ ...choice,
1530
+ delta: firstChunk ? { role: 'assistant', ...choice.delta } : choice.delta,
1531
+ })),
1532
+ ...(chunk.usage !== undefined ? { usage: chunk.usage } : {}),
1533
+ }
1534
+ firstChunk = false
1535
+ chunks.push(full)
1536
+ onData?.(JSON.stringify(full))
1537
+ }
1538
+ const consumed = await consumeStream(response.body, emit, signal, IDLE_TIMEOUT_MS)
1539
+
1540
+ // ⚠️ 空响应必须报错:静默结束会让上层认为「模型正常回答但没内容」,不会重试。
1541
+ if (!consumed.sawContent) {
1542
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'gemini: 模型未返回任何内容块' }
1543
+ }
1544
+ const finalChunk = {
1545
+ choices: [{ index: 0, delta: {}, finish_reason: mapFinishReason(consumed.finishReason, consumed.toolCount) }],
1546
+ ...(consumed.usage !== undefined ? { usage: consumed.usage } : {}),
1547
+ }
1548
+ chunks.push({ id: chunkId, object: 'chat.completion.chunk', created, model: requestedModel, ...finalChunk })
1549
+ onData?.(JSON.stringify(chunks[chunks.length - 1]))
1550
+
1551
+ const merged = mergeSseChunks(chunks.map(chunk => JSON.stringify(chunk)))
1552
+ if (!merged || !merged.choices?.[0]) {
1553
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Gemini 流结束但没有内容帧' }
1554
+ }
1555
+ merged.model = requestedModel
1556
+ // mergeSseChunks 只在首个内容帧时快照 usage(用量帧在后会被丢),此处显式回填。
1557
+ if (consumed.usage !== undefined) merged.usage = consumed.usage
1558
+ return { status: response.status, json: merged }
1559
+ }
1560
+ }
1561
+
1562
+ // ── 配额窗口余额(只做余额;Gemini 无签到)───────────────────────────────────────
1563
+
1564
+ /**
1565
+ * ⚠️ 这不是「充值积分」,是 Gemini 免费线的**配额窗口**(5 小时 / 周两个窗口的
1566
+ * 剩余比例)。面板如实显示「5 小时窗口 99% / 周窗口 99%」,不换算成任何积分数字。
1567
+ *
1568
+ * ⚠️ 端点走 **sandbox**(配额查询路径固定路由到 sandbox),
1569
+ * 身份头与推理请求完全一致({@link probeHeaders},含五个伪装头 + Bearer)。
1570
+ *
1571
+ * ⚠️ 本项目渠道契约要求返回 {@link CreditBalance} 或 null(契约无 error?/tier? 字段)。
1572
+ * 「未授权」在本项目里也用 null 表达,不区分「没登录」与「查询失败」)。
1573
+ */
1574
+
1575
+ /** retrieveUserQuotaSummary 路径(普通 JSON,不是 protobuf)。 */
1576
+ const QUOTA_PATH = '/v1internal:retrieveUserQuotaSummary'
1577
+ /** 5 小时 / 周两个窗口的桶 id。⚠️ 判据是 bucketId,**不按 displayName/window** —— 显示名会被上游改文案。 */
1578
+ const BUCKET_FIVE_HOUR = 'gemini-5h'
1579
+ const BUCKET_WEEKLY = 'gemini-weekly'
1580
+ /** 面板显示名(配额是百分比窗口,不是积分,故不写「积分」二字)。 */
1581
+ const WINDOW_LABEL_FIVE_HOUR = '5 小时窗口'
1582
+ const WINDOW_LABEL_WEEKLY = '周窗口'
1583
+ /** 配额单位:剩余**百分比**。 */
1584
+ const QUOTA_UNIT = '%'
1585
+ /** 配额缓存 TTL(面板 30 秒刷一次,60 秒缓存既扛连续刷新又不至滞后太久)。 */
1586
+ const QUOTA_CACHE_TTL_MS = 60_000
1587
+
1588
+ /**
1589
+ * 60 秒缓存。
1590
+ * 键 = access_token(账号的稳定标识,配额本身按 token 归属);值 = CreditBalance | null。
1591
+ * ⚠️ 缓存的是**适配后**的 null(失败结果同样缓存,避免连续刷新反复打上游)。
1592
+ */
1593
+ const quotaCache = new Map()
1594
+
1595
+ /** 剩余比例 0..1 → 百分比整数(0..100,越界收敛)。 */
1596
+ function quotaPercent(fraction) {
1597
+ const clamped = Math.min(1, Math.max(0, fraction))
1598
+ return Math.round(clamped * 100)
1599
+ }
1600
+
1601
+ /** 一个窗口 → 一个 CreditPackage(单位是百分比,不是积分)。 */
1602
+ function makeQuotaPackage(label, resetTime, fraction) {
1603
+ const remaining = quotaPercent(fraction)
1604
+ return {
1605
+ name: label,
1606
+ unit: QUOTA_UNIT,
1607
+ remaining,
1608
+ total: 100,
1609
+ used: 100 - remaining,
1610
+ active: true,
1611
+ cycleStartTime: '',
1612
+ // 上游自报的重置时刻原样透传;其余周期字段无对应概念,留空串(不编造)。
1613
+ cycleEndTime: resetTime,
1614
+ expiredTime: '',
1615
+ }
1616
+ }
1617
+
1618
+ /**
1619
+ * 解析单个桶。
1620
+ * ⚠️ `remainingFraction` 必须是有限 number;`resetTime` 必须是可被 `Date.parse`
1621
+ * 解析的字符串,**否则整条桶丢弃**(拿不到可解析的重置时间就无法表达窗口周期,
1622
+ * 编一个空串会让面板显示一个永远不过期的窗口 —— 宁可少一个包,也不伪造)。
1623
+ */
1624
+ function parseQuotaBucket(raw) {
1625
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
1626
+ const bucketId = typeof raw.bucketId === 'string' ? raw.bucketId : ''
1627
+ if (bucketId === '') return undefined
1628
+ const fraction = raw.remainingFraction
1629
+ if (typeof fraction !== 'number' || !Number.isFinite(fraction)) return undefined
1630
+ const resetTime = typeof raw.resetTime === 'string' ? raw.resetTime : ''
1631
+ if (resetTime === '' || Number.isNaN(Date.parse(resetTime))) return undefined
1632
+ return { bucketId, resetTime, fraction }
1633
+ }
1634
+
1635
+ /**
1636
+ * 从响应体里挑出两个 Gemini 桶(形状:`groups[].buckets[]`,普通 JSON)。
1637
+ * 响应里第三组桶(`3p-*`)属于 Claude/GPT 产品线,与本 provider 无关,按 id 自然跳过。
1638
+ */
1639
+ function parseQuotaWindows(payload) {
1640
+ let fiveHour
1641
+ let weekly
1642
+ if (payload === null || typeof payload !== 'object') return { fiveHour, weekly }
1643
+ const groups = payload.groups
1644
+ if (!Array.isArray(groups)) return { fiveHour, weekly }
1645
+ for (const group of groups) {
1646
+ if (group === null || typeof group !== 'object' || Array.isArray(group)) continue
1647
+ const buckets = group.buckets
1648
+ if (!Array.isArray(buckets)) continue
1649
+ for (const bucket of buckets) {
1650
+ const parsed = parseQuotaBucket(bucket)
1651
+ if (parsed === undefined) continue
1652
+ if (parsed.bucketId === BUCKET_FIVE_HOUR && fiveHour === undefined) fiveHour = parsed
1653
+ if (parsed.bucketId === BUCKET_WEEKLY && weekly === undefined) weekly = parsed
1654
+ }
1655
+ }
1656
+ return { fiveHour, weekly }
1657
+ }
1658
+
1659
+ /**
1660
+ * 两个窗口 → 插件统一的 CreditBalance。
1661
+ * ⚠️ 两个桶都没认出来 ⇒ null(真失败),**不伪造 100%**(空余额会被渲染成「0」,
1662
+ * 让用户误以为额度用光,比「查询失败」更误导)。
1663
+ * ⚠️ `total` 取两窗口剩余百分比的**平均**(取 min 会把「周 99% / 5h 20%」显示成 20%)。
1664
+ * ⚠️ `expiredTotal` 恒 0:配额窗口没有「过期积分」这个概念。
1665
+ */
1666
+ function toQuotaBalance(fiveHour, weekly) {
1667
+ const packages = []
1668
+ if (fiveHour !== undefined) packages.push(makeQuotaPackage(WINDOW_LABEL_FIVE_HOUR, fiveHour.resetTime, fiveHour.fraction))
1669
+ if (weekly !== undefined) packages.push(makeQuotaPackage(WINDOW_LABEL_WEEKLY, weekly.resetTime, weekly.fraction))
1670
+ if (packages.length === 0) return null
1671
+ const sum = packages.reduce((acc, item) => acc + item.remaining, 0)
1672
+ return {
1673
+ total: roundCredits(sum / packages.length),
1674
+ packages,
1675
+ expiredTotal: 0,
1676
+ }
1677
+ }
1678
+
1679
+ /**
1680
+ * 查询 Gemini 配额窗口余额(**只读**;Gemini 无签到端点,故不实现 claimCredits)。
1681
+ *
1682
+ * ⚠️ **本函数不抛错**:未授权 / 网络失败 / HTTP 非 2xx / 响应非 JSON / 两个桶都没
1683
+ * 认出来 —— 一律返回 null(批量查询时单账号失败不得中断其余账号)。
1684
+ * ⚠️ 请求体**必须带 `project`**(缺 project 会被上游回 403 SUBSCRIPTION_REQUIRED,
1685
+ * 而凭据其实是好的);字段名是 `project`,**不是** `cloudaicompanionProject`
1686
+ * (后者会 400 Unknown name)。值取凭据里的 `cloudaicompanionProject`,缺失退到
1687
+ * {@link DEFAULT_PROJECT}。
1688
+ */
1689
+ export async function fetchCreditBalance(credential) {
1690
+ const accessToken = readStringField(credential, 'access_token')
1691
+ // ⚠️ 无 access_token:本项目契约用 null 表达。
1692
+ if (accessToken === '') return null
1693
+
1694
+ const cached = quotaCache.get(accessToken)
1695
+ if (cached !== undefined && Date.now() - cached.at < QUOTA_CACHE_TTL_MS) return cached.result
1696
+
1697
+ let result = null
1698
+ try {
1699
+ const project = readStringField(credential, 'cloudaicompanionProject') || DEFAULT_PROJECT
1700
+ const response = await httpFetch(`${ENDPOINT_SANDBOX}${QUOTA_PATH}`, {
1701
+ method: 'POST',
1702
+ // ⚠️ 身份头与推理请求完全一致(含五个伪装头);配额是普通 JSON。
1703
+ headers: probeHeaders(credential),
1704
+ body: JSON.stringify({ project }),
1705
+ }, PROBE_TIMEOUT_MS)
1706
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1707
+ // 非 2xx 直接落 null(不解析错误体 —— 契约里失败就是 null,没有 error 字段)。
1708
+ if (response.ok) {
1709
+ // 普通 JSON(不是 protobuf);解析失败会被外层 catch 兜住 → null。
1710
+ const { fiveHour, weekly } = parseQuotaWindows(JSON.parse(text))
1711
+ result = toQuotaBalance(fiveHour, weekly)
1712
+ }
1713
+ } catch {
1714
+ // 网络失败 / 非 JSON 等一切异常 → null(不得抛)。
1715
+ result = null
1716
+ }
1717
+
1718
+ // 失败结果也缓存,避免连续刷新反复打上游。
1719
+ quotaCache.set(accessToken, { at: Date.now(), result })
1720
+ return result
1721
+ }