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,1619 +1,1619 @@
1
- /**
2
- * Qoder 系渠道 —— Qoder(阿里国际) / QoderCN 共用工厂。
3
- *
4
- * 协议要点:
5
- * - 登录:PKCE 设备码轮询(不起本地回调服务器)——
6
- * 浏览器授权页 {authBase}/device/selectAccounts?challenge&challenge_method=S256
7
- * &nonce&machine_id&client_id(client_id 必须用 prod 的那个),
8
- * 轮询 GET {openApiBase}/api/v1/deviceToken/poll?nonce&verifier&challenge_method=S256,
9
- * **404 = 用户尚未完成授权,继续轮询**(其它非 2xx 是服务端异常)。
10
- * - 续期:POST {openApiBase}/api/v1/deviceToken/refresh,
11
- * body {refresh_token, machine_id};machine_id 必须随凭据持久化并原样回传;
12
- * 401/403 或 200 缺 token → 终态失效。
13
- * - 凭据:security_oauth_token 与 access_token 双写同值(源码取用顺序
14
- * security_oauth_token ?? access_token);uid(user_id)是**加密推理必需**
15
- * (generate_runtime_auth_fields 派生 encrypt_user_info,缺了签名无效)。
16
- * - 对话:只走**加密端点** POST {encryptedInferBase}/algo/api/v2/service/pro/sse/
17
- * agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1。
18
- * 请求体由内嵌 WASM(qoder-auth-wasm.js + qoder-auth-wasm.wasm)加密,
19
- * Authorization 是 WASM 生成的 `Bearer COSY.<载荷>.<签名>`,**必须原样透传**
20
- * (用普通 Bearer 覆盖 = 403 Signature invalid)。
21
- * 该端点认**模型目录 key**(qfmodel 等);公开端点(通用名)不认这些 key。
22
- * host:国际版 api2.qoder.sh / 国内版 gateway.qoder.com.cn(写错 404)。
23
- * - 响应:SSE 每帧多一层信封 `{"headers":…,"body":"<内层 OpenAI chunk JSON>",
24
- * "statusCodeValue":200,"statusCode":"OK"}` —— 内层 body **未加密**,只剥信封;
25
- * 心跳帧(body:null/空对象)整帧跳过;错误帧带 code/message。
26
- * - 错误形态:排队 = 业务码 10605(message 内嵌 JSON 带 retryAfterSeconds,
27
- * 也可能 HTTP 200 + SSE 内嵌帧);额度用尽 = 业务码 110 或文案
28
- * `Billing daily count exceeded`,按自然日(UTC+8)重置 → 冷却到当日 24:00;
29
- * 认证失败 = 业务码 105 / HTTP 401。
30
- * - business 字段({type:'agent'})必填:缺失时服务端把请求路由到故障节点
31
- * oa_qwen-plus-2025-04-28(Execution failed),极易误判「模型服务端故障」。
32
- * - 思考档位白名单:none/low/medium/high/xhigh/max(disabled/off → none),
33
- * 白名单外的档位会被服务端静默丢弃。
34
- * - 模型清单:GET {modelListBase}/algo/api/v2/model/list —— 与加密推理同一套
35
- * 网络契约,必须带 WASM `prepareRequest(auth:'auth')` 生成的 COSY 签名头,
36
- * 普通 Bearer 会 403 Signature invalid。拉不到一律抛错,不回落内置静态表。
37
- */
38
-
39
- import { createHash, randomBytes, randomUUID } from 'node:crypto'
40
- import { spawn } from 'node:child_process'
41
- import { existsSync, readFileSync, readdirSync } from 'node:fs'
42
- import { homedir } from 'node:os'
43
- import { join } from 'node:path'
44
- import { httpFetch, readBodyText, readSseData, mergeSseChunks, roundCredits, utc8Hour } from '../util.js'
45
- import { QoderEncryptedInfer } from './qoder-wasm.js'
46
-
47
- // ── 协议路径与常量 ───────────────────────────────────────────────────────────
48
-
49
- const DEVICE_SELECT_PATH = '/device/selectAccounts'
50
- const POLL_PATH = '/api/v1/deviceToken/poll'
51
- const REFRESH_PATH = '/api/v1/deviceToken/refresh'
52
- const USERINFO_PATH = '/api/v1/userinfo'
53
- /** 模型目录端点(同一个上游网关的 /algo 前缀由 WASM 自动拼接)。 */
54
- const MODEL_LIST_PATH = '/api/v2/model/list'
55
-
56
- const REQUEST_TIMEOUT_MS = 30_000
57
- const MODEL_LIST_TIMEOUT_MS = 30_000
58
- const BODY_READ_TIMEOUT_MS = 15_000
59
- /** 登录等待总超时(源码 5 分钟,放宽到 10 分钟)。 */
60
- const LOGIN_TIMEOUT_MS = 10 * 60_000
61
- /** 轮询间隔(源码 Djr = 1e3)。 */
62
- const POLL_INTERVAL_MS = 1_000
63
- /** 轮询连续网络失败容忍次数。 */
64
- const POLL_MAX_FAILURES = 5
65
- /** 续期提前量:过期前 1 小时即刷。 */
66
- const REFRESH_LEAD_MS = 60 * 60_000
67
-
68
- /**
69
- * 排队处理预算(本实现的偏离说明):
70
- * OMR 的请求方网关层有硬编码超时,等 30 分钟毫无意义,
71
- * 故收紧为总预算 120 秒 / 最多 12 次,单次等待封顶 10s。
72
- */
73
- const QUEUE_TOTAL_BUDGET_MS = 120_000
74
- const QUEUE_MAX_ATTEMPTS = 12
75
- const QUEUE_MAX_DELAY_MS = 10_000
76
-
77
- /** 思考档位白名单(客户端 asar 常量 Qj);别名表 _lc:disabled/off → none。 */
78
- const EFFORT_WHITELIST = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
79
- const EFFORT_ALIASES = { disabled: 'none', off: 'none' }
80
-
81
- /** 排队业务码(客户端 obf 产物 mRA)。 */
82
- const QUEUE_BUSINESS_CODE = '10605'
83
- /** 额度用尽业务码。 */
84
- const BILLING_BUSINESS_CODE = '110'
85
-
86
- /** PKCE 字符集(源码 Y_a:66 字符取模选取,与 RFC 7636 unreserved 一致)。 */
87
- const PKCE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
88
-
89
- // ── 静态模型元数据表(仅补推理参数,**不再是清单来源**)─────────────────────
90
- // 清单由 fetchModels 实时拉取上游目录;这张表只在 complete() 里给已知模型补
91
- // is_vl / is_reasoning / display_name / contextWindow(上游目录不随每次对话下发)。
92
- // contextWindow 取官方档位表 context_config 的最大档(有 1M 档就填 1M)。
93
- // priceFactor:目录 price_factor(采集时刻的生效价;0 是免费,不是缺失)。
94
- // promotion:错峰折扣窗口,展示时按本地时间推算,不用采集快照。
95
-
96
- const QODER_FALLBACK_MODELS = [
97
- { id: 'auto', name: 'Auto', contextWindow: 200_000, supportsImage: true, supportsThinking: false, priceFactor: 0.5 },
98
- { id: 'ultimate', name: 'Ultimate', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 2, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'high', supportsDisable: true },
99
- { id: 'performance', name: 'Performance', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 1.1, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'medium', supportsDisable: true },
100
- { id: 'efficient', name: 'Efficient', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 0.3 },
101
- { id: 'smodel', name: 'Sonus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 8, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'high' },
102
- { id: 'cmodel', name: 'Cantus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 4, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'high' },
103
- {
104
- id: 'qmodel_38max', name: 'Qwen3.8-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
105
- isFree: true, priceFactor: 0.2, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'xhigh', supportsDisable: true,
106
- promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
107
- },
108
- // priceFactor 0 = 免费(合法值,不能当缺失)。
109
- {
110
- id: 'qfmodel', name: 'Qwen3.8-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
111
- isFree: true, priceFactor: 0, originalPriceFactor: 0.1, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'medium', supportsDisable: true,
112
- },
113
- {
114
- id: 'qmodel_latest', name: 'Qwen3.7-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false,
115
- priceFactor: 0.1, originalPriceFactor: 0.5, supportsDisable: true,
116
- promotion: { active: true, discountFactor: 0.2, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
117
- },
118
- {
119
- id: 'qmodel', name: 'Qwen3.7-Plus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false,
120
- priceFactor: 0.04, supportsDisable: true,
121
- promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.1, windowStart: '22:00', windowEnd: '08:00' },
122
- },
123
- { id: 'kmodel_latest', name: 'Kimi-K3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 1.4, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
124
- { id: 'kmodel', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
125
- { id: 'gmodel', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
126
- { id: 'gfmodel', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ['high', 'max'], defaultEffort: 'max' },
127
- { id: 'dmodel', name: 'DeepSeek-V4-Pro', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.5, efforts: ['high', 'max'], defaultEffort: 'max', supportsDisable: true },
128
- { id: 'dfmodel', name: 'DeepSeek-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ['high', 'max', 'low'], defaultEffort: 'max', supportsDisable: true },
129
- { id: 'mmodel', name: 'MiniMax-M3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 0.2 },
130
- ]
131
-
132
- const QODER_CN_FALLBACK_MODELS = [
133
- { id: 'auto', name: 'Auto', contextWindow: 200_000, supportsImage: true, supportsThinking: true, priceFactor: 0.5 },
134
- {
135
- id: 'qmodel_38max', name: 'Qwen3.8-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
136
- isFree: true, priceFactor: 0.2, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'medium', supportsDisable: true,
137
- promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
138
- },
139
- {
140
- id: 'qfmodel', name: 'Qwen3.8-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
141
- isFree: true, priceFactor: 0, originalPriceFactor: 0.1, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'medium', supportsDisable: true,
142
- },
143
- {
144
- id: 'qmodel_latest', name: 'Qwen3.7-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
145
- priceFactor: 0.1, supportsDisable: true,
146
- promotion: { active: true, discountFactor: 0.2, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
147
- },
148
- {
149
- id: 'qmodel', name: 'Qwen3.7-Plus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
150
- priceFactor: 0.04, supportsDisable: true,
151
- promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.1, windowStart: '22:00', windowEnd: '08:00' },
152
- },
153
- { id: 'q37fmodel', name: 'Qwen3.7-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1 },
154
- { id: 'dmodel', name: 'DeepSeek-V4-Pro', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.5, efforts: ['high', 'max'], defaultEffort: 'max', supportsDisable: true },
155
- { id: 'dfmodel', name: 'DeepSeek-Flash', contextWindow: 1_000_000, supportsImage: true, priceFactor: 0.1, efforts: ['high', 'max', 'low'], defaultEffort: 'max', supportsDisable: true },
156
- { id: 'gmodel', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
157
- { id: 'gfmodel', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ['high', 'max'], defaultEffort: 'max' },
158
- { id: 'gm51model', name: 'GLM-5.2', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.6, efforts: ['high', 'max'], defaultEffort: 'max', supportsDisable: true },
159
- { id: 'kmodel_latest', name: 'Kimi-K3', contextWindow: 1_000_000, supportsImage: true, priceFactor: 1.4, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
160
- { id: 'kmodel', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
161
- // CN 独有差异:MiniMax-M2.7(国际版 M3)、is_vl false、唯一 200K 档位表
162
- { id: 'mmodel', name: 'MiniMax-M2.7', contextWindow: 200_000, priceFactor: 0.2 },
163
- ]
164
-
165
- // ── 匿名拉取模型目录的占位标识 ──────────────────────────────────────────────
166
- //
167
- // 上游模型目录(/algo/api/v2/model/list)只校验 COSY 签名,**不校验账号身份**:
168
- // 用本地 WASM 生成的签名 + 空 token 就能拿到 HTTP 200 与完整目录(实测 2026-10-23)。
169
- // 签名载荷里必须带一个**非空** uid,否则服务端回 403「Signature invalid (101)」。
170
- //
171
- // ⚠️ **占位 uid 不能是 UUID 形态**:UUID 形态会被上游当成「登录过的账号但令牌已过期」,
172
- // 回 HTTP 403 code=105 Login expired;普通字符串(字母数字)才能通过并拿到完整目录。
173
- // 占位 uid / machine id 只参与签名计算,不对应任何真实账号,也不携带任何凭据。
174
-
175
- const QODER_ANONYMOUS_UID = 'omr-anonymous-guest'
176
- const QODER_ANONYMOUS_MACHINE_ID = 'omr-anonymous-machine'
177
-
178
- // ── 产品配置 ─────────────────────────────────────────────────────────────────
179
-
180
- const QODER_PRODUCTS = {
181
- qoder: {
182
- id: 'qoder',
183
- displayName: 'Qoder (国际版)',
184
- authBase: 'https://qoder.com',
185
- openApiBase: 'https://openapi.qoder.sh',
186
- // ⚠️ 加密端点 host 是 api2.qoder.sh;公开端点的 api2-v2.qoder.sh 不是同一个 host
187
- encryptedInferBase: 'https://api2.qoder.sh',
188
- // 模型目录走 api3.qoder.sh(CLI 日志实测 operation=modelCatalogFetch),
189
- // 与加密推理的 api2 不是同一个 host
190
- modelListBase: 'https://api3.qoder.sh',
191
- // prod 环境的 client id(源码 J_a;用成非 prod 的 G_a 会让授权回调被拒)
192
- clientId: 'e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb',
193
- clientMetadata: { client_type: '5', business_product: 'cli', business_type: 'agent', scene: 'assistant' },
194
- // ⚠️ /sash/ 端点(活动、用量)用的客户端类型与推理的 client_type **不同**:
195
- // '5'(CLI)时 /sash/api/v1/me/campaigns 恒返回 campaigns:[],
196
- // 必须 '10'(桌面 app 身份)服务端才进入活动下发分支。
197
- sashClientType: '10',
198
- userAgentPrefix: 'qoder',
199
- fallbackModels: QODER_FALLBACK_MODELS,
200
- },
201
- qodercn: {
202
- id: 'qodercn',
203
- displayName: 'Qoder (中国版)',
204
- authBase: 'https://qoder.cn',
205
- openApiBase: 'https://openapi.qoder.com.cn',
206
- // E9:algo 网关在 CN 换域名,路径与协议同形
207
- encryptedInferBase: 'https://gateway.qoder.com.cn',
208
- // CN 的模型目录与加密推理同一个 host
209
- modelListBase: 'https://gateway.qoder.com.cn',
210
- // CN asar 的 Vpe.authClientIds.prod(与国际版完全不同,用错则授权报参数无效)
211
- clientId: '732aef47-9cf2-46a2-95fe-4cebb5d0d1fa',
212
- clientMetadata: { client_type: '5', business_product: 'cli', business_type: 'agent', scene: 'assistant' },
213
- sashClientType: '10',
214
- userAgentPrefix: 'qoder',
215
- fallbackModels: QODER_CN_FALLBACK_MODELS,
216
- },
217
- }
218
-
219
- // ── 小工具 ──────────────────────────────────────────────────────────────────
220
-
221
- function readStringField(source, keys) {
222
- for (const key of keys) {
223
- const value = source?.[key]
224
- if (typeof value === 'string' && value.length > 0) return value
225
- }
226
- return undefined
227
- }
228
-
229
- /** 把时间值解析成毫秒时间戳(兼容 ISO 字符串与数字秒/毫秒);绝不填 0。 */
230
- function parseTimestamp(value) {
231
- if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
232
- return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
233
- }
234
- if (typeof value === 'string' && value.length > 0) {
235
- const parsed = Date.parse(value)
236
- return Number.isFinite(parsed) ? parsed : undefined
237
- }
238
- return undefined
239
- }
240
-
241
- /** 解析 `HH:MM`(容忍不补零)为当日分钟数;非法返回 undefined。 */
242
- function parseHHMM(value) {
243
- if (typeof value !== 'string') return undefined
244
- const m = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
245
- if (m === null) return undefined
246
- const h = Number(m[1])
247
- const min = Number(m[2])
248
- return h < 24 && min < 60 ? h * 60 + min : undefined
249
- }
250
-
251
- /**
252
- * 取当前时刻在指定时区里的「当日分钟数」。时区缺失/非法时回退 UTC+8
253
- * (目录的 Asia/Singapore 与 UTC+8 同偏移)。
254
- */
255
- function minutesInTimeZone(now, timeZone) {
256
- if (typeof timeZone === 'string' && timeZone !== '') {
257
- try {
258
- const parts = new Intl.DateTimeFormat('en-GB', {
259
- timeZone, hour: '2-digit', minute: '2-digit', hour12: false,
260
- }).formatToParts(now)
261
- const hour = Number(parts.find(p => p.type === 'hour')?.value)
262
- const minute = Number(parts.find(p => p.type === 'minute')?.value)
263
- if (Number.isFinite(hour) && Number.isFinite(minute)) {
264
- return (hour % 24) * 60 + minute
265
- }
266
- } catch { /* 非法时区名回退 UTC+8 */ }
267
- }
268
- const shifted = new Date(now.getTime() + 8 * 3_600_000)
269
- return shifted.getUTCHours() * 60 + shifted.getUTCMinutes()
270
- }
271
-
272
- /**
273
- * 错峰折扣此刻是否生效(按当前时间推算)。
274
- *
275
- * ⚠️ 不能用目录的 `promotion.active`:那是采集时刻的快照,窗口切换后会失真
276
- * (窗口外显示折后价 = 用户按折扣预期却被按原价计费)。窗口字段稳定,按当前
277
- * 时间推算;支持跨零点(22:00–08:00)。窗口字段缺失时回退到 `active`。
278
- */
279
- function promotionActiveNow(promotion, now = new Date()) {
280
- const start = parseHHMM(promotion?.windowStart)
281
- const end = parseHHMM(promotion?.windowEnd)
282
- if (start === undefined || end === undefined) return promotion?.active === true
283
- const minutes = minutesInTimeZone(now, promotion?.timeZone)
284
- return start <= end
285
- ? minutes >= start && minutes < end
286
- : minutes >= start || minutes < end
287
- }
288
-
289
- /**
290
- * 由上游目录项的 `price_factor` + `promotion` 推算此刻的倍率字段。
291
- *
292
- * - `price_factor === 0` → `rate: 0`(免费,0 是合法值不能当缺失);
293
- * - 折扣窗口内 → `rate` 取 `before_promotion_price_factor × discount_factor`
294
- * (**不采信快照价**),`rateOriginal` 为原价;
295
- * - 窗口外 → 用原价(有 promotion 时原价即 before),否则用 `price_factor`。
296
- */
297
- function liveRateFields(entry, now = new Date()) {
298
- const price = entry?.price_factor
299
- if (price === 0) return { rate: 0 }
300
- const promo = entry?.promotion
301
- const before = promo?.before_promotion_price_factor
302
- const discount = promo?.discount_factor
303
- const hasPromo = typeof before === 'number' && typeof discount === 'number'
304
- if (hasPromo) {
305
- const active = promotionActiveNow({
306
- active: promo.active,
307
- windowStart: promo.window_start,
308
- windowEnd: promo.window_end,
309
- timeZone: promo.timezone,
310
- }, now)
311
- if (active) {
312
- const effective = Number((before * discount).toFixed(4))
313
- return { rate: effective, ...(before > effective ? { rateOriginal: before } : {}) }
314
- }
315
- return { rate: before }
316
- }
317
- if (typeof price !== 'number' || !Number.isFinite(price)) return {}
318
- return { rate: price }
319
- }
320
-
321
- /**
322
- * 上游目录项的上下文窗口:优先取官方档位表 context_config 的最大档
323
- * (有 1M 档就填 1M),其次才用 max_input_tokens(后者常是默认档而非上限)。
324
- */
325
- function contextWindowOf(entry) {
326
- const config = entry?.context_config
327
- if (config !== null && typeof config === 'object') {
328
- const counts = Object.values(config)
329
- .map(item => item?.token_count)
330
- .filter(count => typeof count === 'number' && count > 0)
331
- if (counts.length > 0) return Math.max(...counts)
332
- }
333
- const max = entry?.max_input_tokens
334
- return typeof max === 'number' && max > 0 ? max : undefined
335
- }
336
-
337
- /** PKCE:verifier 43..128 位(源码 43 + floor(86*random)),challenge 去 padding。 */
338
- function createPkce() {
339
- const length = 43 + Math.floor(86 * Math.random())
340
- const bytes = randomBytes(length)
341
- let verifier = ''
342
- for (let i = 0; i < length; i++) verifier += PKCE_ALPHABET[bytes[i] % PKCE_ALPHABET.length]
343
- const challenge = createHash('sha256').update(verifier).digest()
344
- .toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
345
- return { verifier, challenge }
346
- }
347
-
348
- function isRefreshable(credential) {
349
- return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
350
- }
351
-
352
- function credentialExpiresAtMs(credential) {
353
- const value = credential?.expire_time
354
- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
355
- }
356
-
357
- /** 睡眠(可被 signal 中断)。 */
358
- function sleep(ms, signal) {
359
- return new Promise((resolve, reject) => {
360
- if (signal?.aborted) { reject(new Error('登录已取消')); return }
361
- const timer = setTimeout(() => {
362
- signal?.removeEventListener('abort', onAbort)
363
- resolve()
364
- }, ms)
365
- const onAbort = () => { clearTimeout(timer); reject(new Error('登录已取消')) }
366
- signal?.addEventListener('abort', onAbort, { once: true })
367
- })
368
- }
369
-
370
- /** UTC+8 当日 24:00 的毫秒时间戳(额度按自然日重置)。 */
371
- function nextUtc8DayStartMs() {
372
- const now = Date.now()
373
- const shifted = now + 8 * 3_600_000
374
- const msIntoDay = ((shifted % 86_400_000) + 86_400_000) % 86_400_000
375
- return now + (86_400_000 - msIntoDay)
376
- }
377
-
378
- function looksLikeBillingError(text) {
379
- return /billing\s+daily\s+count\s+exceeded|daily\s+count\s+exceeded|billing_error/i.test(String(text ?? ''))
380
- }
381
-
382
- function isQueueCode(code) {
383
- return code === QUEUE_BUSINESS_CODE || code === Number(QUEUE_BUSINESS_CODE)
384
- }
385
-
386
- function isBillingCode(code) {
387
- return code === BILLING_BUSINESS_CODE || code === Number(BILLING_BUSINESS_CODE)
388
- }
389
-
390
- /** 从错误体抽人可读消息(JSON message/error/msg → 原文截断)。 */
391
- function extractMessage(bodyText) {
392
- const text = String(bodyText ?? '').trim()
393
- if (text === '') return ''
394
- try {
395
- const parsed = JSON.parse(text)
396
- const found = [parsed?.message, parsed?.error?.message ?? (typeof parsed?.error === 'string' ? parsed.error : ''), parsed?.msg]
397
- .filter(v => typeof v === 'string' && v.length > 0)
398
- if (found.length > 0) return found.join(' ').slice(0, 300)
399
- } catch { /* 非 JSON */ }
400
- return text.slice(0, 300)
401
- }
402
-
403
- /**
404
- * 解析排队信息。
405
- * 广度优先展开 data/result/message/body 键(字符串再 JSON.parse);
406
- * 业务码命中**或**节点含 isQueued/serviceAvailable 标志即视为排队。
407
- * ⚠️ 不能要求 isQueued===true:瞬时排队实测为 isQueued:false + retryAfterSeconds:2。
408
- */
409
- function parseQueueError(body) {
410
- let root = body
411
- if (typeof body === 'string') {
412
- try { root = JSON.parse(body) } catch { return undefined }
413
- }
414
- if (root === null || typeof root !== 'object') return undefined
415
-
416
- const seen = new Set()
417
- const nodes = []
418
- const queue = [root]
419
- while (queue.length > 0) {
420
- const node = queue.shift()
421
- if (node === null || typeof node !== 'object' || seen.has(node)) continue
422
- seen.add(node)
423
- nodes.push(node)
424
- for (const key of ['data', 'result', 'message', 'body']) {
425
- const value = node[key]
426
- if (value !== null && typeof value === 'object') queue.push(value)
427
- else if (typeof value === 'string' && value.length > 0) {
428
- try { queue.push(JSON.parse(value)) } catch { /* 非 JSON,忽略 */ }
429
- }
430
- }
431
- }
432
-
433
- const info = nodes.find(node => node.isQueued !== undefined || node.serviceAvailable !== undefined)
434
- if (info === undefined) return undefined
435
- const codeHit = nodes.some(node => isQueueCode(node.code))
436
- if (!codeHit && info.isQueued === undefined) return undefined
437
-
438
- const readFinite = v => (typeof v === 'number' && Number.isFinite(v) ? Math.trunc(v) : undefined)
439
- return {
440
- ...(typeof info.isQueued === 'boolean' ? { isQueued: info.isQueued } : {}),
441
- retry_after_ms: readFinite(info.retry_after_ms),
442
- retryAfterMs: readFinite(info.retryAfterMs),
443
- retryAfterSeconds: readFinite(info.retryAfterSeconds),
444
- waitTime: readFinite(info.waitTime),
445
- }
446
- }
447
-
448
- /** 单次排队等待时长:retry_after_ms → retryAfterMs → retryAfterSeconds×1000,封顶 10s。 */
449
- function queueDelayMs(info) {
450
- if (info === undefined) return undefined
451
- const raw = info.retry_after_ms ?? info.retryAfterMs
452
- ?? (info.retryAfterSeconds !== undefined ? info.retryAfterSeconds * 1000 : undefined)
453
- if (raw === undefined || raw < 0) return undefined
454
- return Math.min(Math.trunc(raw), QUEUE_MAX_DELAY_MS)
455
- }
456
-
457
- // ── token 载荷与凭据 ─────────────────────────────────────────────────────────
458
-
459
- /**
460
- * 解析轮询/续期响应。登录响应用 `token`,续期响应用 `device_token` —— 都接受。
461
- * 垃圾输入返回空 accessToken,由调用方判定失败。
462
- * ⚠️ 设备码响应带 user_id/user_name,**加密推理需要 uid**,漏读只能走公开端点。
463
- */
464
- function parseTokenPayload(value) {
465
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return { accessToken: '' }
466
- const accessToken = readStringField(value, ['token', 'device_token', 'access_token']) ?? ''
467
- const refreshToken = readStringField(value, ['refresh_token', 'refreshToken'])
468
- const expiresAt = parseTimestamp(value.expires_at ?? value.expiresAt)
469
- const refreshTokenExpiresAt = parseTimestamp(value.refresh_token_expires_at ?? value.refreshTokenExpiresAt)
470
- const uid = readStringField(value, ['user_id', 'userId'])
471
- const userName = readStringField(value, ['user_name', 'userName'])
472
- return {
473
- accessToken,
474
- ...(refreshToken ? { refreshToken } : {}),
475
- ...(expiresAt !== undefined ? { expiresAt } : {}),
476
- ...(refreshTokenExpiresAt !== undefined ? { refreshTokenExpiresAt } : {}),
477
- ...(uid ? { uid } : {}),
478
- ...(userName ? { userName } : {}),
479
- }
480
- }
481
-
482
- /** 构造持久化凭据:security_oauth_token 与 access_token 双写同值。 */
483
- function buildCredential(payload, machineId, nickname) {
484
- const name = nickname || payload.userName || ''
485
- return {
486
- security_oauth_token: payload.accessToken,
487
- access_token: payload.accessToken,
488
- ...(payload.refreshToken ? { refresh_token: payload.refreshToken } : {}),
489
- ...(payload.expiresAt !== undefined ? { expire_time: payload.expiresAt } : {}),
490
- ...(payload.refreshTokenExpiresAt !== undefined ? { refresh_token_expire_time: payload.refreshTokenExpiresAt } : {}),
491
- machine_id: machineId,
492
- ...(payload.uid ? { uid: payload.uid } : {}),
493
- ...(name ? { nickname: name } : {}),
494
- }
495
- }
496
-
497
- /**
498
- * 用续期结果覆盖旧凭据。**保留** machine_id / uid / nickname:
499
- * 它们不在续期响应里,丢失会让下一次续期缺设备标识、或让加密推理缺 uid。
500
- * 续期响应若未带新 refresh_token,沿用旧的。
501
- */
502
- function applyRefresh(credential, payload) {
503
- const next = {
504
- ...credential,
505
- security_oauth_token: payload.accessToken,
506
- access_token: payload.accessToken,
507
- }
508
- if (payload.refreshToken) next.refresh_token = payload.refreshToken
509
- if (payload.expiresAt !== undefined) next.expire_time = payload.expiresAt
510
- if (payload.refreshTokenExpiresAt !== undefined) next.refresh_token_expire_time = payload.refreshTokenExpiresAt
511
- return next
512
- }
513
-
514
- // ── 渠道工厂 ────────────────────────────────────────────────────────────────
515
-
516
- /**
517
- * Qoder 系渠道工厂。id 取 'qoder' | 'qodercn';未知 id 返回 null(注册表跳过)。
518
- * 两个产品的协议实现完全共用,差异全部收敛在产品配置里。
519
- */
520
- export function qoderChannel(id) {
521
- const product = QODER_PRODUCTS[id]
522
- if (!product) return null
523
-
524
- const fallbackIndex = new Map(product.fallbackModels.map(m => [m.id, m]))
525
- const bearerToken = credential => credential?.security_oauth_token || credential?.access_token || ''
526
-
527
- // anonymousModels: true —— 两版模型目录(/algo/api/v2/model/list)只校验 COSY
528
- // 签名、不校验账号身份(匿名实测 2026-10-23:国际版 14 个模型 / 国内版 10 个),
529
- // 无凭据也能拿到完整清单,无需登录即可发现模型。
530
- const meta = { id: product.id, label: product.displayName, loginMode: 'device-code', anonymousModels: true }
531
-
532
- // ── 登录(PKCE 设备码轮询)─────────────────────────────────────────────────
533
-
534
- function buildAuthUrl(session) {
535
- const query = new URLSearchParams({
536
- challenge: session.pkce.challenge,
537
- challenge_method: 'S256',
538
- nonce: session.nonce,
539
- machine_id: session.machineId,
540
- client_id: product.clientId,
541
- })
542
- return `${product.authBase}${DEVICE_SELECT_PATH}?${query.toString()}`
543
- }
544
-
545
- function buildPollUrl(session) {
546
- const query = new URLSearchParams({
547
- nonce: session.nonce,
548
- verifier: session.pkce.verifier,
549
- challenge_method: 'S256',
550
- })
551
- return `${product.openApiBase}${POLL_PATH}?${query.toString()}`
552
- }
553
-
554
- /**
555
- * 轮询直到拿到 token。**404 = 用户尚未完成授权,继续轮询**
556
- * (该端点被网关豁免认证,404 是业务层的「会话未就绪」;任意不存在路径回 401)。
557
- * 其它非 2xx 立即抛错 —— 那是服务端异常,不是「等用户」。
558
- */
559
- async function pollDeviceToken(session, signal) {
560
- const pollUrl = buildPollUrl(session)
561
- const deadline = Date.now() + LOGIN_TIMEOUT_MS
562
- let failures = 0
563
- while (Date.now() < deadline) {
564
- if (signal?.aborted) throw new Error('登录已取消')
565
- try {
566
- const response = await httpFetch(pollUrl, { method: 'GET', headers: { Accept: 'application/json' }, signal }, REQUEST_TIMEOUT_MS)
567
- failures = 0
568
- if (response.status === 404) { await sleep(POLL_INTERVAL_MS, signal); continue }
569
- if (!response.ok) throw new Error(`登录服务返回异常(HTTP ${response.status})`)
570
- const payload = parseTokenPayload(await response.json().catch(() => ({})))
571
- if (payload.accessToken) return payload
572
- // 2xx 但尚无 token:同样继续轮询
573
- await sleep(POLL_INTERVAL_MS, signal)
574
- } catch (error) {
575
- if (signal?.aborted) throw new Error('登录已取消')
576
- if (error instanceof Error && error.message.startsWith('登录服务返回异常')) throw error
577
- failures += 1
578
- if (failures >= POLL_MAX_FAILURES) {
579
- throw new Error(`无法连接 Qoder 登录服务(连续 ${failures} 次失败):${error?.message ?? error}`)
580
- }
581
- await sleep(POLL_INTERVAL_MS, signal)
582
- }
583
- }
584
- throw new Error('登录等待已超时,请重新发起登录')
585
- }
586
-
587
- /**
588
- * 登录后补一次 userinfo:设备码轮询响应里**没有 user_name**,userinfo 是唯一可靠的昵称来源;顺带补 uid。
589
- * 失败返回原凭据不抛错 —— 展示信息缺失不应让登录整体失败。
590
- */
591
- async function patchFromUserinfo(credential) {
592
- try {
593
- const response = await httpFetch(`${product.openApiBase}${USERINFO_PATH}`, {
594
- method: 'GET',
595
- headers: { Accept: 'application/json', Authorization: `Bearer ${bearerToken(credential)}` },
596
- }, REQUEST_TIMEOUT_MS)
597
- if (!response.ok) return credential
598
- const body = await response.json().catch(() => null)
599
- if (body === null || typeof body !== 'object') return credential
600
- const next = { ...credential }
601
- if (!next.nickname) {
602
- const name = typeof body.name === 'string' ? body.name.trim() : ''
603
- if (name) next.nickname = name
604
- }
605
- if (!next.uid) {
606
- const uid = readStringField(body, ['id', 'user_id', 'userId'])
607
- if (uid) next.uid = uid
608
- }
609
- return next
610
- } catch {
611
- return credential
612
- }
613
- }
614
-
615
- /**
616
- * 启动设备码登录。授权 URL 由 PKCE 纯本地构造(同步就绪),轮询在后台进行。
617
- * 返回 `{ loginUrl, promise, cancel }`;machineId 随凭据持久化
618
- * (不复刻官方硬件指纹:依赖原生模块,不可移植)。
619
- */
620
- function startLogin() {
621
- const controller = new AbortController()
622
- const signal = controller.signal
623
- const session = { pkce: createPkce(), nonce: randomUUID(), machineId: randomUUID() }
624
- const loginUrl = buildAuthUrl(session)
625
-
626
- const promise = (async () => {
627
- const payload = await pollDeviceToken(session, signal)
628
- if (!payload.accessToken) throw new Error('登录响应缺少访问令牌')
629
- let credential = buildCredential(payload, session.machineId)
630
- credential = await patchFromUserinfo(credential)
631
- return credential
632
- })()
633
- promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
634
-
635
- let settled = false
636
- return {
637
- loginUrl,
638
- promise,
639
- cancel: () => {
640
- if (settled) return
641
- settled = true
642
- controller.abort()
643
- },
644
- }
645
- }
646
-
647
- // ── 手动凭据与续期 ──────────────────────────────────────────────────────────
648
-
649
- /** 手动粘贴凭据的规范化:接受 JSON 对象/字符串,补 machine_id(随机 UUID)。 */
650
- function normalizeCredential(raw) {
651
- let value = raw
652
- if (typeof value === 'string') {
653
- try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
654
- }
655
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
656
- throw new Error('凭据必须是 JSON 对象')
657
- }
658
- const accessToken = readStringField(value, ['security_oauth_token', 'access_token', 'token', 'device_token'])
659
- const refreshToken = readStringField(value, ['refresh_token', 'refreshToken'])
660
- if (!accessToken && !refreshToken) throw new Error('凭据缺少 access_token / refresh_token')
661
- const expiresAt = parseTimestamp(value.expire_time ?? value.expires_at ?? value.expiresAt)
662
- return {
663
- ...value,
664
- ...(accessToken ? { security_oauth_token: accessToken, access_token: accessToken } : {}),
665
- ...(refreshToken ? { refresh_token: refreshToken } : {}),
666
- ...(expiresAt !== undefined ? { expire_time: expiresAt } : {}),
667
- machine_id: readStringField(value, ['machine_id', 'machineId']) ?? randomUUID(),
668
- ...(readStringField(value, ['uid', 'user_id', 'userId']) ? { uid: readStringField(value, ['uid', 'user_id', 'userId']) } : {}),
669
- ...(readStringField(value, ['nickname', 'user_name', 'userName']) ? { nickname: readStringField(value, ['nickname', 'user_name', 'userName']) } : {}),
670
- }
671
- }
672
-
673
- /**
674
- * 静默续期:{refresh_token, machine_id} 换新令牌。
675
- * 终态:401/403、200 但缺 token、无 refresh_token —— 停止重试,需重新登录。
676
- * 传输层失败不能判终态 —— 网络抖动不该让用户重新登录。
677
- */
678
- async function refreshCredential(credential) {
679
- if (!isRefreshable(credential)) {
680
- throw { kind: 'auth', retryable: false, terminal: true, message: 'Qoder 无 refresh_token,请重新登录' }
681
- }
682
- let response
683
- try {
684
- response = await httpFetch(`${product.openApiBase}${REFRESH_PATH}`, {
685
- method: 'POST',
686
- headers: {
687
- 'Content-Type': 'application/json',
688
- Accept: 'application/json',
689
- 'User-Agent': `${product.userAgentPrefix}/1.0.0`,
690
- },
691
- body: JSON.stringify({ refresh_token: credential.refresh_token, machine_id: credential.machine_id }),
692
- }, REQUEST_TIMEOUT_MS)
693
- } catch (error) {
694
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Qoder 续期网络失败:${error?.message ?? error}` }
695
- }
696
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
697
- if (response.status === 401 || response.status === 403) {
698
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Qoder 续期被拒绝(HTTP ${response.status}),请重新登录` }
699
- }
700
- let parsed
701
- try { parsed = JSON.parse(text) } catch {
702
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Qoder 续期响应不是 JSON(HTTP ${response.status})` }
703
- }
704
- if (!response.ok) {
705
- // 400 + 点名 refresh_token 无效(实测假 token 返回 DeviceRefreshTokenPrefixInvalid)
706
- // 语义上就是令牌永久失效 —— 重试永远不会成功,判终态。
707
- const code = typeof parsed?.errorCode === 'string' ? parsed.errorCode : ''
708
- if (response.status === 400 && /refreshtoken/i.test(code)) {
709
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Qoder refresh_token 已失效(${code}),请重新登录` }
710
- }
711
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Qoder 续期失败(HTTP ${response.status}):${text.slice(0, 200)}` }
712
- }
713
- const payload = parseTokenPayload(parsed)
714
- if (!payload.accessToken) {
715
- // 200 却没有 token:视为无法续期(需重新登录),不是可重试的瞬时故障
716
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'Qoder 续期响应缺少访问令牌,请重新登录' }
717
- }
718
- return applyRefresh(credential, payload)
719
- }
720
-
721
- function needsRefresh(credential) {
722
- if (!isRefreshable(credential)) return false
723
- const expiresAt = credentialExpiresAtMs(credential)
724
- if (expiresAt === undefined) return false
725
- return Date.now() >= expiresAt - REFRESH_LEAD_MS
726
- }
727
-
728
- function describeCredential(credential) {
729
- const nickname = readStringField(credential, ['nickname']) ?? ''
730
- const uid = readStringField(credential, ['uid']) ?? ''
731
- return {
732
- label: nickname || (uid ? `${product.id}-${uid.slice(0, 8)}` : `${product.displayName} 账号`),
733
- expiresAt: credentialExpiresAtMs(credential) ?? 0,
734
- refreshable: isRefreshable(credential),
735
- }
736
- }
737
-
738
- function credentialIdentity(credential) {
739
- return readStringField(credential, ['uid']) ?? readStringField(credential, ['machine_id']) ?? ''
740
- }
741
-
742
- // ── 模型清单(实时拉取上游目录;拉不到一律抛错,不回落静态表)──────────────
743
-
744
- async function fetchModels(credential) {
745
- // 无凭据 / 缺 token / 缺 uid → 匿名拉取:目录端点只校验 COSY 签名(签名只依赖
746
- // 本地 WASM + 时间/随机数,不依赖账号),用占位标识签名即可拿到完整清单
747
- // (实测 2026-10-23,两版均 HTTP 200)。⚠️ 占位 uid 必须非空且**非 UUID 形态**
748
- // (UUID 形态会被上游判成「登录过但令牌已过期」回 403 code=105),见文件顶部常量说明。
749
- // 有完整凭据时行为不变:真实 uid / token 原样参与签名。
750
- const anonymous = !credential || bearerToken(credential) === ''
751
- || typeof credential.uid !== 'string' || credential.uid === ''
752
- const uid = anonymous ? QODER_ANONYMOUS_UID : credential.uid
753
- // 匿名模式不携带任何账号凭据:签名载荷里 security_oauth_token 置空串。
754
- const token = anonymous ? '' : bearerToken(credential)
755
- const machineId = anonymous ? QODER_ANONYMOUS_MACHINE_ID : credential.machine_id
756
-
757
- const host = new URL(product.modelListBase).host
758
- let request
759
- try {
760
- const client = await QoderEncryptedInfer.create({
761
- user: { uid, securityOauthToken: token },
762
- machineId,
763
- metadata: { ...product.clientMetadata },
764
- host,
765
- })
766
- // auth:'auth' → WASM 追加 COSY 签名头;缺了服务端回 403 Signature invalid
767
- request = client.prepareRequest({ host, path: MODEL_LIST_PATH, method: 'GET', auth: 'auth' })
768
- } catch (error) {
769
- throw { kind: 'server', retryable: true, cooldownMs: 60_000, rotate: false, message: `Qoder 模型目录签名失败:${error?.message ?? error}` }
770
- }
771
-
772
- let response
773
- let text
774
- try {
775
- response = await httpFetch(request.url, { method: 'GET', headers: request.headers }, MODEL_LIST_TIMEOUT_MS)
776
- text = await readBodyText(response, MODEL_LIST_TIMEOUT_MS)
777
- } catch (error) {
778
- throw { kind: 'network', retryable: true, message: `Qoder 模型目录请求失败:${error?.message ?? error}` }
779
- }
780
- if (!response.ok) {
781
- const authFailure = response.status === 401 || response.status === 403
782
- throw {
783
- kind: authFailure ? 'auth' : 'server',
784
- retryable: !authFailure,
785
- terminal: authFailure,
786
- rotate: authFailure,
787
- message: `Qoder 模型目录获取失败:HTTP ${response.status} ${text.slice(0, 300)}`,
788
- }
789
- }
790
-
791
- let payload
792
- try {
793
- payload = JSON.parse(text)
794
- } catch {
795
- throw { kind: 'server', retryable: true, message: `Qoder 模型目录返回非 JSON:${text.slice(0, 300)}` }
796
- }
797
-
798
- const list = Array.isArray(payload?.chat) ? payload.chat : []
799
- const now = new Date()
800
- const models = list
801
- .filter(entry => entry !== null && typeof entry === 'object'
802
- && typeof entry.key === 'string' && entry.key !== '' && entry.enable !== false)
803
- .map(entry => {
804
- const label = String(entry.display_name ?? entry.key)
805
- return {
806
- id: entry.key,
807
- // 只有 price_factor === 0 才是真免费:is_free 表示「有免费额度」,
808
- // 超额仍按倍率计费(Qwen3.8-Max 标成免费会与倍率徽章自相矛盾)
809
- name: entry.price_factor === 0 ? `${label} · 免费` : label,
810
- contextWindow: contextWindowOf(entry),
811
- supportsImage: entry.is_vl === true || undefined,
812
- isFree: entry.is_free === true,
813
- // 倍率按当前时间 + 目录 promotion 窗口实时推算(窗口会切换)
814
- ...liveRateFields(entry, now),
815
- }
816
- })
817
-
818
- if (models.length === 0) {
819
- throw { kind: 'server', retryable: true, message: 'Qoder 模型目录为空(上游未返回 chat 清单)' }
820
- }
821
- return models
822
- }
823
-
824
- // ── 对话(加密端点,信封剥离 + 排队/额度/认证分类)─────────────────────────
825
-
826
- /** content 归一化为字符串(工具调用消息的正文是空串)。 */
827
- function contentText(content) {
828
- if (typeof content === 'string') return content
829
- if (Array.isArray(content)) {
830
- return content
831
- .filter(block => block !== null && typeof block === 'object' && block.type === 'text')
832
- .map(block => String(block.text ?? ''))
833
- .join('')
834
- }
835
- return ''
836
- }
837
-
838
- /**
839
- * content 数组的**多模态 parts 搬运**:无图返回 undefined(保持字符串形态,
840
- * 上游对字符串兼容性最好);有图时保留 text/image_url 两类块。
841
- * ⚠️ 图片的正确通道是 messages[].content 的多模态数组(客户端官方实现把
842
- * chat_context.imageUrls 恒置 null),压成纯文本会让图片在下游全部消失。
843
- */
844
- function contentParts(content) {
845
- if (!Array.isArray(content)) return undefined
846
- const parts = []
847
- let hasImage = false
848
- for (const raw of content) {
849
- if (raw === null || typeof raw !== 'object') continue
850
- const block = raw
851
- if (block.type === 'text') {
852
- const text = String(block.text ?? '')
853
- if (text.length > 0) parts.push({ type: 'text', text })
854
- continue
855
- }
856
- if (block.type === 'image_url') {
857
- const url = block.image_url?.url
858
- if (typeof url !== 'string' || url.length === 0) continue
859
- const detail = block.image_url?.detail
860
- parts.push({ type: 'image_url', image_url: { url, ...(typeof detail === 'string' && detail.length > 0 ? { detail } : {}) } })
861
- hasImage = true
862
- }
863
- }
864
- return hasImage ? parts : undefined
865
- }
866
-
867
- /** 工具调用归一:arguments 必须是字符串(对象形态序列化)。 */
868
- function cleanToolCalls(toolCalls) {
869
- return toolCalls.map(call => {
870
- if (call === null || typeof call !== 'object') return null
871
- const fn = call.function ?? {}
872
- let args = fn.arguments
873
- if (args === undefined || args === null) args = ''
874
- else if (typeof args !== 'string') args = JSON.stringify(args)
875
- return {
876
- ...(typeof call.id === 'string' ? { id: call.id } : {}),
877
- type: 'function',
878
- ...(typeof call.index === 'number' ? { index: call.index } : {}),
879
- function: { name: String(fn.name ?? ''), arguments: args },
880
- }
881
- }).filter(Boolean)
882
- }
883
-
884
- /**
885
- * 把 OpenAI wire 消息转成加密端点的 messages[]。
886
- * ⚠️ 三者缺一不可:assistant 的 tool_calls、role:'tool' 的 tool_call_id、
887
- * 带图消息的多模态数组 —— 只留字符串 content 会让多步工具调用彻底坏掉
888
- * (模型看不到自己调用过什么,反复重调或凭空编造结果)。
889
- * ⚠️ 判空必须把图片算作内容:只发一张图不带文字的消息不能整条吃掉。
890
- */
891
- function buildHistory(messages) {
892
- const history = []
893
- for (const message of messages) {
894
- if (message === null || typeof message !== 'object' || typeof message.role !== 'string') continue
895
- const parts = contentParts(message.content)
896
- const content = parts === undefined ? contentText(message.content) : parts
897
- const toolCalls = Array.isArray(message.tool_calls) && message.tool_calls.length > 0
898
- ? cleanToolCalls(message.tool_calls)
899
- : undefined
900
- const toolCallId = typeof message.tool_call_id === 'string' ? message.tool_call_id : undefined
901
- const isEmpty = parts === undefined ? content.length === 0 : content.length === 0
902
- if (isEmpty && toolCalls === undefined && toolCallId === undefined) continue
903
- history.push({
904
- role: message.role,
905
- content,
906
- ...(toolCalls === undefined ? {} : { tool_calls: toolCalls }),
907
- ...(toolCallId === undefined ? {} : { tool_call_id: toolCallId }),
908
- })
909
- }
910
- return history
911
- }
912
-
913
- /** 工具定义:客户端 $Hc(A) 形态 {type:'function', function:{name, description?, parameters?}}。 */
914
- function buildTools(tools) {
915
- if (!Array.isArray(tools)) return []
916
- const out = []
917
- for (const tool of tools) {
918
- if (tool === null || typeof tool !== 'object' || typeof tool.function?.name !== 'string' || tool.function.name.trim().length === 0) continue
919
- const fn = tool.function
920
- out.push({
921
- type: 'function',
922
- function: {
923
- name: fn.name,
924
- ...(typeof fn.description === 'string' && fn.description.length > 0 ? { description: fn.description } : {}),
925
- ...(fn.parameters !== undefined && fn.parameters !== null ? { parameters: fn.parameters } : {}),
926
- },
927
- })
928
- }
929
- return out
930
- }
931
-
932
- /** 思考档位校验:白名单外静默丢弃(服务端 ao() 同语义);disabled/off → none。 */
933
- function normalizeEffort(value) {
934
- if (typeof value !== 'string') return undefined
935
- const mapped = EFFORT_ALIASES[value] ?? value
936
- return EFFORT_WHITELIST.has(mapped) ? mapped : undefined
937
- }
938
-
939
- /** 组装加密推理入参(消息/系统提示/工具/最后一条 user 文本)。 */
940
- function buildInferInputs(body) {
941
- const messages = Array.isArray(body.messages) ? body.messages : []
942
- const systemParts = []
943
- const rest = []
944
- for (const message of messages) {
945
- if (message !== null && typeof message === 'object' && message.role === 'system') {
946
- const text = contentText(message.content)
947
- if (text) systemParts.push(text)
948
- continue
949
- }
950
- rest.push(message)
951
- }
952
- const history = buildHistory(rest)
953
- let userText = ''
954
- for (let i = history.length - 1; i >= 0; i--) {
955
- if (history[i].role === 'user') {
956
- userText = Array.isArray(history[i].content)
957
- ? history[i].content.filter(b => b.type === 'text').map(b => String(b.text ?? '')).join('')
958
- : String(history[i].content ?? '')
959
- break
960
- }
961
- }
962
- return {
963
- history,
964
- ...(systemParts.length > 0 ? { systemText: systemParts.join('\n\n') } : {}),
965
- userText,
966
- tools: buildTools(body.tools),
967
- }
968
- }
969
-
970
- // ── 加密端点响应的信封剥离 ─────────────────────────────────────────────────
971
-
972
- /** 信封分类:chunk / error / heartbeat。⚠️ body:null 是心跳不是错误(issue IKJOZ8)。 */
973
- function classifyInner(inner) {
974
- const trimmed = inner.trim()
975
- if (trimmed.length === 0) return 'heartbeat'
976
- if (trimmed.includes('[DONE]')) return 'chunk'
977
- let parsed
978
- try { parsed = JSON.parse(trimmed) } catch { return 'error' }
979
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return 'heartbeat'
980
- // choices:[](usage 末帧形态)也算正常帧
981
- if (Array.isArray(parsed.choices) || parsed.usage !== undefined) return 'chunk'
982
- if (parsed.code !== undefined || parsed.message !== undefined || parsed.error !== undefined
983
- || parsed.statusCodeValue !== undefined || parsed.type !== undefined) return 'error'
984
- return 'heartbeat'
985
- }
986
-
987
- /** 从信封 JSON 文本里取出内层帧文本;不是信封(缺 body 键)返回 null。 */
988
- function unwrapEnvelope(payload) {
989
- let envelope
990
- try { envelope = JSON.parse(payload) } catch { return null }
991
- if (envelope === null || typeof envelope !== 'object' || envelope.body === undefined) return null
992
- // 内层 body 可能是字符串或对象,统一转为字符串供后续解析
993
- return typeof envelope.body === 'string' ? envelope.body : JSON.stringify(envelope.body)
994
- }
995
-
996
- /** 非 401/403/409 的 HTTP 失败分类。 */
997
- function failureFrom(status, bodyText) {
998
- const message = extractMessage(bodyText) || `Qoder HTTP ${status}`
999
- if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
1000
- if (status === 402 || looksLikeBillingError(bodyText)) {
1001
- return { kind: 'quota', retryable: false, cooldownMs: Math.max(60_000, nextUtc8DayStartMs() - Date.now()), rotate: true, message }
1002
- }
1003
- if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
1004
- if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1005
- if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
1006
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1007
- }
1008
-
1009
- /** 排队等待:先判时间预算、再判次数(时间上限是硬约束),无延迟信息时退避 1s。 */
1010
- async function waitForQueue(queueInfo, attempts, deadline, signal) {
1011
- if (Date.now() >= deadline || attempts > QUEUE_MAX_ATTEMPTS) {
1012
- throw { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message: 'Qoder 排队等待超时' }
1013
- }
1014
- await sleep(queueDelayMs(queueInfo) ?? 1_000, signal)
1015
- }
1016
-
1017
- /**
1018
- * 单账号一轮对话(加密端点)。恒以非流式聚合返回 { status, json };
1019
- * onData 存在时逐帧发**剥壳后**的 OpenAI chunk JSON 文本。
1020
- * 调用方(providers/index.js)负责续期与换号 —— 这里只如实分类错误。
1021
- *
1022
- * ⚠️ 凭据缺 uid 时明确报错而不是发出必然失败的请求 —— 缺 uid 会让 WASM
1023
- * 产出签名无效的请求,服务端回 `Signature invalid (101)`,极难定位。
1024
- */
1025
- async function complete(credential, body, { signal, onData, headerTimeoutMs = 120_000 } = {}) {
1026
- if (!credential || !bearerToken(credential)) {
1027
- throw { kind: 'auth', retryable: false, terminal: true, message: 'Qoder 凭据缺少访问令牌,请重新登录' }
1028
- }
1029
- if (typeof credential.uid !== 'string' || credential.uid.length === 0) {
1030
- throw { kind: 'auth', retryable: false, terminal: true, rotate: false, cooldownMs: 10 * 60_000, message: 'Qoder 凭据缺少 uid,加密推理无法签名(请重新登录该账号)' }
1031
- }
1032
- const modelKey = typeof body.model === 'string' ? body.model : ''
1033
- const fallback = fallbackIndex.get(modelKey)
1034
- const { history, systemText, userText, tools } = buildInferInputs(body)
1035
-
1036
- let request
1037
- try {
1038
- const client = await QoderEncryptedInfer.create({
1039
- user: { uid: credential.uid, securityOauthToken: bearerToken(credential) },
1040
- machineId: credential.machine_id,
1041
- metadata: { ...product.clientMetadata },
1042
- host: product.encryptedInferBase,
1043
- })
1044
- request = client.prepareInfer({
1045
- modelKey,
1046
- userText,
1047
- ...(systemText !== undefined ? { systemText } : {}),
1048
- isReasoning: fallback?.supportsThinking === true,
1049
- history,
1050
- tools,
1051
- ...(typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0
1052
- ? { maxTokens: Math.floor(body.max_tokens) } : {}),
1053
- ...(normalizeEffort(body.reasoning_effort) !== undefined ? { reasoningEffort: normalizeEffort(body.reasoning_effort) } : {}),
1054
- ...(fallback?.supportsImage !== undefined ? { isVl: fallback.supportsImage } : {}),
1055
- // 官方 model_config 的 display_name / max_input_tokens 必须带上
1056
- ...(fallback?.name !== undefined ? { displayName: fallback.name } : {}),
1057
- ...(fallback?.contextWindow !== undefined ? { maxInputTokens: fallback.contextWindow } : {}),
1058
- // ⚠️ business 必填:缺失时服务端把请求路由到故障节点(Execution failed)
1059
- business: { type: 'agent' },
1060
- })
1061
- } catch (error) {
1062
- // WASM 构造失败是进程级缺陷(换号无用),不标记账号
1063
- throw { kind: 'server', retryable: true, cooldownMs: 60_000, rotate: false, message: `Qoder 加密请求构造失败:${error?.message ?? error}` }
1064
- }
1065
-
1066
- const queueDeadline = Date.now() + QUEUE_TOTAL_BUDGET_MS
1067
- let queueAttempts = 0
1068
- let duplicateRetried = false
1069
-
1070
- for (;;) {
1071
- // ⚠️ 头必须原样透传:Authorization 是 WASM 生成的 COSY 签名
1072
- const response = await httpFetch(request.url, {
1073
- method: 'POST',
1074
- headers: { ...request.headers, Accept: 'text/event-stream' },
1075
- body: request.body,
1076
- signal,
1077
- }, headerTimeoutMs)
1078
-
1079
- if (!response.ok && (response.status === 401 || response.status === 403)) {
1080
- // ⚠️ 必须先读体再判断:排队信息藏在 message 的内嵌 JSON 里
1081
- const errorText = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1082
- const queueInfo = parseQueueError(errorText)
1083
- if (queueInfo !== undefined) {
1084
- await waitForQueue(queueInfo, ++queueAttempts, queueDeadline, signal)
1085
- continue
1086
- }
1087
- const parsed = (() => { try { return JSON.parse(errorText) } catch { return undefined } })()
1088
- const code = parsed?.code ?? parsed?.error?.code
1089
- if (isBillingCode(code) || looksLikeBillingError(errorText)) {
1090
- throw { kind: 'quota', retryable: false, cooldownMs: Math.max(60_000, nextUtc8DayStartMs() - Date.now()), rotate: true, message: extractMessage(errorText) }
1091
- }
1092
- // 非排队的 401/403 = 认证失败(调用方已完成续期,再失败即凭据终态)
1093
- throw { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: `Qoder 认证失败(HTTP ${response.status}):${extractMessage(errorText)}` }
1094
- }
1095
-
1096
- // 重复请求(duplicate_request):凭据没问题,重发一次即可
1097
- if (!response.ok && response.status === 409 && !duplicateRetried) {
1098
- duplicateRetried = true
1099
- continue
1100
- }
1101
-
1102
- if (!response.ok) {
1103
- const errorText = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1104
- throw failureFrom(response.status, errorText)
1105
- }
1106
- if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Qoder 返回空响应体' }
1107
-
1108
- // 消费 SSE:逐帧剥信封;排队/额度错误帧记录后整轮重试/抛出
1109
- const chunks = []
1110
- let streamQueueMessage = null
1111
- let streamBillingMessage = null
1112
- let streamError = null
1113
- let lastUsage = null
1114
- await readSseData(response.body, data => {
1115
- if (streamError || streamQueueMessage || streamBillingMessage) return
1116
- const inner = unwrapEnvelope(data)
1117
- // 不是信封 → 视为已是标准帧(容错:服务端某天直接回标准帧)
1118
- if (inner === null) {
1119
- chunks.push(data)
1120
- // 尝试从原始数据中提取 usage
1121
- try {
1122
- const chunk = JSON.parse(data)
1123
- if (chunk.usage) lastUsage = chunk.usage
1124
- } catch {}
1125
- onData?.(data)
1126
- return
1127
- }
1128
- const kind = classifyInner(inner)
1129
- if (kind === 'heartbeat') return
1130
- if (kind === 'error') {
1131
- let code
1132
- let message = inner
1133
- try {
1134
- const parsed = JSON.parse(inner)
1135
- if (parsed?.code !== undefined) code = parsed.code
1136
- if (typeof parsed?.message === 'string') message = parsed.message
1137
- } catch { /* 保持原文 */ }
1138
- if (isQueueCode(code) || parseQueueError(message) !== undefined) { streamQueueMessage = message; return }
1139
- if (isBillingCode(code) || looksLikeBillingError(message) || looksLikeBillingError(inner)) { streamBillingMessage = message; return }
1140
- streamError = { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: extractMessage(inner) || inner.slice(0, 300) }
1141
- return
1142
- }
1143
- chunks.push(inner)
1144
- // 从内层帧提取 usage(OpenAI 格式通常在最后一帧带 usage)
1145
- try {
1146
- const chunk = JSON.parse(inner)
1147
- if (chunk.usage) lastUsage = chunk.usage
1148
- } catch {}
1149
- onData?.(inner)
1150
- }, signal)
1151
-
1152
- if (streamQueueMessage !== null) {
1153
- const queueInfo = parseQueueError(streamQueueMessage)
1154
- await waitForQueue(queueInfo, ++queueAttempts, queueDeadline, signal)
1155
- continue
1156
- }
1157
- if (streamBillingMessage !== null) {
1158
- throw { kind: 'quota', retryable: false, cooldownMs: Math.max(60_000, nextUtc8DayStartMs() - Date.now()), rotate: true, message: extractMessage(streamBillingMessage) }
1159
- }
1160
- if (streamError !== null) throw streamError
1161
-
1162
- const merged = mergeSseChunks(chunks)
1163
- if (!merged || !merged.choices?.[0]) {
1164
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Qoder 流结束但没有内容帧' }
1165
- }
1166
- if (merged.model !== undefined) merged.model = modelKey
1167
- // 优先使用流中捕获的 usage,否则保留 mergeSseChunks 提取的
1168
- if (lastUsage) merged.usage = lastUsage
1169
- return { status: response.status, json: merged }
1170
- }
1171
- }
1172
-
1173
- return {
1174
- meta,
1175
- fallbackModels: product.fallbackModels,
1176
- fetchModels,
1177
- startLogin,
1178
- normalizeCredential,
1179
- refreshCredential,
1180
- needsRefresh,
1181
- describeCredential,
1182
- credentialIdentity,
1183
- complete,
1184
- claimCredits: credential => qoderClaimDaily(credential, product),
1185
- fetchCreditBalance: credential => qoderFetchBalance(credential, product),
1186
- }
1187
- }
1188
-
1189
- // ── 积分余额与每日领取 ──────────────────────────────────────────────────────
1190
- //
1191
- // `/sash/` 端点**不需要 WASM 签名**,但必须带桌面 app 身份头:
1192
- // - `Cosy-ClientType` = product.sashClientType('10';CLI 的 '5' 会让
1193
- // campaigns 恒返回空);
1194
- // - `Cosy-MachineToken` + `Cosy-MachineType`(**必须成对**,缺一服务端只回
1195
- // VIEW_DETAILS 不回 CLAIM_BENEFIT,进而被误判「今天已领」)。
1196
- // machine 头来自本机 Qoder 客户端:主路径实时 spawn `runtime-info.exe`
1197
- // (参数必须 [environment='3', '--account-stdin'],漏 env 会拿到另一套身份),
1198
- // 退路读磁盘缓存 machine_token.json;都拿不到则**不带这两个头**(保守降级,
1199
- // 与修复前行为一致 —— 漏发安全,发空头反而可能被按非法设备处理)。
1200
-
1201
- const QODER_USAGE_PATH = '/sash/api/v2/me/usage'
1202
- const QODER_CAMPAIGNS_PATH = '/sash/api/v1/me/campaigns'
1203
- const QODER_CREDITS_TIMEOUT_MS = 15_000
1204
-
1205
- /** 每日活动刷新时刻(UTC+8 小时,服务端下发原文)。刷新前看到的全是昨天那一轮。 */
1206
- const QODER_CAMPAIGN_REFRESH_HOUR_UTC8 = 10
1207
-
1208
- const QODER_NOT_ACTIVATED_HINT =
1209
- '该账号尚未在 Qoder 侧开通每日领取(每日 100 Credits)。' +
1210
- '请先用 Qoder 官方客户端登录一次该账号,开通后再回来领取。'
1211
- const QODER_NOT_REFRESHED_YET_HINT =
1212
- `今天的每日活动尚未刷新(每日 ${QODER_CAMPAIGN_REFRESH_HOUR_UTC8}:00(UTC+8)刷新),` +
1213
- '当前看到的是昨天那一轮,请稍后再来领取。'
1214
-
1215
- /** 今天的活动列表是否已刷新(按 UTC+8 算术平移;不能取本机时区)。 */
1216
- function hasQoderCampaignRefreshedToday(nowMs = Date.now()) {
1217
- return utc8Hour(nowMs) >= QODER_CAMPAIGN_REFRESH_HOUR_UTC8
1218
- }
1219
-
1220
- // ── 设备身份(Cosy-MachineToken + Cosy-MachineType)─────────────────────────
1221
-
1222
- const RUNTIME_INFO_TIMEOUT_MS = 20_000
1223
- /** runtime-info.exe 的 environment 位置参数(源码 'global' 分支;IDE 抓包实测用 3)。 */
1224
- const RUNTIME_INFO_ENVIRONMENT = '3'
1225
-
1226
- /** 进程内缓存:undefined=未解析,null=已确认拿不到,对象=成功。 */
1227
- let qoderMachineCache
1228
-
1229
- /** machine_token.json 候选路径(退路;实测可长期陈旧,但「聊胜于无」)。 */
1230
- function qoderMachineCandidatePaths() {
1231
- const override = process.env.QODER_MACHINE_TOKEN_PATH
1232
- if (override && override.length > 0) return [override]
1233
- const paths = []
1234
- const appData = process.env.APPDATA
1235
- if (appData && appData.length > 0) {
1236
- for (const dir of ['Qoder', 'Qoder CN']) {
1237
- paths.push(join(appData, dir, 'SharedClientCache', 'cache', 'machine_token.json'))
1238
- }
1239
- }
1240
- const home = homedir()
1241
- for (const dir of ['Qoder', 'Qoder CN']) {
1242
- paths.push(join(home, 'Library', 'Application Support', dir, 'SharedClientCache', 'cache', 'machine_token.json'))
1243
- paths.push(join(home, '.config', dir, 'SharedClientCache', 'cache', 'machine_token.json'))
1244
- }
1245
- return paths
1246
- }
1247
-
1248
- /** 解析 machine_token.json 的 {token,type};两者须都非空(配对是服务端必要条件)。 */
1249
- function parseQoderMachineFile(path) {
1250
- let raw
1251
- try { raw = readFileSync(path, 'utf8') } catch { return undefined }
1252
- let parsed
1253
- try { parsed = JSON.parse(raw) } catch { return undefined }
1254
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
1255
- const token = parsed.token
1256
- const type = parsed.type
1257
- if (typeof token !== 'string' || token.length === 0) return undefined
1258
- if (typeof type !== 'string' || type.length === 0) return undefined
1259
- return { token, type }
1260
- }
1261
-
1262
- /**
1263
- * 定位 `<home>/.qoder|.qoder-cn/.bin/umid-<hash>/runtime-info(.exe)`。
1264
- * 目录名带哈希(随版本变)必须枚举;某目录存在但 exe 缺失时继续试下一个
1265
- * (半安装残留会留下空目录)。实测两版 exe SHA256 相同、身份与产品无关。
1266
- */
1267
- function findQoderRuntimeInfo(home) {
1268
- const exeName = process.platform === 'win32' ? 'runtime-info.exe' : 'runtime-info'
1269
- for (const dirName of ['.qoder', '.qoder-cn']) {
1270
- const binDir = join(home, dirName, '.bin')
1271
- let entries
1272
- try { entries = readdirSync(binDir) } catch { continue }
1273
- const dir = entries.find(name => name.startsWith('umid-'))
1274
- if (dir === undefined) continue
1275
- const exe = join(binDir, dir, exeName)
1276
- if (existsSync(exe)) return exe
1277
- }
1278
- return undefined
1279
- }
1280
-
1281
- function locateQoderRuntimeInfo() {
1282
- const fromEnv = process.env.QODER_RUNTIME_INFO
1283
- const candidate = fromEnv && fromEnv.length > 0 ? fromEnv : undefined
1284
- if (candidate !== undefined) return existsSync(candidate) ? candidate : undefined
1285
- return findQoderRuntimeInfo(homedir())
1286
- }
1287
-
1288
- /** 解析 runtime-info.exe 单行 JSON 输出(即便 accountOutcome 非 success 也照取)。 */
1289
- function parseRuntimeInfoOutput(out) {
1290
- const start = out.indexOf('{')
1291
- if (start < 0) return undefined
1292
- let parsed
1293
- try { parsed = JSON.parse(out.slice(start)) } catch { return undefined }
1294
- if (parsed === null || typeof parsed !== 'object') return undefined
1295
- const token = parsed.machineToken
1296
- const type = parsed.machineType
1297
- if (typeof token !== 'string' || token.length === 0) return undefined
1298
- if (typeof type !== 'string' || type.length === 0) return undefined
1299
- return { token, type }
1300
- }
1301
-
1302
- /** 异步 spawn runtime-info.exe(实测约 3.8 秒;参数顺序 [env, --account-stdin] 不可反)。 */
1303
- function readFromQoderRuntimeInfoAsync() {
1304
- const exe = locateQoderRuntimeInfo()
1305
- if (exe === undefined) return Promise.resolve(undefined)
1306
- return new Promise(resolve => {
1307
- let settled = false
1308
- const done = value => {
1309
- if (settled) return
1310
- settled = true
1311
- resolve(value)
1312
- }
1313
- let child
1314
- try {
1315
- child = spawn(exe, [RUNTIME_INFO_ENVIRONMENT, '--account-stdin'], { windowsHide: true })
1316
- } catch {
1317
- done(undefined)
1318
- return
1319
- }
1320
- const timer = setTimeout(() => {
1321
- try { child.kill() } catch { /* 忽略 */ }
1322
- done(undefined)
1323
- }, RUNTIME_INFO_TIMEOUT_MS)
1324
- timer.unref?.()
1325
- let stdout = ''
1326
- child.stdout?.on('data', chunk => { stdout += String(chunk) })
1327
- child.stderr?.on('data', () => {}) // 必须消费,否则管道填满会阻塞子进程
1328
- child.once('error', () => { clearTimeout(timer); done(undefined) })
1329
- child.once('close', () => { clearTimeout(timer); done(parseRuntimeInfoOutput(stdout)) })
1330
- child.stdin?.on('error', () => {})
1331
- child.stdin?.end(JSON.stringify({ account: '' }))
1332
- })
1333
- }
1334
-
1335
- /** 解析设备身份(进程内缓存,含「拿不到」);拿不到返回 undefined。 */
1336
- async function resolveQoderMachineIdentity() {
1337
- if (qoderMachineCache !== undefined) return qoderMachineCache ?? undefined
1338
- const live = await readFromQoderRuntimeInfoAsync()
1339
- if (live) {
1340
- qoderMachineCache = live
1341
- return live
1342
- }
1343
- for (const path of qoderMachineCandidatePaths()) {
1344
- const identity = parseQoderMachineFile(path)
1345
- if (identity) {
1346
- qoderMachineCache = identity
1347
- return identity
1348
- }
1349
- }
1350
- qoderMachineCache = null
1351
- return undefined
1352
- }
1353
-
1354
- function qoderBearerToken(credential) {
1355
- return credential?.security_oauth_token || credential?.access_token || ''
1356
- }
1357
-
1358
- /** `/sash/` 端点公共请求头(machine 头成对出现,缺一不发)。 */
1359
- async function qoderCreditsHeaders(credential, product) {
1360
- const identity = await resolveQoderMachineIdentity()
1361
- return {
1362
- Accept: 'application/json',
1363
- Authorization: `Bearer ${qoderBearerToken(credential)}`,
1364
- 'Cosy-ClientType': product.sashClientType,
1365
- 'User-Agent': 'Qoder',
1366
- ...(identity ? { 'Cosy-MachineToken': identity.token, 'Cosy-MachineType': identity.type } : {}),
1367
- }
1368
- }
1369
-
1370
- // ── 余额(/sash/api/v2/me/usage)────────────────────────────────────────────
1371
-
1372
- function readNumber(source, key) {
1373
- if (source === null || typeof source !== 'object') return undefined
1374
- const value = source[key]
1375
- if (typeof value === 'number' && Number.isFinite(value)) return value
1376
- if (typeof value === 'string' && value.trim().length > 0) {
1377
- const parsed = Number(value)
1378
- return Number.isFinite(parsed) ? parsed : undefined
1379
- }
1380
- return undefined
1381
- }
1382
-
1383
- /**
1384
- * quota 对象 → CreditPackage。remaining 缺失时按 total-used 计算;
1385
- * 负值一律 clamp 到 0(计量回滚会下发负值,原样透出会显示「-12.5 积分」)。
1386
- */
1387
- function qoderPackage(name, quota, expiredTime = '') {
1388
- const total = readNumber(quota, 'total')
1389
- const used = readNumber(quota, 'used')
1390
- const remainingRaw = readNumber(quota, 'remaining')
1391
- if (total === undefined && used === undefined && remainingRaw === undefined) return undefined
1392
- const totalValue = Math.max(0, total ?? 0)
1393
- const usedValue = Math.max(0, used ?? 0)
1394
- const remaining = remainingRaw !== undefined
1395
- ? Math.max(0, remainingRaw)
1396
- : Math.max(0, totalValue - usedValue)
1397
- const expMs = expiredTime.length > 0 ? Date.parse(expiredTime.replace(' ', 'T')) : Number.NaN
1398
- return {
1399
- name,
1400
- unit: readStringField(quota, ['unit']) ?? 'credits',
1401
- remaining,
1402
- total: totalValue,
1403
- used: usedValue,
1404
- active: true,
1405
- cycleStartTime: '',
1406
- cycleEndTime: '',
1407
- expiredTime,
1408
- ...(Number.isFinite(expMs) ? { deductionEndTime: expMs } : {}),
1409
- }
1410
- }
1411
-
1412
- /** 拉取用量原始响应(给「未开通」判定喂判据);失败返回 undefined。 */
1413
- async function fetchQoderUsageRaw(credential, product) {
1414
- try {
1415
- const response = await httpFetch(`${product.openApiBase}${QODER_USAGE_PATH}`, {
1416
- method: 'GET',
1417
- headers: await qoderCreditsHeaders(credential, product),
1418
- }, QODER_CREDITS_TIMEOUT_MS)
1419
- if (!response.ok) return undefined
1420
- return await response.json().catch(() => undefined)
1421
- } catch {
1422
- return undefined
1423
- }
1424
- }
1425
-
1426
- /**
1427
- * 「未开通」判据(两条同时满足):活动列表无 CLAIM_BENEFIT(连已领的都没有)
1428
- * 且 usage 里 `addOnQuota` 字段**缺失**(是缺失不是 0 —— 已开通账号额度用尽
1429
- * 也有该字段;用「是否为 0」会把用光额度的老账号误报成未开通)。
1430
- */
1431
- function isQoderNotActivated(campaigns, usageBody) {
1432
- if (campaigns === undefined) return false
1433
- if (campaigns.some(c => c.actionType === 'CLAIM_BENEFIT')) return false
1434
- if (usageBody === null || typeof usageBody !== 'object') return false
1435
- const usage = usageBody.qoderUsage
1436
- if (usage === null || typeof usage !== 'object') return false
1437
- return usage.addOnQuota === undefined
1438
- }
1439
-
1440
- /** 读 benefit.amount(嵌套一层)。 */
1441
- function benefitAmount(item) {
1442
- if (item === null || typeof item !== 'object') return undefined
1443
- return readNumber(item.benefit, 'amount')
1444
- }
1445
-
1446
- /** 解析 campaigns 响应;形状非法返回 undefined。 */
1447
- function parseQoderCampaigns(body) {
1448
- if (body === null || typeof body !== 'object' || Array.isArray(body)) return undefined
1449
- const raw = body.campaigns
1450
- const campaigns = []
1451
- if (Array.isArray(raw)) {
1452
- for (const item of raw) {
1453
- const id = readStringField(item, ['campaignId'])
1454
- if (id === undefined) continue
1455
- campaigns.push({
1456
- campaignId: id,
1457
- campaignKey: readStringField(item, ['campaignKey']),
1458
- actionType: readStringField(item, ['actionType']),
1459
- claimStatus: readStringField(item, ['claimStatus']),
1460
- amount: benefitAmount(item),
1461
- })
1462
- }
1463
- }
1464
- return campaigns
1465
- }
1466
-
1467
- /** 可领取活动:CLAIM_BENEFIT 且 CLAIMABLE(VIEW_DETAILS 只是跳转详情,不能领)。 */
1468
- function claimableCampaigns(campaigns) {
1469
- return campaigns.filter(c => c.actionType === 'CLAIM_BENEFIT' && c.claimStatus === 'CLAIMABLE')
1470
- }
1471
-
1472
- async function loadQoderCampaigns(credential, product) {
1473
- try {
1474
- const response = await httpFetch(`${product.openApiBase}${QODER_CAMPAIGNS_PATH}`, {
1475
- method: 'GET',
1476
- headers: await qoderCreditsHeaders(credential, product),
1477
- }, QODER_CREDITS_TIMEOUT_MS)
1478
- if (!response.ok) return undefined
1479
- const body = await response.json().catch(() => undefined)
1480
- return body === undefined ? undefined : parseQoderCampaigns(body)
1481
- } catch {
1482
- return undefined
1483
- }
1484
- }
1485
-
1486
- /** 查询余额;null = 查不到(与「余额 0」严格区分)。企业版也返回 null(无额度数字)。 */
1487
- async function qoderFetchBalance(credential, product) {
1488
- let body
1489
- try {
1490
- const response = await httpFetch(`${product.openApiBase}${QODER_USAGE_PATH}`, {
1491
- method: 'GET',
1492
- headers: await qoderCreditsHeaders(credential, product),
1493
- }, QODER_CREDITS_TIMEOUT_MS)
1494
- if (!response.ok) return null
1495
- body = await response.json().catch(() => null)
1496
- } catch {
1497
- return null
1498
- }
1499
- if (body === null || typeof body !== 'object' || Array.isArray(body)) return null
1500
- if (body.displayMode === 'enterprise') return null
1501
- const usage = body.qoderUsage
1502
- if (usage === null || typeof usage !== 'object') return null
1503
-
1504
- const packages = []
1505
- // ⚠️ 余额不只在 userQuota:实测 userQuota=0 而 addOnQuota=100(「资源包」)。
1506
- // 顺序即展示顺序:套餐额度 → 资源包 → 专用资源包。
1507
- const userQuota = qoderPackage('套餐额度', usage.userQuota)
1508
- if (userQuota !== undefined) packages.push(userQuota)
1509
- const addOnQuota = qoderPackage('资源包', usage.addOnQuota)
1510
- if (addOnQuota !== undefined) packages.push(addOnQuota)
1511
- const dedicated = usage.dedicatedResourcePackages
1512
- if (Array.isArray(dedicated)) {
1513
- for (const item of dedicated) {
1514
- const pkg = qoderPackage(
1515
- readStringField(item, ['name']) ?? readStringField(item, ['id']) ?? '专用资源包',
1516
- item,
1517
- readStringField(item, ['expiresAt', 'expires_at']) ?? '',
1518
- )
1519
- if (pkg !== undefined) packages.push(pkg)
1520
- }
1521
- }
1522
- // 一个包都没解析出来 → 「查不到」而非「余额 0」(后者会让用户以为额度被清空)。
1523
- if (packages.length === 0) return null
1524
- const total = roundCredits(packages.reduce((sum, pkg) => sum + pkg.remaining, 0))
1525
- return { total, packages, expiredTotal: 0 }
1526
- }
1527
-
1528
- // ── 每日领取(campaigns → claim)────────────────────────────────────────────
1529
-
1530
- /** 非 JSON 响应的可读原因(凭据失效时网关返回 HTML)。 */
1531
- function qoderDescribeNonJson(status, text) {
1532
- if (status === 401 || status === 403) return `凭据已失效(HTTP ${status}),请重新登录该账号`
1533
- const snippet = String(text ?? '').trim().slice(0, 80).replace(/\s+/g, ' ')
1534
- return `服务端返回了非 JSON 响应(HTTP ${status}):${snippet}`
1535
- }
1536
-
1537
- /**
1538
- * 领单个活动。⚠️ 幂等判据是响应体 `replayed:true`,**不是 HTTP 状态码**
1539
- * (重复领取同样 200,但 replayed:true、不含 benefit、claimedAt 是旧时间)。
1540
- * ⚠️ 请求体必须是**空串**(抓包 content-length: 0)。
1541
- */
1542
- async function claimQoderCampaign(credential, product, campaignId) {
1543
- const url = `${product.openApiBase}${QODER_CAMPAIGNS_PATH}/${encodeURIComponent(campaignId)}/claim`
1544
- let response
1545
- try {
1546
- response = await httpFetch(url, {
1547
- method: 'POST',
1548
- headers: { ...(await qoderCreditsHeaders(credential, product)), 'Content-Type': 'application/json' },
1549
- body: '',
1550
- }, QODER_CREDITS_TIMEOUT_MS)
1551
- } catch (error) {
1552
- return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
1553
- }
1554
- const text = await readBodyText(response).catch(() => '')
1555
- let body
1556
- try {
1557
- body = text.length > 0 ? JSON.parse(text) : {}
1558
- } catch {
1559
- return { kind: 'failed', code: response.status, message: qoderDescribeNonJson(response.status, text) }
1560
- }
1561
- if (!response.ok) {
1562
- return { kind: 'failed', code: response.status, message: qoderDescribeNonJson(response.status, text) }
1563
- }
1564
- const status = readStringField(body, ['status'])
1565
- if (body?.replayed === true) return { kind: 'already-claimed', message: '今天已领取' }
1566
- if (status !== undefined && status !== 'CLAIMED') {
1567
- return { kind: 'failed', code: -1, message: `领取未成功(status=${status})` }
1568
- }
1569
- return { kind: 'claimed', credit: benefitAmount(body) ?? 0, streakDays: 0, isStreakDay: false }
1570
- }
1571
-
1572
- /**
1573
- * 领取该账号**当前所有**可领活动(一个账号可能同时挂多个 CLAIM_BENEFIT),
1574
- * 汇总为一条 ClaimOutcome:
1575
- * 无可领 → inactive(⚠️ 不是 already-claimed:没东西可领 ≠ 领过了);
1576
- * 至少一个成功 → claimed(累计 credit);全部 replayed → already-claimed;
1577
- * 全部失败 → failed(带第一条原因)。
1578
- */
1579
- async function qoderClaimDaily(credential, product, nowMs = Date.now()) {
1580
- const campaigns = await loadQoderCampaigns(credential, product)
1581
- if (campaigns === undefined) {
1582
- return { kind: 'failed', code: -1, message: '活动列表查询失败' }
1583
- }
1584
-
1585
- // 刷新前(每日 10:00 UTC+8)看到的全是昨天那一轮:领到也只能算补领,
1586
- // 必须 coversToday:false + pending:true,否则上层把昨天那条已领记成今天已跑 ⇒
1587
- // 当天 10 点刷新后的新额度整天漏领(不可逆方向)。pending 让上层只重试本渠道。
1588
- const refreshed = hasQoderCampaignRefreshedToday(nowMs)
1589
- const stale = refreshed ? {} : { coversToday: false, pending: true }
1590
-
1591
- const targets = claimableCampaigns(campaigns)
1592
- if (targets.length === 0) {
1593
- // 三种「没领到」:① 领过(仅限刷新之后)② 未开通 ③ 暂时没活动。
1594
- const claimedBefore = campaigns.some(c => c.actionType === 'CLAIM_BENEFIT' && c.claimStatus === 'CLAIMED')
1595
- if (claimedBefore) {
1596
- // 刷新前那条 CLAIMED 属于昨天,说成「今天已领取」是谎报(方向不可逆)。
1597
- // 标 pending(可重试):10:00 刷新后还要再来一次;「未开通」则保持终态。
1598
- if (!refreshed) return { kind: 'inactive', message: QODER_NOT_REFRESHED_YET_HINT, coversToday: false, pending: true }
1599
- return { kind: 'already-claimed', message: '今天已领取' }
1600
- }
1601
- // 未开通额外查一次用量(只读)确认 —— 两条判据同时满足才提示。
1602
- const usage = await fetchQoderUsageRaw(credential, product)
1603
- if (isQoderNotActivated(campaigns, usage)) {
1604
- return { kind: 'inactive', message: QODER_NOT_ACTIVATED_HINT, actionRequired: true }
1605
- }
1606
- return { kind: 'inactive', message: '当前没有可领取的活动' }
1607
- }
1608
-
1609
- let total = 0
1610
- let firstError
1611
- for (const target of targets) {
1612
- const outcome = await claimQoderCampaign(credential, product, target.campaignId)
1613
- if (outcome.kind === 'claimed') total += outcome.credit
1614
- else if (outcome.kind === 'failed' && firstError === undefined) firstError = outcome.message
1615
- }
1616
- if (total > 0) return { kind: 'claimed', credit: total, streakDays: 0, isStreakDay: false, ...stale }
1617
- if (firstError !== undefined) return { kind: 'failed', code: -1, message: firstError, ...stale }
1618
- return { kind: 'already-claimed', message: '今天已领取', ...stale }
1619
- }
1
+ /**
2
+ * Qoder 系渠道 —— Qoder(阿里国际) / QoderCN 共用工厂。
3
+ *
4
+ * 协议要点:
5
+ * - 登录:PKCE 设备码轮询(不起本地回调服务器)——
6
+ * 浏览器授权页 {authBase}/device/selectAccounts?challenge&challenge_method=S256
7
+ * &nonce&machine_id&client_id(client_id 必须用 prod 的那个),
8
+ * 轮询 GET {openApiBase}/api/v1/deviceToken/poll?nonce&verifier&challenge_method=S256,
9
+ * **404 = 用户尚未完成授权,继续轮询**(其它非 2xx 是服务端异常)。
10
+ * - 续期:POST {openApiBase}/api/v1/deviceToken/refresh,
11
+ * body {refresh_token, machine_id};machine_id 必须随凭据持久化并原样回传;
12
+ * 401/403 或 200 缺 token → 终态失效。
13
+ * - 凭据:security_oauth_token 与 access_token 双写同值(源码取用顺序
14
+ * security_oauth_token ?? access_token);uid(user_id)是**加密推理必需**
15
+ * (generate_runtime_auth_fields 派生 encrypt_user_info,缺了签名无效)。
16
+ * - 对话:只走**加密端点** POST {encryptedInferBase}/algo/api/v2/service/pro/sse/
17
+ * agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1。
18
+ * 请求体由内嵌 WASM(qoder-auth-wasm.js + qoder-auth-wasm.wasm)加密,
19
+ * Authorization 是 WASM 生成的 `Bearer COSY.<载荷>.<签名>`,**必须原样透传**
20
+ * (用普通 Bearer 覆盖 = 403 Signature invalid)。
21
+ * 该端点认**模型目录 key**(qfmodel 等);公开端点(通用名)不认这些 key。
22
+ * host:国际版 api2.qoder.sh / 国内版 gateway.qoder.com.cn(写错 404)。
23
+ * - 响应:SSE 每帧多一层信封 `{"headers":…,"body":"<内层 OpenAI chunk JSON>",
24
+ * "statusCodeValue":200,"statusCode":"OK"}` —— 内层 body **未加密**,只剥信封;
25
+ * 心跳帧(body:null/空对象)整帧跳过;错误帧带 code/message。
26
+ * - 错误形态:排队 = 业务码 10605(message 内嵌 JSON 带 retryAfterSeconds,
27
+ * 也可能 HTTP 200 + SSE 内嵌帧);额度用尽 = 业务码 110 或文案
28
+ * `Billing daily count exceeded`,按自然日(UTC+8)重置 → 冷却到当日 24:00;
29
+ * 认证失败 = 业务码 105 / HTTP 401。
30
+ * - business 字段({type:'agent'})必填:缺失时服务端把请求路由到故障节点
31
+ * oa_qwen-plus-2025-04-28(Execution failed),极易误判「模型服务端故障」。
32
+ * - 思考档位白名单:none/low/medium/high/xhigh/max(disabled/off → none),
33
+ * 白名单外的档位会被服务端静默丢弃。
34
+ * - 模型清单:GET {modelListBase}/algo/api/v2/model/list —— 与加密推理同一套
35
+ * 网络契约,必须带 WASM `prepareRequest(auth:'auth')` 生成的 COSY 签名头,
36
+ * 普通 Bearer 会 403 Signature invalid。拉不到一律抛错,不回落内置静态表。
37
+ */
38
+
39
+ import { createHash, randomBytes, randomUUID } from 'node:crypto'
40
+ import { spawn } from 'node:child_process'
41
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
42
+ import { homedir } from 'node:os'
43
+ import { join } from 'node:path'
44
+ import { httpFetch, readBodyText, readSseData, mergeSseChunks, roundCredits, utc8Hour } from '../util.js'
45
+ import { QoderEncryptedInfer } from './qoder-wasm.js'
46
+
47
+ // ── 协议路径与常量 ───────────────────────────────────────────────────────────
48
+
49
+ const DEVICE_SELECT_PATH = '/device/selectAccounts'
50
+ const POLL_PATH = '/api/v1/deviceToken/poll'
51
+ const REFRESH_PATH = '/api/v1/deviceToken/refresh'
52
+ const USERINFO_PATH = '/api/v1/userinfo'
53
+ /** 模型目录端点(同一个上游网关的 /algo 前缀由 WASM 自动拼接)。 */
54
+ const MODEL_LIST_PATH = '/api/v2/model/list'
55
+
56
+ const REQUEST_TIMEOUT_MS = 30_000
57
+ const MODEL_LIST_TIMEOUT_MS = 30_000
58
+ const BODY_READ_TIMEOUT_MS = 15_000
59
+ /** 登录等待总超时(源码 5 分钟,放宽到 10 分钟)。 */
60
+ const LOGIN_TIMEOUT_MS = 10 * 60_000
61
+ /** 轮询间隔(源码 Djr = 1e3)。 */
62
+ const POLL_INTERVAL_MS = 1_000
63
+ /** 轮询连续网络失败容忍次数。 */
64
+ const POLL_MAX_FAILURES = 5
65
+ /** 续期提前量:过期前 1 小时即刷。 */
66
+ const REFRESH_LEAD_MS = 60 * 60_000
67
+
68
+ /**
69
+ * 排队处理预算(本实现的偏离说明):
70
+ * OMR 的请求方网关层有硬编码超时,等 30 分钟毫无意义,
71
+ * 故收紧为总预算 120 秒 / 最多 12 次,单次等待封顶 10s。
72
+ */
73
+ const QUEUE_TOTAL_BUDGET_MS = 120_000
74
+ const QUEUE_MAX_ATTEMPTS = 12
75
+ const QUEUE_MAX_DELAY_MS = 10_000
76
+
77
+ /** 思考档位白名单(客户端 asar 常量 Qj);别名表 _lc:disabled/off → none。 */
78
+ const EFFORT_WHITELIST = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
79
+ const EFFORT_ALIASES = { disabled: 'none', off: 'none' }
80
+
81
+ /** 排队业务码(客户端 obf 产物 mRA)。 */
82
+ const QUEUE_BUSINESS_CODE = '10605'
83
+ /** 额度用尽业务码。 */
84
+ const BILLING_BUSINESS_CODE = '110'
85
+
86
+ /** PKCE 字符集(源码 Y_a:66 字符取模选取,与 RFC 7636 unreserved 一致)。 */
87
+ const PKCE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
88
+
89
+ // ── 静态模型元数据表(仅补推理参数,**不再是清单来源**)─────────────────────
90
+ // 清单由 fetchModels 实时拉取上游目录;这张表只在 complete() 里给已知模型补
91
+ // is_vl / is_reasoning / display_name / contextWindow(上游目录不随每次对话下发)。
92
+ // contextWindow 取官方档位表 context_config 的最大档(有 1M 档就填 1M)。
93
+ // priceFactor:目录 price_factor(采集时刻的生效价;0 是免费,不是缺失)。
94
+ // promotion:错峰折扣窗口,展示时按本地时间推算,不用采集快照。
95
+
96
+ const QODER_FALLBACK_MODELS = [
97
+ { id: 'auto', name: 'Auto', contextWindow: 200_000, supportsImage: true, supportsThinking: false, priceFactor: 0.5 },
98
+ { id: 'ultimate', name: 'Ultimate', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 2, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'high', supportsDisable: true },
99
+ { id: 'performance', name: 'Performance', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 1.1, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'medium', supportsDisable: true },
100
+ { id: 'efficient', name: 'Efficient', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 0.3 },
101
+ { id: 'smodel', name: 'Sonus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 8, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'high' },
102
+ { id: 'cmodel', name: 'Cantus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 4, efforts: ['xhigh', 'high', 'low', 'max', 'medium'], defaultEffort: 'high' },
103
+ {
104
+ id: 'qmodel_38max', name: 'Qwen3.8-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
105
+ isFree: true, priceFactor: 0.2, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'xhigh', supportsDisable: true,
106
+ promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
107
+ },
108
+ // priceFactor 0 = 免费(合法值,不能当缺失)。
109
+ {
110
+ id: 'qfmodel', name: 'Qwen3.8-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
111
+ isFree: true, priceFactor: 0, originalPriceFactor: 0.1, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'medium', supportsDisable: true,
112
+ },
113
+ {
114
+ id: 'qmodel_latest', name: 'Qwen3.7-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false,
115
+ priceFactor: 0.1, originalPriceFactor: 0.5, supportsDisable: true,
116
+ promotion: { active: true, discountFactor: 0.2, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
117
+ },
118
+ {
119
+ id: 'qmodel', name: 'Qwen3.7-Plus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false,
120
+ priceFactor: 0.04, supportsDisable: true,
121
+ promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.1, windowStart: '22:00', windowEnd: '08:00' },
122
+ },
123
+ { id: 'kmodel_latest', name: 'Kimi-K3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 1.4, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
124
+ { id: 'kmodel', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
125
+ { id: 'gmodel', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
126
+ { id: 'gfmodel', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ['high', 'max'], defaultEffort: 'max' },
127
+ { id: 'dmodel', name: 'DeepSeek-V4-Pro', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.5, efforts: ['high', 'max'], defaultEffort: 'max', supportsDisable: true },
128
+ { id: 'dfmodel', name: 'DeepSeek-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ['high', 'max', 'low'], defaultEffort: 'max', supportsDisable: true },
129
+ { id: 'mmodel', name: 'MiniMax-M3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: false, priceFactor: 0.2 },
130
+ ]
131
+
132
+ const QODER_CN_FALLBACK_MODELS = [
133
+ { id: 'auto', name: 'Auto', contextWindow: 200_000, supportsImage: true, supportsThinking: true, priceFactor: 0.5 },
134
+ {
135
+ id: 'qmodel_38max', name: 'Qwen3.8-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
136
+ isFree: true, priceFactor: 0.2, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'medium', supportsDisable: true,
137
+ promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
138
+ },
139
+ {
140
+ id: 'qfmodel', name: 'Qwen3.8-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
141
+ isFree: true, priceFactor: 0, originalPriceFactor: 0.1, efforts: ['xhigh', 'low', 'medium'], defaultEffort: 'medium', supportsDisable: true,
142
+ },
143
+ {
144
+ id: 'qmodel_latest', name: 'Qwen3.7-Max', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
145
+ priceFactor: 0.1, supportsDisable: true,
146
+ promotion: { active: true, discountFactor: 0.2, beforePromotionPriceFactor: 0.5, windowStart: '22:00', windowEnd: '08:00' },
147
+ },
148
+ {
149
+ id: 'qmodel', name: 'Qwen3.7-Plus', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true,
150
+ priceFactor: 0.04, supportsDisable: true,
151
+ promotion: { active: true, discountFactor: 0.4, beforePromotionPriceFactor: 0.1, windowStart: '22:00', windowEnd: '08:00' },
152
+ },
153
+ { id: 'q37fmodel', name: 'Qwen3.7-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1 },
154
+ { id: 'dmodel', name: 'DeepSeek-V4-Pro', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.5, efforts: ['high', 'max'], defaultEffort: 'max', supportsDisable: true },
155
+ { id: 'dfmodel', name: 'DeepSeek-Flash', contextWindow: 1_000_000, supportsImage: true, priceFactor: 0.1, efforts: ['high', 'max', 'low'], defaultEffort: 'max', supportsDisable: true },
156
+ { id: 'gmodel', name: 'GLM-5.3', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
157
+ { id: 'gfmodel', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ['high', 'max'], defaultEffort: 'max' },
158
+ { id: 'gm51model', name: 'GLM-5.2', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.6, efforts: ['high', 'max'], defaultEffort: 'max', supportsDisable: true },
159
+ { id: 'kmodel_latest', name: 'Kimi-K3', contextWindow: 1_000_000, supportsImage: true, priceFactor: 1.4, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
160
+ { id: 'kmodel', name: 'Kimi-K2.8-Preview', contextWindow: 1_000_000, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ['high', 'low', 'max'], defaultEffort: 'max' },
161
+ // CN 独有差异:MiniMax-M2.7(国际版 M3)、is_vl false、唯一 200K 档位表
162
+ { id: 'mmodel', name: 'MiniMax-M2.7', contextWindow: 200_000, priceFactor: 0.2 },
163
+ ]
164
+
165
+ // ── 匿名拉取模型目录的占位标识 ──────────────────────────────────────────────
166
+ //
167
+ // 上游模型目录(/algo/api/v2/model/list)只校验 COSY 签名,**不校验账号身份**:
168
+ // 用本地 WASM 生成的签名 + 空 token 就能拿到 HTTP 200 与完整目录(实测 2026-10-23)。
169
+ // 签名载荷里必须带一个**非空** uid,否则服务端回 403「Signature invalid (101)」。
170
+ //
171
+ // ⚠️ **占位 uid 不能是 UUID 形态**:UUID 形态会被上游当成「登录过的账号但令牌已过期」,
172
+ // 回 HTTP 403 code=105 Login expired;普通字符串(字母数字)才能通过并拿到完整目录。
173
+ // 占位 uid / machine id 只参与签名计算,不对应任何真实账号,也不携带任何凭据。
174
+
175
+ const QODER_ANONYMOUS_UID = 'omr-anonymous-guest'
176
+ const QODER_ANONYMOUS_MACHINE_ID = 'omr-anonymous-machine'
177
+
178
+ // ── 产品配置 ─────────────────────────────────────────────────────────────────
179
+
180
+ const QODER_PRODUCTS = {
181
+ qoder: {
182
+ id: 'qoder',
183
+ displayName: 'Qoder (国际版)',
184
+ authBase: 'https://qoder.com',
185
+ openApiBase: 'https://openapi.qoder.sh',
186
+ // ⚠️ 加密端点 host 是 api2.qoder.sh;公开端点的 api2-v2.qoder.sh 不是同一个 host
187
+ encryptedInferBase: 'https://api2.qoder.sh',
188
+ // 模型目录走 api3.qoder.sh(CLI 日志实测 operation=modelCatalogFetch),
189
+ // 与加密推理的 api2 不是同一个 host
190
+ modelListBase: 'https://api3.qoder.sh',
191
+ // prod 环境的 client id(源码 J_a;用成非 prod 的 G_a 会让授权回调被拒)
192
+ clientId: 'e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb',
193
+ clientMetadata: { client_type: '5', business_product: 'cli', business_type: 'agent', scene: 'assistant' },
194
+ // ⚠️ /sash/ 端点(活动、用量)用的客户端类型与推理的 client_type **不同**:
195
+ // '5'(CLI)时 /sash/api/v1/me/campaigns 恒返回 campaigns:[],
196
+ // 必须 '10'(桌面 app 身份)服务端才进入活动下发分支。
197
+ sashClientType: '10',
198
+ userAgentPrefix: 'qoder',
199
+ fallbackModels: QODER_FALLBACK_MODELS,
200
+ },
201
+ qodercn: {
202
+ id: 'qodercn',
203
+ displayName: 'Qoder (中国版)',
204
+ authBase: 'https://qoder.cn',
205
+ openApiBase: 'https://openapi.qoder.com.cn',
206
+ // E9:algo 网关在 CN 换域名,路径与协议同形
207
+ encryptedInferBase: 'https://gateway.qoder.com.cn',
208
+ // CN 的模型目录与加密推理同一个 host
209
+ modelListBase: 'https://gateway.qoder.com.cn',
210
+ // CN asar 的 Vpe.authClientIds.prod(与国际版完全不同,用错则授权报参数无效)
211
+ clientId: '732aef47-9cf2-46a2-95fe-4cebb5d0d1fa',
212
+ clientMetadata: { client_type: '5', business_product: 'cli', business_type: 'agent', scene: 'assistant' },
213
+ sashClientType: '10',
214
+ userAgentPrefix: 'qoder',
215
+ fallbackModels: QODER_CN_FALLBACK_MODELS,
216
+ },
217
+ }
218
+
219
+ // ── 小工具 ──────────────────────────────────────────────────────────────────
220
+
221
+ function readStringField(source, keys) {
222
+ for (const key of keys) {
223
+ const value = source?.[key]
224
+ if (typeof value === 'string' && value.length > 0) return value
225
+ }
226
+ return undefined
227
+ }
228
+
229
+ /** 把时间值解析成毫秒时间戳(兼容 ISO 字符串与数字秒/毫秒);绝不填 0。 */
230
+ function parseTimestamp(value) {
231
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
232
+ return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
233
+ }
234
+ if (typeof value === 'string' && value.length > 0) {
235
+ const parsed = Date.parse(value)
236
+ return Number.isFinite(parsed) ? parsed : undefined
237
+ }
238
+ return undefined
239
+ }
240
+
241
+ /** 解析 `HH:MM`(容忍不补零)为当日分钟数;非法返回 undefined。 */
242
+ function parseHHMM(value) {
243
+ if (typeof value !== 'string') return undefined
244
+ const m = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
245
+ if (m === null) return undefined
246
+ const h = Number(m[1])
247
+ const min = Number(m[2])
248
+ return h < 24 && min < 60 ? h * 60 + min : undefined
249
+ }
250
+
251
+ /**
252
+ * 取当前时刻在指定时区里的「当日分钟数」。时区缺失/非法时回退 UTC+8
253
+ * (目录的 Asia/Singapore 与 UTC+8 同偏移)。
254
+ */
255
+ function minutesInTimeZone(now, timeZone) {
256
+ if (typeof timeZone === 'string' && timeZone !== '') {
257
+ try {
258
+ const parts = new Intl.DateTimeFormat('en-GB', {
259
+ timeZone, hour: '2-digit', minute: '2-digit', hour12: false,
260
+ }).formatToParts(now)
261
+ const hour = Number(parts.find(p => p.type === 'hour')?.value)
262
+ const minute = Number(parts.find(p => p.type === 'minute')?.value)
263
+ if (Number.isFinite(hour) && Number.isFinite(minute)) {
264
+ return (hour % 24) * 60 + minute
265
+ }
266
+ } catch { /* 非法时区名回退 UTC+8 */ }
267
+ }
268
+ const shifted = new Date(now.getTime() + 8 * 3_600_000)
269
+ return shifted.getUTCHours() * 60 + shifted.getUTCMinutes()
270
+ }
271
+
272
+ /**
273
+ * 错峰折扣此刻是否生效(按当前时间推算)。
274
+ *
275
+ * ⚠️ 不能用目录的 `promotion.active`:那是采集时刻的快照,窗口切换后会失真
276
+ * (窗口外显示折后价 = 用户按折扣预期却被按原价计费)。窗口字段稳定,按当前
277
+ * 时间推算;支持跨零点(22:00–08:00)。窗口字段缺失时回退到 `active`。
278
+ */
279
+ function promotionActiveNow(promotion, now = new Date()) {
280
+ const start = parseHHMM(promotion?.windowStart)
281
+ const end = parseHHMM(promotion?.windowEnd)
282
+ if (start === undefined || end === undefined) return promotion?.active === true
283
+ const minutes = minutesInTimeZone(now, promotion?.timeZone)
284
+ return start <= end
285
+ ? minutes >= start && minutes < end
286
+ : minutes >= start || minutes < end
287
+ }
288
+
289
+ /**
290
+ * 由上游目录项的 `price_factor` + `promotion` 推算此刻的倍率字段。
291
+ *
292
+ * - `price_factor === 0` → `rate: 0`(免费,0 是合法值不能当缺失);
293
+ * - 折扣窗口内 → `rate` 取 `before_promotion_price_factor × discount_factor`
294
+ * (**不采信快照价**),`rateOriginal` 为原价;
295
+ * - 窗口外 → 用原价(有 promotion 时原价即 before),否则用 `price_factor`。
296
+ */
297
+ function liveRateFields(entry, now = new Date()) {
298
+ const price = entry?.price_factor
299
+ if (price === 0) return { rate: 0 }
300
+ const promo = entry?.promotion
301
+ const before = promo?.before_promotion_price_factor
302
+ const discount = promo?.discount_factor
303
+ const hasPromo = typeof before === 'number' && typeof discount === 'number'
304
+ if (hasPromo) {
305
+ const active = promotionActiveNow({
306
+ active: promo.active,
307
+ windowStart: promo.window_start,
308
+ windowEnd: promo.window_end,
309
+ timeZone: promo.timezone,
310
+ }, now)
311
+ if (active) {
312
+ const effective = Number((before * discount).toFixed(4))
313
+ return { rate: effective, ...(before > effective ? { rateOriginal: before } : {}) }
314
+ }
315
+ return { rate: before }
316
+ }
317
+ if (typeof price !== 'number' || !Number.isFinite(price)) return {}
318
+ return { rate: price }
319
+ }
320
+
321
+ /**
322
+ * 上游目录项的上下文窗口:优先取官方档位表 context_config 的最大档
323
+ * (有 1M 档就填 1M),其次才用 max_input_tokens(后者常是默认档而非上限)。
324
+ */
325
+ function contextWindowOf(entry) {
326
+ const config = entry?.context_config
327
+ if (config !== null && typeof config === 'object') {
328
+ const counts = Object.values(config)
329
+ .map(item => item?.token_count)
330
+ .filter(count => typeof count === 'number' && count > 0)
331
+ if (counts.length > 0) return Math.max(...counts)
332
+ }
333
+ const max = entry?.max_input_tokens
334
+ return typeof max === 'number' && max > 0 ? max : undefined
335
+ }
336
+
337
+ /** PKCE:verifier 43..128 位(源码 43 + floor(86*random)),challenge 去 padding。 */
338
+ function createPkce() {
339
+ const length = 43 + Math.floor(86 * Math.random())
340
+ const bytes = randomBytes(length)
341
+ let verifier = ''
342
+ for (let i = 0; i < length; i++) verifier += PKCE_ALPHABET[bytes[i] % PKCE_ALPHABET.length]
343
+ const challenge = createHash('sha256').update(verifier).digest()
344
+ .toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
345
+ return { verifier, challenge }
346
+ }
347
+
348
+ function isRefreshable(credential) {
349
+ return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
350
+ }
351
+
352
+ function credentialExpiresAtMs(credential) {
353
+ const value = credential?.expire_time
354
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
355
+ }
356
+
357
+ /** 睡眠(可被 signal 中断)。 */
358
+ function sleep(ms, signal) {
359
+ return new Promise((resolve, reject) => {
360
+ if (signal?.aborted) { reject(new Error('登录已取消')); return }
361
+ const timer = setTimeout(() => {
362
+ signal?.removeEventListener('abort', onAbort)
363
+ resolve()
364
+ }, ms)
365
+ const onAbort = () => { clearTimeout(timer); reject(new Error('登录已取消')) }
366
+ signal?.addEventListener('abort', onAbort, { once: true })
367
+ })
368
+ }
369
+
370
+ /** UTC+8 当日 24:00 的毫秒时间戳(额度按自然日重置)。 */
371
+ function nextUtc8DayStartMs() {
372
+ const now = Date.now()
373
+ const shifted = now + 8 * 3_600_000
374
+ const msIntoDay = ((shifted % 86_400_000) + 86_400_000) % 86_400_000
375
+ return now + (86_400_000 - msIntoDay)
376
+ }
377
+
378
+ function looksLikeBillingError(text) {
379
+ return /billing\s+daily\s+count\s+exceeded|daily\s+count\s+exceeded|billing_error/i.test(String(text ?? ''))
380
+ }
381
+
382
+ function isQueueCode(code) {
383
+ return code === QUEUE_BUSINESS_CODE || code === Number(QUEUE_BUSINESS_CODE)
384
+ }
385
+
386
+ function isBillingCode(code) {
387
+ return code === BILLING_BUSINESS_CODE || code === Number(BILLING_BUSINESS_CODE)
388
+ }
389
+
390
+ /** 从错误体抽人可读消息(JSON message/error/msg → 原文截断)。 */
391
+ function extractMessage(bodyText) {
392
+ const text = String(bodyText ?? '').trim()
393
+ if (text === '') return ''
394
+ try {
395
+ const parsed = JSON.parse(text)
396
+ const found = [parsed?.message, parsed?.error?.message ?? (typeof parsed?.error === 'string' ? parsed.error : ''), parsed?.msg]
397
+ .filter(v => typeof v === 'string' && v.length > 0)
398
+ if (found.length > 0) return found.join(' ').slice(0, 300)
399
+ } catch { /* 非 JSON */ }
400
+ return text.slice(0, 300)
401
+ }
402
+
403
+ /**
404
+ * 解析排队信息。
405
+ * 广度优先展开 data/result/message/body 键(字符串再 JSON.parse);
406
+ * 业务码命中**或**节点含 isQueued/serviceAvailable 标志即视为排队。
407
+ * ⚠️ 不能要求 isQueued===true:瞬时排队实测为 isQueued:false + retryAfterSeconds:2。
408
+ */
409
+ function parseQueueError(body) {
410
+ let root = body
411
+ if (typeof body === 'string') {
412
+ try { root = JSON.parse(body) } catch { return undefined }
413
+ }
414
+ if (root === null || typeof root !== 'object') return undefined
415
+
416
+ const seen = new Set()
417
+ const nodes = []
418
+ const queue = [root]
419
+ while (queue.length > 0) {
420
+ const node = queue.shift()
421
+ if (node === null || typeof node !== 'object' || seen.has(node)) continue
422
+ seen.add(node)
423
+ nodes.push(node)
424
+ for (const key of ['data', 'result', 'message', 'body']) {
425
+ const value = node[key]
426
+ if (value !== null && typeof value === 'object') queue.push(value)
427
+ else if (typeof value === 'string' && value.length > 0) {
428
+ try { queue.push(JSON.parse(value)) } catch { /* 非 JSON,忽略 */ }
429
+ }
430
+ }
431
+ }
432
+
433
+ const info = nodes.find(node => node.isQueued !== undefined || node.serviceAvailable !== undefined)
434
+ if (info === undefined) return undefined
435
+ const codeHit = nodes.some(node => isQueueCode(node.code))
436
+ if (!codeHit && info.isQueued === undefined) return undefined
437
+
438
+ const readFinite = v => (typeof v === 'number' && Number.isFinite(v) ? Math.trunc(v) : undefined)
439
+ return {
440
+ ...(typeof info.isQueued === 'boolean' ? { isQueued: info.isQueued } : {}),
441
+ retry_after_ms: readFinite(info.retry_after_ms),
442
+ retryAfterMs: readFinite(info.retryAfterMs),
443
+ retryAfterSeconds: readFinite(info.retryAfterSeconds),
444
+ waitTime: readFinite(info.waitTime),
445
+ }
446
+ }
447
+
448
+ /** 单次排队等待时长:retry_after_ms → retryAfterMs → retryAfterSeconds×1000,封顶 10s。 */
449
+ function queueDelayMs(info) {
450
+ if (info === undefined) return undefined
451
+ const raw = info.retry_after_ms ?? info.retryAfterMs
452
+ ?? (info.retryAfterSeconds !== undefined ? info.retryAfterSeconds * 1000 : undefined)
453
+ if (raw === undefined || raw < 0) return undefined
454
+ return Math.min(Math.trunc(raw), QUEUE_MAX_DELAY_MS)
455
+ }
456
+
457
+ // ── token 载荷与凭据 ─────────────────────────────────────────────────────────
458
+
459
+ /**
460
+ * 解析轮询/续期响应。登录响应用 `token`,续期响应用 `device_token` —— 都接受。
461
+ * 垃圾输入返回空 accessToken,由调用方判定失败。
462
+ * ⚠️ 设备码响应带 user_id/user_name,**加密推理需要 uid**,漏读只能走公开端点。
463
+ */
464
+ function parseTokenPayload(value) {
465
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return { accessToken: '' }
466
+ const accessToken = readStringField(value, ['token', 'device_token', 'access_token']) ?? ''
467
+ const refreshToken = readStringField(value, ['refresh_token', 'refreshToken'])
468
+ const expiresAt = parseTimestamp(value.expires_at ?? value.expiresAt)
469
+ const refreshTokenExpiresAt = parseTimestamp(value.refresh_token_expires_at ?? value.refreshTokenExpiresAt)
470
+ const uid = readStringField(value, ['user_id', 'userId'])
471
+ const userName = readStringField(value, ['user_name', 'userName'])
472
+ return {
473
+ accessToken,
474
+ ...(refreshToken ? { refreshToken } : {}),
475
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
476
+ ...(refreshTokenExpiresAt !== undefined ? { refreshTokenExpiresAt } : {}),
477
+ ...(uid ? { uid } : {}),
478
+ ...(userName ? { userName } : {}),
479
+ }
480
+ }
481
+
482
+ /** 构造持久化凭据:security_oauth_token 与 access_token 双写同值。 */
483
+ function buildCredential(payload, machineId, nickname) {
484
+ const name = nickname || payload.userName || ''
485
+ return {
486
+ security_oauth_token: payload.accessToken,
487
+ access_token: payload.accessToken,
488
+ ...(payload.refreshToken ? { refresh_token: payload.refreshToken } : {}),
489
+ ...(payload.expiresAt !== undefined ? { expire_time: payload.expiresAt } : {}),
490
+ ...(payload.refreshTokenExpiresAt !== undefined ? { refresh_token_expire_time: payload.refreshTokenExpiresAt } : {}),
491
+ machine_id: machineId,
492
+ ...(payload.uid ? { uid: payload.uid } : {}),
493
+ ...(name ? { nickname: name } : {}),
494
+ }
495
+ }
496
+
497
+ /**
498
+ * 用续期结果覆盖旧凭据。**保留** machine_id / uid / nickname:
499
+ * 它们不在续期响应里,丢失会让下一次续期缺设备标识、或让加密推理缺 uid。
500
+ * 续期响应若未带新 refresh_token,沿用旧的。
501
+ */
502
+ function applyRefresh(credential, payload) {
503
+ const next = {
504
+ ...credential,
505
+ security_oauth_token: payload.accessToken,
506
+ access_token: payload.accessToken,
507
+ }
508
+ if (payload.refreshToken) next.refresh_token = payload.refreshToken
509
+ if (payload.expiresAt !== undefined) next.expire_time = payload.expiresAt
510
+ if (payload.refreshTokenExpiresAt !== undefined) next.refresh_token_expire_time = payload.refreshTokenExpiresAt
511
+ return next
512
+ }
513
+
514
+ // ── 渠道工厂 ────────────────────────────────────────────────────────────────
515
+
516
+ /**
517
+ * Qoder 系渠道工厂。id 取 'qoder' | 'qodercn';未知 id 返回 null(注册表跳过)。
518
+ * 两个产品的协议实现完全共用,差异全部收敛在产品配置里。
519
+ */
520
+ export function qoderChannel(id) {
521
+ const product = QODER_PRODUCTS[id]
522
+ if (!product) return null
523
+
524
+ const fallbackIndex = new Map(product.fallbackModels.map(m => [m.id, m]))
525
+ const bearerToken = credential => credential?.security_oauth_token || credential?.access_token || ''
526
+
527
+ // anonymousModels: true —— 两版模型目录(/algo/api/v2/model/list)只校验 COSY
528
+ // 签名、不校验账号身份(匿名实测 2026-10-23:国际版 14 个模型 / 国内版 10 个),
529
+ // 无凭据也能拿到完整清单,无需登录即可发现模型。
530
+ const meta = { id: product.id, label: product.displayName, loginMode: 'device-code', anonymousModels: true }
531
+
532
+ // ── 登录(PKCE 设备码轮询)─────────────────────────────────────────────────
533
+
534
+ function buildAuthUrl(session) {
535
+ const query = new URLSearchParams({
536
+ challenge: session.pkce.challenge,
537
+ challenge_method: 'S256',
538
+ nonce: session.nonce,
539
+ machine_id: session.machineId,
540
+ client_id: product.clientId,
541
+ })
542
+ return `${product.authBase}${DEVICE_SELECT_PATH}?${query.toString()}`
543
+ }
544
+
545
+ function buildPollUrl(session) {
546
+ const query = new URLSearchParams({
547
+ nonce: session.nonce,
548
+ verifier: session.pkce.verifier,
549
+ challenge_method: 'S256',
550
+ })
551
+ return `${product.openApiBase}${POLL_PATH}?${query.toString()}`
552
+ }
553
+
554
+ /**
555
+ * 轮询直到拿到 token。**404 = 用户尚未完成授权,继续轮询**
556
+ * (该端点被网关豁免认证,404 是业务层的「会话未就绪」;任意不存在路径回 401)。
557
+ * 其它非 2xx 立即抛错 —— 那是服务端异常,不是「等用户」。
558
+ */
559
+ async function pollDeviceToken(session, signal) {
560
+ const pollUrl = buildPollUrl(session)
561
+ const deadline = Date.now() + LOGIN_TIMEOUT_MS
562
+ let failures = 0
563
+ while (Date.now() < deadline) {
564
+ if (signal?.aborted) throw new Error('登录已取消')
565
+ try {
566
+ const response = await httpFetch(pollUrl, { method: 'GET', headers: { Accept: 'application/json' }, signal }, REQUEST_TIMEOUT_MS)
567
+ failures = 0
568
+ if (response.status === 404) { await sleep(POLL_INTERVAL_MS, signal); continue }
569
+ if (!response.ok) throw new Error(`登录服务返回异常(HTTP ${response.status})`)
570
+ const payload = parseTokenPayload(await response.json().catch(() => ({})))
571
+ if (payload.accessToken) return payload
572
+ // 2xx 但尚无 token:同样继续轮询
573
+ await sleep(POLL_INTERVAL_MS, signal)
574
+ } catch (error) {
575
+ if (signal?.aborted) throw new Error('登录已取消')
576
+ if (error instanceof Error && error.message.startsWith('登录服务返回异常')) throw error
577
+ failures += 1
578
+ if (failures >= POLL_MAX_FAILURES) {
579
+ throw new Error(`无法连接 Qoder 登录服务(连续 ${failures} 次失败):${error?.message ?? error}`)
580
+ }
581
+ await sleep(POLL_INTERVAL_MS, signal)
582
+ }
583
+ }
584
+ throw new Error('登录等待已超时,请重新发起登录')
585
+ }
586
+
587
+ /**
588
+ * 登录后补一次 userinfo:设备码轮询响应里**没有 user_name**,userinfo 是唯一可靠的昵称来源;顺带补 uid。
589
+ * 失败返回原凭据不抛错 —— 展示信息缺失不应让登录整体失败。
590
+ */
591
+ async function patchFromUserinfo(credential) {
592
+ try {
593
+ const response = await httpFetch(`${product.openApiBase}${USERINFO_PATH}`, {
594
+ method: 'GET',
595
+ headers: { Accept: 'application/json', Authorization: `Bearer ${bearerToken(credential)}` },
596
+ }, REQUEST_TIMEOUT_MS)
597
+ if (!response.ok) return credential
598
+ const body = await response.json().catch(() => null)
599
+ if (body === null || typeof body !== 'object') return credential
600
+ const next = { ...credential }
601
+ if (!next.nickname) {
602
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
603
+ if (name) next.nickname = name
604
+ }
605
+ if (!next.uid) {
606
+ const uid = readStringField(body, ['id', 'user_id', 'userId'])
607
+ if (uid) next.uid = uid
608
+ }
609
+ return next
610
+ } catch {
611
+ return credential
612
+ }
613
+ }
614
+
615
+ /**
616
+ * 启动设备码登录。授权 URL 由 PKCE 纯本地构造(同步就绪),轮询在后台进行。
617
+ * 返回 `{ loginUrl, promise, cancel }`;machineId 随凭据持久化
618
+ * (不复刻官方硬件指纹:依赖原生模块,不可移植)。
619
+ */
620
+ function startLogin() {
621
+ const controller = new AbortController()
622
+ const signal = controller.signal
623
+ const session = { pkce: createPkce(), nonce: randomUUID(), machineId: randomUUID() }
624
+ const loginUrl = buildAuthUrl(session)
625
+
626
+ const promise = (async () => {
627
+ const payload = await pollDeviceToken(session, signal)
628
+ if (!payload.accessToken) throw new Error('登录响应缺少访问令牌')
629
+ let credential = buildCredential(payload, session.machineId)
630
+ credential = await patchFromUserinfo(credential)
631
+ return credential
632
+ })()
633
+ promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
634
+
635
+ let settled = false
636
+ return {
637
+ loginUrl,
638
+ promise,
639
+ cancel: () => {
640
+ if (settled) return
641
+ settled = true
642
+ controller.abort()
643
+ },
644
+ }
645
+ }
646
+
647
+ // ── 手动凭据与续期 ──────────────────────────────────────────────────────────
648
+
649
+ /** 手动粘贴凭据的规范化:接受 JSON 对象/字符串,补 machine_id(随机 UUID)。 */
650
+ function normalizeCredential(raw) {
651
+ let value = raw
652
+ if (typeof value === 'string') {
653
+ try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
654
+ }
655
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
656
+ throw new Error('凭据必须是 JSON 对象')
657
+ }
658
+ const accessToken = readStringField(value, ['security_oauth_token', 'access_token', 'token', 'device_token'])
659
+ const refreshToken = readStringField(value, ['refresh_token', 'refreshToken'])
660
+ if (!accessToken && !refreshToken) throw new Error('凭据缺少 access_token / refresh_token')
661
+ const expiresAt = parseTimestamp(value.expire_time ?? value.expires_at ?? value.expiresAt)
662
+ return {
663
+ ...value,
664
+ ...(accessToken ? { security_oauth_token: accessToken, access_token: accessToken } : {}),
665
+ ...(refreshToken ? { refresh_token: refreshToken } : {}),
666
+ ...(expiresAt !== undefined ? { expire_time: expiresAt } : {}),
667
+ machine_id: readStringField(value, ['machine_id', 'machineId']) ?? randomUUID(),
668
+ ...(readStringField(value, ['uid', 'user_id', 'userId']) ? { uid: readStringField(value, ['uid', 'user_id', 'userId']) } : {}),
669
+ ...(readStringField(value, ['nickname', 'user_name', 'userName']) ? { nickname: readStringField(value, ['nickname', 'user_name', 'userName']) } : {}),
670
+ }
671
+ }
672
+
673
+ /**
674
+ * 静默续期:{refresh_token, machine_id} 换新令牌。
675
+ * 终态:401/403、200 但缺 token、无 refresh_token —— 停止重试,需重新登录。
676
+ * 传输层失败不能判终态 —— 网络抖动不该让用户重新登录。
677
+ */
678
+ async function refreshCredential(credential) {
679
+ if (!isRefreshable(credential)) {
680
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'Qoder 无 refresh_token,请重新登录' }
681
+ }
682
+ let response
683
+ try {
684
+ response = await httpFetch(`${product.openApiBase}${REFRESH_PATH}`, {
685
+ method: 'POST',
686
+ headers: {
687
+ 'Content-Type': 'application/json',
688
+ Accept: 'application/json',
689
+ 'User-Agent': `${product.userAgentPrefix}/1.0.0`,
690
+ },
691
+ body: JSON.stringify({ refresh_token: credential.refresh_token, machine_id: credential.machine_id }),
692
+ }, REQUEST_TIMEOUT_MS)
693
+ } catch (error) {
694
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Qoder 续期网络失败:${error?.message ?? error}` }
695
+ }
696
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
697
+ if (response.status === 401 || response.status === 403) {
698
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Qoder 续期被拒绝(HTTP ${response.status}),请重新登录` }
699
+ }
700
+ let parsed
701
+ try { parsed = JSON.parse(text) } catch {
702
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Qoder 续期响应不是 JSON(HTTP ${response.status})` }
703
+ }
704
+ if (!response.ok) {
705
+ // 400 + 点名 refresh_token 无效(实测假 token 返回 DeviceRefreshTokenPrefixInvalid)
706
+ // 语义上就是令牌永久失效 —— 重试永远不会成功,判终态。
707
+ const code = typeof parsed?.errorCode === 'string' ? parsed.errorCode : ''
708
+ if (response.status === 400 && /refreshtoken/i.test(code)) {
709
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Qoder refresh_token 已失效(${code}),请重新登录` }
710
+ }
711
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Qoder 续期失败(HTTP ${response.status}):${text.slice(0, 200)}` }
712
+ }
713
+ const payload = parseTokenPayload(parsed)
714
+ if (!payload.accessToken) {
715
+ // 200 却没有 token:视为无法续期(需重新登录),不是可重试的瞬时故障
716
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'Qoder 续期响应缺少访问令牌,请重新登录' }
717
+ }
718
+ return applyRefresh(credential, payload)
719
+ }
720
+
721
+ function needsRefresh(credential) {
722
+ if (!isRefreshable(credential)) return false
723
+ const expiresAt = credentialExpiresAtMs(credential)
724
+ if (expiresAt === undefined) return false
725
+ return Date.now() >= expiresAt - REFRESH_LEAD_MS
726
+ }
727
+
728
+ function describeCredential(credential) {
729
+ const nickname = readStringField(credential, ['nickname']) ?? ''
730
+ const uid = readStringField(credential, ['uid']) ?? ''
731
+ return {
732
+ label: nickname || (uid ? `${product.id}-${uid.slice(0, 8)}` : `${product.displayName} 账号`),
733
+ expiresAt: credentialExpiresAtMs(credential) ?? 0,
734
+ refreshable: isRefreshable(credential),
735
+ }
736
+ }
737
+
738
+ function credentialIdentity(credential) {
739
+ return readStringField(credential, ['uid']) ?? readStringField(credential, ['machine_id']) ?? ''
740
+ }
741
+
742
+ // ── 模型清单(实时拉取上游目录;拉不到一律抛错,不回落静态表)──────────────
743
+
744
+ async function fetchModels(credential) {
745
+ // 无凭据 / 缺 token / 缺 uid → 匿名拉取:目录端点只校验 COSY 签名(签名只依赖
746
+ // 本地 WASM + 时间/随机数,不依赖账号),用占位标识签名即可拿到完整清单
747
+ // (实测 2026-10-23,两版均 HTTP 200)。⚠️ 占位 uid 必须非空且**非 UUID 形态**
748
+ // (UUID 形态会被上游判成「登录过但令牌已过期」回 403 code=105),见文件顶部常量说明。
749
+ // 有完整凭据时行为不变:真实 uid / token 原样参与签名。
750
+ const anonymous = !credential || bearerToken(credential) === ''
751
+ || typeof credential.uid !== 'string' || credential.uid === ''
752
+ const uid = anonymous ? QODER_ANONYMOUS_UID : credential.uid
753
+ // 匿名模式不携带任何账号凭据:签名载荷里 security_oauth_token 置空串。
754
+ const token = anonymous ? '' : bearerToken(credential)
755
+ const machineId = anonymous ? QODER_ANONYMOUS_MACHINE_ID : credential.machine_id
756
+
757
+ const host = new URL(product.modelListBase).host
758
+ let request
759
+ try {
760
+ const client = await QoderEncryptedInfer.create({
761
+ user: { uid, securityOauthToken: token },
762
+ machineId,
763
+ metadata: { ...product.clientMetadata },
764
+ host,
765
+ })
766
+ // auth:'auth' → WASM 追加 COSY 签名头;缺了服务端回 403 Signature invalid
767
+ request = client.prepareRequest({ host, path: MODEL_LIST_PATH, method: 'GET', auth: 'auth' })
768
+ } catch (error) {
769
+ throw { kind: 'server', retryable: true, cooldownMs: 60_000, rotate: false, message: `Qoder 模型目录签名失败:${error?.message ?? error}` }
770
+ }
771
+
772
+ let response
773
+ let text
774
+ try {
775
+ response = await httpFetch(request.url, { method: 'GET', headers: request.headers }, MODEL_LIST_TIMEOUT_MS)
776
+ text = await readBodyText(response, MODEL_LIST_TIMEOUT_MS)
777
+ } catch (error) {
778
+ throw { kind: 'network', retryable: true, message: `Qoder 模型目录请求失败:${error?.message ?? error}` }
779
+ }
780
+ if (!response.ok) {
781
+ const authFailure = response.status === 401 || response.status === 403
782
+ throw {
783
+ kind: authFailure ? 'auth' : 'server',
784
+ retryable: !authFailure,
785
+ terminal: authFailure,
786
+ rotate: authFailure,
787
+ message: `Qoder 模型目录获取失败:HTTP ${response.status} ${text.slice(0, 300)}`,
788
+ }
789
+ }
790
+
791
+ let payload
792
+ try {
793
+ payload = JSON.parse(text)
794
+ } catch {
795
+ throw { kind: 'server', retryable: true, message: `Qoder 模型目录返回非 JSON:${text.slice(0, 300)}` }
796
+ }
797
+
798
+ const list = Array.isArray(payload?.chat) ? payload.chat : []
799
+ const now = new Date()
800
+ const models = list
801
+ .filter(entry => entry !== null && typeof entry === 'object'
802
+ && typeof entry.key === 'string' && entry.key !== '' && entry.enable !== false)
803
+ .map(entry => {
804
+ const label = String(entry.display_name ?? entry.key)
805
+ return {
806
+ id: entry.key,
807
+ // 只有 price_factor === 0 才是真免费:is_free 表示「有免费额度」,
808
+ // 超额仍按倍率计费(Qwen3.8-Max 标成免费会与倍率徽章自相矛盾)
809
+ name: entry.price_factor === 0 ? `${label} · 免费` : label,
810
+ contextWindow: contextWindowOf(entry),
811
+ supportsImage: entry.is_vl === true || undefined,
812
+ isFree: entry.is_free === true,
813
+ // 倍率按当前时间 + 目录 promotion 窗口实时推算(窗口会切换)
814
+ ...liveRateFields(entry, now),
815
+ }
816
+ })
817
+
818
+ if (models.length === 0) {
819
+ throw { kind: 'server', retryable: true, message: 'Qoder 模型目录为空(上游未返回 chat 清单)' }
820
+ }
821
+ return models
822
+ }
823
+
824
+ // ── 对话(加密端点,信封剥离 + 排队/额度/认证分类)─────────────────────────
825
+
826
+ /** content 归一化为字符串(工具调用消息的正文是空串)。 */
827
+ function contentText(content) {
828
+ if (typeof content === 'string') return content
829
+ if (Array.isArray(content)) {
830
+ return content
831
+ .filter(block => block !== null && typeof block === 'object' && block.type === 'text')
832
+ .map(block => String(block.text ?? ''))
833
+ .join('')
834
+ }
835
+ return ''
836
+ }
837
+
838
+ /**
839
+ * content 数组的**多模态 parts 搬运**:无图返回 undefined(保持字符串形态,
840
+ * 上游对字符串兼容性最好);有图时保留 text/image_url 两类块。
841
+ * ⚠️ 图片的正确通道是 messages[].content 的多模态数组(客户端官方实现把
842
+ * chat_context.imageUrls 恒置 null),压成纯文本会让图片在下游全部消失。
843
+ */
844
+ function contentParts(content) {
845
+ if (!Array.isArray(content)) return undefined
846
+ const parts = []
847
+ let hasImage = false
848
+ for (const raw of content) {
849
+ if (raw === null || typeof raw !== 'object') continue
850
+ const block = raw
851
+ if (block.type === 'text') {
852
+ const text = String(block.text ?? '')
853
+ if (text.length > 0) parts.push({ type: 'text', text })
854
+ continue
855
+ }
856
+ if (block.type === 'image_url') {
857
+ const url = block.image_url?.url
858
+ if (typeof url !== 'string' || url.length === 0) continue
859
+ const detail = block.image_url?.detail
860
+ parts.push({ type: 'image_url', image_url: { url, ...(typeof detail === 'string' && detail.length > 0 ? { detail } : {}) } })
861
+ hasImage = true
862
+ }
863
+ }
864
+ return hasImage ? parts : undefined
865
+ }
866
+
867
+ /** 工具调用归一:arguments 必须是字符串(对象形态序列化)。 */
868
+ function cleanToolCalls(toolCalls) {
869
+ return toolCalls.map(call => {
870
+ if (call === null || typeof call !== 'object') return null
871
+ const fn = call.function ?? {}
872
+ let args = fn.arguments
873
+ if (args === undefined || args === null) args = ''
874
+ else if (typeof args !== 'string') args = JSON.stringify(args)
875
+ return {
876
+ ...(typeof call.id === 'string' ? { id: call.id } : {}),
877
+ type: 'function',
878
+ ...(typeof call.index === 'number' ? { index: call.index } : {}),
879
+ function: { name: String(fn.name ?? ''), arguments: args },
880
+ }
881
+ }).filter(Boolean)
882
+ }
883
+
884
+ /**
885
+ * 把 OpenAI wire 消息转成加密端点的 messages[]。
886
+ * ⚠️ 三者缺一不可:assistant 的 tool_calls、role:'tool' 的 tool_call_id、
887
+ * 带图消息的多模态数组 —— 只留字符串 content 会让多步工具调用彻底坏掉
888
+ * (模型看不到自己调用过什么,反复重调或凭空编造结果)。
889
+ * ⚠️ 判空必须把图片算作内容:只发一张图不带文字的消息不能整条吃掉。
890
+ */
891
+ function buildHistory(messages) {
892
+ const history = []
893
+ for (const message of messages) {
894
+ if (message === null || typeof message !== 'object' || typeof message.role !== 'string') continue
895
+ const parts = contentParts(message.content)
896
+ const content = parts === undefined ? contentText(message.content) : parts
897
+ const toolCalls = Array.isArray(message.tool_calls) && message.tool_calls.length > 0
898
+ ? cleanToolCalls(message.tool_calls)
899
+ : undefined
900
+ const toolCallId = typeof message.tool_call_id === 'string' ? message.tool_call_id : undefined
901
+ const isEmpty = parts === undefined ? content.length === 0 : content.length === 0
902
+ if (isEmpty && toolCalls === undefined && toolCallId === undefined) continue
903
+ history.push({
904
+ role: message.role,
905
+ content,
906
+ ...(toolCalls === undefined ? {} : { tool_calls: toolCalls }),
907
+ ...(toolCallId === undefined ? {} : { tool_call_id: toolCallId }),
908
+ })
909
+ }
910
+ return history
911
+ }
912
+
913
+ /** 工具定义:客户端 $Hc(A) 形态 {type:'function', function:{name, description?, parameters?}}。 */
914
+ function buildTools(tools) {
915
+ if (!Array.isArray(tools)) return []
916
+ const out = []
917
+ for (const tool of tools) {
918
+ if (tool === null || typeof tool !== 'object' || typeof tool.function?.name !== 'string' || tool.function.name.trim().length === 0) continue
919
+ const fn = tool.function
920
+ out.push({
921
+ type: 'function',
922
+ function: {
923
+ name: fn.name,
924
+ ...(typeof fn.description === 'string' && fn.description.length > 0 ? { description: fn.description } : {}),
925
+ ...(fn.parameters !== undefined && fn.parameters !== null ? { parameters: fn.parameters } : {}),
926
+ },
927
+ })
928
+ }
929
+ return out
930
+ }
931
+
932
+ /** 思考档位校验:白名单外静默丢弃(服务端 ao() 同语义);disabled/off → none。 */
933
+ function normalizeEffort(value) {
934
+ if (typeof value !== 'string') return undefined
935
+ const mapped = EFFORT_ALIASES[value] ?? value
936
+ return EFFORT_WHITELIST.has(mapped) ? mapped : undefined
937
+ }
938
+
939
+ /** 组装加密推理入参(消息/系统提示/工具/最后一条 user 文本)。 */
940
+ function buildInferInputs(body) {
941
+ const messages = Array.isArray(body.messages) ? body.messages : []
942
+ const systemParts = []
943
+ const rest = []
944
+ for (const message of messages) {
945
+ if (message !== null && typeof message === 'object' && message.role === 'system') {
946
+ const text = contentText(message.content)
947
+ if (text) systemParts.push(text)
948
+ continue
949
+ }
950
+ rest.push(message)
951
+ }
952
+ const history = buildHistory(rest)
953
+ let userText = ''
954
+ for (let i = history.length - 1; i >= 0; i--) {
955
+ if (history[i].role === 'user') {
956
+ userText = Array.isArray(history[i].content)
957
+ ? history[i].content.filter(b => b.type === 'text').map(b => String(b.text ?? '')).join('')
958
+ : String(history[i].content ?? '')
959
+ break
960
+ }
961
+ }
962
+ return {
963
+ history,
964
+ ...(systemParts.length > 0 ? { systemText: systemParts.join('\n\n') } : {}),
965
+ userText,
966
+ tools: buildTools(body.tools),
967
+ }
968
+ }
969
+
970
+ // ── 加密端点响应的信封剥离 ─────────────────────────────────────────────────
971
+
972
+ /** 信封分类:chunk / error / heartbeat。⚠️ body:null 是心跳不是错误(issue IKJOZ8)。 */
973
+ function classifyInner(inner) {
974
+ const trimmed = inner.trim()
975
+ if (trimmed.length === 0) return 'heartbeat'
976
+ if (trimmed.includes('[DONE]')) return 'chunk'
977
+ let parsed
978
+ try { parsed = JSON.parse(trimmed) } catch { return 'error' }
979
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return 'heartbeat'
980
+ // choices:[](usage 末帧形态)也算正常帧
981
+ if (Array.isArray(parsed.choices) || parsed.usage !== undefined) return 'chunk'
982
+ if (parsed.code !== undefined || parsed.message !== undefined || parsed.error !== undefined
983
+ || parsed.statusCodeValue !== undefined || parsed.type !== undefined) return 'error'
984
+ return 'heartbeat'
985
+ }
986
+
987
+ /** 从信封 JSON 文本里取出内层帧文本;不是信封(缺 body 键)返回 null。 */
988
+ function unwrapEnvelope(payload) {
989
+ let envelope
990
+ try { envelope = JSON.parse(payload) } catch { return null }
991
+ if (envelope === null || typeof envelope !== 'object' || envelope.body === undefined) return null
992
+ // 内层 body 可能是字符串或对象,统一转为字符串供后续解析
993
+ return typeof envelope.body === 'string' ? envelope.body : JSON.stringify(envelope.body)
994
+ }
995
+
996
+ /** 非 401/403/409 的 HTTP 失败分类。 */
997
+ function failureFrom(status, bodyText) {
998
+ const message = extractMessage(bodyText) || `Qoder HTTP ${status}`
999
+ if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
1000
+ if (status === 402 || looksLikeBillingError(bodyText)) {
1001
+ return { kind: 'quota', retryable: false, cooldownMs: Math.max(60_000, nextUtc8DayStartMs() - Date.now()), rotate: true, message }
1002
+ }
1003
+ if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
1004
+ if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1005
+ if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
1006
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
1007
+ }
1008
+
1009
+ /** 排队等待:先判时间预算、再判次数(时间上限是硬约束),无延迟信息时退避 1s。 */
1010
+ async function waitForQueue(queueInfo, attempts, deadline, signal) {
1011
+ if (Date.now() >= deadline || attempts > QUEUE_MAX_ATTEMPTS) {
1012
+ throw { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message: 'Qoder 排队等待超时' }
1013
+ }
1014
+ await sleep(queueDelayMs(queueInfo) ?? 1_000, signal)
1015
+ }
1016
+
1017
+ /**
1018
+ * 单账号一轮对话(加密端点)。恒以非流式聚合返回 { status, json };
1019
+ * onData 存在时逐帧发**剥壳后**的 OpenAI chunk JSON 文本。
1020
+ * 调用方(providers/index.js)负责续期与换号 —— 这里只如实分类错误。
1021
+ *
1022
+ * ⚠️ 凭据缺 uid 时明确报错而不是发出必然失败的请求 —— 缺 uid 会让 WASM
1023
+ * 产出签名无效的请求,服务端回 `Signature invalid (101)`,极难定位。
1024
+ */
1025
+ async function complete(credential, body, { signal, onData, headerTimeoutMs = 120_000 } = {}) {
1026
+ if (!credential || !bearerToken(credential)) {
1027
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'Qoder 凭据缺少访问令牌,请重新登录' }
1028
+ }
1029
+ if (typeof credential.uid !== 'string' || credential.uid.length === 0) {
1030
+ throw { kind: 'auth', retryable: false, terminal: true, rotate: false, cooldownMs: 10 * 60_000, message: 'Qoder 凭据缺少 uid,加密推理无法签名(请重新登录该账号)' }
1031
+ }
1032
+ const modelKey = typeof body.model === 'string' ? body.model : ''
1033
+ const fallback = fallbackIndex.get(modelKey)
1034
+ const { history, systemText, userText, tools } = buildInferInputs(body)
1035
+
1036
+ let request
1037
+ try {
1038
+ const client = await QoderEncryptedInfer.create({
1039
+ user: { uid: credential.uid, securityOauthToken: bearerToken(credential) },
1040
+ machineId: credential.machine_id,
1041
+ metadata: { ...product.clientMetadata },
1042
+ host: product.encryptedInferBase,
1043
+ })
1044
+ request = client.prepareInfer({
1045
+ modelKey,
1046
+ userText,
1047
+ ...(systemText !== undefined ? { systemText } : {}),
1048
+ isReasoning: fallback?.supportsThinking === true,
1049
+ history,
1050
+ tools,
1051
+ ...(typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0
1052
+ ? { maxTokens: Math.floor(body.max_tokens) } : {}),
1053
+ ...(normalizeEffort(body.reasoning_effort) !== undefined ? { reasoningEffort: normalizeEffort(body.reasoning_effort) } : {}),
1054
+ ...(fallback?.supportsImage !== undefined ? { isVl: fallback.supportsImage } : {}),
1055
+ // 官方 model_config 的 display_name / max_input_tokens 必须带上
1056
+ ...(fallback?.name !== undefined ? { displayName: fallback.name } : {}),
1057
+ ...(fallback?.contextWindow !== undefined ? { maxInputTokens: fallback.contextWindow } : {}),
1058
+ // ⚠️ business 必填:缺失时服务端把请求路由到故障节点(Execution failed)
1059
+ business: { type: 'agent' },
1060
+ })
1061
+ } catch (error) {
1062
+ // WASM 构造失败是进程级缺陷(换号无用),不标记账号
1063
+ throw { kind: 'server', retryable: true, cooldownMs: 60_000, rotate: false, message: `Qoder 加密请求构造失败:${error?.message ?? error}` }
1064
+ }
1065
+
1066
+ const queueDeadline = Date.now() + QUEUE_TOTAL_BUDGET_MS
1067
+ let queueAttempts = 0
1068
+ let duplicateRetried = false
1069
+
1070
+ for (;;) {
1071
+ // ⚠️ 头必须原样透传:Authorization 是 WASM 生成的 COSY 签名
1072
+ const response = await httpFetch(request.url, {
1073
+ method: 'POST',
1074
+ headers: { ...request.headers, Accept: 'text/event-stream' },
1075
+ body: request.body,
1076
+ signal,
1077
+ }, headerTimeoutMs)
1078
+
1079
+ if (!response.ok && (response.status === 401 || response.status === 403)) {
1080
+ // ⚠️ 必须先读体再判断:排队信息藏在 message 的内嵌 JSON 里
1081
+ const errorText = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1082
+ const queueInfo = parseQueueError(errorText)
1083
+ if (queueInfo !== undefined) {
1084
+ await waitForQueue(queueInfo, ++queueAttempts, queueDeadline, signal)
1085
+ continue
1086
+ }
1087
+ const parsed = (() => { try { return JSON.parse(errorText) } catch { return undefined } })()
1088
+ const code = parsed?.code ?? parsed?.error?.code
1089
+ if (isBillingCode(code) || looksLikeBillingError(errorText)) {
1090
+ throw { kind: 'quota', retryable: false, cooldownMs: Math.max(60_000, nextUtc8DayStartMs() - Date.now()), rotate: true, message: extractMessage(errorText) }
1091
+ }
1092
+ // 非排队的 401/403 = 认证失败(调用方已完成续期,再失败即凭据终态)
1093
+ throw { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message: `Qoder 认证失败(HTTP ${response.status}):${extractMessage(errorText)}` }
1094
+ }
1095
+
1096
+ // 重复请求(duplicate_request):凭据没问题,重发一次即可
1097
+ if (!response.ok && response.status === 409 && !duplicateRetried) {
1098
+ duplicateRetried = true
1099
+ continue
1100
+ }
1101
+
1102
+ if (!response.ok) {
1103
+ const errorText = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
1104
+ throw failureFrom(response.status, errorText)
1105
+ }
1106
+ if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Qoder 返回空响应体' }
1107
+
1108
+ // 消费 SSE:逐帧剥信封;排队/额度错误帧记录后整轮重试/抛出
1109
+ const chunks = []
1110
+ let streamQueueMessage = null
1111
+ let streamBillingMessage = null
1112
+ let streamError = null
1113
+ let lastUsage = null
1114
+ await readSseData(response.body, data => {
1115
+ if (streamError || streamQueueMessage || streamBillingMessage) return
1116
+ const inner = unwrapEnvelope(data)
1117
+ // 不是信封 → 视为已是标准帧(容错:服务端某天直接回标准帧)
1118
+ if (inner === null) {
1119
+ chunks.push(data)
1120
+ // 尝试从原始数据中提取 usage
1121
+ try {
1122
+ const chunk = JSON.parse(data)
1123
+ if (chunk.usage) lastUsage = chunk.usage
1124
+ } catch {}
1125
+ onData?.(data)
1126
+ return
1127
+ }
1128
+ const kind = classifyInner(inner)
1129
+ if (kind === 'heartbeat') return
1130
+ if (kind === 'error') {
1131
+ let code
1132
+ let message = inner
1133
+ try {
1134
+ const parsed = JSON.parse(inner)
1135
+ if (parsed?.code !== undefined) code = parsed.code
1136
+ if (typeof parsed?.message === 'string') message = parsed.message
1137
+ } catch { /* 保持原文 */ }
1138
+ if (isQueueCode(code) || parseQueueError(message) !== undefined) { streamQueueMessage = message; return }
1139
+ if (isBillingCode(code) || looksLikeBillingError(message) || looksLikeBillingError(inner)) { streamBillingMessage = message; return }
1140
+ streamError = { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: extractMessage(inner) || inner.slice(0, 300) }
1141
+ return
1142
+ }
1143
+ chunks.push(inner)
1144
+ // 从内层帧提取 usage(OpenAI 格式通常在最后一帧带 usage)
1145
+ try {
1146
+ const chunk = JSON.parse(inner)
1147
+ if (chunk.usage) lastUsage = chunk.usage
1148
+ } catch {}
1149
+ onData?.(inner)
1150
+ }, signal)
1151
+
1152
+ if (streamQueueMessage !== null) {
1153
+ const queueInfo = parseQueueError(streamQueueMessage)
1154
+ await waitForQueue(queueInfo, ++queueAttempts, queueDeadline, signal)
1155
+ continue
1156
+ }
1157
+ if (streamBillingMessage !== null) {
1158
+ throw { kind: 'quota', retryable: false, cooldownMs: Math.max(60_000, nextUtc8DayStartMs() - Date.now()), rotate: true, message: extractMessage(streamBillingMessage) }
1159
+ }
1160
+ if (streamError !== null) throw streamError
1161
+
1162
+ const merged = mergeSseChunks(chunks)
1163
+ if (!merged || !merged.choices?.[0]) {
1164
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Qoder 流结束但没有内容帧' }
1165
+ }
1166
+ if (merged.model !== undefined) merged.model = modelKey
1167
+ // 优先使用流中捕获的 usage,否则保留 mergeSseChunks 提取的
1168
+ if (lastUsage) merged.usage = lastUsage
1169
+ return { status: response.status, json: merged }
1170
+ }
1171
+ }
1172
+
1173
+ return {
1174
+ meta,
1175
+ fallbackModels: product.fallbackModels,
1176
+ fetchModels,
1177
+ startLogin,
1178
+ normalizeCredential,
1179
+ refreshCredential,
1180
+ needsRefresh,
1181
+ describeCredential,
1182
+ credentialIdentity,
1183
+ complete,
1184
+ claimCredits: credential => qoderClaimDaily(credential, product),
1185
+ fetchCreditBalance: credential => qoderFetchBalance(credential, product),
1186
+ }
1187
+ }
1188
+
1189
+ // ── 积分余额与每日领取 ──────────────────────────────────────────────────────
1190
+ //
1191
+ // `/sash/` 端点**不需要 WASM 签名**,但必须带桌面 app 身份头:
1192
+ // - `Cosy-ClientType` = product.sashClientType('10';CLI 的 '5' 会让
1193
+ // campaigns 恒返回空);
1194
+ // - `Cosy-MachineToken` + `Cosy-MachineType`(**必须成对**,缺一服务端只回
1195
+ // VIEW_DETAILS 不回 CLAIM_BENEFIT,进而被误判「今天已领」)。
1196
+ // machine 头来自本机 Qoder 客户端:主路径实时 spawn `runtime-info.exe`
1197
+ // (参数必须 [environment='3', '--account-stdin'],漏 env 会拿到另一套身份),
1198
+ // 退路读磁盘缓存 machine_token.json;都拿不到则**不带这两个头**(保守降级,
1199
+ // 与修复前行为一致 —— 漏发安全,发空头反而可能被按非法设备处理)。
1200
+
1201
+ const QODER_USAGE_PATH = '/sash/api/v2/me/usage'
1202
+ const QODER_CAMPAIGNS_PATH = '/sash/api/v1/me/campaigns'
1203
+ const QODER_CREDITS_TIMEOUT_MS = 15_000
1204
+
1205
+ /** 每日活动刷新时刻(UTC+8 小时,服务端下发原文)。刷新前看到的全是昨天那一轮。 */
1206
+ const QODER_CAMPAIGN_REFRESH_HOUR_UTC8 = 10
1207
+
1208
+ const QODER_NOT_ACTIVATED_HINT =
1209
+ '该账号尚未在 Qoder 侧开通每日领取(每日 100 Credits)。' +
1210
+ '请先用 Qoder 官方客户端登录一次该账号,开通后再回来领取。'
1211
+ const QODER_NOT_REFRESHED_YET_HINT =
1212
+ `今天的每日活动尚未刷新(每日 ${QODER_CAMPAIGN_REFRESH_HOUR_UTC8}:00(UTC+8)刷新),` +
1213
+ '当前看到的是昨天那一轮,请稍后再来领取。'
1214
+
1215
+ /** 今天的活动列表是否已刷新(按 UTC+8 算术平移;不能取本机时区)。 */
1216
+ function hasQoderCampaignRefreshedToday(nowMs = Date.now()) {
1217
+ return utc8Hour(nowMs) >= QODER_CAMPAIGN_REFRESH_HOUR_UTC8
1218
+ }
1219
+
1220
+ // ── 设备身份(Cosy-MachineToken + Cosy-MachineType)─────────────────────────
1221
+
1222
+ const RUNTIME_INFO_TIMEOUT_MS = 20_000
1223
+ /** runtime-info.exe 的 environment 位置参数(源码 'global' 分支;IDE 抓包实测用 3)。 */
1224
+ const RUNTIME_INFO_ENVIRONMENT = '3'
1225
+
1226
+ /** 进程内缓存:undefined=未解析,null=已确认拿不到,对象=成功。 */
1227
+ let qoderMachineCache
1228
+
1229
+ /** machine_token.json 候选路径(退路;实测可长期陈旧,但「聊胜于无」)。 */
1230
+ function qoderMachineCandidatePaths() {
1231
+ const override = process.env.QODER_MACHINE_TOKEN_PATH
1232
+ if (override && override.length > 0) return [override]
1233
+ const paths = []
1234
+ const appData = process.env.APPDATA
1235
+ if (appData && appData.length > 0) {
1236
+ for (const dir of ['Qoder', 'Qoder CN']) {
1237
+ paths.push(join(appData, dir, 'SharedClientCache', 'cache', 'machine_token.json'))
1238
+ }
1239
+ }
1240
+ const home = homedir()
1241
+ for (const dir of ['Qoder', 'Qoder CN']) {
1242
+ paths.push(join(home, 'Library', 'Application Support', dir, 'SharedClientCache', 'cache', 'machine_token.json'))
1243
+ paths.push(join(home, '.config', dir, 'SharedClientCache', 'cache', 'machine_token.json'))
1244
+ }
1245
+ return paths
1246
+ }
1247
+
1248
+ /** 解析 machine_token.json 的 {token,type};两者须都非空(配对是服务端必要条件)。 */
1249
+ function parseQoderMachineFile(path) {
1250
+ let raw
1251
+ try { raw = readFileSync(path, 'utf8') } catch { return undefined }
1252
+ let parsed
1253
+ try { parsed = JSON.parse(raw) } catch { return undefined }
1254
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
1255
+ const token = parsed.token
1256
+ const type = parsed.type
1257
+ if (typeof token !== 'string' || token.length === 0) return undefined
1258
+ if (typeof type !== 'string' || type.length === 0) return undefined
1259
+ return { token, type }
1260
+ }
1261
+
1262
+ /**
1263
+ * 定位 `<home>/.qoder|.qoder-cn/.bin/umid-<hash>/runtime-info(.exe)`。
1264
+ * 目录名带哈希(随版本变)必须枚举;某目录存在但 exe 缺失时继续试下一个
1265
+ * (半安装残留会留下空目录)。实测两版 exe SHA256 相同、身份与产品无关。
1266
+ */
1267
+ function findQoderRuntimeInfo(home) {
1268
+ const exeName = process.platform === 'win32' ? 'runtime-info.exe' : 'runtime-info'
1269
+ for (const dirName of ['.qoder', '.qoder-cn']) {
1270
+ const binDir = join(home, dirName, '.bin')
1271
+ let entries
1272
+ try { entries = readdirSync(binDir) } catch { continue }
1273
+ const dir = entries.find(name => name.startsWith('umid-'))
1274
+ if (dir === undefined) continue
1275
+ const exe = join(binDir, dir, exeName)
1276
+ if (existsSync(exe)) return exe
1277
+ }
1278
+ return undefined
1279
+ }
1280
+
1281
+ function locateQoderRuntimeInfo() {
1282
+ const fromEnv = process.env.QODER_RUNTIME_INFO
1283
+ const candidate = fromEnv && fromEnv.length > 0 ? fromEnv : undefined
1284
+ if (candidate !== undefined) return existsSync(candidate) ? candidate : undefined
1285
+ return findQoderRuntimeInfo(homedir())
1286
+ }
1287
+
1288
+ /** 解析 runtime-info.exe 单行 JSON 输出(即便 accountOutcome 非 success 也照取)。 */
1289
+ function parseRuntimeInfoOutput(out) {
1290
+ const start = out.indexOf('{')
1291
+ if (start < 0) return undefined
1292
+ let parsed
1293
+ try { parsed = JSON.parse(out.slice(start)) } catch { return undefined }
1294
+ if (parsed === null || typeof parsed !== 'object') return undefined
1295
+ const token = parsed.machineToken
1296
+ const type = parsed.machineType
1297
+ if (typeof token !== 'string' || token.length === 0) return undefined
1298
+ if (typeof type !== 'string' || type.length === 0) return undefined
1299
+ return { token, type }
1300
+ }
1301
+
1302
+ /** 异步 spawn runtime-info.exe(实测约 3.8 秒;参数顺序 [env, --account-stdin] 不可反)。 */
1303
+ function readFromQoderRuntimeInfoAsync() {
1304
+ const exe = locateQoderRuntimeInfo()
1305
+ if (exe === undefined) return Promise.resolve(undefined)
1306
+ return new Promise(resolve => {
1307
+ let settled = false
1308
+ const done = value => {
1309
+ if (settled) return
1310
+ settled = true
1311
+ resolve(value)
1312
+ }
1313
+ let child
1314
+ try {
1315
+ child = spawn(exe, [RUNTIME_INFO_ENVIRONMENT, '--account-stdin'], { windowsHide: true })
1316
+ } catch {
1317
+ done(undefined)
1318
+ return
1319
+ }
1320
+ const timer = setTimeout(() => {
1321
+ try { child.kill() } catch { /* 忽略 */ }
1322
+ done(undefined)
1323
+ }, RUNTIME_INFO_TIMEOUT_MS)
1324
+ timer.unref?.()
1325
+ let stdout = ''
1326
+ child.stdout?.on('data', chunk => { stdout += String(chunk) })
1327
+ child.stderr?.on('data', () => {}) // 必须消费,否则管道填满会阻塞子进程
1328
+ child.once('error', () => { clearTimeout(timer); done(undefined) })
1329
+ child.once('close', () => { clearTimeout(timer); done(parseRuntimeInfoOutput(stdout)) })
1330
+ child.stdin?.on('error', () => {})
1331
+ child.stdin?.end(JSON.stringify({ account: '' }))
1332
+ })
1333
+ }
1334
+
1335
+ /** 解析设备身份(进程内缓存,含「拿不到」);拿不到返回 undefined。 */
1336
+ async function resolveQoderMachineIdentity() {
1337
+ if (qoderMachineCache !== undefined) return qoderMachineCache ?? undefined
1338
+ const live = await readFromQoderRuntimeInfoAsync()
1339
+ if (live) {
1340
+ qoderMachineCache = live
1341
+ return live
1342
+ }
1343
+ for (const path of qoderMachineCandidatePaths()) {
1344
+ const identity = parseQoderMachineFile(path)
1345
+ if (identity) {
1346
+ qoderMachineCache = identity
1347
+ return identity
1348
+ }
1349
+ }
1350
+ qoderMachineCache = null
1351
+ return undefined
1352
+ }
1353
+
1354
+ function qoderBearerToken(credential) {
1355
+ return credential?.security_oauth_token || credential?.access_token || ''
1356
+ }
1357
+
1358
+ /** `/sash/` 端点公共请求头(machine 头成对出现,缺一不发)。 */
1359
+ async function qoderCreditsHeaders(credential, product) {
1360
+ const identity = await resolveQoderMachineIdentity()
1361
+ return {
1362
+ Accept: 'application/json',
1363
+ Authorization: `Bearer ${qoderBearerToken(credential)}`,
1364
+ 'Cosy-ClientType': product.sashClientType,
1365
+ 'User-Agent': 'Qoder',
1366
+ ...(identity ? { 'Cosy-MachineToken': identity.token, 'Cosy-MachineType': identity.type } : {}),
1367
+ }
1368
+ }
1369
+
1370
+ // ── 余额(/sash/api/v2/me/usage)────────────────────────────────────────────
1371
+
1372
+ function readNumber(source, key) {
1373
+ if (source === null || typeof source !== 'object') return undefined
1374
+ const value = source[key]
1375
+ if (typeof value === 'number' && Number.isFinite(value)) return value
1376
+ if (typeof value === 'string' && value.trim().length > 0) {
1377
+ const parsed = Number(value)
1378
+ return Number.isFinite(parsed) ? parsed : undefined
1379
+ }
1380
+ return undefined
1381
+ }
1382
+
1383
+ /**
1384
+ * quota 对象 → CreditPackage。remaining 缺失时按 total-used 计算;
1385
+ * 负值一律 clamp 到 0(计量回滚会下发负值,原样透出会显示「-12.5 积分」)。
1386
+ */
1387
+ function qoderPackage(name, quota, expiredTime = '') {
1388
+ const total = readNumber(quota, 'total')
1389
+ const used = readNumber(quota, 'used')
1390
+ const remainingRaw = readNumber(quota, 'remaining')
1391
+ if (total === undefined && used === undefined && remainingRaw === undefined) return undefined
1392
+ const totalValue = Math.max(0, total ?? 0)
1393
+ const usedValue = Math.max(0, used ?? 0)
1394
+ const remaining = remainingRaw !== undefined
1395
+ ? Math.max(0, remainingRaw)
1396
+ : Math.max(0, totalValue - usedValue)
1397
+ const expMs = expiredTime.length > 0 ? Date.parse(expiredTime.replace(' ', 'T')) : Number.NaN
1398
+ return {
1399
+ name,
1400
+ unit: readStringField(quota, ['unit']) ?? 'credits',
1401
+ remaining,
1402
+ total: totalValue,
1403
+ used: usedValue,
1404
+ active: true,
1405
+ cycleStartTime: '',
1406
+ cycleEndTime: '',
1407
+ expiredTime,
1408
+ ...(Number.isFinite(expMs) ? { deductionEndTime: expMs } : {}),
1409
+ }
1410
+ }
1411
+
1412
+ /** 拉取用量原始响应(给「未开通」判定喂判据);失败返回 undefined。 */
1413
+ async function fetchQoderUsageRaw(credential, product) {
1414
+ try {
1415
+ const response = await httpFetch(`${product.openApiBase}${QODER_USAGE_PATH}`, {
1416
+ method: 'GET',
1417
+ headers: await qoderCreditsHeaders(credential, product),
1418
+ }, QODER_CREDITS_TIMEOUT_MS)
1419
+ if (!response.ok) return undefined
1420
+ return await response.json().catch(() => undefined)
1421
+ } catch {
1422
+ return undefined
1423
+ }
1424
+ }
1425
+
1426
+ /**
1427
+ * 「未开通」判据(两条同时满足):活动列表无 CLAIM_BENEFIT(连已领的都没有)
1428
+ * 且 usage 里 `addOnQuota` 字段**缺失**(是缺失不是 0 —— 已开通账号额度用尽
1429
+ * 也有该字段;用「是否为 0」会把用光额度的老账号误报成未开通)。
1430
+ */
1431
+ function isQoderNotActivated(campaigns, usageBody) {
1432
+ if (campaigns === undefined) return false
1433
+ if (campaigns.some(c => c.actionType === 'CLAIM_BENEFIT')) return false
1434
+ if (usageBody === null || typeof usageBody !== 'object') return false
1435
+ const usage = usageBody.qoderUsage
1436
+ if (usage === null || typeof usage !== 'object') return false
1437
+ return usage.addOnQuota === undefined
1438
+ }
1439
+
1440
+ /** 读 benefit.amount(嵌套一层)。 */
1441
+ function benefitAmount(item) {
1442
+ if (item === null || typeof item !== 'object') return undefined
1443
+ return readNumber(item.benefit, 'amount')
1444
+ }
1445
+
1446
+ /** 解析 campaigns 响应;形状非法返回 undefined。 */
1447
+ function parseQoderCampaigns(body) {
1448
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) return undefined
1449
+ const raw = body.campaigns
1450
+ const campaigns = []
1451
+ if (Array.isArray(raw)) {
1452
+ for (const item of raw) {
1453
+ const id = readStringField(item, ['campaignId'])
1454
+ if (id === undefined) continue
1455
+ campaigns.push({
1456
+ campaignId: id,
1457
+ campaignKey: readStringField(item, ['campaignKey']),
1458
+ actionType: readStringField(item, ['actionType']),
1459
+ claimStatus: readStringField(item, ['claimStatus']),
1460
+ amount: benefitAmount(item),
1461
+ })
1462
+ }
1463
+ }
1464
+ return campaigns
1465
+ }
1466
+
1467
+ /** 可领取活动:CLAIM_BENEFIT 且 CLAIMABLE(VIEW_DETAILS 只是跳转详情,不能领)。 */
1468
+ function claimableCampaigns(campaigns) {
1469
+ return campaigns.filter(c => c.actionType === 'CLAIM_BENEFIT' && c.claimStatus === 'CLAIMABLE')
1470
+ }
1471
+
1472
+ async function loadQoderCampaigns(credential, product) {
1473
+ try {
1474
+ const response = await httpFetch(`${product.openApiBase}${QODER_CAMPAIGNS_PATH}`, {
1475
+ method: 'GET',
1476
+ headers: await qoderCreditsHeaders(credential, product),
1477
+ }, QODER_CREDITS_TIMEOUT_MS)
1478
+ if (!response.ok) return undefined
1479
+ const body = await response.json().catch(() => undefined)
1480
+ return body === undefined ? undefined : parseQoderCampaigns(body)
1481
+ } catch {
1482
+ return undefined
1483
+ }
1484
+ }
1485
+
1486
+ /** 查询余额;null = 查不到(与「余额 0」严格区分)。企业版也返回 null(无额度数字)。 */
1487
+ async function qoderFetchBalance(credential, product) {
1488
+ let body
1489
+ try {
1490
+ const response = await httpFetch(`${product.openApiBase}${QODER_USAGE_PATH}`, {
1491
+ method: 'GET',
1492
+ headers: await qoderCreditsHeaders(credential, product),
1493
+ }, QODER_CREDITS_TIMEOUT_MS)
1494
+ if (!response.ok) return null
1495
+ body = await response.json().catch(() => null)
1496
+ } catch {
1497
+ return null
1498
+ }
1499
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) return null
1500
+ if (body.displayMode === 'enterprise') return null
1501
+ const usage = body.qoderUsage
1502
+ if (usage === null || typeof usage !== 'object') return null
1503
+
1504
+ const packages = []
1505
+ // ⚠️ 余额不只在 userQuota:实测 userQuota=0 而 addOnQuota=100(「资源包」)。
1506
+ // 顺序即展示顺序:套餐额度 → 资源包 → 专用资源包。
1507
+ const userQuota = qoderPackage('套餐额度', usage.userQuota)
1508
+ if (userQuota !== undefined) packages.push(userQuota)
1509
+ const addOnQuota = qoderPackage('资源包', usage.addOnQuota)
1510
+ if (addOnQuota !== undefined) packages.push(addOnQuota)
1511
+ const dedicated = usage.dedicatedResourcePackages
1512
+ if (Array.isArray(dedicated)) {
1513
+ for (const item of dedicated) {
1514
+ const pkg = qoderPackage(
1515
+ readStringField(item, ['name']) ?? readStringField(item, ['id']) ?? '专用资源包',
1516
+ item,
1517
+ readStringField(item, ['expiresAt', 'expires_at']) ?? '',
1518
+ )
1519
+ if (pkg !== undefined) packages.push(pkg)
1520
+ }
1521
+ }
1522
+ // 一个包都没解析出来 → 「查不到」而非「余额 0」(后者会让用户以为额度被清空)。
1523
+ if (packages.length === 0) return null
1524
+ const total = roundCredits(packages.reduce((sum, pkg) => sum + pkg.remaining, 0))
1525
+ return { total, packages, expiredTotal: 0 }
1526
+ }
1527
+
1528
+ // ── 每日领取(campaigns → claim)────────────────────────────────────────────
1529
+
1530
+ /** 非 JSON 响应的可读原因(凭据失效时网关返回 HTML)。 */
1531
+ function qoderDescribeNonJson(status, text) {
1532
+ if (status === 401 || status === 403) return `凭据已失效(HTTP ${status}),请重新登录该账号`
1533
+ const snippet = String(text ?? '').trim().slice(0, 80).replace(/\s+/g, ' ')
1534
+ return `服务端返回了非 JSON 响应(HTTP ${status}):${snippet}`
1535
+ }
1536
+
1537
+ /**
1538
+ * 领单个活动。⚠️ 幂等判据是响应体 `replayed:true`,**不是 HTTP 状态码**
1539
+ * (重复领取同样 200,但 replayed:true、不含 benefit、claimedAt 是旧时间)。
1540
+ * ⚠️ 请求体必须是**空串**(抓包 content-length: 0)。
1541
+ */
1542
+ async function claimQoderCampaign(credential, product, campaignId) {
1543
+ const url = `${product.openApiBase}${QODER_CAMPAIGNS_PATH}/${encodeURIComponent(campaignId)}/claim`
1544
+ let response
1545
+ try {
1546
+ response = await httpFetch(url, {
1547
+ method: 'POST',
1548
+ headers: { ...(await qoderCreditsHeaders(credential, product)), 'Content-Type': 'application/json' },
1549
+ body: '',
1550
+ }, QODER_CREDITS_TIMEOUT_MS)
1551
+ } catch (error) {
1552
+ return { kind: 'failed', code: -1, message: error?.message ?? String(error) }
1553
+ }
1554
+ const text = await readBodyText(response).catch(() => '')
1555
+ let body
1556
+ try {
1557
+ body = text.length > 0 ? JSON.parse(text) : {}
1558
+ } catch {
1559
+ return { kind: 'failed', code: response.status, message: qoderDescribeNonJson(response.status, text) }
1560
+ }
1561
+ if (!response.ok) {
1562
+ return { kind: 'failed', code: response.status, message: qoderDescribeNonJson(response.status, text) }
1563
+ }
1564
+ const status = readStringField(body, ['status'])
1565
+ if (body?.replayed === true) return { kind: 'already-claimed', message: '今天已领取' }
1566
+ if (status !== undefined && status !== 'CLAIMED') {
1567
+ return { kind: 'failed', code: -1, message: `领取未成功(status=${status})` }
1568
+ }
1569
+ return { kind: 'claimed', credit: benefitAmount(body) ?? 0, streakDays: 0, isStreakDay: false }
1570
+ }
1571
+
1572
+ /**
1573
+ * 领取该账号**当前所有**可领活动(一个账号可能同时挂多个 CLAIM_BENEFIT),
1574
+ * 汇总为一条 ClaimOutcome:
1575
+ * 无可领 → inactive(⚠️ 不是 already-claimed:没东西可领 ≠ 领过了);
1576
+ * 至少一个成功 → claimed(累计 credit);全部 replayed → already-claimed;
1577
+ * 全部失败 → failed(带第一条原因)。
1578
+ */
1579
+ async function qoderClaimDaily(credential, product, nowMs = Date.now()) {
1580
+ const campaigns = await loadQoderCampaigns(credential, product)
1581
+ if (campaigns === undefined) {
1582
+ return { kind: 'failed', code: -1, message: '活动列表查询失败' }
1583
+ }
1584
+
1585
+ // 刷新前(每日 10:00 UTC+8)看到的全是昨天那一轮:领到也只能算补领,
1586
+ // 必须 coversToday:false + pending:true,否则上层把昨天那条已领记成今天已跑 ⇒
1587
+ // 当天 10 点刷新后的新额度整天漏领(不可逆方向)。pending 让上层只重试本渠道。
1588
+ const refreshed = hasQoderCampaignRefreshedToday(nowMs)
1589
+ const stale = refreshed ? {} : { coversToday: false, pending: true }
1590
+
1591
+ const targets = claimableCampaigns(campaigns)
1592
+ if (targets.length === 0) {
1593
+ // 三种「没领到」:① 领过(仅限刷新之后)② 未开通 ③ 暂时没活动。
1594
+ const claimedBefore = campaigns.some(c => c.actionType === 'CLAIM_BENEFIT' && c.claimStatus === 'CLAIMED')
1595
+ if (claimedBefore) {
1596
+ // 刷新前那条 CLAIMED 属于昨天,说成「今天已领取」是谎报(方向不可逆)。
1597
+ // 标 pending(可重试):10:00 刷新后还要再来一次;「未开通」则保持终态。
1598
+ if (!refreshed) return { kind: 'inactive', message: QODER_NOT_REFRESHED_YET_HINT, coversToday: false, pending: true }
1599
+ return { kind: 'already-claimed', message: '今天已领取' }
1600
+ }
1601
+ // 未开通额外查一次用量(只读)确认 —— 两条判据同时满足才提示。
1602
+ const usage = await fetchQoderUsageRaw(credential, product)
1603
+ if (isQoderNotActivated(campaigns, usage)) {
1604
+ return { kind: 'inactive', message: QODER_NOT_ACTIVATED_HINT, actionRequired: true }
1605
+ }
1606
+ return { kind: 'inactive', message: '当前没有可领取的活动' }
1607
+ }
1608
+
1609
+ let total = 0
1610
+ let firstError
1611
+ for (const target of targets) {
1612
+ const outcome = await claimQoderCampaign(credential, product, target.campaignId)
1613
+ if (outcome.kind === 'claimed') total += outcome.credit
1614
+ else if (outcome.kind === 'failed' && firstError === undefined) firstError = outcome.message
1615
+ }
1616
+ if (total > 0) return { kind: 'claimed', credit: total, streakDays: 0, isStreakDay: false, ...stale }
1617
+ if (firstError !== undefined) return { kind: 'failed', code: -1, message: firstError, ...stale }
1618
+ return { kind: 'already-claimed', message: '今天已领取', ...stale }
1619
+ }