@eddyskywalker/dsh-chatgpt-subscription 1.0.1 → 1.1.0
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.
- package/lib/client.js +89 -8
- package/lib/client.js.map +1 -1
- package/lib/codemode.js +33 -5
- package/lib/index.js +454 -62
- package/lib/{preset-sync-DWOAwSyl.js → preset-sync-RBsYhDY3.js} +2 -1
- package/lib/{tool-result-pruner-ClgRVOph.js → tool-result-pruner-DsaDg_l1.js} +2 -1
- package/lib/tool-result-pruner.js +1 -1
- package/lib/types/client/features/progress-updates/settings-section.d.ts +2 -2
- package/lib/types/client/locales-ru/qoder.d.ts.map +1 -1
- package/lib/types/client/providers/qoder/QoderComposerQuota.d.ts.map +1 -1
- package/lib/types/client/providers/qoder/QoderSection.d.ts.map +1 -1
- package/lib/types/client/providers/qoder/locales.d.ts +7 -1
- package/lib/types/client/providers/qoder/locales.d.ts.map +1 -1
- package/lib/types/client/providers/qoder/styles.d.ts.map +1 -1
- package/lib/types/client/providers/qoder/useQoderSection.d.ts +15 -0
- package/lib/types/client/providers/qoder/useQoderSection.d.ts.map +1 -1
- package/lib/types/compat.d.ts +1 -1
- package/lib/types/entries/tool-result-pruner.d.ts.map +1 -1
- package/lib/types/host/providers/antigravity-acp/adapter.d.ts.map +1 -1
- package/lib/types/host/providers/qoder/account-affinity.d.ts +16 -0
- package/lib/types/host/providers/qoder/account-affinity.d.ts.map +1 -0
- package/lib/types/host/providers/qoder/account-pool.d.ts +4 -2
- package/lib/types/host/providers/qoder/account-pool.d.ts.map +1 -1
- package/lib/types/host/providers/qoder/adapter.d.ts +15 -0
- package/lib/types/host/providers/qoder/adapter.d.ts.map +1 -1
- package/lib/types/host/providers/qoder/cache-diagnostics.d.ts +20 -0
- package/lib/types/host/providers/qoder/cache-diagnostics.d.ts.map +1 -0
- package/lib/types/host/providers/qoder/cosy.d.ts +12 -5
- package/lib/types/host/providers/qoder/cosy.d.ts.map +1 -1
- package/lib/types/host/providers/qoder/mapper.d.ts +15 -0
- package/lib/types/host/providers/qoder/mapper.d.ts.map +1 -1
- package/lib/types/host/providers/qoder/model-catalog.d.ts +18 -0
- package/lib/types/host/providers/qoder/model-catalog.d.ts.map +1 -1
- package/lib/types/host/providers/qoder/queue-state.d.ts +8 -1
- package/lib/types/host/providers/qoder/queue-state.d.ts.map +1 -1
- package/lib/types/host/providers/qoder/traffic-guard.d.ts +13 -0
- package/lib/types/host/providers/qoder/traffic-guard.d.ts.map +1 -0
- package/lib/types/host/providers/qoder/types.d.ts +6 -6
- package/lib/types/host/providers/qoder/types.d.ts.map +1 -1
- package/lib/types/host/runtime/codemode/rules.d.ts.map +1 -1
- package/lib/types/host/runtime/codemode/transport.d.ts.map +1 -1
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/shared/advisor-contracts.d.ts +9 -2
- package/lib/types/shared/advisor-contracts.d.ts.map +1 -1
- package/lib/types/shared/qoder-contracts.d.ts +30 -1
- package/lib/types/shared/qoder-contracts.d.ts.map +1 -1
- 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-
|
|
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-
|
|
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
|
|
894
|
+
const PLUGIN_VERSION = "1.1.0";
|
|
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,
|
|
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$
|
|
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$
|
|
15449
|
+
await delay$2(RESTART_POLL_MS);
|
|
15450
15450
|
}
|
|
15451
15451
|
}
|
|
15452
15452
|
findWebEntry() {
|
|
@@ -29217,7 +29217,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
|
|
|
29217
29217
|
await Promise.race([
|
|
29218
29218
|
turn.queue.wait(signal),
|
|
29219
29219
|
turn.bridge.waitForWork(signal),
|
|
29220
|
-
delay(200)
|
|
29220
|
+
delay$1(200)
|
|
29221
29221
|
]);
|
|
29222
29222
|
}
|
|
29223
29223
|
} finally {
|
|
@@ -29242,8 +29242,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
|
|
|
29242
29242
|
const options = readPermissionOptions(params);
|
|
29243
29243
|
const answer = () => options.find((option) => option.kind === "allow_once")?.optionId ?? options.find((option) => option.kind === "allow_always")?.optionId;
|
|
29244
29244
|
const deny = () => options.find((option) => option.kind === "reject_once")?.optionId ?? options.find((option) => option.kind === "reject_always")?.optionId;
|
|
29245
|
-
|
|
29246
|
-
if ((typeof toolCall?.name === "string" ? toolCall.name : "").startsWith(`mcp_dsh-bridge_`)) return answer();
|
|
29245
|
+
if (isBridgeToolCall(asRecord$19(params.toolCall))) return answer();
|
|
29247
29246
|
const settings = await this.options.settings.read();
|
|
29248
29247
|
if (settings.nativeToolPolicy === "cancel") return deny();
|
|
29249
29248
|
return settings.permissionPolicy === "allow" ? answer() : deny();
|
|
@@ -29787,9 +29786,39 @@ function assertNoSamplingControls(options) {
|
|
|
29787
29786
|
* @param update - One `session/update` payload.
|
|
29788
29787
|
* @returns The call's id and name when it is a native call; undefined for the bridge.
|
|
29789
29788
|
*/
|
|
29789
|
+
/**
|
|
29790
|
+
* 1.5.20 起权限请求不再带 `name`;桥身份可能落在 `title`、`_meta` 或
|
|
29791
|
+
* `rawInput.ServerName`。任何一处命中 `dsh-bridge` 都按桥处理;空名字也按桥处理,
|
|
29792
|
+
* 因为把它倒向 nativeToolPolicy 会再次触发 #153。
|
|
29793
|
+
*/
|
|
29794
|
+
function mentionsBridge(value) {
|
|
29795
|
+
if (typeof value === "string") return /dsh[-_]bridge/i.test(value);
|
|
29796
|
+
if (Array.isArray(value)) return value.some(mentionsBridge);
|
|
29797
|
+
if (typeof value !== "object" || value === null) return false;
|
|
29798
|
+
return Object.values(value).some(mentionsBridge);
|
|
29799
|
+
}
|
|
29800
|
+
function rawInputNamesBridgeServer(value) {
|
|
29801
|
+
if (Array.isArray(value)) return value.some(rawInputNamesBridgeServer);
|
|
29802
|
+
if (typeof value !== "object" || value === null) return false;
|
|
29803
|
+
const record = value;
|
|
29804
|
+
for (const key of [
|
|
29805
|
+
"ServerName",
|
|
29806
|
+
"serverName",
|
|
29807
|
+
"server_name",
|
|
29808
|
+
"mcpServerName",
|
|
29809
|
+
"mcp_server_name"
|
|
29810
|
+
]) if (mentionsBridge(record[key])) return true;
|
|
29811
|
+
return Object.values(record).some(rawInputNamesBridgeServer);
|
|
29812
|
+
}
|
|
29813
|
+
function isBridgeToolCall(record) {
|
|
29814
|
+
if (record === void 0) return false;
|
|
29815
|
+
const name = typeof record.name === "string" ? record.name : "";
|
|
29816
|
+
if (name.startsWith(`mcp_dsh-bridge_`) || name === "call_mcp_tool" || name === "") return true;
|
|
29817
|
+
return mentionsBridge(record.title) || mentionsBridge(record._meta) || rawInputNamesBridgeServer(record.rawInput);
|
|
29818
|
+
}
|
|
29790
29819
|
function readNativeToolCall(update) {
|
|
29820
|
+
if (isBridgeToolCall(update)) return void 0;
|
|
29791
29821
|
const name = typeof update.name === "string" ? update.name : "";
|
|
29792
|
-
if (name === "" || name.startsWith(`mcp_dsh-bridge_`)) return void 0;
|
|
29793
29822
|
return {
|
|
29794
29823
|
callId: typeof update.toolCallId === "string" ? update.toolCallId : "",
|
|
29795
29824
|
name
|
|
@@ -29991,7 +30020,7 @@ function abortError$1() {
|
|
|
29991
30020
|
error.name = "AbortError";
|
|
29992
30021
|
return error;
|
|
29993
30022
|
}
|
|
29994
|
-
function delay(ms) {
|
|
30023
|
+
function delay$1(ms) {
|
|
29995
30024
|
return new Promise((resolve) => {
|
|
29996
30025
|
setTimeout(resolve, ms).unref?.();
|
|
29997
30026
|
});
|
|
@@ -103771,13 +103800,14 @@ const QODER_AUTH_FILE = "user";
|
|
|
103771
103800
|
/** qodercli 的 machine id 文件(36 字符 UUID;同时也是 adopt 文件的解密钥源)。 */
|
|
103772
103801
|
const QODER_MACHINE_ID_FILE = "machine_id";
|
|
103773
103802
|
/**
|
|
103774
|
-
* 输出上限兜底:
|
|
103803
|
+
* 输出上限兜底:32768。
|
|
103775
103804
|
*
|
|
103776
|
-
*
|
|
103777
|
-
*
|
|
103778
|
-
*
|
|
103805
|
+
* 目录不报输出上限,而上游的参数校验明确要求 `max_tokens ∈ [1, 32768]`:
|
|
103806
|
+
* 实机把 65536 / 131072 发给 Step-5 会直接得到 400
|
|
103807
|
+
* `Range of max_tokens should be [1, 32768]`。Liki4/qodercli2api 与 qoder2api
|
|
103808
|
+
* 的桥接层也都把上限压在 32768;发得更大不会换来更长输出,只会在模型之前被拒。
|
|
103779
103809
|
*/
|
|
103780
|
-
const QODER_MAX_OUTPUT_TOKENS =
|
|
103810
|
+
const QODER_MAX_OUTPUT_TOKENS = 32768;
|
|
103781
103811
|
/**
|
|
103782
103812
|
* 上下文窗口兜底(目录缺 `context_config` 时)。
|
|
103783
103813
|
*
|
|
@@ -103907,6 +103937,20 @@ function isRecord$44(value) {
|
|
|
103907
103937
|
function nonEmptyString$2(value) {
|
|
103908
103938
|
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
103909
103939
|
}
|
|
103940
|
+
function nonNegativeNumber(value) {
|
|
103941
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
103942
|
+
}
|
|
103943
|
+
function promotionOf(value) {
|
|
103944
|
+
if (!isRecord$44(value)) return void 0;
|
|
103945
|
+
const promotion = {
|
|
103946
|
+
...value.active === true ? { active: true } : {},
|
|
103947
|
+
...nonNegativeNumber(value.discount_factor) === void 0 ? {} : { discountFactor: nonNegativeNumber(value.discount_factor) },
|
|
103948
|
+
...nonNegativeNumber(value.before_promotion_price_factor) === void 0 ? {} : { beforePromotionPriceFactor: nonNegativeNumber(value.before_promotion_price_factor) },
|
|
103949
|
+
...nonEmptyString$2(value.window_start) === void 0 ? {} : { windowStart: nonEmptyString$2(value.window_start) },
|
|
103950
|
+
...nonEmptyString$2(value.window_end) === void 0 ? {} : { windowEnd: nonEmptyString$2(value.window_end) }
|
|
103951
|
+
};
|
|
103952
|
+
return Object.keys(promotion).length === 0 ? void 0 : promotion;
|
|
103953
|
+
}
|
|
103910
103954
|
/**
|
|
103911
103955
|
* 上游 `display_name` → 公开模型 id:去掉全部空白字符
|
|
103912
103956
|
* (逐字 pi-provider `toQoderModelId`:`replace(/\s+/g, "")`)。
|
|
@@ -104086,7 +104130,11 @@ function entryFromQoderRecord(record, region) {
|
|
|
104086
104130
|
supportsImages: record.is_vl === true,
|
|
104087
104131
|
defaultContextWindow: contextWindowFromRecord(record, region),
|
|
104088
104132
|
defaultMaxTokens: QODER_MAX_OUTPUT_TOKENS,
|
|
104089
|
-
description: nonEmptyString$2(record.description) ?? null
|
|
104133
|
+
description: nonEmptyString$2(record.description) ?? null,
|
|
104134
|
+
...nonNegativeNumber(record.price_factor) === void 0 ? {} : { priceFactor: nonNegativeNumber(record.price_factor) },
|
|
104135
|
+
...nonNegativeNumber(record.original_price_factor) === void 0 ? {} : { originalPriceFactor: nonNegativeNumber(record.original_price_factor) },
|
|
104136
|
+
...nonNegativeNumber(record.before_promotion_price_factor) === void 0 ? {} : { originalPriceFactor: nonNegativeNumber(record.before_promotion_price_factor) },
|
|
104137
|
+
...promotionOf(record.promotion) === void 0 ? {} : { promotion: promotionOf(record.promotion) }
|
|
104090
104138
|
});
|
|
104091
104139
|
}
|
|
104092
104140
|
/**
|
|
@@ -104432,12 +104480,16 @@ function describeQoderModel(entry, prefix) {
|
|
|
104432
104480
|
const thinking = entry.reasoningEfforts.length === 0 ? entry.thinkingDisableable ? "思考可开关" : "思考恒开" : entry.thinkingDisableable ? "思考可关闭" : "思考恒开";
|
|
104433
104481
|
const effort = entry.reasoningEfforts.length === 0 ? "无档位字段" : "档位 " + entry.reasoningEfforts.join("/");
|
|
104434
104482
|
const modality = entry.supportsImages ? "输入 text + image" : "输入仅 text";
|
|
104483
|
+
const price = entry.priceFactor === void 0 ? void 0 : entry.priceFactor === 0 ? "免费" : "倍率 ×" + entry.priceFactor;
|
|
104484
|
+
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
104485
|
return (prefix === void 0 || prefix === "" ? "" : prefix + ":") + [
|
|
104436
104486
|
thinking,
|
|
104437
104487
|
effort,
|
|
104438
104488
|
modality,
|
|
104439
|
-
"上下文 " + entry.defaultContextWindow
|
|
104440
|
-
|
|
104489
|
+
"上下文 " + entry.defaultContextWindow,
|
|
104490
|
+
price,
|
|
104491
|
+
promotion
|
|
104492
|
+
].filter((part) => part !== void 0).join("|");
|
|
104441
104493
|
}
|
|
104442
104494
|
function positiveInt(value) {
|
|
104443
104495
|
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
|
|
@@ -104895,12 +104947,12 @@ function markQoderLegacyProbeDone() {
|
|
|
104895
104947
|
* - {@link generateQoderRuntimeAuthFields} —— runtime-fields.json;
|
|
104896
104948
|
* - {@link decryptQoderAdoptPayload} —— credential.json;
|
|
104897
104949
|
* - {@link encodeQoderBody} —— infer-user-no-org.json 的 `body_string`;
|
|
104898
|
-
* - {@link buildQoderCosyHeaders} ——
|
|
104950
|
+
* - {@link buildQoderCosyHeaders} —— 最终发送头集合与签名。
|
|
104899
104951
|
*
|
|
104900
|
-
*
|
|
104901
|
-
* `Cosy-
|
|
104902
|
-
* `
|
|
104903
|
-
*
|
|
104952
|
+
* 官方 1.1.74 的**最终发送层**会在无真实 UMID 时移除 `Cosy-MachineToken` /
|
|
104953
|
+
* `Cosy-MachineType`(不能用 machine_id 冒充 machine token),再补
|
|
104954
|
+
* `Cosy-MachineOS`;这一层不在 pinned WASM 的 18/22-header 核心向量里,
|
|
104955
|
+
* 所以 fixture 只能锁核心,不能锁最终网络头。
|
|
104904
104956
|
*
|
|
104905
104957
|
* 本文件不做任何网络 I/O,也不持有凭据:它吃的是调用方递进来的材料,吐出的是
|
|
104906
104958
|
* 头与 body。machine id 的读取顺序(qodercli 原配 → 本线路自己的文件 → 内存生成)
|
|
@@ -105052,6 +105104,15 @@ function cosySignedPath(url) {
|
|
|
105052
105104
|
* payload 的字段顺序固定(`version, requestId, info, cosyVersion, ideVersion`——
|
|
105053
105105
|
* 它参与签名,散装键序就是一次签名漂移),所以这里按字面量顺序写键而不是用 Map。
|
|
105054
105106
|
*/
|
|
105107
|
+
/**
|
|
105108
|
+
* 官方最终发送层的 `Cosy-MachineOS`:`{arch}_{platform}`。
|
|
105109
|
+
*
|
|
105110
|
+
* Linux x64 的 `x86_64_linux` 已由 qodercli2api 对照 1.1.74 样本核实;
|
|
105111
|
+
* 其余平台按同一规则生成。
|
|
105112
|
+
*/
|
|
105113
|
+
function qoderMachineOS(platform = process.platform, arch = process.arch) {
|
|
105114
|
+
return (arch === "x64" ? "x86_64" : arch === "arm64" ? "aarch64" : arch === "ia32" ? "x86" : arch) + "_" + platform;
|
|
105115
|
+
}
|
|
105055
105116
|
function buildQoderCosyHeaders(identity, options) {
|
|
105056
105117
|
if (identity.uid.trim() === "") throw new Error("Qoder COSY:uid 不能为空");
|
|
105057
105118
|
const runtime = generateQoderRuntimeAuthFields(identity.rawUserInfo, options.entropy ?? defaultEntropy);
|
|
@@ -105078,8 +105139,7 @@ function buildQoderCosyHeaders(identity, options) {
|
|
|
105078
105139
|
"Cosy-Date": unixSeconds,
|
|
105079
105140
|
"Cosy-Key": runtime.key,
|
|
105080
105141
|
"Cosy-MachineId": identity.machineId,
|
|
105081
|
-
"Cosy-
|
|
105082
|
-
"Cosy-MachineType": "5",
|
|
105142
|
+
"Cosy-MachineOS": qoderMachineOS(),
|
|
105083
105143
|
"Cosy-Scene": COSY_SCENE.scene,
|
|
105084
105144
|
"Cosy-User": identity.uid,
|
|
105085
105145
|
"Cosy-Version": identity.cosyVersion,
|
|
@@ -106152,6 +106212,32 @@ function resolveQoderThinking(requested, request) {
|
|
|
106152
106212
|
};
|
|
106153
106213
|
}
|
|
106154
106214
|
/**
|
|
106215
|
+
* 中和 Qoder 上游的品牌身份句检测。
|
|
106216
|
+
*
|
|
106217
|
+
* 受控 A/B(shuishuipingan/qoder2api-hub docs/risk-control-and-queueing.md §7)确认:
|
|
106218
|
+
* `You are <Brand>,` 与 `powered by <Brand>.` 会被上游判成第三方客户端,返回
|
|
106219
|
+
* `10605 / queueType:p1 / queueCount:0 / serviceAvailable:false`;这是硬拒绝伪装成
|
|
106220
|
+
* 排队,等待不会放行。DSH 的系统提示首句正好是
|
|
106221
|
+
* `You are an AI agent powered by DeepSeek Harness.`。
|
|
106222
|
+
*
|
|
106223
|
+
* 只做字符级最小中和:在紧跟品牌名的逗号/句号前插一个空格,品牌、语序与语义全部保留;
|
|
106224
|
+
* 自家品牌 Qoder 豁免,避免扰动普通请求的前缀缓存。函数是幂等的。
|
|
106225
|
+
*/
|
|
106226
|
+
function neutralizeQoderIdentityPhrases(text) {
|
|
106227
|
+
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 + " .");
|
|
106228
|
+
}
|
|
106229
|
+
/** 对一条 wire 消息里的所有文本字段做身份句中转(内容、reasoning、内容块 text)。 */
|
|
106230
|
+
function guardQoderWireMessage(message) {
|
|
106231
|
+
const next = { ...message };
|
|
106232
|
+
if (typeof next.content === "string") next.content = neutralizeQoderIdentityPhrases(next.content);
|
|
106233
|
+
else if (Array.isArray(next.content)) next.content = next.content.map((part) => isRecord$41(part) && typeof part.text === "string" ? {
|
|
106234
|
+
...part,
|
|
106235
|
+
text: neutralizeQoderIdentityPhrases(part.text)
|
|
106236
|
+
} : part);
|
|
106237
|
+
for (const key of ["reasoning_content", "reasoning"]) if (typeof next[key] === "string") next[key] = neutralizeQoderIdentityPhrases(next[key]);
|
|
106238
|
+
return next;
|
|
106239
|
+
}
|
|
106240
|
+
/**
|
|
106155
106241
|
* 会话与请求的稳定 id(缓存亲和)。
|
|
106156
106242
|
*
|
|
106157
106243
|
* 逐字 pi-provider \`stream.ts\` 的设计:\`session_id\` 的稳定段来自账号+模型的哈希,
|
|
@@ -106240,7 +106326,8 @@ function buildQoderChatRequest(options, images, request, context) {
|
|
|
106240
106326
|
}
|
|
106241
106327
|
const entry = context.entry;
|
|
106242
106328
|
const modelKey = context.modelKey;
|
|
106243
|
-
const
|
|
106329
|
+
const outputLimit = Math.min(request.defaultMaxTokens ?? entry?.defaultMaxTokens ?? 32768, QODER_MAX_OUTPUT_TOKENS);
|
|
106330
|
+
const maxTokens = Math.max(1, Math.min(options.maxTokens ?? outputLimit, outputLimit));
|
|
106244
106331
|
const tools = options.tools && options.tools.length > 0 ? options.tools.map((tool) => ({
|
|
106245
106332
|
type: "function",
|
|
106246
106333
|
function: {
|
|
@@ -106249,6 +106336,7 @@ function buildQoderChatRequest(options, images, request, context) {
|
|
|
106249
106336
|
parameters: stripMetaSchema$1(tool.parameters)
|
|
106250
106337
|
}
|
|
106251
106338
|
})) : [];
|
|
106339
|
+
for (let index = 0; index < messages.length; index++) messages[index] = guardQoderWireMessage(messages[index]);
|
|
106252
106340
|
const recordId = qoderChatRecordId(modelKey, messages, tools.length > 0 ? tools : void 0, maxTokens);
|
|
106253
106341
|
const thinking = resolveQoderThinking(options.reasoningEffort, request);
|
|
106254
106342
|
const parameters = { max_tokens: maxTokens };
|
|
@@ -106299,7 +106387,7 @@ function buildQoderChatRequest(options, images, request, context) {
|
|
|
106299
106387
|
session_type: "qodercli",
|
|
106300
106388
|
source: 1,
|
|
106301
106389
|
stream: true,
|
|
106302
|
-
system:
|
|
106390
|
+
system: "",
|
|
106303
106391
|
task_id: "common",
|
|
106304
106392
|
tools,
|
|
106305
106393
|
version: "3"
|
|
@@ -106377,6 +106465,10 @@ function closeCurrent$2(state) {
|
|
|
106377
106465
|
function closeToolCalls$1(state) {
|
|
106378
106466
|
const out = [];
|
|
106379
106467
|
for (const [wireIndex, call] of [...state.toolCalls.entries()].sort((a, b) => a[0] - b[0])) {
|
|
106468
|
+
if (!call.started || call.name === "") {
|
|
106469
|
+
state.toolCalls.delete(wireIndex);
|
|
106470
|
+
continue;
|
|
106471
|
+
}
|
|
106380
106472
|
const block = {
|
|
106381
106473
|
type: "tool-call",
|
|
106382
106474
|
id: toToolCallId(call.id),
|
|
@@ -106467,18 +106559,20 @@ function applyToolDelta$1(entry, state) {
|
|
|
106467
106559
|
let call = state.toolCalls.get(wireIndex);
|
|
106468
106560
|
const incomingId = asString$12(entry.id);
|
|
106469
106561
|
if (call !== void 0 && incomingId !== void 0 && call.id !== "call_" + wireIndex && incomingId !== call.id) {
|
|
106470
|
-
|
|
106471
|
-
|
|
106472
|
-
|
|
106473
|
-
|
|
106474
|
-
|
|
106475
|
-
|
|
106476
|
-
|
|
106477
|
-
|
|
106478
|
-
|
|
106479
|
-
|
|
106480
|
-
|
|
106481
|
-
|
|
106562
|
+
if (call.started && call.name !== "") {
|
|
106563
|
+
const closedBlock = {
|
|
106564
|
+
type: "tool-call",
|
|
106565
|
+
id: toToolCallId(call.id),
|
|
106566
|
+
name: call.name,
|
|
106567
|
+
arguments: call.arguments === "" ? "{}" : call.arguments
|
|
106568
|
+
};
|
|
106569
|
+
state.blocks[call.blockIndex] = closedBlock;
|
|
106570
|
+
out.push({
|
|
106571
|
+
type: "block-end",
|
|
106572
|
+
index: call.blockIndex,
|
|
106573
|
+
block: closedBlock
|
|
106574
|
+
});
|
|
106575
|
+
}
|
|
106482
106576
|
state.toolCalls.delete(wireIndex);
|
|
106483
106577
|
call = void 0;
|
|
106484
106578
|
}
|
|
@@ -106497,14 +106591,29 @@ function applyToolDelta$1(entry, state) {
|
|
|
106497
106591
|
const argsDelta = asString$12(fn?.arguments) ?? "";
|
|
106498
106592
|
if (argsDelta !== "") call.arguments += argsDelta;
|
|
106499
106593
|
if (!call.started) {
|
|
106594
|
+
if (call.name === "") return out;
|
|
106500
106595
|
call.started = true;
|
|
106501
106596
|
state.hasToolCall = true;
|
|
106502
106597
|
state.hasContent = true;
|
|
106598
|
+
state.blocks[call.blockIndex] = {
|
|
106599
|
+
type: "tool-call",
|
|
106600
|
+
id: toToolCallId(call.id),
|
|
106601
|
+
name: call.name,
|
|
106602
|
+
arguments: call.arguments === "" ? "{}" : call.arguments
|
|
106603
|
+
};
|
|
106503
106604
|
out.push({
|
|
106504
106605
|
type: "block-start",
|
|
106505
106606
|
index: call.blockIndex,
|
|
106506
106607
|
blockType: "tool-call"
|
|
106507
106608
|
});
|
|
106609
|
+
out.push({
|
|
106610
|
+
type: "tool-call-delta",
|
|
106611
|
+
index: call.blockIndex,
|
|
106612
|
+
id: toToolCallId(call.id),
|
|
106613
|
+
name: call.name,
|
|
106614
|
+
argumentsDelta: call.arguments
|
|
106615
|
+
});
|
|
106616
|
+
return out;
|
|
106508
106617
|
}
|
|
106509
106618
|
if (argsDelta !== "" || out.length > 0) out.push({
|
|
106510
106619
|
type: "tool-call-delta",
|
|
@@ -106821,6 +106930,17 @@ function collectQoderFailureFacts(node, facts, depth, budget) {
|
|
|
106821
106930
|
collectQoderFailureFacts(value, facts, depth + 1, budget);
|
|
106822
106931
|
}
|
|
106823
106932
|
}
|
|
106933
|
+
/**
|
|
106934
|
+
* 文本里是否明确指出了「当前模型暂时不可用」。
|
|
106935
|
+
*
|
|
106936
|
+
* 上游还有一类未带 `RESOURCE_LIMIT` 结构字段的 403:文案只说模型暂时不可用、
|
|
106937
|
+
* 请稍后重试。它是容量 / 模型可用性问题,不是凭据被拒——归 AUTH 会让有额度的
|
|
106938
|
+
* 账号被提示重新登录,也失去切换到同线路其它模型的机会。
|
|
106939
|
+
*
|
|
106940
|
+
* 只认带 model / service / upstream 或「模型 / 服务 / 上游」限定的措辞,
|
|
106941
|
+
* 不拿一句泛泛的 `try again later` 改写普通 403(登录失效的文案也可能这么说)。
|
|
106942
|
+
*/
|
|
106943
|
+
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
106944
|
/** 文本里是否明确指出了排队 / 资源不足(不含笼统的 rate limit,免得改写普通 429)。 */
|
|
106825
106945
|
function hasQoderQueueWording(text) {
|
|
106826
106946
|
return /RESO?URCE_LIMIT|REOSURCE_LIMIT|\b10605\b|queueCount|queue_count|isQueued|is_queued|正在排队|排队等待|模型排队|queue(?:d|ing)\b/i.test(text);
|
|
@@ -106840,9 +106960,16 @@ function isQoderResourceLimited(facts, status, detail = "") {
|
|
|
106840
106960
|
if (facts.codes.includes("10605")) return true;
|
|
106841
106961
|
const combinedText = [detail, ...facts.messages ?? []].join(" ");
|
|
106842
106962
|
if (/RESO?URCE_LIMIT|REOSURCE_LIMIT|\b10605\b/i.test(combinedText)) return true;
|
|
106963
|
+
if (isQoderModelUnavailable(facts, status, detail)) return true;
|
|
106843
106964
|
if (status !== void 0 && status !== 403) return false;
|
|
106844
106965
|
return facts.serviceAvailable === false || facts.isQueued === true || facts.queueCount !== void 0 && facts.queueCount > 0 || hasQoderQueueWording(combinedText);
|
|
106845
106966
|
}
|
|
106967
|
+
/** 上游是否明确报告「当前模型暂时不可用」(403 且带模型级措辞)。 */
|
|
106968
|
+
function isQoderModelUnavailable(facts, status, detail = "") {
|
|
106969
|
+
if (status !== 403) return false;
|
|
106970
|
+
const combinedText = [detail, ...facts.messages ?? []].join(" ");
|
|
106971
|
+
return QODER_MODEL_UNAVAILABLE_WORDING.test(combinedText);
|
|
106972
|
+
}
|
|
106846
106973
|
const QODER_QUEUE_FAILURE_MARKER = /* @__PURE__ */ new WeakSet();
|
|
106847
106974
|
/**
|
|
106848
106975
|
* 排队失败里上游报的结构化容量事实(queueCount / retryAfterSeconds / serviceAvailable)。
|
|
@@ -106913,6 +107040,14 @@ function qoderResourceLimitMessage(facts, status) {
|
|
|
106913
107040
|
if (facts.modelKey !== void 0) details.push("modelKey " + facts.modelKey);
|
|
106914
107041
|
return "Qoder(订阅) 上游资源不足,这个模型正在排队" + (details.length === 0 ? "" : ":" + details.join(",")) + "。这是上游容量问题,不是凭据问题——账号仍是登录状态,不需要重新登录;稍后重试即可。";
|
|
106915
107042
|
}
|
|
107043
|
+
/** 上游模型级暂时不可用的文案:说清与额度 / 凭据无关,并说明会自动换模型。 */
|
|
107044
|
+
function qoderModelUnavailableMessage(facts, status) {
|
|
107045
|
+
const details = [];
|
|
107046
|
+
const codes = [...facts.subCodes, ...facts.codes].filter((code) => code !== "" && code !== String(status));
|
|
107047
|
+
if (codes.length > 0) details.push("code " + codes.join(" / "));
|
|
107048
|
+
if (facts.modelKey !== void 0) details.push("modelKey " + facts.modelKey);
|
|
107049
|
+
return "Qoder(订阅) 当前模型暂时不可用" + (details.length === 0 ? "" : ":" + details.join(",")) + "。这不是账号或额度问题,不需要重新登录;本线路会先切换到其它已启用模型,稍后也可以重试。";
|
|
107050
|
+
}
|
|
106916
107051
|
/** 上游额度用尽的文案:额度恢复前这一请求不会成功,并给出上游给的购买/升级页。 */
|
|
106917
107052
|
function qoderQuotaExhaustedMessage(facts, status) {
|
|
106918
107053
|
const details = [];
|
|
@@ -106963,6 +107098,16 @@ function classifyQoderFailureFacts(status, detail, facts) {
|
|
|
106963
107098
|
const options = status === void 0 ? {} : { status };
|
|
106964
107099
|
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
107100
|
if (isQoderQuotaExhausted(facts, status)) return new LlmError$1(qoderQuotaExhaustedMessage(facts, status) + suffix, "QUOTA", options);
|
|
107101
|
+
if (isQoderModelUnavailable(facts, status, detail)) {
|
|
107102
|
+
const after = facts.retryAfterSeconds;
|
|
107103
|
+
const err = new LlmError$1(qoderModelUnavailableMessage(facts, status) + suffix, "SERVER", after === void 0 || after <= 0 ? options : {
|
|
107104
|
+
...options,
|
|
107105
|
+
providerRetryAfterMs: after * 1e3
|
|
107106
|
+
});
|
|
107107
|
+
QODER_QUEUE_FAILURE_MARKER.add(err);
|
|
107108
|
+
QODER_QUEUE_FACTS.set(err, facts);
|
|
107109
|
+
return err;
|
|
107110
|
+
}
|
|
106966
107111
|
if (isQoderResourceLimited(facts, status, detail)) {
|
|
106967
107112
|
const after = facts.retryAfterSeconds;
|
|
106968
107113
|
const err = new LlmError$1(qoderResourceLimitMessage(facts, status) + suffix, "SERVER", after === void 0 || after <= 0 ? options : {
|
|
@@ -107009,9 +107154,76 @@ function currentQoderQueuePosition(now = Date.now()) {
|
|
|
107009
107154
|
return lastObserved;
|
|
107010
107155
|
}
|
|
107011
107156
|
/** 请求真的拿到内容时清掉:队列已经过去,胶囊不该继续显示旧位置。 */
|
|
107157
|
+
/**
|
|
107158
|
+
* `queueCount=0` + `serviceAvailable=false`:没有位置可显示,但上游确实在排队。
|
|
107159
|
+
* 不能复用 {@link recordQoderQueuePosition} 的「0 不是位置」规则,否则界面一直空白。
|
|
107160
|
+
*/
|
|
107161
|
+
function recordQoderQueueWait(hint, now = Date.now()) {
|
|
107162
|
+
if (hint === void 0 || hint.isQueued !== true) return void 0;
|
|
107163
|
+
const snapshot = {
|
|
107164
|
+
position: 0,
|
|
107165
|
+
waiting: true,
|
|
107166
|
+
observedAt: now,
|
|
107167
|
+
...hint.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: hint.retryAfterSeconds }
|
|
107168
|
+
};
|
|
107169
|
+
lastObserved = snapshot;
|
|
107170
|
+
return snapshot;
|
|
107171
|
+
}
|
|
107012
107172
|
function clearQoderQueuePosition() {
|
|
107013
107173
|
lastObserved = void 0;
|
|
107014
107174
|
}
|
|
107175
|
+
const lastAccountBySession = /* @__PURE__ */ new Map();
|
|
107176
|
+
/** 给当前会话的账号偏好;没有记录或会话 id 为空时返回 undefined。 */
|
|
107177
|
+
function qoderAffinityHint(sessionId) {
|
|
107178
|
+
if (sessionId === void 0 || sessionId.trim() === "") return void 0;
|
|
107179
|
+
const accountId = lastAccountBySession.get(sessionId);
|
|
107180
|
+
return accountId === void 0 ? void 0 : { preferAccountIds: [accountId] };
|
|
107181
|
+
}
|
|
107182
|
+
/** 记录这一轮实际选中的账号;accountId 为空时不动。 */
|
|
107183
|
+
function rememberQoderAffinity(sessionId, accountId) {
|
|
107184
|
+
if (sessionId === void 0 || sessionId.trim() === "" || accountId === null) return;
|
|
107185
|
+
lastAccountBySession.delete(sessionId);
|
|
107186
|
+
lastAccountBySession.set(sessionId, accountId);
|
|
107187
|
+
while (lastAccountBySession.size > 128) {
|
|
107188
|
+
const oldest = lastAccountBySession.keys().next().value;
|
|
107189
|
+
if (oldest === void 0) break;
|
|
107190
|
+
lastAccountBySession.delete(oldest);
|
|
107191
|
+
}
|
|
107192
|
+
}
|
|
107193
|
+
//#endregion
|
|
107194
|
+
//#region src/host/providers/qoder/cache-diagnostics.ts
|
|
107195
|
+
/** 逐请求缓存观察的进程内环形缓冲;只保留最近若干条,重启清空。 */
|
|
107196
|
+
const MAX_OBSERVATIONS = 24;
|
|
107197
|
+
const observations = [];
|
|
107198
|
+
function shortHash(value) {
|
|
107199
|
+
if (typeof value !== "string" || value === "") return "-";
|
|
107200
|
+
return createHash("sha256").update(value).digest("hex").slice(0, 8);
|
|
107201
|
+
}
|
|
107202
|
+
function toolNames(tools) {
|
|
107203
|
+
if (!Array.isArray(tools)) return "";
|
|
107204
|
+
return tools.map((tool) => typeof tool === "object" && tool !== null ? tool.name : void 0).filter((name) => typeof name === "string").join(",");
|
|
107205
|
+
}
|
|
107206
|
+
/** 记录一条带用量的请求;没有用量帧的请求不调用。 */
|
|
107207
|
+
function recordQoderCacheObservation(input) {
|
|
107208
|
+
observations.push({
|
|
107209
|
+
at: Date.now(),
|
|
107210
|
+
model: input.model,
|
|
107211
|
+
account: shortHash(input.accountId ?? input.uid),
|
|
107212
|
+
session: shortHash(input.sessionId),
|
|
107213
|
+
system: shortHash(input.system),
|
|
107214
|
+
tools: shortHash(toolNames(input.tools)),
|
|
107215
|
+
messages: input.messages,
|
|
107216
|
+
bodyChars: input.bodyChars,
|
|
107217
|
+
inputTokens: input.inputTokens + input.cacheReadTokens + input.cacheWriteTokens,
|
|
107218
|
+
cacheReadTokens: input.cacheReadTokens,
|
|
107219
|
+
cacheWriteTokens: input.cacheWriteTokens
|
|
107220
|
+
});
|
|
107221
|
+
while (observations.length > MAX_OBSERVATIONS) observations.shift();
|
|
107222
|
+
}
|
|
107223
|
+
/** 最近请求的快照(副本),最新在后。 */
|
|
107224
|
+
function readQoderCacheObservations() {
|
|
107225
|
+
return observations.map((item) => ({ ...item }));
|
|
107226
|
+
}
|
|
107015
107227
|
//#endregion
|
|
107016
107228
|
//#region src/host/providers/qoder/adapter.ts
|
|
107017
107229
|
/**
|
|
@@ -107158,7 +107370,8 @@ function readQoderCacheStats() {
|
|
|
107158
107370
|
missedInputTokens: Math.max(0, cacheTotals.promptTokens - cacheTotals.cacheReadTokens - cacheTotals.cacheWriteTokens),
|
|
107159
107371
|
cacheWriteTokens: cacheTotals.cacheWriteTokens,
|
|
107160
107372
|
requests: cacheTotals.requests,
|
|
107161
|
-
replay: { ...replayTotals }
|
|
107373
|
+
replay: { ...replayTotals },
|
|
107374
|
+
recent: readQoderCacheObservations()
|
|
107162
107375
|
};
|
|
107163
107376
|
}
|
|
107164
107377
|
/**
|
|
@@ -107181,16 +107394,28 @@ const QODER_QUEUE_WAIT_CAP_MS = 45e3;
|
|
|
107181
107394
|
* 更长的等待应当由用户自己决定要不要重试,而不是让一个回合挂在那里)。
|
|
107182
107395
|
*/
|
|
107183
107396
|
const QODER_QUEUE_WAIT_TOTAL_CAP_MS = 9e4;
|
|
107397
|
+
/** 环境开关:fast = 不等待,立即把排队错误交给宿主;wait = 按预算等待。 */
|
|
107398
|
+
function qoderQueueMode() {
|
|
107399
|
+
return process.env.DSH_QODER_QUEUE_MODE === "fast" ? "fast" : "wait";
|
|
107400
|
+
}
|
|
107401
|
+
/** 服务级排队预算(默认 90 秒;环境可调到 10 分钟,PTC/宿主的上限之外不无限延长)。 */
|
|
107402
|
+
function qoderQueueBudgetMs() {
|
|
107403
|
+
const raw = Number(process.env.DSH_QODER_QUEUE_BUDGET_MS);
|
|
107404
|
+
if (!Number.isFinite(raw) || raw <= 0) return QODER_QUEUE_WAIT_TOTAL_CAP_MS;
|
|
107405
|
+
return Math.min(6e5, Math.max(3e4, Math.floor(raw)));
|
|
107406
|
+
}
|
|
107184
107407
|
/**
|
|
107185
107408
|
* 这一次该等多久;返回 0 表示不再等。
|
|
107186
107409
|
*
|
|
107187
107410
|
* 只认上游自己给的秒数:没有建议值就不发明等待(宁可沿用既有轮询/失败路径)。
|
|
107188
107411
|
*/
|
|
107189
107412
|
function qoderQueueWaitMs(hint, waitsSoFar, waitedSoFar) {
|
|
107190
|
-
|
|
107413
|
+
const serviceUnavailable = hint?.serviceAvailable === false && (hint.queueCount ?? 0) === 0;
|
|
107414
|
+
const totalCap = serviceUnavailable ? qoderQueueBudgetMs() : QODER_QUEUE_WAIT_TOTAL_CAP_MS;
|
|
107415
|
+
if (waitsSoFar >= (serviceUnavailable ? Math.max(1, Math.ceil(totalCap / 3e4)) : 3)) return 0;
|
|
107191
107416
|
const seconds = hint?.retryAfterSeconds;
|
|
107192
107417
|
if (seconds === void 0 || !(seconds > 0)) return 0;
|
|
107193
|
-
const remaining =
|
|
107418
|
+
const remaining = totalCap - waitedSoFar;
|
|
107194
107419
|
if (remaining <= 0) return 0;
|
|
107195
107420
|
return Math.min(seconds * 1e3, QODER_QUEUE_WAIT_CAP_MS, remaining);
|
|
107196
107421
|
}
|
|
@@ -107270,10 +107495,25 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107270
107495
|
*
|
|
107271
107496
|
* 有池时轮转(核心自己做刷新);没有池时读单凭据存储(无头 host 与测试的形态)。
|
|
107272
107497
|
*/
|
|
107273
|
-
|
|
107498
|
+
cacheAffinityEnabled() {
|
|
107499
|
+
return this.options.cacheAffinity?.() !== false;
|
|
107500
|
+
}
|
|
107501
|
+
/** 当前目录里这个公开模型 id 只存在于哪些区域;两区都有时返回两个。 */
|
|
107502
|
+
modelRegions(model) {
|
|
107503
|
+
const regions = [];
|
|
107504
|
+
for (const region of ["global", "cn"]) if (this.catalog(region).some((entry) => entry.id === model)) regions.push(region);
|
|
107505
|
+
return regions;
|
|
107506
|
+
}
|
|
107507
|
+
async credentialFor(excludeIds, sessionId, model) {
|
|
107274
107508
|
const fetchFn = this.options.fetchFn ?? fetch;
|
|
107275
107509
|
if (this.accountPool !== null) {
|
|
107276
|
-
const
|
|
107510
|
+
const affinity = this.cacheAffinityEnabled() ? qoderAffinityHint(sessionId) : void 0;
|
|
107511
|
+
const modelRegions = model === void 0 ? [] : this.modelRegions(model);
|
|
107512
|
+
const regionIds = modelRegions.length === 1 ? await this.accountPool.accountIdsInRegions(modelRegions) : [];
|
|
107513
|
+
const preferred = [.../* @__PURE__ */ new Set([...regionIds, ...affinity?.preferAccountIds ?? []])];
|
|
107514
|
+
const selection = preferred.length === 0 ? void 0 : { preferAccountIds: preferred };
|
|
107515
|
+
const effective = await this.accountPool.getEffectiveCredential(excludeIds, fetchFn, selection);
|
|
107516
|
+
rememberQoderAffinity(sessionId, effective.account.id);
|
|
107277
107517
|
return {
|
|
107278
107518
|
accountId: effective.account.id,
|
|
107279
107519
|
credentials: upstreamCredentialOf$1(effective.credentials)
|
|
@@ -107384,15 +107624,17 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107384
107624
|
const triedAccounts = /* @__PURE__ */ new Set();
|
|
107385
107625
|
const triedModels = /* @__PURE__ */ new Set([options.model]);
|
|
107386
107626
|
let currentModel = options.model;
|
|
107387
|
-
let picked = await this.credentialFor(triedAccounts);
|
|
107627
|
+
let picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107388
107628
|
let queueWaits = 0;
|
|
107389
107629
|
let queueWaitedMs = 0;
|
|
107390
107630
|
const queueSleep = this.options.queueSleep ?? sleepAbortable;
|
|
107391
107631
|
const handlePreContentFailure = async (failure, responseHeaders) => {
|
|
107392
107632
|
if (isQoderQueueFailure(failure)) {
|
|
107393
107633
|
const hint = qoderQueueHintOf(failure);
|
|
107394
|
-
recordQoderQueuePosition(hint);
|
|
107395
|
-
|
|
107634
|
+
if (recordQoderQueuePosition(hint) === void 0) recordQoderQueueWait(hint);
|
|
107635
|
+
const serviceOutage = hint !== void 0 && hint.serviceAvailable === false && (hint.queueCount ?? 0) === 0;
|
|
107636
|
+
if (qoderQueueMode() === "fast") throw failure;
|
|
107637
|
+
if (!serviceOutage) {
|
|
107396
107638
|
const nextModel = this.nextQueuedFallbackModel(currentModel, triedModels, picked.credentials.region, settings);
|
|
107397
107639
|
if (nextModel !== void 0) {
|
|
107398
107640
|
triedModels.add(nextModel);
|
|
@@ -107401,15 +107643,17 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107401
107643
|
}
|
|
107402
107644
|
if (picked.accountId !== null && this.accountPool !== null) {
|
|
107403
107645
|
if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
|
|
107404
|
-
picked = await this.credentialFor(triedAccounts);
|
|
107646
|
+
picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107405
107647
|
return true;
|
|
107406
107648
|
}
|
|
107407
107649
|
}
|
|
107408
107650
|
}
|
|
107409
107651
|
const waitMs = qoderQueueWaitMs(hint, queueWaits, queueWaitedMs);
|
|
107410
107652
|
if (waitMs > 0) {
|
|
107653
|
+
activity?.pulse();
|
|
107411
107654
|
await queueSleep(waitMs, signal);
|
|
107412
107655
|
if (signal.aborted) throw new LlmError$1(t("qo.requestAborted", { provider: PROVIDER_NAME$7 }), "ABORTED");
|
|
107656
|
+
activity?.pulse();
|
|
107413
107657
|
queueWaits += 1;
|
|
107414
107658
|
queueWaitedMs += waitMs;
|
|
107415
107659
|
return true;
|
|
@@ -107423,13 +107667,13 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107423
107667
|
const reason = failure.code === "QUOTA" ? "Qoder(订阅):当前账号额度已用尽" : "Qoder(订阅) 429:上游限流或额度用尽";
|
|
107424
107668
|
await this.accountPool.markCooldown(picked.accountId, after ?? 3e5, reason).catch(() => void 0);
|
|
107425
107669
|
if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
|
|
107426
|
-
picked = await this.credentialFor(triedAccounts);
|
|
107670
|
+
picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107427
107671
|
return true;
|
|
107428
107672
|
}
|
|
107429
107673
|
} else if (failure.code === "AUTH") {
|
|
107430
107674
|
await this.accountPool.markAuthFailed(picked.accountId, failure.message).catch(() => void 0);
|
|
107431
107675
|
if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
|
|
107432
|
-
picked = await this.credentialFor(triedAccounts);
|
|
107676
|
+
picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107433
107677
|
return true;
|
|
107434
107678
|
}
|
|
107435
107679
|
}
|
|
@@ -107526,18 +107770,159 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107526
107770
|
}
|
|
107527
107771
|
throw error;
|
|
107528
107772
|
} finally {
|
|
107529
|
-
if (state.sawUsage)
|
|
107530
|
-
|
|
107531
|
-
|
|
107532
|
-
|
|
107533
|
-
|
|
107534
|
-
|
|
107773
|
+
if (state.sawUsage) {
|
|
107774
|
+
rememberQoderCacheUsage({
|
|
107775
|
+
inputTokens: state.inputTokens,
|
|
107776
|
+
outputTokens: state.outputTokens,
|
|
107777
|
+
cacheReadTokens: state.cacheReadTokens,
|
|
107778
|
+
cacheWriteTokens: state.cacheWriteTokens
|
|
107779
|
+
});
|
|
107780
|
+
recordQoderCacheObservation({
|
|
107781
|
+
model: currentModel,
|
|
107782
|
+
accountId: picked.accountId,
|
|
107783
|
+
uid: picked.credentials.uid,
|
|
107784
|
+
sessionId: options.sessionId,
|
|
107785
|
+
system: typeof normalized.system === "string" ? normalized.system : void 0,
|
|
107786
|
+
tools: normalized.tools,
|
|
107787
|
+
messages: normalized.messages.length,
|
|
107788
|
+
bodyChars: bodyText.length,
|
|
107789
|
+
inputTokens: state.inputTokens,
|
|
107790
|
+
cacheReadTokens: state.cacheReadTokens,
|
|
107791
|
+
cacheWriteTokens: state.cacheWriteTokens
|
|
107792
|
+
});
|
|
107793
|
+
}
|
|
107535
107794
|
reader.cancel().catch(() => void 0);
|
|
107536
107795
|
}
|
|
107537
107796
|
}
|
|
107538
107797
|
}
|
|
107539
107798
|
};
|
|
107540
107799
|
//#endregion
|
|
107800
|
+
//#region src/host/providers/qoder/traffic-guard.ts
|
|
107801
|
+
/**
|
|
107802
|
+
* Qoder 生成请求的每账号串行闸门。
|
|
107803
|
+
*
|
|
107804
|
+
* 上游按账号维护前缀缓存和队列;同一账号并发多个生成请求既容易把队列推深,也会让
|
|
107805
|
+
* 两个请求争抢同一段缓存。这里只在**生成路径**上串行:目录、额度等旁路请求不排队。
|
|
107806
|
+
*
|
|
107807
|
+
* 等待有上限,超时 fail-open(与 qoder2api-hub 的本地整形语义一致);这不是上游
|
|
107808
|
+
* 容量承诺,只是减少自己制造并发的本地保护。
|
|
107809
|
+
*/
|
|
107810
|
+
const GENERATION_PATHS = ["/algo/api/v2/service/pro/sse/agent_chat_generation", "/model/v1/chat/completions"];
|
|
107811
|
+
function envNumber(name, fallback) {
|
|
107812
|
+
const raw = process.env[name];
|
|
107813
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
107814
|
+
const value = Number(raw);
|
|
107815
|
+
return Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
107816
|
+
}
|
|
107817
|
+
function isGenerationRequest(input, init) {
|
|
107818
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
107819
|
+
const path = (() => {
|
|
107820
|
+
try {
|
|
107821
|
+
return new URL(url).pathname;
|
|
107822
|
+
} catch {
|
|
107823
|
+
return url;
|
|
107824
|
+
}
|
|
107825
|
+
})();
|
|
107826
|
+
if (!GENERATION_PATHS.some((segment) => path.includes(segment))) return false;
|
|
107827
|
+
return (init?.method ?? (typeof input === "object" && "method" in input ? input.method : "GET")).toUpperCase() === "POST";
|
|
107828
|
+
}
|
|
107829
|
+
function accountKey(headers) {
|
|
107830
|
+
const auth = new Headers(headers).get("authorization");
|
|
107831
|
+
return auth === null ? "anonymous" : createHash("sha256").update(auth).digest("hex").slice(0, 16);
|
|
107832
|
+
}
|
|
107833
|
+
function delay(ms) {
|
|
107834
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
107835
|
+
}
|
|
107836
|
+
/**
|
|
107837
|
+
* 包一层 fetch:生成请求按账号串行并保持最小间隔,响应体关闭后才释放槽位。
|
|
107838
|
+
*/
|
|
107839
|
+
function createQoderTrafficGuardFetch(baseFetch, options = {}) {
|
|
107840
|
+
const maxConcurrency = Math.max(1, Math.floor(options.maxConcurrency ?? envNumber("DSH_QODER_MAX_CONCURRENCY", 1)));
|
|
107841
|
+
const minGapMs = Math.max(0, options.minGapMs ?? envNumber("DSH_QODER_MIN_GAP_MS", 400));
|
|
107842
|
+
const waitMs = Math.max(0, options.waitMs ?? envNumber("DSH_QODER_GUARD_WAIT_MS", 3e4));
|
|
107843
|
+
const active = /* @__PURE__ */ new Map();
|
|
107844
|
+
const lastStarted = /* @__PURE__ */ new Map();
|
|
107845
|
+
const waiters = /* @__PURE__ */ new Map();
|
|
107846
|
+
async function acquire(key) {
|
|
107847
|
+
const started = Date.now();
|
|
107848
|
+
while ((active.get(key) ?? 0) >= maxConcurrency) {
|
|
107849
|
+
const remaining = waitMs - (Date.now() - started);
|
|
107850
|
+
if (remaining <= 0) return () => void 0;
|
|
107851
|
+
await new Promise((resolve) => {
|
|
107852
|
+
const queue = waiters.get(key) ?? [];
|
|
107853
|
+
const timer = setTimeout(() => {
|
|
107854
|
+
const index = queue.indexOf(wake);
|
|
107855
|
+
if (index >= 0) queue.splice(index, 1);
|
|
107856
|
+
resolve();
|
|
107857
|
+
}, remaining);
|
|
107858
|
+
const wake = () => {
|
|
107859
|
+
clearTimeout(timer);
|
|
107860
|
+
resolve();
|
|
107861
|
+
};
|
|
107862
|
+
queue.push(wake);
|
|
107863
|
+
waiters.set(key, queue);
|
|
107864
|
+
});
|
|
107865
|
+
}
|
|
107866
|
+
const gap = minGapMs - (Date.now() - (lastStarted.get(key) ?? 0));
|
|
107867
|
+
if (gap > 0) await delay(gap);
|
|
107868
|
+
active.set(key, (active.get(key) ?? 0) + 1);
|
|
107869
|
+
lastStarted.set(key, Date.now());
|
|
107870
|
+
let released = false;
|
|
107871
|
+
return () => {
|
|
107872
|
+
if (released) return;
|
|
107873
|
+
released = true;
|
|
107874
|
+
active.set(key, Math.max(0, (active.get(key) ?? 1) - 1));
|
|
107875
|
+
const wake = waiters.get(key)?.shift();
|
|
107876
|
+
if (wake !== void 0) wake();
|
|
107877
|
+
};
|
|
107878
|
+
}
|
|
107879
|
+
return async function guardedFetch(input, init) {
|
|
107880
|
+
if (!isGenerationRequest(input, init)) return baseFetch(input, init);
|
|
107881
|
+
const release = await acquire(accountKey(init?.headers));
|
|
107882
|
+
try {
|
|
107883
|
+
const response = await baseFetch(input, init);
|
|
107884
|
+
if (response.body === null) {
|
|
107885
|
+
release();
|
|
107886
|
+
return response;
|
|
107887
|
+
}
|
|
107888
|
+
const reader = response.body.getReader();
|
|
107889
|
+
let done = false;
|
|
107890
|
+
const finish = () => {
|
|
107891
|
+
if (!done) {
|
|
107892
|
+
done = true;
|
|
107893
|
+
release();
|
|
107894
|
+
}
|
|
107895
|
+
};
|
|
107896
|
+
const body = new ReadableStream({
|
|
107897
|
+
async pull(controller) {
|
|
107898
|
+
try {
|
|
107899
|
+
const next = await reader.read();
|
|
107900
|
+
if (next.done) {
|
|
107901
|
+
finish();
|
|
107902
|
+
controller.close();
|
|
107903
|
+
} else controller.enqueue(next.value);
|
|
107904
|
+
} catch (error) {
|
|
107905
|
+
finish();
|
|
107906
|
+
controller.error(error);
|
|
107907
|
+
}
|
|
107908
|
+
},
|
|
107909
|
+
async cancel(reason) {
|
|
107910
|
+
finish();
|
|
107911
|
+
await reader.cancel(reason);
|
|
107912
|
+
}
|
|
107913
|
+
});
|
|
107914
|
+
return new Response(body, {
|
|
107915
|
+
status: response.status,
|
|
107916
|
+
statusText: response.statusText,
|
|
107917
|
+
headers: response.headers
|
|
107918
|
+
});
|
|
107919
|
+
} catch (error) {
|
|
107920
|
+
release();
|
|
107921
|
+
throw error;
|
|
107922
|
+
}
|
|
107923
|
+
};
|
|
107924
|
+
}
|
|
107925
|
+
//#endregion
|
|
107541
107926
|
//#region src/host/providers/qoder/oauth.ts
|
|
107542
107927
|
/**
|
|
107543
107928
|
* Qoder(订阅)线路的登录:浏览器设备流(仅全球区)+ PAT 兑换 + 令牌刷新。
|
|
@@ -108141,8 +108526,14 @@ var QoderAccountPool = class extends AccountPoolCore {
|
|
|
108141
108526
|
* 核心在这里做轮转、冷却、可用性判断与刷新;本方法只多给适配器一件事:
|
|
108142
108527
|
* 一次请求内换过账号时,把试过的账号排除掉。
|
|
108143
108528
|
*/
|
|
108144
|
-
async getEffectiveCredential(excludeIds, fetchFn = fetch) {
|
|
108145
|
-
return this.getEffectiveAccount(excludeIds, fetchFn);
|
|
108529
|
+
async getEffectiveCredential(excludeIds, fetchFn = fetch, selection) {
|
|
108530
|
+
return this.getEffectiveAccount(excludeIds, fetchFn, false, void 0, selection);
|
|
108531
|
+
}
|
|
108532
|
+
/** 指定区域的账号 id(只做偏好,不做硬过滤;核心仍会跳过冷却/已试账号)。 */
|
|
108533
|
+
async accountIdsInRegions(regions) {
|
|
108534
|
+
if (regions.length === 0) return [];
|
|
108535
|
+
const wanted = new Set(regions);
|
|
108536
|
+
return (await this.read()).accounts.filter((account) => wanted.has(account.region)).map((account) => account.id);
|
|
108146
108537
|
}
|
|
108147
108538
|
/**
|
|
108148
108539
|
* 一次额度读属于哪个账号,连同读它用的凭据。
|
|
@@ -143731,7 +144122,7 @@ const Config = z$1.object({
|
|
|
143731
144122
|
advisorModel: z$1.string().default("").volatile().description("新对话的默认顾问模型。"),
|
|
143732
144123
|
advisorReasoningEffort: z$1.string().default("auto").volatile().description("顾问模型的推理强度;auto 使用模型默认值。"),
|
|
143733
144124
|
advisorMaxTokens: z$1.number().min(256).max(32768).step(1).default(4096).volatile().description("顾问单次回复的最大 token 数。"),
|
|
143734
|
-
advisorTimeoutMs: z$1.number().min(1e3).max(
|
|
144125
|
+
advisorTimeoutMs: z$1.number().min(1e3).max(54e4).step(1).default(54e4).volatile().description("顾问单次咨询的总超时毫秒数。"),
|
|
143735
144126
|
advisorMaxRetries: z$1.number().min(0).max(3).step(1).default(1).volatile().description("顾问遇到临时错误时的最大追加重试次数。"),
|
|
143736
144127
|
advisorContextTokenBudget: z$1.number().min(8e3).max(1e6).step(1).default(1e5).volatile().description("转发给顾问的对话上下文预算。"),
|
|
143737
144128
|
advisorSessionTokenBudget: z$1.number().min(0).max(1e7).step(1).default(2e5).volatile().description("单个对话累计可消耗的顾问 token 上限;0 表示不限制。"),
|
|
@@ -144417,9 +144808,10 @@ function apply(ctx, pluginConfig = {}) {
|
|
|
144417
144808
|
providerId: PROVIDER_ID$7,
|
|
144418
144809
|
label: PROVIDER_NAME$7,
|
|
144419
144810
|
adapter: new QoderAdapter(qoderStore, qoderModelSettings, qoderPreferences, {
|
|
144420
|
-
fetchFn: modelFetch[PROVIDER_ID$7],
|
|
144811
|
+
fetchFn: createQoderTrafficGuardFetch(modelFetch[PROVIDER_ID$7]),
|
|
144421
144812
|
attachments: ctx.attachments,
|
|
144422
|
-
accountPool: qoderAccountPool
|
|
144813
|
+
accountPool: qoderAccountPool,
|
|
144814
|
+
cacheAffinity: () => resolveCacheAffinityEnabled(pluginConfig, process.env)
|
|
144423
144815
|
})
|
|
144424
144816
|
});
|
|
144425
144817
|
const disposeQoderRoutes = registerQoderRoutes(ctx, qoderSettingsSource(qoderPreferences, qoderModelSettings), {
|