dsh-codearts 1.4.7 → 1.4.9

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.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-DNEBIi8C.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-1elDzsw0.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
  }
@@ -704,10 +762,30 @@ const CODEARTS_PROVIDER = "codearts";
704
762
  *
705
763
  * 90s 而不是常见的 300s:华为免费推理后端实测会流中途停摆(吐几个 token 后
706
764
  * 长时间静默),300s 意味着用户要在"等待"里干等 5 分钟才进入自动重试。
707
- * 90s 足够容忍首 token 冷启动与推理间隙,又能让 DSH 的重试策略
708
- * (maxRetries=5, TIMEOUT 可重试)更快接管。
765
+ * 90s 足够容忍首 token 冷启动与推理间隙,又能让 DSH 的重试策略(TIMEOUT
766
+ * 可重试)更快接管。
709
767
  */
710
768
  const CODEARTS_STREAM_IDLE_TIMEOUT_MS = 9e4;
769
+ const DEFAULT_CODEARTS_INITIAL_DELAY_MS = 500;
770
+ const DEFAULT_CODEARTS_MAX_DELAY_MS = 1e4;
771
+ /** 只认有限正整数;非法值忽略而不是抛错(值来自用户写的配置文件)。 */
772
+ function positiveInt(value) {
773
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
774
+ }
775
+ /** 把插件配置解析成宿主快照用的重试策略;缺省值按上面注释对齐冷却窗。 */
776
+ function resolveCodeArtsRetryPolicy(config) {
777
+ const resolved = {
778
+ mode: "normal",
779
+ maxRetries: positiveInt(config?.maxRetries) ?? 8,
780
+ backoff: {
781
+ initialDelayMs: positiveInt(config?.initialDelayMs) ?? DEFAULT_CODEARTS_INITIAL_DELAY_MS,
782
+ maxDelayMs: positiveInt(config?.maxDelayMs) ?? DEFAULT_CODEARTS_MAX_DELAY_MS
783
+ }
784
+ };
785
+ const policy = resolveRetryPolicy(resolved, "dsh-codearts retryPolicy");
786
+ if (policy.mode !== "normal") throw new Error("dsh-codearts retry policy must be normal");
787
+ return policy;
788
+ }
711
789
  /** No per-token pricing is knowable for a subscription quota; report zero. */
712
790
  const NO_COST = {
713
791
  input: 0,
@@ -814,7 +892,7 @@ function createCodeArtsAdapter(options) {
814
892
  provider: CODEARTS_PROVIDER,
815
893
  displayName: "CodeArts",
816
894
  streamIdleTimeoutMs: CODEARTS_STREAM_IDLE_TIMEOUT_MS,
817
- retryPolicy: resolveRetryPolicy(void 0, "dsh-codearts retryPolicy"),
895
+ retryPolicy: resolveCodeArtsRetryPolicy(options.retryPolicy),
818
896
  configuredMaxTokens: /* @__PURE__ */ new Map(),
819
897
  modelErrors: /* @__PURE__ */ new Map(),
820
898
  ...REQUEST_IMAGE_BUDGETS,
@@ -1016,7 +1094,8 @@ function writeOpenAIError(res, status, kind, message) {
1016
1094
  * 种还把真因(比如 billion-context 本地拒签的 403)整个吞掉(issue #1)。
1017
1095
  *
1018
1096
  * 全部被禁用时回 401(宿主只自动重试 429,401 一次就把「去重新登录」说清);
1019
- * 只要还有会自己恢复的(冷却/槽位满)就回 429,宿主重试有概率直接救回来。
1097
+ * 只要还有会自己恢复的(冷却/槽位满)就回 429,让宿主重试接住。默认重试预算
1098
+ * 已对齐 30s 冷却窗(8 次指数退避 ≈45.5s,见 `adapter.ts`),冷却前段也跨得过。
1020
1099
  */
1021
1100
  function noAccountError(accounts, pausedIds = []) {
1022
1101
  const now = Date.now();
@@ -1821,6 +1900,16 @@ const CODEARTS_MODELS_SELECTION_PATH = "/api/codearts/enabled-models";
1821
1900
  * `{ id, window }`,`window: null` 表示删除覆盖、回到跟随上游。
1822
1901
  */
1823
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";
1824
1913
  const CODEARTS_TOKEN_PATH = "/api/codearts/token";
1825
1914
  const CODEARTS_LOGIN_PATH = "/api/codearts/login";
1826
1915
  const CODEARTS_LOGIN_STATUS_PATH = "/api/codearts/login/status";
@@ -1883,6 +1972,8 @@ function selectionOf(models, enabled, writable) {
1883
1972
  contextWindowDiscovered: m.contextWindowDiscovered,
1884
1973
  contextWindowOverride: m.contextWindowOverride,
1885
1974
  maxTokens: m.maxTokens,
1975
+ maxTokensDiscovered: m.maxTokensDiscovered,
1976
+ maxTokensOverride: m.maxTokensOverride,
1886
1977
  ...m.error === void 0 ? {} : { error: m.error },
1887
1978
  enabled: restricted ? allowed.has(m.id) : true
1888
1979
  })),
@@ -1893,11 +1984,13 @@ function selectionOf(models, enabled, writable) {
1893
1984
  /** 目录 -> 勾选 UI 的选项(福利标记、今日不可用标记与倍率都在这里算)。 */
1894
1985
  function choicesOf(deps) {
1895
1986
  const overrides = deps.contextWindowOverrides?.();
1987
+ const maxOverrides = deps.maxTokensOverrides?.();
1896
1988
  return deps.models().map((m) => {
1897
1989
  const benefit = isBenefitModel(m.id);
1898
1990
  const ratio = creditRatioLabel(m.ratio, benefit);
1899
1991
  const error = modelUnavailableReason(m.id);
1900
1992
  const override = contextWindowOverrideFor(overrides, m.id);
1993
+ const maxOverride = overrideValueFor(maxOverrides, m.id);
1901
1994
  return {
1902
1995
  id: m.id,
1903
1996
  name: m.name,
@@ -1909,6 +2002,8 @@ function choicesOf(deps) {
1909
2002
  ...m.contextWindowDiscovered === void 0 ? {} : { contextWindowDiscovered: m.contextWindowDiscovered },
1910
2003
  ...override === void 0 ? {} : { contextWindowOverride: override },
1911
2004
  ...m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {},
2005
+ ...m.maxTokensDiscovered === void 0 ? {} : { maxTokensDiscovered: m.maxTokensDiscovered },
2006
+ ...maxOverride === void 0 ? {} : { maxTokensOverride: maxOverride },
1912
2007
  ...error === void 0 ? {} : { error }
1913
2008
  };
1914
2009
  });
@@ -2498,6 +2593,126 @@ function contextWindowHandler(deps) {
2498
2593
  }
2499
2594
  };
2500
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
+ }
2501
2716
  /** POST /api/codearts/token { token, label? } — store a pasted token. */
2502
2717
  function tokenPostHandler(deps) {
2503
2718
  return async (req, res) => {
@@ -2873,6 +3088,16 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2873
3088
  path: CODEARTS_CONTEXT_WINDOW_PATH,
2874
3089
  handler: contextWindowHandler(deps)
2875
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
+ });
2876
3101
  const disposeToken = ctx.webServer.register({
2877
3102
  kind: "exact",
2878
3103
  path: CODEARTS_TOKEN_PATH,
@@ -2938,6 +3163,8 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2938
3163
  disposeModels();
2939
3164
  disposeModelsSelection();
2940
3165
  disposeContextWindow();
3166
+ disposeMaxTokens();
3167
+ disposeConcurrency();
2941
3168
  disposeToken();
2942
3169
  disposeLoginStart();
2943
3170
  disposeLoginStatus();
@@ -3066,6 +3293,30 @@ function entryNamespaceOf(ctx) {
3066
3293
  ];
3067
3294
  for (const candidate of candidates) if (typeof candidate === "string" && candidate !== "") return candidate;
3068
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
+ }
3069
3320
  function resolveSettingsNamespaceCompat(ctx, provider, fallback) {
3070
3321
  if (compatModule.installSettingsSection !== void 0) return fallback;
3071
3322
  const candidate = provider;
@@ -3126,6 +3377,14 @@ function unwrapConfig(value) {
3126
3377
  const Config = z.object({
3127
3378
  enabledModels: z.array(z.string()).description("Model ids offered in the model pickers (empty means every model)").volatile(),
3128
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(),
3383
+ retryPolicy: z.object({
3384
+ maxRetries: z.natural(),
3385
+ initialDelayMs: z.natural(),
3386
+ maxDelayMs: z.natural()
3387
+ }).description("Host retry budget for this provider (issue #14). Defaults to 8 retries (≈45.5s of backoff) so it outlasts the 30s account cooldown; changes apply after the plugin reloads.").volatile(),
3129
3388
  showCreditDock: z.boolean().default(true).description("Show the remaining-credits line under the chat input box").volatile(),
3130
3389
  showQueueDock: z.boolean().default(true).description("Show the upstream queue position under the chat input box").volatile(),
3131
3390
  showSidebarPanel: z.boolean().default(false).description("Show a CodeArts icon in the DSH sidebar icon column, opening this page in the middle column").volatile(),
@@ -3138,8 +3397,28 @@ const Config = z.object({
3138
3397
  function settingsCompatNamespace(ctx) {
3139
3398
  return resolveSettingsNamespaceCompat(ctx, ctx.get("settings"), CODEARTS_SETTINGS_NS);
3140
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
+ }
3141
3419
  async function apply(ctx, rawConfig) {
3142
3420
  const config = unwrapConfig(rawConfig);
3421
+ setMaxTokenOverrides(config.maxTokensOverrides);
3143
3422
  const accountsPath = codeartsAccountsPath();
3144
3423
  /**
3145
3424
  * 续期失败日志。
@@ -3158,7 +3437,11 @@ async function apply(ctx, rawConfig) {
3158
3437
  } catch {}
3159
3438
  };
3160
3439
  const store = new CodeArtsAccountStore(accountsPath, void 0, { log: appendRefreshLog });
3161
- 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);
3162
3445
  const catalog = new CodeArtsCatalog();
3163
3446
  const usage = new CodeArtsUsageTracker({ path: codeartsUsagePath() });
3164
3447
  const queue = new CodeArtsQueueGate();
@@ -3221,6 +3504,49 @@ async function apply(ctx, rawConfig) {
3221
3504
  };
3222
3505
  let current = () => config;
3223
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
+ };
3224
3550
  const setEnabledModels = async (ids) => {
3225
3551
  const settings = ctx.get("settings");
3226
3552
  if (settings === void 0) return false;
@@ -3238,25 +3564,33 @@ async function apply(ctx, rawConfig) {
3238
3564
  const settings = ctx.get("settings");
3239
3565
  if (settings === void 0) return false;
3240
3566
  const lower = id.trim().toLowerCase();
3241
- const next = {};
3242
- for (const [key, value] of Object.entries(current().contextWindowOverrides ?? {})) if (key.trim().toLowerCase() !== lower) next[key] = value;
3243
- if (window !== null) next[id.trim()] = window;
3244
- await settings.update(settingsCompatNamespace(ctx), { contextWindowOverrides: next });
3245
- catalog.set(catalog.current().map((model) => {
3246
- if (model.id.toLowerCase() !== lower) return model;
3247
- const target = window ?? model.contextWindowDiscovered ?? model.contextWindow;
3248
- const { contextWindowDiscovered, ...rest } = model;
3249
- const known = window === null ? model.contextWindowKnown : true;
3250
- const patched = {
3251
- ...rest,
3252
- contextWindow: target,
3253
- ...known === true ? { contextWindowKnown: true } : {}
3254
- };
3255
- return contextWindowDiscovered === void 0 || contextWindowDiscovered === target ? patched : {
3256
- ...patched,
3257
- contextWindowDiscovered
3258
- };
3259
- }));
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);
3260
3594
  return true;
3261
3595
  };
3262
3596
  const dock = () => ({
@@ -3486,6 +3820,13 @@ async function apply(ctx, rawConfig) {
3486
3820
  setEnabledModels,
3487
3821
  contextWindowOverrides: () => current().contextWindowOverrides,
3488
3822
  setContextWindowOverride,
3823
+ maxTokensOverrides: () => current().maxTokensOverrides,
3824
+ setMaxTokensOverride,
3825
+ concurrency: () => ({
3826
+ default: concurrencyNow,
3827
+ caps: { ...concurrencyCapsNow }
3828
+ }),
3829
+ setAccountConcurrency,
3489
3830
  pool: () => pool.list(),
3490
3831
  reviveAccount: (id) => pool.revive(id),
3491
3832
  usage: () => usage.snapshot(),
@@ -3524,10 +3865,12 @@ async function apply(ctx, rawConfig) {
3524
3865
  installSettingsSectionCompat(ctx, CODEARTS_SETTINGS_NS, Config, config, {
3525
3866
  setSource(source) {
3526
3867
  current = () => unwrapConfig(source());
3868
+ applyLiveConfig();
3527
3869
  armAutoClaim();
3528
3870
  armKeepAliveDaemon();
3529
3871
  },
3530
3872
  onChange() {
3873
+ applyLiveConfig();
3531
3874
  armAutoClaim();
3532
3875
  armKeepAliveDaemon();
3533
3876
  }
@@ -3740,6 +4083,7 @@ async function apply(ctx, rawConfig) {
3740
4083
  shim,
3741
4084
  catalog,
3742
4085
  enabledModels,
4086
+ retryPolicy: current().retryPolicy,
3743
4087
  resolveAttachments: () => ctx.get("attachments")
3744
4088
  });
3745
4089
  let releaseAdapter;
@@ -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";