dsh-codearts 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -1,8 +1,9 @@
1
- import { a as codeartsAuthPath, d as startLogin, i as codeartsAccountsPath, n as CodeArtsCredentialStore, o as credentialFromOAuth, r as MANUAL_ACCOUNT_ID, t as CodeArtsAccountStore } from "./auth-CF9XHMX-.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-CJTTrulR.mjs";
1
+ import { a as codeartsAuthPath, c as credentialFromOAuth, i as codeartsAccountsPath, m as startLogin, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-C00dJphV.mjs";
2
+ import { A as upstreamErrorMessage, B as markModelUnavailable, C as learnedContextWindowFor, D as prepareChatBody, E as pickDailyWelfareCampaign, F as creditRatioLabel, I as filterEnabledModels, L as forgetModelUnavailable, M as CodeArtsCatalog, N as FALLBACK_CODEARTS_MODELS, O as rateLimitFrame, P as clearBenefitBlocked, R as isBenefitBlocked, S as learnContextWindow, T as modelUnavailableReasonText, U as modelUnavailableReason, _ as isNotMultimodal, a as claimDailyWelfare, b as isTpmLimit, c as degradeTokenCeiling, d as fetchQueueStatus, f as fetchWelfareCampaigns, g as isModelNotAccessible, h as isIamTokenError, i as chatStream, k as signedGet, l as fetchCallerIdentity, m as isConcurrencyCap, n as SNAP_HOST, o as clearQueueStatus, p as firstFrameError, r as canonicalModel, s as contextWindowOverrideFor, t as MAX_TOKENS_FLOOR, u as fetchModels, v as isParamInvalidFrame, w as maxTokensCeilingFor, x as isWelfareClaimedStatus, y as isQueueableRate, z as isBenefitModel } from "./upstream-D1wYeXC7.mjs";
3
+ import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-DC5JRWls.mjs";
4
4
  import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
5
- import { a as keeperLogPath, c as keeperStats, d as stopKeeper, n as KEEPER_STALE_MS, o as keeperScriptPath, u as spawnKeeper } from "./keeper-P4FkDUEd.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";
6
+ import { appendFileSync, statSync, writeFileSync } from "node:fs";
6
7
  import z from "@deepseek-ai/schemastery";
7
8
  import { randomBytes, timingSafeEqual } from "node:crypto";
8
9
  import { createServer } from "node:http";
@@ -52,6 +53,8 @@ var CodeArtsAccountPool = class {
52
53
  preferred = /* @__PURE__ */ new Set();
53
54
  maxConcurrent;
54
55
  now;
56
+ /** 等槽位的唤醒器:槽位释放 / 池里新增账号 / 账号复活时逐个唤醒。 */
57
+ waiters = /* @__PURE__ */ new Set();
55
58
  constructor(ids, options = {}) {
56
59
  this.maxConcurrent = options.maxConcurrent ?? 2;
57
60
  this.now = options.now ?? (() => Date.now());
@@ -60,6 +63,7 @@ var CodeArtsAccountPool = class {
60
63
  /** 让池与账号文档对齐:新增的进来,删掉的出去。已有账号的运行时状态保留。 */
61
64
  sync(ids) {
62
65
  const wanted = new Set(ids);
66
+ const before = this.accounts.size;
63
67
  for (const id of [...this.accounts.keys()]) if (!wanted.has(id)) this.accounts.delete(id);
64
68
  for (const id of ids) {
65
69
  if (this.accounts.has(id)) continue;
@@ -76,6 +80,7 @@ var CodeArtsAccountPool = class {
76
80
  errorCount: 0
77
81
  });
78
82
  }
83
+ if (this.accounts.size !== before) this.notifyWaiters();
79
84
  }
80
85
  list() {
81
86
  return [...this.accounts.values()];
@@ -101,6 +106,11 @@ var CodeArtsAccountPool = class {
101
106
  setPaused(ids) {
102
107
  this.paused.clear();
103
108
  for (const id of ids) this.paused.add(id);
109
+ this.notifyWaiters();
110
+ }
111
+ /** 当前被用户暂停的账号 id(报错文案要把「暂停」与「槽位满」分开说)。 */
112
+ pausedIds() {
113
+ return [...this.paused];
104
114
  }
105
115
  /** 设置置顶集合(账号 id)。置顶只在「同时可用」时改变先后,不会绕过冷却/上限。 */
106
116
  setPreferred(ids) {
@@ -134,6 +144,58 @@ var CodeArtsAccountPool = class {
134
144
  const account = this.accounts.get(id);
135
145
  if (account === void 0) return;
136
146
  if (account.activeConcurrent > 0) account.activeConcurrent -= 1;
147
+ this.notifyWaiters();
148
+ }
149
+ notifyWaiters() {
150
+ for (const waiter of [...this.waiters]) try {
151
+ waiter();
152
+ } catch {}
153
+ }
154
+ /** 现在是否有一个真正能接活的空槽位(禁用/暂停/冷却中的号不算)。 */
155
+ hasFreeSlot() {
156
+ const now = this.now();
157
+ return this.list().some((a) => !a.disabled && !this.paused.has(a.id) && now >= a.coolUntil && a.activeConcurrent < a.maxConcurrent);
158
+ }
159
+ /**
160
+ * 有没有「健康、但本地槽位被占满」的号。
161
+ *
162
+ * 只有这一种情况值得等一会儿:禁用要重新登录、暂停是用户自己停的、冷却有明确
163
+ * 截止时间 —— 等它们都不会在预算内自己好。
164
+ */
165
+ hasBusyWaitable() {
166
+ const now = this.now();
167
+ return this.list().some((a) => !a.disabled && !this.paused.has(a.id) && now >= a.coolUntil && a.activeConcurrent >= a.maxConcurrent);
168
+ }
169
+ /**
170
+ * 等一个本地槽位空出来,最多 `maxWaitMs`。
171
+ *
172
+ * 返回 true = 等到了;false = 超时、被中止,或者池里根本没有「等一会儿就会空」的号。
173
+ * issue #8:本地槽位满以前是立刻回 429「没有可用账号」,并发场景下(一次派 5 个
174
+ * subagent)必然误伤;现在与上游排队对齐 —— 先短时等待,等不到再报错。
175
+ */
176
+ waitForFreeSlot(maxWaitMs, signal) {
177
+ if (this.hasFreeSlot()) return Promise.resolve(true);
178
+ if (!this.hasBusyWaitable() || maxWaitMs <= 0) return Promise.resolve(false);
179
+ if (signal?.aborted === true) return Promise.resolve(false);
180
+ return new Promise((resolve) => {
181
+ let settled = false;
182
+ const finish = (value) => {
183
+ if (settled) return;
184
+ settled = true;
185
+ this.waiters.delete(check);
186
+ clearTimeout(timer);
187
+ signal?.removeEventListener("abort", onAbort);
188
+ resolve(value);
189
+ };
190
+ const check = () => {
191
+ if (this.hasFreeSlot()) finish(true);
192
+ };
193
+ const onAbort = () => finish(false);
194
+ const timer = setTimeout(() => finish(false), maxWaitMs);
195
+ timer.unref?.();
196
+ this.waiters.add(check);
197
+ signal?.addEventListener("abort", onAbort, { once: true });
198
+ });
137
199
  }
138
200
  /**
139
201
  * 撞到上游并发上限。
@@ -188,6 +250,7 @@ var CodeArtsAccountPool = class {
188
250
  account.lastCapAt = 0;
189
251
  account.errorCount = 0;
190
252
  account.lastError = void 0;
253
+ this.notifyWaiters();
191
254
  }
192
255
  /** 上游 5xx / 软限流:短时冷却。 */
193
256
  cooldown(id, ms, reason) {
@@ -963,11 +1026,13 @@ function queuedMessage(model, gate) {
963
1026
  * 全部被禁用时回 401(宿主只自动重试 429,401 一次就把「去重新登录」说清);
964
1027
  * 只要还有会自己恢复的(冷却/槽位满)就回 429,宿主重试有概率直接救回来。
965
1028
  */
966
- function noAccountError(accounts) {
1029
+ function noAccountError(accounts, pausedIds = []) {
967
1030
  const now = Date.now();
1031
+ const paused = new Set(pausedIds);
968
1032
  const disabled = accounts.filter((a) => a.disabled);
969
1033
  const cooling = accounts.filter((a) => !a.disabled && now < a.coolUntil);
970
- const busy = accounts.filter((a) => !a.disabled && now >= a.coolUntil);
1034
+ const idleButPaused = accounts.filter((a) => !a.disabled && now >= a.coolUntil && paused.has(a.id));
1035
+ const busy = accounts.filter((a) => !a.disabled && now >= a.coolUntil && !paused.has(a.id));
971
1036
  const parts = [];
972
1037
  if (disabled.length > 0) {
973
1038
  const reasons = disabled.map((a) => a.lastError === void 0 ? a.id : `${a.id}(${a.lastError.slice(0, 120)})`).join("、");
@@ -977,8 +1042,9 @@ function noAccountError(accounts) {
977
1042
  const secs = Math.max(1, Math.ceil((Math.min(...cooling.map((a) => a.coolUntil)) - now) / 1e3));
978
1043
  parts.push(`${cooling.length} 个在短时冷却中(约 ${secs} 秒后恢复)`);
979
1044
  }
980
- if (busy.length > 0) parts.push(`${busy.length} 个的本地并发槽位已满(每账号最多 ${busy[0]?.maxConcurrent ?? 2} 个在飞请求),等几秒再发`);
981
- const message = `codearts 当前没有可用账号:${parts.join(";")}`;
1045
+ if (idleButPaused.length > 0) parts.push(`${idleButPaused.length} 个已被暂停(在卡片上取消暂停即可恢复)`);
1046
+ if (busy.length > 0) parts.push(`${busy.length} 个的本地并发槽位已满(每账号最多 ${busy[0]?.maxConcurrent ?? 2} 个在飞请求)`);
1047
+ const message = disabled.length === 0 && cooling.length === 0 && idleButPaused.length === 0 && busy.length > 0 ? `codearts 账号忙:${parts.join(";")},已等待仍没有空位,请稍后重试` : `codearts 当前没有可用账号:${parts.join(";")}`;
982
1048
  return disabled.length === accounts.length ? {
983
1049
  status: 401,
984
1050
  kind: "session_dead",
@@ -1006,7 +1072,12 @@ function readBody$1(req) {
1006
1072
  req.on("error", reject);
1007
1073
  });
1008
1074
  }
1009
- /** 一次请求最多把 max_tokens 降几档(65536 → 32768 → 16384 → 8192)。 */
1075
+ /**
1076
+ * 一次请求最多把 max_tokens 降几档(65536 → 32768 → 16384 → 8192)。
1077
+ *
1078
+ * 到地板后还会再进循环一次 —— 那一次不再重发,而是把「其实是上下文装不下」
1079
+ * 报出来并学习窗口上界(见 `openWithCeilingHeal`)。
1080
+ */
1010
1081
  const MAX_CEILING_HEALS = 3;
1011
1082
  /**
1012
1083
  * 一次请求最多试几个账号:clamp(可用账号数, ROTATE_MIN_ATTEMPTS, ROTATE_MAX_ATTEMPTS)。
@@ -1083,6 +1154,8 @@ function createCodeArtsShim(options) {
1083
1154
  const logger = options.logger;
1084
1155
  const usage = options.usage;
1085
1156
  const queue = options.queue;
1157
+ const debug = options.debug;
1158
+ const localSlotWaitBudgetMs = options.localSlotWaitMs ?? 3e4;
1086
1159
  const pool = options.pool ?? new CodeArtsAccountPool([]);
1087
1160
  const SHARED_SECRET = randomBytes(32).toString("base64url");
1088
1161
  function bearerOk(req) {
@@ -1150,11 +1223,24 @@ function createCodeArtsShim(options) {
1150
1223
  else res.end();
1151
1224
  }
1152
1225
  }
1153
- /** 该模型的上下文窗口(catalog 里查,大小写不敏感);查不到返回 0 = 不做超长预判。 */
1226
+ /**
1227
+ * 该模型当前应使用的上下文窗口:用户覆盖优先于目录值,再被进程内学到的上界往下钳。
1228
+ *
1229
+ * 学到的上界来自「max_tokens 已到地板仍被判参数非法」的实测(issue #9)。必须在这里
1230
+ * 生效 —— 只改目录不够,目录要等下一轮发现,而用户下一句话马上就来。
1231
+ * 返回 0 表示查不到该模型,不做超长预判。
1232
+ */
1154
1233
  function contextWindowFor(id) {
1155
1234
  const lower = id.trim().toLowerCase();
1156
- for (const model of catalog.current()) if (model.id.toLowerCase() === lower) return model.contextWindow;
1157
- 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;
1158
1244
  }
1159
1245
  /**
1160
1246
  * 打开上游流;撞到「参数非法」就把该模型的 max_tokens 上限折半降一档再开一次。
@@ -1220,7 +1306,8 @@ function createCodeArtsShim(options) {
1220
1306
  };
1221
1307
  }
1222
1308
  }
1223
- 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);
1224
1311
  reader.releaseLock();
1225
1312
  if (!shouldHeal) return {
1226
1313
  prepared,
@@ -1228,15 +1315,22 @@ function createCodeArtsShim(options) {
1228
1315
  head
1229
1316
  };
1230
1317
  await result.stream.cancel().catch(() => {});
1231
- if (degradeTokenCeiling(prepared.model) === 0) return {
1232
- prepared,
1233
- result: {
1234
- ok: false,
1235
- kind: "client",
1236
- status: 400,
1237
- 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}`);
1238
1322
  }
1239
- };
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
+ }
1240
1334
  logger?.warn(`dsh-codearts: ${prepared.model} 被判参数非法,max_tokens 降档到 ${maxTokensCeilingFor(prepared.model)} 后重发`);
1241
1335
  }
1242
1336
  }
@@ -1334,91 +1428,117 @@ function createCodeArtsShim(options) {
1334
1428
  let cappedAccount;
1335
1429
  let tpmAccount;
1336
1430
  let queueWaitedMs = 0;
1431
+ let localSlotWaitedMs = 0;
1337
1432
  let lastKind;
1338
1433
  let lastAccountId;
1339
1434
  let lastStatus = 0;
1340
1435
  let lastMessage = "";
1341
1436
  const rotateDeadline = Date.now() + CAP_WAIT_LIMIT;
1342
1437
  const attempts = Math.min(Math.max(ids.length, ROTATE_MIN_ATTEMPTS), ROTATE_MAX_ATTEMPTS);
1343
- for (let attempt = 0; attempt < attempts; attempt += 1) {
1344
- if (Date.now() + ATTEMPT_RESERVE_MS > rotateDeadline) break;
1345
- const id = pool.pick(tried);
1346
- if (id === void 0) break;
1347
- tried.add(id);
1348
- if (!pool.acquire(id)) continue;
1349
- try {
1350
- const credential = await store.resolve(id);
1351
- if (credential === void 0) {
1352
- pool.disable(id, "no credential");
1438
+ /** 日志里区分并发请求;没开调试时不生成。 */
1439
+ const requestTag = debug === void 0 ? "" : randomBytes(3).toString("hex");
1440
+ /**
1441
+ * 两轮:第一轮按账号轮换;如果全被「本地槽位满」挡住,就等一个槽位空出来
1442
+ * 再跑第二轮。以前这里直接落到「没有可用账号」的 429,并发派发(一次 5 个
1443
+ * subagent)必然误伤(issue #8)。
1444
+ */
1445
+ for (let round = 0; round < 2; round += 1) {
1446
+ tried.clear();
1447
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
1448
+ if (Date.now() + ATTEMPT_RESERVE_MS > rotateDeadline) break;
1449
+ const id = pool.pick(tried);
1450
+ if (id === void 0) break;
1451
+ tried.add(id);
1452
+ if (!pool.acquire(id)) {
1453
+ debug?.(`acquire miss req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
1353
1454
  continue;
1354
1455
  }
1355
- if (queue !== void 0) {
1356
- const gate = await queue.wait(credential, checked.chatId, checked.model, controller.signal);
1357
- if (controller.signal.aborted) return;
1358
- if (gate.kind === "queued") {
1359
- usage?.noteFailure("queued", id);
1360
- writeOpenAIError(res, 400, "queued", queuedMessage(checked.model, gate));
1456
+ debug?.(`acquire ok req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
1457
+ try {
1458
+ const credential = await store.resolve(id);
1459
+ if (credential === void 0) {
1460
+ pool.disable(id, "no credential");
1461
+ continue;
1462
+ }
1463
+ if (queue !== void 0) {
1464
+ const gate = await queue.wait(credential, checked.chatId, checked.model, controller.signal);
1465
+ if (controller.signal.aborted) return;
1466
+ if (gate.kind === "queued") {
1467
+ usage?.noteFailure("queued", id);
1468
+ writeOpenAIError(res, 400, "queued", queuedMessage(checked.model, gate));
1469
+ return;
1470
+ }
1471
+ if (gate.kind === "queue_full" || gate.kind === "error") {
1472
+ usage?.noteFailure(gate.kind, id);
1473
+ writeOpenAIError(res, gate.kind === "queue_full" ? 429 : 502, gate.kind, gate.message);
1474
+ return;
1475
+ }
1476
+ }
1477
+ const opened = await openWithCeilingHeal(credential, raw, contextWindow, controller.signal);
1478
+ const { prepared, result } = opened;
1479
+ if (controller.signal.aborted) {
1480
+ if (result.ok) await result.stream.cancel().catch(() => {});
1361
1481
  return;
1362
1482
  }
1363
- if (gate.kind === "queue_full" || gate.kind === "error") {
1364
- usage?.noteFailure(gate.kind, id);
1365
- writeOpenAIError(res, gate.kind === "queue_full" ? 429 : 502, gate.kind, gate.message);
1483
+ if (result.ok) {
1484
+ pool.noteSuccess(id);
1485
+ await pipeToResponse(res, result.stream, controller.signal, {
1486
+ accountId: id,
1487
+ model: prepared.model,
1488
+ startedAt: requestStartedAt
1489
+ }, opened.head);
1366
1490
  return;
1367
1491
  }
1368
- }
1369
- const opened = await openWithCeilingHeal(credential, raw, contextWindow, controller.signal);
1370
- const { prepared, result } = opened;
1371
- if (controller.signal.aborted) {
1372
- if (result.ok) await result.stream.cancel().catch(() => {});
1373
- return;
1374
- }
1375
- if (result.ok) {
1376
- pool.noteSuccess(id);
1377
- await pipeToResponse(res, result.stream, controller.signal, {
1378
- accountId: id,
1379
- model: prepared.model,
1380
- startedAt: requestStartedAt
1381
- }, opened.head);
1382
- return;
1383
- }
1384
- lastKind = result.kind;
1385
- lastAccountId = id;
1386
- lastStatus = result.status;
1387
- lastMessage = result.message;
1388
- if (isConcurrencyCap(result)) {
1389
- pool.noteConcurrencyCap(id);
1390
- cappedAccount = id;
1391
- continue;
1392
- }
1393
- if (isTpmLimit(result)) {
1394
- tpmAccount = id;
1395
- break;
1396
- }
1397
- if (result.kind === "iam_stale") {
1398
- if (!refreshed.has(id)) {
1399
- refreshed.add(id);
1400
- logger?.warn(`dsh-codearts: ${id} 的 IAM token 被判失效,强制续期后重试`);
1401
- if (await store.forceRefresh(id, credential.token) !== void 0) {
1402
- tried.delete(id);
1403
- continue;
1492
+ lastKind = result.kind;
1493
+ lastAccountId = id;
1494
+ lastStatus = result.status;
1495
+ lastMessage = result.message;
1496
+ if (isConcurrencyCap(result)) {
1497
+ pool.noteConcurrencyCap(id);
1498
+ cappedAccount = id;
1499
+ continue;
1500
+ }
1501
+ if (isTpmLimit(result)) {
1502
+ tpmAccount = id;
1503
+ break;
1504
+ }
1505
+ if (result.kind === "iam_stale") {
1506
+ if (!refreshed.has(id)) {
1507
+ refreshed.add(id);
1508
+ logger?.warn(`dsh-codearts: ${id} 的 IAM token 被判失效,强制续期后重试`);
1509
+ if (await store.forceRefresh(id, credential.token) !== void 0) {
1510
+ tried.delete(id);
1511
+ continue;
1512
+ }
1404
1513
  }
1514
+ pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1515
+ continue;
1405
1516
  }
1406
- pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1407
- continue;
1408
- }
1409
- if (result.kind === "session_dead") {
1410
- pool.disable(id, result.message);
1411
- continue;
1412
- }
1413
- if (result.kind === "server" || result.kind === "soft_rate") {
1414
- pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1517
+ if (result.kind === "session_dead") {
1518
+ pool.disable(id, result.message);
1519
+ continue;
1520
+ }
1521
+ if (result.kind === "server" || result.kind === "soft_rate") {
1522
+ pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1523
+ break;
1524
+ }
1525
+ pool.noteError(id, 3, ERROR_COOLDOWN_MS, result.message);
1415
1526
  break;
1527
+ } finally {
1528
+ pool.release(id);
1529
+ debug?.(`release req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
1416
1530
  }
1417
- pool.noteError(id, 3, ERROR_COOLDOWN_MS, result.message);
1418
- break;
1419
- } finally {
1420
- pool.release(id);
1421
1531
  }
1532
+ if (lastKind !== void 0 || controller.signal.aborted) break;
1533
+ if (!pool.hasBusyWaitable()) break;
1534
+ const waitBudget = Math.min(localSlotWaitBudgetMs, rotateDeadline - ATTEMPT_RESERVE_MS - Date.now());
1535
+ if (waitBudget <= 0) break;
1536
+ const waitingSince = Date.now();
1537
+ debug?.(`slot wait start req=${requestTag} budget=${waitBudget}ms pool=${pool.list().map((a) => `${a.id}:${a.activeConcurrent}/${a.maxConcurrent}`).join(",")}`);
1538
+ const got = await pool.waitForFreeSlot(waitBudget, controller.signal);
1539
+ localSlotWaitedMs += Date.now() - waitingSince;
1540
+ debug?.(`slot wait ${got ? "done" : "timeout"} req=${requestTag} waited=${Date.now() - waitingSince}ms`);
1541
+ if (!got) break;
1422
1542
  }
1423
1543
  if (controller.signal.aborted) return;
1424
1544
  const queueAccount = cappedAccount ?? tpmAccount;
@@ -1453,13 +1573,16 @@ function createCodeArtsShim(options) {
1453
1573
  }
1454
1574
  }
1455
1575
  if (lastKind === void 0) {
1456
- const none = noAccountError(pool.list());
1576
+ const none = noAccountError(pool.list(), pool.pausedIds());
1457
1577
  usage?.noteFailure(none.kind);
1458
1578
  writeOpenAIError(res, none.status, none.kind, none.message);
1459
1579
  return;
1460
1580
  }
1461
1581
  const explanation = upstreamErrorMessage(lastMessage, lastStatus);
1462
- const waited = queueWaitedMs >= 1e3 ? `(本地已排队重试 ${Math.round(queueWaitedMs / 1e3)} 秒)` : "";
1582
+ const waits = [];
1583
+ if (queueWaitedMs >= 1e3) waits.push(`排队重试 ${Math.round(queueWaitedMs / 1e3)} 秒`);
1584
+ if (localSlotWaitedMs >= 1e3) waits.push(`等本地槽位 ${Math.round(localSlotWaitedMs / 1e3)} 秒`);
1585
+ const waited = waits.length > 0 ? `(本地已${waits.join("、")})` : "";
1463
1586
  usage?.noteFailure(lastKind, lastAccountId);
1464
1587
  writeOpenAIError(res, KIND_STATUS[lastKind], lastKind, `${explanation}${waited}`);
1465
1588
  }
@@ -1564,6 +1687,11 @@ const IDENTITY_TIMEOUT_MS = 8e3;
1564
1687
  const CODEARTS_STATUS_PATH = "/api/codearts/status";
1565
1688
  const CODEARTS_MODELS_PATH = "/api/codearts/models";
1566
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";
1567
1695
  const CODEARTS_TOKEN_PATH = "/api/codearts/token";
1568
1696
  const CODEARTS_LOGIN_PATH = "/api/codearts/login";
1569
1697
  const CODEARTS_LOGIN_STATUS_PATH = "/api/codearts/login/status";
@@ -1623,6 +1751,8 @@ function selectionOf(models, enabled, writable) {
1623
1751
  ratio: m.ratio,
1624
1752
  supportsImages: m.supportsImages,
1625
1753
  contextWindow: m.contextWindow,
1754
+ contextWindowDiscovered: m.contextWindowDiscovered,
1755
+ contextWindowOverride: m.contextWindowOverride,
1626
1756
  maxTokens: m.maxTokens,
1627
1757
  ...m.error === void 0 ? {} : { error: m.error },
1628
1758
  enabled: restricted ? allowed.has(m.id) : true
@@ -1633,10 +1763,12 @@ function selectionOf(models, enabled, writable) {
1633
1763
  }
1634
1764
  /** 目录 -> 勾选 UI 的选项(福利标记、今日不可用标记与倍率都在这里算)。 */
1635
1765
  function choicesOf(deps) {
1766
+ const overrides = deps.contextWindowOverrides?.();
1636
1767
  return deps.models().map((m) => {
1637
1768
  const benefit = isBenefitModel(m.id);
1638
1769
  const ratio = creditRatioLabel(m.ratio, benefit);
1639
1770
  const error = modelUnavailableReason(m.id);
1771
+ const override = contextWindowOverrideFor(overrides, m.id);
1640
1772
  return {
1641
1773
  id: m.id,
1642
1774
  name: m.name,
@@ -1645,6 +1777,8 @@ function choicesOf(deps) {
1645
1777
  ...ratio === void 0 ? {} : { ratio },
1646
1778
  ...m.supportsImages === true ? { supportsImages: true } : {},
1647
1779
  ...m.contextWindowKnown === true ? { contextWindow: m.contextWindow } : {},
1780
+ ...m.contextWindowDiscovered === void 0 ? {} : { contextWindowDiscovered: m.contextWindowDiscovered },
1781
+ ...override === void 0 ? {} : { contextWindowOverride: override },
1648
1782
  ...m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {},
1649
1783
  ...error === void 0 ? {} : { error }
1650
1784
  };
@@ -1675,6 +1809,7 @@ const DEFAULT_DOCK_FLAGS = {
1675
1809
  credits: true,
1676
1810
  queue: true,
1677
1811
  sidebar: false,
1812
+ settingsEntry: true,
1678
1813
  modelDetail: true,
1679
1814
  autoClaim: false,
1680
1815
  keepAliveDaemon: false
@@ -2061,12 +2196,13 @@ function dockHandler(deps) {
2061
2196
  "credits",
2062
2197
  "queue",
2063
2198
  "sidebar",
2199
+ "settingsEntry",
2064
2200
  "modelDetail",
2065
2201
  "autoClaim",
2066
2202
  "keepAliveDaemon"
2067
2203
  ].filter((key) => body[key] !== void 0);
2068
2204
  if (touched.length === 0 || touched.some((key) => typeof body[key] !== "boolean")) {
2069
- json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean}" });
2205
+ json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"settingsEntry\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean}" });
2070
2206
  return;
2071
2207
  }
2072
2208
  if (!await deps.setDock(Object.fromEntries(touched.map((key) => [key, body[key]])))) {
@@ -2181,6 +2317,56 @@ function modelsSelectionHandler(deps) {
2181
2317
  json(res, 405, { error: "method not allowed" });
2182
2318
  };
2183
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
+ }
2184
2370
  /** POST /api/codearts/token { token, label? } — store a pasted token. */
2185
2371
  function tokenPostHandler(deps) {
2186
2372
  return async (req, res) => {
@@ -2551,6 +2737,11 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2551
2737
  path: CODEARTS_MODELS_SELECTION_PATH,
2552
2738
  handler: modelsSelectionHandler(deps)
2553
2739
  });
2740
+ const disposeContextWindow = ctx.webServer.register({
2741
+ kind: "exact",
2742
+ path: CODEARTS_CONTEXT_WINDOW_PATH,
2743
+ handler: contextWindowHandler(deps)
2744
+ });
2554
2745
  const disposeToken = ctx.webServer.register({
2555
2746
  kind: "exact",
2556
2747
  path: CODEARTS_TOKEN_PATH,
@@ -2615,6 +2806,7 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2615
2806
  disposeStatus();
2616
2807
  disposeModels();
2617
2808
  disposeModelsSelection();
2809
+ disposeContextWindow();
2618
2810
  disposeToken();
2619
2811
  disposeLoginStart();
2620
2812
  disposeLoginStatus();
@@ -2802,9 +2994,11 @@ function unwrapConfig(value) {
2802
2994
  }
2803
2995
  const Config = z.object({
2804
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(),
2805
2998
  showCreditDock: z.boolean().default(true).description("Show the remaining-credits line under the chat input box").volatile(),
2806
2999
  showQueueDock: z.boolean().default(true).description("Show the upstream queue position under the chat input box").volatile(),
2807
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
+ showSettingsEntry: z.boolean().default(true).description("Show a CodeArts entry in the left navigation of DSH Settings (default: shown)").volatile(),
2808
3002
  showModelDetailDock: z.boolean().default(true).description("Show \"Model … · x ratio\" on the line under the chat input box (Provider CodeArts always shows)").volatile(),
2809
3003
  autoClaim: z.boolean().default(false).description("Automatically claim the daily sign-in credits for every signed-in account").volatile(),
2810
3004
  keepAliveDaemon: z.boolean().default(false).description("Keep a detached background process that refreshes the OAuth credential while DSH is closed").volatile()
@@ -2815,7 +3009,23 @@ function settingsCompatNamespace(ctx) {
2815
3009
  function apply(ctx, rawConfig) {
2816
3010
  const config = unwrapConfig(rawConfig);
2817
3011
  const accountsPath = codeartsAccountsPath();
2818
- const store = new CodeArtsAccountStore(accountsPath);
3012
+ /**
3013
+ * 续期失败日志。
3014
+ *
3015
+ * 宿主对插件的 `info`/`debug` 没有任何出口,`warn` 会变成系统通知 —— 一次网络抖动
3016
+ * 就弹一次窗口显然不行。所以失败原因写插件自己的文件(issue #8 里 03:22 那次续期
3017
+ * 失败就是因为零日志而永远无法取证)。1MB 截断重来,避免长期运行无限增长。
3018
+ */
3019
+ const appendRefreshLog = (message) => {
3020
+ try {
3021
+ const path = codeartsRefreshLogPath();
3022
+ try {
3023
+ if (statSync(path).size > 1e6) writeFileSync(path, "");
3024
+ } catch {}
3025
+ appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
3026
+ } catch {}
3027
+ };
3028
+ const store = new CodeArtsAccountStore(accountsPath, void 0, { log: appendRefreshLog });
2819
3029
  const pool = new CodeArtsAccountPool([]);
2820
3030
  const catalog = new CodeArtsCatalog();
2821
3031
  const usage = new CodeArtsUsageTracker({ path: codeartsUsagePath() });
@@ -2885,10 +3095,41 @@ function apply(ctx, rawConfig) {
2885
3095
  await settings.update(settingsCompatNamespace(ctx), { enabledModels: [...ids] });
2886
3096
  return true;
2887
3097
  };
3098
+ /**
3099
+ * 写/清某个模型的窗口覆盖(issue #9)。
3100
+ *
3101
+ * 除了落 settings,还**当场**把目录里那条改成新值:卡片保存后会立刻重拉 selection,
3102
+ * 目录不跟着变的话输入框会弹回旧数字,用户会以为没存上。
3103
+ * `window: null` = 删除覆盖,生效值退回上游标称值(`contextWindowDiscovered`)。
3104
+ */
3105
+ const setContextWindowOverride = async (id, window) => {
3106
+ const settings = ctx.get("settings");
3107
+ if (settings === void 0) return false;
3108
+ const lower = id.trim().toLowerCase();
3109
+ const next = {};
3110
+ for (const [key, value] of Object.entries(current().contextWindowOverrides ?? {})) if (key.trim().toLowerCase() !== lower) next[key] = value;
3111
+ if (window !== null) next[id.trim()] = window;
3112
+ await settings.update(settingsCompatNamespace(ctx), { contextWindowOverrides: next });
3113
+ catalog.set(catalog.current().map((model) => {
3114
+ if (model.id.toLowerCase() !== lower) return model;
3115
+ const target = window ?? model.contextWindowDiscovered ?? model.contextWindow;
3116
+ const { contextWindowDiscovered, ...rest } = model;
3117
+ return contextWindowDiscovered === void 0 || contextWindowDiscovered === target ? {
3118
+ ...rest,
3119
+ contextWindow: target
3120
+ } : {
3121
+ ...rest,
3122
+ contextWindow: target,
3123
+ contextWindowDiscovered
3124
+ };
3125
+ }));
3126
+ return true;
3127
+ };
2888
3128
  const dock = () => ({
2889
3129
  credits: current().showCreditDock !== false,
2890
3130
  queue: current().showQueueDock !== false,
2891
3131
  sidebar: current().showSidebarPanel === true,
3132
+ settingsEntry: current().showSettingsEntry !== false,
2892
3133
  modelDetail: current().showModelDetailDock !== false,
2893
3134
  autoClaim: current().autoClaim === true,
2894
3135
  keepAliveDaemon: current().keepAliveDaemon === true
@@ -2900,6 +3141,7 @@ function apply(ctx, rawConfig) {
2900
3141
  ...patch.credits === void 0 ? {} : { showCreditDock: patch.credits },
2901
3142
  ...patch.queue === void 0 ? {} : { showQueueDock: patch.queue },
2902
3143
  ...patch.sidebar === void 0 ? {} : { showSidebarPanel: patch.sidebar },
3144
+ ...patch.settingsEntry === void 0 ? {} : { showSettingsEntry: patch.settingsEntry },
2903
3145
  ...patch.modelDetail === void 0 ? {} : { showModelDetailDock: patch.modelDetail },
2904
3146
  ...patch.autoClaim === void 0 ? {} : { autoClaim: patch.autoClaim },
2905
3147
  ...patch.keepAliveDaemon === void 0 ? {} : { keepAliveDaemon: patch.keepAliveDaemon }
@@ -3099,6 +3341,8 @@ function apply(ctx, rawConfig) {
3099
3341
  models: () => catalog.current(),
3100
3342
  enabledModels,
3101
3343
  setEnabledModels,
3344
+ contextWindowOverrides: () => current().contextWindowOverrides,
3345
+ setContextWindowOverride,
3102
3346
  pool: () => pool.list(),
3103
3347
  reviveAccount: (id) => pool.revive(id),
3104
3348
  usage: () => usage.snapshot(),
@@ -3125,7 +3369,7 @@ function apply(ctx, rawConfig) {
3125
3369
  return outcome;
3126
3370
  },
3127
3371
  refreshModels: async () => {
3128
- const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS));
3372
+ const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS), current().contextWindowOverrides);
3129
3373
  const models = catalog.current();
3130
3374
  return {
3131
3375
  models: models.length,
@@ -3159,7 +3403,7 @@ function apply(ctx, rawConfig) {
3159
3403
  const discover = async () => {
3160
3404
  if (stopped) return;
3161
3405
  try {
3162
- const outcome = await refreshCatalog(store, catalog, abort.signal);
3406
+ const outcome = await refreshCatalog(store, catalog, abort.signal, current().contextWindowOverrides);
3163
3407
  if (outcome === void 0 || stopped) return;
3164
3408
  if (outcome.anySucceeded) {
3165
3409
  const free = outcome.models.filter((model) => model.benefit === true).length;
@@ -3280,13 +3524,30 @@ function apply(ctx, rawConfig) {
3280
3524
  if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
3281
3525
  if (keeperTimer !== void 0) clearTimeout(keeperTimer);
3282
3526
  });
3527
+ /**
3528
+ * 槽位取证日志:acquire/release 的时间点与在飞计数。
3529
+ *
3530
+ * 默认关闭(只有 `DSH_CODEARTS_DEBUG=1` 时写)。issue #8 里「只剩一个在飞请求,
3531
+ * 但所有 acquire 都失败」的怀疑,只能靠这份日志证实或排除。
3532
+ */
3533
+ const writeDebugLog = process.env.DSH_CODEARTS_DEBUG === "1" ? (message) => {
3534
+ try {
3535
+ const path = codeartsDebugLogPath();
3536
+ try {
3537
+ if (statSync(path).size > 2e6) writeFileSync(path, "");
3538
+ } catch {}
3539
+ appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
3540
+ } catch {}
3541
+ } : void 0;
3283
3542
  const shim = createCodeArtsShim({
3284
3543
  store,
3285
3544
  catalog,
3286
3545
  pool,
3287
3546
  usage,
3288
3547
  queue,
3289
- logger: ctx.logger
3548
+ logger: ctx.logger,
3549
+ debug: writeDebugLog,
3550
+ contextWindowOverrides: () => current().contextWindowOverrides
3290
3551
  });
3291
3552
  usage.load().catch(() => {});
3292
3553
  shim.ready.then(async () => {