dsh-codearts 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.mts CHANGED
@@ -793,6 +793,13 @@ interface CodeArtsModelInfo {
793
793
  * 卡片只在上游给值时印「1M 上下文」这类规格;兜底值印出来就是假数据。
794
794
  */
795
795
  contextWindowKnown?: boolean;
796
+ /**
797
+ * 上游标称的窗口(用户覆盖、实测学习之前的原值)。
798
+ *
799
+ * `contextWindow` 是**生效值**:用户按模型覆盖(issue #9)或进程内学到的上界都会
800
+ * 把它压低。卡片要把窗口改回「跟随上游」时需要这个原值,所以只在两者不等时才带出来。
801
+ */
802
+ contextWindowDiscovered?: number;
796
803
  maxTokens: number;
797
804
  supportsImages: boolean;
798
805
  /**
@@ -910,6 +917,14 @@ interface PreparedChatBody {
910
917
  * 那句话里没有模型、没有 token 数,用户无从下手。
911
918
  */
912
919
  error?: string;
920
+ /**
921
+ * 本次请求的 prompt 估算(messages + tools,含工具定义)。
922
+ *
923
+ * 两个用途:守卫算 room;shim 在「max_tokens 已到地板仍被判参数非法」时把它
924
+ * 记成该模型的真实窗口上界(issue #9 的诉求 2)。守卫和报错用的是同一份数值,
925
+ * 不会出现「守卫说 40 万、报错说 39 万」的漂移。
926
+ */
927
+ promptTokens: number;
913
928
  }
914
929
  /**
915
930
  * 把 OpenAI 风格 chat body 适配给 CodeArts /api/v2/chat/completions。
@@ -987,11 +1002,13 @@ interface CodeArtsQueueStatus {
987
1002
  * `gateway/config` 给福利模型标的是 393216 / 384000,而聊天端点实测超过 65536
988
1003
  * 就流内报 InferHub.001001005.400;DSH 会把 catalog 的 maxTokens 原样当
989
1004
  * max_tokens 发出去,照抄标称值等于让每个请求都失败。
990
- * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由)。
1005
+ * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由);
1006
+ * 用户配置的按模型覆盖值与进程内学到的真实上界在这里压过发现值(issue #9)。
991
1007
  *
1008
+ * @param contextWindowOverrides 按模型 id 覆盖 contextWindow(大小写不敏感)
992
1009
  * @throws 三路全失败,或合并结果为空。
993
1010
  */
994
- declare function fetchModels(credential: CodeArtsResolved, signal?: AbortSignal): Promise<ModelDiscoveryResult>;
1011
+ declare function fetchModels(credential: CodeArtsResolved, signal?: AbortSignal, contextWindowOverrides?: Readonly<Record<string, number>>): Promise<ModelDiscoveryResult>;
995
1012
  //#endregion
996
1013
  //#region src/auth.d.ts
997
1014
  /** 持久化的完整凭证。 */
@@ -1620,6 +1637,13 @@ interface CodeArtsShimOptions {
1620
1637
  debug?: (message: string) => void;
1621
1638
  /** 本地槽位满时最多等多久(缺省 30 秒)。测试用它把等待压到毫秒级。 */
1622
1639
  localSlotWaitMs?: number;
1640
+ /**
1641
+ * 按模型 id 覆盖 contextWindow(用户配置,每次请求实时读取)。
1642
+ *
1643
+ * 目录值来自上游标称,免费档真实窗口可能小得多(issue #9)。回调而不是快照:
1644
+ * 用户在设置里改完,下一句话就该用新值,不必等下一轮模型发现。
1645
+ */
1646
+ contextWindowOverrides?: () => Readonly<Record<string, number>> | undefined;
1623
1647
  }
1624
1648
  declare function createCodeArtsShim(options: CodeArtsShimOptions): CodeArtsShim;
1625
1649
  //#endregion
@@ -1792,14 +1816,15 @@ interface DiscoveryOutcome {
1792
1816
  *
1793
1817
  * @param store 账号文档;逐个 `resolve()` 以拿到已续期的签名材料
1794
1818
  * @param signal 取消信号(宿主关停时用)
1819
+ * @param contextWindowOverrides 用户按模型 id 配置的窗口覆盖值(issue #9)
1795
1820
  */
1796
- declare function discoverModels(store: CodeArtsAccountStore, signal?: AbortSignal): Promise<DiscoveryOutcome>;
1821
+ declare function discoverModels(store: CodeArtsAccountStore, signal?: AbortSignal, contextWindowOverrides?: Readonly<Record<string, number>>): Promise<DiscoveryOutcome>;
1797
1822
  /**
1798
1823
  * 发现并**提交**到全局目录:目录内容 + 福利集合。
1799
1824
  *
1800
1825
  * @returns 提交后的目录;没有任何账号成功时返回 `undefined`(调用方保留原目录)
1801
1826
  */
1802
- declare function refreshCatalog(store: CodeArtsAccountStore, catalog: CodeArtsCatalog, signal?: AbortSignal): Promise<DiscoveryOutcome | undefined>;
1827
+ declare function refreshCatalog(store: CodeArtsAccountStore, catalog: CodeArtsCatalog, signal?: AbortSignal, contextWindowOverrides?: Readonly<Record<string, number>>): Promise<DiscoveryOutcome | undefined>;
1803
1828
  //#endregion
1804
1829
  //#region src/index.d.ts
1805
1830
  /** Stable Cordis plugin name. */
@@ -1812,6 +1837,14 @@ declare const CODEARTS_SETTINGS_NS: SettingsNamespace;
1812
1837
  interface Config {
1813
1838
  /** Allowlist of CodeArts model ids offered in the model pickers. */
1814
1839
  enabledModels?: string[];
1840
+ /**
1841
+ * 按模型 id 强制覆盖 `contextWindow`(id 大小写不敏感,值 = tokens)。
1842
+ *
1843
+ * 动态发现给的是上游/网关的标称值,免费档的真实窗口可能远小于它、还会漂
1844
+ * (issue #9:deepseek-v4.1-flash-1017 标称 1M、实测 ≈49 万)。覆盖值压过发现值;
1845
+ * 进程内按实测学到的上界仍会在此基础上继续往下钳。
1846
+ */
1847
+ contextWindowOverrides?: Record<string, number>;
1815
1848
  /** 对话输入框下方那行「积分 N」是否显示。缺省 = 显示(老配置不改行为)。 */
1816
1849
  showCreditDock?: boolean;
1817
1850
  /** 等上游开流时那行「排队第 N 位」是否显示。缺省 = 显示。 */
package/lib/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { a as codeartsAuthPath, c as credentialFromOAuth, i as codeartsAccountsPath, m as startLogin, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-Ch0vYSAo.mjs";
2
- import { A as clearBenefitBlocked, C as prepareChatBody, E as upstreamErrorMessage, F as isBenefitModel, I as markModelUnavailable, M as filterEnabledModels, N as forgetModelUnavailable, O as CodeArtsCatalog, P as isBenefitBlocked, S as pickDailyWelfareCampaign, T as signedGet, _ as isQueueableRate, a as clearQueueStatus, b as maxTokensCeilingFor, c as fetchModels, d as firstFrameError, f as isConcurrencyCap, g as isParamInvalidFrame, h as isNotMultimodal, i as claimDailyWelfare, j as creditRatioLabel, k as FALLBACK_CODEARTS_MODELS, l as fetchQueueStatus, m as isModelNotAccessible, n as canonicalModel, o as degradeTokenCeiling, p as isIamTokenError, r as chatStream, s as fetchCallerIdentity, t as SNAP_HOST, u as fetchWelfareCampaigns, v as isTpmLimit, w as rateLimitFrame, x as modelUnavailableReasonText, y as isWelfareClaimedStatus, z as modelUnavailableReason } from "./upstream-CVtspzAv.mjs";
3
- import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-BjBwEMks.mjs";
1
+ import { a as codeartsAuthPath, c as credentialFromOAuth, i as codeartsAccountsPath, m as startLogin, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-C00dJphV.mjs";
2
+ import { A as upstreamErrorMessage, B as markModelUnavailable, C as learnedContextWindowFor, D as prepareChatBody, E as pickDailyWelfareCampaign, F as creditRatioLabel, I as filterEnabledModels, L as forgetModelUnavailable, M as CodeArtsCatalog, N as FALLBACK_CODEARTS_MODELS, O as rateLimitFrame, P as clearBenefitBlocked, R as isBenefitBlocked, S as learnContextWindow, T as modelUnavailableReasonText, U as modelUnavailableReason, _ as isNotMultimodal, a as claimDailyWelfare, b as isTpmLimit, c as degradeTokenCeiling, d as fetchQueueStatus, f as fetchWelfareCampaigns, g as isModelNotAccessible, h as isIamTokenError, i as chatStream, k as signedGet, l as fetchCallerIdentity, m as isConcurrencyCap, n as SNAP_HOST, o as clearQueueStatus, p as firstFrameError, r as canonicalModel, s as contextWindowOverrideFor, t as MAX_TOKENS_FLOOR, u as fetchModels, v as isParamInvalidFrame, w as maxTokensCeilingFor, x as isWelfareClaimedStatus, y as isQueueableRate, z as isBenefitModel } from "./upstream-D1wYeXC7.mjs";
3
+ import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-DC5JRWls.mjs";
4
4
  import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
5
5
  import { a as keeperLogPath, c as keeperStats, d as stopKeeper, n as KEEPER_STALE_MS, o as keeperScriptPath, u as spawnKeeper } from "./keeper-MHeAp_eV.mjs";
6
6
  import { appendFileSync, statSync, writeFileSync } from "node:fs";
@@ -1072,7 +1072,12 @@ function readBody$1(req) {
1072
1072
  req.on("error", reject);
1073
1073
  });
1074
1074
  }
1075
- /** 一次请求最多把 max_tokens 降几档(65536 → 32768 → 16384 → 8192)。 */
1075
+ /**
1076
+ * 一次请求最多把 max_tokens 降几档(65536 → 32768 → 16384 → 8192)。
1077
+ *
1078
+ * 到地板后还会再进循环一次 —— 那一次不再重发,而是把「其实是上下文装不下」
1079
+ * 报出来并学习窗口上界(见 `openWithCeilingHeal`)。
1080
+ */
1076
1081
  const MAX_CEILING_HEALS = 3;
1077
1082
  /**
1078
1083
  * 一次请求最多试几个账号:clamp(可用账号数, ROTATE_MIN_ATTEMPTS, ROTATE_MAX_ATTEMPTS)。
@@ -1218,11 +1223,24 @@ function createCodeArtsShim(options) {
1218
1223
  else res.end();
1219
1224
  }
1220
1225
  }
1221
- /** 该模型的上下文窗口(catalog 里查,大小写不敏感);查不到返回 0 = 不做超长预判。 */
1226
+ /**
1227
+ * 该模型当前应使用的上下文窗口:用户覆盖优先于目录值,再被进程内学到的上界往下钳。
1228
+ *
1229
+ * 学到的上界来自「max_tokens 已到地板仍被判参数非法」的实测(issue #9)。必须在这里
1230
+ * 生效 —— 只改目录不够,目录要等下一轮发现,而用户下一句话马上就来。
1231
+ * 返回 0 表示查不到该模型,不做超长预判。
1232
+ */
1222
1233
  function contextWindowFor(id) {
1223
1234
  const lower = id.trim().toLowerCase();
1224
- for (const model of catalog.current()) if (model.id.toLowerCase() === lower) return model.contextWindow;
1225
- return 0;
1235
+ let discovered = 0;
1236
+ for (const model of catalog.current()) if (model.id.toLowerCase() === lower) {
1237
+ discovered = model.contextWindow;
1238
+ break;
1239
+ }
1240
+ const base = contextWindowOverrideFor(options.contextWindowOverrides?.(), lower) ?? discovered;
1241
+ const learned = learnedContextWindowFor(lower);
1242
+ const window = learned === void 0 ? base : Math.min(base, learned);
1243
+ return window > 0 ? window : 0;
1226
1244
  }
1227
1245
  /**
1228
1246
  * 打开上游流;撞到「参数非法」就把该模型的 max_tokens 上限折半降一档再开一次。
@@ -1288,7 +1306,8 @@ function createCodeArtsShim(options) {
1288
1306
  };
1289
1307
  }
1290
1308
  }
1291
- const shouldHeal = heal < MAX_CEILING_HEALS && headText !== void 0 && isParamInvalidFrame(headText);
1309
+ const atFloor = maxTokensCeilingFor(prepared.model) <= MAX_TOKENS_FLOOR;
1310
+ const shouldHeal = prepared.promptTokens > 0 && headText !== void 0 && isParamInvalidFrame(headText) && (heal < MAX_CEILING_HEALS || atFloor);
1292
1311
  reader.releaseLock();
1293
1312
  if (!shouldHeal) return {
1294
1313
  prepared,
@@ -1296,15 +1315,22 @@ function createCodeArtsShim(options) {
1296
1315
  head
1297
1316
  };
1298
1317
  await result.stream.cancel().catch(() => {});
1299
- if (degradeTokenCeiling(prepared.model) === 0) return {
1300
- prepared,
1301
- result: {
1302
- ok: false,
1303
- kind: "client",
1304
- status: 400,
1305
- message: `${prepared.model}: max_tokens 已降到下限仍被判参数非法`
1318
+ if (degradeTokenCeiling(prepared.model) === 0) {
1319
+ if (prepared.promptTokens > 0) {
1320
+ const learned = learnContextWindow(prepared.model, prepared.promptTokens);
1321
+ logger?.warn(`dsh-codearts: ${prepared.model} 在 max_tokens 地板仍被判参数非法,按本次 prompt 估算 ${prepared.promptTokens} tokens 学习窗口上界 ${learned}`);
1306
1322
  }
1307
- };
1323
+ const estimate = prepared.promptTokens > 0 ? `本次 prompt 估算约 ${prepared.promptTokens} tokens,` : "";
1324
+ return {
1325
+ prepared,
1326
+ result: {
1327
+ ok: false,
1328
+ kind: "client",
1329
+ status: 400,
1330
+ message: `${prepared.model}: 上下文放不下 —— ${estimate}max_tokens 已降到 ${MAX_TOKENS_FLOOR} 仍被上游判参数非法。请压缩上下文(/compact)或新建会话;如果目录里的窗口值不准,可在设置里覆盖该模型的 contextWindow。`
1331
+ }
1332
+ };
1333
+ }
1308
1334
  logger?.warn(`dsh-codearts: ${prepared.model} 被判参数非法,max_tokens 降档到 ${maxTokensCeilingFor(prepared.model)} 后重发`);
1309
1335
  }
1310
1336
  }
@@ -1661,6 +1687,11 @@ const IDENTITY_TIMEOUT_MS = 8e3;
1661
1687
  const CODEARTS_STATUS_PATH = "/api/codearts/status";
1662
1688
  const CODEARTS_MODELS_PATH = "/api/codearts/models";
1663
1689
  const CODEARTS_MODELS_SELECTION_PATH = "/api/codearts/enabled-models";
1690
+ /**
1691
+ * POST /api/codearts/context-window — 按模型设置/清除上下文窗口覆盖(issue #9)。
1692
+ * `{ id, window }`,`window: null` 表示删除覆盖、回到跟随上游。
1693
+ */
1694
+ const CODEARTS_CONTEXT_WINDOW_PATH = "/api/codearts/context-window";
1664
1695
  const CODEARTS_TOKEN_PATH = "/api/codearts/token";
1665
1696
  const CODEARTS_LOGIN_PATH = "/api/codearts/login";
1666
1697
  const CODEARTS_LOGIN_STATUS_PATH = "/api/codearts/login/status";
@@ -1720,6 +1751,8 @@ function selectionOf(models, enabled, writable) {
1720
1751
  ratio: m.ratio,
1721
1752
  supportsImages: m.supportsImages,
1722
1753
  contextWindow: m.contextWindow,
1754
+ contextWindowDiscovered: m.contextWindowDiscovered,
1755
+ contextWindowOverride: m.contextWindowOverride,
1723
1756
  maxTokens: m.maxTokens,
1724
1757
  ...m.error === void 0 ? {} : { error: m.error },
1725
1758
  enabled: restricted ? allowed.has(m.id) : true
@@ -1730,10 +1763,12 @@ function selectionOf(models, enabled, writable) {
1730
1763
  }
1731
1764
  /** 目录 -> 勾选 UI 的选项(福利标记、今日不可用标记与倍率都在这里算)。 */
1732
1765
  function choicesOf(deps) {
1766
+ const overrides = deps.contextWindowOverrides?.();
1733
1767
  return deps.models().map((m) => {
1734
1768
  const benefit = isBenefitModel(m.id);
1735
1769
  const ratio = creditRatioLabel(m.ratio, benefit);
1736
1770
  const error = modelUnavailableReason(m.id);
1771
+ const override = contextWindowOverrideFor(overrides, m.id);
1737
1772
  return {
1738
1773
  id: m.id,
1739
1774
  name: m.name,
@@ -1742,6 +1777,8 @@ function choicesOf(deps) {
1742
1777
  ...ratio === void 0 ? {} : { ratio },
1743
1778
  ...m.supportsImages === true ? { supportsImages: true } : {},
1744
1779
  ...m.contextWindowKnown === true ? { contextWindow: m.contextWindow } : {},
1780
+ ...m.contextWindowDiscovered === void 0 ? {} : { contextWindowDiscovered: m.contextWindowDiscovered },
1781
+ ...override === void 0 ? {} : { contextWindowOverride: override },
1745
1782
  ...m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {},
1746
1783
  ...error === void 0 ? {} : { error }
1747
1784
  };
@@ -2280,6 +2317,56 @@ function modelsSelectionHandler(deps) {
2280
2317
  json(res, 405, { error: "method not allowed" });
2281
2318
  };
2282
2319
  }
2320
+ /**
2321
+ * POST /api/codearts/context-window { id, window } — 按模型覆盖上下文窗口。
2322
+ *
2323
+ * 存在的理由(issue #9):目录给的是上游标称窗口,免费档实际能装下的往往差一半,
2324
+ * 而超限时上游只回一句「参数非法」、不指名参数。`window: null` 删除覆盖、回到跟随上游。
2325
+ */
2326
+ function contextWindowHandler(deps) {
2327
+ return async (req, res) => {
2328
+ if (req.method !== "POST") {
2329
+ json(res, 405, { error: "method not allowed" });
2330
+ return;
2331
+ }
2332
+ if (!loopbackRequest(req)) {
2333
+ json(res, 403, { error: "request-not-trusted" });
2334
+ return;
2335
+ }
2336
+ if (deps.setContextWindowOverride === void 0) {
2337
+ json(res, 403, { error: "context-window-not-writable" });
2338
+ return;
2339
+ }
2340
+ const type = req.headers["content-type"];
2341
+ if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
2342
+ json(res, 415, { error: "content-type must be application/json" });
2343
+ return;
2344
+ }
2345
+ try {
2346
+ const body = JSON.parse(await readBody(req));
2347
+ const id = typeof body.id === "string" ? body.id.trim() : "";
2348
+ if (id === "") {
2349
+ json(res, 400, { error: "expected {\"id\": string, \"window\": number|null}" });
2350
+ return;
2351
+ }
2352
+ let window = null;
2353
+ if (body.window !== null && body.window !== void 0) {
2354
+ if (typeof body.window !== "number" || !Number.isFinite(body.window) || body.window <= 0) {
2355
+ json(res, 400, { error: "window must be a positive number or null" });
2356
+ return;
2357
+ }
2358
+ window = Math.floor(body.window);
2359
+ }
2360
+ if (!await deps.setContextWindowOverride(id, window)) {
2361
+ json(res, 403, { error: "context-window-not-writable" });
2362
+ return;
2363
+ }
2364
+ json(res, 200, { selection: selectionOf(choicesOf(deps), deps.enabledModels?.(), true) });
2365
+ } catch (error) {
2366
+ json(res, 500, { error: safeMessage(error) });
2367
+ }
2368
+ };
2369
+ }
2283
2370
  /** POST /api/codearts/token { token, label? } — store a pasted token. */
2284
2371
  function tokenPostHandler(deps) {
2285
2372
  return async (req, res) => {
@@ -2650,6 +2737,11 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2650
2737
  path: CODEARTS_MODELS_SELECTION_PATH,
2651
2738
  handler: modelsSelectionHandler(deps)
2652
2739
  });
2740
+ const disposeContextWindow = ctx.webServer.register({
2741
+ kind: "exact",
2742
+ path: CODEARTS_CONTEXT_WINDOW_PATH,
2743
+ handler: contextWindowHandler(deps)
2744
+ });
2653
2745
  const disposeToken = ctx.webServer.register({
2654
2746
  kind: "exact",
2655
2747
  path: CODEARTS_TOKEN_PATH,
@@ -2714,6 +2806,7 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2714
2806
  disposeStatus();
2715
2807
  disposeModels();
2716
2808
  disposeModelsSelection();
2809
+ disposeContextWindow();
2717
2810
  disposeToken();
2718
2811
  disposeLoginStart();
2719
2812
  disposeLoginStatus();
@@ -2901,6 +2994,7 @@ function unwrapConfig(value) {
2901
2994
  }
2902
2995
  const Config = z.object({
2903
2996
  enabledModels: z.array(z.string()).description("Model ids offered in the model pickers (empty means every model)").volatile(),
2997
+ contextWindowOverrides: z.dict(z.natural()).description("Per-model contextWindow overrides (model id → tokens). Discovery reports the nominal server window, which the free tier may not actually serve (issue #9); an override wins over it, and the in-process learned upper bound still clamps it.").volatile(),
2904
2998
  showCreditDock: z.boolean().default(true).description("Show the remaining-credits line under the chat input box").volatile(),
2905
2999
  showQueueDock: z.boolean().default(true).description("Show the upstream queue position under the chat input box").volatile(),
2906
3000
  showSidebarPanel: z.boolean().default(false).description("Show a CodeArts icon in the DSH sidebar icon column, opening this page in the middle column").volatile(),
@@ -3001,6 +3095,36 @@ function apply(ctx, rawConfig) {
3001
3095
  await settings.update(settingsCompatNamespace(ctx), { enabledModels: [...ids] });
3002
3096
  return true;
3003
3097
  };
3098
+ /**
3099
+ * 写/清某个模型的窗口覆盖(issue #9)。
3100
+ *
3101
+ * 除了落 settings,还**当场**把目录里那条改成新值:卡片保存后会立刻重拉 selection,
3102
+ * 目录不跟着变的话输入框会弹回旧数字,用户会以为没存上。
3103
+ * `window: null` = 删除覆盖,生效值退回上游标称值(`contextWindowDiscovered`)。
3104
+ */
3105
+ const setContextWindowOverride = async (id, window) => {
3106
+ const settings = ctx.get("settings");
3107
+ if (settings === void 0) return false;
3108
+ const lower = id.trim().toLowerCase();
3109
+ const next = {};
3110
+ for (const [key, value] of Object.entries(current().contextWindowOverrides ?? {})) if (key.trim().toLowerCase() !== lower) next[key] = value;
3111
+ if (window !== null) next[id.trim()] = window;
3112
+ await settings.update(settingsCompatNamespace(ctx), { contextWindowOverrides: next });
3113
+ catalog.set(catalog.current().map((model) => {
3114
+ if (model.id.toLowerCase() !== lower) return model;
3115
+ const target = window ?? model.contextWindowDiscovered ?? model.contextWindow;
3116
+ const { contextWindowDiscovered, ...rest } = model;
3117
+ return contextWindowDiscovered === void 0 || contextWindowDiscovered === target ? {
3118
+ ...rest,
3119
+ contextWindow: target
3120
+ } : {
3121
+ ...rest,
3122
+ contextWindow: target,
3123
+ contextWindowDiscovered
3124
+ };
3125
+ }));
3126
+ return true;
3127
+ };
3004
3128
  const dock = () => ({
3005
3129
  credits: current().showCreditDock !== false,
3006
3130
  queue: current().showQueueDock !== false,
@@ -3217,6 +3341,8 @@ function apply(ctx, rawConfig) {
3217
3341
  models: () => catalog.current(),
3218
3342
  enabledModels,
3219
3343
  setEnabledModels,
3344
+ contextWindowOverrides: () => current().contextWindowOverrides,
3345
+ setContextWindowOverride,
3220
3346
  pool: () => pool.list(),
3221
3347
  reviveAccount: (id) => pool.revive(id),
3222
3348
  usage: () => usage.snapshot(),
@@ -3243,7 +3369,7 @@ function apply(ctx, rawConfig) {
3243
3369
  return outcome;
3244
3370
  },
3245
3371
  refreshModels: async () => {
3246
- const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS));
3372
+ const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS), current().contextWindowOverrides);
3247
3373
  const models = catalog.current();
3248
3374
  return {
3249
3375
  models: models.length,
@@ -3277,7 +3403,7 @@ function apply(ctx, rawConfig) {
3277
3403
  const discover = async () => {
3278
3404
  if (stopped) return;
3279
3405
  try {
3280
- const outcome = await refreshCatalog(store, catalog, abort.signal);
3406
+ const outcome = await refreshCatalog(store, catalog, abort.signal, current().contextWindowOverrides);
3281
3407
  if (outcome === void 0 || stopped) return;
3282
3408
  if (outcome.anySucceeded) {
3283
3409
  const free = outcome.models.filter((model) => model.benefit === true).length;
@@ -3420,7 +3546,8 @@ function apply(ctx, rawConfig) {
3420
3546
  usage,
3421
3547
  queue,
3422
3548
  logger: ctx.logger,
3423
- debug: writeDebugLog
3549
+ debug: writeDebugLog,
3550
+ contextWindowOverrides: () => current().contextWindowOverrides
3424
3551
  });
3425
3552
  usage.load().catch(() => {});
3426
3553
  shim.ready.then(async () => {
@@ -1,4 +1,4 @@
1
- import { d as OAuthTokenError, f as defaultLoginConfig, i as codeartsAccountsPath, l as readAccountDocument, p as refreshToken, u as writeJsonAtomic } from "./auth-Ch0vYSAo.mjs";
1
+ import { d as OAuthTokenError, f as defaultLoginConfig, i as codeartsAccountsPath, l as readAccountDocument, p as refreshToken, u as writeJsonAtomic } from "./auth-C00dJphV.mjs";
2
2
  import { a as keeperLogPath, f as stopRequested, i as clearKeeperState, l as readKeeperState, p as writeKeeperState, r as KEEPER_TICK_MS, s as keeperStatePath, t as KEEPER_HEARTBEAT_MS } from "./keeper-MHeAp_eV.mjs";
3
3
  import { appendFileSync, existsSync, unlinkSync } from "node:fs";
4
4
  //#region src/keeper-main.ts
@@ -451,6 +451,7 @@ var upstream_exports = /* @__PURE__ */ __exportAll({
451
451
  BENEFIT_MISSING_CODE: () => BENEFIT_MISSING_CODE,
452
452
  CONCURRENCY_CAP_CODE: () => CONCURRENCY_CAP_CODE,
453
453
  MAX_TOKENS_CEILING: () => MAX_TOKENS_CEILING,
454
+ MAX_TOKENS_FLOOR: () => MAX_TOKENS_FLOOR,
454
455
  PARAM_INVALID_CODE: () => PARAM_INVALID_CODE,
455
456
  SNAP_HOST: () => SNAP_HOST,
456
457
  TPM_LIMIT_CODE: () => TPM_LIMIT_CODE,
@@ -459,6 +460,7 @@ var upstream_exports = /* @__PURE__ */ __exportAll({
459
460
  claimBenefit: () => claimBenefit,
460
461
  claimDailyWelfare: () => claimDailyWelfare,
461
462
  clearQueueStatus: () => clearQueueStatus,
463
+ contextWindowOverrideFor: () => contextWindowOverrideFor,
462
464
  degradeTokenCeiling: () => degradeTokenCeiling,
463
465
  estimateImageTokens: () => estimateImageTokens,
464
466
  estimatePromptTokens: () => estimatePromptTokens,
@@ -478,6 +480,8 @@ var upstream_exports = /* @__PURE__ */ __exportAll({
478
480
  isResignRefusal: () => isResignRefusal,
479
481
  isTpmLimit: () => isTpmLimit,
480
482
  isWelfareClaimedStatus: () => isWelfareClaimedStatus,
483
+ learnContextWindow: () => learnContextWindow,
484
+ learnedContextWindowFor: () => learnedContextWindowFor,
481
485
  maxTokensCeilingFor: () => maxTokensCeilingFor,
482
486
  modelUnavailableReasonText: () => modelUnavailableReasonText,
483
487
  pickDailyWelfareCampaign: () => pickDailyWelfareCampaign,
@@ -584,7 +588,12 @@ function isParamInvalidFrame(text) {
584
588
  * 免得该模型后面每一轮都先白撞一次。
585
589
  */
586
590
  const learnedMaxTokens = /* @__PURE__ */ new Map();
587
- /** 降档下限:再低就没有可用的生成长度了,此时宁可把具体错误报给用户。 */
591
+ /**
592
+ * 降档下限:再低就没有可用的生成长度了,此时宁可把具体错误报给用户。
593
+ *
594
+ * 导出是因为 shim 要拿它写报错文案(「max_tokens 已降到 8192 仍被拒」),文案里
595
+ * 的数字必须和真正的降档逻辑同源,不能在两处各写一个。
596
+ */
588
597
  const MAX_TOKENS_FLOOR = 8192;
589
598
  function ceilingKey(id) {
590
599
  return id.trim().toLowerCase();
@@ -598,11 +607,55 @@ function measuredCeilingFor(id) {
598
607
  */
599
608
  function degradeTokenCeiling(id) {
600
609
  const next = Math.floor(maxTokensCeilingFor(id) / 2);
601
- if (next < MAX_TOKENS_FLOOR) return 0;
610
+ if (next < 8192) return 0;
602
611
  learnedMaxTokens.set(ceilingKey(id), next);
603
612
  return next;
604
613
  }
605
614
  /**
615
+ * 本次进程内学到的「真实上下文窗口」上界(小写 id → tokens)。
616
+ *
617
+ * 目录值来自上游动态发现,但免费档真实窗口可能远小于标称、还会漂(issue #9:
618
+ * `deepseek-v4.1-flash-1017` 标称 1M、实测 ≈49 万,换一天又变)。上游对「装不下」
619
+ * 只回一句 InferHub.001001005.400,不说是哪个参数 —— 所以只能自己判:
620
+ * max_tokens 已经降到地板仍然被拒 ⇒ 不是 max_tokens 的问题,是 prompt 侧装不下
621
+ * ⇒ 把这次的 prompt 估算值记成该模型的上界。下一轮守卫就会在本地拦下来,并给出
622
+ * 指向上下文的报错,而不是让用户去猜「参数非法」。
623
+ *
624
+ * 与 learnedMaxTokens 一样是进程内状态:重启后第一次仍会白撞一次,之后立刻学会。
625
+ * 上游窗口只会收紧、不会放宽,所以取历史最小值,不被后面更大的估算抬高。
626
+ */
627
+ const learnedContextWindow = /* @__PURE__ */ new Map();
628
+ /** 该模型学到的真实窗口上界;没学过返回 undefined。 */
629
+ function learnedContextWindowFor(id) {
630
+ return learnedContextWindow.get(ceilingKey(id));
631
+ }
632
+ /**
633
+ * 记录一次「prompt 装不下」:把本次 prompt 估算值作为该模型的上界。
634
+ * @returns 学习后的上界(取历史最小值)
635
+ */
636
+ function learnContextWindow(id, promptTokens) {
637
+ const key = ceilingKey(id);
638
+ const measured = Math.max(1, Math.floor(promptTokens));
639
+ const previous = learnedContextWindow.get(key);
640
+ const learned = previous === void 0 ? measured : Math.min(previous, measured);
641
+ learnedContextWindow.set(key, learned);
642
+ return learned;
643
+ }
644
+ /**
645
+ * 从用户配置里取某模型的 contextWindow 覆盖值(id 大小写不敏感)。
646
+ *
647
+ * 非正数、NaN、Infinity 一律视为「没配」:这些值只会让守卫把每一次请求都判成
648
+ * 放不下,比目录值更糟。用户真要表达「不知道窗口」,删掉这个键即可。
649
+ */
650
+ function contextWindowOverrideFor(overrides, id) {
651
+ if (overrides === void 0) return void 0;
652
+ const key = ceilingKey(id);
653
+ for (const [rawKey, value] of Object.entries(overrides)) {
654
+ if (ceilingKey(rawKey) !== key) continue;
655
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
656
+ }
657
+ }
658
+ /**
606
659
  * 粗估一段**文本**占多少 token:CJK 每字约 1,其余每 4 字符约 1。
607
660
  *
608
661
  * 只要保守就够用 —— 它的用途是「在我们这边就把装不下的情况判掉」,
@@ -810,7 +863,8 @@ function prepareChatBody(rawJson, contextWindow = 0) {
810
863
  url: `${SNAP_HOST}${EP_CHAT}`,
811
864
  body: rawJson,
812
865
  model: "",
813
- chatId: ""
866
+ chatId: "",
867
+ promptTokens: 0
814
868
  };
815
869
  }
816
870
  const model = typeof parsed.model === "string" ? canonicalModel(parsed.model) : "";
@@ -837,11 +891,13 @@ function prepareChatBody(rawJson, contextWindow = 0) {
837
891
  if (body.stream_options === void 0 || typeof body.stream_options !== "object") body.stream_options = { include_usage: true };
838
892
  else body.stream_options.include_usage = true;
839
893
  if (body.max_tokens === void 0 && typeof parsed.max_completion_tokens === "number") body.max_tokens = parsed.max_completion_tokens;
894
+ /** 本次 prompt 的估算值:不管窗口知不知道都算,shim 要靠它学真实上界。 */
895
+ let promptTokens = 0;
840
896
  const ceiling = maxTokensCeilingFor(model);
841
897
  if (typeof body.max_tokens === "number") {
842
898
  let maxTokens = Math.min(body.max_tokens, ceiling);
899
+ promptTokens = estimatePromptTokens(body.messages, body.tools);
843
900
  if (contextWindow > 0) {
844
- const promptTokens = estimatePromptTokens(body.messages, body.tools);
845
901
  const room = contextWindow - promptTokens - PROMPT_ESTIMATE_MARGIN;
846
902
  if (room < MIN_USEFUL_OUTPUT_TOKENS) {
847
903
  body.max_tokens = maxTokens;
@@ -850,7 +906,8 @@ function prepareChatBody(rawJson, contextWindow = 0) {
850
906
  body: JSON.stringify(body),
851
907
  model,
852
908
  chatId,
853
- error: `上下文放不下:${model} 的窗口是 ${contextWindow} tokens,本次请求(含 ${Array.isArray(body.messages) ? body.messages.length : 0} 条消息与工具定义)估算约 ${promptTokens} tokens,剩余不足 ${MIN_USEFUL_OUTPUT_TOKENS} tokens 的生成余量。请新建会话或改用上下文更大的模型。`
909
+ promptTokens,
910
+ error: `上下文放不下:${model} 的窗口是 ${contextWindow} tokens,本次请求(含 ${Array.isArray(body.messages) ? body.messages.length : 0} 条消息与工具定义)估算约 ${promptTokens} tokens,剩余不足 ${MIN_USEFUL_OUTPUT_TOKENS} tokens 的生成余量。请新建会话或改用上下文更大的模型;如果目录里的窗口值不准,可在设置里覆盖该模型的 contextWindow。`
854
911
  };
855
912
  }
856
913
  maxTokens = Math.min(maxTokens, room);
@@ -877,7 +934,8 @@ function prepareChatBody(rawJson, contextWindow = 0) {
877
934
  url: `${SNAP_HOST}${EP_CHAT}`,
878
935
  body: JSON.stringify(body),
879
936
  model,
880
- chatId
937
+ chatId,
938
+ promptTokens
881
939
  };
882
940
  }
883
941
  /**
@@ -1605,11 +1663,13 @@ async function clearQueueStatus(credential, chatId, model, signal) {
1605
1663
  * `gateway/config` 给福利模型标的是 393216 / 384000,而聊天端点实测超过 65536
1606
1664
  * 就流内报 InferHub.001001005.400;DSH 会把 catalog 的 maxTokens 原样当
1607
1665
  * max_tokens 发出去,照抄标称值等于让每个请求都失败。
1608
- * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由)。
1666
+ * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由);
1667
+ * 用户配置的按模型覆盖值与进程内学到的真实上界在这里压过发现值(issue #9)。
1609
1668
  *
1669
+ * @param contextWindowOverrides 按模型 id 覆盖 contextWindow(大小写不敏感)
1610
1670
  * @throws 三路全失败,或合并结果为空。
1611
1671
  */
1612
- async function fetchModels(credential, signal) {
1672
+ async function fetchModels(credential, signal, contextWindowOverrides = {}) {
1613
1673
  const settled = await Promise.all([
1614
1674
  fetchBuiltinModels(credential, signal).then((models) => ({
1615
1675
  source: "builtin",
@@ -1659,11 +1719,17 @@ async function fetchModels(credential, signal) {
1659
1719
  return {
1660
1720
  models: merged.map((model) => {
1661
1721
  const thinking = variants.get(model.id.toLowerCase());
1722
+ const override = contextWindowOverrideFor(contextWindowOverrides, model.id);
1723
+ const learned = learnedContextWindowFor(model.id);
1724
+ const discovered = model.contextWindow > 0 ? model.contextWindow : UNKNOWN_CONTEXT_WINDOW;
1725
+ const base = override ?? discovered;
1726
+ const contextWindow = learned === void 0 ? base : Math.min(base, learned);
1662
1727
  return {
1663
1728
  ...model,
1664
1729
  ...thinking === void 0 ? {} : { thinking },
1665
- contextWindowKnown: model.contextWindow > 0,
1666
- contextWindow: model.contextWindow > 0 ? model.contextWindow : UNKNOWN_CONTEXT_WINDOW,
1730
+ contextWindowKnown: override !== void 0 || learned !== void 0 || model.contextWindow > 0,
1731
+ contextWindow,
1732
+ ...contextWindow === discovered ? {} : { contextWindowDiscovered: discovered },
1667
1733
  maxTokens: Math.min(model.maxTokens > 0 ? model.maxTokens : UNKNOWN_MAX_TOKENS, maxTokensCeilingFor(model.id))
1668
1734
  };
1669
1735
  }),
@@ -1886,4 +1952,4 @@ async function claimDailyWelfare(credential, signal) {
1886
1952
  };
1887
1953
  }
1888
1954
  //#endregion
1889
- export { clearBenefitBlocked as A, setDiscoveredBenefitModels as B, prepareChatBody as C, upstream_exports as D, upstreamErrorMessage as E, isBenefitModel as F, markModelUnavailable as I, mergeModelLists as L, filterEnabledModels as M, forgetModelUnavailable as N, CodeArtsCatalog as O, isBenefitBlocked as P, modelDisplayName as R, pickDailyWelfareCampaign as S, signedGet as T, isQueueableRate as _, clearQueueStatus as a, maxTokensCeilingFor as b, fetchModels as c, firstFrameError as d, isConcurrencyCap as f, isParamInvalidFrame as g, isNotMultimodal as h, claimDailyWelfare as i, creditRatioLabel as j, FALLBACK_CODEARTS_MODELS as k, fetchQueueStatus as l, isModelNotAccessible as m, canonicalModel as n, degradeTokenCeiling as o, isIamTokenError as p, chatStream as r, fetchCallerIdentity as s, SNAP_HOST as t, fetchWelfareCampaigns as u, isTpmLimit as v, rateLimitFrame as w, modelUnavailableReasonText as x, isWelfareClaimedStatus as y, modelUnavailableReason as z };
1955
+ export { upstreamErrorMessage as A, markModelUnavailable as B, learnedContextWindowFor as C, prepareChatBody as D, pickDailyWelfareCampaign as E, creditRatioLabel as F, modelDisplayName as H, filterEnabledModels as I, forgetModelUnavailable as L, CodeArtsCatalog as M, FALLBACK_CODEARTS_MODELS as N, rateLimitFrame as O, clearBenefitBlocked as P, isBenefitBlocked as R, learnContextWindow as S, modelUnavailableReasonText as T, modelUnavailableReason as U, mergeModelLists as V, setDiscoveredBenefitModels as W, isNotMultimodal as _, claimDailyWelfare as a, isTpmLimit as b, degradeTokenCeiling as c, fetchQueueStatus as d, fetchWelfareCampaigns as f, isModelNotAccessible as g, isIamTokenError as h, chatStream as i, upstream_exports as j, signedGet as k, fetchCallerIdentity as l, isConcurrencyCap as m, SNAP_HOST as n, clearQueueStatus as o, firstFrameError as p, canonicalModel as r, contextWindowOverrideFor as s, MAX_TOKENS_FLOOR as t, fetchModels as u, isParamInvalidFrame as v, maxTokensCeilingFor as w, isWelfareClaimedStatus as x, isQueueableRate as y, isBenefitModel as z };
@@ -1,5 +1,5 @@
1
- import { u as writeJsonAtomic } from "./auth-Ch0vYSAo.mjs";
2
- import { B as setDiscoveredBenefitModels, F as isBenefitModel, L as mergeModelLists, R as modelDisplayName, c as fetchModels } from "./upstream-CVtspzAv.mjs";
1
+ import { u as writeJsonAtomic } from "./auth-C00dJphV.mjs";
2
+ import { H as modelDisplayName, V as mergeModelLists, W as setDiscoveredBenefitModels, u as fetchModels, z as isBenefitModel } from "./upstream-D1wYeXC7.mjs";
3
3
  import { existsSync } from "node:fs";
4
4
  import { readFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
@@ -22,8 +22,9 @@ import { join } from "node:path";
22
22
  *
23
23
  * @param store 账号文档;逐个 `resolve()` 以拿到已续期的签名材料
24
24
  * @param signal 取消信号(宿主关停时用)
25
+ * @param contextWindowOverrides 用户按模型 id 配置的窗口覆盖值(issue #9)
25
26
  */
26
- async function discoverModels(store, signal) {
27
+ async function discoverModels(store, signal, contextWindowOverrides) {
27
28
  const ids = await store.ids();
28
29
  const accounts = [];
29
30
  for (const id of ids) {
@@ -46,7 +47,7 @@ async function discoverModels(store, signal) {
46
47
  continue;
47
48
  }
48
49
  try {
49
- const result = await fetchModels(resolved, signal);
50
+ const result = await fetchModels(resolved, signal, contextWindowOverrides);
50
51
  accounts.push({
51
52
  accountId: id,
52
53
  ...label === void 0 ? {} : { label },
@@ -81,8 +82,8 @@ async function discoverModels(store, signal) {
81
82
  *
82
83
  * @returns 提交后的目录;没有任何账号成功时返回 `undefined`(调用方保留原目录)
83
84
  */
84
- async function refreshCatalog(store, catalog, signal) {
85
- const outcome = await discoverModels(store, signal);
85
+ async function refreshCatalog(store, catalog, signal, contextWindowOverrides) {
86
+ const outcome = await discoverModels(store, signal, contextWindowOverrides);
86
87
  if (!outcome.anySucceeded || outcome.models.length === 0) return outcome;
87
88
  setDiscoveredBenefitModels(outcome.models.filter((model) => model.benefit === true).map((model) => model.id));
88
89
  catalog.set(outcome.models.map((model) => {
@@ -534,6 +535,6 @@ function percentileOf(buckets, ratio) {
534
535
  }
535
536
  //#endregion
536
537
  //#region src/version.ts
537
- const CODEARTS_VERSION = "1.4.0";
538
+ const CODEARTS_VERSION = "1.4.1";
538
539
  //#endregion
539
540
  export { refreshCatalog as a, discoverModels as i, CodeArtsUsageTracker as n, codeartsUsagePath as r, CODEARTS_VERSION as t };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-codearts",
3
3
  "displayName": "DSH CodeArts Connect",
4
4
  "description": "把华为云 CodeArts 接入 DeepSeek Harness —— 内置 OAuth2 登录(PKCE + DPoP),登录后即可在 DSH 对话窗口使用 CodeArts 的模型。",
5
- "version": "1.4.0",
5
+ "version": "1.4.1",
6
6
  "packageManager": "pnpm@11.24.0",
7
7
  "author": "elegant01",
8
8
  "keywords": [