dsh-codearts 1.4.1 → 1.4.3
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/CHANGELOG.md +41 -0
- package/lib/{auth-C00dJphV.mjs → auth-Cd2SvQIy.mjs} +1 -1
- package/lib/bin.mjs +3 -3
- package/lib/client/index.d.cts +3 -0
- package/lib/client/index.js +134 -98
- package/lib/index.d.mts +36 -11
- package/lib/index.mjs +196 -52
- package/lib/{keeper-MHeAp_eV.mjs → keeper-DJLwIiR4.mjs} +82 -7
- package/lib/keeper-main.mjs +62 -12
- package/lib/{upstream-D1wYeXC7.mjs → upstream-BV4XWB4l.mjs} +74 -10
- package/lib/{version-DC5JRWls.mjs → version-DqzkoxeU.mjs} +3 -3
- package/package.json +1 -1
package/lib/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as codeartsAuthPath, c as credentialFromOAuth, i as codeartsAccountsPath, m as startLogin, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-
|
|
2
|
-
import { A as
|
|
3
|
-
import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-
|
|
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-Cd2SvQIy.mjs";
|
|
2
|
+
import { A as queueFrame, B as forgetModelUnavailable, C as isWelfareClaimedStatus, D as modelUnavailableReasonText, E as maxTokensCeilingFor, F as CodeArtsCatalog, H as isBenefitModel, I as FALLBACK_CODEARTS_MODELS, K as modelUnavailableReason, L as clearBenefitBlocked, M as signedGet, N as upstreamErrorMessage, O as pickDailyWelfareCampaign, R as creditRatioLabel, S as isTpmLimit, T as learnedContextWindowFor, U as markModelUnavailable, V as isBenefitBlocked, _ 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, 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 filterEnabledModels } from "./upstream-BV4XWB4l.mjs";
|
|
3
|
+
import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-DqzkoxeU.mjs";
|
|
4
4
|
import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { c as keeperLogPath, d as keeperStats, f as spawnKeeper, i as clearKeeperHandoff, l as keeperScriptPath, n as KEEPER_STALE_MS, p as stopKeeper, s as keeperHandoffRecent } from "./keeper-DJLwIiR4.mjs";
|
|
6
6
|
import { appendFileSync, statSync, writeFileSync } from "node:fs";
|
|
7
7
|
import z from "@deepseek-ai/schemastery";
|
|
8
8
|
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
@@ -294,16 +294,16 @@ var CodeArtsAccountPool = class {
|
|
|
294
294
|
* 官方客户端的做法是:只对 `enable_queue` 的模型,先轮询排队接口,等状态变成
|
|
295
295
|
* `working` 才发聊天请求(见 vscode-codebot 的 `startQueuePolling`)。
|
|
296
296
|
*
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
* - 等到 working → 放行;
|
|
302
|
-
* - 还在队里 → 返回 `queued` 带上位置和队长度,由 shim 直接回一句「排队中,
|
|
303
|
-
* 稍后再试」,让用户自己决定要不要再发一次;
|
|
304
|
-
* - 队列已满 → `queue_full`;连续失败 → `error`。
|
|
297
|
+
* 这张票的定位是**提示,不是门禁**(issue #10):真正的 chat 请求并不校验它,
|
|
298
|
+
* 所以 `wait()` 只做一次短探(`maxWaitMs`,默认 5 秒),结果交给 shim ——
|
|
299
|
+
* 没轮到也照发请求,底部积分条在这几秒里显示「排队第 N 位」。以前等满 20 秒
|
|
300
|
+
* 就直接回 400,用户看到的失败其实是插件自己造出来的。
|
|
305
301
|
*
|
|
306
|
-
*
|
|
302
|
+
* 宿主也等不起:流空闲超时只有 90 秒(等待期间一个字节都发不出去,SSE 注释帧
|
|
303
|
+
* 也不算事件),而 flash 高峰期队尾有 500+ 号、要等二十几分钟。真正值得等的位置
|
|
304
|
+
* 在 POST 被上游明确拒绝之后(还没写任何字节,重发安全),由 shim 退避重试。
|
|
305
|
+
*
|
|
306
|
+
* 收尾(轮到/超时/取消/失败)都会 DELETE 清号,别把幽灵排队留在上游撑大队列。
|
|
307
307
|
*
|
|
308
308
|
* @module dsh-codearts/queue
|
|
309
309
|
*/
|
|
@@ -319,17 +319,17 @@ var CodeArtsQueueGate = class {
|
|
|
319
319
|
now;
|
|
320
320
|
constructor(options = {}) {
|
|
321
321
|
this.intervalMs = options.intervalMs ?? 5e3;
|
|
322
|
-
this.maxWaitMs = options.maxWaitMs ??
|
|
322
|
+
this.maxWaitMs = options.maxWaitMs ?? 5e3;
|
|
323
323
|
this.maxErrors = options.maxErrors ?? 3;
|
|
324
324
|
this.query = options.fetchStatus ?? fetchQueueStatus;
|
|
325
325
|
this.clear = options.clearStatus ?? ((credential, chatId, model) => clearQueueStatus(credential, chatId, model, AbortSignal.timeout(CLEAR_TIMEOUT_MS)));
|
|
326
326
|
this.now = options.now ?? Date.now;
|
|
327
327
|
}
|
|
328
328
|
/**
|
|
329
|
-
*
|
|
330
|
-
*
|
|
329
|
+
* 占号并**最多探 `maxWaitMs`**。调用方只拿结果做提示:`working` 表示正好轮到,
|
|
330
|
+
* 其余结果照发 chat 请求(这张票不拦请求,见模块注释)。
|
|
331
331
|
*/
|
|
332
|
-
async wait(credential, chatId, model, signal) {
|
|
332
|
+
async wait(credential, chatId, model, signal, budgetMs = this.maxWaitMs) {
|
|
333
333
|
if (chatId === "") return { kind: "working" };
|
|
334
334
|
if (signal?.aborted === true) return { kind: "aborted" };
|
|
335
335
|
const controller = new AbortController();
|
|
@@ -346,7 +346,7 @@ var CodeArtsQueueGate = class {
|
|
|
346
346
|
};
|
|
347
347
|
this.entries.set(chatId, entry);
|
|
348
348
|
let errors = 0;
|
|
349
|
-
const deadlineAt = this.now() +
|
|
349
|
+
const deadlineAt = this.now() + budgetMs;
|
|
350
350
|
try {
|
|
351
351
|
for (;;) {
|
|
352
352
|
if (controller.signal.aborted) return { kind: "aborted" };
|
|
@@ -1011,14 +1011,6 @@ function writeOpenAIError(res, status, kind, message) {
|
|
|
1011
1011
|
} });
|
|
1012
1012
|
}
|
|
1013
1013
|
/**
|
|
1014
|
-
* 排队没等到时回给用户的那句:优先用上游自己的文案(它就是写给人看的,带位置和
|
|
1015
|
-
* 「建议切换模型/升级套餐」),上游没给才自己拼。
|
|
1016
|
-
*/
|
|
1017
|
-
function queuedMessage(model, gate) {
|
|
1018
|
-
const upstream = gate.message.trim();
|
|
1019
|
-
return `${upstream === "" ? `上游排队中:${model} 第 ${gate.position} 位(共 ${gate.length} 条)` : upstream} 插件没有一直等下去,请稍后重试。`;
|
|
1020
|
-
}
|
|
1021
|
-
/**
|
|
1022
1014
|
* 「一个账号都选不出来」时的报错:把真实原因说清 —— 是禁用(附最后错误)、冷却
|
|
1023
1015
|
* (附剩余秒数),还是本地槽位全满。以前三种都回同一句「没有可用账号」,禁用那
|
|
1024
1016
|
* 种还把真因(比如 billion-context 本地拒签的 403)整个吞掉(issue #1)。
|
|
@@ -1091,7 +1083,7 @@ const MAX_CEILING_HEALS = 3;
|
|
|
1091
1083
|
*/
|
|
1092
1084
|
const ROTATE_MIN_ATTEMPTS = 3;
|
|
1093
1085
|
const ROTATE_MAX_ATTEMPTS = 6;
|
|
1094
|
-
/**
|
|
1086
|
+
/** 开始下一次尝试前必须留下的预算:一次挂号短探(默认 5 秒)再加一次开流。 */
|
|
1095
1087
|
const ATTEMPT_RESERVE_MS = 2e4;
|
|
1096
1088
|
/**
|
|
1097
1089
|
* 一次请求在「换号轮换 + 回落到同一账号原地重发」上总共能花的墙上时间,从进入
|
|
@@ -1108,6 +1100,17 @@ const ATTEMPT_RESERVE_MS = 2e4;
|
|
|
1108
1100
|
*/
|
|
1109
1101
|
const CAP_WAIT_LIMIT = 75e3;
|
|
1110
1102
|
const CAP_RETRY_GAP = 3e3;
|
|
1103
|
+
/** 上游回「排队」拒绝后的首次退避,之后翻倍(5s → 10s → 20s → 30s)。 */
|
|
1104
|
+
const QUEUE_RETRY_GAP = 5e3;
|
|
1105
|
+
/**
|
|
1106
|
+
* 「排队时一直等到轮到」开关打开后替用户挂多久。
|
|
1107
|
+
*
|
|
1108
|
+
* 默认关(卡片「显示」页):这一段会提前打开 SSE 并每 20 秒发一个空帧保活,
|
|
1109
|
+
* 等待期间界面上已经开始「回复」了 —— 属于用户应当主动选择的行为。
|
|
1110
|
+
*/
|
|
1111
|
+
const QUEUE_WAIT_LIMIT_MS = 9e5;
|
|
1112
|
+
/** 空帧间隔:宿主按「可解析的流事件」算 90 秒空闲,20 秒留足余量。 */
|
|
1113
|
+
const QUEUE_HEARTBEAT_MS = 2e4;
|
|
1111
1114
|
/** 上游 5xx 后短时冷却该账号。 */
|
|
1112
1115
|
const SERVER_COOLDOWN_MS = 3e4;
|
|
1113
1116
|
/** 零散错误累计到阈值后冷却该账号。 */
|
|
@@ -1156,6 +1159,7 @@ function createCodeArtsShim(options) {
|
|
|
1156
1159
|
const queue = options.queue;
|
|
1157
1160
|
const debug = options.debug;
|
|
1158
1161
|
const localSlotWaitBudgetMs = options.localSlotWaitMs ?? 3e4;
|
|
1162
|
+
const queueRetryGapMs = options.queueRetryGapMs ?? QUEUE_RETRY_GAP;
|
|
1159
1163
|
const pool = options.pool ?? new CodeArtsAccountPool([]);
|
|
1160
1164
|
const SHARED_SECRET = randomBytes(32).toString("base64url");
|
|
1161
1165
|
function bearerOk(req) {
|
|
@@ -1286,6 +1290,21 @@ function createCodeArtsShim(options) {
|
|
|
1286
1290
|
}
|
|
1287
1291
|
};
|
|
1288
1292
|
}
|
|
1293
|
+
const queued = headText === void 0 ? void 0 : queueFrame(headText);
|
|
1294
|
+
if (queued !== void 0) {
|
|
1295
|
+
reader.releaseLock();
|
|
1296
|
+
await result.stream.cancel().catch(() => {});
|
|
1297
|
+
logger?.warn(`dsh-codearts: ${prepared.model} 首帧被判排队,本地退避重发`);
|
|
1298
|
+
return {
|
|
1299
|
+
prepared,
|
|
1300
|
+
result: {
|
|
1301
|
+
ok: false,
|
|
1302
|
+
kind: "client",
|
|
1303
|
+
status: 400,
|
|
1304
|
+
message: `queued: ${queued.message}`
|
|
1305
|
+
}
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1289
1308
|
const upstreamError = headText === void 0 ? void 0 : firstFrameError(headText);
|
|
1290
1309
|
if (upstreamError !== void 0) {
|
|
1291
1310
|
const detail = `${upstreamError.code}: ${upstreamError.message}`.replace(/^: /, "");
|
|
@@ -1345,11 +1364,15 @@ function createCodeArtsShim(options) {
|
|
|
1345
1364
|
* 间隔逐次翻倍(3s → 6s → 12s → 24s,封顶 30s),避免在配额已经满的时候
|
|
1346
1365
|
* 把重试本身也打成一波流量。
|
|
1347
1366
|
*
|
|
1367
|
+
* 「排队」拒绝(issue #10)同理:上游让等一会儿再来,从 5 秒起翻倍重发;
|
|
1368
|
+
* 这段等待发生在 POST 被拒之后 —— 还没写给宿主任何字节,重发安全。
|
|
1369
|
+
*
|
|
1348
1370
|
* 命中限流不甩给 pi-ai:429 会被重试 5 次,每次再撞一次限流,越试越满。
|
|
1349
1371
|
*/
|
|
1350
1372
|
async function openStream(credential, raw, contextWindow, signal, untilAt) {
|
|
1351
1373
|
const started = Date.now();
|
|
1352
1374
|
let gap = CAP_RETRY_GAP;
|
|
1375
|
+
let queueGap = queueRetryGapMs;
|
|
1353
1376
|
for (;;) {
|
|
1354
1377
|
const opened = await openWithCeilingHeal(credential, raw, contextWindow, signal);
|
|
1355
1378
|
const waitedMs = Date.now() - started;
|
|
@@ -1362,6 +1385,10 @@ function createCodeArtsShim(options) {
|
|
|
1362
1385
|
waitedMs
|
|
1363
1386
|
};
|
|
1364
1387
|
if (isTpmLimit(opened.result)) gap = Math.min(gap * 2, 3e4);
|
|
1388
|
+
if (isQueueReject(opened.result)) {
|
|
1389
|
+
gap = queueGap;
|
|
1390
|
+
queueGap = Math.min(queueGap * 2, 3e4);
|
|
1391
|
+
}
|
|
1365
1392
|
if (Date.now() + gap > untilAt) return {
|
|
1366
1393
|
...opened,
|
|
1367
1394
|
waitedMs
|
|
@@ -1427,6 +1454,7 @@ function createCodeArtsShim(options) {
|
|
|
1427
1454
|
const refreshed = /* @__PURE__ */ new Set();
|
|
1428
1455
|
let cappedAccount;
|
|
1429
1456
|
let tpmAccount;
|
|
1457
|
+
let queuedAccount;
|
|
1430
1458
|
let queueWaitedMs = 0;
|
|
1431
1459
|
let localSlotWaitedMs = 0;
|
|
1432
1460
|
let lastKind;
|
|
@@ -1463,16 +1491,7 @@ function createCodeArtsShim(options) {
|
|
|
1463
1491
|
if (queue !== void 0) {
|
|
1464
1492
|
const gate = await queue.wait(credential, checked.chatId, checked.model, controller.signal);
|
|
1465
1493
|
if (controller.signal.aborted) return;
|
|
1466
|
-
if (gate.kind
|
|
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
|
-
}
|
|
1494
|
+
if (gate.kind !== "working") debug?.(`queue ${gate.kind} req=${requestTag} ${id}`);
|
|
1476
1495
|
}
|
|
1477
1496
|
const opened = await openWithCeilingHeal(credential, raw, contextWindow, controller.signal);
|
|
1478
1497
|
const { prepared, result } = opened;
|
|
@@ -1502,6 +1521,10 @@ function createCodeArtsShim(options) {
|
|
|
1502
1521
|
tpmAccount = id;
|
|
1503
1522
|
break;
|
|
1504
1523
|
}
|
|
1524
|
+
if (isQueueReject(result)) {
|
|
1525
|
+
queuedAccount = id;
|
|
1526
|
+
break;
|
|
1527
|
+
}
|
|
1505
1528
|
if (result.kind === "iam_stale") {
|
|
1506
1529
|
if (!refreshed.has(id)) {
|
|
1507
1530
|
refreshed.add(id);
|
|
@@ -1541,7 +1564,11 @@ function createCodeArtsShim(options) {
|
|
|
1541
1564
|
if (!got) break;
|
|
1542
1565
|
}
|
|
1543
1566
|
if (controller.signal.aborted) return;
|
|
1544
|
-
|
|
1567
|
+
if (queuedAccount !== void 0 && options.waitInQueue?.() === true) {
|
|
1568
|
+
await waitForQueueTurn(queuedAccount);
|
|
1569
|
+
return;
|
|
1570
|
+
}
|
|
1571
|
+
const queueAccount = cappedAccount ?? tpmAccount ?? queuedAccount;
|
|
1545
1572
|
if (queueAccount !== void 0) {
|
|
1546
1573
|
if (pool.acquire(queueAccount)) try {
|
|
1547
1574
|
const credential = await store.resolve(queueAccount);
|
|
@@ -1583,8 +1610,110 @@ function createCodeArtsShim(options) {
|
|
|
1583
1610
|
if (queueWaitedMs >= 1e3) waits.push(`排队重试 ${Math.round(queueWaitedMs / 1e3)} 秒`);
|
|
1584
1611
|
if (localSlotWaitedMs >= 1e3) waits.push(`等本地槽位 ${Math.round(localSlotWaitedMs / 1e3)} 秒`);
|
|
1585
1612
|
const waited = waits.length > 0 ? `(本地已${waits.join("、")})` : "";
|
|
1586
|
-
|
|
1587
|
-
|
|
1613
|
+
const failedKind = isQueueRejectText(lastMessage) ? "queued" : lastKind;
|
|
1614
|
+
usage?.noteFailure(failedKind, lastAccountId);
|
|
1615
|
+
writeOpenAIError(res, KIND_STATUS[lastKind], failedKind, `${explanation}${waited}`);
|
|
1616
|
+
/**
|
|
1617
|
+
* 「一直等到轮到」:提前开流保住宿主连接,轮询这张票直到 working,再发请求。
|
|
1618
|
+
*
|
|
1619
|
+
* 和上面的兜底通道有一个本质区别:响应头已经发出去了,后面任何失败都**不能再
|
|
1620
|
+
* 换号、也不能回 HTTP 状态码**,只能以流内错误帧交代。所以只有上游明确回排队
|
|
1621
|
+
* 拒绝时才会走到这里 —— 那时换别的号去撞同一张票也没有意义。
|
|
1622
|
+
*/
|
|
1623
|
+
async function waitForQueueTurn(id) {
|
|
1624
|
+
const gate = queue;
|
|
1625
|
+
if (gate === void 0) return;
|
|
1626
|
+
const credential = await store.resolve(id);
|
|
1627
|
+
if (credential === void 0) return;
|
|
1628
|
+
const waitStartedAt = Date.now();
|
|
1629
|
+
const heartbeat = startHeartbeat(checked.model);
|
|
1630
|
+
try {
|
|
1631
|
+
const verdict = await gate.wait(credential, checked.chatId, checked.model, controller.signal, QUEUE_WAIT_LIMIT_MS);
|
|
1632
|
+
if (controller.signal.aborted || verdict.kind === "aborted") return;
|
|
1633
|
+
if (verdict.kind !== "working") {
|
|
1634
|
+
usage?.noteFailure(verdict.kind === "error" ? "queued" : verdict.kind, id);
|
|
1635
|
+
failStream(res, verdict.kind === "queued" ? `等了 ${Math.round(QUEUE_WAIT_LIMIT_MS / 6e4)} 分钟仍未轮到(第 ${verdict.position} 位,共 ${verdict.length} 条)。请稍后重试,或临时切换模型。` : verdict.message);
|
|
1636
|
+
return;
|
|
1637
|
+
}
|
|
1638
|
+
let acquired = pool.acquire(id);
|
|
1639
|
+
if (!acquired) acquired = await pool.waitForFreeSlot(1e4, controller.signal) && pool.acquire(id);
|
|
1640
|
+
if (!acquired) {
|
|
1641
|
+
failStream(res, "轮到排队后本地账号槽位仍被占用,请稍后重试。");
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
try {
|
|
1645
|
+
const opened = await openStream(credential, raw, contextWindow, controller.signal, Date.now() + 6e4);
|
|
1646
|
+
queueWaitedMs = opened.waitedMs;
|
|
1647
|
+
if (controller.signal.aborted) {
|
|
1648
|
+
if (opened.result.ok) await opened.result.stream.cancel().catch(() => {});
|
|
1649
|
+
return;
|
|
1650
|
+
}
|
|
1651
|
+
if (opened.result.ok) {
|
|
1652
|
+
pool.noteSuccess(id);
|
|
1653
|
+
await pipeToResponse(res, opened.result.stream, controller.signal, {
|
|
1654
|
+
accountId: id,
|
|
1655
|
+
model: opened.prepared.model,
|
|
1656
|
+
startedAt: requestStartedAt
|
|
1657
|
+
}, opened.head);
|
|
1658
|
+
return;
|
|
1659
|
+
}
|
|
1660
|
+
usage?.noteFailure(isQueueReject(opened.result) ? "queued" : opened.result.kind, id);
|
|
1661
|
+
const waitedSec = Math.round((Date.now() - waitStartedAt) / 1e3);
|
|
1662
|
+
const suffix = waitedSec >= 1 ? `(本地已排队 ${waitedSec} 秒)` : "";
|
|
1663
|
+
failStream(res, `${upstreamErrorMessage(opened.result.message, opened.result.status)}${suffix}`);
|
|
1664
|
+
} finally {
|
|
1665
|
+
pool.release(id);
|
|
1666
|
+
}
|
|
1667
|
+
} finally {
|
|
1668
|
+
heartbeat.stop();
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
/**
|
|
1672
|
+
* 等待期间的空帧:宿主只看「可解析的流事件」续空闲计时(SSE 注释不算),
|
|
1673
|
+
* 空 delta 不产生任何可见文字,但足以让连接活着。
|
|
1674
|
+
*/
|
|
1675
|
+
function startHeartbeat(model) {
|
|
1676
|
+
if (!res.headersSent) res.writeHead(200, {
|
|
1677
|
+
"Content-Type": "text/event-stream",
|
|
1678
|
+
"Cache-Control": "no-cache",
|
|
1679
|
+
"Connection": "keep-alive",
|
|
1680
|
+
"X-Accel-Buffering": "no"
|
|
1681
|
+
});
|
|
1682
|
+
const beat = () => {
|
|
1683
|
+
if (!res.writable || res.writableEnded) return;
|
|
1684
|
+
res.write(`data: ${JSON.stringify({
|
|
1685
|
+
id: "codearts-queue",
|
|
1686
|
+
object: "chat.completion.chunk",
|
|
1687
|
+
created: Math.floor(Date.now() / 1e3),
|
|
1688
|
+
model,
|
|
1689
|
+
choices: [{
|
|
1690
|
+
index: 0,
|
|
1691
|
+
delta: {},
|
|
1692
|
+
finish_reason: null
|
|
1693
|
+
}]
|
|
1694
|
+
})}\n\n`);
|
|
1695
|
+
};
|
|
1696
|
+
beat();
|
|
1697
|
+
const timer = setInterval(beat, QUEUE_HEARTBEAT_MS);
|
|
1698
|
+
timer.unref?.();
|
|
1699
|
+
return { stop: () => clearInterval(timer) };
|
|
1700
|
+
}
|
|
1701
|
+
/** 响应头已经发出之后的失败:只能作为流内错误帧交代,不能再改状态码。 */
|
|
1702
|
+
function failStream(response, message) {
|
|
1703
|
+
if (!response.writable || response.writableEnded) return;
|
|
1704
|
+
response.write(`data: ${JSON.stringify({
|
|
1705
|
+
choices: [{
|
|
1706
|
+
index: 0,
|
|
1707
|
+
delta: { content: "" },
|
|
1708
|
+
finish_reason: "stop"
|
|
1709
|
+
}],
|
|
1710
|
+
error: {
|
|
1711
|
+
code: "queued",
|
|
1712
|
+
message
|
|
1713
|
+
}
|
|
1714
|
+
})}\n\n`);
|
|
1715
|
+
response.end("data: [DONE]\n\n");
|
|
1716
|
+
}
|
|
1588
1717
|
}
|
|
1589
1718
|
/**
|
|
1590
1719
|
* 记下一帧里的上游流内错误。判据宽松(帧文本含 "error" 才解析),解析不出来就忽略 ——
|
|
@@ -1602,7 +1731,7 @@ function createCodeArtsShim(options) {
|
|
|
1602
1731
|
}
|
|
1603
1732
|
/** 把上游 SSE 按事件边界转发给 DSH,直到流结束或被中止。 */
|
|
1604
1733
|
async function pipeToResponse(res, stream, signal, attribution, head) {
|
|
1605
|
-
res.writeHead(200, {
|
|
1734
|
+
if (!res.headersSent) res.writeHead(200, {
|
|
1606
1735
|
"Content-Type": "text/event-stream",
|
|
1607
1736
|
"Cache-Control": "no-cache",
|
|
1608
1737
|
"Connection": "keep-alive",
|
|
@@ -1812,7 +1941,8 @@ const DEFAULT_DOCK_FLAGS = {
|
|
|
1812
1941
|
settingsEntry: true,
|
|
1813
1942
|
modelDetail: true,
|
|
1814
1943
|
autoClaim: false,
|
|
1815
|
-
keepAliveDaemon: false
|
|
1944
|
+
keepAliveDaemon: false,
|
|
1945
|
+
queueWait: false
|
|
1816
1946
|
};
|
|
1817
1947
|
/**
|
|
1818
1948
|
* 把逐账号的领取结果汇总成一条:HTTP 层只看 ok,卡片看 results 逐号展示。
|
|
@@ -2199,10 +2329,11 @@ function dockHandler(deps) {
|
|
|
2199
2329
|
"settingsEntry",
|
|
2200
2330
|
"modelDetail",
|
|
2201
2331
|
"autoClaim",
|
|
2202
|
-
"keepAliveDaemon"
|
|
2332
|
+
"keepAliveDaemon",
|
|
2333
|
+
"queueWait"
|
|
2203
2334
|
].filter((key) => body[key] !== void 0);
|
|
2204
2335
|
if (touched.length === 0 || touched.some((key) => typeof body[key] !== "boolean")) {
|
|
2205
|
-
json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"settingsEntry\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean}" });
|
|
2336
|
+
json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"settingsEntry\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean, \"queueWait\"?: boolean}" });
|
|
2206
2337
|
return;
|
|
2207
2338
|
}
|
|
2208
2339
|
if (!await deps.setDock(Object.fromEntries(touched.map((key) => [key, body[key]])))) {
|
|
@@ -3001,7 +3132,8 @@ const Config = z.object({
|
|
|
3001
3132
|
showSettingsEntry: z.boolean().default(true).description("Show a CodeArts entry in the left navigation of DSH Settings (default: shown)").volatile(),
|
|
3002
3133
|
showModelDetailDock: z.boolean().default(true).description("Show \"Model … · x ratio\" on the line under the chat input box (Provider CodeArts always shows)").volatile(),
|
|
3003
3134
|
autoClaim: z.boolean().default(false).description("Automatically claim the daily sign-in credits for every signed-in account").volatile(),
|
|
3004
|
-
keepAliveDaemon: z.boolean().default(false).description("Keep a detached background process that refreshes the OAuth credential while DSH is closed").volatile()
|
|
3135
|
+
keepAliveDaemon: z.boolean().default(false).description("Keep a detached background process that refreshes the OAuth credential while DSH is closed").volatile(),
|
|
3136
|
+
queueWaitUntilReady: z.boolean().default(false).description("When upstream rejects with \"queued\", keep the stream alive and wait up to 15 minutes for a turn instead of failing (issue #10)").volatile()
|
|
3005
3137
|
});
|
|
3006
3138
|
function settingsCompatNamespace(ctx) {
|
|
3007
3139
|
return resolveSettingsNamespaceCompat(ctx, ctx.get("settings"), CODEARTS_SETTINGS_NS);
|
|
@@ -3114,12 +3246,14 @@ function apply(ctx, rawConfig) {
|
|
|
3114
3246
|
if (model.id.toLowerCase() !== lower) return model;
|
|
3115
3247
|
const target = window ?? model.contextWindowDiscovered ?? model.contextWindow;
|
|
3116
3248
|
const { contextWindowDiscovered, ...rest } = model;
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
contextWindow: target
|
|
3120
|
-
} : {
|
|
3249
|
+
const known = window === null ? model.contextWindowKnown : true;
|
|
3250
|
+
const patched = {
|
|
3121
3251
|
...rest,
|
|
3122
3252
|
contextWindow: target,
|
|
3253
|
+
...known === true ? { contextWindowKnown: true } : {}
|
|
3254
|
+
};
|
|
3255
|
+
return contextWindowDiscovered === void 0 || contextWindowDiscovered === target ? patched : {
|
|
3256
|
+
...patched,
|
|
3123
3257
|
contextWindowDiscovered
|
|
3124
3258
|
};
|
|
3125
3259
|
}));
|
|
@@ -3132,7 +3266,8 @@ function apply(ctx, rawConfig) {
|
|
|
3132
3266
|
settingsEntry: current().showSettingsEntry !== false,
|
|
3133
3267
|
modelDetail: current().showModelDetailDock !== false,
|
|
3134
3268
|
autoClaim: current().autoClaim === true,
|
|
3135
|
-
keepAliveDaemon: current().keepAliveDaemon === true
|
|
3269
|
+
keepAliveDaemon: current().keepAliveDaemon === true,
|
|
3270
|
+
queueWait: current().queueWaitUntilReady === true
|
|
3136
3271
|
});
|
|
3137
3272
|
const setDock = async (patch) => {
|
|
3138
3273
|
const settings = ctx.get("settings");
|
|
@@ -3144,7 +3279,8 @@ function apply(ctx, rawConfig) {
|
|
|
3144
3279
|
...patch.settingsEntry === void 0 ? {} : { showSettingsEntry: patch.settingsEntry },
|
|
3145
3280
|
...patch.modelDetail === void 0 ? {} : { showModelDetailDock: patch.modelDetail },
|
|
3146
3281
|
...patch.autoClaim === void 0 ? {} : { autoClaim: patch.autoClaim },
|
|
3147
|
-
...patch.keepAliveDaemon === void 0 ? {} : { keepAliveDaemon: patch.keepAliveDaemon }
|
|
3282
|
+
...patch.keepAliveDaemon === void 0 ? {} : { keepAliveDaemon: patch.keepAliveDaemon },
|
|
3283
|
+
...patch.queueWait === void 0 ? {} : { queueWaitUntilReady: patch.queueWait }
|
|
3148
3284
|
});
|
|
3149
3285
|
return true;
|
|
3150
3286
|
};
|
|
@@ -3189,6 +3325,11 @@ function apply(ctx, rawConfig) {
|
|
|
3189
3325
|
...keeperLastError === void 0 ? {} : { error: keeperLastError },
|
|
3190
3326
|
logPath
|
|
3191
3327
|
};
|
|
3328
|
+
if (keeperHandoffRecent()) return {
|
|
3329
|
+
alive: false,
|
|
3330
|
+
error: "守护进程为更新安装让路,重启后会自动恢复",
|
|
3331
|
+
logPath
|
|
3332
|
+
};
|
|
3192
3333
|
try {
|
|
3193
3334
|
await setDock({ keepAliveDaemon: false });
|
|
3194
3335
|
} catch {}
|
|
@@ -3230,6 +3371,7 @@ function apply(ctx, rawConfig) {
|
|
|
3230
3371
|
keeperSpawnedAt = Date.now();
|
|
3231
3372
|
if (outcome.ok) {
|
|
3232
3373
|
keeperLastError = void 0;
|
|
3374
|
+
clearKeeperHandoff();
|
|
3233
3375
|
ctx.logger.debug(`dsh-codearts: credential keeper running (pid ${outcome.pid ?? "?"})`);
|
|
3234
3376
|
} else {
|
|
3235
3377
|
keeperLastError = outcome.reason ?? "spawn failed";
|
|
@@ -3252,6 +3394,7 @@ function apply(ctx, rawConfig) {
|
|
|
3252
3394
|
if (!keeperRunning() && Date.now() - keeperSpawnedAt >= KEEPER_START_GRACE_MS) {
|
|
3253
3395
|
keeperTimer = void 0;
|
|
3254
3396
|
keeperSpawnedAt = 0;
|
|
3397
|
+
if (keeperHandoffRecent()) return;
|
|
3255
3398
|
await setDock({ keepAliveDaemon: false }).catch(() => false);
|
|
3256
3399
|
return;
|
|
3257
3400
|
}
|
|
@@ -3547,7 +3690,8 @@ function apply(ctx, rawConfig) {
|
|
|
3547
3690
|
queue,
|
|
3548
3691
|
logger: ctx.logger,
|
|
3549
3692
|
debug: writeDebugLog,
|
|
3550
|
-
contextWindowOverrides: () => current().contextWindowOverrides
|
|
3693
|
+
contextWindowOverrides: () => current().contextWindowOverrides,
|
|
3694
|
+
waitInQueue: () => current().queueWaitUntilReady === true
|
|
3551
3695
|
});
|
|
3552
3696
|
usage.load().catch(() => {});
|
|
3553
3697
|
shim.ready.then(async () => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
//#region src/keeper.ts
|
|
@@ -18,9 +18,11 @@ import { fileURLToPath } from "node:url";
|
|
|
18
18
|
* ## 进程形态
|
|
19
19
|
*
|
|
20
20
|
* DSH Desktop 是 Electron,宿主 exe 可以直接当 Node 用:设置
|
|
21
|
-
* `ELECTRON_RUN_AS_NODE=1` 后启动它就是 node 24.21.0
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* `ELECTRON_RUN_AS_NODE=1` 后启动它就是 node 24.21.0(已实测)。但**优先用宿主自带的
|
|
22
|
+
* 真 node.exe**(`resources/runtime/<runtime>/dependencies/node/bin/node.exe`)—— 宿主 exe 的
|
|
23
|
+
* 进程名是 `DeepSeek Harness.exe`,会被更新安装器当成「应用还在跑」而挡住更新
|
|
24
|
+
* (见 `bundledNodeExecutable`)。两者都不依赖用户装没装 node,也不引入任何原生依赖。
|
|
25
|
+
* 启动后 `detached` + `unref` + `stdio:'ignore'`,DSH 退出它不跟着退出(同样已实测)。
|
|
24
26
|
*
|
|
25
27
|
* ## 谁有权续期(重要)
|
|
26
28
|
*
|
|
@@ -100,10 +102,42 @@ function keeperScriptPath() {
|
|
|
100
102
|
return fileURLToPath(new URL("./keeper-main.mjs", import.meta.url));
|
|
101
103
|
}
|
|
102
104
|
/**
|
|
105
|
+
* 宿主自带的 node(`resources/runtime/<runtime>/dependencies/node/bin/node.exe`)。
|
|
106
|
+
*
|
|
107
|
+
* 为什么不直接用 `process.execPath`:那是宿主 exe,keeper 的进程名就成了
|
|
108
|
+
* `DeepSeek Harness.exe`。DSH 的更新安装器会枚举同名进程判断「应用是否已关闭」,
|
|
109
|
+
* 看到 keeper 就认为应用还在跑 —— 更新在十秒左右中止,而且安装器不会把应用拉回来
|
|
110
|
+
* (2026-11-16 实测:装 0.2.2-rc.3 时两次都是被这个挡住的)。
|
|
111
|
+
*
|
|
112
|
+
* 运行时目录名会随版本变(`primary-runtime` / `dsh-primary-runtime`),所以按目录枚举,
|
|
113
|
+
* 不把某一版的名字写死。拿不到就返回 undefined,由调用方退回宿主 exe。
|
|
114
|
+
*/
|
|
115
|
+
function bundledNodeExecutable() {
|
|
116
|
+
const name = process.platform === "win32" ? "node.exe" : "node";
|
|
117
|
+
const roots = [];
|
|
118
|
+
const resources = process.resourcesPath;
|
|
119
|
+
if (typeof resources === "string" && resources !== "") roots.push(resources);
|
|
120
|
+
roots.push(join(dirname(process.execPath), "resources"));
|
|
121
|
+
for (const root of roots) {
|
|
122
|
+
const runtime = join(root, "runtime");
|
|
123
|
+
let runtimes;
|
|
124
|
+
try {
|
|
125
|
+
runtimes = readdirSync(runtime);
|
|
126
|
+
} catch {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
for (const runtimeName of runtimes) {
|
|
130
|
+
const candidate = join(runtime, runtimeName, "dependencies", "node", "bin", name);
|
|
131
|
+
if (existsSync(candidate)) return candidate;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
103
136
|
* 拿 `ELECTRON_RUN_AS_NODE` 这条路启动 node 所需的 exe。
|
|
104
137
|
*
|
|
105
138
|
* 优先级:宿主自己给的 `DSH_DESKTOP_NODE_EXECUTABLE`(Desktop 注入,最准)→
|
|
106
|
-
*
|
|
139
|
+
* 宿主自带的 node.exe(见 `bundledNodeExecutable`,进程名不会撞 DSH)→
|
|
140
|
+
* `process.execPath`(Electron 自己或普通 node 都适用)。
|
|
107
141
|
*/
|
|
108
142
|
function nodeLauncher() {
|
|
109
143
|
const desktop = process.env.DSH_DESKTOP_NODE_EXECUTABLE;
|
|
@@ -114,6 +148,11 @@ function nodeLauncher() {
|
|
|
114
148
|
ELECTRON_RUN_AS_NODE: "1"
|
|
115
149
|
}
|
|
116
150
|
};
|
|
151
|
+
const bundled = bundledNodeExecutable();
|
|
152
|
+
if (bundled !== void 0) return {
|
|
153
|
+
command: bundled,
|
|
154
|
+
env: { ...process.env }
|
|
155
|
+
};
|
|
117
156
|
return {
|
|
118
157
|
command: process.execPath,
|
|
119
158
|
env: {
|
|
@@ -123,6 +162,42 @@ function nodeLauncher() {
|
|
|
123
162
|
};
|
|
124
163
|
}
|
|
125
164
|
/**
|
|
165
|
+
* 这是 DSH 更新安装器在 `%TEMP%` 里建的插件目录吗。
|
|
166
|
+
*
|
|
167
|
+
* 安装器(NSIS)一启动就把自己签名的 `window-frame.dll` 解到 `%TEMP%\ns*.tmp\`。
|
|
168
|
+
* 用「目录名 + 那个 dll」两条一起判,用户装别的软件留下同名目录也不会误伤。
|
|
169
|
+
*/
|
|
170
|
+
function isDshInstallerTempDir(path) {
|
|
171
|
+
if (!/^ns[\w.-]{2,}\.tmp$/i.test(basename(path))) return false;
|
|
172
|
+
return existsSync(join(path, "window-frame.dll"));
|
|
173
|
+
}
|
|
174
|
+
/** 「让路」标记:keeper 为更新安装器主动退出时写,插件据此不把开关关掉。 */
|
|
175
|
+
function keeperHandoffPath(home) {
|
|
176
|
+
return join(home ?? dshHome(), ".codearts-keeper.handoff");
|
|
177
|
+
}
|
|
178
|
+
function writeKeeperHandoff(reason, home) {
|
|
179
|
+
try {
|
|
180
|
+
writeFileSync(keeperHandoffPath(home), JSON.stringify({
|
|
181
|
+
at: Date.now(),
|
|
182
|
+
reason
|
|
183
|
+
}), { mode: 384 });
|
|
184
|
+
} catch {}
|
|
185
|
+
}
|
|
186
|
+
/** 最近发生过一次「为更新让路」的退出吗(默认 15 分钟内)。 */
|
|
187
|
+
function keeperHandoffRecent(home, maxAgeMs = 9e5) {
|
|
188
|
+
try {
|
|
189
|
+
const parsed = JSON.parse(readFileSync(keeperHandoffPath(home), "utf8"));
|
|
190
|
+
return typeof parsed.at === "number" && Date.now() - parsed.at <= maxAgeMs;
|
|
191
|
+
} catch {
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
function clearKeeperHandoff(home) {
|
|
196
|
+
try {
|
|
197
|
+
if (existsSync(keeperHandoffPath(home))) unlinkSync(keeperHandoffPath(home));
|
|
198
|
+
} catch {}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
126
201
|
* 起一个守护进程。已经在跑就返回现有的那个(幂等,不重复起)。
|
|
127
202
|
*
|
|
128
203
|
* `detached` + `unref` + `stdio:'ignore'` 三件套缺一不可:少了任何一个,DSH 退出时
|
|
@@ -212,4 +287,4 @@ function stopRequested(home) {
|
|
|
212
287
|
return existsSync(join(home ?? dshHome(), ".codearts-keeper.stop"));
|
|
213
288
|
}
|
|
214
289
|
//#endregion
|
|
215
|
-
export {
|
|
290
|
+
export { clearKeeperState as a, keeperLogPath as c, keeperStats as d, spawnKeeper as f, writeKeeperState as g, writeKeeperHandoff as h, clearKeeperHandoff as i, keeperScriptPath as l, stopRequested as m, KEEPER_STALE_MS as n, isDshInstallerTempDir as o, stopKeeper as p, KEEPER_TICK_MS as r, keeperHandoffRecent as s, KEEPER_HEARTBEAT_MS as t, keeperStatePath as u };
|