@xixka/dsh-hub 0.4.11 → 0.4.13

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 (144) hide show
  1. package/README.md +11 -0
  2. package/icon.svg +5 -0
  3. package/lib/aggregate-adapter.d.ts.map +1 -1
  4. package/lib/aggregate-adapter.js +11 -0
  5. package/lib/aggregate-adapter.js.map +1 -1
  6. package/lib/astudio-adapter.d.ts.map +1 -1
  7. package/lib/astudio-adapter.js +7 -1
  8. package/lib/astudio-adapter.js.map +1 -1
  9. package/lib/astudio.d.ts +28 -0
  10. package/lib/astudio.d.ts.map +1 -1
  11. package/lib/astudio.js +42 -2
  12. package/lib/astudio.js.map +1 -1
  13. package/lib/atomcode-auth.js +3 -3
  14. package/lib/atomcode-auth.js.map +1 -1
  15. package/lib/atomcode-credits.js +3 -3
  16. package/lib/atomcode-credits.js.map +1 -1
  17. package/lib/atomcode-product.d.ts +8 -0
  18. package/lib/atomcode-product.d.ts.map +1 -1
  19. package/lib/atomcode-product.js +10 -0
  20. package/lib/atomcode-product.js.map +1 -1
  21. package/lib/auto-adapter.d.ts +0 -8
  22. package/lib/auto-adapter.d.ts.map +1 -1
  23. package/lib/auto-adapter.js +17 -8
  24. package/lib/auto-adapter.js.map +1 -1
  25. package/lib/buddy-adapter.d.ts.map +1 -1
  26. package/lib/buddy-adapter.js +5 -5
  27. package/lib/buddy-adapter.js.map +1 -1
  28. package/lib/buddy-balance-rank.d.ts +121 -15
  29. package/lib/buddy-balance-rank.d.ts.map +1 -1
  30. package/lib/buddy-balance-rank.js +267 -20
  31. package/lib/buddy-balance-rank.js.map +1 -1
  32. package/lib/buddy-balance-selector.d.ts +20 -0
  33. package/lib/buddy-balance-selector.d.ts.map +1 -1
  34. package/lib/buddy-balance-selector.js +23 -2
  35. package/lib/buddy-balance-selector.js.map +1 -1
  36. package/lib/cache-token-count.d.ts +21 -0
  37. package/lib/cache-token-count.d.ts.map +1 -0
  38. package/lib/cache-token-count.js +23 -0
  39. package/lib/cache-token-count.js.map +1 -0
  40. package/lib/chromium-session.d.ts +125 -51
  41. package/lib/chromium-session.d.ts.map +1 -1
  42. package/lib/chromium-session.js +402 -162
  43. package/lib/chromium-session.js.map +1 -1
  44. package/lib/client/jet-hub.js +722 -58
  45. package/lib/doubao-login.d.ts +0 -20
  46. package/lib/doubao-login.d.ts.map +1 -1
  47. package/lib/doubao-login.js +53 -17
  48. package/lib/doubao-login.js.map +1 -1
  49. package/lib/doubao-signin.d.ts +0 -32
  50. package/lib/doubao-signin.d.ts.map +1 -1
  51. package/lib/doubao-signin.js +21 -35
  52. package/lib/doubao-signin.js.map +1 -1
  53. package/lib/gemini-messages.d.ts.map +1 -1
  54. package/lib/gemini-messages.js +4 -3
  55. package/lib/gemini-messages.js.map +1 -1
  56. package/lib/index.d.ts.map +1 -1
  57. package/lib/index.js +9 -2
  58. package/lib/index.js.map +1 -1
  59. package/lib/jet-hub-rpc.js +115 -4
  60. package/lib/jet-hub-rpc.js.map +1 -1
  61. package/lib/llm-adapter.d.ts.map +1 -1
  62. package/lib/llm-adapter.js +12 -5
  63. package/lib/llm-adapter.js.map +1 -1
  64. package/lib/llm-register-compat.d.ts.map +1 -1
  65. package/lib/llm-register-compat.js +6 -1
  66. package/lib/llm-register-compat.js.map +1 -1
  67. package/lib/lobsterai-adapter.d.ts.map +1 -1
  68. package/lib/lobsterai-adapter.js +5 -5
  69. package/lib/lobsterai-adapter.js.map +1 -1
  70. package/lib/login.d.ts +7 -20
  71. package/lib/login.d.ts.map +1 -1
  72. package/lib/login.js +7 -21
  73. package/lib/login.js.map +1 -1
  74. package/lib/loomy-adapter.d.ts.map +1 -1
  75. package/lib/loomy-adapter.js +23 -7
  76. package/lib/loomy-adapter.js.map +1 -1
  77. package/lib/minimax-messages.d.ts.map +1 -1
  78. package/lib/minimax-messages.js +2 -1
  79. package/lib/minimax-messages.js.map +1 -1
  80. package/lib/model-promotions.d.ts +122 -0
  81. package/lib/model-promotions.d.ts.map +1 -1
  82. package/lib/model-promotions.js +260 -0
  83. package/lib/model-promotions.js.map +1 -1
  84. package/lib/models.d.ts +14 -0
  85. package/lib/models.d.ts.map +1 -1
  86. package/lib/models.js +105 -4
  87. package/lib/models.js.map +1 -1
  88. package/lib/officeace-lock.d.ts +32 -2
  89. package/lib/officeace-lock.d.ts.map +1 -1
  90. package/lib/officeace-lock.js +53 -7
  91. package/lib/officeace-lock.js.map +1 -1
  92. package/lib/openai-compat.d.ts +32 -0
  93. package/lib/openai-compat.d.ts.map +1 -1
  94. package/lib/openai-compat.js +17 -5
  95. package/lib/openai-compat.js.map +1 -1
  96. package/lib/openai-gateway/responses.d.ts.map +1 -1
  97. package/lib/openai-gateway/responses.js +2 -1
  98. package/lib/openai-gateway/responses.js.map +1 -1
  99. package/lib/openai-gateway/stream.d.ts.map +1 -1
  100. package/lib/openai-gateway/stream.js +15 -5
  101. package/lib/openai-gateway/stream.js.map +1 -1
  102. package/lib/openai-gateway/usage.d.ts +1 -2
  103. package/lib/openai-gateway/usage.d.ts.map +1 -1
  104. package/lib/openai-gateway/usage.js +4 -3
  105. package/lib/openai-gateway/usage.js.map +1 -1
  106. package/lib/qoder-catalog.d.ts.map +1 -1
  107. package/lib/qoder-catalog.js +74 -5
  108. package/lib/qoder-catalog.js.map +1 -1
  109. package/lib/qoder-product.d.ts +15 -0
  110. package/lib/qoder-product.d.ts.map +1 -1
  111. package/lib/qoder-product.js.map +1 -1
  112. package/lib/raccoon-account-queue.d.ts +15 -0
  113. package/lib/raccoon-account-queue.d.ts.map +1 -0
  114. package/lib/raccoon-account-queue.js +59 -0
  115. package/lib/raccoon-account-queue.js.map +1 -0
  116. package/lib/raccoon-adapter.d.ts +60 -9
  117. package/lib/raccoon-adapter.d.ts.map +1 -1
  118. package/lib/raccoon-adapter.js +297 -190
  119. package/lib/raccoon-adapter.js.map +1 -1
  120. package/lib/raccoon-auth.d.ts +11 -0
  121. package/lib/raccoon-auth.d.ts.map +1 -1
  122. package/lib/raccoon-auth.js +96 -4
  123. package/lib/raccoon-auth.js.map +1 -1
  124. package/lib/raccoon-login-page.d.ts.map +1 -1
  125. package/lib/raccoon-login-page.js +11 -1
  126. package/lib/raccoon-login-page.js.map +1 -1
  127. package/lib/token-ledger.d.ts +1 -1
  128. package/lib/token-ledger.d.ts.map +1 -1
  129. package/lib/token-ledger.js +21 -4
  130. package/lib/token-ledger.js.map +1 -1
  131. package/lib/trae.d.ts.map +1 -1
  132. package/lib/trae.js +3 -2
  133. package/lib/trae.js.map +1 -1
  134. package/lib/types.d.ts +65 -0
  135. package/lib/types.d.ts.map +1 -1
  136. package/lib/types.js.map +1 -1
  137. package/lib/usage-badge.d.ts +8 -0
  138. package/lib/usage-badge.d.ts.map +1 -1
  139. package/lib/usage-badge.js +20 -0
  140. package/lib/usage-badge.js.map +1 -1
  141. package/lib/zcode-anthropic.d.ts.map +1 -1
  142. package/lib/zcode-anthropic.js +2 -1
  143. package/lib/zcode-anthropic.js.map +1 -1
  144. package/package.json +5 -2
@@ -21,11 +21,13 @@
21
21
  import { LlmAdapter, LlmError, ReasoningEffortId } from '@deepseek-ai/dsh-llm';
22
22
  import { createModelCatalog, isCatalogFresh, isCatalogFreshFor } from './model-catalog.js';
23
23
  import { RemoteCatalogGate } from './remote-catalog-gate.js';
24
+ import { RaccoonAccountQueue } from './raccoon-account-queue.js';
24
25
  import { broadcastCatalogChanged } from './catalog-broadcast.js';
25
26
  import { isRaccoonExpired } from './raccoon.js';
26
27
  import { RACCOON, RACCOON_DEFAULT_EFFORT, RACCOON_EFFORT_NAMES, RACCOON_EFFORT_OFF, RACCOON_EFFORT_ON, RACCOON_REASONING_EFFORTS, } from './raccoon-product.js';
27
28
  import { projectRequestImage } from './image-budget.js';
28
29
  import { planSessionTitleThinking } from './session-title.js';
30
+ import { nextPromotionEdgeMs, promotionBadgeFor, raccoonPromotionCandidate } from './model-promotions.js';
29
31
  import { registerAdapterIdempotent, } from './llm-register-compat.js';
30
32
  import { collectImages, consumeOpenAiSse, errorDetail, httpErrorCode, isTransportError, serializeMessages, } from './openai-compat.js';
31
33
  /** 本适配器注册的 provider 路由名(等价于 `RACCOON.id`)。 */
@@ -358,6 +360,19 @@ export class RaccoonAdapter extends LlmAdapter {
358
360
  * (现状);只有 `catalogAt` 则无内容可展示。
359
361
  */
360
362
  catalogAt = 0;
363
+ /** 每账号一条推理队列:同账号最多一个完整 SSE 请求在途。 */
364
+ accountRequestQueues = new Map();
365
+ requestQueueFor(accountId, accessToken) {
366
+ // 池账号用稳定 id;旧单凭据模式没有账号 id 时以 token 区分,绝不把
367
+ // 不同单凭据误串成同一条全局队列。token 只留在内存,不输出日志。
368
+ const key = accountId || accessToken;
369
+ let queue = this.accountRequestQueues.get(key);
370
+ if (queue === undefined) {
371
+ queue = new RaccoonAccountQueue();
372
+ this.accountRequestQueues.set(key, queue);
373
+ }
374
+ return queue;
375
+ }
361
376
  /** 目录加载闸门:并发去重 + 失败/空结果冷却(见 `remote-catalog-gate.ts`)。 */
362
377
  catalogGate;
363
378
  /**
@@ -442,6 +457,14 @@ export class RaccoonAdapter extends LlmAdapter {
442
457
  // ⚠️ 必须走夹子(issue IKS1L5):兜底表/远端都可能声明 100_000,而上游硬校验
443
458
  // 1..65536 ⇒ 声明值会被 DSH 原样回传进每一轮请求,命中就整轮 400。
444
459
  const maxTokens = clampRaccoonMaxTokens(model.maxTokens ?? fallback?.maxTokens);
460
+ // ★ 徽标(issue #101):上游的计费活动(`billing_status`/`billing_discounts`)。
461
+ // ⚠️ 时钟必须在**装配时刻**读(与目录新鲜度同一个注入时钟):目录是 20 分钟一份的
462
+ // 快照,把徽标在解析时挑定并缓存正是 issue #101 要修的形态
463
+ // (「活动 11月22日结束,22 日之后还挂着一枚限时折扣」)。
464
+ // ⚠️ 窗口外**什么都不画**(`standingEligible: false`):宿主徽标契约只有 text+tone,
465
+ // 没有悬停位去说「还没到点」。
466
+ const promotion = raccoonPromotionCandidate(model.promotion, model.id, 'Asia/Shanghai', this.promotionWarn);
467
+ const badge = promotionBadgeFor(promotion === undefined ? undefined : [promotion], this.nowMs());
445
468
  return {
446
469
  id: model.id,
447
470
  name: model.name,
@@ -455,8 +478,70 @@ export class RaccoonAdapter extends LlmAdapter {
455
478
  // 思考档位(两态:深度思考 / 关闭思考)。实测确证见 `raccoonReasoningInfo`。
456
479
  // ⚠️ 所有模型一致 —— `extra_body.thinking` 是 provider 级方言,与模型无关。
457
480
  reasoning: raccoonReasoningInfo(),
481
+ // ⚠️ 省略即「本家没有活动可画」(宿主据此回落到裸 name + 倍率);不写空值。
482
+ ...badge === undefined ? {} : { badge },
458
483
  };
459
484
  }
485
+ /** 注入时钟(与目录 TTL 同一个 `options.now`,单测可推进)。 */
486
+ nowMs() {
487
+ return this.options.now?.() ?? Date.now();
488
+ }
489
+ /**
490
+ * ★ 本家目录里的**未决**活动候选(方案 A:选择器悬停的数据来源)。
491
+ *
492
+ * ⚠️ 与 buddy 家**刻意不同**的一处:本家远端条目里**本来就带** `billing_discounts`
493
+ * 的原料,故在线路径有候选;而兜底表是编译期快照(红线「静态表必然腐坏」),
494
+ * **不带**活动 ⇒ 离线路径返回空,与「上游没有活动」同形(与 buddy 一致)。
495
+ *
496
+ * ⚠️ 逐条走 `raccoonPromotionCandidate`(与 `toCatalogEntry` **同一个**构造函数),
497
+ * 不另写一份解析:同一 schema 两套判据是本仓的复发缺陷形态。
498
+ *
499
+ * ⚠️ 交出去的是**未决候选**:徽标在装配时刻挑定并缓存正是 issue #101 要修的形态;
500
+ * 悬停侧(`plugin-src/client/model-label.js`)每次渲染重读时钟。
501
+ */
502
+ promotionCandidates() {
503
+ const rows = [];
504
+ for (const model of this.remoteModels ?? []) {
505
+ const promotion = raccoonPromotionCandidate(model.promotion, model.id, 'Asia/Shanghai', this.promotionWarn);
506
+ if (promotion !== undefined)
507
+ rows.push({ modelId: model.id, promotion });
508
+ }
509
+ return rows;
510
+ }
511
+ /**
512
+ * ★ 本家的下一次活动边界(epoch ms),供 `promotion-edge-broadcast` 定时重算徽标。
513
+ *
514
+ * ⚠️⚠️ 不接这个 getter 的后果(2026-11-18 我实测):raccoon 的 `start_at`/`end_at` 是
515
+ * 「绝对时刻窗口」,而目录缓存 20 分钟一轮 —— 边界时刻不触发重算 ⇒ 8:00 结束的活动
516
+ * 要在行上**多挂最长 20 分钟**,正是 issue #101 点名的那格(「活动过期而用户仍按优惠
517
+ * 期选择」)。同批接上这个 getter 的 lobsterai(PR #114)就是同型。
518
+ *
519
+ * ⚠️ **零网络**:只读 `remoteModels` 里已解析好的候选,不触发 `fetchRemoteModels`。
520
+ * 返回 `undefined` 是安全值 —— `nearestPromotionEdge` 逐源 try/catch、非有限数即跳过。
521
+ */
522
+ nextPromotionEdgeAt(nowMs = this.nowMs()) {
523
+ const rows = this.promotionCandidates();
524
+ if (rows.length === 0)
525
+ return undefined;
526
+ return nextPromotionEdgeMs(rows.map((row) => row.promotion), nowMs);
527
+ }
528
+ /**
529
+ * 徽标解析的日志出口(与 `options.warn` 同一个通道),**按消息去重**。
530
+ *
531
+ * ⚠️ 必须去重:本回调挂在 `toCatalogEntry` 上,对**目录里每一条**、每次 `listModels`
532
+ * 都跑;不去重就是「每次打开选择器 × 每个坏条目」一行。
533
+ * ⚠️ 上限 64 条:长期运行的进程不该攒出一张没人读的字典;封顶后不再播,
534
+ * 也不清空(宁可少一条日志,也不要一个会自己长大的内存)。
535
+ */
536
+ promotionWarned = new Set();
537
+ promotionWarn = (message) => {
538
+ if (this.promotionWarned.has(message))
539
+ return;
540
+ if (this.promotionWarned.size >= 64)
541
+ return;
542
+ this.promotionWarned.add(message);
543
+ this.options.warn?.(message);
544
+ };
460
545
  async loadCatalogEntries() {
461
546
  const all = await this.loadModels();
462
547
  return all.map((model) => this.toCatalogEntry(model, this.fallbackIndex.get(model.id)));
@@ -594,209 +679,231 @@ export class RaccoonAdapter extends LlmAdapter {
594
679
  }
595
680
  catch { /* 反查失败不阻断主路径:轮换退化为「不标记」 */ }
596
681
  }
597
- const messages = serializeMessages(options.messages, imageUrls);
598
- /**
599
- * 前置 system 消息(若有)。
600
- *
601
- * ⚠️ 必须**先拼再放进对象**,不要在对象字面量里写两次 `messages` ——
602
- * 后者依赖「后面的键覆盖前面」这一隐式行为,读者极易误判成漏了 system。
603
- */
604
- const wireMessages = options.system !== undefined && options.system.length > 0
605
- ? [{ role: 'system', content: options.system }, ...messages]
606
- : messages;
607
- /**
608
- * 思考档位 → `extra_body` 内容。
609
- *
610
- * ⚠️ 在 `buildBody` **之外**算一次:`buildBody` 会在重试时被多次调用,
611
- * 每次重算虽无害但没必要。
612
- *
613
- * ⚠️ **会话自动命名(`purpose: 'session-title'`)必须关闭思考**(issue
614
- * IKKVDH):DSH 用 **64 token** 发标题请求且**不传 `reasoningEffort`**,
615
- * 而宿主会把本模型的默认档(本家恒为 `'on'`)注入进来
616
- * (`effective = requested ?? reasoning.defaultEffort`)。照常开思考时实测
617
- * 均值约 222 个思考 token,必然顶穿 64 ⇒ 正文 0 字符、
618
- * `finish_reason:'length'` ⇒ DSH 直接拒绝、标题永远停在 fallback。
619
- *
620
- * 本家的档位表是**恒声明的两档**(`on`/`off`,与模型无关,见
621
- * `raccoon-product.ts`)⇒ 任何模型都**关得掉**,故不需要抬预算。
622
- */
623
- const titlePlan = planSessionTitleThinking({
624
- purpose: options.purpose,
625
- requestedEffort: options.reasoningEffort === undefined ? undefined : String(options.reasoningEffort),
626
- declaredEfforts: RACCOON_REASONING_EFFORTS,
627
- maxTokens: options.maxTokens,
628
- });
629
- const thinking = raccoonThinkingExtraBody(titlePlan.effort);
630
- // ⚠️ **请求体这一腿也必须夹**(issue IKS1L5):`titlePlan.maxTokens` 对非标题
631
- // 请求是原样透传调用方的 `maxTokens` 的(用户 / OpenAI 兼容网关都能塞 999999),
632
- // 上游会把整轮打成 400 且该 model group 没有 fallback。
633
- const requestMaxTokens = clampRaccoonMaxTokens(titlePlan.maxTokens);
634
- /** 构造请求体。 */
635
- const buildBody = () => JSON.stringify({
636
- model: options.model,
637
- messages: wireMessages,
638
- stream: true,
639
- ...requestMaxTokens !== undefined ? { max_tokens: requestMaxTokens } : {},
640
- ...options.temperature !== undefined ? { temperature: options.temperature } : {},
641
- ...options.stop !== undefined && options.stop.length > 0 ? { stop: options.stop } : {},
642
- // ⚠️ tools 必须真的下发到请求体**顶层**:Qoder/TRAE 都因漏发而让模型
643
- // 在正文里臆造 XML 工具调用,harness 认不出 → 任务终止。
644
- ...options.tools !== undefined && options.tools.length > 0
645
- ? {
646
- tools: options.tools.map((tool) => ({
647
- type: 'function',
648
- function: {
649
- name: tool.name,
650
- ...tool.description.length > 0 ? { description: tool.description } : {},
651
- ...tool.parameters === undefined ? {} : { parameters: tool.parameters },
652
- },
653
- })),
654
- }
655
- : {},
656
- // 思考档位(开 / 关)。⚠️ **必须在 `extra_body` 内** —— 实测放顶层会被忽略
657
- //(连非法值都不报错)。不传档位时不发该字段,保持服务端默认(= 开)。
658
- ...thinking !== undefined ? { extra_body: thinking } : {},
659
- });
660
- const headers = () => ({
661
- Accept: 'text/event-stream',
662
- 'Content-Type': 'application/json',
663
- Authorization: `Bearer ${credential?.access_token ?? ''}`,
664
- 'X-Org-Code': credential?.office_identity ?? '',
665
- 'X-Raccoon-Language': 'zh',
666
- 'X-Client-Platform': this.product.clientPlatform,
667
- });
668
- /** 发送一次 chat 请求。 */
669
- const send = async () => {
670
- try {
671
- return await this.fetchImpl(`${this.product.apiBase}${this.product.llmApiPrefix}/chat/completions`, {
672
- method: 'POST',
673
- headers: headers(),
674
- body: buildBody(),
675
- signal: options.signal,
676
- });
677
- }
678
- catch (error) {
679
- if (options.signal?.aborted)
680
- throw error;
681
- if (isTransportError(error)) {
682
- throw new LlmError(`raccoon: transport error: ${error instanceof Error ? error.message : String(error)}`, 'TRANSPORT', { cause: error });
683
- }
684
- throw error;
685
- }
682
+ let requestQueue = this.requestQueueFor(activeAccountId, credential.access_token);
683
+ let releaseRequest = await requestQueue.acquire({ signal: options.signal });
684
+ const switchRequestAccount = async () => {
685
+ const nextQueue = this.requestQueueFor(activeAccountId, credential?.access_token ?? '');
686
+ if (nextQueue === requestQueue)
687
+ return;
688
+ // 旧账号的 HTTP 响应已经落定,先释放再等新账号,避免两个并发请求
689
+ // 交叉换号时分别持有对方所需队列而死锁。释放函数幂等,外层 finally
690
+ // 在等待新队列被取消时也能安全收尾。
691
+ releaseRequest();
692
+ releaseRequest = await nextQueue.acquire({ signal: options.signal });
693
+ requestQueue = nextQueue;
686
694
  };
687
- let response = await send();
688
- // 401/403 时续期一次并重试(raccoon 有 refresh_token 轮换)。
689
- if (response.status === 401 || response.status === 403) {
690
- await this.options.refresh();
691
- const refreshed = await this.options.resolveCredential(options.model, options.sessionId);
692
- if (refreshed === undefined || refreshed.access_token.length === 0) {
693
- throw new LlmError('raccoon: credential expired and refresh failed', 'AUTH', { status: response.status });
694
- }
695
- credential = refreshed;
696
- // ⚠️ **必须跟着重新反查账号 id**(PR !71 审计发现):`resolveCredential`
697
- // 是「池优先」的(`src/index.ts` 的 raccoon 分支先 `getAvailableAccount`
698
- // 再回退单凭据 ref),而 `refresh()` 续期的是**默认单凭据 ref**。
699
- // ⇒ 续期后取回的凭据**可能属于另一个账号**,但 `activeAccountId` 还停在
700
- // 刷新前的那个号上。
701
- // 后果(实测可复现):A 的 token 过期 → 刷新后拿到 B 的凭据 → B 随后
702
- // 返回额度耗尽,而冷却标记却**记在 A 头上** ⇒ 没耗尽的 A 被封 24h,
703
- // 真该封的 B 下次仍被选中(本段要修的「卡死在一个号上」照旧)。
704
- // 这与 AGENTS.md 记的 Qoder「标记用了会变的回调导致标错账号」同型。
705
- if (this.options.accountPool) {
706
- try {
707
- activeAccountId = await this.options.accountPool.findAccountIdByCredential(this.product.id, refreshed.access_token) ?? '';
708
- }
709
- catch { /* 反查失败不阻断主路径:轮换退化为「不标记」 */ }
710
- }
711
- response = await send();
712
- }
713
- if (!response.ok) {
714
- let errorText = await response.text().catch(() => '');
715
- let status = response.status;
695
+ try {
696
+ const messages = serializeMessages(options.messages, imageUrls);
716
697
  /**
717
- * 请求级账号轮换(2026-10-05,用户报障「余额用完一个号就卡死」)。
698
+ * 前置 system 消息(若有)。
718
699
  *
719
- * ## 为什么必须有这一段
700
+ * ⚠️ 必须**先拼再放进对象**,不要在对象字面量里写两次 `messages` ——
701
+ * 后者依赖「后面的键覆盖前面」这一隐式行为,读者极易误判成漏了 system。
702
+ */
703
+ const wireMessages = options.system !== undefined && options.system.length > 0
704
+ ? [{ role: 'system', content: options.system }, ...messages]
705
+ : messages;
706
+ /**
707
+ * 思考档位 → `extra_body` 内容。
720
708
  *
721
- * `resolveCredential` 从池里取号按**手动顺序**(`getAvailableAccount`
722
- * 的既有语义),失败类别不写标记时,下次请求取回的**仍是同一个号**。
723
- * 首号余额耗尽(`14018 Credits exhausted`)→ 错误抛给 harness →
724
- * 下次请求还是它 ⇒ 用户看到的是「卡死在一个号上」,池里其余账号
725
- * 完好却永远轮不到。
709
+ * ⚠️ 在 `buildBody` **之外**算一次:`buildBody` 会在重试时被多次调用,
710
+ * 每次重算虽无害但没必要。
726
711
  *
727
- * ## 语义对齐 buddy(本项目无感换号的基准实现)
712
+ * ⚠️ **会话自动命名(`purpose: 'session-title'`)必须关闭思考**(issue
713
+ * IKKVDH):DSH 用 **64 token** 发标题请求且**不传 `reasoningEffort`**,
714
+ * 而宿主会把本模型的默认档(本家恒为 `'on'`)注入进来
715
+ * (`effective = requested ?? reasoning.defaultEffort`)。照常开思考时实测
716
+ * 均值约 222 个思考 token,必然顶穿 64 ⇒ 正文 0 字符、
717
+ * `finish_reason:'length'` ⇒ DSH 直接拒绝、标题永远停在 fallback。
728
718
  *
729
- * - **可换号**的失败类别:余额/额度耗尽(14018 / Credits / quota /
730
- * 积分不足等)、限流(429)、认证(401/403——单号凭据失效时池里
731
- * 可能有别的好号);**非额度且非限流**(400 参数错等)换号无益,
732
- * 按原错误抛(避免把「请求本身有问题」吞成「均不可用」)。
733
- * - **每个账号只试一次**:`tried` 传给 `getAvailableAccount`——不排除
734
- * 会拿回同一个号(池排序不因失败而变),换号形同虚设。
735
- * - **只有配额 / 限流类才写冷却**(`recordsRaccoonRateLimit`):
736
- * 认证类(401/403)**只换号、绝不写标记** —— 详见
737
- * {@link RaccoonFailureClass} 记的 2026-10-06 全池被封事故。
738
- * - **全部试完才报错**,且带**最后一次**的真实原因——笼统的
739
- * 「所有账号均不可用」会丢掉服务端真正说的东西(buddy 上同款教训)。
740
- * - **冷却时长按类别**:`quota` 记 24 小时(日配额;无可靠重置字段,
741
- * 与 trae 4008 同形)、`rate` 记 1 小时。
719
+ * 本家的档位表是**恒声明的两档**(`on`/`off`,与模型无关,见
720
+ * `raccoon-product.ts`)⇒ 任何模型都**关得掉**,故不需要抬预算。
742
721
  */
743
- let failureClass = classifyRaccoonFailure(errorText, status);
744
- const accountPool = this.options.accountPool;
745
- if (accountPool && failureClass !== 'other') {
746
- const tried = new Set();
747
- if (activeAccountId)
748
- tried.add(activeAccountId);
749
- const markCurrentAccount = async () => {
750
- // 每次失败后立即记账,包括轮换预算用尽的最后一个账号。
751
- // 认证错误只换号,不写模型冷却。
752
- if (!activeAccountId || !recordsRaccoonRateLimit(failureClass))
753
- return;
754
- await accountPool.updateModelRateLimit(activeAccountId, options.model, Date.now() + (failureClass === 'rate'
755
- ? RACCOON_RATE_LIMIT_COOLDOWN_MS
756
- : RACCOON_QUOTA_COOLDOWN_MS));
757
- };
758
- await markCurrentAccount();
759
- const maxRotate = RACCOON_MAX_ROTATE - 1;
760
- for (let round = 0; round < maxRotate; round++) {
761
- const next = await accountPool.getAvailableAccount(this.product.id, options.model, tried);
762
- if (!next || tried.has(next.entry.id))
763
- break;
764
- tried.add(next.entry.id);
765
- credential = next.credential;
766
- activeAccountId = next.entry.id;
767
- response = await send();
768
- if (response.ok) {
769
- // ⚠️ 业务失败也可能以 HTTP 200 + SSE 内嵌错误帧返回(既有说明见下)。
770
- yield* consumeOpenAiSse(response, { signal: options.signal }, {
771
- label: 'raccoon',
772
- firstTokenTimeoutMs: resolveFirstTokenTimeoutMs(),
773
- chunkTimeoutMs: resolveChunkTimeoutMs(),
774
- ...options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens },
775
- });
776
- return;
722
+ const titlePlan = planSessionTitleThinking({
723
+ purpose: options.purpose,
724
+ requestedEffort: options.reasoningEffort === undefined ? undefined : String(options.reasoningEffort),
725
+ declaredEfforts: RACCOON_REASONING_EFFORTS,
726
+ maxTokens: options.maxTokens,
727
+ });
728
+ const thinking = raccoonThinkingExtraBody(titlePlan.effort);
729
+ // ⚠️ **请求体这一腿也必须夹**(issue IKS1L5):`titlePlan.maxTokens` 对非标题
730
+ // 请求是原样透传调用方的 `maxTokens` 的(用户 / OpenAI 兼容网关都能塞 999999),
731
+ // 上游会把整轮打成 400 且该 model group 没有 fallback。
732
+ const requestMaxTokens = clampRaccoonMaxTokens(titlePlan.maxTokens);
733
+ /** 构造请求体。 */
734
+ const buildBody = () => JSON.stringify({
735
+ model: options.model,
736
+ messages: wireMessages,
737
+ stream: true,
738
+ ...requestMaxTokens !== undefined ? { max_tokens: requestMaxTokens } : {},
739
+ ...options.temperature !== undefined ? { temperature: options.temperature } : {},
740
+ ...options.stop !== undefined && options.stop.length > 0 ? { stop: options.stop } : {},
741
+ // ⚠️ tools 必须真的下发到请求体**顶层**:Qoder/TRAE 都因漏发而让模型
742
+ // 在正文里臆造 XML 工具调用,harness 认不出 → 任务终止。
743
+ ...options.tools !== undefined && options.tools.length > 0
744
+ ? {
745
+ tools: options.tools.map((tool) => ({
746
+ type: 'function',
747
+ function: {
748
+ name: tool.name,
749
+ ...tool.description.length > 0 ? { description: tool.description } : {},
750
+ ...tool.parameters === undefined ? {} : { parameters: tool.parameters },
751
+ },
752
+ })),
753
+ }
754
+ : {},
755
+ // 思考档位(开 / 关)。⚠️ **必须在 `extra_body` 内** —— 实测放顶层会被忽略
756
+ //(连非法值都不报错)。不传档位时不发该字段,保持服务端默认(= 开)。
757
+ ...thinking !== undefined ? { extra_body: thinking } : {},
758
+ });
759
+ const headers = () => ({
760
+ Accept: 'text/event-stream',
761
+ 'Content-Type': 'application/json',
762
+ Authorization: `Bearer ${credential?.access_token ?? ''}`,
763
+ 'X-Org-Code': credential?.office_identity ?? '',
764
+ 'X-Raccoon-Language': 'zh',
765
+ 'X-Client-Platform': this.product.clientPlatform,
766
+ });
767
+ /** 发送一次 chat 请求。 */
768
+ const send = async () => {
769
+ try {
770
+ return await this.fetchImpl(`${this.product.apiBase}${this.product.llmApiPrefix}/chat/completions`, {
771
+ method: 'POST',
772
+ headers: headers(),
773
+ body: buildBody(),
774
+ signal: options.signal,
775
+ });
776
+ }
777
+ catch (error) {
778
+ if (options.signal?.aborted)
779
+ throw error;
780
+ if (isTransportError(error)) {
781
+ throw new LlmError(`raccoon: transport error: ${error instanceof Error ? error.message : String(error)}`, 'TRANSPORT', { cause: error });
777
782
  }
778
- errorText = await response.text().catch(() => '');
779
- status = response.status;
780
- failureClass = classifyRaccoonFailure(errorText, status);
783
+ throw error;
784
+ }
785
+ };
786
+ let response = await send();
787
+ // 401/403 时续期一次并重试(raccoon 有 refresh_token 轮换)。
788
+ if (response.status === 401 || response.status === 403) {
789
+ await this.options.refresh();
790
+ const refreshed = await this.options.resolveCredential(options.model, options.sessionId);
791
+ if (refreshed === undefined || refreshed.access_token.length === 0) {
792
+ throw new LlmError('raccoon: credential expired and refresh failed', 'AUTH', { status: response.status });
793
+ }
794
+ credential = refreshed;
795
+ // ⚠️ **必须跟着重新反查账号 id**(PR !71 审计发现):`resolveCredential`
796
+ // 是「池优先」的(`src/index.ts` 的 raccoon 分支先 `getAvailableAccount`
797
+ // 再回退单凭据 ref),而 `refresh()` 续期的是**默认单凭据 ref**。
798
+ // ⇒ 续期后取回的凭据**可能属于另一个账号**,但 `activeAccountId` 还停在
799
+ // 刷新前的那个号上。
800
+ // 后果(实测可复现):A 的 token 过期 → 刷新后拿到 B 的凭据 → B 随后
801
+ // 返回额度耗尽,而冷却标记却**记在 A 头上** ⇒ 没耗尽的 A 被封 24h,
802
+ // 真该封的 B 下次仍被选中(本段要修的「卡死在一个号上」照旧)。
803
+ // 这与 AGENTS.md 记的 Qoder「标记用了会变的回调导致标错账号」同型。
804
+ if (this.options.accountPool) {
805
+ try {
806
+ activeAccountId = await this.options.accountPool.findAccountIdByCredential(this.product.id, refreshed.access_token) ?? '';
807
+ }
808
+ catch { /* 反查失败不阻断主路径:轮换退化为「不标记」 */ }
809
+ }
810
+ await switchRequestAccount();
811
+ response = await send();
812
+ }
813
+ if (!response.ok) {
814
+ let errorText = await response.text().catch(() => '');
815
+ let status = response.status;
816
+ /**
817
+ * 请求级账号轮换(2026-10-05,用户报障「余额用完一个号就卡死」)。
818
+ *
819
+ * ## 为什么必须有这一段
820
+ *
821
+ * `resolveCredential` 从池里取号按**手动顺序**(`getAvailableAccount`
822
+ * 的既有语义),失败类别不写标记时,下次请求取回的**仍是同一个号**。
823
+ * 首号余额耗尽(`14018 Credits exhausted`)→ 错误抛给 harness →
824
+ * 下次请求还是它 ⇒ 用户看到的是「卡死在一个号上」,池里其余账号
825
+ * 完好却永远轮不到。
826
+ *
827
+ * ## 语义对齐 buddy(本项目无感换号的基准实现)
828
+ *
829
+ * - **可换号**的失败类别:余额/额度耗尽(14018 / Credits / quota /
830
+ * 积分不足等)、限流(429)、认证(401/403——单号凭据失效时池里
831
+ * 可能有别的好号);**非额度且非限流**(400 参数错等)换号无益,
832
+ * 按原错误抛(避免把「请求本身有问题」吞成「均不可用」)。
833
+ * - **每个账号只试一次**:`tried` 传给 `getAvailableAccount`——不排除
834
+ * 会拿回同一个号(池排序不因失败而变),换号形同虚设。
835
+ * - **只有配额 / 限流类才写冷却**(`recordsRaccoonRateLimit`):
836
+ * 认证类(401/403)**只换号、绝不写标记** —— 详见
837
+ * {@link RaccoonFailureClass} 记的 2026-10-06 全池被封事故。
838
+ * - **全部试完才报错**,且带**最后一次**的真实原因——笼统的
839
+ * 「所有账号均不可用」会丢掉服务端真正说的东西(buddy 上同款教训)。
840
+ * - **冷却时长按类别**:`quota` 记 24 小时(日配额;无可靠重置字段,
841
+ * 与 trae 4008 同形)、`rate` 记 1 小时。
842
+ */
843
+ let failureClass = classifyRaccoonFailure(errorText, status);
844
+ const accountPool = this.options.accountPool;
845
+ if (accountPool && failureClass !== 'other') {
846
+ const tried = new Set();
847
+ if (activeAccountId)
848
+ tried.add(activeAccountId);
849
+ const markCurrentAccount = async () => {
850
+ // 每次失败后立即记账,包括轮换预算用尽的最后一个账号。
851
+ // 认证错误只换号,不写模型冷却。
852
+ if (!activeAccountId || !recordsRaccoonRateLimit(failureClass))
853
+ return;
854
+ await accountPool.updateModelRateLimit(activeAccountId, options.model, Date.now() + (failureClass === 'rate'
855
+ ? RACCOON_RATE_LIMIT_COOLDOWN_MS
856
+ : RACCOON_QUOTA_COOLDOWN_MS));
857
+ };
781
858
  await markCurrentAccount();
782
- if (failureClass === 'other') {
783
- // 新账号失败但不是可换号类别:按原错误分类抛出(buddy 同款)。
784
- throw abortLikeOrNormal(errorText, status);
859
+ const maxRotate = RACCOON_MAX_ROTATE - 1;
860
+ for (let round = 0; round < maxRotate; round++) {
861
+ const next = await accountPool.getAvailableAccount(this.product.id, options.model, tried);
862
+ if (!next || tried.has(next.entry.id))
863
+ break;
864
+ tried.add(next.entry.id);
865
+ credential = next.credential;
866
+ activeAccountId = next.entry.id;
867
+ await switchRequestAccount();
868
+ response = await send();
869
+ if (response.ok) {
870
+ // ⚠️ 业务失败也可能以 HTTP 200 + SSE 内嵌错误帧返回(既有说明见下)。
871
+ yield* consumeOpenAiSse(response, { signal: options.signal }, {
872
+ label: 'raccoon',
873
+ firstTokenTimeoutMs: resolveFirstTokenTimeoutMs(),
874
+ chunkTimeoutMs: resolveChunkTimeoutMs(),
875
+ ...options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens },
876
+ });
877
+ return;
878
+ }
879
+ errorText = await response.text().catch(() => '');
880
+ status = response.status;
881
+ failureClass = classifyRaccoonFailure(errorText, status);
882
+ await markCurrentAccount();
883
+ if (failureClass === 'other') {
884
+ // 新账号失败但不是可换号类别:按原错误分类抛出(buddy 同款)。
885
+ throw abortLikeOrNormal(errorText, status);
886
+ }
785
887
  }
888
+ throw new LlmError(`raccoon: 模型 ${options.model} 所有账号均不可用(${errorDetail(errorText)})`, failureClass === 'rate' ? 'RATE_LIMIT'
889
+ : failureClass === 'auth' ? 'AUTH'
890
+ : 'QUOTA_EXCEEDED', { status });
786
891
  }
787
- throw new LlmError(`raccoon: 模型 ${options.model} 所有账号均不可用(${errorDetail(errorText)})`, failureClass === 'rate' ? 'RATE_LIMIT'
788
- : failureClass === 'auth' ? 'AUTH'
789
- : 'QUOTA_EXCEEDED', { status });
892
+ throw abortLikeOrNormal(errorText, status);
790
893
  }
791
- throw abortLikeOrNormal(errorText, status);
894
+ // ⚠️ 业务失败也可能以 HTTP 200 + SSE 内嵌错误帧返回,由 consumeOpenAiSse 处理。
895
+ yield* consumeOpenAiSse(response, { signal: options.signal }, {
896
+ label: 'raccoon',
897
+ firstTokenTimeoutMs: resolveFirstTokenTimeoutMs(),
898
+ chunkTimeoutMs: resolveChunkTimeoutMs(),
899
+ ...options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens },
900
+ });
901
+ }
902
+ finally {
903
+ // 持有到 SSE 完整消费(或异常、调用方提前 return)才释放;只在
904
+ // fetch 返回时释放会让同账号的第二个请求与第一条流并发上行。
905
+ releaseRequest();
792
906
  }
793
- // ⚠️ 业务失败也可能以 HTTP 200 + SSE 内嵌错误帧返回,由 consumeOpenAiSse 处理。
794
- yield* consumeOpenAiSse(response, { signal: options.signal }, {
795
- label: 'raccoon',
796
- firstTokenTimeoutMs: resolveFirstTokenTimeoutMs(),
797
- chunkTimeoutMs: resolveChunkTimeoutMs(),
798
- ...options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens },
799
- });
800
907
  }
801
908
  }
802
909
  /** 首 token 超时(毫秒);可用环境变量覆盖(与其余适配器同约定)。 */