dsh-unified-router 0.7.4 → 0.7.7

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.
@@ -217,7 +217,9 @@ export function createApiKeyManager(ctx, spec, deps = {}) {
217
217
  ])
218
218
  if (disposed || !toolsEnabled || !(await readKey())) return
219
219
  const outputDir = stateFile ? join(dirname(stateFile), spec.tools.outputDirName ?? `${spec.id}-tools-output`) : undefined
220
- const unregister = await module.registerTools({
220
+ // 渠道用同一模块、不同注册函数(如百炼的图像规格与 Agnes 不同)。
221
+ const register = module[spec.tools.register ?? 'registerTools']
222
+ const unregister = await register({
221
223
  tools, attachments: serviceOf(ctx, 'attachments'), resolveKey: readKey, fetchImpl, outputDir, defineTool: toolsModule.defineTool,
222
224
  })
223
225
  if (disposed) unregister()
@@ -844,6 +844,8 @@ const bailian = {
844
844
  chatPath: '/compatible-mode/v1/chat/completions',
845
845
  baseUrl: 'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
846
846
  credentialRef: 'UNIFIED_ROUTER_BAILIAN_API_KEY',
847
+ // 图像生成走 DashScope 协议的另一条路径,注册函数与聊天共用模块。
848
+ tools: { module: './image-tools.js', register: 'registerBailianTools' },
847
849
  consoleCredentialRef: 'UNIFIED_ROUTER_BAILIAN_CONSOLE',
848
850
  consoleLogin: {
849
851
  url: BAILIAN_CONSOLE_PAGE,
@@ -913,9 +915,20 @@ const bailian = {
913
915
  rate_limit_exceeded: 'rpm',
914
916
  Throttling: 'rpm',
915
917
  'Throttling.RateQuota': 'rpm',
918
+ 'Throttling.ServiceOverloaded': 'rpm',
916
919
  'Throttling.AllocationQuota': 'tpm',
920
+ 'Throttling.ResourceExhausted': 'tpm',
921
+ // 百炼把每分钟 Token 限流也标成 `insufficient_quota`(429 实测样本见
922
+ // throttlePattern),按 TPM 限流处理;真正的额度用尽由 exhaustedPattern
923
+ // 与 exhaustedCodes 拦住。
924
+ insufficient_quota: 'tpm',
917
925
  },
918
- exhaustedCodes: ['insufficient_quota', 'AllocationQuota.FreeTierOnly'],
926
+ // 429 实测原文:`Allocated quota exceeded, please increase your quota limit.
927
+ // For details, see: …/error-code#token-limit` —— message 与锚点都指向
928
+ // **每分钟 Token 限流**,不是账户额度耗尽。
929
+ throttlePattern: /token-limit|allocated[\s_-]+quota[\s_-]+exceeded|increase[\s_-]+your[\s_-]+quota[\s_-]+limit|quota[\s_-]+per[\s_-]+minute|\brate[\s_-]+limit|too[\s_-]+many[\s_-]+requests/i,
930
+ exhaustedCodes: ['AllocationQuota.FreeTierOnly'],
931
+ exhaustedPattern: /free[\s_-]+tier|free[\s_-]+quota|欠费|arrears|balance[\s_-]+(?:exhausted|depleted)|out[\s_-]+of[\s_-]+(?:credits?|budget)/i,
919
932
  },
920
933
  }
921
934
 
@@ -93,13 +93,39 @@ async function peekApiKeyError(response) {
93
93
  } catch { return null } finally { clearTimeout(timer); void reader.cancel().catch(() => {}) }
94
94
  }
95
95
 
96
+ /**
97
+ * 通用限流/耗尽判据(默认值,渠道规格可用 `throttlePattern` / `exhaustedPattern` 覆盖)。
98
+ *
99
+ * 为什么用文本判据而不是错误码表:上游对「每分钟 Token 超限」与「账户额度用尽」
100
+ * 用同一个错误码(百炼 429 实测两者都是 `insufficient_quota`),只查码必然误判;
101
+ * 而各家的码表既不稳定也无法穷举。同类实现(magpie 网关)同样以正文措辞为主判据,
102
+ * 只在少数明确码上走快路径 —— 这里沿用同一口径。
103
+ *
104
+ * 判定顺序:**先认「明确指向用尽」且不指向限流的**(真耗尽不能换号/不能当可重试),
105
+ * 其余落到限流或未知。文本取自错误正文的 message。
106
+ */
107
+ const DEFAULT_THROTTLE_PATTERN = new RegExp([
108
+ 'rate[\\s_.-]?limit', 'frequency[\\s_.-]?limit', 'too many requests',
109
+ 'per[\\s_.-]?(?:second|sec|minute|min)\\b', '\\b[rt]p[ms]\\b',
110
+ '(?:token|call|request)[\\s_.-]+rate[\\s_.-]+limit',
111
+ '每分钟', '每秒', '频率', '太频繁', '过于频繁', '速率',
112
+ 'token[\\s_.-]?limit',
113
+ ].join('|'), 'i')
114
+ const DEFAULT_EXHAUSTED_PATTERN = new RegExp([
115
+ 'insufficient[\\s_.-]?(?:balance|credit|fund)', '\\bcredits? (?:are )?exhausted\\b',
116
+ 'credit[\\s_.-]?balance[\\s_.-]?exhausted', 'out of (?:credits?|budget)',
117
+ 'budget.{0,32}(?:exceeded|exhausted)', 'free[\\s_.-]?tier', 'free[\\s_.-]?quota',
118
+ '余额不足', '欠费', '请充值', 'arrears',
119
+ ].join('|'), 'i')
120
+
96
121
  /**
97
122
  * 识别限流信号。
98
123
  *
99
- * 规格用两个字段表达差异:
124
+ * 规格用四个字段表达差异:
100
125
  * - `scanOnOk`:有的上游用 2xx + 业务码回限流(云知声 `100501`/`100502`),
101
126
  * 这类渠道连成功响应也要读 body;其余渠道只在 429 时读。
102
127
  * - `codes`:业务码 → `rpm` / `tpm` 的映射。
128
+ * - `throttlePattern` / `exhaustedPattern`:可选覆盖默认文本判据。
103
129
  */
104
130
  export async function detectApiKeyRateLimit(spec, response, now = Date.now()) {
105
131
  const recipe = spec?.rateLimit
@@ -107,16 +133,28 @@ export async function detectApiKeyRateLimit(spec, response, now = Date.now()) {
107
133
  // 只在 429,或规格声明「2xx 也可能带限流」时才读 body。
108
134
  if (response.status !== 429 && !(recipe.scanOnOk === true && response.ok)) return null
109
135
  const body = await peekApiKeyError(response)
110
- const code = String(body?.base_resp?.status_code ?? body?.error?.code ?? body?.error?.type ?? '')
111
- const type = String(body?.error?.type ?? '')
136
+ // 错误信封有两种形状:OpenAI 兼容(`{error:{code,type,message}}`)与阿里云风格
137
+ // (顶层 `{code,type,message}`)。只查 `error.*` 会把后者读成空串,进而把限流
138
+ // 误判为「unknown」。两种都要取。
139
+ const code = String(body?.base_resp?.status_code ?? body?.error?.code ?? body?.code ?? body?.error?.type ?? body?.type ?? '')
140
+ const type = String(body?.error?.type ?? body?.type ?? '')
141
+ const message = String(body?.error?.message ?? body?.message ?? body?.msg ?? '')
112
142
  // 额度耗尽不是限流:这类信号交给额度面板,不参与换号。
113
143
  const exhausted = new Set([
114
144
  '100104', '220107', '220108', '220109',
115
145
  'insufficient_quota', 'insufficient_balance', 'billing_hard_limit_reached',
116
146
  ...(recipe.exhaustedCodes ?? []),
117
147
  ])
118
- if (exhausted.has(code) || exhausted.has(type)) return null
119
- const reason = recipe.codes?.[code] ?? 'unknown'
148
+ // ⚠️ 上游会把**每分钟 Token 限流**也标成 `insufficient_quota`(百炼 429 实测:
149
+ // `{"code":"insufficient_quota","message":"Allocated quota exceeded, please
150
+ // increase your quota limit. …#token-limit"}`),只按错误码一刀切会把可恢复的
151
+ // TPM 限流当成账户额度用尽。故用正文二次判定:明确指向限流的不算耗尽,
152
+ // 明确指向额度/余额用尽的仍然排除。
153
+ const looksThrottled = (recipe.throttlePattern ?? DEFAULT_THROTTLE_PATTERN).test(message)
154
+ const looksExhausted = (recipe.exhaustedPattern ?? DEFAULT_EXHAUSTED_PATTERN).test(message)
155
+ if (looksExhausted && !looksThrottled) return null
156
+ if ((exhausted.has(code) || exhausted.has(type)) && !looksThrottled) return null
157
+ const reason = recipe.codes?.[code] ?? recipe.codes?.[type] ?? (looksThrottled ? 'tpm' : 'unknown')
120
158
  if (reason === 'unknown' && response.status !== 429) return null
121
159
  const header = response.headers.get('retry-after')?.trim()
122
160
  const delay = header && /^\d+(?:\.\d+)?$/.test(header) ? Number(header) * 1000
package/lib/backend.js CHANGED
@@ -3260,18 +3260,34 @@ var QODER = {
3260
3260
  fallbackModels: QODER_FALLBACK_MODELS
3261
3261
  };
3262
3262
  var QODER_CN_FALLBACK_MODELS = [
3263
- { id: "auto", name: "Auto", contextWindow: 2e5, supportsImage: true, supportsThinking: true, priceFactor: 0.5 },
3264
- { id: "fast", name: "Fast", contextWindow: 2e5, supportsImage: true, supportsThinking: false, priceFactor: 0.8 },
3265
- // 2026-11-19 --list-models lists these titles without publishing their backend keys or capabilities.
3266
- { id: "Qwen4-Max", name: "Qwen4-Max", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.4, efforts: ["xhigh", "low", "medium"], defaultEffort: "medium", supportsDisable: true },
3263
+ // ⚠️ **本表按上游目录接口逐项对齐**(`GET /algo/api/v2/model/list` 的 `chat`
3264
+ // 分组,2026-11-26 实测)。`id` 是**真实调用 key**,不是显示名 —— 两者常常
3265
+ // 不同(Qwen4-Max=`qmodel_latest`、GLM-5.4=`gmodel_latest`、
3266
+ // Step-5-Preview=`jmodel`);拿显示名当 `model` 发请求会回落默认模型且
3267
+ // 不产出 `reasoning_content`(用户报障「Qoder 思考设置无效」)。
3268
+ //
3269
+ // `--list-models` 只作接口不可用时的回退,它对这些条目只给显示名。
3270
+ // 倍率 `0` 是合法值(免费),不能当缺失。
3271
+ { id: "auto", name: "Auto", contextWindow: 2e5, priceFactor: 0.3, supportsImage: true, supportsThinking: true },
3272
+ {
3273
+ id: "qmodel_latest",
3274
+ name: "Qwen4-Max",
3275
+ contextWindow: 1e6,
3276
+ priceFactor: 0.4,
3277
+ supportsImage: true,
3278
+ supportsThinking: true,
3279
+ efforts: ["xhigh", "high", "low"],
3280
+ defaultEffort: "high",
3281
+ supportsDisable: true
3282
+ },
3267
3283
  {
3268
3284
  id: "qmodel_38max",
3269
3285
  name: "Qwen3.8-Max",
3270
- contextWindow: 1e6,
3286
+ contextWindow: 2e5,
3287
+ priceFactor: 0.5,
3271
3288
  supportsImage: true,
3272
3289
  supportsThinking: true,
3273
3290
  isFree: true,
3274
- priceFactor: 0.5,
3275
3291
  efforts: ["xhigh", "low", "medium"],
3276
3292
  defaultEffort: "medium",
3277
3293
  supportsDisable: true,
@@ -3280,28 +3296,116 @@ var QODER_CN_FALLBACK_MODELS = [
3280
3296
  {
3281
3297
  id: "qfmodel",
3282
3298
  name: "Qwen3.8-Flash",
3283
- contextWindow: 1e6,
3299
+ contextWindow: 2e5,
3300
+ priceFactor: 0.1,
3284
3301
  supportsImage: true,
3285
3302
  supportsThinking: true,
3286
3303
  isFree: true,
3287
- priceFactor: 0.1,
3288
3304
  efforts: ["xhigh", "low", "medium"],
3289
3305
  defaultEffort: "medium",
3290
3306
  supportsDisable: true
3291
3307
  },
3292
- { id: "dmodel", name: "DeepSeek-V4-Pro", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.5, efforts: ["low", "high", "max"], defaultEffort: "max", supportsDisable: true },
3293
- // 滚动别名按渠道原名保留,不凭别名推断具体快照版本。
3294
- { id: "dfmodel", name: "DeepSeek-Flash", contextWindow: 1e6, maxTokens: 393216, supportsImage: true, priceFactor: 0.1, efforts: ["low", "high", "max"], defaultEffort: "high", supportsDisable: true },
3295
- // 2026-11-26 实跑 --list-models 新增 GLM-5.4(CLI 不下发能力字段);规格取智谱官方文档(1M/128K、原生视觉、三档思考),倍率未知不编造。
3296
- { id: "GLM-5.4", name: "GLM-5.4", contextWindow: 1e6, maxTokens: 131072, supportsImage: true, supportsThinking: true, efforts: ["low", "high", "max"], defaultEffort: "high" },
3297
- { id: "gmodel", name: "GLM-5.3", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ["low", "high", "max"], defaultEffort: "high" },
3298
- { id: "gfmodel", name: "GLM-5.3-Flash", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ["high", "max"], defaultEffort: "max" },
3299
- { id: "kmodel_latest", name: "Kimi-K3.1-Pro", contextWindow: 1e6, supportsImage: true, priceFactor: 1, efforts: ["low", "high", "max"], defaultEffort: "high" },
3308
+ {
3309
+ id: "dmodel",
3310
+ name: "DeepSeek-V4-Pro",
3311
+ contextWindow: 2e5,
3312
+ priceFactor: 0.5,
3313
+ supportsImage: true,
3314
+ supportsThinking: true,
3315
+ efforts: ["high", "max"],
3316
+ defaultEffort: "max",
3317
+ supportsDisable: true
3318
+ },
3319
+ // 上游 `is_reasoning:false` 但目录给了三档,实测有思考帧 —— 以档位为准。
3320
+ {
3321
+ id: "dfmodel",
3322
+ name: "DeepSeek-Flash",
3323
+ contextWindow: 2e5,
3324
+ maxTokens: 393216,
3325
+ priceFactor: 0.1,
3326
+ supportsImage: true,
3327
+ supportsThinking: true,
3328
+ efforts: ["high", "max", "low"],
3329
+ defaultEffort: "high",
3330
+ supportsDisable: true
3331
+ },
3332
+ // ⚠️ 实测:`high` / `low` 档**不产出** reasoning_content(各 0 帧),
3333
+ // 只有 `max` 档会(423/540 帧)。故默认档取 `max`,并把 `max` 排在最前,
3334
+ // 让宿主默认落在能真正思考的那一档。
3335
+ {
3336
+ id: "gmodel_latest",
3337
+ name: "GLM-5.4",
3338
+ contextWindow: 2e5,
3339
+ priceFactor: 0.8,
3340
+ supportsImage: true,
3341
+ supportsThinking: true,
3342
+ efforts: ["max", "high", "low"],
3343
+ defaultEffort: "max"
3344
+ },
3345
+ {
3346
+ id: "gmodel",
3347
+ name: "GLM-5.3",
3348
+ contextWindow: 2e5,
3349
+ priceFactor: 0.8,
3350
+ supportsImage: true,
3351
+ supportsThinking: true,
3352
+ efforts: ["high", "low", "max"],
3353
+ defaultEffort: "high"
3354
+ },
3355
+ {
3356
+ id: "gfmodel",
3357
+ name: "GLM-5.3-Flash",
3358
+ contextWindow: 1e6,
3359
+ priceFactor: 0.1,
3360
+ supportsImage: true,
3361
+ supportsThinking: true,
3362
+ efforts: ["high", "max"],
3363
+ defaultEffort: "max"
3364
+ },
3365
+ {
3366
+ id: "kmodel_latest",
3367
+ name: "Kimi-K3.1-Pro",
3368
+ contextWindow: 2e5,
3369
+ priceFactor: 1,
3370
+ supportsImage: true,
3371
+ supportsThinking: true,
3372
+ efforts: ["high", "low", "max"],
3373
+ defaultEffort: "high"
3374
+ },
3300
3375
  // 同目录已有 Kimi-K3.1-Pro(`kmodel_latest`),K2.8 预览款默认不选。
3301
- { id: "kmodel", name: "Kimi-K2.8-Preview", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.8, efforts: ["low", "high", "max"], defaultEffort: "high", stale: true, staleReason: "\u540C\u76EE\u5F55\u5DF2\u6709 Kimi-K3.1-Pro\u3002" },
3302
- // 官方客户端只有 max 一档,不能补出关闭思考或其它强度选项。
3303
- { id: "Step-5-Preview", name: "Step-5-Preview", contextWindow: 0, priceFactor: 0.3 },
3304
- { id: "mmodel", name: "MiniMax-M3.1-Flash", contextWindow: 1e6, supportsImage: true, supportsThinking: true, priceFactor: 0.1, efforts: ["max"], defaultEffort: "max" }
3376
+ {
3377
+ id: "kmodel",
3378
+ name: "Kimi-K2.8-Preview",
3379
+ contextWindow: 2e5,
3380
+ priceFactor: 0.8,
3381
+ supportsImage: true,
3382
+ supportsThinking: true,
3383
+ efforts: ["high", "low", "max"],
3384
+ defaultEffort: "high",
3385
+ stale: true,
3386
+ staleReason: "\u540C\u76EE\u5F55\u5DF2\u6709 Kimi-K3.1-Pro\u3002"
3387
+ },
3388
+ {
3389
+ id: "jmodel",
3390
+ name: "Step-5-Preview",
3391
+ contextWindow: 1e6,
3392
+ priceFactor: 0.3,
3393
+ supportsImage: true,
3394
+ supportsThinking: true,
3395
+ efforts: ["high", "low", "medium"],
3396
+ defaultEffort: "high",
3397
+ supportsDisable: true
3398
+ },
3399
+ {
3400
+ id: "mmodel",
3401
+ name: "MiniMax-M3.1-Flash",
3402
+ contextWindow: 2e5,
3403
+ priceFactor: 0.1,
3404
+ supportsImage: true,
3405
+ supportsThinking: true,
3406
+ efforts: ["xhigh", "high", "low", "max", "medium"],
3407
+ defaultEffort: "xhigh"
3408
+ }
3305
3409
  ];
3306
3410
  var QODER_CN = {
3307
3411
  // ⚠️ id 不带连字符:它同时是 cordis 服务名(`qodercnAuth`)、LLM 路由名
@@ -5199,14 +5303,33 @@ import { dirname, resolve } from "node:path";
5199
5303
  var WASM_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "qoder-auth-wasm.wasm");
5200
5304
  var COSY_VERSION = "1.1.49";
5201
5305
  var IMPORT_MODULE = "./qoder_auth_wasm_bg.js";
5306
+ function reasoningBudgetFor(effort) {
5307
+ switch (effort) {
5308
+ case "minimal":
5309
+ case "low":
5310
+ return 1024;
5311
+ case "medium":
5312
+ return 8192;
5313
+ case "high":
5314
+ return 24576;
5315
+ case "xhigh":
5316
+ return 49152;
5317
+ case "max":
5318
+ return 65536;
5319
+ default:
5320
+ return void 0;
5321
+ }
5322
+ }
5202
5323
  function buildQoderInferPayload(ask, requestId = crypto.randomUUID()) {
5203
5324
  const isReasoning = ask.isReasoning ?? false;
5204
5325
  const text = ask.userText;
5205
5326
  const parameters = {};
5206
5327
  if (ask.maxTokens !== void 0) parameters.max_tokens = ask.maxTokens;
5207
5328
  if (ask.reasoningEffort !== void 0) {
5208
- parameters.reasoning_effort = ask.reasoningEffort;
5209
- parameters.enable_thinking = ask.reasoningEffort !== "none";
5329
+ const effort = ask.reasoningEffort === "off" ? "none" : ask.reasoningEffort;
5330
+ parameters.reasoning_effort = effort;
5331
+ if (effort !== "none") parameters.reasoning_budget_tokens = reasoningBudgetFor(effort);
5332
+ parameters.enable_thinking = effort !== "none";
5210
5333
  }
5211
5334
  if (ask.contextWindow !== void 0) parameters.context_length = ask.contextWindow;
5212
5335
  const messages = [];
@@ -5268,6 +5391,20 @@ function buildQoderInferPayload(ask, requestId = crypto.randomUUID()) {
5268
5391
  // 用户报障「qwen3.8-flash 执行任务出现任务调用 xml 泄露任务终止」。
5269
5392
  // 无工具时是**空数组**而非缺字段(与客户端一致)。
5270
5393
  tools: ask.tools ?? [],
5394
+ // ⚠️ **顶层 `reasoningEffort` 是官方客户端的第二个写入点**(用户报障
5395
+ // 「Qoder 思考设置无效」的真实原因):反编译 Qoder 桌面端 agent SDK 可见
5396
+ // 请求体为
5397
+ // ```
5398
+ // {..., reasoningEffort:"none", parameters:{...A.parameters, reasoning_effort:"none"}}
5399
+ // ```
5400
+ // 即**顶层 `reasoningEffort` 与 `parameters.reasoning_effort` 双写**。
5401
+ // 只写 `parameters` 时上游照常回正文,但从不产出 `reasoning_content`
5402
+ // —— 实测:日志显示 parameters 正确(`reasoning_effort:"xhigh"` +
5403
+ // `enable_thinking:true` + 预算),而响应帧只有 `content`/`tool_calls`。
5404
+ // 证据:`@dmh2002/dsh-connect-qoder` CHANGELOG 的同一条反编译结论。
5405
+ ...ask.reasoningEffort === void 0 ? {} : {
5406
+ reasoningEffort: ask.reasoningEffort === "off" ? "none" : ask.reasoningEffort
5407
+ },
5271
5408
  parameters,
5272
5409
  // `business` 决定服务端路由(`sec_scan` → 安全池,其余 → 默认池)。
5273
5410
  ...ask.business === void 0 ? {} : { business: ask.business }
@@ -5448,6 +5585,15 @@ async function generateRuntimeAuthFields(user) {
5448
5585
  return JSON.parse(raw);
5449
5586
  }
5450
5587
  var QoderEncryptedInfer = class _QoderEncryptedInfer {
5588
+ // ⚠️ 用显式字段赋值而不是构造函数参数属性(`constructor(private g: Glue)`):
5589
+ // 参数属性是 TypeScript 独有语法,Node 的 strip-only 类型剥离**不支持**
5590
+ // (`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`),会让 `buildQoderInferPayload`
5591
+ // 这类纯函数无法被测试直接 import。行为等价。
5592
+ g;
5593
+ context;
5594
+ metadata;
5595
+ /** 加密端点所在 host(`agent_chat_generation`)。 */
5596
+ host;
5451
5597
  constructor(g, context, metadata, host) {
5452
5598
  this.g = g;
5453
5599
  this.context = context;
@@ -5657,6 +5803,7 @@ import { dirname as dirname2 } from "node:path";
5657
5803
  import { randomUUID as randomUUID2 } from "node:crypto";
5658
5804
  var QODER_CLI_RUNTIME = "C:\\Program Files\\Qoder CN\\resources\\app.asar.unpacked\\node_modules\\@qoder-ai\\qoder-cn-agent-sdk\\dist\\_worker\\qoder-worker-runtime.obf.mjs";
5659
5805
  var QODER_CLI_TIMEOUT_MS = 25e3;
5806
+ var QODER_ROUTE_KEYS = /* @__PURE__ */ new Set(["auto", "fast"]);
5660
5807
  function parseQoderCliModels(stdout) {
5661
5808
  const out = [];
5662
5809
  const seen = /* @__PURE__ */ new Set();
@@ -5667,14 +5814,15 @@ function parseQoderCliModels(stdout) {
5667
5814
  const match = /^(.+?)(?: \(([^()]+)\))?$/.exec(line);
5668
5815
  if (!match) continue;
5669
5816
  const name = match[1].trim();
5817
+ const keyed = match[2] !== void 0;
5670
5818
  const id = (match[2] ?? name).trim();
5671
5819
  if (!id || seen.has(id)) continue;
5672
5820
  seen.add(id);
5673
- out.push({ id, name });
5821
+ out.push({ id, name, keyed });
5674
5822
  }
5675
5823
  return out;
5676
5824
  }
5677
- function mergeQoderCatalog(cli, fallback) {
5825
+ function mergeQoderCatalog(cli, fallback, requireKey = true) {
5678
5826
  const byId = new Map(fallback.map((model) => [model.id, model]));
5679
5827
  const byName = new Map(fallback.map((model) => [model.name.toLowerCase(), model]));
5680
5828
  const out = [];
@@ -5683,6 +5831,7 @@ function mergeQoderCatalog(cli, fallback) {
5683
5831
  const known = byId.get(row.id) ?? (row.id === row.name ? byName.get(row.name.toLowerCase()) : void 0);
5684
5832
  const id = known?.id ?? row.id;
5685
5833
  if (!id || seen.has(id)) continue;
5834
+ if (requireKey && row.keyed === false && !QODER_ROUTE_KEYS.has(id)) continue;
5686
5835
  seen.add(id);
5687
5836
  out.push(known ? { ...known, name: row.name } : { id, name: row.name, contextWindow: 0 });
5688
5837
  }
@@ -5722,6 +5871,7 @@ ${result.stderr}`;
5722
5871
  const cli = parseQoderCliModels(result.stdout);
5723
5872
  if (cli.length === 0) return fail("empty");
5724
5873
  const catalog = mergeQoderCatalog(cli, fallback);
5874
+ if (catalog.length === 0) return fail("no-model-key");
5725
5875
  return { catalog, count: catalog.length, source: "remote" };
5726
5876
  } catch {
5727
5877
  return fail("cli-failed");
@@ -5771,6 +5921,156 @@ async function defaultRunQoderCli() {
5771
5921
  return first;
5772
5922
  }
5773
5923
 
5924
+ // vendor/channel-pack/src/qoder-model-list.ts
5925
+ var QODER_MODEL_LIST_PATH = "/algo/api/v2/model/list?Encode=1";
5926
+ var QODER_MODEL_GROUPS = ["assistant", "developer", "chat"];
5927
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
5928
+ var nonEmptyString = (value) => typeof value === "string" && value.length > 0 && value.length <= 256;
5929
+ function toQoderModelRow(entry) {
5930
+ if (!object(entry) || !nonEmptyString(entry.key)) return null;
5931
+ const row = entry;
5932
+ const efforts = object(row.thinking_config?.enabled?.efforts) ? Object.keys(row.thinking_config.enabled.efforts) : [];
5933
+ const defaultEffort = efforts.find((effort) => {
5934
+ const value = (row.thinking_config?.enabled?.efforts)[effort];
5935
+ return value?.is_default === true;
5936
+ });
5937
+ const defaults = object(row.context_config) ? Object.values(row.context_config) : [];
5938
+ const preferred = Number((defaults.find((cfg) => cfg?.is_default === true) ?? defaults[0])?.token_count);
5939
+ const contextWindow = Number.isFinite(preferred) && preferred > 0 ? preferred : Number(row.max_input_tokens);
5940
+ const priceFactor = Number(row.price_factor);
5941
+ return {
5942
+ id: row.key,
5943
+ name: nonEmptyString(row.display_name) ? row.display_name : row.key,
5944
+ // `0` 是「未知窗口」哨兵(宿主投影按 `> 0` 过滤),不编造。
5945
+ contextWindow: Number.isFinite(contextWindow) && contextWindow > 0 ? contextWindow : 0,
5946
+ supportsImage: row.is_vl === true,
5947
+ // ⚠️ 上游 `is_reasoning` 与「是否产出 reasoning_content」不完全一致:
5948
+ // `dfmodel` 报 `is_reasoning:false` 但实测 50/57 帧有思考,且目录给了
5949
+ // 三个档位。有档位即可思考 —— 不要用 `is_reasoning:false` 把档位选择器关掉。
5950
+ supportsThinking: row.is_reasoning === true || efforts.length > 0,
5951
+ ...efforts.length > 0 ? { efforts } : {},
5952
+ ...defaultEffort !== void 0 ? { defaultEffort } : {},
5953
+ ...row.thinking_config?.disabled !== void 0 ? { supportsDisable: true } : {},
5954
+ // ⚠️ `0` 是合法的「免费」倍率,不能当缺失处理(`Number.isFinite` 判据)。
5955
+ ...Number.isFinite(priceFactor) && priceFactor >= 0 ? { priceFactor } : {}
5956
+ };
5957
+ }
5958
+ function parseQoderModelList(json) {
5959
+ if (!object(json)) return null;
5960
+ let rows = null;
5961
+ for (const group of QODER_MODEL_GROUPS) {
5962
+ const candidate = json[group];
5963
+ if (Array.isArray(candidate) && candidate.length > 0) {
5964
+ rows = candidate;
5965
+ break;
5966
+ }
5967
+ }
5968
+ if (rows === null) return null;
5969
+ const out = [];
5970
+ const seen = /* @__PURE__ */ new Set();
5971
+ for (const entry of rows) {
5972
+ const row = toQoderModelRow(entry);
5973
+ if (row === null || seen.has(row.id)) continue;
5974
+ seen.add(row.id);
5975
+ out.push(row);
5976
+ }
5977
+ return out.length > 0 ? out : null;
5978
+ }
5979
+
5980
+ // vendor/channel-pack/src/qoder-cosy.ts
5981
+ import { createCipheriv as createCipheriv2, createHash as createHash3, constants, publicEncrypt, randomBytes as randomBytes3 } from "node:crypto";
5982
+ var COSY_VERSION2 = "1.0.10";
5983
+ var SERVER_PUB_KEY = `-----BEGIN PUBLIC KEY-----
5984
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
5985
+ 4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
5986
+ 6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
5987
+ XcW+ML9FoCI6AOvOzwIDAQAB
5988
+ -----END PUBLIC KEY-----`;
5989
+ var md5Hex = (s) => createHash3("md5").update(s).digest("hex");
5990
+ var deriveID = (seed, salt, installSalt = "") => md5Hex(`${salt}:${installSalt ? `${seed}|salt:${installSalt}` : seed}`);
5991
+ var deriveMachineId = (seed, installSalt = "") => deriveID(seed, "machine", installSalt);
5992
+ var deriveMachineType = (seed, installSalt = "") => deriveID(seed, "machinetype", installSalt).slice(0, 18);
5993
+ var deriveMachineToken = (seed, installSalt = "") => createHash3("sha512").update(`machinetoken:${installSalt ? `${seed}|salt:${installSalt}` : seed}`).digest().toString("base64url").slice(0, 43);
5994
+ var aesCbcEncrypt = (plain, key) => {
5995
+ const pad = 16 - plain.length % 16;
5996
+ const padded = Buffer.concat([plain, Buffer.alloc(pad, pad)]);
5997
+ const cipher = createCipheriv2("aes-128-cbc", key, key.subarray(0, 16));
5998
+ cipher.setAutoPadding(false);
5999
+ return Buffer.concat([cipher.update(padded), cipher.final()]);
6000
+ };
6001
+ var newUUID = () => {
6002
+ const hex = randomBytes3(16).toString("hex");
6003
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
6004
+ };
6005
+ function newCosySession(identity) {
6006
+ const tempKey = randomBytes3(8).toString("hex");
6007
+ const cosyKey = publicEncrypt(
6008
+ { key: SERVER_PUB_KEY, padding: constants.RSA_PKCS1_PADDING },
6009
+ Buffer.from(tempKey, "utf8")
6010
+ ).toString("base64");
6011
+ const payload = JSON.stringify({
6012
+ name: "",
6013
+ aid: "",
6014
+ uid: identity.uid,
6015
+ yx_uid: "",
6016
+ organization_id: "",
6017
+ organization_name: "",
6018
+ user_type: "",
6019
+ security_oauth_token: identity.securityOauthToken,
6020
+ refresh_token: identity.refreshToken ?? ""
6021
+ });
6022
+ const info = aesCbcEncrypt(Buffer.from(payload, "utf8"), Buffer.from(tempKey, "utf8")).toString("base64");
6023
+ const seed = identity.uid;
6024
+ return {
6025
+ uid: identity.uid,
6026
+ info,
6027
+ cosyKey,
6028
+ machineId: deriveMachineId(seed),
6029
+ machineType: deriveMachineType(seed),
6030
+ machineToken: deriveMachineToken(seed)
6031
+ };
6032
+ }
6033
+ var pathSigOf = (rawUrl) => {
6034
+ const url = new URL(rawUrl);
6035
+ return url.pathname.startsWith("/algo") ? url.pathname.slice(5) : url.pathname;
6036
+ };
6037
+ var signRequest = (payloadB64, cosyKey, cosyDate, body, pathSig) => md5Hex(`${payloadB64}
6038
+ ${cosyKey}
6039
+ ${cosyDate}
6040
+ ${body}
6041
+ ${pathSig}`);
6042
+ function cosyHeaders(session, fullUrl, body, accept = "application/json") {
6043
+ const payloadB64 = Buffer.from(JSON.stringify({
6044
+ cosyVersion: COSY_VERSION2,
6045
+ ideVersion: "",
6046
+ info: session.info,
6047
+ requestId: newUUID(),
6048
+ version: "v1"
6049
+ }), "utf8").toString("base64");
6050
+ const date = String(Math.floor(Date.now() / 1e3));
6051
+ const sig = signRequest(payloadB64, session.cosyKey, date, body, pathSigOf(fullUrl));
6052
+ return {
6053
+ "cosy-data-policy": "agree",
6054
+ "content-type": "application/json",
6055
+ "cosy-machinetype": session.machineType,
6056
+ "cosy-clienttype": "5",
6057
+ "cosy-date": date,
6058
+ "cosy-user": session.uid,
6059
+ "cosy-key": session.cosyKey,
6060
+ "cache-control": "no-cache",
6061
+ accept,
6062
+ authorization: `Bearer COSY.${payloadB64}.${sig}`,
6063
+ "cosy-version": COSY_VERSION2,
6064
+ "cosy-machineid": session.machineId,
6065
+ "cosy-machinetoken": session.machineToken,
6066
+ "login-version": "v2",
6067
+ "user-agent": "Go-http-client/2.0",
6068
+ "cosy-scene": "assistant",
6069
+ "cosy-business-product": "ide",
6070
+ "cosy-business-type": "agent"
6071
+ };
6072
+ }
6073
+
5774
6074
  // src/image-pricing.js
5775
6075
  var FALLBACK_IMAGE_PRICING = Object.freeze({
5776
6076
  /** @param {readonly { offloaded?: boolean }[]} images */
@@ -6959,7 +7259,9 @@ function buildQoderHistory(messages) {
6959
7259
  const isEmpty = parts === void 0 ? content.length === 0 : content.length === 0;
6960
7260
  if (isEmpty && toolCalls === void 0 && toolCallId === void 0) continue;
6961
7261
  history.push({
6962
- role: message.role,
7262
+ // ⚠️ 上游不认 `developer` 角色(OpenAI 新角色):原样发出去会被当成未知
7263
+ // role 忽略整条消息(社区插件的同一结论)。折叠为 `system`。
7264
+ role: message.role === "developer" ? "system" : message.role,
6963
7265
  content,
6964
7266
  ...toolCalls === void 0 ? {} : { tool_calls: toolCalls },
6965
7267
  ...toolCallId === void 0 ? {} : { tool_call_id: toolCallId }
@@ -7113,6 +7415,15 @@ var QoderAdapter = class extends LlmAdapter {
7113
7415
  * 只在用户**手动点「刷新目录」**时被调到 —— 第三方驱动官方组件的显式同意。
7114
7416
  */
7115
7417
  async refreshRemoteModels() {
7418
+ const direct = await this.fetchDirectCatalog();
7419
+ if (direct !== null) {
7420
+ this.catalogIssue = void 0;
7421
+ this.cliCatalog = direct;
7422
+ this.catalogSource = "remote";
7423
+ if (this.options.cliCatalogFile) await saveQoderCatalog(this.options.cliCatalogFile, direct).catch(() => {
7424
+ });
7425
+ return { source: this.catalogSource, count: direct.length, catalog: direct };
7426
+ }
7116
7427
  const { catalog, ...result } = await refreshQoderCatalog(
7117
7428
  this.options.runQoderCli ?? defaultRunQoderCli,
7118
7429
  this.product.fallbackModels ?? []
@@ -7128,6 +7439,31 @@ var QoderAdapter = class extends LlmAdapter {
7128
7439
  }
7129
7440
  return { ...result, source: this.catalogSource, count: this.cliCatalog?.length ?? result.count };
7130
7441
  }
7442
+ /**
7443
+ * 直连上游目录接口取模型表;任一环节不可用返回 `null`(交给 CLI 回退)。
7444
+ *
7445
+ * 凭据取当前可用账号的 `uid` + `security_oauth_token`(签名身份);
7446
+ * **凭据不进日志**。
7447
+ */
7448
+ async fetchDirectCatalog() {
7449
+ try {
7450
+ const credential = await this.options.resolveCredential(void 0);
7451
+ if (credential === void 0) return null;
7452
+ const uid = credential.uid ?? "";
7453
+ const securityOauthToken = credential.security_oauth_token ?? credential.access_token ?? "";
7454
+ if (!uid || !securityOauthToken) return null;
7455
+ const url = `${this.product.encryptedInferBase.replace(/\/+$/, "")}${QODER_MODEL_LIST_PATH}`;
7456
+ const session = newCosySession({ uid, securityOauthToken, refreshToken: credential.refresh_token });
7457
+ const response = await (this.options.fetchImpl ?? fetch)(url, {
7458
+ headers: cosyHeaders(session, url, ""),
7459
+ signal: AbortSignal.timeout(2e4)
7460
+ });
7461
+ if (!response.ok) return null;
7462
+ return parseQoderModelList(await response.json().catch(() => null));
7463
+ } catch {
7464
+ return null;
7465
+ }
7466
+ }
7131
7467
  async listModels(_provider) {
7132
7468
  if (!await providerCatalogVisible(this.options.accountPool, this.product.id)) return [];
7133
7469
  const disabled = this.options.accountPool?.disabledModelsFor?.(this.product.id);
@@ -7254,7 +7590,12 @@ var QoderAdapter = class extends LlmAdapter {
7254
7590
  modelKey: options.model,
7255
7591
  userText,
7256
7592
  ...systemText !== void 0 ? { systemText } : {},
7257
- isReasoning: fallback?.supportsThinking ?? (fallback !== void 0 && qoderEffortsFor(fallback).some((effort) => effort !== "off")),
7593
+ // ⚠️ 对齐官方 `dQ.isEnabled(model, config)`:`支持思考且未关闭`,
7594
+ // **不是**只看模型能力。用户把档位切到「关闭思考」时仍发
7595
+ // `is_reasoning: true` 会让上游按「要思考」解析、却又没有预算
7596
+ // (旧实现连 `reasoning_budget_tokens` 都不发),回包因此没有任何
7597
+ // 思考内容 —— 用户报障「思考设置无效」。
7598
+ isReasoning: reasoningEffort === void 0 ? fallback?.supportsThinking === true : reasoningEffort !== "off" && fallback?.supportsThinking !== false,
7258
7599
  history,
7259
7600
  // 工具定义:这是模型**唯一**能学到函数 schema 的通道,
7260
7601
  // 缺了它模型只能用正文 XML 臆造调用(真实缺陷)。
@@ -11878,7 +12219,7 @@ async function fetchRaccoonOnboardingStatus(product, credential, fetcher = fetch
11878
12219
  }
11879
12220
 
11880
12221
  // vendor/channel-pack/src/raccoon-oauth.ts
11881
- import { randomBytes as randomBytes3 } from "node:crypto";
12222
+ import { randomBytes as randomBytes4 } from "node:crypto";
11882
12223
  function parseEnvelope2(payload, status) {
11883
12224
  const record = typeof payload === "object" && payload !== null && !Array.isArray(payload) ? payload : {};
11884
12225
  const code = typeof record.code === "number" ? record.code : status >= 400 ? status : 0;
@@ -11915,7 +12256,7 @@ async function postJson2(url, body, fetcher, headers = {}) {
11915
12256
  return { envelope: parseEnvelope2(parsed, response.status), status: response.status };
11916
12257
  }
11917
12258
  function generateQrCode() {
11918
- return randomBytes3(16).toString("hex");
12259
+ return randomBytes4(16).toString("hex");
11919
12260
  }
11920
12261
  function buildQrImageUrl(product, code) {
11921
12262
  const params = new URLSearchParams({ code, appname: "\u5546\u6C64\u5C0F\u6D63\u718A\u5B98\u7F51" });