dsh-codearts 1.4.8 → 1.4.10

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
@@ -807,6 +807,13 @@ interface CodeArtsModelInfo {
807
807
  */
808
808
  contextWindowDiscovered?: number;
809
809
  maxTokens: number;
810
+ /**
811
+ * 上游声明的输出上限(用户覆盖之前的原值,issue #15)。
812
+ *
813
+ * `maxTokens` 是**生效值**:用户按模型覆盖、或进程内降档都会改它。卡片把输出上限
814
+ * 「改回跟随上游」时需要这个原值,所以只在两者不等时才带出来。
815
+ */
816
+ maxTokensDiscovered?: number;
810
817
  supportsImages: boolean;
811
818
  /**
812
819
  * 该模型可选的思考强度。
@@ -910,7 +917,13 @@ interface CodeArtsResolved {
910
917
  securityToken: string;
911
918
  }
912
919
  declare function canonicalModel(id: string): string;
913
- /** 该模型可用的 max_tokens 上限(实测值与会话内学到的更低值取小)。 */
920
+ /**
921
+ * 该模型可用的 max_tokens 上限(用户覆盖 > 实测值,再被会话内学到的更低值压住)。
922
+ *
923
+ * 用户覆盖(issue #15)就是**天花板本身**,不只是替换目录声明值:企业自定义模型的
924
+ * 实测上限是 131072,而全局 `MAX_TOKENS_CEILING` 是 65536,不给覆盖值穿透这道墙,
925
+ * 手动设置对 128K 的用例就没意义。设过头的值由降档机制(400 → 折半重发)自愈。
926
+ */
914
927
  declare function maxTokensCeilingFor(id: string): number;
915
928
  interface PreparedChatBody {
916
929
  url: string;
@@ -1008,7 +1021,8 @@ interface CodeArtsQueueStatus {
1008
1021
  * - **maxTokens 钳到该模型的实测上限**(`MEASURED_MAX_TOKENS`)。上游
1009
1022
  * `gateway/config` 给福利模型标的是 393216 / 384000,而聊天端点实测超过 65536
1010
1023
  * 就流内报 InferHub.001001005.400;DSH 会把 catalog 的 maxTokens 原样当
1011
- * max_tokens 发出去,照抄标称值等于让每个请求都失败。
1024
+ * max_tokens 发出去,照抄标称值等于让每个请求都失败。用户按模型设了覆盖值时
1025
+ * 覆盖值直接当天花板,不再被 65536 压住(issue #15)。
1012
1026
  * - contextWindow 用发现值(只影响 DSH 的上下文计量与截断余量,不影响路由);
1013
1027
  * 用户配置的按模型覆盖值与进程内学到的真实上界在这里压过发现值(issue #9)。
1014
1028
  *
@@ -1278,13 +1292,39 @@ declare class CodeArtsAccountPool {
1278
1292
  private readonly paused;
1279
1293
  /** 用户置顶的账号:选号时排在最前面,不再按「最久未用」轮它。 */
1280
1294
  private readonly preferred;
1281
- private readonly maxConcurrent;
1295
+ private maxConcurrent;
1296
+ /**
1297
+ * 按账号的上限覆盖(账号 id → 并发数,issue #16 后续)。
1298
+ *
1299
+ * 上游配额按账号算:一个号可能个人档(3 个会话)、另一个企业档(5 个)。
1300
+ * 没有覆盖的号用 `maxConcurrent` 这个默认值。
1301
+ */
1302
+ private accountCaps;
1282
1303
  private readonly now;
1283
1304
  /** 等槽位的唤醒器:槽位释放 / 池里新增账号 / 账号复活时逐个唤醒。 */
1284
1305
  private readonly waiters;
1285
1306
  constructor(ids: readonly string[], options?: PoolOptions);
1286
1307
  /** 让池与账号文档对齐:新增的进来,删掉的出去。已有账号的运行时状态保留。 */
1287
1308
  sync(ids: readonly string[]): void;
1309
+ /**
1310
+ * 调整「没有单独设置」的号的默认上限(issue #16)。
1311
+ *
1312
+ * 直接改运行时对象而不重建池:冷却、避让窗口、槽位计数都是本进程里学出来的,
1313
+ * 重建会把它们全丢掉。调大时要唤醒等槽位的请求,否则它们会睡到下一次释放。
1314
+ * 单独设过上限的号不动。
1315
+ */
1316
+ setMaxConcurrent(value: number): void;
1317
+ /**
1318
+ * 一次性替换「按账号覆盖」表(设置变更时从配置整表灌进来)。
1319
+ *
1320
+ * 表里没有的号退回默认上限;和 `setMaxConcurrent` 一样保持运行时状态不动。
1321
+ */
1322
+ setAccountCaps(caps: Readonly<Record<string, number>>): void;
1323
+ /** 单个账号设/清上限(`null` = 回到默认)。卡片上每张账号卡各有一枚加减器。 */
1324
+ setAccountCap(id: string, value: number | null): void;
1325
+ /** 当前按账号覆盖表的副本(状态接口给卡片按号显示)。 */
1326
+ accountCapOverrides(): Record<string, number>;
1327
+ private applyCaps;
1288
1328
  list(): AccountRuntime[];
1289
1329
  get(id: string): AccountRuntime | undefined;
1290
1330
  /** 账号本身可用(没被禁用、不在冷却中)。 */
@@ -1882,6 +1922,30 @@ interface Config {
1882
1922
  * 进程内按实测学到的上界仍会在此基础上继续往下钳。
1883
1923
  */
1884
1924
  contextWindowOverrides?: Record<string, number>;
1925
+ /**
1926
+ * 按模型 id 强制覆盖 `maxTokens`(单次输出上限,id 大小写不敏感,issue #15)。
1927
+ *
1928
+ * 企业自定义模型实测能到 128K,而插件全局天花板是 65536(2026-09-30 对福利模型
1929
+ * 实测的值)。覆盖值直接作为该模型的天花板、可越过那道墙;设过头的值仍由
1930
+ * 「400 → 折半重发」的降档机制自愈。
1931
+ */
1932
+ maxTokensOverrides?: Record<string, number>;
1933
+ /**
1934
+ * 每个账号的本地并发上限(issue #16),缺省 2。
1935
+ *
1936
+ * 上游会话槽位随套餐不同:个人免费档实测 3、企业版实测 5(上游报错原话
1937
+ * 「并发会话数已达上限(5个)」)。默认留 1 个给 CodeArts 网页端,所以是 3−1;
1938
+ * 企业档用户调大才能用上闲置的并行槽位。改完立即生效,无需重启。
1939
+ */
1940
+ maxConcurrentPerAccount?: number;
1941
+ /**
1942
+ * 按**账号**覆盖并发上限(账号 id → 并发数,issue #16 后续)。
1943
+ *
1944
+ * 上游配额按账号算:一个号可能个人档(3 个会话)、另一个企业档(5 个)。
1945
+ * 没写在这里的号用 `maxConcurrentPerAccount`(默认 2)。卡片上每张账号卡各有一个
1946
+ * −/+,改的就是这张表;也可以直接写配置。
1947
+ */
1948
+ maxConcurrentOverrides?: Record<string, number>;
1885
1949
  /**
1886
1950
  * 宿主的请求重试预算(issue #14)。
1887
1951
  *
package/lib/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { a as codeartsAuthPath, c as credentialFromOAuth, g as startLogin, i as codeartsAccountsPath, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-BRlNY6dB.mjs";
2
- import { A as queueFrame, B as filterEnabledModels, C as isWelfareClaimedStatus, D as modelUnavailableReasonText, E as maxTokensCeilingFor, F as CodeArtsCatalog, H as isBenefitBlocked, I as FALLBACK_CODEARTS_MODELS, M as signedGet, N as upstreamErrorMessage, O as pickDailyWelfareCampaign, R as clearBenefitBlocked, S as isTpmLimit, T as learnedContextWindowFor, U as isBenefitModel, V as forgetModelUnavailable, W as markModelUnavailable, _ as isNotMultimodal, a as claimDailyWelfare, b as isQueueRejectText, c as degradeTokenCeiling, d as fetchQueueStatus, f as fetchWelfareCampaigns, g as isModelNotAccessible, h as isIamTokenError, i as chatStream, j as rateLimitFrame, k as prepareChatBody, l as fetchCallerIdentity, m as isConcurrencyCap, n as SNAP_HOST, o as clearQueueStatus, p as firstFrameError, q as modelUnavailableReason, r as canonicalModel, s as contextWindowOverrideFor, t as MAX_TOKENS_FLOOR, u as fetchModels, v as isParamInvalidFrame, w as learnContextWindow, x as isQueueableRate, y as isQueueReject, z as creditRatioLabel } from "./upstream-CgQXomCI.mjs";
3
- import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-qgKLf1Cq.mjs";
1
+ import { a as codeartsAuthPath, c as credentialFromOAuth, g as startLogin, i as codeartsAccountsPath, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-BaxN0iKC.mjs";
2
+ import { $ as withMaxTokensOverride, A as prepareChatBody, C as isWelfareClaimedStatus, D as modelUnavailableReasonText, E as maxTokensCeilingFor, F as signedGet, G as isBenefitBlocked, H as creditRatioLabel, I as upstreamErrorMessage, K as isBenefitModel, M as rateLimitFrame, N as setMaxTokenOverride, O as overrideValueFor, P as setMaxTokenOverrides, Q as withContextWindowOverride, R as CodeArtsCatalog, S as isTpmLimit, T as learnedContextWindowFor, U as filterEnabledModels, V as clearBenefitBlocked, W as forgetModelUnavailable, X as modelUnavailableReason, _ as isNotMultimodal, a as claimDailyWelfare, b as isQueueRejectText, c as degradeTokenCeiling, d as fetchQueueStatus, f as fetchWelfareCampaigns, g as isModelNotAccessible, h as isIamTokenError, i as chatStream, j as queueFrame, k as pickDailyWelfareCampaign, l as fetchCallerIdentity, m as isConcurrencyCap, n as SNAP_HOST, o as clearQueueStatus, p as firstFrameError, q as markModelUnavailable, r as canonicalModel, s as contextWindowOverrideFor, t as MAX_TOKENS_FLOOR, u as fetchModels, v as isParamInvalidFrame, w as learnContextWindow, x as isQueueableRate, y as isQueueReject, z as FALLBACK_CODEARTS_MODELS } from "./upstream-BX6-klXI.mjs";
3
+ import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-CUnRcNkz.mjs";
4
4
  import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
5
5
  import { c as keeperLogPath, f as keeperStats, i as clearKeeperHandoff, l as keeperNextPassAt, m as stopKeeper, n as KEEPER_STALE_MS, p as spawnKeeper, s as keeperHandoffRecent, u as keeperScriptPath } from "./keeper-BWHQDFAh.mjs";
6
6
  import { appendFileSync, statSync, writeFileSync } from "node:fs";
@@ -52,6 +52,13 @@ var CodeArtsAccountPool = class {
52
52
  /** 用户置顶的账号:选号时排在最前面,不再按「最久未用」轮它。 */
53
53
  preferred = /* @__PURE__ */ new Set();
54
54
  maxConcurrent;
55
+ /**
56
+ * 按账号的上限覆盖(账号 id → 并发数,issue #16 后续)。
57
+ *
58
+ * 上游配额按账号算:一个号可能个人档(3 个会话)、另一个企业档(5 个)。
59
+ * 没有覆盖的号用 `maxConcurrent` 这个默认值。
60
+ */
61
+ accountCaps = /* @__PURE__ */ new Map();
55
62
  now;
56
63
  /** 等槽位的唤醒器:槽位释放 / 池里新增账号 / 账号复活时逐个唤醒。 */
57
64
  waiters = /* @__PURE__ */ new Set();
@@ -64,13 +71,16 @@ var CodeArtsAccountPool = class {
64
71
  sync(ids) {
65
72
  const wanted = new Set(ids);
66
73
  const before = this.accounts.size;
67
- for (const id of [...this.accounts.keys()]) if (!wanted.has(id)) this.accounts.delete(id);
74
+ for (const id of [...this.accounts.keys()]) if (!wanted.has(id)) {
75
+ this.accounts.delete(id);
76
+ this.accountCaps.delete(id);
77
+ }
68
78
  for (const id of ids) {
69
79
  if (this.accounts.has(id)) continue;
70
80
  this.accounts.set(id, {
71
81
  id,
72
82
  activeConcurrent: 0,
73
- maxConcurrent: this.maxConcurrent,
83
+ maxConcurrent: this.accountCaps.get(id) ?? this.maxConcurrent,
74
84
  coolUntil: 0,
75
85
  cappedUntil: 0,
76
86
  lastCapAt: 0,
@@ -82,6 +92,54 @@ var CodeArtsAccountPool = class {
82
92
  }
83
93
  if (this.accounts.size !== before) this.notifyWaiters();
84
94
  }
95
+ /**
96
+ * 调整「没有单独设置」的号的默认上限(issue #16)。
97
+ *
98
+ * 直接改运行时对象而不重建池:冷却、避让窗口、槽位计数都是本进程里学出来的,
99
+ * 重建会把它们全丢掉。调大时要唤醒等槽位的请求,否则它们会睡到下一次释放。
100
+ * 单独设过上限的号不动。
101
+ */
102
+ setMaxConcurrent(value) {
103
+ if (!Number.isFinite(value)) return;
104
+ const next = Math.max(1, Math.floor(value));
105
+ if (next === this.maxConcurrent) return;
106
+ this.maxConcurrent = next;
107
+ this.applyCaps();
108
+ this.notifyWaiters();
109
+ }
110
+ /**
111
+ * 一次性替换「按账号覆盖」表(设置变更时从配置整表灌进来)。
112
+ *
113
+ * 表里没有的号退回默认上限;和 `setMaxConcurrent` 一样保持运行时状态不动。
114
+ */
115
+ setAccountCaps(caps) {
116
+ const next = /* @__PURE__ */ new Map();
117
+ for (const [id, value] of Object.entries(caps)) {
118
+ const key = id.trim();
119
+ if (key === "" || !Number.isFinite(value)) continue;
120
+ next.set(key, Math.max(1, Math.floor(value)));
121
+ }
122
+ this.accountCaps = next;
123
+ this.applyCaps();
124
+ this.notifyWaiters();
125
+ }
126
+ /** 单个账号设/清上限(`null` = 回到默认)。卡片上每张账号卡各有一枚加减器。 */
127
+ setAccountCap(id, value) {
128
+ const key = id.trim();
129
+ if (key === "") return;
130
+ if (value === null) this.accountCaps.delete(key);
131
+ else if (Number.isFinite(value)) this.accountCaps.set(key, Math.max(1, Math.floor(value)));
132
+ else return;
133
+ this.applyCaps();
134
+ this.notifyWaiters();
135
+ }
136
+ /** 当前按账号覆盖表的副本(状态接口给卡片按号显示)。 */
137
+ accountCapOverrides() {
138
+ return Object.fromEntries(this.accountCaps);
139
+ }
140
+ applyCaps() {
141
+ for (const account of this.accounts.values()) account.maxConcurrent = this.accountCaps.get(account.id) ?? this.maxConcurrent;
142
+ }
85
143
  list() {
86
144
  return [...this.accounts.values()];
87
145
  }
@@ -1842,6 +1900,16 @@ const CODEARTS_MODELS_SELECTION_PATH = "/api/codearts/enabled-models";
1842
1900
  * `{ id, window }`,`window: null` 表示删除覆盖、回到跟随上游。
1843
1901
  */
1844
1902
  const CODEARTS_CONTEXT_WINDOW_PATH = "/api/codearts/context-window";
1903
+ /**
1904
+ * POST /api/codearts/max-tokens — 按模型设置/清除输出上限覆盖(issue #15)。
1905
+ * `{ id, tokens }`,`tokens: null` 表示删除覆盖、回到跟随上游。
1906
+ */
1907
+ const CODEARTS_MAX_TOKENS_PATH = "/api/codearts/max-tokens";
1908
+ /**
1909
+ * GET/POST /api/codearts/concurrency — 每账号本地并发上限(issue #16)。
1910
+ * GET 回 `{ value, writable }`;POST 收 `{ value: number }`,改完立即生效。
1911
+ */
1912
+ const CODEARTS_CONCURRENCY_PATH = "/api/codearts/concurrency";
1845
1913
  const CODEARTS_TOKEN_PATH = "/api/codearts/token";
1846
1914
  const CODEARTS_LOGIN_PATH = "/api/codearts/login";
1847
1915
  const CODEARTS_LOGIN_STATUS_PATH = "/api/codearts/login/status";
@@ -1904,6 +1972,8 @@ function selectionOf(models, enabled, writable) {
1904
1972
  contextWindowDiscovered: m.contextWindowDiscovered,
1905
1973
  contextWindowOverride: m.contextWindowOverride,
1906
1974
  maxTokens: m.maxTokens,
1975
+ maxTokensDiscovered: m.maxTokensDiscovered,
1976
+ maxTokensOverride: m.maxTokensOverride,
1907
1977
  ...m.error === void 0 ? {} : { error: m.error },
1908
1978
  enabled: restricted ? allowed.has(m.id) : true
1909
1979
  })),
@@ -1914,11 +1984,13 @@ function selectionOf(models, enabled, writable) {
1914
1984
  /** 目录 -> 勾选 UI 的选项(福利标记、今日不可用标记与倍率都在这里算)。 */
1915
1985
  function choicesOf(deps) {
1916
1986
  const overrides = deps.contextWindowOverrides?.();
1987
+ const maxOverrides = deps.maxTokensOverrides?.();
1917
1988
  return deps.models().map((m) => {
1918
1989
  const benefit = isBenefitModel(m.id);
1919
1990
  const ratio = creditRatioLabel(m.ratio, benefit);
1920
1991
  const error = modelUnavailableReason(m.id);
1921
1992
  const override = contextWindowOverrideFor(overrides, m.id);
1993
+ const maxOverride = overrideValueFor(maxOverrides, m.id);
1922
1994
  return {
1923
1995
  id: m.id,
1924
1996
  name: m.name,
@@ -1930,6 +2002,8 @@ function choicesOf(deps) {
1930
2002
  ...m.contextWindowDiscovered === void 0 ? {} : { contextWindowDiscovered: m.contextWindowDiscovered },
1931
2003
  ...override === void 0 ? {} : { contextWindowOverride: override },
1932
2004
  ...m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {},
2005
+ ...m.maxTokensDiscovered === void 0 ? {} : { maxTokensDiscovered: m.maxTokensDiscovered },
2006
+ ...maxOverride === void 0 ? {} : { maxTokensOverride: maxOverride },
1933
2007
  ...error === void 0 ? {} : { error }
1934
2008
  };
1935
2009
  });
@@ -2519,6 +2593,126 @@ function contextWindowHandler(deps) {
2519
2593
  }
2520
2594
  };
2521
2595
  }
2596
+ /**
2597
+ * POST /api/codearts/max-tokens { id, tokens } — 按模型覆盖输出上限(issue #15)。
2598
+ *
2599
+ * 存在的理由:企业自定义模型实测能到 128K,而插件全局天花板是 65536(对福利模型
2600
+ * 实测的保守值),两道 `min` 把覆盖值压回去,手动设置就没意义。`tokens: null`
2601
+ * 删除覆盖、回到跟随上游(目录声明值)。
2602
+ */
2603
+ function maxTokensHandler(deps) {
2604
+ return async (req, res) => {
2605
+ if (req.method !== "POST") {
2606
+ json(res, 405, { error: "method not allowed" });
2607
+ return;
2608
+ }
2609
+ if (!loopbackRequest(req)) {
2610
+ json(res, 403, { error: "request-not-trusted" });
2611
+ return;
2612
+ }
2613
+ if (deps.setMaxTokensOverride === void 0) {
2614
+ json(res, 403, { error: "max-tokens-not-writable" });
2615
+ return;
2616
+ }
2617
+ const type = req.headers["content-type"];
2618
+ if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
2619
+ json(res, 415, { error: "content-type must be application/json" });
2620
+ return;
2621
+ }
2622
+ try {
2623
+ const body = JSON.parse(await readBody(req));
2624
+ const id = typeof body.id === "string" ? body.id.trim() : "";
2625
+ if (id === "") {
2626
+ json(res, 400, { error: "expected {\"id\": string, \"tokens\": number|null}" });
2627
+ return;
2628
+ }
2629
+ let tokens = null;
2630
+ if (body.tokens !== null && body.tokens !== void 0) {
2631
+ if (typeof body.tokens !== "number" || !Number.isFinite(body.tokens) || body.tokens <= 0) {
2632
+ json(res, 400, { error: "tokens must be a positive number or null" });
2633
+ return;
2634
+ }
2635
+ tokens = Math.floor(body.tokens);
2636
+ }
2637
+ if (!await deps.setMaxTokensOverride(id, tokens)) {
2638
+ json(res, 403, { error: "max-tokens-not-writable" });
2639
+ return;
2640
+ }
2641
+ json(res, 200, { selection: selectionOf(choicesOf(deps), deps.enabledModels?.(), true) });
2642
+ } catch (error) {
2643
+ json(res, 500, { error: safeMessage(error) });
2644
+ }
2645
+ };
2646
+ }
2647
+ /**
2648
+ * GET/POST /api/codearts/concurrency — 每个账号各自的并发上限(issue #16)。
2649
+ *
2650
+ * 上游会话槽位按账号算(个人 3 / 企业 5),所以上限也按账号设:`caps` 里的号用自己的,
2651
+ * 其余用 `default`。POST 只收 `{ id, value }`,`value: null` = 删掉覆盖、回到默认。
2652
+ * 真正的钳制与热更新在 `index.ts`(池逐账号改上限并唤醒等槽请求)。
2653
+ */
2654
+ function concurrencyHandler(deps) {
2655
+ const snapshot = () => deps.concurrency?.() ?? {
2656
+ default: 2,
2657
+ caps: {}
2658
+ };
2659
+ return async (req, res) => {
2660
+ if (!loopbackRequest(req)) {
2661
+ json(res, 403, { error: "request-not-trusted" });
2662
+ return;
2663
+ }
2664
+ if (req.method === "GET") {
2665
+ const current = snapshot();
2666
+ json(res, 200, {
2667
+ default: current.default,
2668
+ caps: current.caps,
2669
+ writable: deps.setAccountConcurrency !== void 0
2670
+ });
2671
+ return;
2672
+ }
2673
+ if (req.method === "POST") {
2674
+ if (deps.setAccountConcurrency === void 0) {
2675
+ json(res, 403, { error: "concurrency-not-writable" });
2676
+ return;
2677
+ }
2678
+ const type = req.headers["content-type"];
2679
+ if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
2680
+ json(res, 415, { error: "content-type must be application/json" });
2681
+ return;
2682
+ }
2683
+ try {
2684
+ const body = JSON.parse(await readBody(req));
2685
+ const id = typeof body.id === "string" ? body.id.trim() : "";
2686
+ if (id === "") {
2687
+ json(res, 400, { error: "expected {\"id\": string, \"value\": number|null}" });
2688
+ return;
2689
+ }
2690
+ let value = null;
2691
+ if (body.value !== null && body.value !== void 0) {
2692
+ if (typeof body.value !== "number" || !Number.isInteger(body.value) || body.value < 1 || body.value > 16) {
2693
+ json(res, 400, { error: "value must be an integer between 1 and 16, or null" });
2694
+ return;
2695
+ }
2696
+ value = body.value;
2697
+ }
2698
+ if (!await deps.setAccountConcurrency(id, value)) {
2699
+ json(res, 403, { error: "concurrency-not-writable" });
2700
+ return;
2701
+ }
2702
+ const current = snapshot();
2703
+ json(res, 200, {
2704
+ default: current.default,
2705
+ caps: current.caps,
2706
+ writable: true
2707
+ });
2708
+ } catch (error) {
2709
+ json(res, 500, { error: safeMessage(error) });
2710
+ }
2711
+ return;
2712
+ }
2713
+ json(res, 405, { error: "method not allowed" });
2714
+ };
2715
+ }
2522
2716
  /** POST /api/codearts/token { token, label? } — store a pasted token. */
2523
2717
  function tokenPostHandler(deps) {
2524
2718
  return async (req, res) => {
@@ -2894,6 +3088,16 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2894
3088
  path: CODEARTS_CONTEXT_WINDOW_PATH,
2895
3089
  handler: contextWindowHandler(deps)
2896
3090
  });
3091
+ const disposeMaxTokens = ctx.webServer.register({
3092
+ kind: "exact",
3093
+ path: CODEARTS_MAX_TOKENS_PATH,
3094
+ handler: maxTokensHandler(deps)
3095
+ });
3096
+ const disposeConcurrency = ctx.webServer.register({
3097
+ kind: "exact",
3098
+ path: CODEARTS_CONCURRENCY_PATH,
3099
+ handler: concurrencyHandler(deps)
3100
+ });
2897
3101
  const disposeToken = ctx.webServer.register({
2898
3102
  kind: "exact",
2899
3103
  path: CODEARTS_TOKEN_PATH,
@@ -2959,6 +3163,8 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2959
3163
  disposeModels();
2960
3164
  disposeModelsSelection();
2961
3165
  disposeContextWindow();
3166
+ disposeMaxTokens();
3167
+ disposeConcurrency();
2962
3168
  disposeToken();
2963
3169
  disposeLoginStart();
2964
3170
  disposeLoginStatus();
@@ -3087,6 +3293,30 @@ function entryNamespaceOf(ctx) {
3087
3293
  ];
3088
3294
  for (const candidate of candidates) if (typeof candidate === "string" && candidate !== "") return candidate;
3089
3295
  }
3296
+ /**
3297
+ * 从 settings 的某个 dict 字段里删键,并可顺带写入一个键(issue #17)。
3298
+ *
3299
+ * `update` 是**深合并**:传一份「过滤掉目标键的整表」删不掉那个键 —— 它还留在
3300
+ * `cordis.patch.yml` 里,重启后覆盖照常生效,用户以为清了其实没清。真正能删键的是
3301
+ * `mutate` + `unset`。老宿主没有这个方法时退回 `update`:只能设新值、删不掉,
3302
+ * 与 1.4.8 行为相同,至少设置路径不炸。
3303
+ */
3304
+ async function writeSettingsDictKey(settings, ns, field, remove, put) {
3305
+ if (settings.mutate !== void 0) {
3306
+ const ops = remove.map((key) => ({
3307
+ op: "unset",
3308
+ path: [field, key]
3309
+ }));
3310
+ if (put !== void 0) ops.push({
3311
+ op: "set",
3312
+ path: [field, put.key],
3313
+ value: put.value
3314
+ });
3315
+ if (ops.length > 0) await settings.mutate(ns, ops);
3316
+ return;
3317
+ }
3318
+ if (put !== void 0) await settings.update(ns, { [field]: { [put.key]: put.value } });
3319
+ }
3090
3320
  function resolveSettingsNamespaceCompat(ctx, provider, fallback) {
3091
3321
  if (compatModule.installSettingsSection !== void 0) return fallback;
3092
3322
  const candidate = provider;
@@ -3147,6 +3377,9 @@ function unwrapConfig(value) {
3147
3377
  const Config = z.object({
3148
3378
  enabledModels: z.array(z.string()).description("Model ids offered in the model pickers (empty means every model)").volatile(),
3149
3379
  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(),
3380
+ maxTokensOverrides: z.dict(z.natural()).description("Per-model max output tokens (model id → tokens, issue #15). The override becomes that model's ceiling and may exceed the 65536 global cap; rejected values still self-heal by halving the ceiling.").volatile(),
3381
+ maxConcurrentPerAccount: z.natural().default(2).description("Default per-account in-flight request cap (default 2). Upstream session slots depend on the plan: measured 3 on the free tier and 5 on enterprise (issue #16); leave one spare for the CodeArts web console. Applies immediately.").volatile(),
3382
+ maxConcurrentOverrides: z.dict(z.natural()).description("Per-account overrides of the concurrency cap (account id → slots, issue #16). Accounts listed here ignore maxConcurrentPerAccount; the card stepper on each account writes this map.").volatile(),
3150
3383
  retryPolicy: z.object({
3151
3384
  maxRetries: z.natural(),
3152
3385
  initialDelayMs: z.natural(),
@@ -3164,8 +3397,28 @@ const Config = z.object({
3164
3397
  function settingsCompatNamespace(ctx) {
3165
3398
  return resolveSettingsNamespaceCompat(ctx, ctx.get("settings"), CODEARTS_SETTINGS_NS);
3166
3399
  }
3400
+ /**
3401
+ * 每账号并发上限的兜底解析:坏值(0 / 负数 / NaN)回默认,别把池子锁成 0 槽。
3402
+ * 上限 16 是拍得住的宽松值 —— 真实套餐最多也就个位数,再大只说明用户乱填。
3403
+ */
3404
+ function concurrencyCap(value) {
3405
+ const n = value === void 0 ? 2 : Math.floor(value);
3406
+ return Number.isFinite(n) && n >= 1 ? Math.min(n, 16) : 2;
3407
+ }
3408
+ /** 按账号覆盖表:坏值丢掉、逐项钳制(值来自用户写的配置)。 */
3409
+ function concurrencyCaps(value) {
3410
+ const out = {};
3411
+ for (const [key, cap] of Object.entries(value ?? {})) {
3412
+ const id = key.trim();
3413
+ if (id === "") continue;
3414
+ if (typeof cap !== "number" || !Number.isFinite(cap)) continue;
3415
+ out[id] = Math.min(Math.max(1, Math.floor(cap)), 16);
3416
+ }
3417
+ return out;
3418
+ }
3167
3419
  async function apply(ctx, rawConfig) {
3168
3420
  const config = unwrapConfig(rawConfig);
3421
+ setMaxTokenOverrides(config.maxTokensOverrides);
3169
3422
  const accountsPath = codeartsAccountsPath();
3170
3423
  /**
3171
3424
  * 续期失败日志。
@@ -3184,7 +3437,11 @@ async function apply(ctx, rawConfig) {
3184
3437
  } catch {}
3185
3438
  };
3186
3439
  const store = new CodeArtsAccountStore(accountsPath, void 0, { log: appendRefreshLog });
3187
- const pool = new CodeArtsAccountPool([]);
3440
+ const pool = new CodeArtsAccountPool([], { maxConcurrent: concurrencyCap(config.maxConcurrentPerAccount) });
3441
+ /** 卡片按号显示的「默认并发 + 按账号覆盖」(配置可能因旧宿主不刷新,所以单独记一份)。 */
3442
+ let concurrencyNow = concurrencyCap(config.maxConcurrentPerAccount);
3443
+ let concurrencyCapsNow = concurrencyCaps(config.maxConcurrentOverrides);
3444
+ pool.setAccountCaps(concurrencyCapsNow);
3188
3445
  const catalog = new CodeArtsCatalog();
3189
3446
  const usage = new CodeArtsUsageTracker({ path: codeartsUsagePath() });
3190
3447
  const queue = new CodeArtsQueueGate();
@@ -3247,6 +3504,49 @@ async function apply(ctx, rawConfig) {
3247
3504
  };
3248
3505
  let current = () => config;
3249
3506
  const enabledModels = () => current().enabledModels;
3507
+ /**
3508
+ * 把「改了立即生效」的配置推给运行时(issue #15 #16)。
3509
+ *
3510
+ * 走设置变更而不是重建组件:并发上限在池里逐账号生效,重建会把冷却/避让/槽位
3511
+ * 计数这些本进程学出来的状态全丢掉。
3512
+ */
3513
+ const applyLiveConfig = () => {
3514
+ setMaxTokenOverrides(current().maxTokensOverrides);
3515
+ concurrencyNow = concurrencyCap(current().maxConcurrentPerAccount);
3516
+ concurrencyCapsNow = concurrencyCaps(current().maxConcurrentOverrides);
3517
+ pool.setMaxConcurrent(concurrencyNow);
3518
+ pool.setAccountCaps(concurrencyCapsNow);
3519
+ };
3520
+ /**
3521
+ * 卡片上某个账号的并发加减器(issue #16)。写配置 + 立刻改组运行中的池。
3522
+ *
3523
+ * `value: null` = 删掉这个号的覆盖、回到默认值。不需要重启也不用等设置事件:
3524
+ * 用户点一下就要看到槽位变化。
3525
+ */
3526
+ const setAccountConcurrency = async (accountId, value) => {
3527
+ const settings = ctx.get("settings");
3528
+ if (settings === void 0) return false;
3529
+ const id = accountId.trim();
3530
+ if (id === "") return false;
3531
+ const lower = id.toLowerCase();
3532
+ const stored = Object.keys(current().maxConcurrentOverrides ?? {}).filter((key) => key.trim().toLowerCase() === lower);
3533
+ const cap = value === null ? null : concurrencyCap(value);
3534
+ await writeDictKey(settings, "maxConcurrentOverrides", value === null ? stored : stored.filter((key) => key !== id), cap === null ? void 0 : {
3535
+ key: id,
3536
+ value: cap
3537
+ });
3538
+ const next = { ...concurrencyCapsNow };
3539
+ for (const key of stored) delete next[key];
3540
+ if (cap === null) delete next[id];
3541
+ else next[id] = cap;
3542
+ concurrencyCapsNow = next;
3543
+ pool.setAccountCap(id, cap);
3544
+ return true;
3545
+ };
3546
+ /** 设置里 dict 字段的删键/写入(issue #17 的落地,见 `writeSettingsDictKey`)。 */
3547
+ const writeDictKey = async (settings, field, remove, put) => {
3548
+ await writeSettingsDictKey(settings, settingsCompatNamespace(ctx), field, remove, put);
3549
+ };
3250
3550
  const setEnabledModels = async (ids) => {
3251
3551
  const settings = ctx.get("settings");
3252
3552
  if (settings === void 0) return false;
@@ -3264,25 +3564,33 @@ async function apply(ctx, rawConfig) {
3264
3564
  const settings = ctx.get("settings");
3265
3565
  if (settings === void 0) return false;
3266
3566
  const lower = id.trim().toLowerCase();
3267
- const next = {};
3268
- for (const [key, value] of Object.entries(current().contextWindowOverrides ?? {})) if (key.trim().toLowerCase() !== lower) next[key] = value;
3269
- if (window !== null) next[id.trim()] = window;
3270
- await settings.update(settingsCompatNamespace(ctx), { contextWindowOverrides: next });
3271
- catalog.set(catalog.current().map((model) => {
3272
- if (model.id.toLowerCase() !== lower) return model;
3273
- const target = window ?? model.contextWindowDiscovered ?? model.contextWindow;
3274
- const { contextWindowDiscovered, ...rest } = model;
3275
- const known = window === null ? model.contextWindowKnown : true;
3276
- const patched = {
3277
- ...rest,
3278
- contextWindow: target,
3279
- ...known === true ? { contextWindowKnown: true } : {}
3280
- };
3281
- return contextWindowDiscovered === void 0 || contextWindowDiscovered === target ? patched : {
3282
- ...patched,
3283
- contextWindowDiscovered
3284
- };
3285
- }));
3567
+ const stored = Object.keys(current().contextWindowOverrides ?? {}).filter((key) => key.trim().toLowerCase() === lower);
3568
+ await writeDictKey(settings, "contextWindowOverrides", window === null ? stored : stored.filter((key) => key !== id.trim()), window === null ? void 0 : {
3569
+ key: id.trim(),
3570
+ value: window
3571
+ });
3572
+ if (window === null && stored.length === 0) return true;
3573
+ catalog.set(withContextWindowOverride(catalog.current(), id, window));
3574
+ return true;
3575
+ };
3576
+ /**
3577
+ * 写/清某个模型的输出上限覆盖(issue #15),语义与窗口覆盖一致。
3578
+ *
3579
+ * 生效值是模块级状态(`upstream.maxTokensCeilingFor`),必须同时更新它,否则
3580
+ * 卡片显示改了、下一条请求仍按旧天花板钳制。
3581
+ */
3582
+ const setMaxTokensOverride = async (id, tokens) => {
3583
+ const settings = ctx.get("settings");
3584
+ if (settings === void 0) return false;
3585
+ const lower = id.trim().toLowerCase();
3586
+ const stored = Object.keys(current().maxTokensOverrides ?? {}).filter((key) => key.trim().toLowerCase() === lower);
3587
+ await writeDictKey(settings, "maxTokensOverrides", tokens === null ? stored : stored.filter((key) => key !== id.trim()), tokens === null ? void 0 : {
3588
+ key: id.trim(),
3589
+ value: tokens
3590
+ });
3591
+ if (tokens === null && stored.length === 0) return true;
3592
+ catalog.set(withMaxTokensOverride(catalog.current(), id, tokens));
3593
+ setMaxTokenOverride(id, tokens);
3286
3594
  return true;
3287
3595
  };
3288
3596
  const dock = () => ({
@@ -3512,6 +3820,13 @@ async function apply(ctx, rawConfig) {
3512
3820
  setEnabledModels,
3513
3821
  contextWindowOverrides: () => current().contextWindowOverrides,
3514
3822
  setContextWindowOverride,
3823
+ maxTokensOverrides: () => current().maxTokensOverrides,
3824
+ setMaxTokensOverride,
3825
+ concurrency: () => ({
3826
+ default: concurrencyNow,
3827
+ caps: { ...concurrencyCapsNow }
3828
+ }),
3829
+ setAccountConcurrency,
3515
3830
  pool: () => pool.list(),
3516
3831
  reviveAccount: (id) => pool.revive(id),
3517
3832
  usage: () => usage.snapshot(),
@@ -3550,10 +3865,12 @@ async function apply(ctx, rawConfig) {
3550
3865
  installSettingsSectionCompat(ctx, CODEARTS_SETTINGS_NS, Config, config, {
3551
3866
  setSource(source) {
3552
3867
  current = () => unwrapConfig(source());
3868
+ applyLiveConfig();
3553
3869
  armAutoClaim();
3554
3870
  armKeepAliveDaemon();
3555
3871
  },
3556
3872
  onChange() {
3873
+ applyLiveConfig();
3557
3874
  armAutoClaim();
3558
3875
  armKeepAliveDaemon();
3559
3876
  }
@@ -1,4 +1,4 @@
1
- import { d as refreshLockPath, f as withRefreshLock, h as refreshToken, i as codeartsAccountsPath, l as readAccountDocument, m as defaultLoginConfig, p as OAuthTokenError, u as writeJsonAtomic } from "./auth-BRlNY6dB.mjs";
1
+ import { d as refreshLockPath, f as withRefreshLock, h as refreshToken, i as codeartsAccountsPath, l as readAccountDocument, m as defaultLoginConfig, p as OAuthTokenError, u as writeJsonAtomic } from "./auth-BaxN0iKC.mjs";
2
2
  import { _ as writeKeeperState, a as clearKeeperState, c as keeperLogPath, d as keeperStatePath, f as keeperStats, g as writeKeeperHandoff, h as stopRequested, i as clearKeeperHandoff, o as isDshInstallerTempDir, r as KEEPER_TICK_MS, t as KEEPER_HEARTBEAT_MS } from "./keeper-BWHQDFAh.mjs";
3
3
  import { appendFileSync, existsSync, unlinkSync, watch } from "node:fs";
4
4
  import { dirname, join } from "node:path";