dsh-codearts 1.3.0 → 1.4.0
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 +598 -559
- package/lib/{auth-CF9XHMX-.mjs → auth-Ch0vYSAo.mjs} +327 -48
- package/lib/bin.mjs +2 -2
- package/lib/client/index.d.cts +15 -0
- package/lib/client/index.js +454 -176
- package/lib/index.d.mts +71 -4
- package/lib/index.mjs +214 -80
- package/lib/keeper-main.mjs +20 -9
- package/lib/{version-CJTTrulR.mjs → version-BjBwEMks.mjs} +3 -3
- package/package.json +125 -125
- package/lib/{keeper-P4FkDUEd.mjs → keeper-MHeAp_eV.mjs} +1 -1
package/lib/index.d.mts
CHANGED
|
@@ -1041,6 +1041,10 @@ declare class CodeArtsCredentialStore {
|
|
|
1041
1041
|
private _path;
|
|
1042
1042
|
/** 正在进行的刷新。并发请求必须共用它,不能各刷一次。 */
|
|
1043
1043
|
private _inflight;
|
|
1044
|
+
/** 瞬时失败后的冷却:这之前不再拿 refresh_token 去撞上游。 */
|
|
1045
|
+
private _refreshBlockedUntil;
|
|
1046
|
+
/** 续期失败的落地日志(由宿主注入;测试里没有就是静默)。 */
|
|
1047
|
+
private readonly log?;
|
|
1044
1048
|
/**
|
|
1045
1049
|
* 凭证代际。重登/清除会推进它,让还在飞的刷新发现自己过期,
|
|
1046
1050
|
* 从而不把刷新结果写回去覆盖掉刚拿到的新凭证。
|
|
@@ -1048,7 +1052,7 @@ declare class CodeArtsCredentialStore {
|
|
|
1048
1052
|
private _gen;
|
|
1049
1053
|
/** 作废在飞的刷新;任何直接写凭证的路径都要先调它。 */
|
|
1050
1054
|
private invalidateInflight;
|
|
1051
|
-
constructor(path: string);
|
|
1055
|
+
constructor(path: string, log?: (message: string) => void);
|
|
1052
1056
|
setPath(path: string): void;
|
|
1053
1057
|
/** 给 shim 用:返回签名所需全套。 */
|
|
1054
1058
|
resolve(): Promise<ResolvedCredential | undefined>;
|
|
@@ -1066,7 +1070,8 @@ declare class CodeArtsCredentialStore {
|
|
|
1066
1070
|
* 返回当前(可能已刷新)凭证。
|
|
1067
1071
|
*/
|
|
1068
1072
|
ensureFresh(): Promise<CodeArtsCredential | undefined>;
|
|
1069
|
-
/**
|
|
1073
|
+
/** 真正去刷一次;失败按错误类别决定「重试 / 冷却 / 落 stale」。 */
|
|
1074
|
+
private runRefresh;
|
|
1070
1075
|
private refresh;
|
|
1071
1076
|
}
|
|
1072
1077
|
interface CodeArtsAccountSummary {
|
|
@@ -1095,7 +1100,11 @@ declare class CodeArtsAccountStore {
|
|
|
1095
1100
|
private readonly path;
|
|
1096
1101
|
/** 旧版单凭证文件;新文档不存在时把它收编成第一个账号。 */
|
|
1097
1102
|
private readonly legacyPath;
|
|
1098
|
-
|
|
1103
|
+
/** 续期失败的落地日志(由宿主注入;测试里没有就是静默)。 */
|
|
1104
|
+
private readonly log?;
|
|
1105
|
+
constructor(path: string, legacyPath?: string, options?: {
|
|
1106
|
+
log?: (message: string) => void;
|
|
1107
|
+
});
|
|
1099
1108
|
private loaded;
|
|
1100
1109
|
private load;
|
|
1101
1110
|
private adopt;
|
|
@@ -1158,6 +1167,21 @@ declare class CodeArtsAccountStore {
|
|
|
1158
1167
|
* (refresh_token 会轮换,白刷一次就多一次失败风险)。
|
|
1159
1168
|
*/
|
|
1160
1169
|
forceRefresh(id: string, seenToken?: string): Promise<CodeArtsCredential | undefined>;
|
|
1170
|
+
/**
|
|
1171
|
+
* 磁盘上的 refresh_token 和内存里不一样了 → 说明另一个写入方(肯家是守护进程)
|
|
1172
|
+
* 已经续过:用磁盘那份重建槽位,返回 true。
|
|
1173
|
+
*
|
|
1174
|
+
* 只在续期失败后调用,重建会让在飞的刷新结果作废(代际号),这正是我们要的。
|
|
1175
|
+
*/
|
|
1176
|
+
private reloadIfPeerAdvanced;
|
|
1177
|
+
/**
|
|
1178
|
+
* 把账号标成 stale。
|
|
1179
|
+
*
|
|
1180
|
+
* 必须先重读磁盘再写:内存里的 `_doc` 可能是几小时前的快照,直接落库会把另一个
|
|
1181
|
+
* 账号(或本账号)刚被守护进程轮换出来的 refresh_token 覆盖回旧的 —— 2026-11-13
|
|
1182
|
+
* 真踩过,代价是必须重新登录。
|
|
1183
|
+
*/
|
|
1184
|
+
private markStale;
|
|
1161
1185
|
/**
|
|
1162
1186
|
* 从磁盘重读账号文档,丢掉内存里的槽位缓存。
|
|
1163
1187
|
*
|
|
@@ -1179,7 +1203,10 @@ declare class CodeArtsAccountStore {
|
|
|
1179
1203
|
*
|
|
1180
1204
|
* 只刷「距过期不足 `REFRESH_SKEW_MS`」的那些,刚从上游拿到的号不会被白刷一次:
|
|
1181
1205
|
* `refresh_token` 是一次性的,多余的刷新只会多一份失败风险。
|
|
1182
|
-
*
|
|
1206
|
+
*
|
|
1207
|
+
* `stale` 的号会做一次**低成本复验**:1.3.0 及以前任何一次续期失败(含网络抖动)
|
|
1208
|
+
* 都会永久落 stale,那些被误判的账号不该逼用户重新登录。真失效的话一轮只多一个
|
|
1209
|
+
* 请求(20 分钟一次),代价可以忽略;复验成功即自动复活。
|
|
1183
1210
|
*/
|
|
1184
1211
|
keepAlive(): Promise<{
|
|
1185
1212
|
checked: number;
|
|
@@ -1221,6 +1248,8 @@ declare class CodeArtsAccountPool {
|
|
|
1221
1248
|
private readonly preferred;
|
|
1222
1249
|
private readonly maxConcurrent;
|
|
1223
1250
|
private readonly now;
|
|
1251
|
+
/** 等槽位的唤醒器:槽位释放 / 池里新增账号 / 账号复活时逐个唤醒。 */
|
|
1252
|
+
private readonly waiters;
|
|
1224
1253
|
constructor(ids: readonly string[], options?: PoolOptions);
|
|
1225
1254
|
/** 让池与账号文档对齐:新增的进来,删掉的出去。已有账号的运行时状态保留。 */
|
|
1226
1255
|
sync(ids: readonly string[]): void;
|
|
@@ -1232,6 +1261,8 @@ declare class CodeArtsAccountPool {
|
|
|
1232
1261
|
private available;
|
|
1233
1262
|
/** 设置暂停集合(账号 id)。与账号文档同步时调用。 */
|
|
1234
1263
|
setPaused(ids: readonly string[]): void;
|
|
1264
|
+
/** 当前被用户暂停的账号 id(报错文案要把「暂停」与「槽位满」分开说)。 */
|
|
1265
|
+
pausedIds(): string[];
|
|
1235
1266
|
/** 设置置顶集合(账号 id)。置顶只在「同时可用」时改变先后,不会绕过冷却/上限。 */
|
|
1236
1267
|
setPreferred(ids: readonly string[]): void;
|
|
1237
1268
|
/**
|
|
@@ -1245,6 +1276,24 @@ declare class CodeArtsAccountPool {
|
|
|
1245
1276
|
acquire(id: string): boolean;
|
|
1246
1277
|
/** 释放槽位;重复释放不会把计数压到负数。 */
|
|
1247
1278
|
release(id: string): void;
|
|
1279
|
+
private notifyWaiters;
|
|
1280
|
+
/** 现在是否有一个真正能接活的空槽位(禁用/暂停/冷却中的号不算)。 */
|
|
1281
|
+
hasFreeSlot(): boolean;
|
|
1282
|
+
/**
|
|
1283
|
+
* 有没有「健康、但本地槽位被占满」的号。
|
|
1284
|
+
*
|
|
1285
|
+
* 只有这一种情况值得等一会儿:禁用要重新登录、暂停是用户自己停的、冷却有明确
|
|
1286
|
+
* 截止时间 —— 等它们都不会在预算内自己好。
|
|
1287
|
+
*/
|
|
1288
|
+
hasBusyWaitable(): boolean;
|
|
1289
|
+
/**
|
|
1290
|
+
* 等一个本地槽位空出来,最多 `maxWaitMs`。
|
|
1291
|
+
*
|
|
1292
|
+
* 返回 true = 等到了;false = 超时、被中止,或者池里根本没有「等一会儿就会空」的号。
|
|
1293
|
+
* issue #8:本地槽位满以前是立刻回 429「没有可用账号」,并发场景下(一次派 5 个
|
|
1294
|
+
* subagent)必然误伤;现在与上游排队对齐 —— 先短时等待,等不到再报错。
|
|
1295
|
+
*/
|
|
1296
|
+
waitForFreeSlot(maxWaitMs: number, signal?: AbortSignal): Promise<boolean>;
|
|
1248
1297
|
/**
|
|
1249
1298
|
* 撞到上游并发上限。
|
|
1250
1299
|
*
|
|
@@ -1561,6 +1610,16 @@ interface CodeArtsShimOptions {
|
|
|
1561
1610
|
*/
|
|
1562
1611
|
queue?: CodeArtsQueueGate;
|
|
1563
1612
|
logger?: ShimLogger;
|
|
1613
|
+
/**
|
|
1614
|
+
* 调试日志(默认关闭)。
|
|
1615
|
+
*
|
|
1616
|
+
* 宿主对插件的 info/debug 没有出口,acquire/release 这类取证信息只能让宿主
|
|
1617
|
+
* 注入一个落盘函数(见 index.ts 的 DSH_CODEARTS_DEBUG)。issue #8 的「槽位
|
|
1618
|
+
* 疑似泄漏」没有这些日志就无法证实或排除。
|
|
1619
|
+
*/
|
|
1620
|
+
debug?: (message: string) => void;
|
|
1621
|
+
/** 本地槽位满时最多等多久(缺省 30 秒)。测试用它把等待压到毫秒级。 */
|
|
1622
|
+
localSlotWaitMs?: number;
|
|
1564
1623
|
}
|
|
1565
1624
|
declare function createCodeArtsShim(options: CodeArtsShimOptions): CodeArtsShim;
|
|
1566
1625
|
//#endregion
|
|
@@ -1764,6 +1823,14 @@ interface Config {
|
|
|
1764
1823
|
* 而「设置 → 插件」里本来就能看到同一张卡片,所以这一格交给用户自己决定要不要。
|
|
1765
1824
|
*/
|
|
1766
1825
|
showSidebarPanel?: boolean;
|
|
1826
|
+
/**
|
|
1827
|
+
* 是否在 DSH 设置左侧导航里加一个 CodeArts 入口(点开是整页版卡片)。
|
|
1828
|
+
*
|
|
1829
|
+
* 缺省 = **显示**。插件自带的配置页挂在「内置插件 → bundle 详情页」里,这条路径
|
|
1830
|
+
* 对第一次用的人基本等于找不到(issue #7)。设置导航本来就是按插件分组的,
|
|
1831
|
+
* 多一项不会挤占主界面,所以缺省开;不想要的人可以在卡片的「显示」页关掉。
|
|
1832
|
+
*/
|
|
1833
|
+
showSettingsEntry?: boolean;
|
|
1767
1834
|
/**
|
|
1768
1835
|
* 对话底部的「Model 模型 · x 倍率 · 排队」这几段是否显示。缺省 = 显示。
|
|
1769
1836
|
*
|
package/lib/index.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { a as codeartsAuthPath,
|
|
1
|
+
import { a as codeartsAuthPath, c as credentialFromOAuth, i as codeartsAccountsPath, m as startLogin, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-Ch0vYSAo.mjs";
|
|
2
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-
|
|
3
|
+
import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-BjBwEMks.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-
|
|
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
|
|
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 (
|
|
981
|
-
|
|
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",
|
|
@@ -1083,6 +1149,8 @@ function createCodeArtsShim(options) {
|
|
|
1083
1149
|
const logger = options.logger;
|
|
1084
1150
|
const usage = options.usage;
|
|
1085
1151
|
const queue = options.queue;
|
|
1152
|
+
const debug = options.debug;
|
|
1153
|
+
const localSlotWaitBudgetMs = options.localSlotWaitMs ?? 3e4;
|
|
1086
1154
|
const pool = options.pool ?? new CodeArtsAccountPool([]);
|
|
1087
1155
|
const SHARED_SECRET = randomBytes(32).toString("base64url");
|
|
1088
1156
|
function bearerOk(req) {
|
|
@@ -1334,91 +1402,117 @@ function createCodeArtsShim(options) {
|
|
|
1334
1402
|
let cappedAccount;
|
|
1335
1403
|
let tpmAccount;
|
|
1336
1404
|
let queueWaitedMs = 0;
|
|
1405
|
+
let localSlotWaitedMs = 0;
|
|
1337
1406
|
let lastKind;
|
|
1338
1407
|
let lastAccountId;
|
|
1339
1408
|
let lastStatus = 0;
|
|
1340
1409
|
let lastMessage = "";
|
|
1341
1410
|
const rotateDeadline = Date.now() + CAP_WAIT_LIMIT;
|
|
1342
1411
|
const attempts = Math.min(Math.max(ids.length, ROTATE_MIN_ATTEMPTS), ROTATE_MAX_ATTEMPTS);
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1412
|
+
/** 日志里区分并发请求;没开调试时不生成。 */
|
|
1413
|
+
const requestTag = debug === void 0 ? "" : randomBytes(3).toString("hex");
|
|
1414
|
+
/**
|
|
1415
|
+
* 两轮:第一轮按账号轮换;如果全被「本地槽位满」挡住,就等一个槽位空出来
|
|
1416
|
+
* 再跑第二轮。以前这里直接落到「没有可用账号」的 429,并发派发(一次 5 个
|
|
1417
|
+
* subagent)必然误伤(issue #8)。
|
|
1418
|
+
*/
|
|
1419
|
+
for (let round = 0; round < 2; round += 1) {
|
|
1420
|
+
tried.clear();
|
|
1421
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
1422
|
+
if (Date.now() + ATTEMPT_RESERVE_MS > rotateDeadline) break;
|
|
1423
|
+
const id = pool.pick(tried);
|
|
1424
|
+
if (id === void 0) break;
|
|
1425
|
+
tried.add(id);
|
|
1426
|
+
if (!pool.acquire(id)) {
|
|
1427
|
+
debug?.(`acquire miss req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
|
|
1353
1428
|
continue;
|
|
1354
1429
|
}
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
if (
|
|
1359
|
-
|
|
1360
|
-
|
|
1430
|
+
debug?.(`acquire ok req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
|
|
1431
|
+
try {
|
|
1432
|
+
const credential = await store.resolve(id);
|
|
1433
|
+
if (credential === void 0) {
|
|
1434
|
+
pool.disable(id, "no credential");
|
|
1435
|
+
continue;
|
|
1436
|
+
}
|
|
1437
|
+
if (queue !== void 0) {
|
|
1438
|
+
const gate = await queue.wait(credential, checked.chatId, checked.model, controller.signal);
|
|
1439
|
+
if (controller.signal.aborted) return;
|
|
1440
|
+
if (gate.kind === "queued") {
|
|
1441
|
+
usage?.noteFailure("queued", id);
|
|
1442
|
+
writeOpenAIError(res, 400, "queued", queuedMessage(checked.model, gate));
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1445
|
+
if (gate.kind === "queue_full" || gate.kind === "error") {
|
|
1446
|
+
usage?.noteFailure(gate.kind, id);
|
|
1447
|
+
writeOpenAIError(res, gate.kind === "queue_full" ? 429 : 502, gate.kind, gate.message);
|
|
1448
|
+
return;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
const opened = await openWithCeilingHeal(credential, raw, contextWindow, controller.signal);
|
|
1452
|
+
const { prepared, result } = opened;
|
|
1453
|
+
if (controller.signal.aborted) {
|
|
1454
|
+
if (result.ok) await result.stream.cancel().catch(() => {});
|
|
1361
1455
|
return;
|
|
1362
1456
|
}
|
|
1363
|
-
if (
|
|
1364
|
-
|
|
1365
|
-
|
|
1457
|
+
if (result.ok) {
|
|
1458
|
+
pool.noteSuccess(id);
|
|
1459
|
+
await pipeToResponse(res, result.stream, controller.signal, {
|
|
1460
|
+
accountId: id,
|
|
1461
|
+
model: prepared.model,
|
|
1462
|
+
startedAt: requestStartedAt
|
|
1463
|
+
}, opened.head);
|
|
1366
1464
|
return;
|
|
1367
1465
|
}
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
if (result
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
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;
|
|
1466
|
+
lastKind = result.kind;
|
|
1467
|
+
lastAccountId = id;
|
|
1468
|
+
lastStatus = result.status;
|
|
1469
|
+
lastMessage = result.message;
|
|
1470
|
+
if (isConcurrencyCap(result)) {
|
|
1471
|
+
pool.noteConcurrencyCap(id);
|
|
1472
|
+
cappedAccount = id;
|
|
1473
|
+
continue;
|
|
1474
|
+
}
|
|
1475
|
+
if (isTpmLimit(result)) {
|
|
1476
|
+
tpmAccount = id;
|
|
1477
|
+
break;
|
|
1478
|
+
}
|
|
1479
|
+
if (result.kind === "iam_stale") {
|
|
1480
|
+
if (!refreshed.has(id)) {
|
|
1481
|
+
refreshed.add(id);
|
|
1482
|
+
logger?.warn(`dsh-codearts: ${id} 的 IAM token 被判失效,强制续期后重试`);
|
|
1483
|
+
if (await store.forceRefresh(id, credential.token) !== void 0) {
|
|
1484
|
+
tried.delete(id);
|
|
1485
|
+
continue;
|
|
1486
|
+
}
|
|
1404
1487
|
}
|
|
1488
|
+
pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
|
|
1489
|
+
continue;
|
|
1405
1490
|
}
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
pool.
|
|
1491
|
+
if (result.kind === "session_dead") {
|
|
1492
|
+
pool.disable(id, result.message);
|
|
1493
|
+
continue;
|
|
1494
|
+
}
|
|
1495
|
+
if (result.kind === "server" || result.kind === "soft_rate") {
|
|
1496
|
+
pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
|
|
1497
|
+
break;
|
|
1498
|
+
}
|
|
1499
|
+
pool.noteError(id, 3, ERROR_COOLDOWN_MS, result.message);
|
|
1415
1500
|
break;
|
|
1501
|
+
} finally {
|
|
1502
|
+
pool.release(id);
|
|
1503
|
+
debug?.(`release req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
|
|
1416
1504
|
}
|
|
1417
|
-
pool.noteError(id, 3, ERROR_COOLDOWN_MS, result.message);
|
|
1418
|
-
break;
|
|
1419
|
-
} finally {
|
|
1420
|
-
pool.release(id);
|
|
1421
1505
|
}
|
|
1506
|
+
if (lastKind !== void 0 || controller.signal.aborted) break;
|
|
1507
|
+
if (!pool.hasBusyWaitable()) break;
|
|
1508
|
+
const waitBudget = Math.min(localSlotWaitBudgetMs, rotateDeadline - ATTEMPT_RESERVE_MS - Date.now());
|
|
1509
|
+
if (waitBudget <= 0) break;
|
|
1510
|
+
const waitingSince = Date.now();
|
|
1511
|
+
debug?.(`slot wait start req=${requestTag} budget=${waitBudget}ms pool=${pool.list().map((a) => `${a.id}:${a.activeConcurrent}/${a.maxConcurrent}`).join(",")}`);
|
|
1512
|
+
const got = await pool.waitForFreeSlot(waitBudget, controller.signal);
|
|
1513
|
+
localSlotWaitedMs += Date.now() - waitingSince;
|
|
1514
|
+
debug?.(`slot wait ${got ? "done" : "timeout"} req=${requestTag} waited=${Date.now() - waitingSince}ms`);
|
|
1515
|
+
if (!got) break;
|
|
1422
1516
|
}
|
|
1423
1517
|
if (controller.signal.aborted) return;
|
|
1424
1518
|
const queueAccount = cappedAccount ?? tpmAccount;
|
|
@@ -1453,13 +1547,16 @@ function createCodeArtsShim(options) {
|
|
|
1453
1547
|
}
|
|
1454
1548
|
}
|
|
1455
1549
|
if (lastKind === void 0) {
|
|
1456
|
-
const none = noAccountError(pool.list());
|
|
1550
|
+
const none = noAccountError(pool.list(), pool.pausedIds());
|
|
1457
1551
|
usage?.noteFailure(none.kind);
|
|
1458
1552
|
writeOpenAIError(res, none.status, none.kind, none.message);
|
|
1459
1553
|
return;
|
|
1460
1554
|
}
|
|
1461
1555
|
const explanation = upstreamErrorMessage(lastMessage, lastStatus);
|
|
1462
|
-
const
|
|
1556
|
+
const waits = [];
|
|
1557
|
+
if (queueWaitedMs >= 1e3) waits.push(`排队重试 ${Math.round(queueWaitedMs / 1e3)} 秒`);
|
|
1558
|
+
if (localSlotWaitedMs >= 1e3) waits.push(`等本地槽位 ${Math.round(localSlotWaitedMs / 1e3)} 秒`);
|
|
1559
|
+
const waited = waits.length > 0 ? `(本地已${waits.join("、")})` : "";
|
|
1463
1560
|
usage?.noteFailure(lastKind, lastAccountId);
|
|
1464
1561
|
writeOpenAIError(res, KIND_STATUS[lastKind], lastKind, `${explanation}${waited}`);
|
|
1465
1562
|
}
|
|
@@ -1675,6 +1772,7 @@ const DEFAULT_DOCK_FLAGS = {
|
|
|
1675
1772
|
credits: true,
|
|
1676
1773
|
queue: true,
|
|
1677
1774
|
sidebar: false,
|
|
1775
|
+
settingsEntry: true,
|
|
1678
1776
|
modelDetail: true,
|
|
1679
1777
|
autoClaim: false,
|
|
1680
1778
|
keepAliveDaemon: false
|
|
@@ -2061,12 +2159,13 @@ function dockHandler(deps) {
|
|
|
2061
2159
|
"credits",
|
|
2062
2160
|
"queue",
|
|
2063
2161
|
"sidebar",
|
|
2162
|
+
"settingsEntry",
|
|
2064
2163
|
"modelDetail",
|
|
2065
2164
|
"autoClaim",
|
|
2066
2165
|
"keepAliveDaemon"
|
|
2067
2166
|
].filter((key) => body[key] !== void 0);
|
|
2068
2167
|
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}" });
|
|
2168
|
+
json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"settingsEntry\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean}" });
|
|
2070
2169
|
return;
|
|
2071
2170
|
}
|
|
2072
2171
|
if (!await deps.setDock(Object.fromEntries(touched.map((key) => [key, body[key]])))) {
|
|
@@ -2805,6 +2904,7 @@ const Config = z.object({
|
|
|
2805
2904
|
showCreditDock: z.boolean().default(true).description("Show the remaining-credits line under the chat input box").volatile(),
|
|
2806
2905
|
showQueueDock: z.boolean().default(true).description("Show the upstream queue position under the chat input box").volatile(),
|
|
2807
2906
|
showSidebarPanel: z.boolean().default(false).description("Show a CodeArts icon in the DSH sidebar icon column, opening this page in the middle column").volatile(),
|
|
2907
|
+
showSettingsEntry: z.boolean().default(true).description("Show a CodeArts entry in the left navigation of DSH Settings (default: shown)").volatile(),
|
|
2808
2908
|
showModelDetailDock: z.boolean().default(true).description("Show \"Model … · x ratio\" on the line under the chat input box (Provider CodeArts always shows)").volatile(),
|
|
2809
2909
|
autoClaim: z.boolean().default(false).description("Automatically claim the daily sign-in credits for every signed-in account").volatile(),
|
|
2810
2910
|
keepAliveDaemon: z.boolean().default(false).description("Keep a detached background process that refreshes the OAuth credential while DSH is closed").volatile()
|
|
@@ -2815,7 +2915,23 @@ function settingsCompatNamespace(ctx) {
|
|
|
2815
2915
|
function apply(ctx, rawConfig) {
|
|
2816
2916
|
const config = unwrapConfig(rawConfig);
|
|
2817
2917
|
const accountsPath = codeartsAccountsPath();
|
|
2818
|
-
|
|
2918
|
+
/**
|
|
2919
|
+
* 续期失败日志。
|
|
2920
|
+
*
|
|
2921
|
+
* 宿主对插件的 `info`/`debug` 没有任何出口,`warn` 会变成系统通知 —— 一次网络抖动
|
|
2922
|
+
* 就弹一次窗口显然不行。所以失败原因写插件自己的文件(issue #8 里 03:22 那次续期
|
|
2923
|
+
* 失败就是因为零日志而永远无法取证)。1MB 截断重来,避免长期运行无限增长。
|
|
2924
|
+
*/
|
|
2925
|
+
const appendRefreshLog = (message) => {
|
|
2926
|
+
try {
|
|
2927
|
+
const path = codeartsRefreshLogPath();
|
|
2928
|
+
try {
|
|
2929
|
+
if (statSync(path).size > 1e6) writeFileSync(path, "");
|
|
2930
|
+
} catch {}
|
|
2931
|
+
appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
|
|
2932
|
+
} catch {}
|
|
2933
|
+
};
|
|
2934
|
+
const store = new CodeArtsAccountStore(accountsPath, void 0, { log: appendRefreshLog });
|
|
2819
2935
|
const pool = new CodeArtsAccountPool([]);
|
|
2820
2936
|
const catalog = new CodeArtsCatalog();
|
|
2821
2937
|
const usage = new CodeArtsUsageTracker({ path: codeartsUsagePath() });
|
|
@@ -2889,6 +3005,7 @@ function apply(ctx, rawConfig) {
|
|
|
2889
3005
|
credits: current().showCreditDock !== false,
|
|
2890
3006
|
queue: current().showQueueDock !== false,
|
|
2891
3007
|
sidebar: current().showSidebarPanel === true,
|
|
3008
|
+
settingsEntry: current().showSettingsEntry !== false,
|
|
2892
3009
|
modelDetail: current().showModelDetailDock !== false,
|
|
2893
3010
|
autoClaim: current().autoClaim === true,
|
|
2894
3011
|
keepAliveDaemon: current().keepAliveDaemon === true
|
|
@@ -2900,6 +3017,7 @@ function apply(ctx, rawConfig) {
|
|
|
2900
3017
|
...patch.credits === void 0 ? {} : { showCreditDock: patch.credits },
|
|
2901
3018
|
...patch.queue === void 0 ? {} : { showQueueDock: patch.queue },
|
|
2902
3019
|
...patch.sidebar === void 0 ? {} : { showSidebarPanel: patch.sidebar },
|
|
3020
|
+
...patch.settingsEntry === void 0 ? {} : { showSettingsEntry: patch.settingsEntry },
|
|
2903
3021
|
...patch.modelDetail === void 0 ? {} : { showModelDetailDock: patch.modelDetail },
|
|
2904
3022
|
...patch.autoClaim === void 0 ? {} : { autoClaim: patch.autoClaim },
|
|
2905
3023
|
...patch.keepAliveDaemon === void 0 ? {} : { keepAliveDaemon: patch.keepAliveDaemon }
|
|
@@ -3280,13 +3398,29 @@ function apply(ctx, rawConfig) {
|
|
|
3280
3398
|
if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
|
|
3281
3399
|
if (keeperTimer !== void 0) clearTimeout(keeperTimer);
|
|
3282
3400
|
});
|
|
3401
|
+
/**
|
|
3402
|
+
* 槽位取证日志:acquire/release 的时间点与在飞计数。
|
|
3403
|
+
*
|
|
3404
|
+
* 默认关闭(只有 `DSH_CODEARTS_DEBUG=1` 时写)。issue #8 里「只剩一个在飞请求,
|
|
3405
|
+
* 但所有 acquire 都失败」的怀疑,只能靠这份日志证实或排除。
|
|
3406
|
+
*/
|
|
3407
|
+
const writeDebugLog = process.env.DSH_CODEARTS_DEBUG === "1" ? (message) => {
|
|
3408
|
+
try {
|
|
3409
|
+
const path = codeartsDebugLogPath();
|
|
3410
|
+
try {
|
|
3411
|
+
if (statSync(path).size > 2e6) writeFileSync(path, "");
|
|
3412
|
+
} catch {}
|
|
3413
|
+
appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
|
|
3414
|
+
} catch {}
|
|
3415
|
+
} : void 0;
|
|
3283
3416
|
const shim = createCodeArtsShim({
|
|
3284
3417
|
store,
|
|
3285
3418
|
catalog,
|
|
3286
3419
|
pool,
|
|
3287
3420
|
usage,
|
|
3288
3421
|
queue,
|
|
3289
|
-
logger: ctx.logger
|
|
3422
|
+
logger: ctx.logger,
|
|
3423
|
+
debug: writeDebugLog
|
|
3290
3424
|
});
|
|
3291
3425
|
usage.load().catch(() => {});
|
|
3292
3426
|
shim.ready.then(async () => {
|
package/lib/keeper-main.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as keeperLogPath, f as stopRequested, i as clearKeeperState, l as readKeeperState, p as writeKeeperState, r as KEEPER_TICK_MS, s as keeperStatePath, t as KEEPER_HEARTBEAT_MS } from "./keeper-
|
|
1
|
+
import { d as OAuthTokenError, f as defaultLoginConfig, i as codeartsAccountsPath, l as readAccountDocument, p as refreshToken, u as writeJsonAtomic } from "./auth-Ch0vYSAo.mjs";
|
|
2
|
+
import { a as keeperLogPath, f as stopRequested, i as clearKeeperState, l as readKeeperState, p as writeKeeperState, r as KEEPER_TICK_MS, s as keeperStatePath, t as KEEPER_HEARTBEAT_MS } from "./keeper-MHeAp_eV.mjs";
|
|
3
3
|
import { appendFileSync, existsSync, unlinkSync } from "node:fs";
|
|
4
4
|
//#region src/keeper-main.ts
|
|
5
5
|
/**
|
|
@@ -115,13 +115,24 @@ async function tick(state) {
|
|
|
115
115
|
refreshed += 1;
|
|
116
116
|
log(`refreshed ${id.slice(0, 12)} → expires ${next.expiration}`);
|
|
117
117
|
} catch (error) {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
118
|
+
const used = error instanceof OAuthTokenError && error.refreshTokenUsed;
|
|
119
|
+
if (used) {
|
|
120
|
+
const fresh = await readAccountDocument(accountsPath);
|
|
121
|
+
const advanced = fresh !== void 0 && fresh.accounts[id]?.refreshToken !== void 0 && fresh.accounts[id]?.refreshToken !== cred.refreshToken;
|
|
122
|
+
log(`refresh SKIPPED ${id.slice(0, 12)} (refresh token already used${advanced ? ", newer token on disk" : ""})`);
|
|
123
|
+
if (advanced) continue;
|
|
124
|
+
}
|
|
125
|
+
const permanent = !used && error instanceof OAuthTokenError && error.permanent;
|
|
126
|
+
if (permanent) {
|
|
127
|
+
doc.accounts[id] = {
|
|
128
|
+
...cred,
|
|
129
|
+
stale: true
|
|
130
|
+
};
|
|
131
|
+
dirty = true;
|
|
132
|
+
needsLogin.push(id);
|
|
133
|
+
}
|
|
134
|
+
const reason = error instanceof OAuthTokenError ? `HTTP ${error.status} ${error.body.slice(0, 200)}` : error instanceof Error ? error.message : String(error);
|
|
135
|
+
log(`refresh FAILED ${id.slice(0, 12)} (${permanent ? "permanent, marked stale" : "transient, retry next pass"}): ${reason}`);
|
|
125
136
|
}
|
|
126
137
|
}
|
|
127
138
|
if (dirty) await writeJsonAtomic(accountsPath, doc);
|