@eddyskywalker/dsh-chatgpt-subscription 1.0.0 → 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 +92 -11
- package/lib/client.js.map +1 -1
- package/lib/codemode.js +139 -7
- package/lib/index.js +545 -90
- package/lib/{preset-sync-DWOAwSyl.js → preset-sync-RBsYhDY3.js} +2 -1
- package/lib/{tool-result-pruner-C6CDvZtG.js → tool-result-pruner-DsaDg_l1.js} +4 -3
- package/lib/tool-result-pruner.js +1 -1
- package/lib/types/client/features/progress-updates/locales.d.ts +3 -3
- 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/advisor/catalog-route.d.ts +20 -0
- package/lib/types/host/runtime/advisor/catalog-route.d.ts.map +1 -0
- package/lib/types/host/runtime/advisor/index.d.ts.map +1 -1
- package/lib/types/host/runtime/advisor/selection-store.d.ts +9 -1
- package/lib/types/host/runtime/advisor/selection-store.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 +5 -0
- package/lib/types/host/runtime/codemode/transport.d.ts.map +1 -1
- package/lib/types/host/runtime/deepseek-v41-flash/state-anchor.d.ts +8 -0
- package/lib/types/host/runtime/deepseek-v41-flash/state-anchor.d.ts.map +1 -1
- package/lib/types/host/runtime/open-models/profiles.d.ts.map +1 -1
- package/lib/types/host/runtime/open-models/state-anchor.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.
|
|
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`;
|
|
@@ -14491,6 +14491,39 @@ Call advisor BEFORE substantive work: before writing, editing, committing to an
|
|
|
14491
14491
|
|
|
14492
14492
|
Ask the user instead whenever the gap is what the user wants — scope, priorities, destructive actions, product behavior — and use tools for facts about the world: the advisor cannot answer what the user wants, and its reply never grants a decision the user owns. Never put the same question to both the advisor and the user. Give the advice serious weight. If a step fails empirically or primary-source evidence contradicts a specific claim, adapt. If your evidence and the advisor conflict, state the conflict and call advisor once more instead of silently switching. If disabled or unavailable, continue with your own judgment.`;
|
|
14493
14493
|
//#endregion
|
|
14494
|
+
//#region src/host/runtime/advisor/catalog-route.ts
|
|
14495
|
+
/**
|
|
14496
|
+
* Pick the first advertised model without changing model-selection order.
|
|
14497
|
+
* A provider that cannot list its catalog is skipped rather than failing the
|
|
14498
|
+
* whole fallback, because one disabled route must not hide the next one.
|
|
14499
|
+
* @param catalog - live LLM registry, absent in isolated tests.
|
|
14500
|
+
* @returns the first usable provider/model route, or null when none is listed.
|
|
14501
|
+
*/
|
|
14502
|
+
async function firstAvailableAdvisorRoute(catalog) {
|
|
14503
|
+
if (catalog === void 0) return null;
|
|
14504
|
+
let providers;
|
|
14505
|
+
try {
|
|
14506
|
+
providers = catalog.listProviders();
|
|
14507
|
+
} catch {
|
|
14508
|
+
return null;
|
|
14509
|
+
}
|
|
14510
|
+
for (const provider of providers) {
|
|
14511
|
+
if (typeof provider.id !== "string" || provider.id === "") continue;
|
|
14512
|
+
let models;
|
|
14513
|
+
try {
|
|
14514
|
+
models = await catalog.listModels(provider.id);
|
|
14515
|
+
} catch {
|
|
14516
|
+
continue;
|
|
14517
|
+
}
|
|
14518
|
+
const model = models.find((entry) => typeof entry.id === "string" && entry.id !== "");
|
|
14519
|
+
if (model !== void 0 && typeof model.id === "string") return {
|
|
14520
|
+
provider: provider.id,
|
|
14521
|
+
model: model.id
|
|
14522
|
+
};
|
|
14523
|
+
}
|
|
14524
|
+
return null;
|
|
14525
|
+
}
|
|
14526
|
+
//#endregion
|
|
14494
14527
|
//#region src/host/runtime/advisor/selection-store.ts
|
|
14495
14528
|
const ROUTE_SCHEMA = z.object({
|
|
14496
14529
|
provider: z.string(),
|
|
@@ -14519,7 +14552,8 @@ const SESSION_SCHEMA = z.object({
|
|
|
14519
14552
|
const DOCUMENT_SCHEMA = z.object({
|
|
14520
14553
|
defaults: z.object({
|
|
14521
14554
|
enabled: z.boolean().optional(),
|
|
14522
|
-
route: ROUTE_SCHEMA.optional()
|
|
14555
|
+
route: ROUTE_SCHEMA.optional(),
|
|
14556
|
+
recentRoute: ROUTE_SCHEMA.optional()
|
|
14523
14557
|
}).default({}),
|
|
14524
14558
|
sessions: z.record(z.string(), SESSION_SCHEMA).default({})
|
|
14525
14559
|
});
|
|
@@ -14549,22 +14583,34 @@ function spentTokens$1(usage) {
|
|
|
14549
14583
|
var AdvisorSelectionStore = class {
|
|
14550
14584
|
defaults;
|
|
14551
14585
|
lineage;
|
|
14586
|
+
firstRoute;
|
|
14552
14587
|
store;
|
|
14553
14588
|
/** Usage writes queue here: they share one conversation total. */
|
|
14554
14589
|
pendingUsage = Promise.resolve();
|
|
14555
|
-
|
|
14590
|
+
/** A catalog fallback is a seed, not a user choice: resolve it once per process. */
|
|
14591
|
+
catalogRoute;
|
|
14592
|
+
constructor(defaults, filePath, lineage, firstRoute) {
|
|
14556
14593
|
this.defaults = defaults;
|
|
14557
14594
|
this.lineage = lineage;
|
|
14595
|
+
this.firstRoute = firstRoute;
|
|
14558
14596
|
this.store = new FilePreferencesStore(validateDocument, filePath ?? path.join(dshHomeDir(), "storages", "dsh-chatgpt-subscription-advisor.json"));
|
|
14559
14597
|
}
|
|
14560
14598
|
/** The user-level default: an explicit saved choice, else the configured seed. */
|
|
14561
14599
|
base(fallback) {
|
|
14562
14600
|
const saved = this.store.get().defaults;
|
|
14563
14601
|
return {
|
|
14564
|
-
enabled: saved.enabled ??
|
|
14565
|
-
route: saved.route ?? fallback.selection
|
|
14602
|
+
enabled: fallback.enabled || (saved.enabled ?? false),
|
|
14603
|
+
route: saved.route ?? fallback.selection,
|
|
14604
|
+
recentRoute: saved.recentRoute ?? null
|
|
14566
14605
|
};
|
|
14567
14606
|
}
|
|
14607
|
+
/** Resolve the first routable model only when an enabled session has no selection. */
|
|
14608
|
+
async firstAvailableRoute() {
|
|
14609
|
+
if (this.catalogRoute !== void 0) return this.catalogRoute;
|
|
14610
|
+
const route = await this.firstRoute?.().catch(() => null) ?? null;
|
|
14611
|
+
if (route !== null) this.catalogRoute = route;
|
|
14612
|
+
return route;
|
|
14613
|
+
}
|
|
14568
14614
|
/**
|
|
14569
14615
|
* The effective state for one session: its own choice first, then each
|
|
14570
14616
|
* ancestor's, field by field, and finally the user-level default.
|
|
@@ -14586,12 +14632,15 @@ var AdvisorSelectionStore = class {
|
|
|
14586
14632
|
if (route === void 0) route = entry.route;
|
|
14587
14633
|
if (enabled !== void 0 && route !== void 0) break;
|
|
14588
14634
|
}
|
|
14635
|
+
const effectiveEnabled = enabled ?? userDefault.enabled;
|
|
14636
|
+
const userRoute = userDefault.recentRoute ?? userDefault.route;
|
|
14637
|
+
const catalogRoute = effectiveEnabled && userRoute === null ? await this.firstAvailableRoute() : null;
|
|
14589
14638
|
return {
|
|
14590
14639
|
sessionId,
|
|
14591
|
-
enabled:
|
|
14592
|
-
selection: route ?? userDefault.route,
|
|
14640
|
+
enabled: effectiveEnabled,
|
|
14641
|
+
selection: route ?? (effectiveEnabled ? userRoute ?? catalogRoute : userDefault.route),
|
|
14593
14642
|
defaultEnabled: userDefault.enabled,
|
|
14594
|
-
defaultSelection:
|
|
14643
|
+
defaultSelection: userRoute ?? catalogRoute,
|
|
14595
14644
|
inherited: enabled === void 0 && route === void 0,
|
|
14596
14645
|
limits: {
|
|
14597
14646
|
maxTokens: fallback.maxTokens,
|
|
@@ -14621,15 +14670,24 @@ var AdvisorSelectionStore = class {
|
|
|
14621
14670
|
if (patch.selection !== void 0) if (patch.selection === null) delete next.route;
|
|
14622
14671
|
else next.route = patch.selection;
|
|
14623
14672
|
sessions[sessionId] = next;
|
|
14624
|
-
|
|
14673
|
+
const recent = patch.selection === void 0 || patch.selection === null ? void 0 : {
|
|
14674
|
+
...this.store.get().defaults,
|
|
14675
|
+
recentRoute: patch.selection
|
|
14676
|
+
};
|
|
14677
|
+
await this.commit(sessions, recent);
|
|
14625
14678
|
return this.state(sessionId);
|
|
14626
14679
|
}
|
|
14627
14680
|
/** Move the user-level default; a later session that never overrode it follows this. */
|
|
14628
14681
|
async setDefault(route, enabled) {
|
|
14629
14682
|
await this.store.hydrate();
|
|
14630
14683
|
const defaults = { ...this.store.get().defaults };
|
|
14631
|
-
if (route === null)
|
|
14632
|
-
|
|
14684
|
+
if (route === null) {
|
|
14685
|
+
delete defaults.route;
|
|
14686
|
+
delete defaults.recentRoute;
|
|
14687
|
+
} else {
|
|
14688
|
+
defaults.route = route;
|
|
14689
|
+
defaults.recentRoute = route;
|
|
14690
|
+
}
|
|
14633
14691
|
if (enabled !== void 0) defaults.enabled = enabled;
|
|
14634
14692
|
await this.store.update({ defaults });
|
|
14635
14693
|
}
|
|
@@ -14698,9 +14756,12 @@ var AdvisorSelectionStore = class {
|
|
|
14698
14756
|
}
|
|
14699
14757
|
}
|
|
14700
14758
|
/** Bounded map: the 512 most recently touched sessions survive. */
|
|
14701
|
-
async commit(sessions) {
|
|
14759
|
+
async commit(sessions, defaults) {
|
|
14702
14760
|
const retained = Object.entries(sessions).sort((a, b) => b[1].updatedAt - a[1].updatedAt).slice(0, 512);
|
|
14703
|
-
await this.store.update({ sessions: Object.fromEntries(retained) }
|
|
14761
|
+
await this.store.update(defaults === void 0 ? { sessions: Object.fromEntries(retained) } : {
|
|
14762
|
+
sessions: Object.fromEntries(retained),
|
|
14763
|
+
defaults
|
|
14764
|
+
});
|
|
14704
14765
|
}
|
|
14705
14766
|
};
|
|
14706
14767
|
//#endregion
|
|
@@ -15104,11 +15165,11 @@ function installAdvisor(ctx, config) {
|
|
|
15104
15165
|
enabled: value(config.advisorEnabled, false),
|
|
15105
15166
|
selection: routeOf$1(config),
|
|
15106
15167
|
maxTokens: value(config.advisorMaxTokens, 4096),
|
|
15107
|
-
timeoutMs: value(config.advisorTimeoutMs,
|
|
15168
|
+
timeoutMs: value(config.advisorTimeoutMs, 54e4),
|
|
15108
15169
|
maxRetries: value(config.advisorMaxRetries, 1),
|
|
15109
15170
|
contextTokenBudget: value(config.advisorContextTokenBudget, 1e5),
|
|
15110
15171
|
sessionTokenBudget: value(config.advisorSessionTokenBudget, 2e5)
|
|
15111
|
-
}), void 0, (sessionId) => sessionHeaderOf(ctx, sessionId));
|
|
15172
|
+
}), void 0, (sessionId) => sessionHeaderOf(ctx, sessionId), () => firstAvailableAdvisorRoute(ctx.llm));
|
|
15112
15173
|
const service = new AdvisorService(store, ctx.llm);
|
|
15113
15174
|
const disposeTool = ctx.tools.register(defineTool({
|
|
15114
15175
|
name: CONSULT_ADVISOR_TOOL_NAME,
|
|
@@ -15288,7 +15349,7 @@ const FIBER_UNLOADING = 5;
|
|
|
15288
15349
|
const RESTART_TIMEOUT_MS = 1e4;
|
|
15289
15350
|
/** Gap between restart-state samples. */
|
|
15290
15351
|
const RESTART_POLL_MS = 10;
|
|
15291
|
-
function delay$
|
|
15352
|
+
function delay$2(ms) {
|
|
15292
15353
|
return new Promise((resolve) => {
|
|
15293
15354
|
setTimeout(resolve, ms);
|
|
15294
15355
|
});
|
|
@@ -15385,7 +15446,7 @@ var SearchProviderSwitcher = class {
|
|
|
15385
15446
|
if (sawRestart && state === FIBER_ACTIVE) return;
|
|
15386
15447
|
await fiber.await();
|
|
15387
15448
|
if (fiber.state === FIBER_ACTIVE) return;
|
|
15388
|
-
await delay$
|
|
15449
|
+
await delay$2(RESTART_POLL_MS);
|
|
15389
15450
|
}
|
|
15390
15451
|
}
|
|
15391
15452
|
findWebEntry() {
|
|
@@ -29156,7 +29217,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
|
|
|
29156
29217
|
await Promise.race([
|
|
29157
29218
|
turn.queue.wait(signal),
|
|
29158
29219
|
turn.bridge.waitForWork(signal),
|
|
29159
|
-
delay(200)
|
|
29220
|
+
delay$1(200)
|
|
29160
29221
|
]);
|
|
29161
29222
|
}
|
|
29162
29223
|
} finally {
|
|
@@ -29181,8 +29242,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
|
|
|
29181
29242
|
const options = readPermissionOptions(params);
|
|
29182
29243
|
const answer = () => options.find((option) => option.kind === "allow_once")?.optionId ?? options.find((option) => option.kind === "allow_always")?.optionId;
|
|
29183
29244
|
const deny = () => options.find((option) => option.kind === "reject_once")?.optionId ?? options.find((option) => option.kind === "reject_always")?.optionId;
|
|
29184
|
-
|
|
29185
|
-
if ((typeof toolCall?.name === "string" ? toolCall.name : "").startsWith(`mcp_dsh-bridge_`)) return answer();
|
|
29245
|
+
if (isBridgeToolCall(asRecord$19(params.toolCall))) return answer();
|
|
29186
29246
|
const settings = await this.options.settings.read();
|
|
29187
29247
|
if (settings.nativeToolPolicy === "cancel") return deny();
|
|
29188
29248
|
return settings.permissionPolicy === "allow" ? answer() : deny();
|
|
@@ -29726,9 +29786,39 @@ function assertNoSamplingControls(options) {
|
|
|
29726
29786
|
* @param update - One `session/update` payload.
|
|
29727
29787
|
* @returns The call's id and name when it is a native call; undefined for the bridge.
|
|
29728
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
|
+
}
|
|
29729
29819
|
function readNativeToolCall(update) {
|
|
29820
|
+
if (isBridgeToolCall(update)) return void 0;
|
|
29730
29821
|
const name = typeof update.name === "string" ? update.name : "";
|
|
29731
|
-
if (name === "" || name.startsWith(`mcp_dsh-bridge_`)) return void 0;
|
|
29732
29822
|
return {
|
|
29733
29823
|
callId: typeof update.toolCallId === "string" ? update.toolCallId : "",
|
|
29734
29824
|
name
|
|
@@ -29930,7 +30020,7 @@ function abortError$1() {
|
|
|
29930
30020
|
error.name = "AbortError";
|
|
29931
30021
|
return error;
|
|
29932
30022
|
}
|
|
29933
|
-
function delay(ms) {
|
|
30023
|
+
function delay$1(ms) {
|
|
29934
30024
|
return new Promise((resolve) => {
|
|
29935
30025
|
setTimeout(resolve, ms).unref?.();
|
|
29936
30026
|
});
|
|
@@ -103710,13 +103800,14 @@ const QODER_AUTH_FILE = "user";
|
|
|
103710
103800
|
/** qodercli 的 machine id 文件(36 字符 UUID;同时也是 adopt 文件的解密钥源)。 */
|
|
103711
103801
|
const QODER_MACHINE_ID_FILE = "machine_id";
|
|
103712
103802
|
/**
|
|
103713
|
-
* 输出上限兜底:
|
|
103803
|
+
* 输出上限兜底:32768。
|
|
103714
103804
|
*
|
|
103715
|
-
*
|
|
103716
|
-
*
|
|
103717
|
-
*
|
|
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;发得更大不会换来更长输出,只会在模型之前被拒。
|
|
103718
103809
|
*/
|
|
103719
|
-
const QODER_MAX_OUTPUT_TOKENS =
|
|
103810
|
+
const QODER_MAX_OUTPUT_TOKENS = 32768;
|
|
103720
103811
|
/**
|
|
103721
103812
|
* 上下文窗口兜底(目录缺 `context_config` 时)。
|
|
103722
103813
|
*
|
|
@@ -103846,6 +103937,20 @@ function isRecord$44(value) {
|
|
|
103846
103937
|
function nonEmptyString$2(value) {
|
|
103847
103938
|
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
103848
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
|
+
}
|
|
103849
103954
|
/**
|
|
103850
103955
|
* 上游 `display_name` → 公开模型 id:去掉全部空白字符
|
|
103851
103956
|
* (逐字 pi-provider `toQoderModelId`:`replace(/\s+/g, "")`)。
|
|
@@ -104025,7 +104130,11 @@ function entryFromQoderRecord(record, region) {
|
|
|
104025
104130
|
supportsImages: record.is_vl === true,
|
|
104026
104131
|
defaultContextWindow: contextWindowFromRecord(record, region),
|
|
104027
104132
|
defaultMaxTokens: QODER_MAX_OUTPUT_TOKENS,
|
|
104028
|
-
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) }
|
|
104029
104138
|
});
|
|
104030
104139
|
}
|
|
104031
104140
|
/**
|
|
@@ -104371,12 +104480,16 @@ function describeQoderModel(entry, prefix) {
|
|
|
104371
104480
|
const thinking = entry.reasoningEfforts.length === 0 ? entry.thinkingDisableable ? "思考可开关" : "思考恒开" : entry.thinkingDisableable ? "思考可关闭" : "思考恒开";
|
|
104372
104481
|
const effort = entry.reasoningEfforts.length === 0 ? "无档位字段" : "档位 " + entry.reasoningEfforts.join("/");
|
|
104373
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 + ")");
|
|
104374
104485
|
return (prefix === void 0 || prefix === "" ? "" : prefix + ":") + [
|
|
104375
104486
|
thinking,
|
|
104376
104487
|
effort,
|
|
104377
104488
|
modality,
|
|
104378
|
-
"上下文 " + entry.defaultContextWindow
|
|
104379
|
-
|
|
104489
|
+
"上下文 " + entry.defaultContextWindow,
|
|
104490
|
+
price,
|
|
104491
|
+
promotion
|
|
104492
|
+
].filter((part) => part !== void 0).join("|");
|
|
104380
104493
|
}
|
|
104381
104494
|
function positiveInt(value) {
|
|
104382
104495
|
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
|
|
@@ -104834,12 +104947,12 @@ function markQoderLegacyProbeDone() {
|
|
|
104834
104947
|
* - {@link generateQoderRuntimeAuthFields} —— runtime-fields.json;
|
|
104835
104948
|
* - {@link decryptQoderAdoptPayload} —— credential.json;
|
|
104836
104949
|
* - {@link encodeQoderBody} —— infer-user-no-org.json 的 `body_string`;
|
|
104837
|
-
* - {@link buildQoderCosyHeaders} ——
|
|
104950
|
+
* - {@link buildQoderCosyHeaders} —— 最终发送头集合与签名。
|
|
104838
104951
|
*
|
|
104839
|
-
*
|
|
104840
|
-
* `Cosy-
|
|
104841
|
-
* `
|
|
104842
|
-
*
|
|
104952
|
+
* 官方 1.1.74 的**最终发送层**会在无真实 UMID 时移除 `Cosy-MachineToken` /
|
|
104953
|
+
* `Cosy-MachineType`(不能用 machine_id 冒充 machine token),再补
|
|
104954
|
+
* `Cosy-MachineOS`;这一层不在 pinned WASM 的 18/22-header 核心向量里,
|
|
104955
|
+
* 所以 fixture 只能锁核心,不能锁最终网络头。
|
|
104843
104956
|
*
|
|
104844
104957
|
* 本文件不做任何网络 I/O,也不持有凭据:它吃的是调用方递进来的材料,吐出的是
|
|
104845
104958
|
* 头与 body。machine id 的读取顺序(qodercli 原配 → 本线路自己的文件 → 内存生成)
|
|
@@ -104991,6 +105104,15 @@ function cosySignedPath(url) {
|
|
|
104991
105104
|
* payload 的字段顺序固定(`version, requestId, info, cosyVersion, ideVersion`——
|
|
104992
105105
|
* 它参与签名,散装键序就是一次签名漂移),所以这里按字面量顺序写键而不是用 Map。
|
|
104993
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
|
+
}
|
|
104994
105116
|
function buildQoderCosyHeaders(identity, options) {
|
|
104995
105117
|
if (identity.uid.trim() === "") throw new Error("Qoder COSY:uid 不能为空");
|
|
104996
105118
|
const runtime = generateQoderRuntimeAuthFields(identity.rawUserInfo, options.entropy ?? defaultEntropy);
|
|
@@ -105017,8 +105139,7 @@ function buildQoderCosyHeaders(identity, options) {
|
|
|
105017
105139
|
"Cosy-Date": unixSeconds,
|
|
105018
105140
|
"Cosy-Key": runtime.key,
|
|
105019
105141
|
"Cosy-MachineId": identity.machineId,
|
|
105020
|
-
"Cosy-
|
|
105021
|
-
"Cosy-MachineType": "5",
|
|
105142
|
+
"Cosy-MachineOS": qoderMachineOS(),
|
|
105022
105143
|
"Cosy-Scene": COSY_SCENE.scene,
|
|
105023
105144
|
"Cosy-User": identity.uid,
|
|
105024
105145
|
"Cosy-Version": identity.cosyVersion,
|
|
@@ -106091,6 +106212,32 @@ function resolveQoderThinking(requested, request) {
|
|
|
106091
106212
|
};
|
|
106092
106213
|
}
|
|
106093
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
|
+
/**
|
|
106094
106241
|
* 会话与请求的稳定 id(缓存亲和)。
|
|
106095
106242
|
*
|
|
106096
106243
|
* 逐字 pi-provider \`stream.ts\` 的设计:\`session_id\` 的稳定段来自账号+模型的哈希,
|
|
@@ -106179,7 +106326,8 @@ function buildQoderChatRequest(options, images, request, context) {
|
|
|
106179
106326
|
}
|
|
106180
106327
|
const entry = context.entry;
|
|
106181
106328
|
const modelKey = context.modelKey;
|
|
106182
|
-
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));
|
|
106183
106331
|
const tools = options.tools && options.tools.length > 0 ? options.tools.map((tool) => ({
|
|
106184
106332
|
type: "function",
|
|
106185
106333
|
function: {
|
|
@@ -106188,6 +106336,7 @@ function buildQoderChatRequest(options, images, request, context) {
|
|
|
106188
106336
|
parameters: stripMetaSchema$1(tool.parameters)
|
|
106189
106337
|
}
|
|
106190
106338
|
})) : [];
|
|
106339
|
+
for (let index = 0; index < messages.length; index++) messages[index] = guardQoderWireMessage(messages[index]);
|
|
106191
106340
|
const recordId = qoderChatRecordId(modelKey, messages, tools.length > 0 ? tools : void 0, maxTokens);
|
|
106192
106341
|
const thinking = resolveQoderThinking(options.reasoningEffort, request);
|
|
106193
106342
|
const parameters = { max_tokens: maxTokens };
|
|
@@ -106238,7 +106387,7 @@ function buildQoderChatRequest(options, images, request, context) {
|
|
|
106238
106387
|
session_type: "qodercli",
|
|
106239
106388
|
source: 1,
|
|
106240
106389
|
stream: true,
|
|
106241
|
-
system:
|
|
106390
|
+
system: "",
|
|
106242
106391
|
task_id: "common",
|
|
106243
106392
|
tools,
|
|
106244
106393
|
version: "3"
|
|
@@ -106316,6 +106465,10 @@ function closeCurrent$2(state) {
|
|
|
106316
106465
|
function closeToolCalls$1(state) {
|
|
106317
106466
|
const out = [];
|
|
106318
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
|
+
}
|
|
106319
106472
|
const block = {
|
|
106320
106473
|
type: "tool-call",
|
|
106321
106474
|
id: toToolCallId(call.id),
|
|
@@ -106406,18 +106559,20 @@ function applyToolDelta$1(entry, state) {
|
|
|
106406
106559
|
let call = state.toolCalls.get(wireIndex);
|
|
106407
106560
|
const incomingId = asString$12(entry.id);
|
|
106408
106561
|
if (call !== void 0 && incomingId !== void 0 && call.id !== "call_" + wireIndex && incomingId !== call.id) {
|
|
106409
|
-
|
|
106410
|
-
|
|
106411
|
-
|
|
106412
|
-
|
|
106413
|
-
|
|
106414
|
-
|
|
106415
|
-
|
|
106416
|
-
|
|
106417
|
-
|
|
106418
|
-
|
|
106419
|
-
|
|
106420
|
-
|
|
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
|
+
}
|
|
106421
106576
|
state.toolCalls.delete(wireIndex);
|
|
106422
106577
|
call = void 0;
|
|
106423
106578
|
}
|
|
@@ -106436,14 +106591,29 @@ function applyToolDelta$1(entry, state) {
|
|
|
106436
106591
|
const argsDelta = asString$12(fn?.arguments) ?? "";
|
|
106437
106592
|
if (argsDelta !== "") call.arguments += argsDelta;
|
|
106438
106593
|
if (!call.started) {
|
|
106594
|
+
if (call.name === "") return out;
|
|
106439
106595
|
call.started = true;
|
|
106440
106596
|
state.hasToolCall = true;
|
|
106441
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
|
+
};
|
|
106442
106604
|
out.push({
|
|
106443
106605
|
type: "block-start",
|
|
106444
106606
|
index: call.blockIndex,
|
|
106445
106607
|
blockType: "tool-call"
|
|
106446
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;
|
|
106447
106617
|
}
|
|
106448
106618
|
if (argsDelta !== "" || out.length > 0) out.push({
|
|
106449
106619
|
type: "tool-call-delta",
|
|
@@ -106760,6 +106930,17 @@ function collectQoderFailureFacts(node, facts, depth, budget) {
|
|
|
106760
106930
|
collectQoderFailureFacts(value, facts, depth + 1, budget);
|
|
106761
106931
|
}
|
|
106762
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;
|
|
106763
106944
|
/** 文本里是否明确指出了排队 / 资源不足(不含笼统的 rate limit,免得改写普通 429)。 */
|
|
106764
106945
|
function hasQoderQueueWording(text) {
|
|
106765
106946
|
return /RESO?URCE_LIMIT|REOSURCE_LIMIT|\b10605\b|queueCount|queue_count|isQueued|is_queued|正在排队|排队等待|模型排队|queue(?:d|ing)\b/i.test(text);
|
|
@@ -106779,9 +106960,16 @@ function isQoderResourceLimited(facts, status, detail = "") {
|
|
|
106779
106960
|
if (facts.codes.includes("10605")) return true;
|
|
106780
106961
|
const combinedText = [detail, ...facts.messages ?? []].join(" ");
|
|
106781
106962
|
if (/RESO?URCE_LIMIT|REOSURCE_LIMIT|\b10605\b/i.test(combinedText)) return true;
|
|
106963
|
+
if (isQoderModelUnavailable(facts, status, detail)) return true;
|
|
106782
106964
|
if (status !== void 0 && status !== 403) return false;
|
|
106783
106965
|
return facts.serviceAvailable === false || facts.isQueued === true || facts.queueCount !== void 0 && facts.queueCount > 0 || hasQoderQueueWording(combinedText);
|
|
106784
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
|
+
}
|
|
106785
106973
|
const QODER_QUEUE_FAILURE_MARKER = /* @__PURE__ */ new WeakSet();
|
|
106786
106974
|
/**
|
|
106787
106975
|
* 排队失败里上游报的结构化容量事实(queueCount / retryAfterSeconds / serviceAvailable)。
|
|
@@ -106852,6 +107040,14 @@ function qoderResourceLimitMessage(facts, status) {
|
|
|
106852
107040
|
if (facts.modelKey !== void 0) details.push("modelKey " + facts.modelKey);
|
|
106853
107041
|
return "Qoder(订阅) 上游资源不足,这个模型正在排队" + (details.length === 0 ? "" : ":" + details.join(",")) + "。这是上游容量问题,不是凭据问题——账号仍是登录状态,不需要重新登录;稍后重试即可。";
|
|
106854
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
|
+
}
|
|
106855
107051
|
/** 上游额度用尽的文案:额度恢复前这一请求不会成功,并给出上游给的购买/升级页。 */
|
|
106856
107052
|
function qoderQuotaExhaustedMessage(facts, status) {
|
|
106857
107053
|
const details = [];
|
|
@@ -106902,6 +107098,16 @@ function classifyQoderFailureFacts(status, detail, facts) {
|
|
|
106902
107098
|
const options = status === void 0 ? {} : { status };
|
|
106903
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);
|
|
106904
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
|
+
}
|
|
106905
107111
|
if (isQoderResourceLimited(facts, status, detail)) {
|
|
106906
107112
|
const after = facts.retryAfterSeconds;
|
|
106907
107113
|
const err = new LlmError$1(qoderResourceLimitMessage(facts, status) + suffix, "SERVER", after === void 0 || after <= 0 ? options : {
|
|
@@ -106948,9 +107154,76 @@ function currentQoderQueuePosition(now = Date.now()) {
|
|
|
106948
107154
|
return lastObserved;
|
|
106949
107155
|
}
|
|
106950
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
|
+
}
|
|
106951
107172
|
function clearQoderQueuePosition() {
|
|
106952
107173
|
lastObserved = void 0;
|
|
106953
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
|
+
}
|
|
106954
107227
|
//#endregion
|
|
106955
107228
|
//#region src/host/providers/qoder/adapter.ts
|
|
106956
107229
|
/**
|
|
@@ -107097,7 +107370,8 @@ function readQoderCacheStats() {
|
|
|
107097
107370
|
missedInputTokens: Math.max(0, cacheTotals.promptTokens - cacheTotals.cacheReadTokens - cacheTotals.cacheWriteTokens),
|
|
107098
107371
|
cacheWriteTokens: cacheTotals.cacheWriteTokens,
|
|
107099
107372
|
requests: cacheTotals.requests,
|
|
107100
|
-
replay: { ...replayTotals }
|
|
107373
|
+
replay: { ...replayTotals },
|
|
107374
|
+
recent: readQoderCacheObservations()
|
|
107101
107375
|
};
|
|
107102
107376
|
}
|
|
107103
107377
|
/**
|
|
@@ -107120,16 +107394,28 @@ const QODER_QUEUE_WAIT_CAP_MS = 45e3;
|
|
|
107120
107394
|
* 更长的等待应当由用户自己决定要不要重试,而不是让一个回合挂在那里)。
|
|
107121
107395
|
*/
|
|
107122
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
|
+
}
|
|
107123
107407
|
/**
|
|
107124
107408
|
* 这一次该等多久;返回 0 表示不再等。
|
|
107125
107409
|
*
|
|
107126
107410
|
* 只认上游自己给的秒数:没有建议值就不发明等待(宁可沿用既有轮询/失败路径)。
|
|
107127
107411
|
*/
|
|
107128
107412
|
function qoderQueueWaitMs(hint, waitsSoFar, waitedSoFar) {
|
|
107129
|
-
|
|
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;
|
|
107130
107416
|
const seconds = hint?.retryAfterSeconds;
|
|
107131
107417
|
if (seconds === void 0 || !(seconds > 0)) return 0;
|
|
107132
|
-
const remaining =
|
|
107418
|
+
const remaining = totalCap - waitedSoFar;
|
|
107133
107419
|
if (remaining <= 0) return 0;
|
|
107134
107420
|
return Math.min(seconds * 1e3, QODER_QUEUE_WAIT_CAP_MS, remaining);
|
|
107135
107421
|
}
|
|
@@ -107209,10 +107495,25 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107209
107495
|
*
|
|
107210
107496
|
* 有池时轮转(核心自己做刷新);没有池时读单凭据存储(无头 host 与测试的形态)。
|
|
107211
107497
|
*/
|
|
107212
|
-
|
|
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) {
|
|
107213
107508
|
const fetchFn = this.options.fetchFn ?? fetch;
|
|
107214
107509
|
if (this.accountPool !== null) {
|
|
107215
|
-
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);
|
|
107216
107517
|
return {
|
|
107217
107518
|
accountId: effective.account.id,
|
|
107218
107519
|
credentials: upstreamCredentialOf$1(effective.credentials)
|
|
@@ -107323,15 +107624,17 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107323
107624
|
const triedAccounts = /* @__PURE__ */ new Set();
|
|
107324
107625
|
const triedModels = /* @__PURE__ */ new Set([options.model]);
|
|
107325
107626
|
let currentModel = options.model;
|
|
107326
|
-
let picked = await this.credentialFor(triedAccounts);
|
|
107627
|
+
let picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107327
107628
|
let queueWaits = 0;
|
|
107328
107629
|
let queueWaitedMs = 0;
|
|
107329
107630
|
const queueSleep = this.options.queueSleep ?? sleepAbortable;
|
|
107330
107631
|
const handlePreContentFailure = async (failure, responseHeaders) => {
|
|
107331
107632
|
if (isQoderQueueFailure(failure)) {
|
|
107332
107633
|
const hint = qoderQueueHintOf(failure);
|
|
107333
|
-
recordQoderQueuePosition(hint);
|
|
107334
|
-
|
|
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) {
|
|
107335
107638
|
const nextModel = this.nextQueuedFallbackModel(currentModel, triedModels, picked.credentials.region, settings);
|
|
107336
107639
|
if (nextModel !== void 0) {
|
|
107337
107640
|
triedModels.add(nextModel);
|
|
@@ -107340,15 +107643,17 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107340
107643
|
}
|
|
107341
107644
|
if (picked.accountId !== null && this.accountPool !== null) {
|
|
107342
107645
|
if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
|
|
107343
|
-
picked = await this.credentialFor(triedAccounts);
|
|
107646
|
+
picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107344
107647
|
return true;
|
|
107345
107648
|
}
|
|
107346
107649
|
}
|
|
107347
107650
|
}
|
|
107348
107651
|
const waitMs = qoderQueueWaitMs(hint, queueWaits, queueWaitedMs);
|
|
107349
107652
|
if (waitMs > 0) {
|
|
107653
|
+
activity?.pulse();
|
|
107350
107654
|
await queueSleep(waitMs, signal);
|
|
107351
107655
|
if (signal.aborted) throw new LlmError$1(t("qo.requestAborted", { provider: PROVIDER_NAME$7 }), "ABORTED");
|
|
107656
|
+
activity?.pulse();
|
|
107352
107657
|
queueWaits += 1;
|
|
107353
107658
|
queueWaitedMs += waitMs;
|
|
107354
107659
|
return true;
|
|
@@ -107362,13 +107667,13 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107362
107667
|
const reason = failure.code === "QUOTA" ? "Qoder(订阅):当前账号额度已用尽" : "Qoder(订阅) 429:上游限流或额度用尽";
|
|
107363
107668
|
await this.accountPool.markCooldown(picked.accountId, after ?? 3e5, reason).catch(() => void 0);
|
|
107364
107669
|
if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
|
|
107365
|
-
picked = await this.credentialFor(triedAccounts);
|
|
107670
|
+
picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107366
107671
|
return true;
|
|
107367
107672
|
}
|
|
107368
107673
|
} else if (failure.code === "AUTH") {
|
|
107369
107674
|
await this.accountPool.markAuthFailed(picked.accountId, failure.message).catch(() => void 0);
|
|
107370
107675
|
if (await this.accountPool.hasAnotherAvailableAccount(triedAccounts)) {
|
|
107371
|
-
picked = await this.credentialFor(triedAccounts);
|
|
107676
|
+
picked = await this.credentialFor(triedAccounts, options.sessionId, currentModel);
|
|
107372
107677
|
return true;
|
|
107373
107678
|
}
|
|
107374
107679
|
}
|
|
@@ -107465,18 +107770,159 @@ var QoderAdapter = class extends LlmAdapter {
|
|
|
107465
107770
|
}
|
|
107466
107771
|
throw error;
|
|
107467
107772
|
} finally {
|
|
107468
|
-
if (state.sawUsage)
|
|
107469
|
-
|
|
107470
|
-
|
|
107471
|
-
|
|
107472
|
-
|
|
107473
|
-
|
|
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
|
+
}
|
|
107474
107794
|
reader.cancel().catch(() => void 0);
|
|
107475
107795
|
}
|
|
107476
107796
|
}
|
|
107477
107797
|
}
|
|
107478
107798
|
};
|
|
107479
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
|
|
107480
107926
|
//#region src/host/providers/qoder/oauth.ts
|
|
107481
107927
|
/**
|
|
107482
107928
|
* Qoder(订阅)线路的登录:浏览器设备流(仅全球区)+ PAT 兑换 + 令牌刷新。
|
|
@@ -108080,8 +108526,14 @@ var QoderAccountPool = class extends AccountPoolCore {
|
|
|
108080
108526
|
* 核心在这里做轮转、冷却、可用性判断与刷新;本方法只多给适配器一件事:
|
|
108081
108527
|
* 一次请求内换过账号时,把试过的账号排除掉。
|
|
108082
108528
|
*/
|
|
108083
|
-
async getEffectiveCredential(excludeIds, fetchFn = fetch) {
|
|
108084
|
-
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);
|
|
108085
108537
|
}
|
|
108086
108538
|
/**
|
|
108087
108539
|
* 一次额度读属于哪个账号,连同读它用的凭据。
|
|
@@ -123949,12 +124401,12 @@ function formatApproxTokens(tokens) {
|
|
|
123949
124401
|
* GOAL 只含最新回合;更早回合标注为仅供参考,且有任务清单时由 TASKS 承接连续性而不再渲染。
|
|
123950
124402
|
*/
|
|
123951
124403
|
function renderStateAnchorText(input) {
|
|
123952
|
-
const header = `${
|
|
123953
|
-
const goalLine = input.goal.length > 0 ?
|
|
124404
|
+
const header = `${input.prefix ?? "[V4.1-Flash State Anchor"}${input.modelLabel === void 0 ? "" : ` | model=${input.modelLabel}`} | step=${input.step} | trigger=${input.reason}]`;
|
|
124405
|
+
const goalLine = input.goal.length > 0 ? `${input.goalMerged === true ? "GOAL (later parts override earlier)" : "GOAL"}: ${input.goal}` : void 0;
|
|
123954
124406
|
const toolLabel = input.lastErrorTool ? ` (${input.lastErrorTool})` : "";
|
|
123955
124407
|
const alertLine = input.reason === "consecutive-errors" ? `ALERT: ${input.consecutiveErrors} consecutive tool failures${toolLabel}. Do NOT retry the same approach; switch to minimal verification or inspect the root definition.` : void 0;
|
|
123956
124408
|
const earlier = !(input.tasks !== void 0 && input.tasks.length > 0) && input.earlierGoal !== void 0 ? input.earlierGoal : "";
|
|
123957
|
-
const ruleLine = earlier.length > 0 ? "RULE: GOAL is the latest request and later parts override earlier ones; EARLIER is context only and loses on any conflict; verify via tools/PTC instead of long speculation; finish once acceptance criteria pass." : "RULE: GOAL is the latest request and later parts override earlier ones; verify via tools/PTC instead of long speculation; finish once acceptance criteria pass.";
|
|
124409
|
+
const ruleLine = input.ruleLine === void 0 ? earlier.length > 0 ? "RULE: GOAL is the latest request and later parts override earlier ones; EARLIER is context only and loses on any conflict; verify via tools/PTC instead of long speculation; finish once acceptance criteria pass." : "RULE: GOAL is the latest request and later parts override earlier ones; verify via tools/PTC instead of long speculation; finish once acceptance criteria pass." : earlier.length > 0 && !input.ruleLine.includes("EARLIER") ? `${input.ruleLine} EARLIER is context only and loses on any conflict.` : input.ruleLine;
|
|
123958
124410
|
const fixed = [
|
|
123959
124411
|
header,
|
|
123960
124412
|
goalLine,
|
|
@@ -125458,18 +125910,20 @@ function recordActiveFile(state, file) {
|
|
|
125458
125910
|
}
|
|
125459
125911
|
/** 渲染紧凑尾部状态锚文本(保持简短以减少噪声与 token 开销)。 */
|
|
125460
125912
|
function renderOpenModelStateAnchorText(input) {
|
|
125461
|
-
|
|
125462
|
-
|
|
125463
|
-
|
|
125464
|
-
|
|
125465
|
-
|
|
125466
|
-
|
|
125467
|
-
|
|
125468
|
-
|
|
125469
|
-
|
|
125470
|
-
|
|
125471
|
-
|
|
125472
|
-
|
|
125913
|
+
return renderStateAnchorText({
|
|
125914
|
+
prefix: OPEN_MODEL_ANCHOR_PREFIX,
|
|
125915
|
+
modelLabel: input.profile.label,
|
|
125916
|
+
goalMerged: input.goalMerged,
|
|
125917
|
+
ruleLine: input.profile.anchorRuleLine,
|
|
125918
|
+
step: input.step,
|
|
125919
|
+
reason: input.reason,
|
|
125920
|
+
goal: input.goal,
|
|
125921
|
+
earlierGoal: input.earlierGoal,
|
|
125922
|
+
tasks: input.tasks,
|
|
125923
|
+
activeFiles: input.activeFiles,
|
|
125924
|
+
consecutiveErrors: input.consecutiveErrors,
|
|
125925
|
+
lastErrorTool: input.lastErrorTool
|
|
125926
|
+
});
|
|
125473
125927
|
}
|
|
125474
125928
|
function createAnchorMessage(text, label) {
|
|
125475
125929
|
return createUserMessage$1({
|
|
@@ -143668,7 +144122,7 @@ const Config = z$1.object({
|
|
|
143668
144122
|
advisorModel: z$1.string().default("").volatile().description("新对话的默认顾问模型。"),
|
|
143669
144123
|
advisorReasoningEffort: z$1.string().default("auto").volatile().description("顾问模型的推理强度;auto 使用模型默认值。"),
|
|
143670
144124
|
advisorMaxTokens: z$1.number().min(256).max(32768).step(1).default(4096).volatile().description("顾问单次回复的最大 token 数。"),
|
|
143671
|
-
advisorTimeoutMs: z$1.number().min(1e3).max(
|
|
144125
|
+
advisorTimeoutMs: z$1.number().min(1e3).max(54e4).step(1).default(54e4).volatile().description("顾问单次咨询的总超时毫秒数。"),
|
|
143672
144126
|
advisorMaxRetries: z$1.number().min(0).max(3).step(1).default(1).volatile().description("顾问遇到临时错误时的最大追加重试次数。"),
|
|
143673
144127
|
advisorContextTokenBudget: z$1.number().min(8e3).max(1e6).step(1).default(1e5).volatile().description("转发给顾问的对话上下文预算。"),
|
|
143674
144128
|
advisorSessionTokenBudget: z$1.number().min(0).max(1e7).step(1).default(2e5).volatile().description("单个对话累计可消耗的顾问 token 上限;0 表示不限制。"),
|
|
@@ -144354,9 +144808,10 @@ function apply(ctx, pluginConfig = {}) {
|
|
|
144354
144808
|
providerId: PROVIDER_ID$7,
|
|
144355
144809
|
label: PROVIDER_NAME$7,
|
|
144356
144810
|
adapter: new QoderAdapter(qoderStore, qoderModelSettings, qoderPreferences, {
|
|
144357
|
-
fetchFn: modelFetch[PROVIDER_ID$7],
|
|
144811
|
+
fetchFn: createQoderTrafficGuardFetch(modelFetch[PROVIDER_ID$7]),
|
|
144358
144812
|
attachments: ctx.attachments,
|
|
144359
|
-
accountPool: qoderAccountPool
|
|
144813
|
+
accountPool: qoderAccountPool,
|
|
144814
|
+
cacheAffinity: () => resolveCacheAffinityEnabled(pluginConfig, process.env)
|
|
144360
144815
|
})
|
|
144361
144816
|
});
|
|
144362
144817
|
const disposeQoderRoutes = registerQoderRoutes(ctx, qoderSettingsSource(qoderPreferences, qoderModelSettings), {
|