dsh-codearts 1.4.0 → 1.4.2

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.
@@ -334,10 +334,12 @@ function backfillParams(discovered, params = FALLBACK_CODEARTS_MODELS) {
334
334
  for (const fallback of params) {
335
335
  const current = byId.get(fallback.id.toLowerCase());
336
336
  if (current === void 0) continue;
337
+ const keptWindow = current.contextWindow > 0;
337
338
  byId.set(fallback.id.toLowerCase(), {
338
339
  id: current.id,
339
340
  name: current.name || fallback.name,
340
- contextWindow: current.contextWindow > 0 ? current.contextWindow : fallback.contextWindow,
341
+ contextWindow: keptWindow ? current.contextWindow : fallback.contextWindow,
342
+ ...keptWindow && current.contextWindowKnown === true ? { contextWindowKnown: true } : {},
341
343
  maxTokens: current.maxTokens > 0 ? current.maxTokens : fallback.maxTokens,
342
344
  supportsImages: current.supportsImages || fallback.supportsImages,
343
345
  ...current.ratio === void 0 ? {} : { ratio: current.ratio },
@@ -451,6 +453,7 @@ var upstream_exports = /* @__PURE__ */ __exportAll({
451
453
  BENEFIT_MISSING_CODE: () => BENEFIT_MISSING_CODE,
452
454
  CONCURRENCY_CAP_CODE: () => CONCURRENCY_CAP_CODE,
453
455
  MAX_TOKENS_CEILING: () => MAX_TOKENS_CEILING,
456
+ MAX_TOKENS_FLOOR: () => MAX_TOKENS_FLOOR,
454
457
  PARAM_INVALID_CODE: () => PARAM_INVALID_CODE,
455
458
  SNAP_HOST: () => SNAP_HOST,
456
459
  TPM_LIMIT_CODE: () => TPM_LIMIT_CODE,
@@ -459,6 +462,7 @@ var upstream_exports = /* @__PURE__ */ __exportAll({
459
462
  claimBenefit: () => claimBenefit,
460
463
  claimDailyWelfare: () => claimDailyWelfare,
461
464
  clearQueueStatus: () => clearQueueStatus,
465
+ contextWindowOverrideFor: () => contextWindowOverrideFor,
462
466
  degradeTokenCeiling: () => degradeTokenCeiling,
463
467
  estimateImageTokens: () => estimateImageTokens,
464
468
  estimatePromptTokens: () => estimatePromptTokens,
@@ -478,6 +482,8 @@ var upstream_exports = /* @__PURE__ */ __exportAll({
478
482
  isResignRefusal: () => isResignRefusal,
479
483
  isTpmLimit: () => isTpmLimit,
480
484
  isWelfareClaimedStatus: () => isWelfareClaimedStatus,
485
+ learnContextWindow: () => learnContextWindow,
486
+ learnedContextWindowFor: () => learnedContextWindowFor,
481
487
  maxTokensCeilingFor: () => maxTokensCeilingFor,
482
488
  modelUnavailableReasonText: () => modelUnavailableReasonText,
483
489
  pickDailyWelfareCampaign: () => pickDailyWelfareCampaign,
@@ -584,7 +590,12 @@ function isParamInvalidFrame(text) {
584
590
  * 免得该模型后面每一轮都先白撞一次。
585
591
  */
586
592
  const learnedMaxTokens = /* @__PURE__ */ new Map();
587
- /** 降档下限:再低就没有可用的生成长度了,此时宁可把具体错误报给用户。 */
593
+ /**
594
+ * 降档下限:再低就没有可用的生成长度了,此时宁可把具体错误报给用户。
595
+ *
596
+ * 导出是因为 shim 要拿它写报错文案(「max_tokens 已降到 8192 仍被拒」),文案里
597
+ * 的数字必须和真正的降档逻辑同源,不能在两处各写一个。
598
+ */
588
599
  const MAX_TOKENS_FLOOR = 8192;
589
600
  function ceilingKey(id) {
590
601
  return id.trim().toLowerCase();
@@ -598,11 +609,55 @@ function measuredCeilingFor(id) {
598
609
  */
599
610
  function degradeTokenCeiling(id) {
600
611
  const next = Math.floor(maxTokensCeilingFor(id) / 2);
601
- if (next < MAX_TOKENS_FLOOR) return 0;
612
+ if (next < 8192) return 0;
602
613
  learnedMaxTokens.set(ceilingKey(id), next);
603
614
  return next;
604
615
  }
605
616
  /**
617
+ * 本次进程内学到的「真实上下文窗口」上界(小写 id → tokens)。
618
+ *
619
+ * 目录值来自上游动态发现,但免费档真实窗口可能远小于标称、还会漂(issue #9:
620
+ * `deepseek-v4.1-flash-1017` 标称 1M、实测 ≈49 万,换一天又变)。上游对「装不下」
621
+ * 只回一句 InferHub.001001005.400,不说是哪个参数 —— 所以只能自己判:
622
+ * max_tokens 已经降到地板仍然被拒 ⇒ 不是 max_tokens 的问题,是 prompt 侧装不下
623
+ * ⇒ 把这次的 prompt 估算值记成该模型的上界。下一轮守卫就会在本地拦下来,并给出
624
+ * 指向上下文的报错,而不是让用户去猜「参数非法」。
625
+ *
626
+ * 与 learnedMaxTokens 一样是进程内状态:重启后第一次仍会白撞一次,之后立刻学会。
627
+ * 上游窗口只会收紧、不会放宽,所以取历史最小值,不被后面更大的估算抬高。
628
+ */
629
+ const learnedContextWindow = /* @__PURE__ */ new Map();
630
+ /** 该模型学到的真实窗口上界;没学过返回 undefined。 */
631
+ function learnedContextWindowFor(id) {
632
+ return learnedContextWindow.get(ceilingKey(id));
633
+ }
634
+ /**
635
+ * 记录一次「prompt 装不下」:把本次 prompt 估算值作为该模型的上界。
636
+ * @returns 学习后的上界(取历史最小值)
637
+ */
638
+ function learnContextWindow(id, promptTokens) {
639
+ const key = ceilingKey(id);
640
+ const measured = Math.max(1, Math.floor(promptTokens));
641
+ const previous = learnedContextWindow.get(key);
642
+ const learned = previous === void 0 ? measured : Math.min(previous, measured);
643
+ learnedContextWindow.set(key, learned);
644
+ return learned;
645
+ }
646
+ /**
647
+ * 从用户配置里取某模型的 contextWindow 覆盖值(id 大小写不敏感)。
648
+ *
649
+ * 非正数、NaN、Infinity 一律视为「没配」:这些值只会让守卫把每一次请求都判成
650
+ * 放不下,比目录值更糟。用户真要表达「不知道窗口」,删掉这个键即可。
651
+ */
652
+ function contextWindowOverrideFor(overrides, id) {
653
+ if (overrides === void 0) return void 0;
654
+ const key = ceilingKey(id);
655
+ for (const [rawKey, value] of Object.entries(overrides)) {
656
+ if (ceilingKey(rawKey) !== key) continue;
657
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
658
+ }
659
+ }
660
+ /**
606
661
  * 粗估一段**文本**占多少 token:CJK 每字约 1,其余每 4 字符约 1。
607
662
  *
608
663
  * 只要保守就够用 —— 它的用途是「在我们这边就把装不下的情况判掉」,
@@ -810,7 +865,8 @@ function prepareChatBody(rawJson, contextWindow = 0) {
810
865
  url: `${SNAP_HOST}${EP_CHAT}`,
811
866
  body: rawJson,
812
867
  model: "",
813
- chatId: ""
868
+ chatId: "",
869
+ promptTokens: 0
814
870
  };
815
871
  }
816
872
  const model = typeof parsed.model === "string" ? canonicalModel(parsed.model) : "";
@@ -837,11 +893,13 @@ function prepareChatBody(rawJson, contextWindow = 0) {
837
893
  if (body.stream_options === void 0 || typeof body.stream_options !== "object") body.stream_options = { include_usage: true };
838
894
  else body.stream_options.include_usage = true;
839
895
  if (body.max_tokens === void 0 && typeof parsed.max_completion_tokens === "number") body.max_tokens = parsed.max_completion_tokens;
896
+ /** 本次 prompt 的估算值:不管窗口知不知道都算,shim 要靠它学真实上界。 */
897
+ let promptTokens = 0;
840
898
  const ceiling = maxTokensCeilingFor(model);
841
899
  if (typeof body.max_tokens === "number") {
842
900
  let maxTokens = Math.min(body.max_tokens, ceiling);
901
+ promptTokens = estimatePromptTokens(body.messages, body.tools);
843
902
  if (contextWindow > 0) {
844
- const promptTokens = estimatePromptTokens(body.messages, body.tools);
845
903
  const room = contextWindow - promptTokens - PROMPT_ESTIMATE_MARGIN;
846
904
  if (room < MIN_USEFUL_OUTPUT_TOKENS) {
847
905
  body.max_tokens = maxTokens;
@@ -850,7 +908,8 @@ function prepareChatBody(rawJson, contextWindow = 0) {
850
908
  body: JSON.stringify(body),
851
909
  model,
852
910
  chatId,
853
- error: `上下文放不下:${model} 的窗口是 ${contextWindow} tokens,本次请求(含 ${Array.isArray(body.messages) ? body.messages.length : 0} 条消息与工具定义)估算约 ${promptTokens} tokens,剩余不足 ${MIN_USEFUL_OUTPUT_TOKENS} tokens 的生成余量。请新建会话或改用上下文更大的模型。`
911
+ promptTokens,
912
+ error: `上下文放不下:${model} 的窗口是 ${contextWindow} tokens,本次请求(含 ${Array.isArray(body.messages) ? body.messages.length : 0} 条消息与工具定义)估算约 ${promptTokens} tokens,剩余不足 ${MIN_USEFUL_OUTPUT_TOKENS} tokens 的生成余量。请新建会话或改用上下文更大的模型;如果目录里的窗口值不准,可在设置里覆盖该模型的 contextWindow。`
854
913
  };
855
914
  }
856
915
  maxTokens = Math.min(maxTokens, room);
@@ -877,7 +936,8 @@ function prepareChatBody(rawJson, contextWindow = 0) {
877
936
  url: `${SNAP_HOST}${EP_CHAT}`,
878
937
  body: JSON.stringify(body),
879
938
  model,
880
- chatId
939
+ chatId,
940
+ promptTokens
881
941
  };
882
942
  }
883
943
  /**
@@ -1386,10 +1446,12 @@ async function fetchBuiltinModels(credential, signal) {
1386
1446
  const id = firstString(model.model_id, model.model_name);
1387
1447
  if (id === "") continue;
1388
1448
  const ratio = creditRatioOf(model);
1449
+ const contextWindow = positive(model.context_window);
1389
1450
  out.push({
1390
1451
  id,
1391
1452
  name: firstString(model.model_name, id),
1392
- contextWindow: positive(model.context_window),
1453
+ contextWindow,
1454
+ ...contextWindow > 0 ? { contextWindowKnown: true } : {},
1393
1455
  maxTokens: positive(model.max_tokens),
1394
1456
  supportsImages: model.supports_images === true,
1395
1457
  ...ratio === void 0 ? {} : { ratio }
@@ -1414,10 +1476,12 @@ async function fetchBenefitModels(credential, signal) {
1414
1476
  const id = firstString(model.model_id, model.model_name);
1415
1477
  if (id === "") continue;
1416
1478
  const ratio = creditRatioOf(model);
1479
+ const contextWindow = positive(model.context_window);
1417
1480
  out.push({
1418
1481
  id,
1419
1482
  name: firstString(model.model_name, id),
1420
- contextWindow: positive(model.context_window),
1483
+ contextWindow,
1484
+ ...contextWindow > 0 ? { contextWindowKnown: true } : {},
1421
1485
  maxTokens: positive(model.max_tokens),
1422
1486
  supportsImages: model.supports_images === true,
1423
1487
  ...ratio === void 0 ? {} : { ratio },
@@ -1461,10 +1525,12 @@ async function fetchAgentModels(credential, signal) {
1461
1525
  const id = firstString(params.model_id, model.model_id, model.model_alias, model.model_name);
1462
1526
  if (id === "") continue;
1463
1527
  const ratio = creditRatioOf(model) ?? creditRatioOf(params);
1528
+ const contextWindow = positive(params.context_window);
1464
1529
  out.push({
1465
1530
  id,
1466
1531
  name: firstString(model.model_name, model.model_alias, id),
1467
- contextWindow: positive(params.context_window),
1532
+ contextWindow,
1533
+ ...contextWindow > 0 ? { contextWindowKnown: true } : {},
1468
1534
  maxTokens: positive(params.max_tokens),
1469
1535
  supportsImages: model.supports_images === true,
1470
1536
  ...ratio === void 0 ? {} : { ratio }
@@ -1605,11 +1671,13 @@ async function clearQueueStatus(credential, chatId, model, signal) {
1605
1671
  * `gateway/config` 给福利模型标的是 393216 / 384000,而聊天端点实测超过 65536
1606
1672
  * 就流内报 InferHub.001001005.400;DSH 会把 catalog 的 maxTokens 原样当
1607
1673
  * max_tokens 发出去,照抄标称值等于让每个请求都失败。
1608
- * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由)。
1674
+ * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由);
1675
+ * 用户配置的按模型覆盖值与进程内学到的真实上界在这里压过发现值(issue #9)。
1609
1676
  *
1677
+ * @param contextWindowOverrides 按模型 id 覆盖 contextWindow(大小写不敏感)
1610
1678
  * @throws 三路全失败,或合并结果为空。
1611
1679
  */
1612
- async function fetchModels(credential, signal) {
1680
+ async function fetchModels(credential, signal, contextWindowOverrides = {}) {
1613
1681
  const settled = await Promise.all([
1614
1682
  fetchBuiltinModels(credential, signal).then((models) => ({
1615
1683
  source: "builtin",
@@ -1659,11 +1727,18 @@ async function fetchModels(credential, signal) {
1659
1727
  return {
1660
1728
  models: merged.map((model) => {
1661
1729
  const thinking = variants.get(model.id.toLowerCase());
1730
+ const override = contextWindowOverrideFor(contextWindowOverrides, model.id);
1731
+ const learned = learnedContextWindowFor(model.id);
1732
+ const upstreamKnown = model.contextWindowKnown === true;
1733
+ const discovered = model.contextWindow > 0 ? model.contextWindow : learned ?? UNKNOWN_CONTEXT_WINDOW;
1734
+ const base = override ?? discovered;
1735
+ const contextWindow = learned === void 0 ? base : Math.min(base, learned);
1662
1736
  return {
1663
1737
  ...model,
1664
1738
  ...thinking === void 0 ? {} : { thinking },
1665
- contextWindowKnown: model.contextWindow > 0,
1666
- contextWindow: model.contextWindow > 0 ? model.contextWindow : UNKNOWN_CONTEXT_WINDOW,
1739
+ ...override !== void 0 || learned !== void 0 || upstreamKnown ? { contextWindowKnown: true } : {},
1740
+ contextWindow,
1741
+ ...upstreamKnown && contextWindow !== model.contextWindow ? { contextWindowDiscovered: model.contextWindow } : {},
1667
1742
  maxTokens: Math.min(model.maxTokens > 0 ? model.maxTokens : UNKNOWN_MAX_TOKENS, maxTokensCeilingFor(model.id))
1668
1743
  };
1669
1744
  }),
@@ -1886,4 +1961,4 @@ async function claimDailyWelfare(credential, signal) {
1886
1961
  };
1887
1962
  }
1888
1963
  //#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 };
1964
+ 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-CsAz93vO.mjs";
2
+ import { H as modelDisplayName, V as mergeModelLists, W as setDiscoveredBenefitModels, u as fetchModels, z as isBenefitModel } from "./upstream-BsoeSKrY.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.2";
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.2",
6
6
  "packageManager": "pnpm@11.24.0",
7
7
  "author": "elegant01",
8
8
  "keywords": [