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.
package/lib/index.d.mts CHANGED
@@ -788,11 +788,23 @@ interface CodeArtsModelInfo {
788
788
  name: string;
789
789
  contextWindow: number;
790
790
  /**
791
- * `contextWindow` 是上游真的给的,还是兜底值(32768)。
791
+ * 这个 `contextWindow` 能不能当「上游真实规格」展示。
792
792
  *
793
- * 卡片只在上游给值时印「1M 上下文」这类规格;兜底值印出来就是假数据。
793
+ * 由各发现源在解析时置位(上游真给了字段、且 > 0),再一路带过合并与 `backfillParams`;
794
+ * 用户按模型覆盖、或进程内实测学到上界时,`fetchModels` 也会把它置位(那些值是我们
795
+ * 确认过的,可以展示)。
796
+ *
797
+ * 参数表补出来的值**永远不带**这个标记:`contextWindow` 同时是守卫输入,补一个保守值
798
+ * 让它保守拦截是对的;但把兜底值印成上游规格就是假数据(issue #9 的遗留项)。
794
799
  */
795
800
  contextWindowKnown?: boolean;
801
+ /**
802
+ * 上游标称的窗口(用户覆盖、实测学习之前的原值)。
803
+ *
804
+ * `contextWindow` 是**生效值**:用户按模型覆盖(issue #9)或进程内学到的上界都会
805
+ * 把它压低。卡片要把窗口改回「跟随上游」时需要这个原值,所以只在两者不等时才带出来。
806
+ */
807
+ contextWindowDiscovered?: number;
796
808
  maxTokens: number;
797
809
  supportsImages: boolean;
798
810
  /**
@@ -910,6 +922,14 @@ interface PreparedChatBody {
910
922
  * 那句话里没有模型、没有 token 数,用户无从下手。
911
923
  */
912
924
  error?: string;
925
+ /**
926
+ * 本次请求的 prompt 估算(messages + tools,含工具定义)。
927
+ *
928
+ * 两个用途:守卫算 room;shim 在「max_tokens 已到地板仍被判参数非法」时把它
929
+ * 记成该模型的真实窗口上界(issue #9 的诉求 2)。守卫和报错用的是同一份数值,
930
+ * 不会出现「守卫说 40 万、报错说 39 万」的漂移。
931
+ */
932
+ promptTokens: number;
913
933
  }
914
934
  /**
915
935
  * 把 OpenAI 风格 chat body 适配给 CodeArts /api/v2/chat/completions。
@@ -987,11 +1007,13 @@ interface CodeArtsQueueStatus {
987
1007
  * `gateway/config` 给福利模型标的是 393216 / 384000,而聊天端点实测超过 65536
988
1008
  * 就流内报 InferHub.001001005.400;DSH 会把 catalog 的 maxTokens 原样当
989
1009
  * max_tokens 发出去,照抄标称值等于让每个请求都失败。
990
- * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由)。
1010
+ * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由);
1011
+ * 用户配置的按模型覆盖值与进程内学到的真实上界在这里压过发现值(issue #9)。
991
1012
  *
1013
+ * @param contextWindowOverrides 按模型 id 覆盖 contextWindow(大小写不敏感)
992
1014
  * @throws 三路全失败,或合并结果为空。
993
1015
  */
994
- declare function fetchModels(credential: CodeArtsResolved, signal?: AbortSignal): Promise<ModelDiscoveryResult>;
1016
+ declare function fetchModels(credential: CodeArtsResolved, signal?: AbortSignal, contextWindowOverrides?: Readonly<Record<string, number>>): Promise<ModelDiscoveryResult>;
995
1017
  //#endregion
996
1018
  //#region src/auth.d.ts
997
1019
  /** 持久化的完整凭证。 */
@@ -1620,6 +1642,13 @@ interface CodeArtsShimOptions {
1620
1642
  debug?: (message: string) => void;
1621
1643
  /** 本地槽位满时最多等多久(缺省 30 秒)。测试用它把等待压到毫秒级。 */
1622
1644
  localSlotWaitMs?: number;
1645
+ /**
1646
+ * 按模型 id 覆盖 contextWindow(用户配置,每次请求实时读取)。
1647
+ *
1648
+ * 目录值来自上游标称,免费档真实窗口可能小得多(issue #9)。回调而不是快照:
1649
+ * 用户在设置里改完,下一句话就该用新值,不必等下一轮模型发现。
1650
+ */
1651
+ contextWindowOverrides?: () => Readonly<Record<string, number>> | undefined;
1623
1652
  }
1624
1653
  declare function createCodeArtsShim(options: CodeArtsShimOptions): CodeArtsShim;
1625
1654
  //#endregion
@@ -1792,14 +1821,15 @@ interface DiscoveryOutcome {
1792
1821
  *
1793
1822
  * @param store 账号文档;逐个 `resolve()` 以拿到已续期的签名材料
1794
1823
  * @param signal 取消信号(宿主关停时用)
1824
+ * @param contextWindowOverrides 用户按模型 id 配置的窗口覆盖值(issue #9)
1795
1825
  */
1796
- declare function discoverModels(store: CodeArtsAccountStore, signal?: AbortSignal): Promise<DiscoveryOutcome>;
1826
+ declare function discoverModels(store: CodeArtsAccountStore, signal?: AbortSignal, contextWindowOverrides?: Readonly<Record<string, number>>): Promise<DiscoveryOutcome>;
1797
1827
  /**
1798
1828
  * 发现并**提交**到全局目录:目录内容 + 福利集合。
1799
1829
  *
1800
1830
  * @returns 提交后的目录;没有任何账号成功时返回 `undefined`(调用方保留原目录)
1801
1831
  */
1802
- declare function refreshCatalog(store: CodeArtsAccountStore, catalog: CodeArtsCatalog, signal?: AbortSignal): Promise<DiscoveryOutcome | undefined>;
1832
+ declare function refreshCatalog(store: CodeArtsAccountStore, catalog: CodeArtsCatalog, signal?: AbortSignal, contextWindowOverrides?: Readonly<Record<string, number>>): Promise<DiscoveryOutcome | undefined>;
1803
1833
  //#endregion
1804
1834
  //#region src/index.d.ts
1805
1835
  /** Stable Cordis plugin name. */
@@ -1812,6 +1842,14 @@ declare const CODEARTS_SETTINGS_NS: SettingsNamespace;
1812
1842
  interface Config {
1813
1843
  /** Allowlist of CodeArts model ids offered in the model pickers. */
1814
1844
  enabledModels?: string[];
1845
+ /**
1846
+ * 按模型 id 强制覆盖 `contextWindow`(id 大小写不敏感,值 = tokens)。
1847
+ *
1848
+ * 动态发现给的是上游/网关的标称值,免费档的真实窗口可能远小于它、还会漂
1849
+ * (issue #9:deepseek-v4.1-flash-1017 标称 1M、实测 ≈49 万)。覆盖值压过发现值;
1850
+ * 进程内按实测学到的上界仍会在此基础上继续往下钳。
1851
+ */
1852
+ contextWindowOverrides?: Record<string, number>;
1815
1853
  /** 对话输入框下方那行「积分 N」是否显示。缺省 = 显示(老配置不改行为)。 */
1816
1854
  showCreditDock?: boolean;
1817
1855
  /** 等上游开流时那行「排队第 N 位」是否显示。缺省 = 显示。 */
package/lib/index.mjs CHANGED
@@ -1,8 +1,8 @@
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-CsAz93vO.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-BsoeSKrY.mjs";
3
+ import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-DLMVdsWB.mjs";
4
4
  import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
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";
5
+ import { c as keeperLogPath, d as keeperStats, f as spawnKeeper, i as clearKeeperHandoff, l as keeperScriptPath, n as KEEPER_STALE_MS, p as stopKeeper, s as keeperHandoffRecent } from "./keeper-DJLwIiR4.mjs";
6
6
  import { appendFileSync, statSync, writeFileSync } from "node:fs";
7
7
  import z from "@deepseek-ai/schemastery";
8
8
  import { randomBytes, timingSafeEqual } from "node:crypto";
@@ -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,38 @@ 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
+ const known = window === null ? model.contextWindowKnown : true;
3118
+ const patched = {
3119
+ ...rest,
3120
+ contextWindow: target,
3121
+ ...known === true ? { contextWindowKnown: true } : {}
3122
+ };
3123
+ return contextWindowDiscovered === void 0 || contextWindowDiscovered === target ? patched : {
3124
+ ...patched,
3125
+ contextWindowDiscovered
3126
+ };
3127
+ }));
3128
+ return true;
3129
+ };
3004
3130
  const dock = () => ({
3005
3131
  credits: current().showCreditDock !== false,
3006
3132
  queue: current().showQueueDock !== false,
@@ -3065,6 +3191,11 @@ function apply(ctx, rawConfig) {
3065
3191
  ...keeperLastError === void 0 ? {} : { error: keeperLastError },
3066
3192
  logPath
3067
3193
  };
3194
+ if (keeperHandoffRecent()) return {
3195
+ alive: false,
3196
+ error: "守护进程为更新安装让路,重启后会自动恢复",
3197
+ logPath
3198
+ };
3068
3199
  try {
3069
3200
  await setDock({ keepAliveDaemon: false });
3070
3201
  } catch {}
@@ -3106,6 +3237,7 @@ function apply(ctx, rawConfig) {
3106
3237
  keeperSpawnedAt = Date.now();
3107
3238
  if (outcome.ok) {
3108
3239
  keeperLastError = void 0;
3240
+ clearKeeperHandoff();
3109
3241
  ctx.logger.debug(`dsh-codearts: credential keeper running (pid ${outcome.pid ?? "?"})`);
3110
3242
  } else {
3111
3243
  keeperLastError = outcome.reason ?? "spawn failed";
@@ -3128,6 +3260,7 @@ function apply(ctx, rawConfig) {
3128
3260
  if (!keeperRunning() && Date.now() - keeperSpawnedAt >= KEEPER_START_GRACE_MS) {
3129
3261
  keeperTimer = void 0;
3130
3262
  keeperSpawnedAt = 0;
3263
+ if (keeperHandoffRecent()) return;
3131
3264
  await setDock({ keepAliveDaemon: false }).catch(() => false);
3132
3265
  return;
3133
3266
  }
@@ -3217,6 +3350,8 @@ function apply(ctx, rawConfig) {
3217
3350
  models: () => catalog.current(),
3218
3351
  enabledModels,
3219
3352
  setEnabledModels,
3353
+ contextWindowOverrides: () => current().contextWindowOverrides,
3354
+ setContextWindowOverride,
3220
3355
  pool: () => pool.list(),
3221
3356
  reviveAccount: (id) => pool.revive(id),
3222
3357
  usage: () => usage.snapshot(),
@@ -3243,7 +3378,7 @@ function apply(ctx, rawConfig) {
3243
3378
  return outcome;
3244
3379
  },
3245
3380
  refreshModels: async () => {
3246
- const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS));
3381
+ const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS), current().contextWindowOverrides);
3247
3382
  const models = catalog.current();
3248
3383
  return {
3249
3384
  models: models.length,
@@ -3277,7 +3412,7 @@ function apply(ctx, rawConfig) {
3277
3412
  const discover = async () => {
3278
3413
  if (stopped) return;
3279
3414
  try {
3280
- const outcome = await refreshCatalog(store, catalog, abort.signal);
3415
+ const outcome = await refreshCatalog(store, catalog, abort.signal, current().contextWindowOverrides);
3281
3416
  if (outcome === void 0 || stopped) return;
3282
3417
  if (outcome.anySucceeded) {
3283
3418
  const free = outcome.models.filter((model) => model.benefit === true).length;
@@ -3420,7 +3555,8 @@ function apply(ctx, rawConfig) {
3420
3555
  usage,
3421
3556
  queue,
3422
3557
  logger: ctx.logger,
3423
- debug: writeDebugLog
3558
+ debug: writeDebugLog,
3559
+ contextWindowOverrides: () => current().contextWindowOverrides
3424
3560
  });
3425
3561
  usage.load().catch(() => {});
3426
3562
  shim.ready.then(async () => {
@@ -1,6 +1,6 @@
1
- import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { join } from "node:path";
3
+ import { basename, dirname, join } from "node:path";
4
4
  import { spawn } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  //#region src/keeper.ts
@@ -18,9 +18,11 @@ import { fileURLToPath } from "node:url";
18
18
  * ## 进程形态
19
19
  *
20
20
  * DSH Desktop 是 Electron,宿主 exe 可以直接当 Node 用:设置
21
- * `ELECTRON_RUN_AS_NODE=1` 后启动它就是 node 24.21.0(已实测)。所以不依赖用户
22
- * 装没装 node,也不引入任何原生依赖。启动后 `detached` + `unref` + `stdio:'ignore'`,
23
- * DSH 退出它不跟着退出(同样已实测)。
21
+ * `ELECTRON_RUN_AS_NODE=1` 后启动它就是 node 24.21.0(已实测)。但**优先用宿主自带的
22
+ * 真 node.exe**(`resources/runtime/<runtime>/dependencies/node/bin/node.exe`)—— 宿主 exe 的
23
+ * 进程名是 `DeepSeek Harness.exe`,会被更新安装器当成「应用还在跑」而挡住更新
24
+ * (见 `bundledNodeExecutable`)。两者都不依赖用户装没装 node,也不引入任何原生依赖。
25
+ * 启动后 `detached` + `unref` + `stdio:'ignore'`,DSH 退出它不跟着退出(同样已实测)。
24
26
  *
25
27
  * ## 谁有权续期(重要)
26
28
  *
@@ -100,10 +102,42 @@ function keeperScriptPath() {
100
102
  return fileURLToPath(new URL("./keeper-main.mjs", import.meta.url));
101
103
  }
102
104
  /**
105
+ * 宿主自带的 node(`resources/runtime/<runtime>/dependencies/node/bin/node.exe`)。
106
+ *
107
+ * 为什么不直接用 `process.execPath`:那是宿主 exe,keeper 的进程名就成了
108
+ * `DeepSeek Harness.exe`。DSH 的更新安装器会枚举同名进程判断「应用是否已关闭」,
109
+ * 看到 keeper 就认为应用还在跑 —— 更新在十秒左右中止,而且安装器不会把应用拉回来
110
+ * (2026-11-16 实测:装 0.2.2-rc.3 时两次都是被这个挡住的)。
111
+ *
112
+ * 运行时目录名会随版本变(`primary-runtime` / `dsh-primary-runtime`),所以按目录枚举,
113
+ * 不把某一版的名字写死。拿不到就返回 undefined,由调用方退回宿主 exe。
114
+ */
115
+ function bundledNodeExecutable() {
116
+ const name = process.platform === "win32" ? "node.exe" : "node";
117
+ const roots = [];
118
+ const resources = process.resourcesPath;
119
+ if (typeof resources === "string" && resources !== "") roots.push(resources);
120
+ roots.push(join(dirname(process.execPath), "resources"));
121
+ for (const root of roots) {
122
+ const runtime = join(root, "runtime");
123
+ let runtimes;
124
+ try {
125
+ runtimes = readdirSync(runtime);
126
+ } catch {
127
+ continue;
128
+ }
129
+ for (const runtimeName of runtimes) {
130
+ const candidate = join(runtime, runtimeName, "dependencies", "node", "bin", name);
131
+ if (existsSync(candidate)) return candidate;
132
+ }
133
+ }
134
+ }
135
+ /**
103
136
  * 拿 `ELECTRON_RUN_AS_NODE` 这条路启动 node 所需的 exe。
104
137
  *
105
138
  * 优先级:宿主自己给的 `DSH_DESKTOP_NODE_EXECUTABLE`(Desktop 注入,最准)→
106
- * `process.execPath`(Electron 自己或普通 node 都适用)→ PATH 里的 `node`。
139
+ * 宿主自带的 node.exe(见 `bundledNodeExecutable`,进程名不会撞 DSH)→
140
+ * `process.execPath`(Electron 自己或普通 node 都适用)。
107
141
  */
108
142
  function nodeLauncher() {
109
143
  const desktop = process.env.DSH_DESKTOP_NODE_EXECUTABLE;
@@ -114,6 +148,11 @@ function nodeLauncher() {
114
148
  ELECTRON_RUN_AS_NODE: "1"
115
149
  }
116
150
  };
151
+ const bundled = bundledNodeExecutable();
152
+ if (bundled !== void 0) return {
153
+ command: bundled,
154
+ env: { ...process.env }
155
+ };
117
156
  return {
118
157
  command: process.execPath,
119
158
  env: {
@@ -123,6 +162,42 @@ function nodeLauncher() {
123
162
  };
124
163
  }
125
164
  /**
165
+ * 这是 DSH 更新安装器在 `%TEMP%` 里建的插件目录吗。
166
+ *
167
+ * 安装器(NSIS)一启动就把自己签名的 `window-frame.dll` 解到 `%TEMP%\ns*.tmp\`。
168
+ * 用「目录名 + 那个 dll」两条一起判,用户装别的软件留下同名目录也不会误伤。
169
+ */
170
+ function isDshInstallerTempDir(path) {
171
+ if (!/^ns[\w.-]{2,}\.tmp$/i.test(basename(path))) return false;
172
+ return existsSync(join(path, "window-frame.dll"));
173
+ }
174
+ /** 「让路」标记:keeper 为更新安装器主动退出时写,插件据此不把开关关掉。 */
175
+ function keeperHandoffPath(home) {
176
+ return join(home ?? dshHome(), ".codearts-keeper.handoff");
177
+ }
178
+ function writeKeeperHandoff(reason, home) {
179
+ try {
180
+ writeFileSync(keeperHandoffPath(home), JSON.stringify({
181
+ at: Date.now(),
182
+ reason
183
+ }), { mode: 384 });
184
+ } catch {}
185
+ }
186
+ /** 最近发生过一次「为更新让路」的退出吗(默认 15 分钟内)。 */
187
+ function keeperHandoffRecent(home, maxAgeMs = 9e5) {
188
+ try {
189
+ const parsed = JSON.parse(readFileSync(keeperHandoffPath(home), "utf8"));
190
+ return typeof parsed.at === "number" && Date.now() - parsed.at <= maxAgeMs;
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
195
+ function clearKeeperHandoff(home) {
196
+ try {
197
+ if (existsSync(keeperHandoffPath(home))) unlinkSync(keeperHandoffPath(home));
198
+ } catch {}
199
+ }
200
+ /**
126
201
  * 起一个守护进程。已经在跑就返回现有的那个(幂等,不重复起)。
127
202
  *
128
203
  * `detached` + `unref` + `stdio:'ignore'` 三件套缺一不可:少了任何一个,DSH 退出时
@@ -212,4 +287,4 @@ function stopRequested(home) {
212
287
  return existsSync(join(home ?? dshHome(), ".codearts-keeper.stop"));
213
288
  }
214
289
  //#endregion
215
- export { keeperLogPath as a, keeperStats as c, stopKeeper as d, stopRequested as f, clearKeeperState as i, readKeeperState as l, KEEPER_STALE_MS as n, keeperScriptPath as o, writeKeeperState as p, KEEPER_TICK_MS as r, keeperStatePath as s, KEEPER_HEARTBEAT_MS as t, spawnKeeper as u };
290
+ export { clearKeeperState as a, keeperLogPath as c, keeperStats as d, spawnKeeper as f, writeKeeperState as g, writeKeeperHandoff as h, clearKeeperHandoff as i, keeperScriptPath as l, stopRequested as m, KEEPER_STALE_MS as n, isDshInstallerTempDir as o, stopKeeper as p, KEEPER_TICK_MS as r, keeperHandoffRecent as s, KEEPER_HEARTBEAT_MS as t, keeperStatePath as u };
@@ -1,6 +1,7 @@
1
- import { d as OAuthTokenError, f as defaultLoginConfig, i as codeartsAccountsPath, l as readAccountDocument, p as refreshToken, u as writeJsonAtomic } from "./auth-Ch0vYSAo.mjs";
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
- import { appendFileSync, existsSync, unlinkSync } from "node:fs";
1
+ import { d as OAuthTokenError, f as defaultLoginConfig, i as codeartsAccountsPath, l as readAccountDocument, p as refreshToken, u as writeJsonAtomic } from "./auth-CsAz93vO.mjs";
2
+ import { a as clearKeeperState, c as keeperLogPath, d as keeperStats, g as writeKeeperState, h as writeKeeperHandoff, i as clearKeeperHandoff, m as stopRequested, o as isDshInstallerTempDir, r as KEEPER_TICK_MS, t as KEEPER_HEARTBEAT_MS, u as keeperStatePath } from "./keeper-DJLwIiR4.mjs";
3
+ import { appendFileSync, existsSync, unlinkSync, watch } from "node:fs";
4
+ import { join } from "node:path";
4
5
  //#region src/keeper-main.ts
5
6
  /**
6
7
  * dsh-codearts 凭证守护进程(独立入口,由 DSH 用 `ELECTRON_RUN_AS_NODE=1` 拉起)。
@@ -39,17 +40,16 @@ function log(message) {
39
40
  *
40
41
  * 从卡片连点两次、或同时开两个 DSH 窗口时,第二次 spawn 必须让路 —— 两个进程同时
41
42
  * 刷 refresh_token 就是上面说的那个翻车场景。
43
+ *
44
+ * 判据用 `keeperStats`(心跳 + pid 都算),不能只看 pid:上一份 keeper 被强杀后
45
+ * 状态文件会留在盘上,而 Windows 很快就把那个 pid 发给别的进程 —— 只探 pid 会
46
+ * 把一个正常的新进程当成「已有 keeper」,于是每次启动都立刻退出(2026-11-16 实测)。
42
47
  */
43
48
  function alreadyRunning() {
44
- const state = readKeeperState(home);
45
- if (state === void 0) return void 0;
46
- if (state.pid === process.pid) return void 0;
47
- try {
48
- process.kill(state.pid, 0);
49
- return state.pid;
50
- } catch (error) {
51
- return error?.code === "EPERM" ? state.pid : void 0;
52
- }
49
+ const stats = keeperStats(home);
50
+ if (!stats.alive || stats.state === void 0) return void 0;
51
+ if (stats.state.pid === process.pid) return void 0;
52
+ return stats.state.pid;
53
53
  }
54
54
  /**
55
55
  * 一轮续期:读文档 → 逐个续 → 写回。
@@ -144,6 +144,39 @@ async function tick(state) {
144
144
  };
145
145
  if (refreshed > 0 || needsLogin.length > 0) log(`pass done: checked=${checked} refreshed=${refreshed} needsLogin=${needsLogin.length}`);
146
146
  }
147
+ /**
148
+ * 更新安装器一出现就通知调用方让路。
149
+ *
150
+ * 为什么需要:安装器启动后会枚举进程判断「应用是否已关闭」,keeper 只要还在跑就
151
+ * 可能被当成应用本身,更新在十秒左右中止、也不把应用拉回来(`keeper.ts` 的
152
+ * `bundledNodeExecutable` 注释里有完整现场)。换 node.exe 是主路,这里是双保险 —
153
+ * 安装器就算按安装路径匹配也挡不住。
154
+ *
155
+ * 实现上用 `fs.watch` 盯 `%TEMP%`(事件驱动,不轮询):只有新出现的 `ns*.tmp`
156
+ * 目录里真有安装器的 `window-frame.dll` 才算数,用户装别的软件不会误伤。
157
+ */
158
+ function watchForUpdateInstaller(onSeen) {
159
+ if (process.platform !== "win32") return;
160
+ const root = process.env.TEMP ?? process.env.TMP;
161
+ if (root === void 0 || root === "") return;
162
+ const confirm = (name, attempt) => {
163
+ if (!name.toLowerCase().startsWith("ns")) return;
164
+ const dir = join(root, name);
165
+ if (isDshInstallerTempDir(dir)) {
166
+ onSeen();
167
+ return;
168
+ }
169
+ if (attempt < 2) setTimeout(() => confirm(name, attempt + 1), 500);
170
+ };
171
+ try {
172
+ watch(root, (_event, filename) => {
173
+ if (filename === null) return;
174
+ confirm(String(filename), 0);
175
+ });
176
+ } catch (error) {
177
+ log(`installer watch unavailable: ${error instanceof Error ? error.message : String(error)}`);
178
+ }
179
+ }
147
180
  async function main() {
148
181
  const other = alreadyRunning();
149
182
  if (other !== void 0) {
@@ -167,6 +200,23 @@ async function main() {
167
200
  clearKeeperState(home);
168
201
  process.exit(0);
169
202
  };
203
+ clearKeeperHandoff(home);
204
+ /**
205
+ * 为更新安装让路。
206
+ *
207
+ * 和 `shutdown` 的区别只有一条:留一个「让路」标记。插件看到它会知道这是预期内
208
+ * 的退出,不把「常驻保活」开关关掉 —— 新版应用起来后开关还开着,keeper 会照常被
209
+ * 拉起,用户不会发现自己"被关了保活"。
210
+ */
211
+ const stepAside = (reason) => {
212
+ if (stopped) return;
213
+ log(`keeper stepping aside: ${reason}`);
214
+ writeKeeperHandoff(reason, home);
215
+ clearKeeperState(home);
216
+ stopped = true;
217
+ process.exit(0);
218
+ };
219
+ watchForUpdateInstaller(() => stepAside("update installer detected"));
170
220
  for (const signal of [
171
221
  "SIGINT",
172
222
  "SIGTERM",