@eddyskywalker/dsh-chatgpt-subscription 1.0.1 → 1.1.1

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 (47) hide show
  1. package/lib/client.js +89 -8
  2. package/lib/client.js.map +1 -1
  3. package/lib/codemode.js +33 -5
  4. package/lib/index.js +461 -64
  5. package/lib/{preset-sync-DWOAwSyl.js → preset-sync-RBsYhDY3.js} +2 -1
  6. package/lib/{tool-result-pruner-ClgRVOph.js → tool-result-pruner-DsaDg_l1.js} +2 -1
  7. package/lib/tool-result-pruner.js +1 -1
  8. package/lib/types/client/features/progress-updates/settings-section.d.ts +2 -2
  9. package/lib/types/client/locales-ru/qoder.d.ts.map +1 -1
  10. package/lib/types/client/providers/qoder/QoderComposerQuota.d.ts.map +1 -1
  11. package/lib/types/client/providers/qoder/QoderSection.d.ts.map +1 -1
  12. package/lib/types/client/providers/qoder/locales.d.ts +7 -1
  13. package/lib/types/client/providers/qoder/locales.d.ts.map +1 -1
  14. package/lib/types/client/providers/qoder/styles.d.ts.map +1 -1
  15. package/lib/types/client/providers/qoder/useQoderSection.d.ts +15 -0
  16. package/lib/types/client/providers/qoder/useQoderSection.d.ts.map +1 -1
  17. package/lib/types/compat.d.ts +1 -1
  18. package/lib/types/entries/tool-result-pruner.d.ts.map +1 -1
  19. package/lib/types/host/providers/antigravity-acp/adapter.d.ts.map +1 -1
  20. package/lib/types/host/providers/qoder/account-affinity.d.ts +16 -0
  21. package/lib/types/host/providers/qoder/account-affinity.d.ts.map +1 -0
  22. package/lib/types/host/providers/qoder/account-pool.d.ts +4 -2
  23. package/lib/types/host/providers/qoder/account-pool.d.ts.map +1 -1
  24. package/lib/types/host/providers/qoder/adapter.d.ts +15 -0
  25. package/lib/types/host/providers/qoder/adapter.d.ts.map +1 -1
  26. package/lib/types/host/providers/qoder/cache-diagnostics.d.ts +20 -0
  27. package/lib/types/host/providers/qoder/cache-diagnostics.d.ts.map +1 -0
  28. package/lib/types/host/providers/qoder/cosy.d.ts +12 -5
  29. package/lib/types/host/providers/qoder/cosy.d.ts.map +1 -1
  30. package/lib/types/host/providers/qoder/mapper.d.ts +15 -0
  31. package/lib/types/host/providers/qoder/mapper.d.ts.map +1 -1
  32. package/lib/types/host/providers/qoder/model-catalog.d.ts +18 -0
  33. package/lib/types/host/providers/qoder/model-catalog.d.ts.map +1 -1
  34. package/lib/types/host/providers/qoder/queue-state.d.ts +8 -1
  35. package/lib/types/host/providers/qoder/queue-state.d.ts.map +1 -1
  36. package/lib/types/host/providers/qoder/traffic-guard.d.ts +13 -0
  37. package/lib/types/host/providers/qoder/traffic-guard.d.ts.map +1 -0
  38. package/lib/types/host/providers/qoder/types.d.ts +6 -6
  39. package/lib/types/host/providers/qoder/types.d.ts.map +1 -1
  40. package/lib/types/host/runtime/codemode/rules.d.ts.map +1 -1
  41. package/lib/types/host/runtime/codemode/transport.d.ts.map +1 -1
  42. package/lib/types/index.d.ts.map +1 -1
  43. package/lib/types/shared/advisor-contracts.d.ts +9 -2
  44. package/lib/types/shared/advisor-contracts.d.ts.map +1 -1
  45. package/lib/types/shared/qoder-contracts.d.ts +30 -1
  46. package/lib/types/shared/qoder-contracts.d.ts.map +1 -1
  47. package/package.json +2 -2
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as resolveProgressUpdatesSettings, n as attachProgressSettings } from "./progress-updates-jiHnSAmz.js";
2
2
  import { h as resolvePlanModePipelineEnabled, l as attachPlanModePipelineSettings } from "./plan-mode-pipeline-DQ8TM6mP.js";
3
- import { a as ADVISOR_TOOL_TIMEOUT_MS, c as PLUGIN_MESSAGE_SOURCE_KIND, d as formatToolUpdateNotice, f as leadingSystemEndIndex, h as normalizeGenerateOptions, i as ADVISOR_STATE_PATH, l as extractSystemText, m as midConversationUpdateToUserMessage, n as installBundledPresets, o as CONSULT_ADVISOR_TOOL_NAME, p as midConversationSystemToUserMessage, r as resolvesFromHere, s as LlmError$1, u as formatMidConversationSystemReminder } from "./preset-sync-DWOAwSyl.js";
4
- import { A as isDeepSeekV41Flash, B as estimateCodexPayloadTokens, C as isOpenModelSessionPrefixCacheProtected, D as matchOpenModelScope, E as matchOpenModelProfile, F as checkpointFromMetadata, G as shouldCompactCodexPayload, H as latestCodexCompaction, I as checkpointFromOutputItems, K as withCodexCompactionTrigger, L as codexCompactionReplayMetadata, M as isDeepSeekV41FlashSession, N as readScopeRoute, O as matchOpenModelSession, P as readSessionRoute, R as codexRemoteCompactionEnabled, S as isOpenModelPrefixCacheProtected, T as isStepOpenModel, U as noteCodexRemoteCompactionFailure, V as isCompactionItem, W as projectFreshCodexCompaction, _ as isKimiOpenModel, b as isMinimaxOpenModel, d as OPEN_MODEL_PROFILES, f as bareOpenModelId, g as isKimiK31OpenModel, h as isGlm5OpenModel, j as isDeepSeekV41FlashScope, k as DEEPSEEK_OFFICIAL_PROVIDERS, l as resolveSkipProviders, m as isGlm54OpenModel, n as DEFAULT_SKIP_PROVIDERS, p as isDeepSeekV4NonV41Model, r as PRUNER_SERVICE_NAME, u as shouldSkipPruningForSession, v as isLongSparseOpenModel, w as isQwenOpenModel, x as isOpenModelCacheWarmupProtected, y as isMimoOpenModel, z as codexRemoteCompactionThreshold } from "./tool-result-pruner-ClgRVOph.js";
3
+ import { a as ADVISOR_TOOL_TIMEOUT_MS, c as PLUGIN_MESSAGE_SOURCE_KIND, d as formatToolUpdateNotice, f as leadingSystemEndIndex, h as normalizeGenerateOptions, i as ADVISOR_STATE_PATH, l as extractSystemText, m as midConversationUpdateToUserMessage, n as installBundledPresets, o as CONSULT_ADVISOR_TOOL_NAME, p as midConversationSystemToUserMessage, r as resolvesFromHere, s as LlmError$1, u as formatMidConversationSystemReminder } from "./preset-sync-RBsYhDY3.js";
4
+ import { A as isDeepSeekV41Flash, B as estimateCodexPayloadTokens, C as isOpenModelSessionPrefixCacheProtected, D as matchOpenModelScope, E as matchOpenModelProfile, F as checkpointFromMetadata, G as shouldCompactCodexPayload, H as latestCodexCompaction, I as checkpointFromOutputItems, K as withCodexCompactionTrigger, L as codexCompactionReplayMetadata, M as isDeepSeekV41FlashSession, N as readScopeRoute, O as matchOpenModelSession, P as readSessionRoute, R as codexRemoteCompactionEnabled, S as isOpenModelPrefixCacheProtected, T as isStepOpenModel, U as noteCodexRemoteCompactionFailure, V as isCompactionItem, W as projectFreshCodexCompaction, _ as isKimiOpenModel, b as isMinimaxOpenModel, d as OPEN_MODEL_PROFILES, f as bareOpenModelId, g as isKimiK31OpenModel, h as isGlm5OpenModel, j as isDeepSeekV41FlashScope, k as DEEPSEEK_OFFICIAL_PROVIDERS, l as resolveSkipProviders, m as isGlm54OpenModel, n as DEFAULT_SKIP_PROVIDERS, p as isDeepSeekV4NonV41Model, r as PRUNER_SERVICE_NAME, u as shouldSkipPruningForSession, v as isLongSparseOpenModel, w as isQwenOpenModel, x as isOpenModelCacheWarmupProtected, y as isMimoOpenModel, z as codexRemoteCompactionThreshold } from "./tool-result-pruner-DsaDg_l1.js";
5
5
  import { C as isDelegatedCaller, S as installDispatchExecutionGuard, T as resolveDispatchExecutionGuardEnabled, _ as installPlanModeExitReminder, b as registeredPlanControllerActive, h as createPlanNotice, l as PLAN_PROJECTION_KEY, n as EXIT_PLAN_MODE, w as isDelegatedSession } from "./plan-mode-cY8pp0PZ.js";
6
6
  import { createRequire } from "node:module";
7
7
  import * as LlmModule from "@deepseek-ai/dsh-llm";
@@ -891,7 +891,7 @@ const ROUTE_PREFIX$6 = "/api/dsh-chatgpt-subscription";
891
891
  * `test/responses-client.test.ts` asserts the two agree, so a release that
892
892
  * forgets this constant fails the suite instead of shipping quietly.
893
893
  */
894
- const PLUGIN_VERSION = "1.0.1";
894
+ const PLUGIN_VERSION = "1.1.1";
895
895
  const CODEX_CHATGPT_PROVIDER_ID = "codex-chatgpt";
896
896
  const CODEX_API_BASE = "https://chatgpt.com/backend-api/codex";
897
897
  const CODEX_RESPONSES_URL = `${CODEX_API_BASE}/responses`;
@@ -15165,7 +15165,7 @@ function installAdvisor(ctx, config) {
15165
15165
  enabled: value(config.advisorEnabled, false),
15166
15166
  selection: routeOf$1(config),
15167
15167
  maxTokens: value(config.advisorMaxTokens, 4096),
15168
- timeoutMs: value(config.advisorTimeoutMs, 3e5),
15168
+ timeoutMs: value(config.advisorTimeoutMs, 54e4),
15169
15169
  maxRetries: value(config.advisorMaxRetries, 1),
15170
15170
  contextTokenBudget: value(config.advisorContextTokenBudget, 1e5),
15171
15171
  sessionTokenBudget: value(config.advisorSessionTokenBudget, 2e5)
@@ -15349,7 +15349,7 @@ const FIBER_UNLOADING = 5;
15349
15349
  const RESTART_TIMEOUT_MS = 1e4;
15350
15350
  /** Gap between restart-state samples. */
15351
15351
  const RESTART_POLL_MS = 10;
15352
- function delay$1(ms) {
15352
+ function delay$2(ms) {
15353
15353
  return new Promise((resolve) => {
15354
15354
  setTimeout(resolve, ms);
15355
15355
  });
@@ -15446,7 +15446,7 @@ var SearchProviderSwitcher = class {
15446
15446
  if (sawRestart && state === FIBER_ACTIVE) return;
15447
15447
  await fiber.await();
15448
15448
  if (fiber.state === FIBER_ACTIVE) return;
15449
- await delay$1(RESTART_POLL_MS);
15449
+ await delay$2(RESTART_POLL_MS);
15450
15450
  }
15451
15451
  }
15452
15452
  findWebEntry() {
@@ -28190,17 +28190,22 @@ function renderMessages(messages, indices, images) {
28190
28190
  }
28191
28191
  return blocks;
28192
28192
  }
28193
+ /** Source kind the harness stamps on the user message a compaction leaves behind. */
28194
+ const COMPACT_CHECKPOINT_KIND = "compact-checkpoint";
28193
28195
  /**
28194
28196
  * Whether this `user` message was injected by something other than a human.
28195
28197
  *
28196
28198
  * A message without a source kind is treated as human: older harness generations
28197
28199
  * do not stamp one, and mistaking the real request for synthetic context is worse
28198
- * than the reverse.
28200
+ * than the reverse. A compaction checkpoint is the other message that must count:
28201
+ * it replaces the span that carried the task, so after an in-turn compaction it is
28202
+ * the only message left saying what the turn is about. Filtered as noise, the
28203
+ * cold replay carried no request at all and the agent answered that none was given.
28199
28204
  */
28200
28205
  function isSyntheticUserMessage$1(message) {
28201
28206
  if (message.role !== "user") return false;
28202
28207
  const kind = message.source?.kind;
28203
- return typeof kind === "string" && kind !== "user";
28208
+ return typeof kind === "string" && kind !== "user" && kind !== COMPACT_CHECKPOINT_KIND;
28204
28209
  }
28205
28210
  /** Index of the newest message a human actually wrote. */
28206
28211
  function lastHumanRequestIndex(messages) {
@@ -29217,7 +29222,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
29217
29222
  await Promise.race([
29218
29223
  turn.queue.wait(signal),
29219
29224
  turn.bridge.waitForWork(signal),
29220
- delay(200)
29225
+ delay$1(200)
29221
29226
  ]);
29222
29227
  }
29223
29228
  } finally {
@@ -29242,8 +29247,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
29242
29247
  const options = readPermissionOptions(params);
29243
29248
  const answer = () => options.find((option) => option.kind === "allow_once")?.optionId ?? options.find((option) => option.kind === "allow_always")?.optionId;
29244
29249
  const deny = () => options.find((option) => option.kind === "reject_once")?.optionId ?? options.find((option) => option.kind === "reject_always")?.optionId;
29245
- const toolCall = asRecord$19(params.toolCall);
29246
- if ((typeof toolCall?.name === "string" ? toolCall.name : "").startsWith(`mcp_dsh-bridge_`)) return answer();
29250
+ if (isBridgeToolCall(asRecord$19(params.toolCall))) return answer();
29247
29251
  const settings = await this.options.settings.read();
29248
29252
  if (settings.nativeToolPolicy === "cancel") return deny();
29249
29253
  return settings.permissionPolicy === "allow" ? answer() : deny();
@@ -29787,9 +29791,39 @@ function assertNoSamplingControls(options) {
29787
29791
  * @param update - One `session/update` payload.
29788
29792
  * @returns The call's id and name when it is a native call; undefined for the bridge.
29789
29793
  */
29794
+ /**
29795
+ * 1.5.20 起权限请求不再带 `name`;桥身份可能落在 `title`、`_meta` 或
29796
+ * `rawInput.ServerName`。任何一处命中 `dsh-bridge` 都按桥处理;空名字也按桥处理,
29797
+ * 因为把它倒向 nativeToolPolicy 会再次触发 #153。
29798
+ */
29799
+ function mentionsBridge(value) {
29800
+ if (typeof value === "string") return /dsh[-_]bridge/i.test(value);
29801
+ if (Array.isArray(value)) return value.some(mentionsBridge);
29802
+ if (typeof value !== "object" || value === null) return false;
29803
+ return Object.values(value).some(mentionsBridge);
29804
+ }
29805
+ function rawInputNamesBridgeServer(value) {
29806
+ if (Array.isArray(value)) return value.some(rawInputNamesBridgeServer);
29807
+ if (typeof value !== "object" || value === null) return false;
29808
+ const record = value;
29809
+ for (const key of [
29810
+ "ServerName",
29811
+ "serverName",
29812
+ "server_name",
29813
+ "mcpServerName",
29814
+ "mcp_server_name"
29815
+ ]) if (mentionsBridge(record[key])) return true;
29816
+ return Object.values(record).some(rawInputNamesBridgeServer);
29817
+ }
29818
+ function isBridgeToolCall(record) {
29819
+ if (record === void 0) return false;
29820
+ const name = typeof record.name === "string" ? record.name : "";
29821
+ if (name.startsWith(`mcp_dsh-bridge_`) || name === "call_mcp_tool" || name === "") return true;
29822
+ return mentionsBridge(record.title) || mentionsBridge(record._meta) || rawInputNamesBridgeServer(record.rawInput);
29823
+ }
29790
29824
  function readNativeToolCall(update) {
29825
+ if (isBridgeToolCall(update)) return void 0;
29791
29826
  const name = typeof update.name === "string" ? update.name : "";
29792
- if (name === "" || name.startsWith(`mcp_dsh-bridge_`)) return void 0;
29793
29827
  return {
29794
29828
  callId: typeof update.toolCallId === "string" ? update.toolCallId : "",
29795
29829
  name
@@ -29991,7 +30025,7 @@ function abortError$1() {
29991
30025
  error.name = "AbortError";
29992
30026
  return error;
29993
30027
  }
29994
- function delay(ms) {
30028
+ function delay$1(ms) {
29995
30029
  return new Promise((resolve) => {
29996
30030
  setTimeout(resolve, ms).unref?.();
29997
30031
  });
@@ -103771,13 +103805,14 @@ const QODER_AUTH_FILE = "user";
103771
103805
  /** qodercli 的 machine id 文件(36 字符 UUID;同时也是 adopt 文件的解密钥源)。 */
103772
103806
  const QODER_MACHINE_ID_FILE = "machine_id";
103773
103807
  /**
103774
- * 输出上限兜底:131072。
103808
+ * 输出上限兜底:32768。
103775
103809
  *
103776
- * 目录不报输出上限;逐字 pi-provider `catalog.ts` 的 `MAX_OUTPUT_TOKENS`(依据:
103777
- * Aliyun Model Studio——Qoder CN 目录背后的上游——文档对 qwen3.8/3.7 全系给出
103778
- * Max Output Length = 131072;qodercli 自带的 32K 默认过于保守)。
103810
+ * 目录不报输出上限,而上游的参数校验明确要求 `max_tokens ∈ [1, 32768]`:
103811
+ * 实机把 65536 / 131072 发给 Step-5 会直接得到 400
103812
+ * `Range of max_tokens should be [1, 32768]`。Liki4/qodercli2api 与 qoder2api
103813
+ * 的桥接层也都把上限压在 32768;发得更大不会换来更长输出,只会在模型之前被拒。
103779
103814
  */
103780
- const QODER_MAX_OUTPUT_TOKENS = 131072;
103815
+ const QODER_MAX_OUTPUT_TOKENS = 32768;
103781
103816
  /**
103782
103817
  * 上下文窗口兜底(目录缺 `context_config` 时)。
103783
103818
  *
@@ -103907,6 +103942,20 @@ function isRecord$44(value) {
103907
103942
  function nonEmptyString$2(value) {
103908
103943
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
103909
103944
  }
103945
+ function nonNegativeNumber(value) {
103946
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
103947
+ }
103948
+ function promotionOf(value) {
103949
+ if (!isRecord$44(value)) return void 0;
103950
+ const promotion = {
103951
+ ...value.active === true ? { active: true } : {},
103952
+ ...nonNegativeNumber(value.discount_factor) === void 0 ? {} : { discountFactor: nonNegativeNumber(value.discount_factor) },
103953
+ ...nonNegativeNumber(value.before_promotion_price_factor) === void 0 ? {} : { beforePromotionPriceFactor: nonNegativeNumber(value.before_promotion_price_factor) },
103954
+ ...nonEmptyString$2(value.window_start) === void 0 ? {} : { windowStart: nonEmptyString$2(value.window_start) },
103955
+ ...nonEmptyString$2(value.window_end) === void 0 ? {} : { windowEnd: nonEmptyString$2(value.window_end) }
103956
+ };
103957
+ return Object.keys(promotion).length === 0 ? void 0 : promotion;
103958
+ }
103910
103959
  /**
103911
103960
  * 上游 `display_name` → 公开模型 id:去掉全部空白字符
103912
103961
  * (逐字 pi-provider `toQoderModelId`:`replace(/\s+/g, "")`)。
@@ -104086,7 +104135,11 @@ function entryFromQoderRecord(record, region) {
104086
104135
  supportsImages: record.is_vl === true,
104087
104136
  defaultContextWindow: contextWindowFromRecord(record, region),
104088
104137
  defaultMaxTokens: QODER_MAX_OUTPUT_TOKENS,
104089
- description: nonEmptyString$2(record.description) ?? null
104138
+ description: nonEmptyString$2(record.description) ?? null,
104139
+ ...nonNegativeNumber(record.price_factor) === void 0 ? {} : { priceFactor: nonNegativeNumber(record.price_factor) },
104140
+ ...nonNegativeNumber(record.original_price_factor) === void 0 ? {} : { originalPriceFactor: nonNegativeNumber(record.original_price_factor) },
104141
+ ...nonNegativeNumber(record.before_promotion_price_factor) === void 0 ? {} : { originalPriceFactor: nonNegativeNumber(record.before_promotion_price_factor) },
104142
+ ...promotionOf(record.promotion) === void 0 ? {} : { promotion: promotionOf(record.promotion) }
104090
104143
  });
104091
104144
  }
104092
104145
  /**
@@ -104432,12 +104485,16 @@ function describeQoderModel(entry, prefix) {
104432
104485
  const thinking = entry.reasoningEfforts.length === 0 ? entry.thinkingDisableable ? "思考可开关" : "思考恒开" : entry.thinkingDisableable ? "思考可关闭" : "思考恒开";
104433
104486
  const effort = entry.reasoningEfforts.length === 0 ? "无档位字段" : "档位 " + entry.reasoningEfforts.join("/");
104434
104487
  const modality = entry.supportsImages ? "输入 text + image" : "输入仅 text";
104488
+ const price = entry.priceFactor === void 0 ? void 0 : entry.priceFactor === 0 ? "免费" : "倍率 ×" + entry.priceFactor;
104489
+ const promotion = entry.promotion?.discountFactor === void 0 ? void 0 : "错峰 " + Math.round(entry.promotion.discountFactor * 10) + " 折" + (entry.promotion.windowStart === void 0 || entry.promotion.windowEnd === void 0 ? "" : "(" + entry.promotion.windowStart + "–" + entry.promotion.windowEnd + ")");
104435
104490
  return (prefix === void 0 || prefix === "" ? "" : prefix + ":") + [
104436
104491
  thinking,
104437
104492
  effort,
104438
104493
  modality,
104439
- "上下文 " + entry.defaultContextWindow
104440
- ].join("|");
104494
+ "上下文 " + entry.defaultContextWindow,
104495
+ price,
104496
+ promotion
104497
+ ].filter((part) => part !== void 0).join("|");
104441
104498
  }
104442
104499
  function positiveInt(value) {
104443
104500
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
@@ -104895,12 +104952,12 @@ function markQoderLegacyProbeDone() {
104895
104952
  * - {@link generateQoderRuntimeAuthFields} —— runtime-fields.json;
104896
104953
  * - {@link decryptQoderAdoptPayload} —— credential.json;
104897
104954
  * - {@link encodeQoderBody} —— infer-user-no-org.json 的 `body_string`;
104898
- * - {@link buildQoderCosyHeaders} —— infer-user-no-org.json 的 18 头集合与签名。
104955
+ * - {@link buildQoderCosyHeaders} —— 最终发送头集合与签名。
104899
104956
  *
104900
- * 与 pi-provider-qoder `src/cosy.ts` 的分歧(它多发 `Cosy-Machineos` /
104901
- * `Cosy-Clientip` / `Cosy-Bodyhash` / `Cosy-Bodylength` / `Cosy-Sigpath` /
104902
- * `X-Request-Id` 六个头)以 **fixture 为准**:那是官方 pinned WASM 的头集合,
104903
- * pi 的超集只是「被服务端容忍」,不是协议的一部分(计划 §9 风险 3)。
104957
+ * 官方 1.1.74 的**最终发送层**会在无真实 UMID 时移除 `Cosy-MachineToken` /
104958
+ * `Cosy-MachineType`(不能用 machine_id 冒充 machine token),再补
104959
+ * `Cosy-MachineOS`;这一层不在 pinned WASM 的 18/22-header 核心向量里,
104960
+ * 所以 fixture 只能锁核心,不能锁最终网络头。
104904
104961
  *
104905
104962
  * 本文件不做任何网络 I/O,也不持有凭据:它吃的是调用方递进来的材料,吐出的是
104906
104963
  * 头与 body。machine id 的读取顺序(qodercli 原配 → 本线路自己的文件 → 内存生成)
@@ -105052,6 +105109,15 @@ function cosySignedPath(url) {
105052
105109
  * payload 的字段顺序固定(`version, requestId, info, cosyVersion, ideVersion`——
105053
105110
  * 它参与签名,散装键序就是一次签名漂移),所以这里按字面量顺序写键而不是用 Map。
105054
105111
  */
105112
+ /**
105113
+ * 官方最终发送层的 `Cosy-MachineOS`:`{arch}_{platform}`。
105114
+ *
105115
+ * Linux x64 的 `x86_64_linux` 已由 qodercli2api 对照 1.1.74 样本核实;
105116
+ * 其余平台按同一规则生成。
105117
+ */
105118
+ function qoderMachineOS(platform = process.platform, arch = process.arch) {
105119
+ return (arch === "x64" ? "x86_64" : arch === "arm64" ? "aarch64" : arch === "ia32" ? "x86" : arch) + "_" + platform;
105120
+ }
105055
105121
  function buildQoderCosyHeaders(identity, options) {
105056
105122
  if (identity.uid.trim() === "") throw new Error("Qoder COSY:uid 不能为空");
105057
105123
  const runtime = generateQoderRuntimeAuthFields(identity.rawUserInfo, options.entropy ?? defaultEntropy);
@@ -105078,8 +105144,7 @@ function buildQoderCosyHeaders(identity, options) {
105078
105144
  "Cosy-Date": unixSeconds,
105079
105145
  "Cosy-Key": runtime.key,
105080
105146
  "Cosy-MachineId": identity.machineId,
105081
- "Cosy-MachineToken": identity.machineId,
105082
- "Cosy-MachineType": "5",
105147
+ "Cosy-MachineOS": qoderMachineOS(),
105083
105148
  "Cosy-Scene": COSY_SCENE.scene,
105084
105149
  "Cosy-User": identity.uid,
105085
105150
  "Cosy-Version": identity.cosyVersion,
@@ -106152,6 +106217,32 @@ function resolveQoderThinking(requested, request) {
106152
106217
  };
106153
106218
  }
106154
106219
  /**
106220
+ * 中和 Qoder 上游的品牌身份句检测。
106221
+ *
106222
+ * 受控 A/B(shuishuipingan/qoder2api-hub docs/risk-control-and-queueing.md §7)确认:
106223
+ * `You are <Brand>,` 与 `powered by <Brand>.` 会被上游判成第三方客户端,返回
106224
+ * `10605 / queueType:p1 / queueCount:0 / serviceAvailable:false`;这是硬拒绝伪装成
106225
+ * 排队,等待不会放行。DSH 的系统提示首句正好是
106226
+ * `You are an AI agent powered by DeepSeek Harness.`。
106227
+ *
106228
+ * 只做字符级最小中和:在紧跟品牌名的逗号/句号前插一个空格,品牌、语序与语义全部保留;
106229
+ * 自家品牌 Qoder 豁免,避免扰动普通请求的前缀缓存。函数是幂等的。
106230
+ */
106231
+ function neutralizeQoderIdentityPhrases(text) {
106232
+ return text.replace(/* @__PURE__ */ new RegExp("\\bYou are ([A-Z][A-Za-z0-9]*(?:[ -][A-Z0-9][A-Za-z0-9]*)*),", "g"), (match, name) => name === "Qoder" ? match : "You are " + name + " ,").replace(/* @__PURE__ */ new RegExp("\\bpowered by ([A-Z][A-Za-z0-9]*(?:[ -][A-Z0-9][A-Za-z0-9]*)*)\\.", "g"), (match, name) => name === "Qoder" ? match : "powered by " + name + " .");
106233
+ }
106234
+ /** 对一条 wire 消息里的所有文本字段做身份句中转(内容、reasoning、内容块 text)。 */
106235
+ function guardQoderWireMessage(message) {
106236
+ const next = { ...message };
106237
+ if (typeof next.content === "string") next.content = neutralizeQoderIdentityPhrases(next.content);
106238
+ else if (Array.isArray(next.content)) next.content = next.content.map((part) => isRecord$41(part) && typeof part.text === "string" ? {
106239
+ ...part,
106240
+ text: neutralizeQoderIdentityPhrases(part.text)
106241
+ } : part);
106242
+ for (const key of ["reasoning_content", "reasoning"]) if (typeof next[key] === "string") next[key] = neutralizeQoderIdentityPhrases(next[key]);
106243
+ return next;
106244
+ }
106245
+ /**
106155
106246
  * 会话与请求的稳定 id(缓存亲和)。
106156
106247
  *
106157
106248
  * 逐字 pi-provider \`stream.ts\` 的设计:\`session_id\` 的稳定段来自账号+模型的哈希,
@@ -106240,7 +106331,8 @@ function buildQoderChatRequest(options, images, request, context) {
106240
106331
  }
106241
106332
  const entry = context.entry;
106242
106333
  const modelKey = context.modelKey;
106243
- const maxTokens = options.maxTokens ?? request.defaultMaxTokens ?? entry?.defaultMaxTokens ?? 131072;
106334
+ const outputLimit = Math.min(request.defaultMaxTokens ?? entry?.defaultMaxTokens ?? 32768, QODER_MAX_OUTPUT_TOKENS);
106335
+ const maxTokens = Math.max(1, Math.min(options.maxTokens ?? outputLimit, outputLimit));
106244
106336
  const tools = options.tools && options.tools.length > 0 ? options.tools.map((tool) => ({
106245
106337
  type: "function",
106246
106338
  function: {
@@ -106249,6 +106341,7 @@ function buildQoderChatRequest(options, images, request, context) {
106249
106341
  parameters: stripMetaSchema$1(tool.parameters)
106250
106342
  }
106251
106343
  })) : [];
106344
+ for (let index = 0; index < messages.length; index++) messages[index] = guardQoderWireMessage(messages[index]);
106252
106345
  const recordId = qoderChatRecordId(modelKey, messages, tools.length > 0 ? tools : void 0, maxTokens);
106253
106346
  const thinking = resolveQoderThinking(options.reasoningEffort, request);
106254
106347
  const parameters = { max_tokens: maxTokens };
@@ -106299,7 +106392,7 @@ function buildQoderChatRequest(options, images, request, context) {
106299
106392
  session_type: "qodercli",
106300
106393
  source: 1,
106301
106394
  stream: true,
106302
- system: system ?? "",
106395
+ system: "",
106303
106396
  task_id: "common",
106304
106397
  tools,
106305
106398
  version: "3"
@@ -106377,6 +106470,10 @@ function closeCurrent$2(state) {
106377
106470
  function closeToolCalls$1(state) {
106378
106471
  const out = [];
106379
106472
  for (const [wireIndex, call] of [...state.toolCalls.entries()].sort((a, b) => a[0] - b[0])) {
106473
+ if (!call.started || call.name === "") {
106474
+ state.toolCalls.delete(wireIndex);
106475
+ continue;
106476
+ }
106380
106477
  const block = {
106381
106478
  type: "tool-call",
106382
106479
  id: toToolCallId(call.id),
@@ -106467,18 +106564,20 @@ function applyToolDelta$1(entry, state) {
106467
106564
  let call = state.toolCalls.get(wireIndex);
106468
106565
  const incomingId = asString$12(entry.id);
106469
106566
  if (call !== void 0 && incomingId !== void 0 && call.id !== "call_" + wireIndex && incomingId !== call.id) {
106470
- const closedBlock = {
106471
- type: "tool-call",
106472
- id: toToolCallId(call.id),
106473
- name: call.name,
106474
- arguments: call.arguments === "" ? "{}" : call.arguments
106475
- };
106476
- state.blocks[call.blockIndex] = closedBlock;
106477
- out.push({
106478
- type: "block-end",
106479
- index: call.blockIndex,
106480
- block: closedBlock
106481
- });
106567
+ if (call.started && call.name !== "") {
106568
+ const closedBlock = {
106569
+ type: "tool-call",
106570
+ id: toToolCallId(call.id),
106571
+ name: call.name,
106572
+ arguments: call.arguments === "" ? "{}" : call.arguments
106573
+ };
106574
+ state.blocks[call.blockIndex] = closedBlock;
106575
+ out.push({
106576
+ type: "block-end",
106577
+ index: call.blockIndex,
106578
+ block: closedBlock
106579
+ });
106580
+ }
106482
106581
  state.toolCalls.delete(wireIndex);
106483
106582
  call = void 0;
106484
106583
  }
@@ -106497,14 +106596,29 @@ function applyToolDelta$1(entry, state) {
106497
106596
  const argsDelta = asString$12(fn?.arguments) ?? "";
106498
106597
  if (argsDelta !== "") call.arguments += argsDelta;
106499
106598
  if (!call.started) {
106599
+ if (call.name === "") return out;
106500
106600
  call.started = true;
106501
106601
  state.hasToolCall = true;
106502
106602
  state.hasContent = true;
106603
+ state.blocks[call.blockIndex] = {
106604
+ type: "tool-call",
106605
+ id: toToolCallId(call.id),
106606
+ name: call.name,
106607
+ arguments: call.arguments === "" ? "{}" : call.arguments
106608
+ };
106503
106609
  out.push({
106504
106610
  type: "block-start",
106505
106611
  index: call.blockIndex,
106506
106612
  blockType: "tool-call"
106507
106613
  });
106614
+ out.push({
106615
+ type: "tool-call-delta",
106616
+ index: call.blockIndex,
106617
+ id: toToolCallId(call.id),
106618
+ name: call.name,
106619
+ argumentsDelta: call.arguments
106620
+ });
106621
+ return out;
106508
106622
  }
106509
106623
  if (argsDelta !== "" || out.length > 0) out.push({
106510
106624
  type: "tool-call-delta",
@@ -106821,6 +106935,17 @@ function collectQoderFailureFacts(node, facts, depth, budget) {
106821
106935
  collectQoderFailureFacts(value, facts, depth + 1, budget);
106822
106936
  }
106823
106937
  }
106938
+ /**
106939
+ * 文本里是否明确指出了「当前模型暂时不可用」。
106940
+ *
106941
+ * 上游还有一类未带 `RESOURCE_LIMIT` 结构字段的 403:文案只说模型暂时不可用、
106942
+ * 请稍后重试。它是容量 / 模型可用性问题,不是凭据被拒——归 AUTH 会让有额度的
106943
+ * 账号被提示重新登录,也失去切换到同线路其它模型的机会。
106944
+ *
106945
+ * 只认带 model / service / upstream 或「模型 / 服务 / 上游」限定的措辞,
106946
+ * 不拿一句泛泛的 `try again later` 改写普通 403(登录失效的文案也可能这么说)。
106947
+ */
106948
+ const QODER_MODEL_UNAVAILABLE_WORDING = /\bmodel\b[^"\\\n]{0,48}\b(?:temporarily\s+)?(?:unavailable|not\s+available|busy)\b|\b(?:service|upstream)\b[^"\\\n]{0,32}\b(?:temporarily\s+)?unavailable\b|(?:模型|服务|上游)[^"\\\n]{0,24}(?:暂不可用|暂时不可用|不可用|繁忙|暂忙)/i;
106824
106949
  /** 文本里是否明确指出了排队 / 资源不足(不含笼统的 rate limit,免得改写普通 429)。 */
106825
106950
  function hasQoderQueueWording(text) {
106826
106951
  return /RESO?URCE_LIMIT|REOSURCE_LIMIT|\b10605\b|queueCount|queue_count|isQueued|is_queued|正在排队|排队等待|模型排队|queue(?:d|ing)\b/i.test(text);
@@ -106840,9 +106965,16 @@ function isQoderResourceLimited(facts, status, detail = "") {
106840
106965
  if (facts.codes.includes("10605")) return true;
106841
106966
  const combinedText = [detail, ...facts.messages ?? []].join(" ");
106842
106967
  if (/RESO?URCE_LIMIT|REOSURCE_LIMIT|\b10605\b/i.test(combinedText)) return true;
106968
+ if (isQoderModelUnavailable(facts, status, detail)) return true;
106843
106969
  if (status !== void 0 && status !== 403) return false;
106844
106970
  return facts.serviceAvailable === false || facts.isQueued === true || facts.queueCount !== void 0 && facts.queueCount > 0 || hasQoderQueueWording(combinedText);
106845
106971
  }
106972
+ /** 上游是否明确报告「当前模型暂时不可用」(403 且带模型级措辞)。 */
106973
+ function isQoderModelUnavailable(facts, status, detail = "") {
106974
+ if (status !== 403) return false;
106975
+ const combinedText = [detail, ...facts.messages ?? []].join(" ");
106976
+ return QODER_MODEL_UNAVAILABLE_WORDING.test(combinedText);
106977
+ }
106846
106978
  const QODER_QUEUE_FAILURE_MARKER = /* @__PURE__ */ new WeakSet();
106847
106979
  /**
106848
106980
  * 排队失败里上游报的结构化容量事实(queueCount / retryAfterSeconds / serviceAvailable)。
@@ -106913,6 +107045,14 @@ function qoderResourceLimitMessage(facts, status) {
106913
107045
  if (facts.modelKey !== void 0) details.push("modelKey " + facts.modelKey);
106914
107046
  return "Qoder(订阅) 上游资源不足,这个模型正在排队" + (details.length === 0 ? "" : ":" + details.join(",")) + "。这是上游容量问题,不是凭据问题——账号仍是登录状态,不需要重新登录;稍后重试即可。";
106915
107047
  }
107048
+ /** 上游模型级暂时不可用的文案:说清与额度 / 凭据无关,并说明会自动换模型。 */
107049
+ function qoderModelUnavailableMessage(facts, status) {
107050
+ const details = [];
107051
+ const codes = [...facts.subCodes, ...facts.codes].filter((code) => code !== "" && code !== String(status));
107052
+ if (codes.length > 0) details.push("code " + codes.join(" / "));
107053
+ if (facts.modelKey !== void 0) details.push("modelKey " + facts.modelKey);
107054
+ return "Qoder(订阅) 当前模型暂时不可用" + (details.length === 0 ? "" : ":" + details.join(",")) + "。这不是账号或额度问题,不需要重新登录;本线路会先切换到其它已启用模型,稍后也可以重试。";
107055
+ }
106916
107056
  /** 上游额度用尽的文案:额度恢复前这一请求不会成功,并给出上游给的购买/升级页。 */
106917
107057
  function qoderQuotaExhaustedMessage(facts, status) {
106918
107058
  const details = [];
@@ -106963,6 +107103,16 @@ function classifyQoderFailureFacts(status, detail, facts) {
106963
107103
  const options = status === void 0 ? {} : { status };
106964
107104
  if (status === 401 || facts.codes.includes("105")) return new LlmError$1("Qoder(订阅) rejected the credential (" + (status ?? "no status") + (code === void 0 ? "" : ", code " + code) + "). Sign the account in again." + suffix, "AUTH", options);
106965
107105
  if (isQoderQuotaExhausted(facts, status)) return new LlmError$1(qoderQuotaExhaustedMessage(facts, status) + suffix, "QUOTA", options);
107106
+ if (isQoderModelUnavailable(facts, status, detail)) {
107107
+ const after = facts.retryAfterSeconds;
107108
+ const err = new LlmError$1(qoderModelUnavailableMessage(facts, status) + suffix, "SERVER", after === void 0 || after <= 0 ? options : {
107109
+ ...options,
107110
+ providerRetryAfterMs: after * 1e3
107111
+ });
107112
+ QODER_QUEUE_FAILURE_MARKER.add(err);
107113
+ QODER_QUEUE_FACTS.set(err, facts);
107114
+ return err;
107115
+ }
106966
107116
  if (isQoderResourceLimited(facts, status, detail)) {
106967
107117
  const after = facts.retryAfterSeconds;
106968
107118
  const err = new LlmError$1(qoderResourceLimitMessage(facts, status) + suffix, "SERVER", after === void 0 || after <= 0 ? options : {
@@ -107009,9 +107159,76 @@ function currentQoderQueuePosition(now = Date.now()) {
107009
107159
  return lastObserved;
107010
107160
  }
107011
107161
  /** 请求真的拿到内容时清掉:队列已经过去,胶囊不该继续显示旧位置。 */
107162
+ /**
107163
+ * `queueCount=0` + `serviceAvailable=false`:没有位置可显示,但上游确实在排队。
107164
+ * 不能复用 {@link recordQoderQueuePosition} 的「0 不是位置」规则,否则界面一直空白。
107165
+ */
107166
+ function recordQoderQueueWait(hint, now = Date.now()) {
107167
+ if (hint === void 0 || hint.isQueued !== true) return void 0;
107168
+ const snapshot = {
107169
+ position: 0,
107170
+ waiting: true,
107171
+ observedAt: now,
107172
+ ...hint.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: hint.retryAfterSeconds }
107173
+ };
107174
+ lastObserved = snapshot;
107175
+ return snapshot;
107176
+ }
107012
107177
  function clearQoderQueuePosition() {
107013
107178
  lastObserved = void 0;
107014
107179
  }
107180
+ const lastAccountBySession = /* @__PURE__ */ new Map();
107181
+ /** 给当前会话的账号偏好;没有记录或会话 id 为空时返回 undefined。 */
107182
+ function qoderAffinityHint(sessionId) {
107183
+ if (sessionId === void 0 || sessionId.trim() === "") return void 0;
107184
+ const accountId = lastAccountBySession.get(sessionId);
107185
+ return accountId === void 0 ? void 0 : { preferAccountIds: [accountId] };
107186
+ }
107187
+ /** 记录这一轮实际选中的账号;accountId 为空时不动。 */
107188
+ function rememberQoderAffinity(sessionId, accountId) {
107189
+ if (sessionId === void 0 || sessionId.trim() === "" || accountId === null) return;
107190
+ lastAccountBySession.delete(sessionId);
107191
+ lastAccountBySession.set(sessionId, accountId);
107192
+ while (lastAccountBySession.size > 128) {
107193
+ const oldest = lastAccountBySession.keys().next().value;
107194
+ if (oldest === void 0) break;
107195
+ lastAccountBySession.delete(oldest);
107196
+ }
107197
+ }
107198
+ //#endregion
107199
+ //#region src/host/providers/qoder/cache-diagnostics.ts
107200
+ /** 逐请求缓存观察的进程内环形缓冲;只保留最近若干条,重启清空。 */
107201
+ const MAX_OBSERVATIONS = 24;
107202
+ const observations = [];
107203
+ function shortHash(value) {
107204
+ if (typeof value !== "string" || value === "") return "-";
107205
+ return createHash("sha256").update(value).digest("hex").slice(0, 8);
107206
+ }
107207
+ function toolNames(tools) {
107208
+ if (!Array.isArray(tools)) return "";
107209
+ return tools.map((tool) => typeof tool === "object" && tool !== null ? tool.name : void 0).filter((name) => typeof name === "string").join(",");
107210
+ }
107211
+ /** 记录一条带用量的请求;没有用量帧的请求不调用。 */
107212
+ function recordQoderCacheObservation(input) {
107213
+ observations.push({
107214
+ at: Date.now(),
107215
+ model: input.model,
107216
+ account: shortHash(input.accountId ?? input.uid),
107217
+ session: shortHash(input.sessionId),
107218
+ system: shortHash(input.system),
107219
+ tools: shortHash(toolNames(input.tools)),
107220
+ messages: input.messages,
107221
+ bodyChars: input.bodyChars,
107222
+ inputTokens: input.inputTokens + input.cacheReadTokens + input.cacheWriteTokens,
107223
+ cacheReadTokens: input.cacheReadTokens,
107224
+ cacheWriteTokens: input.cacheWriteTokens
107225
+ });
107226
+ while (observations.length > MAX_OBSERVATIONS) observations.shift();
107227
+ }
107228
+ /** 最近请求的快照(副本),最新在后。 */
107229
+ function readQoderCacheObservations() {
107230
+ return observations.map((item) => ({ ...item }));
107231
+ }
107015
107232
  //#endregion
107016
107233
  //#region src/host/providers/qoder/adapter.ts
107017
107234
  /**
@@ -107158,7 +107375,8 @@ function readQoderCacheStats() {
107158
107375
  missedInputTokens: Math.max(0, cacheTotals.promptTokens - cacheTotals.cacheReadTokens - cacheTotals.cacheWriteTokens),
107159
107376
  cacheWriteTokens: cacheTotals.cacheWriteTokens,
107160
107377
  requests: cacheTotals.requests,
107161
- replay: { ...replayTotals }
107378
+ replay: { ...replayTotals },
107379
+ recent: readQoderCacheObservations()
107162
107380
  };
107163
107381
  }
107164
107382
  /**
@@ -107181,16 +107399,28 @@ const QODER_QUEUE_WAIT_CAP_MS = 45e3;
107181
107399
  * 更长的等待应当由用户自己决定要不要重试,而不是让一个回合挂在那里)。
107182
107400
  */
107183
107401
  const QODER_QUEUE_WAIT_TOTAL_CAP_MS = 9e4;
107402
+ /** 环境开关:fast = 不等待,立即把排队错误交给宿主;wait = 按预算等待。 */
107403
+ function qoderQueueMode() {
107404
+ return process.env.DSH_QODER_QUEUE_MODE === "fast" ? "fast" : "wait";
107405
+ }
107406
+ /** 服务级排队预算(默认 90 秒;环境可调到 10 分钟,PTC/宿主的上限之外不无限延长)。 */
107407
+ function qoderQueueBudgetMs() {
107408
+ const raw = Number(process.env.DSH_QODER_QUEUE_BUDGET_MS);
107409
+ if (!Number.isFinite(raw) || raw <= 0) return QODER_QUEUE_WAIT_TOTAL_CAP_MS;
107410
+ return Math.min(6e5, Math.max(3e4, Math.floor(raw)));
107411
+ }
107184
107412
  /**
107185
107413
  * 这一次该等多久;返回 0 表示不再等。
107186
107414
  *
107187
107415
  * 只认上游自己给的秒数:没有建议值就不发明等待(宁可沿用既有轮询/失败路径)。
107188
107416
  */
107189
107417
  function qoderQueueWaitMs(hint, waitsSoFar, waitedSoFar) {
107190
- if (waitsSoFar >= (hint?.serviceAvailable === false && (hint.queueCount ?? 0) === 0 ? 1 : 3)) return 0;
107418
+ const serviceUnavailable = hint?.serviceAvailable === false && (hint.queueCount ?? 0) === 0;
107419
+ const totalCap = serviceUnavailable ? qoderQueueBudgetMs() : QODER_QUEUE_WAIT_TOTAL_CAP_MS;
107420
+ if (waitsSoFar >= (serviceUnavailable ? Math.max(1, Math.ceil(totalCap / 3e4)) : 3)) return 0;
107191
107421
  const seconds = hint?.retryAfterSeconds;
107192
107422
  if (seconds === void 0 || !(seconds > 0)) return 0;
107193
- const remaining = QODER_QUEUE_WAIT_TOTAL_CAP_MS - waitedSoFar;
107423
+ const remaining = totalCap - waitedSoFar;
107194
107424
  if (remaining <= 0) return 0;
107195
107425
  return Math.min(seconds * 1e3, QODER_QUEUE_WAIT_CAP_MS, remaining);
107196
107426
  }
@@ -107270,10 +107500,25 @@ var QoderAdapter = class extends LlmAdapter {
107270
107500
  *
107271
107501
  * 有池时轮转(核心自己做刷新);没有池时读单凭据存储(无头 host 与测试的形态)。
107272
107502
  */
107273
- async credentialFor(excludeIds) {
107503
+ cacheAffinityEnabled() {
107504
+ return this.options.cacheAffinity?.() !== false;
107505
+ }
107506
+ /** 当前目录里这个公开模型 id 只存在于哪些区域;两区都有时返回两个。 */
107507
+ modelRegions(model) {
107508
+ const regions = [];
107509
+ for (const region of ["global", "cn"]) if (this.catalog(region).some((entry) => entry.id === model)) regions.push(region);
107510
+ return regions;
107511
+ }
107512
+ async credentialFor(excludeIds, sessionId, model) {
107274
107513
  const fetchFn = this.options.fetchFn ?? fetch;
107275
107514
  if (this.accountPool !== null) {
107276
- const effective = await this.accountPool.getEffectiveCredential(excludeIds, fetchFn);
107515
+ const affinity = this.cacheAffinityEnabled() ? qoderAffinityHint(sessionId) : void 0;
107516
+ const modelRegions = model === void 0 ? [] : this.modelRegions(model);
107517
+ const regionIds = modelRegions.length === 1 ? await this.accountPool.accountIdsInRegions(modelRegions) : [];
107518
+ const preferred = [.../* @__PURE__ */ new Set([...regionIds, ...affinity?.preferAccountIds ?? []])];
107519
+ const selection = preferred.length === 0 ? void 0 : { preferAccountIds: preferred };
107520
+ const effective = await this.accountPool.getEffectiveCredential(excludeIds, fetchFn, selection);
107521
+ rememberQoderAffinity(sessionId, effective.account.id);
107277
107522
  return {
107278
107523
  accountId: effective.account.id,
107279
107524
  credentials: upstreamCredentialOf$1(effective.credentials)
@@ -107384,15 +107629,17 @@ var QoderAdapter = class extends LlmAdapter {
107384
107629
  const triedAccounts = /* @__PURE__ */ new Set();
107385
107630
  const triedModels = /* @__PURE__ */ new Set([options.model]);
107386
107631
  let currentModel = options.model;
107387
- let picked = await this.credentialFor(triedAccounts);
107632
+ let picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
107388
107633
  let queueWaits = 0;
107389
107634
  let queueWaitedMs = 0;
107390
107635
  const queueSleep = this.options.queueSleep ?? sleepAbortable;
107391
107636
  const handlePreContentFailure = async (failure, responseHeaders) => {
107392
107637
  if (isQoderQueueFailure(failure)) {
107393
107638
  const hint = qoderQueueHintOf(failure);
107394
- recordQoderQueuePosition(hint);
107395
- if (!(hint !== void 0 && hint.serviceAvailable === false && (hint.queueCount ?? 0) === 0)) {
107639
+ if (recordQoderQueuePosition(hint) === void 0) recordQoderQueueWait(hint);
107640
+ const serviceOutage = hint !== void 0 && hint.serviceAvailable === false && (hint.queueCount ?? 0) === 0;
107641
+ if (qoderQueueMode() === "fast") throw failure;
107642
+ if (!serviceOutage) {
107396
107643
  const nextModel = this.nextQueuedFallbackModel(currentModel, triedModels, picked.credentials.region, settings);
107397
107644
  if (nextModel !== void 0) {
107398
107645
  triedModels.add(nextModel);
@@ -107401,15 +107648,17 @@ var QoderAdapter = class extends LlmAdapter {
107401
107648
  }
107402
107649
  if (picked.accountId !== null && this.accountPool !== null) {
107403
107650
  if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
107404
- picked = await this.credentialFor(triedAccounts);
107651
+ picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
107405
107652
  return true;
107406
107653
  }
107407
107654
  }
107408
107655
  }
107409
107656
  const waitMs = qoderQueueWaitMs(hint, queueWaits, queueWaitedMs);
107410
107657
  if (waitMs > 0) {
107658
+ activity?.pulse();
107411
107659
  await queueSleep(waitMs, signal);
107412
107660
  if (signal.aborted) throw new LlmError$1(t("qo.requestAborted", { provider: PROVIDER_NAME$7 }), "ABORTED");
107661
+ activity?.pulse();
107413
107662
  queueWaits += 1;
107414
107663
  queueWaitedMs += waitMs;
107415
107664
  return true;
@@ -107423,13 +107672,13 @@ var QoderAdapter = class extends LlmAdapter {
107423
107672
  const reason = failure.code === "QUOTA" ? "Qoder(订阅):当前账号额度已用尽" : "Qoder(订阅) 429:上游限流或额度用尽";
107424
107673
  await this.accountPool.markCooldown(picked.accountId, after ?? 3e5, reason).catch(() => void 0);
107425
107674
  if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
107426
- picked = await this.credentialFor(triedAccounts);
107675
+ picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
107427
107676
  return true;
107428
107677
  }
107429
107678
  } else if (failure.code === "AUTH") {
107430
107679
  await this.accountPool.markAuthFailed(picked.accountId, failure.message).catch(() => void 0);
107431
107680
  if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
107432
- picked = await this.credentialFor(triedAccounts);
107681
+ picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
107433
107682
  return true;
107434
107683
  }
107435
107684
  }
@@ -107526,18 +107775,159 @@ var QoderAdapter = class extends LlmAdapter {
107526
107775
  }
107527
107776
  throw error;
107528
107777
  } finally {
107529
- if (state.sawUsage) rememberQoderCacheUsage({
107530
- inputTokens: state.inputTokens,
107531
- outputTokens: state.outputTokens,
107532
- cacheReadTokens: state.cacheReadTokens,
107533
- cacheWriteTokens: state.cacheWriteTokens
107534
- });
107778
+ if (state.sawUsage) {
107779
+ rememberQoderCacheUsage({
107780
+ inputTokens: state.inputTokens,
107781
+ outputTokens: state.outputTokens,
107782
+ cacheReadTokens: state.cacheReadTokens,
107783
+ cacheWriteTokens: state.cacheWriteTokens
107784
+ });
107785
+ recordQoderCacheObservation({
107786
+ model: currentModel,
107787
+ accountId: picked.accountId,
107788
+ uid: picked.credentials.uid,
107789
+ sessionId: options.sessionId,
107790
+ system: typeof normalized.system === "string" ? normalized.system : void 0,
107791
+ tools: normalized.tools,
107792
+ messages: normalized.messages.length,
107793
+ bodyChars: bodyText.length,
107794
+ inputTokens: state.inputTokens,
107795
+ cacheReadTokens: state.cacheReadTokens,
107796
+ cacheWriteTokens: state.cacheWriteTokens
107797
+ });
107798
+ }
107535
107799
  reader.cancel().catch(() => void 0);
107536
107800
  }
107537
107801
  }
107538
107802
  }
107539
107803
  };
107540
107804
  //#endregion
107805
+ //#region src/host/providers/qoder/traffic-guard.ts
107806
+ /**
107807
+ * Qoder 生成请求的每账号串行闸门。
107808
+ *
107809
+ * 上游按账号维护前缀缓存和队列;同一账号并发多个生成请求既容易把队列推深,也会让
107810
+ * 两个请求争抢同一段缓存。这里只在**生成路径**上串行:目录、额度等旁路请求不排队。
107811
+ *
107812
+ * 等待有上限,超时 fail-open(与 qoder2api-hub 的本地整形语义一致);这不是上游
107813
+ * 容量承诺,只是减少自己制造并发的本地保护。
107814
+ */
107815
+ const GENERATION_PATHS = ["/algo/api/v2/service/pro/sse/agent_chat_generation", "/model/v1/chat/completions"];
107816
+ function envNumber(name, fallback) {
107817
+ const raw = process.env[name];
107818
+ if (raw === void 0 || raw.trim() === "") return fallback;
107819
+ const value = Number(raw);
107820
+ return Number.isFinite(value) && value >= 0 ? value : fallback;
107821
+ }
107822
+ function isGenerationRequest(input, init) {
107823
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
107824
+ const path = (() => {
107825
+ try {
107826
+ return new URL(url).pathname;
107827
+ } catch {
107828
+ return url;
107829
+ }
107830
+ })();
107831
+ if (!GENERATION_PATHS.some((segment) => path.includes(segment))) return false;
107832
+ return (init?.method ?? (typeof input === "object" && "method" in input ? input.method : "GET")).toUpperCase() === "POST";
107833
+ }
107834
+ function accountKey(headers) {
107835
+ const auth = new Headers(headers).get("authorization");
107836
+ return auth === null ? "anonymous" : createHash("sha256").update(auth).digest("hex").slice(0, 16);
107837
+ }
107838
+ function delay(ms) {
107839
+ return new Promise((resolve) => setTimeout(resolve, ms));
107840
+ }
107841
+ /**
107842
+ * 包一层 fetch:生成请求按账号串行并保持最小间隔,响应体关闭后才释放槽位。
107843
+ */
107844
+ function createQoderTrafficGuardFetch(baseFetch, options = {}) {
107845
+ const maxConcurrency = Math.max(1, Math.floor(options.maxConcurrency ?? envNumber("DSH_QODER_MAX_CONCURRENCY", 1)));
107846
+ const minGapMs = Math.max(0, options.minGapMs ?? envNumber("DSH_QODER_MIN_GAP_MS", 400));
107847
+ const waitMs = Math.max(0, options.waitMs ?? envNumber("DSH_QODER_GUARD_WAIT_MS", 3e4));
107848
+ const active = /* @__PURE__ */ new Map();
107849
+ const lastStarted = /* @__PURE__ */ new Map();
107850
+ const waiters = /* @__PURE__ */ new Map();
107851
+ async function acquire(key) {
107852
+ const started = Date.now();
107853
+ while ((active.get(key) ?? 0) >= maxConcurrency) {
107854
+ const remaining = waitMs - (Date.now() - started);
107855
+ if (remaining <= 0) return () => void 0;
107856
+ await new Promise((resolve) => {
107857
+ const queue = waiters.get(key) ?? [];
107858
+ const timer = setTimeout(() => {
107859
+ const index = queue.indexOf(wake);
107860
+ if (index >= 0) queue.splice(index, 1);
107861
+ resolve();
107862
+ }, remaining);
107863
+ const wake = () => {
107864
+ clearTimeout(timer);
107865
+ resolve();
107866
+ };
107867
+ queue.push(wake);
107868
+ waiters.set(key, queue);
107869
+ });
107870
+ }
107871
+ const gap = minGapMs - (Date.now() - (lastStarted.get(key) ?? 0));
107872
+ if (gap > 0) await delay(gap);
107873
+ active.set(key, (active.get(key) ?? 0) + 1);
107874
+ lastStarted.set(key, Date.now());
107875
+ let released = false;
107876
+ return () => {
107877
+ if (released) return;
107878
+ released = true;
107879
+ active.set(key, Math.max(0, (active.get(key) ?? 1) - 1));
107880
+ const wake = waiters.get(key)?.shift();
107881
+ if (wake !== void 0) wake();
107882
+ };
107883
+ }
107884
+ return async function guardedFetch(input, init) {
107885
+ if (!isGenerationRequest(input, init)) return baseFetch(input, init);
107886
+ const release = await acquire(accountKey(init?.headers));
107887
+ try {
107888
+ const response = await baseFetch(input, init);
107889
+ if (response.body === null) {
107890
+ release();
107891
+ return response;
107892
+ }
107893
+ const reader = response.body.getReader();
107894
+ let done = false;
107895
+ const finish = () => {
107896
+ if (!done) {
107897
+ done = true;
107898
+ release();
107899
+ }
107900
+ };
107901
+ const body = new ReadableStream({
107902
+ async pull(controller) {
107903
+ try {
107904
+ const next = await reader.read();
107905
+ if (next.done) {
107906
+ finish();
107907
+ controller.close();
107908
+ } else controller.enqueue(next.value);
107909
+ } catch (error) {
107910
+ finish();
107911
+ controller.error(error);
107912
+ }
107913
+ },
107914
+ async cancel(reason) {
107915
+ finish();
107916
+ await reader.cancel(reason);
107917
+ }
107918
+ });
107919
+ return new Response(body, {
107920
+ status: response.status,
107921
+ statusText: response.statusText,
107922
+ headers: response.headers
107923
+ });
107924
+ } catch (error) {
107925
+ release();
107926
+ throw error;
107927
+ }
107928
+ };
107929
+ }
107930
+ //#endregion
107541
107931
  //#region src/host/providers/qoder/oauth.ts
107542
107932
  /**
107543
107933
  * Qoder(订阅)线路的登录:浏览器设备流(仅全球区)+ PAT 兑换 + 令牌刷新。
@@ -108141,8 +108531,14 @@ var QoderAccountPool = class extends AccountPoolCore {
108141
108531
  * 核心在这里做轮转、冷却、可用性判断与刷新;本方法只多给适配器一件事:
108142
108532
  * 一次请求内换过账号时,把试过的账号排除掉。
108143
108533
  */
108144
- async getEffectiveCredential(excludeIds, fetchFn = fetch) {
108145
- return this.getEffectiveAccount(excludeIds, fetchFn);
108534
+ async getEffectiveCredential(excludeIds, fetchFn = fetch, selection) {
108535
+ return this.getEffectiveAccount(excludeIds, fetchFn, false, void 0, selection);
108536
+ }
108537
+ /** 指定区域的账号 id(只做偏好,不做硬过滤;核心仍会跳过冷却/已试账号)。 */
108538
+ async accountIdsInRegions(regions) {
108539
+ if (regions.length === 0) return [];
108540
+ const wanted = new Set(regions);
108541
+ return (await this.read()).accounts.filter((account) => wanted.has(account.region)).map((account) => account.id);
108146
108542
  }
108147
108543
  /**
108148
108544
  * 一次额度读属于哪个账号,连同读它用的凭据。
@@ -143731,7 +144127,7 @@ const Config = z$1.object({
143731
144127
  advisorModel: z$1.string().default("").volatile().description("新对话的默认顾问模型。"),
143732
144128
  advisorReasoningEffort: z$1.string().default("auto").volatile().description("顾问模型的推理强度;auto 使用模型默认值。"),
143733
144129
  advisorMaxTokens: z$1.number().min(256).max(32768).step(1).default(4096).volatile().description("顾问单次回复的最大 token 数。"),
143734
- advisorTimeoutMs: z$1.number().min(1e3).max(3e5).step(1).default(3e5).volatile().description("顾问单次咨询的总超时毫秒数。"),
144130
+ advisorTimeoutMs: z$1.number().min(1e3).max(54e4).step(1).default(54e4).volatile().description("顾问单次咨询的总超时毫秒数。"),
143735
144131
  advisorMaxRetries: z$1.number().min(0).max(3).step(1).default(1).volatile().description("顾问遇到临时错误时的最大追加重试次数。"),
143736
144132
  advisorContextTokenBudget: z$1.number().min(8e3).max(1e6).step(1).default(1e5).volatile().description("转发给顾问的对话上下文预算。"),
143737
144133
  advisorSessionTokenBudget: z$1.number().min(0).max(1e7).step(1).default(2e5).volatile().description("单个对话累计可消耗的顾问 token 上限;0 表示不限制。"),
@@ -144417,9 +144813,10 @@ function apply(ctx, pluginConfig = {}) {
144417
144813
  providerId: PROVIDER_ID$7,
144418
144814
  label: PROVIDER_NAME$7,
144419
144815
  adapter: new QoderAdapter(qoderStore, qoderModelSettings, qoderPreferences, {
144420
- fetchFn: modelFetch[PROVIDER_ID$7],
144816
+ fetchFn: createQoderTrafficGuardFetch(modelFetch[PROVIDER_ID$7]),
144421
144817
  attachments: ctx.attachments,
144422
- accountPool: qoderAccountPool
144818
+ accountPool: qoderAccountPool,
144819
+ cacheAffinity: () => resolveCacheAffinityEnabled(pluginConfig, process.env)
144423
144820
  })
144424
144821
  });
144425
144822
  const disposeQoderRoutes = registerQoderRoutes(ctx, qoderSettingsSource(qoderPreferences, qoderModelSettings), {