dsh-go-codearts 0.0.0-stage → 1.0.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/cordis.patch.yml +6 -0
- package/lib/index.js +516 -0
- package/package.json +72 -4
- package/package.json.bak-pub +72 -0
- package/vendor/dsh-codearts/LICENSE +21 -0
- package/vendor/dsh-codearts/lib/auth-T5qnGSPp.mjs +1533 -0
- package/vendor/dsh-codearts/lib/bin.mjs +360 -0
- package/vendor/dsh-codearts/lib/estimate-BePoD-Np.mjs +113 -0
- package/vendor/dsh-codearts/lib/index.mjs +4387 -0
- package/vendor/dsh-codearts/lib/keeper-BWHQDFAh.mjs +334 -0
- package/vendor/dsh-codearts/lib/keeper-main.mjs +304 -0
- package/vendor/dsh-codearts/lib/models-CgKCibpk.mjs +377 -0
- package/vendor/dsh-codearts/lib/openai-completions-Cn5ZQvOO.mjs +19392 -0
- package/vendor/dsh-codearts/lib/rolldown-runtime-B4iAMlE-.mjs +35 -0
- package/vendor/dsh-codearts/lib/upstream-Cr5tUI75.mjs +2363 -0
- package/vendor/dsh-codearts/lib/version-Bienp51v.mjs +541 -0
- package/vendor/dsh-codearts/package.json +7 -0
- package/README.md +0 -3
|
@@ -0,0 +1,4387 @@
|
|
|
1
|
+
import { a as codeartsAuthPath, c as credentialFromOAuth, g as startLogin, i as codeartsAccountsPath, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-T5qnGSPp.mjs";
|
|
2
|
+
import { A as overrideValueFor, B as CodeArtsCatalog, C as isQueueableRate, D as learnedContextWindowFor, E as learnContextWindow, F as setMaxTokenOverride, G as filterEnabledModels, I as setMaxTokenOverrides, J as isBenefitModel, K as forgetModelUnavailable, L as signedGet, M as prepareChatBody, N as queueFrame, O as maxTokensCeilingFor, P as rateLimitFrame, Q as modelUnavailableReason, R as upstreamErrorMessage, S as isQueueRejectText, T as isWelfareClaimedStatus, U as clearBenefitBlocked, V as FALLBACK_CODEARTS_MODELS, W as creditRatioLabel, Y as markModelUnavailable, _ as isIamTokenError, a as claimDailyWelfare, b as isParamInvalidFrame, c as degradeTokenCeiling, d as fetchQueueStatus, et as withContextWindowOverride, f as fetchWelfareCampaigns, g as isCreditExhausted, h as isContextOverflowText, i as chatStream, j as pickDailyWelfareCampaign, k as modelUnavailableReasonText, l as fetchCallerIdentity, m as isConcurrencyCap, n as SNAP_HOST, o as clearQueueStatus, p as firstFrameError, q as isBenefitBlocked, r as canonicalModel, s as contextWindowOverrideFor, t as MAX_TOKENS_FLOOR, tt as withMaxTokensOverride, u as fetchModels, v as isModelNotAccessible, w as isTpmLimit, x as isQueueReject, y as isNotMultimodal } from "./upstream-Cr5tUI75.mjs";
|
|
3
|
+
import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-Bienp51v.mjs";
|
|
4
|
+
import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
|
|
5
|
+
import { c as keeperLogPath, f as keeperStats, i as clearKeeperHandoff, l as keeperNextPassAt, m as stopKeeper, n as KEEPER_STALE_MS, p as spawnKeeper, s as keeperHandoffRecent, u as keeperScriptPath } from "./keeper-BWHQDFAh.mjs";
|
|
6
|
+
import { appendFileSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import z from "@deepseek-ai/schemastery";
|
|
8
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
|
|
11
|
+
import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
|
|
12
|
+
import * as settingsModule from "@deepseek-ai/dsh-settings";
|
|
13
|
+
/**
|
|
14
|
+
* 撞到上游并发上限后,多久内优先不选这个账号。
|
|
15
|
+
*
|
|
16
|
+
* 这不是冷却:账号本身没坏,只是它的会话槽位暂时满了(约 52 秒才释放)。
|
|
17
|
+
* 所以只是一个「倾向」——池里还有别的账号就先换一个;全都这样时照样会选它,
|
|
18
|
+
* 因为排队等它总比直接失败强。
|
|
19
|
+
*
|
|
20
|
+
* 这里只是**默认值**:每个号的真实释放时长不一样(52 秒是实测均值,不是常数),
|
|
21
|
+
* 一旦量到过就不再用它 —— 见 `noteCapRelease` 与 `capHintFor`。以前固定 30 秒比
|
|
22
|
+
* 实测短 20 多秒,窗口一过这个号又变成优先候选,于是白打一次上游、再记一次 cap,
|
|
23
|
+
* 而每次 cap 又把窗口重置成同样的 30 秒,永远学不到真实时长。
|
|
24
|
+
*/
|
|
25
|
+
const CAPPED_HINT_MS = 3e4;
|
|
26
|
+
/** 实测样本的下界:比这还短说明量的不是槽位释放(比如立刻就成功了)。 */
|
|
27
|
+
const CAP_SAMPLE_MIN_MS = 5e3;
|
|
28
|
+
/**
|
|
29
|
+
* 实测样本的上界:比这还长说明样本不来自「同一请求内排队等槽位」。
|
|
30
|
+
* 脏样本(用户隔几分钟才再问一次)会把避让窗口拉到几分钟,卡片会长时间显示「避让中」,
|
|
31
|
+
* 比固定 30 秒更糟 —— 所以宁可丢掉。
|
|
32
|
+
*/
|
|
33
|
+
const CAP_SAMPLE_MAX_MS = 12e4;
|
|
34
|
+
/** 参与中位数的最近样本数。 */
|
|
35
|
+
const CAP_SAMPLE_KEEP = 5;
|
|
36
|
+
/** 睡到解冻时刻后再多醒一点,防止定时器抖动导致醒来时 `coolUntil` 还差几毫秒。 */
|
|
37
|
+
const COOLDOWN_WAKE_EPSILON_MS = 250;
|
|
38
|
+
/**
|
|
39
|
+
* 这个号的「优先避开」窗口:量到过就用实测中位数,没量过用默认提示。
|
|
40
|
+
*
|
|
41
|
+
* 取中位数而不是均值:一次被打断的请求可能让某个样本偏长,中位数不会被单点带跑。
|
|
42
|
+
*/
|
|
43
|
+
function capHintFor(account) {
|
|
44
|
+
const samples = account.capSamples;
|
|
45
|
+
if (samples.length === 0) return CAPPED_HINT_MS;
|
|
46
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
47
|
+
const mid = Math.floor(sorted.length / 2);
|
|
48
|
+
return sorted.length % 2 === 1 ? sorted[mid] ?? 3e4 : Math.round(((sorted[mid - 1] ?? 3e4) + (sorted[mid] ?? 3e4)) / 2);
|
|
49
|
+
}
|
|
50
|
+
var CodeArtsAccountPool = class {
|
|
51
|
+
accounts = /* @__PURE__ */ new Map();
|
|
52
|
+
/** 用户手动暂停的账号:运行时状态留着(卡片还看得见槽位),但不参与轮转。 */
|
|
53
|
+
paused = /* @__PURE__ */ new Set();
|
|
54
|
+
/** 用户置顶的账号:选号时排在最前面,不再按「最久未用」轮它。 */
|
|
55
|
+
preferred = /* @__PURE__ */ new Set();
|
|
56
|
+
maxConcurrent;
|
|
57
|
+
/**
|
|
58
|
+
* 按账号的上限覆盖(账号 id → 并发数,issue #16 后续)。
|
|
59
|
+
*
|
|
60
|
+
* 上游配额按账号算:一个号可能个人档(3 个会话)、另一个企业档(5 个)。
|
|
61
|
+
* 没有覆盖的号用 `maxConcurrent` 这个默认值。
|
|
62
|
+
*/
|
|
63
|
+
accountCaps = /* @__PURE__ */ new Map();
|
|
64
|
+
now;
|
|
65
|
+
/** 等槽位的唤醒器:槽位释放 / 池里新增账号 / 账号复活时逐个唤醒。 */
|
|
66
|
+
waiters = /* @__PURE__ */ new Set();
|
|
67
|
+
constructor(ids, options = {}) {
|
|
68
|
+
this.maxConcurrent = options.maxConcurrent ?? 2;
|
|
69
|
+
this.now = options.now ?? (() => Date.now());
|
|
70
|
+
this.sync(ids);
|
|
71
|
+
}
|
|
72
|
+
/** 让池与账号文档对齐:新增的进来,删掉的出去。已有账号的运行时状态保留。 */
|
|
73
|
+
sync(ids) {
|
|
74
|
+
const wanted = new Set(ids);
|
|
75
|
+
const before = this.accounts.size;
|
|
76
|
+
for (const id of [...this.accounts.keys()]) if (!wanted.has(id)) {
|
|
77
|
+
this.accounts.delete(id);
|
|
78
|
+
this.accountCaps.delete(id);
|
|
79
|
+
}
|
|
80
|
+
for (const id of ids) {
|
|
81
|
+
if (this.accounts.has(id)) continue;
|
|
82
|
+
this.accounts.set(id, {
|
|
83
|
+
id,
|
|
84
|
+
activeConcurrent: 0,
|
|
85
|
+
maxConcurrent: this.accountCaps.get(id) ?? this.maxConcurrent,
|
|
86
|
+
coolUntil: 0,
|
|
87
|
+
cappedUntil: 0,
|
|
88
|
+
lastCapAt: 0,
|
|
89
|
+
capSamples: [],
|
|
90
|
+
disabled: false,
|
|
91
|
+
lastUsed: 0,
|
|
92
|
+
errorCount: 0
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
if (this.accounts.size !== before) this.notifyWaiters();
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* 调整「没有单独设置」的号的默认上限(issue #16)。
|
|
99
|
+
*
|
|
100
|
+
* 直接改运行时对象而不重建池:冷却、避让窗口、槽位计数都是本进程里学出来的,
|
|
101
|
+
* 重建会把它们全丢掉。调大时要唤醒等槽位的请求,否则它们会睡到下一次释放。
|
|
102
|
+
* 单独设过上限的号不动。
|
|
103
|
+
*/
|
|
104
|
+
setMaxConcurrent(value) {
|
|
105
|
+
if (!Number.isFinite(value)) return;
|
|
106
|
+
const next = Math.max(1, Math.floor(value));
|
|
107
|
+
if (next === this.maxConcurrent) return;
|
|
108
|
+
this.maxConcurrent = next;
|
|
109
|
+
this.applyCaps();
|
|
110
|
+
this.notifyWaiters();
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 一次性替换「按账号覆盖」表(设置变更时从配置整表灌进来)。
|
|
114
|
+
*
|
|
115
|
+
* 表里没有的号退回默认上限;和 `setMaxConcurrent` 一样保持运行时状态不动。
|
|
116
|
+
*/
|
|
117
|
+
setAccountCaps(caps) {
|
|
118
|
+
const next = /* @__PURE__ */ new Map();
|
|
119
|
+
for (const [id, value] of Object.entries(caps)) {
|
|
120
|
+
const key = id.trim();
|
|
121
|
+
if (key === "" || !Number.isFinite(value)) continue;
|
|
122
|
+
next.set(key, Math.max(1, Math.floor(value)));
|
|
123
|
+
}
|
|
124
|
+
this.accountCaps = next;
|
|
125
|
+
this.applyCaps();
|
|
126
|
+
this.notifyWaiters();
|
|
127
|
+
}
|
|
128
|
+
/** 单个账号设/清上限(`null` = 回到默认)。卡片上每张账号卡各有一枚加减器。 */
|
|
129
|
+
setAccountCap(id, value) {
|
|
130
|
+
const key = id.trim();
|
|
131
|
+
if (key === "") return;
|
|
132
|
+
if (value === null) this.accountCaps.delete(key);
|
|
133
|
+
else if (Number.isFinite(value)) this.accountCaps.set(key, Math.max(1, Math.floor(value)));
|
|
134
|
+
else return;
|
|
135
|
+
this.applyCaps();
|
|
136
|
+
this.notifyWaiters();
|
|
137
|
+
}
|
|
138
|
+
/** 当前按账号覆盖表的副本(状态接口给卡片按号显示)。 */
|
|
139
|
+
accountCapOverrides() {
|
|
140
|
+
return Object.fromEntries(this.accountCaps);
|
|
141
|
+
}
|
|
142
|
+
applyCaps() {
|
|
143
|
+
for (const account of this.accounts.values()) account.maxConcurrent = this.accountCaps.get(account.id) ?? this.maxConcurrent;
|
|
144
|
+
}
|
|
145
|
+
list() {
|
|
146
|
+
return [...this.accounts.values()];
|
|
147
|
+
}
|
|
148
|
+
get(id) {
|
|
149
|
+
return this.accounts.get(id);
|
|
150
|
+
}
|
|
151
|
+
/** 账号本身可用(没被禁用、不在冷却中)。 */
|
|
152
|
+
healthy(id) {
|
|
153
|
+
const account = this.accounts.get(id);
|
|
154
|
+
if (account === void 0) return false;
|
|
155
|
+
return !account.disabled && this.now() >= account.coolUntil;
|
|
156
|
+
}
|
|
157
|
+
/** 现在就能接活的账号(健康 + 未暂停 + 本地还有空槽位),置顶的优先,其余按「最久未用」。 */
|
|
158
|
+
available(exclude) {
|
|
159
|
+
const now = this.now();
|
|
160
|
+
return this.list().filter((a) => !a.disabled && !this.paused.has(a.id) && now >= a.coolUntil && !exclude.has(a.id) && a.activeConcurrent < a.maxConcurrent).sort((a, b) => {
|
|
161
|
+
const pinned = Number(this.preferred.has(b.id)) - Number(this.preferred.has(a.id));
|
|
162
|
+
return pinned !== 0 ? pinned : a.lastUsed - b.lastUsed;
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** 设置暂停集合(账号 id)。与账号文档同步时调用。 */
|
|
166
|
+
setPaused(ids) {
|
|
167
|
+
this.paused.clear();
|
|
168
|
+
for (const id of ids) this.paused.add(id);
|
|
169
|
+
this.notifyWaiters();
|
|
170
|
+
}
|
|
171
|
+
/** 当前被用户暂停的账号 id(报错文案要把「暂停」与「槽位满」分开说)。 */
|
|
172
|
+
pausedIds() {
|
|
173
|
+
return [...this.paused];
|
|
174
|
+
}
|
|
175
|
+
/** 设置置顶集合(账号 id)。置顶只在「同时可用」时改变先后,不会绕过冷却/上限。 */
|
|
176
|
+
setPreferred(ids) {
|
|
177
|
+
this.preferred.clear();
|
|
178
|
+
for (const id of ids) this.preferred.add(id);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 选一个账号。
|
|
182
|
+
*
|
|
183
|
+
* 优先挑没人撞上限的(`cappedUntil` 已过的);如果全都撞了,就退回其中任意
|
|
184
|
+
* 一个 —— 排它的队总比直接失败强。都没得选(全禁用/全在冷却)时返回 undefined。
|
|
185
|
+
*/
|
|
186
|
+
pick(exclude = /* @__PURE__ */ new Set()) {
|
|
187
|
+
const candidates = this.available(exclude);
|
|
188
|
+
if (candidates.length === 0) return void 0;
|
|
189
|
+
const now = this.now();
|
|
190
|
+
const notCapped = candidates.filter((a) => now >= a.cappedUntil);
|
|
191
|
+
return (notCapped.length > 0 ? notCapped[0] : candidates[0]).id;
|
|
192
|
+
}
|
|
193
|
+
/** 占一个本地槽位。占用失败(已满/不存在)返回 false。 */
|
|
194
|
+
acquire(id) {
|
|
195
|
+
const account = this.accounts.get(id);
|
|
196
|
+
if (account === void 0) return false;
|
|
197
|
+
if (account.activeConcurrent >= account.maxConcurrent) return false;
|
|
198
|
+
account.activeConcurrent += 1;
|
|
199
|
+
account.lastUsed = this.now();
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
/** 释放槽位;重复释放不会把计数压到负数。 */
|
|
203
|
+
release(id) {
|
|
204
|
+
const account = this.accounts.get(id);
|
|
205
|
+
if (account === void 0) return;
|
|
206
|
+
if (account.activeConcurrent > 0) account.activeConcurrent -= 1;
|
|
207
|
+
this.notifyWaiters();
|
|
208
|
+
}
|
|
209
|
+
notifyWaiters() {
|
|
210
|
+
for (const waiter of [...this.waiters]) try {
|
|
211
|
+
waiter();
|
|
212
|
+
} catch {}
|
|
213
|
+
}
|
|
214
|
+
/** 现在是否有一个真正能接活的空槽位(禁用/暂停/冷却中的号不算)。 */
|
|
215
|
+
hasFreeSlot() {
|
|
216
|
+
const now = this.now();
|
|
217
|
+
return this.list().some((a) => !a.disabled && !this.paused.has(a.id) && now >= a.coolUntil && a.activeConcurrent < a.maxConcurrent);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* 有没有「健康、但本地槽位被占满」的号。
|
|
221
|
+
*
|
|
222
|
+
* 只有这一种情况值得等一会儿:禁用要重新登录、暂停是用户自己停的、冷却有明确
|
|
223
|
+
* 截止时间 —— 等它们都不会在预算内自己好。
|
|
224
|
+
*/
|
|
225
|
+
hasBusyWaitable() {
|
|
226
|
+
const now = this.now();
|
|
227
|
+
return this.list().some((a) => !a.disabled && !this.paused.has(a.id) && now >= a.coolUntil && a.activeConcurrent >= a.maxConcurrent);
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* 等一个本地槽位空出来,最多 `maxWaitMs`。
|
|
231
|
+
*
|
|
232
|
+
* 返回 true = 等到了;false = 超时、被中止,或者池里根本没有「等一会儿就会空」的号。
|
|
233
|
+
* issue #8:本地槽位满以前是立刻回 429「没有可用账号」,并发场景下(一次派 5 个
|
|
234
|
+
* subagent)必然误伤;现在与上游排队对齐 —— 先短时等待,等不到再报错。
|
|
235
|
+
*/
|
|
236
|
+
waitForFreeSlot(maxWaitMs, signal) {
|
|
237
|
+
if (this.hasFreeSlot()) return Promise.resolve(true);
|
|
238
|
+
if (!this.hasBusyWaitable() || maxWaitMs <= 0) return Promise.resolve(false);
|
|
239
|
+
if (signal?.aborted === true) return Promise.resolve(false);
|
|
240
|
+
return new Promise((resolve) => {
|
|
241
|
+
let settled = false;
|
|
242
|
+
const finish = (value) => {
|
|
243
|
+
if (settled) return;
|
|
244
|
+
settled = true;
|
|
245
|
+
this.waiters.delete(check);
|
|
246
|
+
clearTimeout(timer);
|
|
247
|
+
signal?.removeEventListener("abort", onAbort);
|
|
248
|
+
resolve(value);
|
|
249
|
+
};
|
|
250
|
+
const check = () => {
|
|
251
|
+
if (this.hasFreeSlot()) finish(true);
|
|
252
|
+
};
|
|
253
|
+
const onAbort = () => finish(false);
|
|
254
|
+
const timer = setTimeout(() => finish(false), maxWaitMs);
|
|
255
|
+
timer.unref?.();
|
|
256
|
+
this.waiters.add(check);
|
|
257
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* 最近一个冷却账号的解冻时刻(epoch ms);没有冷却中的号返回 undefined。
|
|
262
|
+
*
|
|
263
|
+
* 与「槽位满」不同:解冻时刻是池子自己记的倒计时,精确已知 —— 值得内联等到
|
|
264
|
+
* 那一刻再发,而不是立刻回 429 让宿主在冷却窗里盲退避(issue #22)。禁用/暂停
|
|
265
|
+
* 的号不会自己恢复,不参与。
|
|
266
|
+
*/
|
|
267
|
+
earliestCooldownEnd() {
|
|
268
|
+
const now = this.now();
|
|
269
|
+
let soonest;
|
|
270
|
+
for (const account of this.accounts.values()) {
|
|
271
|
+
if (account.disabled || this.paused.has(account.id) || account.coolUntil <= now) continue;
|
|
272
|
+
if (soonest === void 0 || account.coolUntil < soonest) soonest = account.coolUntil;
|
|
273
|
+
}
|
|
274
|
+
return soonest;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* 睡到最近一个冷却账号解冻,最多 `maxWaitMs`。
|
|
278
|
+
*
|
|
279
|
+
* 返回 true = 已经醒了(可能刚好到解冻时刻);false = 没有冷却中的号、预算不够
|
|
280
|
+
* 或等待被中止。调用方醒后要重新走一遍选号:解冻的号可能又发了新请求。
|
|
281
|
+
*/
|
|
282
|
+
waitForCooldownEnd(maxWaitMs, signal) {
|
|
283
|
+
const thawAt = this.earliestCooldownEnd();
|
|
284
|
+
if (thawAt === void 0 || maxWaitMs <= 0) return Promise.resolve(false);
|
|
285
|
+
if (signal?.aborted === true) return Promise.resolve(false);
|
|
286
|
+
const waitMs = Math.min(maxWaitMs, Math.max(0, thawAt - this.now()));
|
|
287
|
+
return new Promise((resolve) => {
|
|
288
|
+
let settled = false;
|
|
289
|
+
const finish = (value) => {
|
|
290
|
+
if (settled) return;
|
|
291
|
+
settled = true;
|
|
292
|
+
clearTimeout(timer);
|
|
293
|
+
signal?.removeEventListener("abort", onAbort);
|
|
294
|
+
resolve(value);
|
|
295
|
+
};
|
|
296
|
+
const onAbort = () => finish(false);
|
|
297
|
+
const timer = setTimeout(() => finish(true), waitMs + COOLDOWN_WAKE_EPSILON_MS);
|
|
298
|
+
timer.unref?.();
|
|
299
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* 撞到上游并发上限。
|
|
304
|
+
*
|
|
305
|
+
* **不冷却账号** —— 账号没坏,只是会话槽位暂时满了(约 52 秒释放)。冷却会
|
|
306
|
+
* 让它在一分钟内彻底不可用,反而把后续请求也一起误伤(Go 参考里也是这么
|
|
307
|
+
* 处理的)。这里只记一个「优先避开」的提示,好让并发的请求先去用别的账号。
|
|
308
|
+
*/
|
|
309
|
+
noteConcurrencyCap(id) {
|
|
310
|
+
const account = this.accounts.get(id);
|
|
311
|
+
if (account === void 0) return;
|
|
312
|
+
account.lastCapAt = this.now();
|
|
313
|
+
account.cappedUntil = this.now() + capHintFor(account);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* 撞过上限、又在**同一个请求里**排队等到成功 —— 这就是这个号槽位释放的实测时长。
|
|
317
|
+
*
|
|
318
|
+
* 只在兜底排队那条路上调用:主循环里普通成功不能当样本,那样量到的是「用户下一次
|
|
319
|
+
* 提问隔了多久」(常常是几分钟),窗口会被拉到几分钟,比固定 30 秒更糟。
|
|
320
|
+
*/
|
|
321
|
+
noteCapRelease(id) {
|
|
322
|
+
const account = this.accounts.get(id);
|
|
323
|
+
if (account === void 0) return;
|
|
324
|
+
const cappedAt = account.lastCapAt;
|
|
325
|
+
account.lastCapAt = 0;
|
|
326
|
+
if (cappedAt === 0) return;
|
|
327
|
+
const sample = this.now() - cappedAt;
|
|
328
|
+
if (sample < CAP_SAMPLE_MIN_MS || sample > CAP_SAMPLE_MAX_MS) return;
|
|
329
|
+
account.capSamples.push(sample);
|
|
330
|
+
if (account.capSamples.length > CAP_SAMPLE_KEEP) account.capSamples.shift();
|
|
331
|
+
}
|
|
332
|
+
/** 凭据失效等硬错误:直接停用,等用户重新登录。 */
|
|
333
|
+
disable(id, reason) {
|
|
334
|
+
const account = this.accounts.get(id);
|
|
335
|
+
if (account === void 0) return;
|
|
336
|
+
account.disabled = true;
|
|
337
|
+
account.lastError = reason;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* 用户重新登录(凭据已换新)后调用:把账号从禁用/冷却里捞出来。
|
|
341
|
+
*
|
|
342
|
+
* `sync()` 只对齐成员、特意保留运行时状态(account-pool 不读凭据文档),所以
|
|
343
|
+
* 「同一账号重新登录」不会自动清掉 disabled —— 以前只能靠重启(见 issue #1)。
|
|
344
|
+
* 登录成功的语义就是「这个号现在该能用了」,由登录路径显式调这里复位。
|
|
345
|
+
*/
|
|
346
|
+
revive(id) {
|
|
347
|
+
const account = this.accounts.get(id);
|
|
348
|
+
if (account === void 0) return;
|
|
349
|
+
account.disabled = false;
|
|
350
|
+
account.coolUntil = 0;
|
|
351
|
+
account.cappedUntil = 0;
|
|
352
|
+
account.lastCapAt = 0;
|
|
353
|
+
account.errorCount = 0;
|
|
354
|
+
account.lastError = void 0;
|
|
355
|
+
this.notifyWaiters();
|
|
356
|
+
}
|
|
357
|
+
/** 上游 5xx / 软限流:短时冷却。 */
|
|
358
|
+
cooldown(id, ms, reason) {
|
|
359
|
+
const account = this.accounts.get(id);
|
|
360
|
+
if (account === void 0) return;
|
|
361
|
+
account.coolUntil = this.now() + ms;
|
|
362
|
+
account.lastError = reason;
|
|
363
|
+
}
|
|
364
|
+
/** 累计错误;达到阈值就冷却。 */
|
|
365
|
+
noteError(id, threshold, cooldownMs, reason) {
|
|
366
|
+
const account = this.accounts.get(id);
|
|
367
|
+
if (account === void 0) return;
|
|
368
|
+
account.errorCount += 1;
|
|
369
|
+
account.lastError = reason;
|
|
370
|
+
if (threshold > 0 && account.errorCount >= threshold) account.coolUntil = this.now() + cooldownMs;
|
|
371
|
+
}
|
|
372
|
+
/** 一次成功:清掉错误计数与冷却。 */
|
|
373
|
+
noteSuccess(id) {
|
|
374
|
+
const account = this.accounts.get(id);
|
|
375
|
+
if (account === void 0) return;
|
|
376
|
+
account.errorCount = 0;
|
|
377
|
+
account.coolUntil = 0;
|
|
378
|
+
account.lastError = void 0;
|
|
379
|
+
account.cappedUntil = 0;
|
|
380
|
+
account.lastCapAt = 0;
|
|
381
|
+
}
|
|
382
|
+
/** 有没有任何账号可用(含被撞上限提示的)。 */
|
|
383
|
+
hasUsable() {
|
|
384
|
+
const now = this.now();
|
|
385
|
+
return this.list().some((a) => !a.disabled && now >= a.coolUntil);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
//#endregion
|
|
389
|
+
//#region src/queue.ts
|
|
390
|
+
/**
|
|
391
|
+
* 上游排队的「闸门」。
|
|
392
|
+
*
|
|
393
|
+
* 26.10.0 起上游有 `GET /api/v1/queue/status`,但它**不是只读查询**:GET 本身会把
|
|
394
|
+
* 这个 task 挂进队列、返回队尾位置,`DELETE` 才把它清掉(2026-10-21 实测)。真正
|
|
395
|
+
* 的 chat 请求并不看这个号 —— 拿着一张第 535 位的票去 POST,942ms 就开流了。
|
|
396
|
+
* 官方客户端的做法是:只对 `enable_queue` 的模型,先轮询排队接口,等状态变成
|
|
397
|
+
* `working` 才发聊天请求(见 vscode-codebot 的 `startQueuePolling`)。
|
|
398
|
+
*
|
|
399
|
+
* 这张票的定位是**提示,不是门禁**(issue #10):真正的 chat 请求并不校验它,
|
|
400
|
+
* 所以 `wait()` 只做一次短探(`maxWaitMs`,默认 5 秒),结果交给 shim ——
|
|
401
|
+
* 没轮到也照发请求,底部积分条在这几秒里显示「排队第 N 位」。以前等满 20 秒
|
|
402
|
+
* 就直接回 400,用户看到的失败其实是插件自己造出来的。
|
|
403
|
+
*
|
|
404
|
+
* 宿主也等不起:流空闲超时只有 90 秒(等待期间一个字节都发不出去,SSE 注释帧
|
|
405
|
+
* 也不算事件),而 flash 高峰期队尾有 500+ 号、要等二十几分钟。真正值得等的位置
|
|
406
|
+
* 在 POST 被上游明确拒绝之后(还没写任何字节,重发安全),由 shim 退避重试。
|
|
407
|
+
*
|
|
408
|
+
* 收尾(轮到/超时/取消/失败)都会 DELETE 清号,别把幽灵排队留在上游撑大队列。
|
|
409
|
+
*
|
|
410
|
+
* @module dsh-codearts/queue
|
|
411
|
+
*/
|
|
412
|
+
const CLEAR_TIMEOUT_MS = 5e3;
|
|
413
|
+
var CodeArtsQueueGate = class {
|
|
414
|
+
entries = /* @__PURE__ */ new Map();
|
|
415
|
+
controllers = /* @__PURE__ */ new Set();
|
|
416
|
+
intervalMs;
|
|
417
|
+
maxWaitMs;
|
|
418
|
+
maxErrors;
|
|
419
|
+
query;
|
|
420
|
+
clear;
|
|
421
|
+
now;
|
|
422
|
+
constructor(options = {}) {
|
|
423
|
+
this.intervalMs = options.intervalMs ?? 5e3;
|
|
424
|
+
this.maxWaitMs = options.maxWaitMs ?? 5e3;
|
|
425
|
+
this.maxErrors = options.maxErrors ?? 3;
|
|
426
|
+
this.query = options.fetchStatus ?? fetchQueueStatus;
|
|
427
|
+
this.clear = options.clearStatus ?? ((credential, chatId, model) => clearQueueStatus(credential, chatId, model, AbortSignal.timeout(CLEAR_TIMEOUT_MS)));
|
|
428
|
+
this.now = options.now ?? Date.now;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* 占号并**最多探 `maxWaitMs`**。调用方只拿结果做提示:`working` 表示正好轮到,
|
|
432
|
+
* 其余结果照发 chat 请求(这张票不拦请求,见模块注释)。
|
|
433
|
+
*/
|
|
434
|
+
async wait(credential, chatId, model, signal, budgetMs = this.maxWaitMs) {
|
|
435
|
+
if (chatId === "") return { kind: "working" };
|
|
436
|
+
if (signal?.aborted === true) return { kind: "aborted" };
|
|
437
|
+
const controller = new AbortController();
|
|
438
|
+
const onAbort = () => controller.abort();
|
|
439
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
440
|
+
this.controllers.add(controller);
|
|
441
|
+
const entry = {
|
|
442
|
+
id: chatId,
|
|
443
|
+
model,
|
|
444
|
+
position: 0,
|
|
445
|
+
length: 0,
|
|
446
|
+
status: "",
|
|
447
|
+
updatedAt: this.now()
|
|
448
|
+
};
|
|
449
|
+
this.entries.set(chatId, entry);
|
|
450
|
+
let errors = 0;
|
|
451
|
+
const deadlineAt = this.now() + budgetMs;
|
|
452
|
+
try {
|
|
453
|
+
for (;;) {
|
|
454
|
+
if (controller.signal.aborted) return { kind: "aborted" };
|
|
455
|
+
let status;
|
|
456
|
+
try {
|
|
457
|
+
status = await this.query(credential, chatId, model, controller.signal);
|
|
458
|
+
errors = 0;
|
|
459
|
+
} catch (error) {
|
|
460
|
+
if (controller.signal.aborted) return { kind: "aborted" };
|
|
461
|
+
errors += 1;
|
|
462
|
+
if (errors >= this.maxErrors) return {
|
|
463
|
+
kind: "error",
|
|
464
|
+
message: `查询上游排队状态连续失败 ${errors} 次:${errorText(error)}`
|
|
465
|
+
};
|
|
466
|
+
await this.pause(controller.signal);
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
entry.status = status.status;
|
|
470
|
+
entry.position = status.queuePosition;
|
|
471
|
+
entry.length = status.queueLength;
|
|
472
|
+
entry.message = status.message;
|
|
473
|
+
entry.updatedAt = this.now();
|
|
474
|
+
const verdict = verdictOf(status);
|
|
475
|
+
if (verdict !== void 0) return verdict;
|
|
476
|
+
if (this.now() >= deadlineAt) return {
|
|
477
|
+
kind: "queued",
|
|
478
|
+
position: status.queuePosition,
|
|
479
|
+
length: status.queueLength,
|
|
480
|
+
message: status.message
|
|
481
|
+
};
|
|
482
|
+
await this.pause(controller.signal, Math.min(this.intervalMs, deadlineAt - this.now()));
|
|
483
|
+
}
|
|
484
|
+
} finally {
|
|
485
|
+
this.controllers.delete(controller);
|
|
486
|
+
signal?.removeEventListener("abort", onAbort);
|
|
487
|
+
if (this.entries.get(chatId) === entry) this.entries.delete(chatId);
|
|
488
|
+
await this.clear(credential, chatId, model).catch(() => {});
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
/** 正在排队的条目(给底部条)。 */
|
|
492
|
+
snapshot() {
|
|
493
|
+
return [...this.entries.values()].filter((entry) => entry.position > 0 || entry.status !== "" && entry.status !== "working").map((entry) => ({
|
|
494
|
+
id: entry.id,
|
|
495
|
+
model: entry.model,
|
|
496
|
+
position: entry.position,
|
|
497
|
+
length: entry.length,
|
|
498
|
+
status: entry.status,
|
|
499
|
+
...entry.message === "" ? {} : { message: entry.message },
|
|
500
|
+
updatedAt: entry.updatedAt
|
|
501
|
+
}));
|
|
502
|
+
}
|
|
503
|
+
dispose() {
|
|
504
|
+
for (const controller of [...this.controllers]) controller.abort();
|
|
505
|
+
}
|
|
506
|
+
pause(signal, delay = this.intervalMs) {
|
|
507
|
+
return new Promise((resolve) => {
|
|
508
|
+
const timer = setTimeout(finish, Math.max(0, delay));
|
|
509
|
+
timer.unref?.();
|
|
510
|
+
function finish() {
|
|
511
|
+
clearTimeout(timer);
|
|
512
|
+
signal.removeEventListener("abort", finish);
|
|
513
|
+
resolve();
|
|
514
|
+
}
|
|
515
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
/**
|
|
520
|
+
* 这个状态还要不要继续等。
|
|
521
|
+
*
|
|
522
|
+
* `working` = 轮到;`queue_full` = 队列已满,上游建议换模型;其余(waiting 等)继续。
|
|
523
|
+
* 空状态且位置为 0 说明这个模型根本没排队(如 GLM),直接放行。
|
|
524
|
+
*/
|
|
525
|
+
function verdictOf(status) {
|
|
526
|
+
const text = status.status.trim().toLowerCase();
|
|
527
|
+
if (text === "working") return { kind: "working" };
|
|
528
|
+
if (text === "queue_full") return {
|
|
529
|
+
kind: "queue_full",
|
|
530
|
+
message: status.message
|
|
531
|
+
};
|
|
532
|
+
if (text === "" && status.queuePosition === 0 && status.queueLength === 0) return { kind: "working" };
|
|
533
|
+
}
|
|
534
|
+
function errorText(error) {
|
|
535
|
+
return error instanceof Error ? error.message : String(error);
|
|
536
|
+
}
|
|
537
|
+
//#endregion
|
|
538
|
+
//#region src/credits.ts
|
|
539
|
+
/**
|
|
540
|
+
* CodeArts 积分与额度。
|
|
541
|
+
*
|
|
542
|
+
* 老结论「CodeArts 没有额度接口」是**错的**。2026-10-10 从官方 CodeArts Agent
|
|
543
|
+
* 客户端(`<安装目录>/resources/app/extensions/vscode-codebot/out/extension.js`)
|
|
544
|
+
* 里挖出它自己的接口清单,并逐条实测通过:
|
|
545
|
+
*
|
|
546
|
+
* GET {SNAP_HOST}/snap-manager/v1/statistics/plugin
|
|
547
|
+
* 积分体系:套餐名/状态、总量、已用、剩余、即将过期、额度周期(重置日)
|
|
548
|
+
* GET https://opengw.developer.huaweicloud.com/api/v1/user/tokens/balance
|
|
549
|
+
* 日/月 token 额度与余额
|
|
550
|
+
*
|
|
551
|
+
* 鉴权必须带 AK/SK 签名(SDK-HMAC-SHA256)。官方客户端那里只写了 `x-auth-token`,
|
|
552
|
+
* 是因为它走 IDE 内部的请求通道;我们直连时只带 `x-auth-token` 会被 APIG 拒掉:
|
|
553
|
+
* `401 APIG.0301 decrypt token fail`(实测三种组合,只有签名那一路 200)。
|
|
554
|
+
*
|
|
555
|
+
* 卡片每次刷新都会问一次状态,所以这里带 TTL 缓存 + 单飞:命中缓存不打上游,
|
|
556
|
+
* 失败也缓存一小段,免得上游抽风时每次刷新都要等一次超时。
|
|
557
|
+
*
|
|
558
|
+
* @module dsh-codearts/credits
|
|
559
|
+
*/
|
|
560
|
+
/** 福利网关:token 余额接口在这里(与 benefit/claim、gateway/config 同一个 host)。 */
|
|
561
|
+
const BENEFIT_GATEWAY_HOST = "https://opengw.developer.huaweicloud.com";
|
|
562
|
+
const EP_STATISTICS_PLUGIN = "/snap-manager/v1/statistics/plugin";
|
|
563
|
+
const EP_TOKEN_BALANCE = "/api/v1/user/tokens/balance";
|
|
564
|
+
function asRecord(value) {
|
|
565
|
+
return typeof value === "object" && value !== null ? value : {};
|
|
566
|
+
}
|
|
567
|
+
function asArray(value) {
|
|
568
|
+
return Array.isArray(value) ? value : [];
|
|
569
|
+
}
|
|
570
|
+
function firstString(...values) {
|
|
571
|
+
for (const value of values) if (typeof value === "string" && value.trim() !== "") return value.trim();
|
|
572
|
+
return "";
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* 取一个非负数字。
|
|
576
|
+
*
|
|
577
|
+
* 上游用 `-1` 表示「这个指标不适用」(例如模型维度的 usage_token / model_quota_num),
|
|
578
|
+
* 所以负数一律当「没有」而不是当 0 —— 否则界面会把「不适用」显示成「已用 0」。
|
|
579
|
+
*/
|
|
580
|
+
function nonNegative(value) {
|
|
581
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
582
|
+
}
|
|
583
|
+
function numberOrZero(value) {
|
|
584
|
+
return nonNegative(value) ?? 0;
|
|
585
|
+
}
|
|
586
|
+
/** 按 name 找一条 metrics(上游的 metrics 是一个带 name 的数组)。 */
|
|
587
|
+
function metricNamed(raw, name) {
|
|
588
|
+
for (const item of asArray(raw)) {
|
|
589
|
+
const metric = asRecord(item);
|
|
590
|
+
if (firstString(metric.name) === name) return metric;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
function categoryOf(metric) {
|
|
594
|
+
if (metric === void 0) return void 0;
|
|
595
|
+
const total = nonNegative(metric.package_credit_amount);
|
|
596
|
+
const used = nonNegative(metric.package_credit_used);
|
|
597
|
+
const remain = nonNegative(metric.package_credit_remain);
|
|
598
|
+
if (total === void 0 && used === void 0 && remain === void 0) return void 0;
|
|
599
|
+
return {
|
|
600
|
+
total: numberOrZero(total),
|
|
601
|
+
used: numberOrZero(used),
|
|
602
|
+
remain: numberOrZero(remain),
|
|
603
|
+
expiring: numberOrZero(metric.package_credit_expiring_amount)
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
/** 套餐状态映射:与官方客户端 CreditPackageService.mapPackageStatus 一致。 */
|
|
607
|
+
function mapPlanStatus(raw) {
|
|
608
|
+
if (raw === "normal") return "active";
|
|
609
|
+
if (raw === "closed") return "expired";
|
|
610
|
+
if (raw === "freeze") return "frozen";
|
|
611
|
+
return "unknown";
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* 解析 `GET /snap-manager/v1/statistics/plugin` 的响应。
|
|
615
|
+
*
|
|
616
|
+
* 返回 undefined 表示这不是一份能用的积分文档(上游改了形状/账号没有积分体系)——
|
|
617
|
+
* 调用方据此报「积分不可用」,而不是显示一排 0 假装是真的。
|
|
618
|
+
*/
|
|
619
|
+
function parseCreditStatistics(raw) {
|
|
620
|
+
const body = asRecord(raw);
|
|
621
|
+
const metrics = body.metrics;
|
|
622
|
+
if (!Array.isArray(metrics)) return void 0;
|
|
623
|
+
const total = categoryOf(metricNamed(metrics, "usageTotalPackageCredit"));
|
|
624
|
+
if (total === void 0) return void 0;
|
|
625
|
+
const pkg = asRecord(body.package);
|
|
626
|
+
const planNameCn = firstString(pkg.package_name_cn);
|
|
627
|
+
const planNameEn = firstString(pkg.package_name_en);
|
|
628
|
+
const packageUrl = firstString(pkg.package_url);
|
|
629
|
+
const periodStart = firstString(body.start_date);
|
|
630
|
+
const periodEnd = firstString(body.end_date);
|
|
631
|
+
return {
|
|
632
|
+
planName: planNameCn !== "" ? planNameCn : planNameEn,
|
|
633
|
+
planNameEn,
|
|
634
|
+
specCode: firstString(pkg.spec_code),
|
|
635
|
+
planStatus: mapPlanStatus(firstString(pkg.status)),
|
|
636
|
+
isCreditPackage: pkg.is_credit_package === true,
|
|
637
|
+
...packageUrl === "" ? {} : { packageUrl },
|
|
638
|
+
...periodStart === "" ? {} : { periodStart },
|
|
639
|
+
...periodEnd === "" ? {} : { periodEnd },
|
|
640
|
+
total,
|
|
641
|
+
...pick("bonus", categoryOf(metricNamed(metrics, "usageBonusPackageCredit"))),
|
|
642
|
+
...pick("basic", categoryOf(metricNamed(metrics, "usageBasicPackageCredit"))),
|
|
643
|
+
...pick("onDemand", categoryOf(metricNamed(metrics, "usageOnDemandPackageCredit"))),
|
|
644
|
+
fetchedAt: Date.now()
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
function pick(key, value) {
|
|
648
|
+
return value === void 0 ? {} : { [key]: value };
|
|
649
|
+
}
|
|
650
|
+
/** 解析 `GET /api/v1/user/tokens/balance` 的响应(`result` 里是额度口径)。 */
|
|
651
|
+
function parseTokenBalance(raw) {
|
|
652
|
+
const result = asRecord(asRecord(raw).result);
|
|
653
|
+
const balance = nonNegative(result.total_balance);
|
|
654
|
+
const quota = nonNegative(result.total_quota);
|
|
655
|
+
if (balance === void 0 && quota === void 0) return void 0;
|
|
656
|
+
return {
|
|
657
|
+
dailyLimit: numberOrZero(result.daily_token_limit),
|
|
658
|
+
dailyUsed: numberOrZero(result.daily_tokens_used),
|
|
659
|
+
monthlyLimit: numberOrZero(result.monthly_token_limit),
|
|
660
|
+
monthlyUsed: numberOrZero(result.monthly_tokens_used),
|
|
661
|
+
balance: numberOrZero(balance),
|
|
662
|
+
quota: numberOrZero(quota)
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
function errorOf(action, result) {
|
|
666
|
+
return new Error(`${action} HTTP ${result.status} ${result.message}`.trim().slice(0, 300));
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* 拉一次积分与 token 额度。
|
|
670
|
+
*
|
|
671
|
+
* 积分是主口径:它失败就整体失败(卡片要能看见原因)。token 额度是附带的,
|
|
672
|
+
* 它失败只让 `tokens` 缺席 —— 别让一个次要接口把主数字一起拖没。
|
|
673
|
+
*/
|
|
674
|
+
async function fetchCredits(credential, signal) {
|
|
675
|
+
const [statistics, balance, welfare] = await Promise.all([
|
|
676
|
+
signedGet(`${SNAP_HOST}${EP_STATISTICS_PLUGIN}`, credential, void 0, signal),
|
|
677
|
+
signedGet(`${BENEFIT_GATEWAY_HOST}${EP_TOKEN_BALANCE}`, credential, void 0, signal).catch(() => ({
|
|
678
|
+
ok: false,
|
|
679
|
+
status: 0,
|
|
680
|
+
message: "request failed"
|
|
681
|
+
})),
|
|
682
|
+
fetchWelfareCampaigns(credential, signal).then((campaigns) => {
|
|
683
|
+
const daily = pickDailyWelfareCampaign(campaigns);
|
|
684
|
+
if (daily === void 0) return void 0;
|
|
685
|
+
return {
|
|
686
|
+
claimable: daily.claimable,
|
|
687
|
+
claimedToday: !daily.claimable && isWelfareClaimedStatus(daily.status),
|
|
688
|
+
amount: daily.amount
|
|
689
|
+
};
|
|
690
|
+
}).catch(() => void 0)
|
|
691
|
+
]);
|
|
692
|
+
if (!statistics.ok) throw errorOf("statistics", statistics);
|
|
693
|
+
const credits = parseCreditStatistics(safeJson(statistics.text));
|
|
694
|
+
if (credits === void 0) throw new Error("statistics response carries no credit metrics");
|
|
695
|
+
const tokens = balance.ok ? parseTokenBalance(safeJson(balance.text)) : void 0;
|
|
696
|
+
return {
|
|
697
|
+
credits,
|
|
698
|
+
...tokens === void 0 ? {} : { tokens },
|
|
699
|
+
...welfare === void 0 ? {} : { welfare }
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
function safeJson(text) {
|
|
703
|
+
try {
|
|
704
|
+
return JSON.parse(text);
|
|
705
|
+
} catch {
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* 积分缓存(TTL + 单飞)。
|
|
711
|
+
*
|
|
712
|
+
* 单飞很重要:卡片刷新、对话底部的轮询可能同时打进来,没有它就会并发问上游好几次;
|
|
713
|
+
* 而上游对同一账号的并发是有成本/风险的。
|
|
714
|
+
*/
|
|
715
|
+
var CodeArtsCreditCache = class {
|
|
716
|
+
/** 按账号分槽:多账号下每个号有自己的余额,不能共用一个快照。 */
|
|
717
|
+
states = /* @__PURE__ */ new Map();
|
|
718
|
+
inflights = /* @__PURE__ */ new Map();
|
|
719
|
+
ttlMs;
|
|
720
|
+
failureTtlMs;
|
|
721
|
+
load;
|
|
722
|
+
now;
|
|
723
|
+
constructor(options = {}) {
|
|
724
|
+
this.ttlMs = options.ttlMs ?? 6e4;
|
|
725
|
+
this.failureTtlMs = options.failureTtlMs ?? 15e3;
|
|
726
|
+
this.load = options.load ?? fetchCredits;
|
|
727
|
+
this.now = options.now ?? (() => Date.now());
|
|
728
|
+
}
|
|
729
|
+
/** 某账号的缓存内容(不触发请求),供只想读快照的场景使用。 */
|
|
730
|
+
peek(accountId) {
|
|
731
|
+
return this.states.get(accountId);
|
|
732
|
+
}
|
|
733
|
+
/** 丢掉缓存,下次 get 会重新拉(重新登录/添加账号后调用)。省略账号则清空全部。 */
|
|
734
|
+
invalidate(accountId) {
|
|
735
|
+
if (accountId === void 0) {
|
|
736
|
+
this.states.clear();
|
|
737
|
+
this.inflights.clear();
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
this.states.delete(accountId);
|
|
741
|
+
this.inflights.delete(accountId);
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* 取一次某账号的积分。命中缓存直接返回;否则合并成一次上游请求。
|
|
745
|
+
* **不抛异常**:失败以 `phase: 'error'` 返回,调用方(状态路由)照样能渲染。
|
|
746
|
+
*/
|
|
747
|
+
async get(accountId, credential, signal) {
|
|
748
|
+
const cached = this.states.get(accountId);
|
|
749
|
+
if (cached !== void 0) {
|
|
750
|
+
const ttl = cached.phase === "ok" ? this.ttlMs : this.failureTtlMs;
|
|
751
|
+
if (this.now() - cached.at < ttl) return cached;
|
|
752
|
+
}
|
|
753
|
+
const existing = this.inflights.get(accountId);
|
|
754
|
+
if (existing !== void 0) return existing;
|
|
755
|
+
const inflight = this.run(accountId, credential, signal).finally(() => {
|
|
756
|
+
this.inflights.delete(accountId);
|
|
757
|
+
});
|
|
758
|
+
this.inflights.set(accountId, inflight);
|
|
759
|
+
return inflight;
|
|
760
|
+
}
|
|
761
|
+
async run(accountId, credential, signal) {
|
|
762
|
+
try {
|
|
763
|
+
const state = {
|
|
764
|
+
phase: "ok",
|
|
765
|
+
value: await this.load(credential, signal),
|
|
766
|
+
at: this.now()
|
|
767
|
+
};
|
|
768
|
+
this.states.set(accountId, state);
|
|
769
|
+
return state;
|
|
770
|
+
} catch (error) {
|
|
771
|
+
const state = {
|
|
772
|
+
phase: "error",
|
|
773
|
+
message: error instanceof Error ? error.message : String(error),
|
|
774
|
+
at: this.now()
|
|
775
|
+
};
|
|
776
|
+
this.states.set(accountId, state);
|
|
777
|
+
return state;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
//#endregion
|
|
782
|
+
//#region node_modules/.pnpm/@earendil-works+pi-ai@1.3.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+signature-v4@5.7.4_ws@8.22.0_zod@4.6.5/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
|
|
783
|
+
const openAICompletionsApi = () => lazyApi(() => import("./openai-completions-Cn5ZQvOO.mjs"));
|
|
784
|
+
//#endregion
|
|
785
|
+
//#region src/adapter.ts
|
|
786
|
+
/**
|
|
787
|
+
* The `codearts` pi-ai provider.
|
|
788
|
+
*
|
|
789
|
+
* One loopback-backed adapter registered into the Harness LLM seam, assembled
|
|
790
|
+
* from the same public `dsh-llm-pi-ai` extension points dsh-codebuddy-cli uses.
|
|
791
|
+
* The shim does the CodeArts wire translation; this file only describes the
|
|
792
|
+
* models and points pi-ai at the shim's OpenAI-compatible endpoint.
|
|
793
|
+
*
|
|
794
|
+
* MVP simplifications vs dsh-codebuddy-cli:
|
|
795
|
+
* - only the default-slot credit multiplier goes into the model name (`(x0.18)`);
|
|
796
|
+
* per-request cost is not modelled (subscription quota, cost reported as zero)
|
|
797
|
+
* - reasoning levels are surfaced only where upstream's thinking-variants names
|
|
798
|
+
* them (`GLM-5.2` → high/max); everything else stays a plain chat model
|
|
799
|
+
*
|
|
800
|
+
* @module dsh-codearts/adapter
|
|
801
|
+
*/
|
|
802
|
+
/** Provider route this bundle owns. Keep in sync with cordis.patch.yml. */
|
|
803
|
+
const CODEARTS_PROVIDER = "codearts";
|
|
804
|
+
/**
|
|
805
|
+
* Provider idle ceiling while one stream read is outstanding.
|
|
806
|
+
*
|
|
807
|
+
* 90s 而不是常见的 300s:华为免费推理后端实测会流中途停摆(吐几个 token 后
|
|
808
|
+
* 长时间静默),300s 意味着用户要在"等待"里干等 5 分钟才进入自动重试。
|
|
809
|
+
* 90s 足够容忍首 token 冷启动与推理间隙,又能让 DSH 的重试策略(TIMEOUT
|
|
810
|
+
* 可重试)更快接管。
|
|
811
|
+
*/
|
|
812
|
+
const CODEARTS_STREAM_IDLE_TIMEOUT_MS = 9e4;
|
|
813
|
+
const DEFAULT_CODEARTS_INITIAL_DELAY_MS = 500;
|
|
814
|
+
const DEFAULT_CODEARTS_MAX_DELAY_MS = 1e4;
|
|
815
|
+
/**
|
|
816
|
+
* 重试码 = 宿主默认五项 + MALFORMED_RESPONSE。
|
|
817
|
+
*
|
|
818
|
+
* 模型偶尔把 tool_call 参数写成非法 JSON(未转义引号、流内 JSON 损坏),
|
|
819
|
+
* pi-ai 在**派发工具之前**就判整轮失败 —— 用户看到的是一轮报错、选项全无。
|
|
820
|
+
* 重发一次让模型重新生成,多数自愈。宿主的默认集合不含这个码,而
|
|
821
|
+
* `retryableCodes` 是替换语义(不是并入),所以五项默认值必须显式列全。
|
|
822
|
+
*/
|
|
823
|
+
const RETRYABLE_CODES = [
|
|
824
|
+
"EMPTY_RESPONSE",
|
|
825
|
+
"RATE_LIMIT",
|
|
826
|
+
"SERVER",
|
|
827
|
+
"TIMEOUT",
|
|
828
|
+
"TRANSPORT",
|
|
829
|
+
"MALFORMED_RESPONSE"
|
|
830
|
+
];
|
|
831
|
+
/** 只认有限正整数;非法值忽略而不是抛错(值来自用户写的配置文件)。 */
|
|
832
|
+
function positiveInt(value) {
|
|
833
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
|
|
834
|
+
}
|
|
835
|
+
/** 把插件配置解析成宿主快照用的重试策略;缺省值按上面注释对齐冷却窗。 */
|
|
836
|
+
function resolveCodeArtsRetryPolicy(config) {
|
|
837
|
+
const resolved = {
|
|
838
|
+
mode: "normal",
|
|
839
|
+
maxRetries: positiveInt(config?.maxRetries) ?? 8,
|
|
840
|
+
retryableCodes: [...RETRYABLE_CODES],
|
|
841
|
+
backoff: {
|
|
842
|
+
initialDelayMs: positiveInt(config?.initialDelayMs) ?? DEFAULT_CODEARTS_INITIAL_DELAY_MS,
|
|
843
|
+
maxDelayMs: positiveInt(config?.maxDelayMs) ?? DEFAULT_CODEARTS_MAX_DELAY_MS
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
const policy = resolveRetryPolicy(resolved, "dsh-codearts retryPolicy");
|
|
847
|
+
if (policy.mode !== "normal") throw new Error("dsh-codearts retry policy must be normal");
|
|
848
|
+
return policy;
|
|
849
|
+
}
|
|
850
|
+
/** No per-token pricing is knowable for a subscription quota; report zero. */
|
|
851
|
+
const NO_COST = {
|
|
852
|
+
input: 0,
|
|
853
|
+
output: 0,
|
|
854
|
+
cacheRead: 0,
|
|
855
|
+
cacheWrite: 0
|
|
856
|
+
};
|
|
857
|
+
/**
|
|
858
|
+
* 6 MiB 而不是 20 MiB:上游网关对**整个请求体**约 10 MB 就拒(issue #18 实测
|
|
859
|
+
* 9.71 MB 过、10.41 MB 拒,且纯文本 1 MB 能过 ⇒ 是字节而非 token)。20 MiB 的
|
|
860
|
+
* 预算会让图片总量 10 MB 左右的请求直接发给上游,撞 InferHub.001001005.400,
|
|
861
|
+
* 再被误判成上下文超限。压到 6 MiB 后,宿主会把最老的图片换成占位文本
|
|
862
|
+
* (`read_image` 按需重读),给文本与工具定义留出约 4 MB 余量。
|
|
863
|
+
*/
|
|
864
|
+
const REQUEST_IMAGE_BUDGETS = {
|
|
865
|
+
maxRequestImageBytes: 6291456,
|
|
866
|
+
requestImagePixelBudget: 4194304,
|
|
867
|
+
/**
|
|
868
|
+
* 单图上限。这个字段在宿主里有两个拼写:0.2.2 及以前读 `requestImageMaxBytes`,
|
|
869
|
+
* 0.2.3 起 resolved profile 改叫 `maxImageBytes`(配置里的旧名由 resolveProfiles
|
|
870
|
+
* 映射过去)。本插件是手搓 profile、不走 resolveProfiles,两处都得写,各自忽略
|
|
871
|
+
* 不认识的那一个。
|
|
872
|
+
*/
|
|
873
|
+
requestImageMaxBytes: 1048576,
|
|
874
|
+
maxImageBytes: 1048576,
|
|
875
|
+
/**
|
|
876
|
+
* 0.2.3 起宿主要求的字节预算除数(issue #21):
|
|
877
|
+
* allocated = floor(maxRequestImageBytes / requestImageBudgetCount / 4) * 3
|
|
878
|
+
* cap = min(allocated, maxImageBytes)
|
|
879
|
+
* 漏掉它时分母是 undefined ⇒ NaN,`NaN < 1` 为 false 绕过宿主自检,带图请求
|
|
880
|
+
* 必然在附件层抛 INVALID_ATTACHMENT_REF。
|
|
881
|
+
*
|
|
882
|
+
* 取 4 而不是宿主默认的 20:allocated 只是 min() 的候选,除数必须让商仍盖过
|
|
883
|
+
* 1 MiB 单图上限,否则没人选的更小数字会悄悄顶替单图上限(6 MiB 时
|
|
884
|
+
* 20 → 235,929 字节,4 → 1,179,648)。5 已差一点(943,716),所以是 4。
|
|
885
|
+
*/
|
|
886
|
+
requestImageBudgetCount: 4,
|
|
887
|
+
/**
|
|
888
|
+
* 0.2.2-rc.1 起 resolved profile 的必填项(宿主默认 50 / 10)。
|
|
889
|
+
* 不写等于「数量不设限」,在带图长会话里会先撞上游请求体上限才轮到宿主 offload。
|
|
890
|
+
*/
|
|
891
|
+
maxRequestImages: 50,
|
|
892
|
+
imageOffloadCountQuantum: 10
|
|
893
|
+
};
|
|
894
|
+
/** Inert pi-ai auth plane: the codearts route authenticates only via the shim secret. */
|
|
895
|
+
const INERT_AUTH = {
|
|
896
|
+
credentials: {
|
|
897
|
+
async read() {},
|
|
898
|
+
async list() {
|
|
899
|
+
return [];
|
|
900
|
+
},
|
|
901
|
+
async modify() {
|
|
902
|
+
throw new Error("dsh-codearts: the codearts route has no pi-ai credential lifecycle");
|
|
903
|
+
},
|
|
904
|
+
async delete() {}
|
|
905
|
+
},
|
|
906
|
+
authContext: {
|
|
907
|
+
async env() {},
|
|
908
|
+
async fileExists() {
|
|
909
|
+
return false;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
/** pi-ai's selectable levels, in escalation order. */
|
|
914
|
+
const REASONING_LEVELS = [
|
|
915
|
+
"off",
|
|
916
|
+
"minimal",
|
|
917
|
+
"low",
|
|
918
|
+
"medium",
|
|
919
|
+
"high",
|
|
920
|
+
"xhigh",
|
|
921
|
+
"max"
|
|
922
|
+
];
|
|
923
|
+
/**
|
|
924
|
+
* Turn upstream's thinking strengths into pi-ai reasoning metadata.
|
|
925
|
+
*
|
|
926
|
+
* Every level upstream does not declare is pinned to `null`: pi-ai treats a
|
|
927
|
+
* missing entry as supported, so leaving them out would offer Off/Minimal/Low/
|
|
928
|
+
* Medium for a model that only knows high/max. `off` is pinned as well — the
|
|
929
|
+
* gateway's default is already high, and claiming Off would send no effort
|
|
930
|
+
* field and still think.
|
|
931
|
+
*/
|
|
932
|
+
function thinkingFields(strengths) {
|
|
933
|
+
const offered = new Set(strengths ?? []);
|
|
934
|
+
if (!REASONING_LEVELS.some((level) => level !== "off" && offered.has(level))) return { reasoning: false };
|
|
935
|
+
const map = {};
|
|
936
|
+
for (const level of REASONING_LEVELS) map[level] = offered.has(level) ? level : null;
|
|
937
|
+
return {
|
|
938
|
+
reasoning: true,
|
|
939
|
+
thinkingLevelMap: map
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
/** Build one pi-ai model descriptor pointing at the loopback shim. */
|
|
943
|
+
function toPiModel(info, baseUrl) {
|
|
944
|
+
const thinking = thinkingFields(info.thinking?.strengths);
|
|
945
|
+
return {
|
|
946
|
+
id: info.id,
|
|
947
|
+
name: info.name,
|
|
948
|
+
api: "openai-completions",
|
|
949
|
+
provider: CODEARTS_PROVIDER,
|
|
950
|
+
baseUrl,
|
|
951
|
+
input: info.supportsImages === true ? ["text", "image"] : ["text"],
|
|
952
|
+
reasoning: thinking.reasoning,
|
|
953
|
+
...thinking.thinkingLevelMap === void 0 ? {} : { thinkingLevelMap: thinking.thinkingLevelMap },
|
|
954
|
+
cost: NO_COST,
|
|
955
|
+
contextWindow: info.contextWindow,
|
|
956
|
+
maxTokens: info.maxTokens
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
function createCodeArtsAdapter(options) {
|
|
960
|
+
const { shim, catalog, enabledModels, resolveAttachments } = options;
|
|
961
|
+
const buildModels = () => {
|
|
962
|
+
const baseUrl = `${shim.baseUrl()}/v1`;
|
|
963
|
+
return catalog.current().map((info) => toPiModel(info, baseUrl));
|
|
964
|
+
};
|
|
965
|
+
const provider = {
|
|
966
|
+
...createProvider({
|
|
967
|
+
id: CODEARTS_PROVIDER,
|
|
968
|
+
name: "CodeArts",
|
|
969
|
+
auth: { apiKey: {
|
|
970
|
+
name: "CodeArts token",
|
|
971
|
+
async resolve({ credential }) {
|
|
972
|
+
const apiKey = credential?.key;
|
|
973
|
+
return apiKey === void 0 || apiKey.length === 0 ? void 0 : {
|
|
974
|
+
auth: { apiKey },
|
|
975
|
+
source: "CodeArts"
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
} },
|
|
979
|
+
models: buildModels(),
|
|
980
|
+
api: openAICompletionsApi()
|
|
981
|
+
}),
|
|
982
|
+
getModels: () => buildModels()
|
|
983
|
+
};
|
|
984
|
+
const profile = {
|
|
985
|
+
provider: CODEARTS_PROVIDER,
|
|
986
|
+
displayName: "CodeArts",
|
|
987
|
+
streamIdleTimeoutMs: CODEARTS_STREAM_IDLE_TIMEOUT_MS,
|
|
988
|
+
retryPolicy: resolveCodeArtsRetryPolicy(options.retryPolicy),
|
|
989
|
+
configuredMaxTokens: /* @__PURE__ */ new Map(),
|
|
990
|
+
modelErrors: /* @__PURE__ */ new Map(),
|
|
991
|
+
...REQUEST_IMAGE_BUDGETS,
|
|
992
|
+
piProvider: provider
|
|
993
|
+
};
|
|
994
|
+
let profiles = /* @__PURE__ */ new Map([[CODEARTS_PROVIDER, profile]]);
|
|
995
|
+
return {
|
|
996
|
+
adapter: new CodeArtsPiAiAdapter(catalog, enabledModels, {
|
|
997
|
+
profiles: () => profiles,
|
|
998
|
+
auth: INERT_AUTH,
|
|
999
|
+
resolveApiKey: async () => shim.token(),
|
|
1000
|
+
...resolveAttachments === void 0 ? {} : { resolveAttachments }
|
|
1001
|
+
}),
|
|
1002
|
+
invalidate: () => {
|
|
1003
|
+
profiles = /* @__PURE__ */ new Map([[CODEARTS_PROVIDER, profile]]);
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Adapter that narrows the *offered* model surface to the enabled allowlist
|
|
1009
|
+
* (dispatch stays whole). Mirrors dsh-codebuddy-cli's CodeBuddyPiAiAdapter.
|
|
1010
|
+
*/
|
|
1011
|
+
var CodeArtsPiAiAdapter = class extends PiAiAdapter {
|
|
1012
|
+
catalog;
|
|
1013
|
+
enabledModels;
|
|
1014
|
+
constructor(catalog, enabledModels, options) {
|
|
1015
|
+
super(options);
|
|
1016
|
+
this.catalog = catalog;
|
|
1017
|
+
this.enabledModels = enabledModels;
|
|
1018
|
+
}
|
|
1019
|
+
async listModels(provider) {
|
|
1020
|
+
const models = await super.listModels(provider);
|
|
1021
|
+
const allowed = filterEnabledModels(this.catalog.current(), this.enabledModels?.());
|
|
1022
|
+
const catalogIds = new Set(this.catalog.current().map((entry) => entry.id));
|
|
1023
|
+
const allowedIds = new Set(allowed.map((entry) => entry.id));
|
|
1024
|
+
return models.filter((model) => !catalogIds.has(model.id) || allowedIds.has(model.id));
|
|
1025
|
+
}
|
|
1026
|
+
async resolveModel(provider, model, signal) {
|
|
1027
|
+
return super.resolveModel(provider, model, signal);
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
//#endregion
|
|
1031
|
+
//#region src/pi-ai-compat.ts
|
|
1032
|
+
/**
|
|
1033
|
+
* `@earendil-works/pi-ai` 运行时自检。
|
|
1034
|
+
*
|
|
1035
|
+
* 本插件编译时对齐的是 1.3.0,而宿主(`dsh-llm-pi-ai` 0.2.1-rc.2 起)会先把系统提示
|
|
1036
|
+
* 折叠成一条 `role:"system"`、`content` 为**字符串**的消息,再交给 provider。1.3.0 之前
|
|
1037
|
+
* 的 `estimateMessageTokens` 没有 system 分支:字符串内容被按字符遍历,每个"块"是单个
|
|
1038
|
+
* 字符,`block.name` 为 undefined,于是每条消息都死在
|
|
1039
|
+
* `Cannot read properties of undefined (reading 'length')` 上 —— 而且是在出网之前,
|
|
1040
|
+
* 用户只看得到一句「本轮运行失败」。
|
|
1041
|
+
*
|
|
1042
|
+
* 什么时候会拿到旧的那份:profile 顶层被别的插件 hoist 了一个低版本,而本插件的依赖
|
|
1043
|
+
* 没落地到自己的 `node_modules`。1.1.4 起 pi-ai 直接打包进 `lib/`(不再经 npm 解析),
|
|
1044
|
+
* 版本漂移在结构上不可能了;这里仍探测一次,把「产物损坏/不兼容」明说,而不是让
|
|
1045
|
+
* 每条消息各自崩在一个看不懂的 TypeError 上。
|
|
1046
|
+
*
|
|
1047
|
+
* 探测用能力而不是版本号:不依赖 package.json 能不能读到,也对未来的版本漂移免疫。
|
|
1048
|
+
*
|
|
1049
|
+
* @module dsh-codearts/pi-ai-compat
|
|
1050
|
+
*/
|
|
1051
|
+
/** 折叠后的系统消息要能被估token;从这一版起才支持。 */
|
|
1052
|
+
const MIN_PI_AI_VERSION = "1.3.0";
|
|
1053
|
+
let probe;
|
|
1054
|
+
/** 不兼容时的说明;兼容时 undefined。结果只算一次(模块加载后版本不会再变)。 */
|
|
1055
|
+
function probePiAiCompat() {
|
|
1056
|
+
probe ??= runProbe();
|
|
1057
|
+
return probe;
|
|
1058
|
+
}
|
|
1059
|
+
async function runProbe() {
|
|
1060
|
+
const hint = `需要 @earendil-works/pi-ai >= ${MIN_PI_AI_VERSION} 的行为;1.1.4 起它已打进插件产物,探测失败说明产物损坏或被改动,请重装 dsh-codearts`;
|
|
1061
|
+
let estimate;
|
|
1062
|
+
try {
|
|
1063
|
+
({estimateMessageTokens: estimate} = await import("./estimate-BePoD-Np.mjs").then((n) => n.n));
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
return `pi-ai 不兼容:读不到 @earendil-works/pi-ai/utils/estimate(${messageOf(error)})。${hint}`;
|
|
1066
|
+
}
|
|
1067
|
+
if (typeof estimate !== "function") return `pi-ai 不兼容:这份 @earendil-works/pi-ai 没有 estimateMessageTokens。${hint}`;
|
|
1068
|
+
try {
|
|
1069
|
+
estimate({
|
|
1070
|
+
role: "system",
|
|
1071
|
+
content: "probe"
|
|
1072
|
+
});
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
return `pi-ai 不兼容:这份 @earendil-works/pi-ai 处理不了宿主折叠出的 system 消息(${messageOf(error)}),每条请求都会在出网前失败。${hint}`;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
function messageOf(error) {
|
|
1078
|
+
return error instanceof Error ? error.message : String(error);
|
|
1079
|
+
}
|
|
1080
|
+
//#endregion
|
|
1081
|
+
//#region src/loopback.ts
|
|
1082
|
+
/**
|
|
1083
|
+
* Shared loopback gates for the plugin's local HTTP surfaces: the loopback
|
|
1084
|
+
* shim and the same-origin web-status route. Both are only ever meant to be
|
|
1085
|
+
* addressed through the machine's loopback interface.
|
|
1086
|
+
*
|
|
1087
|
+
* The 127.0.0.1 bind alone is not a trust boundary (any local process or a
|
|
1088
|
+
* DNS-rebinding page can reach 127.0.0.1), so both surfaces also check the
|
|
1089
|
+
* Host and Origin headers.
|
|
1090
|
+
*
|
|
1091
|
+
* @module dsh-codearts/loopback
|
|
1092
|
+
*/
|
|
1093
|
+
/**
|
|
1094
|
+
* Loopback hostnames a local plugin surface may be addressed by.
|
|
1095
|
+
*
|
|
1096
|
+
* `0.0.0.0` and `::` are deliberately absent: they are wildcard *bind*
|
|
1097
|
+
* addresses, not loopback identities, and accepting them in a Host header
|
|
1098
|
+
* would let a request that never went through the loopback interface pass.
|
|
1099
|
+
*/
|
|
1100
|
+
const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
1101
|
+
"127.0.0.1",
|
|
1102
|
+
"localhost",
|
|
1103
|
+
"[::1]"
|
|
1104
|
+
]);
|
|
1105
|
+
/** Strip the optional :port from a Host header value, IPv6-bracket aware. */
|
|
1106
|
+
function hostnameOfHost(host) {
|
|
1107
|
+
let hostname = host.trim().toLowerCase();
|
|
1108
|
+
if (hostname.startsWith("[")) {
|
|
1109
|
+
const end = hostname.indexOf("]");
|
|
1110
|
+
return end === -1 ? hostname : hostname.slice(0, end + 1);
|
|
1111
|
+
}
|
|
1112
|
+
const colon = hostname.lastIndexOf(":");
|
|
1113
|
+
if (colon !== -1 && !hostname.slice(0, colon).includes(":") && /^\d+$/.test(hostname.slice(colon + 1))) hostname = hostname.slice(0, colon);
|
|
1114
|
+
return hostname;
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* The request's Host header must name the loopback interface. A DNS-rebinding
|
|
1118
|
+
* page (attacker domain re-resolved to 127.0.0.1) sends its own domain in
|
|
1119
|
+
* Host, so this check drops those before any routing happens.
|
|
1120
|
+
*/
|
|
1121
|
+
function hostIsLoopback(host) {
|
|
1122
|
+
if (host === void 0 || host.trim() === "") return false;
|
|
1123
|
+
return LOOPBACK_HOSTS.has(hostnameOfHost(host));
|
|
1124
|
+
}
|
|
1125
|
+
/** 归一化地址用于比较:去方括号、去 zone、IPv4-mapped IPv6 还原成 IPv4。 */
|
|
1126
|
+
function addressKey(value) {
|
|
1127
|
+
let address = value.trim().toLowerCase();
|
|
1128
|
+
if (address.startsWith("[") && address.endsWith("]")) address = address.slice(1, -1);
|
|
1129
|
+
const zone = address.indexOf("%");
|
|
1130
|
+
if (zone !== -1) address = address.slice(0, zone);
|
|
1131
|
+
if (address.startsWith("::ffff:") && address.slice(7).includes(".")) address = address.slice(7);
|
|
1132
|
+
return address;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Host 是否就是这条连接实际落到的本机地址(`socket.localAddress`)。
|
|
1136
|
+
*
|
|
1137
|
+
* DSH webserver 绑定局域网 IP 时(`--host <内网IP>`,没监听回环),浏览器发的
|
|
1138
|
+
* Host 只能是那个 IP,以前的「只认回环 Host」把整组路由拦成 403(issue #25)。
|
|
1139
|
+
* 信任连接的本机地址不是放宽成「信任任意 Host」:DNS-rebinding 页面发的是自己的
|
|
1140
|
+
* 域名,永远对不上连接实际落到的地址。
|
|
1141
|
+
*/
|
|
1142
|
+
function hostMatchesLocalAddress(host, localAddress) {
|
|
1143
|
+
if (host === void 0 || host.trim() === "") return false;
|
|
1144
|
+
if (localAddress === void 0 || localAddress.trim() === "") return false;
|
|
1145
|
+
return addressKey(hostnameOfHost(host)) === addressKey(localAddress);
|
|
1146
|
+
}
|
|
1147
|
+
/** 回环或连接本机地址都算可信 Host(web-status 路由用)。 */
|
|
1148
|
+
function hostIsTrusted(host, localAddress) {
|
|
1149
|
+
return hostIsLoopback(host) || hostMatchesLocalAddress(host, localAddress);
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* A browser-sent Origin (present header) must be loopback. Non-browser
|
|
1153
|
+
* clients (the plugin's own fetch calls) send no Origin at all and pass.
|
|
1154
|
+
*/
|
|
1155
|
+
function originIsLoopback(origin) {
|
|
1156
|
+
if (origin === void 0 || origin.trim() === "") return true;
|
|
1157
|
+
try {
|
|
1158
|
+
const { hostname } = new URL(origin);
|
|
1159
|
+
return LOOPBACK_HOSTS.has(hostname) || hostname === "::1";
|
|
1160
|
+
} catch {
|
|
1161
|
+
return false;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* 浏览器 Origin 必须是回环或**与连接本机地址同源**(web-status 路由用)。
|
|
1166
|
+
* 缺 Origin 的非浏览器客户端照旧放行;跨站页面的 Origin 对不上本机地址,
|
|
1167
|
+
* 依旧被拦下。
|
|
1168
|
+
*/
|
|
1169
|
+
function originIsTrusted(origin, localAddress) {
|
|
1170
|
+
if (origin === void 0 || origin.trim() === "") return true;
|
|
1171
|
+
if (localAddress === void 0 || localAddress.trim() === "") return originIsLoopback(origin);
|
|
1172
|
+
try {
|
|
1173
|
+
const { hostname } = new URL(origin);
|
|
1174
|
+
return LOOPBACK_HOSTS.has(hostname) || hostname === "::1" || hostMatchesLocalAddress(hostname, localAddress);
|
|
1175
|
+
} catch {
|
|
1176
|
+
return false;
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
//#endregion
|
|
1180
|
+
//#region src/shim.ts
|
|
1181
|
+
/**
|
|
1182
|
+
* Loopback OpenAI-compatible endpoint for CodeArts.
|
|
1183
|
+
*
|
|
1184
|
+
* DSH's pi-ai provider points here. The shim validates the loopback + shared
|
|
1185
|
+
* secret, resolves the pasted `cloud_dragon_token`, and forwards the request
|
|
1186
|
+
* to CodeArts' `/api/v2/chat/completions` — whose SSE chunk shape is already
|
|
1187
|
+
* OpenAI-compatible, so we pipe the upstream stream straight through.
|
|
1188
|
+
*
|
|
1189
|
+
* Inbound hardening (copied from dsh-codebuddy-cli): bind 127.0.0.1 only,
|
|
1190
|
+
* require a loopback Host header, a loopback Origin, and the per-process
|
|
1191
|
+
* shared secret as `Authorization: Bearer`. Any local attacker hitting the
|
|
1192
|
+
* port still cannot forge the secret.
|
|
1193
|
+
*
|
|
1194
|
+
* @module dsh-codearts/shim
|
|
1195
|
+
*/
|
|
1196
|
+
const REQUEST_BODY_LIMIT = 67108864;
|
|
1197
|
+
const KIND_STATUS = {
|
|
1198
|
+
hard_credit: 402,
|
|
1199
|
+
soft_rate: 429,
|
|
1200
|
+
gate_rate: 429,
|
|
1201
|
+
session_dead: 401,
|
|
1202
|
+
iam_stale: 401,
|
|
1203
|
+
not_found: 502,
|
|
1204
|
+
server: 502,
|
|
1205
|
+
client: 400
|
|
1206
|
+
};
|
|
1207
|
+
function isJsonContentType(req) {
|
|
1208
|
+
const type = req.headers["content-type"];
|
|
1209
|
+
return typeof type === "string" && type.trim().toLowerCase().startsWith("application/json");
|
|
1210
|
+
}
|
|
1211
|
+
function writeJson(res, status, body) {
|
|
1212
|
+
const payload = JSON.stringify(body);
|
|
1213
|
+
res.writeHead(status, {
|
|
1214
|
+
"Content-Type": "application/json",
|
|
1215
|
+
"Content-Length": Buffer.byteLength(payload)
|
|
1216
|
+
});
|
|
1217
|
+
res.end(payload);
|
|
1218
|
+
}
|
|
1219
|
+
function writeOpenAIError(res, status, kind, message) {
|
|
1220
|
+
writeJson(res, status, { error: {
|
|
1221
|
+
message,
|
|
1222
|
+
type: kind,
|
|
1223
|
+
code: kind
|
|
1224
|
+
} });
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* 「一个账号都选不出来」时的报错:把真实原因说清 —— 是禁用(附最后错误)、冷却
|
|
1228
|
+
* (附剩余秒数),还是本地槽位全满。以前三种都回同一句「没有可用账号」,禁用那
|
|
1229
|
+
* 种还把真因(比如 billion-context 本地拒签的 403)整个吞掉(issue #1)。
|
|
1230
|
+
*
|
|
1231
|
+
* 全部被禁用时回 401(宿主只自动重试 429,401 一次就把「去重新登录」说清);
|
|
1232
|
+
* 只要还有会自己恢复的(冷却/槽位满)就回 429,让宿主重试接住。默认重试预算
|
|
1233
|
+
* 已对齐 30s 冷却窗(8 次指数退避 ≈45.5s,见 `adapter.ts`),冷却前段也跨得过。
|
|
1234
|
+
*/
|
|
1235
|
+
function noAccountError(accounts, pausedIds = []) {
|
|
1236
|
+
const now = Date.now();
|
|
1237
|
+
const paused = new Set(pausedIds);
|
|
1238
|
+
const disabled = accounts.filter((a) => a.disabled);
|
|
1239
|
+
const cooling = accounts.filter((a) => !a.disabled && now < a.coolUntil);
|
|
1240
|
+
const idleButPaused = accounts.filter((a) => !a.disabled && now >= a.coolUntil && paused.has(a.id));
|
|
1241
|
+
const busy = accounts.filter((a) => !a.disabled && now >= a.coolUntil && !paused.has(a.id));
|
|
1242
|
+
const parts = [];
|
|
1243
|
+
if (disabled.length > 0) {
|
|
1244
|
+
const reasons = disabled.map((a) => a.lastError === void 0 ? a.id : `${a.id}(${a.lastError.slice(0, 120)})`).join("、");
|
|
1245
|
+
parts.push(`${disabled.length} 个被禁用:${reasons}——请到设置卡片重新登录(若在用 billion-context,先检查它的 resign 配置)`);
|
|
1246
|
+
}
|
|
1247
|
+
if (cooling.length > 0) {
|
|
1248
|
+
const secs = Math.max(1, Math.ceil((Math.min(...cooling.map((a) => a.coolUntil)) - now) / 1e3));
|
|
1249
|
+
parts.push(`${cooling.length} 个在短时冷却中(约 ${secs} 秒后恢复)`);
|
|
1250
|
+
}
|
|
1251
|
+
if (idleButPaused.length > 0) parts.push(`${idleButPaused.length} 个已被暂停(在卡片上取消暂停即可恢复)`);
|
|
1252
|
+
if (busy.length > 0) parts.push(`${busy.length} 个的本地并发槽位已满(每账号最多 ${busy[0]?.maxConcurrent ?? 2} 个在飞请求)`);
|
|
1253
|
+
const message = disabled.length === 0 && cooling.length === 0 && idleButPaused.length === 0 && busy.length > 0 ? `codearts 账号忙:${parts.join(";")},已等待仍没有空位,请稍后重试` : `codearts 当前没有可用账号:${parts.join(";")}`;
|
|
1254
|
+
return disabled.length === accounts.length ? {
|
|
1255
|
+
status: 401,
|
|
1256
|
+
kind: "session_dead",
|
|
1257
|
+
message
|
|
1258
|
+
} : {
|
|
1259
|
+
status: 429,
|
|
1260
|
+
kind: "soft_rate",
|
|
1261
|
+
message
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
function readBody$1(req) {
|
|
1265
|
+
return new Promise((resolve, reject) => {
|
|
1266
|
+
const chunks = [];
|
|
1267
|
+
let size = 0;
|
|
1268
|
+
req.on("data", (chunk) => {
|
|
1269
|
+
size += chunk.length;
|
|
1270
|
+
if (size > REQUEST_BODY_LIMIT) {
|
|
1271
|
+
reject(/* @__PURE__ */ new Error("request body too large"));
|
|
1272
|
+
req.destroy();
|
|
1273
|
+
return;
|
|
1274
|
+
}
|
|
1275
|
+
chunks.push(chunk);
|
|
1276
|
+
});
|
|
1277
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
1278
|
+
req.on("error", reject);
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* 一次请求最多把 max_tokens 降几档(65536 → 32768 → 16384 → 8192)。
|
|
1283
|
+
*
|
|
1284
|
+
* 到地板后还会再进循环一次 —— 那一次不再重发,而是把「其实是上下文装不下」
|
|
1285
|
+
* 报出来并学习窗口上界(见 `openWithCeilingHeal`)。
|
|
1286
|
+
*/
|
|
1287
|
+
const MAX_CEILING_HEALS = 3;
|
|
1288
|
+
/**
|
|
1289
|
+
* 一次请求最多试几个账号:clamp(可用账号数, ROTATE_MIN_ATTEMPTS, ROTATE_MAX_ATTEMPTS)。
|
|
1290
|
+
*
|
|
1291
|
+
* 原来固定试 3 个(与 Go 参考的 MaxRotate 一致)。多号才是这个插件的核心场景:
|
|
1292
|
+
* 5 个号时前 3 个在这一轮里都新报了并发上限,第 4 个明明空着也轮不到,只能落到
|
|
1293
|
+
* 下面那根「原地排队等 52 秒」的稻草上 —— 那 52 秒本来是可以绕开的。
|
|
1294
|
+
*
|
|
1295
|
+
* 上界 6 只是次数天花板,真正的刹车是 CAP_WAIT_LIMIT 那个共用截止点:每次尝试都要
|
|
1296
|
+
* 挂号 + 开一次流,号再多也不能无限试下去。
|
|
1297
|
+
*/
|
|
1298
|
+
const ROTATE_MIN_ATTEMPTS = 3;
|
|
1299
|
+
const ROTATE_MAX_ATTEMPTS = 6;
|
|
1300
|
+
/**
|
|
1301
|
+
* 轮换最多跑几轮:每轮重新按账号试一遍。轮间要么等本地槽位释放(槽满),
|
|
1302
|
+
* 要么等冷却到点解冻(全在冷却)—— 两种都会让时间往前走,所以是有限的。
|
|
1303
|
+
*/
|
|
1304
|
+
const ROTATE_MAX_ROUNDS = 3;
|
|
1305
|
+
/** 开始下一次尝试前必须留下的预算:一次挂号短探(默认 5 秒)再加一次开流。 */
|
|
1306
|
+
const ATTEMPT_RESERVE_MS = 2e4;
|
|
1307
|
+
/**
|
|
1308
|
+
* 一次请求在「换号轮换 + 回落到同一账号原地重发」上总共能花的墙上时间,从进入
|
|
1309
|
+
* 轮换起算,两段共用一个截止点。
|
|
1310
|
+
*
|
|
1311
|
+
* 2026-09-30 实测:一个上游会话要 ~52s 才被释放,而且**中途打断并不减免** ——
|
|
1312
|
+
* 只跑了 98ms 就中止的请求,同样占满一个名额 52s。所以用户「打断 → 马上重问」
|
|
1313
|
+
* 时等的就是这个 52s。池里有别的账号时下面会直接换号(不用等);这条是最后一根
|
|
1314
|
+
* 稻草,必须盖过 52s,否则用户看到的不是「稍等一下」而是直接失败。
|
|
1315
|
+
*
|
|
1316
|
+
* 上限受 pi-ai 的 90s idle 超时约束:等待期间我们发不出任何内容,超过 90s 用户
|
|
1317
|
+
* 看到的就是超时。75s 给 52s 留了余量,也还在 90s 之内。以前这个预算只归兜底那一段
|
|
1318
|
+
* 自己,轮换花掉的时间是额外加的,多号最坏能顶穿 90s —— 所以现在是共用截止点。
|
|
1319
|
+
*/
|
|
1320
|
+
const CAP_WAIT_LIMIT = 75e3;
|
|
1321
|
+
const CAP_RETRY_GAP = 3e3;
|
|
1322
|
+
/** 上游回「排队」拒绝后的首次退避,之后翻倍(5s → 10s → 20s → 30s)。 */
|
|
1323
|
+
const QUEUE_RETRY_GAP = 5e3;
|
|
1324
|
+
/**
|
|
1325
|
+
* 「排队时一直等到轮到」开关打开后替用户挂多久。
|
|
1326
|
+
*
|
|
1327
|
+
* 默认关(卡片「显示」页):这一段会提前打开 SSE 并每 20 秒发一个空帧保活,
|
|
1328
|
+
* 等待期间界面上已经开始「回复」了 —— 属于用户应当主动选择的行为。
|
|
1329
|
+
*/
|
|
1330
|
+
const QUEUE_WAIT_LIMIT_MS = 9e5;
|
|
1331
|
+
/** 空帧间隔:宿主按「可解析的流事件」算 90 秒空闲,20 秒留足余量。 */
|
|
1332
|
+
const QUEUE_HEARTBEAT_MS = 2e4;
|
|
1333
|
+
/**
|
|
1334
|
+
* 软限流的冷却:上游实测真的会拒约 30 秒、且无 Retry-After 头(issue #22)。
|
|
1335
|
+
* 这是上游的罚站时长,不动。
|
|
1336
|
+
*/
|
|
1337
|
+
const SERVER_COOLDOWN_MS = 3e4;
|
|
1338
|
+
/**
|
|
1339
|
+
* 上游 5xx 的首次冷却:5xx 多为瞬时抖动,几秒即恢复。借用软限流的 30 秒属于
|
|
1340
|
+
* 保守误伤 —— 内联等待落地后,冷却时长就是用户实打实的等待(issue #22)。
|
|
1341
|
+
* 连续 5xx 按倍数递增、封顶到 SERVER_COOLDOWN_MS,避免持续故障被短冷却连打。
|
|
1342
|
+
*/
|
|
1343
|
+
const SERVER_5XX_COOLDOWN_MS = 4e3;
|
|
1344
|
+
/**
|
|
1345
|
+
* API 网关限流(APIG.0308)的冷却:官方窗口是 1 分钟,必须长于它才能让下次请求
|
|
1346
|
+
* 落在窗口外。65 秒留出边界抖动余量(issue #22 后续,纯本地退避)。
|
|
1347
|
+
*/
|
|
1348
|
+
const GATEWAY_COOLDOWN_MS = 65e3;
|
|
1349
|
+
/** 零散错误累计到阈值后冷却该账号。 */
|
|
1350
|
+
const ERROR_COOLDOWN_MS = 6e4;
|
|
1351
|
+
/**
|
|
1352
|
+
* 积分耗尽后的冷却。积分是账号级的,不会在几十秒内回来(要等套餐周期刷新或
|
|
1353
|
+
* 领取活动积分),30 秒的短冷却只会让它被反复选中、反复失败一遍。30 分钟是
|
|
1354
|
+
* 「不反复白撞」与「用户中途领到积分后还能恢复」之间的折中;用户也可以在
|
|
1355
|
+
* 卡片上暂停这个号。
|
|
1356
|
+
*/
|
|
1357
|
+
const CREDIT_COOLDOWN_MS = 18e5;
|
|
1358
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1359
|
+
const recentShapes = [];
|
|
1360
|
+
/** 最近的请求形状,最新在前。 */
|
|
1361
|
+
function recentRequestShapes() {
|
|
1362
|
+
return [...recentShapes].reverse();
|
|
1363
|
+
}
|
|
1364
|
+
const recentUsages = [];
|
|
1365
|
+
/** 探针只留最近 5 帧:够看形状,又不至于把内存堆成日志。 */
|
|
1366
|
+
const USAGE_PROBE_LIMIT = 5;
|
|
1367
|
+
/** 最近的 usage 原帧,最新在前。 */
|
|
1368
|
+
function recentUsageShapes() {
|
|
1369
|
+
return [...recentUsages].reverse();
|
|
1370
|
+
}
|
|
1371
|
+
function noteRequestShape(raw, model) {
|
|
1372
|
+
let parsed;
|
|
1373
|
+
try {
|
|
1374
|
+
parsed = JSON.parse(raw);
|
|
1375
|
+
} catch {
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
if (parsed === null || typeof parsed !== "object") return;
|
|
1379
|
+
const list = Array.isArray(parsed.messages) ? parsed.messages : [];
|
|
1380
|
+
const roles = list.map((message) => {
|
|
1381
|
+
if (message === null || typeof message !== "object") return "";
|
|
1382
|
+
const role = message.role;
|
|
1383
|
+
return typeof role === "string" ? role : "";
|
|
1384
|
+
});
|
|
1385
|
+
recentShapes.push({
|
|
1386
|
+
at: Date.now(),
|
|
1387
|
+
model,
|
|
1388
|
+
messages: list.length,
|
|
1389
|
+
roles,
|
|
1390
|
+
emptyRoleAt: roles.map((role, index) => role === "" ? index : -1).filter((index) => index >= 0),
|
|
1391
|
+
tools: Array.isArray(parsed.tools) ? parsed.tools.length : 0
|
|
1392
|
+
});
|
|
1393
|
+
if (recentShapes.length > 8) recentShapes.shift();
|
|
1394
|
+
}
|
|
1395
|
+
function createCodeArtsShim(options) {
|
|
1396
|
+
const { store, catalog } = options;
|
|
1397
|
+
const logger = options.logger;
|
|
1398
|
+
const usage = options.usage;
|
|
1399
|
+
const queue = options.queue;
|
|
1400
|
+
const debug = options.debug;
|
|
1401
|
+
const localSlotWaitBudgetMs = options.localSlotWaitMs ?? 3e4;
|
|
1402
|
+
const queueRetryGapMs = options.queueRetryGapMs ?? QUEUE_RETRY_GAP;
|
|
1403
|
+
const pool = options.pool ?? new CodeArtsAccountPool([]);
|
|
1404
|
+
/**
|
|
1405
|
+
* 连续 5xx 次数(按账号):5xx 冷却按 4s 起翻倍递增、封顶 30s(issue #22 辅建议)。
|
|
1406
|
+
* 跨请求保留,任何非 5xx 结果(成功、软限流、客户端错误)清零。
|
|
1407
|
+
*/
|
|
1408
|
+
const serverStreaks = /* @__PURE__ */ new Map();
|
|
1409
|
+
const SHARED_SECRET = randomBytes(32).toString("base64url");
|
|
1410
|
+
function bearerOk(req) {
|
|
1411
|
+
const header = req.headers.authorization;
|
|
1412
|
+
if (typeof header !== "string") return false;
|
|
1413
|
+
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
|
|
1414
|
+
if (match === null) return false;
|
|
1415
|
+
const presented = match[1];
|
|
1416
|
+
const a = Buffer.from(presented);
|
|
1417
|
+
const b = Buffer.from(SHARED_SECRET);
|
|
1418
|
+
if (a.length !== b.length) return false;
|
|
1419
|
+
return timingSafeEqual(a, b);
|
|
1420
|
+
}
|
|
1421
|
+
const server = createServer((req, res) => {
|
|
1422
|
+
handle(req, res);
|
|
1423
|
+
});
|
|
1424
|
+
const ready = new Promise((resolve, reject) => {
|
|
1425
|
+
server.once("listening", () => resolve());
|
|
1426
|
+
server.once("error", reject);
|
|
1427
|
+
});
|
|
1428
|
+
server.listen(0, "127.0.0.1");
|
|
1429
|
+
const baseUrl = () => {
|
|
1430
|
+
const address = server.address();
|
|
1431
|
+
if (address === null || typeof address === "string") throw new Error("codearts shim has no listening address");
|
|
1432
|
+
return `http://127.0.0.1:${address.port}`;
|
|
1433
|
+
};
|
|
1434
|
+
async function handle(req, res) {
|
|
1435
|
+
try {
|
|
1436
|
+
if (!hostIsLoopback(req.headers.host)) {
|
|
1437
|
+
writeOpenAIError(res, 403, "host_not_allowed", "Host header must name the loopback interface");
|
|
1438
|
+
return;
|
|
1439
|
+
}
|
|
1440
|
+
if (!originIsLoopback(req.headers.origin)) {
|
|
1441
|
+
writeOpenAIError(res, 403, "origin_not_allowed", "Origin must be a loopback origin");
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
if (!bearerOk(req)) {
|
|
1445
|
+
writeOpenAIError(res, 401, "unauthorized", "missing or invalid Authorization bearer");
|
|
1446
|
+
return;
|
|
1447
|
+
}
|
|
1448
|
+
const url = req.url ?? "/";
|
|
1449
|
+
if (req.method === "GET" && (url === "/healthz" || url === "/healthz/")) {
|
|
1450
|
+
writeJson(res, 200, { ok: true });
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
if (req.method === "GET" && (url === "/v1/models" || url === "/v1/models/")) {
|
|
1454
|
+
writeJson(res, 200, {
|
|
1455
|
+
object: "list",
|
|
1456
|
+
data: catalog.current().map((model) => ({
|
|
1457
|
+
id: model.id,
|
|
1458
|
+
object: "model",
|
|
1459
|
+
created: 0,
|
|
1460
|
+
owned_by: "codearts"
|
|
1461
|
+
}))
|
|
1462
|
+
});
|
|
1463
|
+
return;
|
|
1464
|
+
}
|
|
1465
|
+
if (req.method === "POST" && (url === "/v1/chat/completions" || url === "/v1/chat/completions/")) {
|
|
1466
|
+
await chatCompletions(req, res);
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
writeOpenAIError(res, 404, "not_found", `no such route: ${req.method} ${url}`);
|
|
1470
|
+
} catch (error) {
|
|
1471
|
+
if (!res.headersSent) writeOpenAIError(res, 500, "internal", String(error));
|
|
1472
|
+
else res.end();
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* 该模型当前应使用的上下文窗口:用户覆盖优先于目录值,再被进程内学到的上界往下钳。
|
|
1477
|
+
*
|
|
1478
|
+
* 学到的上界来自「max_tokens 已到地板仍被判参数非法」的实测(issue #9)。必须在这里
|
|
1479
|
+
* 生效 —— 只改目录不够,目录要等下一轮发现,而用户下一句话马上就来。
|
|
1480
|
+
* 返回 0 表示查不到该模型,不做超长预判。
|
|
1481
|
+
*/
|
|
1482
|
+
function contextWindowFor(id) {
|
|
1483
|
+
const lower = id.trim().toLowerCase();
|
|
1484
|
+
let discovered = 0;
|
|
1485
|
+
for (const model of catalog.current()) if (model.id.toLowerCase() === lower) {
|
|
1486
|
+
discovered = model.contextWindow;
|
|
1487
|
+
break;
|
|
1488
|
+
}
|
|
1489
|
+
const base = contextWindowOverrideFor(options.contextWindowOverrides?.(), lower) ?? discovered;
|
|
1490
|
+
const learned = learnedContextWindowFor(lower);
|
|
1491
|
+
const window = learned === void 0 ? base : Math.min(base, learned);
|
|
1492
|
+
return window > 0 ? window : 0;
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* 打开上游流;撞到「参数非法」就把该模型的 max_tokens 上限折半降一档再开一次。
|
|
1496
|
+
*
|
|
1497
|
+
* 上游的 max_tokens 上限由服务端控制、会漂(GLM-5.2 标称 131072,2026-10-10 起
|
|
1498
|
+
* 直接被拒),手工实测表必然滞后。而这类错误是**流内**帧(HTTP 仍 200),只能在
|
|
1499
|
+
* 第一帧判 —— 此时还没有任何内容产出,重发是安全的。降档结果记在 upstream 的
|
|
1500
|
+
* 进程内表里,该模型后续请求直接从新上限起步,不必每轮再白撞一次。
|
|
1501
|
+
*/
|
|
1502
|
+
async function openWithCeilingHeal(credential, raw, contextWindow, signal) {
|
|
1503
|
+
for (let heal = 0;; heal += 1) {
|
|
1504
|
+
const prepared = prepareChatBody(raw, contextWindow);
|
|
1505
|
+
if (prepared.error !== void 0) return {
|
|
1506
|
+
prepared,
|
|
1507
|
+
result: {
|
|
1508
|
+
ok: false,
|
|
1509
|
+
kind: "client",
|
|
1510
|
+
status: 400,
|
|
1511
|
+
message: prepared.error
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
const result = await chatStream(credential, prepared, signal);
|
|
1515
|
+
if (!result.ok) return {
|
|
1516
|
+
prepared,
|
|
1517
|
+
result
|
|
1518
|
+
};
|
|
1519
|
+
const reader = result.stream.getReader();
|
|
1520
|
+
const first = await reader.read();
|
|
1521
|
+
const head = first.done ? void 0 : first.value;
|
|
1522
|
+
const headText = head === void 0 ? void 0 : new TextDecoder().decode(head);
|
|
1523
|
+
const rate = headText === void 0 ? void 0 : rateLimitFrame(headText);
|
|
1524
|
+
if (rate !== void 0) {
|
|
1525
|
+
reader.releaseLock();
|
|
1526
|
+
await result.stream.cancel().catch(() => {});
|
|
1527
|
+
logger?.warn(`dsh-codearts: ${prepared.model} 首帧被判限流(${rate.code}),进入本地排队`);
|
|
1528
|
+
return {
|
|
1529
|
+
prepared,
|
|
1530
|
+
result: {
|
|
1531
|
+
ok: false,
|
|
1532
|
+
kind: "soft_rate",
|
|
1533
|
+
status: 429,
|
|
1534
|
+
message: `${rate.code}: ${rate.message}`
|
|
1535
|
+
}
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
const queued = headText === void 0 ? void 0 : queueFrame(headText);
|
|
1539
|
+
if (queued !== void 0) {
|
|
1540
|
+
reader.releaseLock();
|
|
1541
|
+
await result.stream.cancel().catch(() => {});
|
|
1542
|
+
logger?.warn(`dsh-codearts: ${prepared.model} 首帧被判排队,本地退避重发`);
|
|
1543
|
+
return {
|
|
1544
|
+
prepared,
|
|
1545
|
+
result: {
|
|
1546
|
+
ok: false,
|
|
1547
|
+
kind: "client",
|
|
1548
|
+
status: 400,
|
|
1549
|
+
message: `queued: ${queued.message}`
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
const upstreamError = headText === void 0 ? void 0 : firstFrameError(headText);
|
|
1554
|
+
if (upstreamError !== void 0) {
|
|
1555
|
+
const detail = `${upstreamError.code}: ${upstreamError.message}`.replace(/^: /, "");
|
|
1556
|
+
if (isIamTokenError(detail) || isModelNotAccessible(detail) || isNotMultimodal(detail) || isCreditExhausted(detail)) {
|
|
1557
|
+
reader.releaseLock();
|
|
1558
|
+
await result.stream.cancel().catch(() => {});
|
|
1559
|
+
logger?.warn(`dsh-codearts: ${prepared.model} 首帧报上游错误(${detail.slice(0, 160)})`);
|
|
1560
|
+
if (isModelNotAccessible(detail)) markModelUnavailable(prepared.model, modelUnavailableReasonText(detail));
|
|
1561
|
+
const kind = isIamTokenError(detail) ? "iam_stale" : isModelNotAccessible(detail) ? "not_found" : isCreditExhausted(detail) ? "hard_credit" : "client";
|
|
1562
|
+
return {
|
|
1563
|
+
prepared,
|
|
1564
|
+
result: {
|
|
1565
|
+
ok: false,
|
|
1566
|
+
kind,
|
|
1567
|
+
status: KIND_STATUS[kind],
|
|
1568
|
+
message: detail
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
const atFloor = maxTokensCeilingFor(prepared.model) <= MAX_TOKENS_FLOOR;
|
|
1574
|
+
const shouldHeal = prepared.promptTokens > 0 && headText !== void 0 && isParamInvalidFrame(headText) && (heal < MAX_CEILING_HEALS || atFloor);
|
|
1575
|
+
reader.releaseLock();
|
|
1576
|
+
if (!shouldHeal) return {
|
|
1577
|
+
prepared,
|
|
1578
|
+
result,
|
|
1579
|
+
head
|
|
1580
|
+
};
|
|
1581
|
+
await result.stream.cancel().catch(() => {});
|
|
1582
|
+
if (degradeTokenCeiling(prepared.model) === 0) {
|
|
1583
|
+
const overflow = isContextOverflowText(headText ?? "");
|
|
1584
|
+
if (overflow && prepared.promptTokens > 0) {
|
|
1585
|
+
const learned = learnContextWindow(prepared.model, prepared.promptTokens);
|
|
1586
|
+
logger?.warn(`dsh-codearts: ${prepared.model} 上游明确报超窗,按本次 prompt 估算 ${prepared.promptTokens} tokens 学习窗口上界 ${learned}`);
|
|
1587
|
+
}
|
|
1588
|
+
if (overflow) {
|
|
1589
|
+
const estimate = prepared.promptTokens > 0 ? `本次 prompt 估算约 ${prepared.promptTokens} tokens,` : "";
|
|
1590
|
+
return {
|
|
1591
|
+
prepared,
|
|
1592
|
+
result: {
|
|
1593
|
+
ok: false,
|
|
1594
|
+
kind: "client",
|
|
1595
|
+
status: 400,
|
|
1596
|
+
message: `${prepared.model}: 上下文放不下 —— ${estimate}max_tokens 已降到 ${MAX_TOKENS_FLOOR} 仍被上游判参数非法。请压缩上下文(/compact)或新建会话;如果目录里的窗口值不准,可在设置里覆盖该模型的 contextWindow。`
|
|
1597
|
+
}
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
logger?.warn(`dsh-codearts: ${prepared.model} 在 max_tokens 地板仍被判参数非法,但文案不是超窗 —— 按请求体过大处理,不学习窗口上界`);
|
|
1601
|
+
return {
|
|
1602
|
+
prepared,
|
|
1603
|
+
result: {
|
|
1604
|
+
ok: false,
|
|
1605
|
+
kind: "client",
|
|
1606
|
+
status: 400,
|
|
1607
|
+
message: `${prepared.model}: 上游判定参数非法,但 max_tokens 已降到 ${MAX_TOKENS_FLOOR},报错里也没有超窗口文案 —— 多半是请求体过大(内联图片/附件过多,上游约 10 MB 就拒)。请减少图片或附件后重试;这不是上下文窗口问题,本次没有记录窗口上界。`
|
|
1608
|
+
}
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1611
|
+
logger?.warn(`dsh-codearts: ${prepared.model} 被判参数非法,max_tokens 降档到 ${maxTokensCeilingFor(prepared.model)} 后重发`);
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
/**
|
|
1615
|
+
* 在**同一个账号**上重发,直到不再被限流或预算耗尽。
|
|
1616
|
+
*
|
|
1617
|
+
* `untilAt` 由调用方给:它和前面的换号轮换是同一个截止点,不是这段自己重新起算,
|
|
1618
|
+
* 否则两段各自 75s 会顶穿宿主的 90s 流空闲超时。
|
|
1619
|
+
*
|
|
1620
|
+
* 并发槽位是账号级的:有别的号就该换号,等 52s 是最后手段。
|
|
1621
|
+
* TPM 是模型级配额:换号只是换个账号撞同一堵墙,只能原地等窗口滑过去 ——
|
|
1622
|
+
* 间隔逐次翻倍(3s → 6s → 12s → 24s,封顶 30s),避免在配额已经满的时候
|
|
1623
|
+
* 把重试本身也打成一波流量。
|
|
1624
|
+
*
|
|
1625
|
+
* 「排队」拒绝(issue #10)同理:上游让等一会儿再来,从 5 秒起翻倍重发;
|
|
1626
|
+
* 这段等待发生在 POST 被拒之后 —— 还没写给宿主任何字节,重发安全。
|
|
1627
|
+
*
|
|
1628
|
+
* 命中限流不甩给 pi-ai:429 会被重试 5 次,每次再撞一次限流,越试越满。
|
|
1629
|
+
*/
|
|
1630
|
+
async function openStream(credential, raw, contextWindow, signal, untilAt) {
|
|
1631
|
+
const started = Date.now();
|
|
1632
|
+
let gap = CAP_RETRY_GAP;
|
|
1633
|
+
let queueGap = queueRetryGapMs;
|
|
1634
|
+
for (;;) {
|
|
1635
|
+
const opened = await openWithCeilingHeal(credential, raw, contextWindow, signal);
|
|
1636
|
+
const waitedMs = Date.now() - started;
|
|
1637
|
+
if (opened.result.ok || signal.aborted) return {
|
|
1638
|
+
...opened,
|
|
1639
|
+
waitedMs
|
|
1640
|
+
};
|
|
1641
|
+
if (!isQueueableRate(opened.result)) return {
|
|
1642
|
+
...opened,
|
|
1643
|
+
waitedMs
|
|
1644
|
+
};
|
|
1645
|
+
if (isTpmLimit(opened.result)) gap = Math.min(gap * 2, 3e4);
|
|
1646
|
+
if (isQueueReject(opened.result)) {
|
|
1647
|
+
gap = queueGap;
|
|
1648
|
+
queueGap = Math.min(queueGap * 2, 3e4);
|
|
1649
|
+
}
|
|
1650
|
+
if (Date.now() + gap > untilAt) return {
|
|
1651
|
+
...opened,
|
|
1652
|
+
waitedMs
|
|
1653
|
+
};
|
|
1654
|
+
await sleep(gap);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
/** 先交回降档判定读过的那一帧(它是流的开头,丢了就少一段),再接着读剩下的。 */
|
|
1658
|
+
async function* drainFrames(reader, head) {
|
|
1659
|
+
if (head !== void 0) yield head;
|
|
1660
|
+
for (;;) {
|
|
1661
|
+
const { done, value } = await reader.read();
|
|
1662
|
+
if (done) return;
|
|
1663
|
+
if (value !== void 0) yield value;
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
async function chatCompletions(req, res) {
|
|
1667
|
+
/** 首字延迟的起点:从读完请求头就开始算,排队与换号的时间都算「用户等了多久」。 */
|
|
1668
|
+
const requestStartedAt = Date.now();
|
|
1669
|
+
if (!isJsonContentType(req)) {
|
|
1670
|
+
usage?.noteFailure("media_type");
|
|
1671
|
+
writeOpenAIError(res, 415, "unsupported_media_type", "Content-Type must be application/json");
|
|
1672
|
+
return;
|
|
1673
|
+
}
|
|
1674
|
+
const raw = (await readBody$1(req)).toString("utf8");
|
|
1675
|
+
let contextWindow = 0;
|
|
1676
|
+
try {
|
|
1677
|
+
const inbound = JSON.parse(raw);
|
|
1678
|
+
if (typeof inbound.model === "string") contextWindow = contextWindowFor(canonicalModel(inbound.model));
|
|
1679
|
+
} catch {}
|
|
1680
|
+
const checked = prepareChatBody(raw, contextWindow);
|
|
1681
|
+
noteRequestShape(raw, checked.model);
|
|
1682
|
+
if (checked.error !== void 0) {
|
|
1683
|
+
usage?.noteFailure("context_overflow");
|
|
1684
|
+
writeOpenAIError(res, 400, "context_overflow", checked.error);
|
|
1685
|
+
return;
|
|
1686
|
+
}
|
|
1687
|
+
const controller = new AbortController();
|
|
1688
|
+
res.on("close", () => {
|
|
1689
|
+
if (!res.writableEnded) controller.abort();
|
|
1690
|
+
});
|
|
1691
|
+
let ids;
|
|
1692
|
+
try {
|
|
1693
|
+
const all = await store.ids();
|
|
1694
|
+
const paused = new Set(await store.pausedIds());
|
|
1695
|
+
pool.sync(all);
|
|
1696
|
+
pool.setPaused([...paused]);
|
|
1697
|
+
pool.setPreferred(await store.pinnedIds());
|
|
1698
|
+
ids = all.filter((id) => !paused.has(id));
|
|
1699
|
+
} catch (error) {
|
|
1700
|
+
usage?.noteFailure("not_signed_in");
|
|
1701
|
+
writeOpenAIError(res, 401, "not_signed_in", String(error));
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1704
|
+
if (ids.length === 0) {
|
|
1705
|
+
usage?.noteFailure("not_signed_in");
|
|
1706
|
+
writeOpenAIError(res, 401, "not_signed_in", "no CodeArts account stored; sign in from the CodeArts settings card");
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1709
|
+
pool.sync(ids);
|
|
1710
|
+
const tried = /* @__PURE__ */ new Set();
|
|
1711
|
+
/** 已经为它强制续期过一次的账号:同一个号只重试一次,避免把 refresh_token 连烧。 */
|
|
1712
|
+
const refreshed = /* @__PURE__ */ new Set();
|
|
1713
|
+
let cappedAccount;
|
|
1714
|
+
let tpmAccount;
|
|
1715
|
+
let queuedAccount;
|
|
1716
|
+
let queueWaitedMs = 0;
|
|
1717
|
+
let localSlotWaitedMs = 0;
|
|
1718
|
+
let cooldownWaitedMs = 0;
|
|
1719
|
+
/** 冷却等待时已经先开了 SSE(空帧保活):之后的失败只能走流内错误帧。 */
|
|
1720
|
+
let streamStarted = false;
|
|
1721
|
+
let lastKind;
|
|
1722
|
+
let lastAccountId;
|
|
1723
|
+
let lastStatus = 0;
|
|
1724
|
+
let lastMessage = "";
|
|
1725
|
+
const rotateDeadline = Date.now() + CAP_WAIT_LIMIT;
|
|
1726
|
+
const attempts = Math.min(Math.max(ids.length, ROTATE_MIN_ATTEMPTS), ROTATE_MAX_ATTEMPTS);
|
|
1727
|
+
/** 日志里区分并发请求;没开调试时不生成。 */
|
|
1728
|
+
const requestTag = debug === void 0 ? "" : randomBytes(3).toString("hex");
|
|
1729
|
+
/**
|
|
1730
|
+
* 两轮:第一轮按账号轮换;如果全被「本地槽位满」挡住,就等一个槽位空出来
|
|
1731
|
+
* 再跑第二轮。以前这里直接落到「没有可用账号」的 429,并发派发(一次 5 个
|
|
1732
|
+
* subagent)必然误伤(issue #8)。
|
|
1733
|
+
*/
|
|
1734
|
+
for (let round = 0; round < ROTATE_MAX_ROUNDS; round += 1) {
|
|
1735
|
+
tried.clear();
|
|
1736
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
1737
|
+
if (Date.now() + ATTEMPT_RESERVE_MS > rotateDeadline) break;
|
|
1738
|
+
const id = pool.pick(tried);
|
|
1739
|
+
if (id === void 0) break;
|
|
1740
|
+
tried.add(id);
|
|
1741
|
+
if (!pool.acquire(id)) {
|
|
1742
|
+
debug?.(`acquire miss req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
|
|
1743
|
+
continue;
|
|
1744
|
+
}
|
|
1745
|
+
debug?.(`acquire ok req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
|
|
1746
|
+
try {
|
|
1747
|
+
const credential = await store.resolve(id);
|
|
1748
|
+
if (credential === void 0) {
|
|
1749
|
+
pool.disable(id, "no credential");
|
|
1750
|
+
continue;
|
|
1751
|
+
}
|
|
1752
|
+
if (queue !== void 0) {
|
|
1753
|
+
const gate = await queue.wait(credential, checked.chatId, checked.model, controller.signal);
|
|
1754
|
+
if (controller.signal.aborted) return;
|
|
1755
|
+
if (gate.kind !== "working") debug?.(`queue ${gate.kind} req=${requestTag} ${id}`);
|
|
1756
|
+
}
|
|
1757
|
+
const opened = await openWithCeilingHeal(credential, raw, contextWindow, controller.signal);
|
|
1758
|
+
const { prepared, result } = opened;
|
|
1759
|
+
if (controller.signal.aborted) {
|
|
1760
|
+
if (result.ok) await result.stream.cancel().catch(() => {});
|
|
1761
|
+
return;
|
|
1762
|
+
}
|
|
1763
|
+
if (result.ok) {
|
|
1764
|
+
pool.noteSuccess(id);
|
|
1765
|
+
serverStreaks.delete(id);
|
|
1766
|
+
await pipeToResponse(res, result.stream, controller.signal, {
|
|
1767
|
+
accountId: id,
|
|
1768
|
+
model: prepared.model,
|
|
1769
|
+
startedAt: requestStartedAt
|
|
1770
|
+
}, opened.head);
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
lastKind = result.kind;
|
|
1774
|
+
lastAccountId = id;
|
|
1775
|
+
lastStatus = result.status;
|
|
1776
|
+
lastMessage = result.message;
|
|
1777
|
+
if (result.kind !== "server") serverStreaks.delete(id);
|
|
1778
|
+
if (isConcurrencyCap(result)) {
|
|
1779
|
+
pool.noteConcurrencyCap(id);
|
|
1780
|
+
cappedAccount = id;
|
|
1781
|
+
continue;
|
|
1782
|
+
}
|
|
1783
|
+
if (isTpmLimit(result)) {
|
|
1784
|
+
tpmAccount = id;
|
|
1785
|
+
break;
|
|
1786
|
+
}
|
|
1787
|
+
if (isQueueReject(result)) {
|
|
1788
|
+
queuedAccount = id;
|
|
1789
|
+
break;
|
|
1790
|
+
}
|
|
1791
|
+
if (result.kind === "iam_stale") {
|
|
1792
|
+
if (!refreshed.has(id)) {
|
|
1793
|
+
refreshed.add(id);
|
|
1794
|
+
logger?.warn(`dsh-codearts: ${id} 的 IAM token 被判失效,强制续期后重试`);
|
|
1795
|
+
if (await store.forceRefresh(id, credential.token) !== void 0) {
|
|
1796
|
+
tried.delete(id);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
|
|
1801
|
+
continue;
|
|
1802
|
+
}
|
|
1803
|
+
if (result.kind === "session_dead") {
|
|
1804
|
+
pool.disable(id, result.message);
|
|
1805
|
+
continue;
|
|
1806
|
+
}
|
|
1807
|
+
if (result.kind === "hard_credit") {
|
|
1808
|
+
pool.cooldown(id, CREDIT_COOLDOWN_MS, "该账号积分已耗尽(TM.00001050),额度刷新或领取积分后恢复");
|
|
1809
|
+
continue;
|
|
1810
|
+
}
|
|
1811
|
+
if (result.kind === "server") {
|
|
1812
|
+
const streak = (serverStreaks.get(id) ?? 0) + 1;
|
|
1813
|
+
serverStreaks.set(id, streak);
|
|
1814
|
+
const cooldownMs = Math.min(SERVER_COOLDOWN_MS, SERVER_5XX_COOLDOWN_MS * 2 ** Math.min(streak - 1, 10));
|
|
1815
|
+
pool.cooldown(id, cooldownMs, result.message);
|
|
1816
|
+
debug?.(`server 5xx cooldown account=${id} streak=${streak} ms=${cooldownMs}`);
|
|
1817
|
+
break;
|
|
1818
|
+
}
|
|
1819
|
+
if (result.kind === "gate_rate") {
|
|
1820
|
+
pool.cooldown(id, GATEWAY_COOLDOWN_MS, result.message);
|
|
1821
|
+
break;
|
|
1822
|
+
}
|
|
1823
|
+
if (result.kind === "soft_rate") {
|
|
1824
|
+
pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
|
|
1825
|
+
break;
|
|
1826
|
+
}
|
|
1827
|
+
pool.noteError(id, 3, ERROR_COOLDOWN_MS, result.message);
|
|
1828
|
+
break;
|
|
1829
|
+
} finally {
|
|
1830
|
+
pool.release(id);
|
|
1831
|
+
debug?.(`release req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
if (lastKind !== void 0 || controller.signal.aborted) break;
|
|
1835
|
+
if (!pool.hasBusyWaitable()) {
|
|
1836
|
+
const thawAt = pool.earliestCooldownEnd();
|
|
1837
|
+
const thawBudget = rotateDeadline - ATTEMPT_RESERVE_MS - Date.now();
|
|
1838
|
+
if (thawAt === void 0 || thawBudget <= 0) break;
|
|
1839
|
+
if (thawAt - Date.now() > thawBudget) break;
|
|
1840
|
+
const heartbeat = startHeartbeat(checked.model);
|
|
1841
|
+
streamStarted = true;
|
|
1842
|
+
const coolingSince = Date.now();
|
|
1843
|
+
debug?.(`cooldown wait start req=${requestTag} thawIn=${thawAt - coolingSince}ms`);
|
|
1844
|
+
const thawed = await pool.waitForCooldownEnd(thawBudget, controller.signal);
|
|
1845
|
+
cooldownWaitedMs += Date.now() - coolingSince;
|
|
1846
|
+
heartbeat.stop();
|
|
1847
|
+
debug?.(`cooldown wait ${thawed ? "done" : "timeout"} req=${requestTag} waited=${Date.now() - coolingSince}ms`);
|
|
1848
|
+
if (!thawed) break;
|
|
1849
|
+
continue;
|
|
1850
|
+
}
|
|
1851
|
+
const waitBudget = Math.min(localSlotWaitBudgetMs, rotateDeadline - ATTEMPT_RESERVE_MS - Date.now());
|
|
1852
|
+
if (waitBudget <= 0) break;
|
|
1853
|
+
const waitingSince = Date.now();
|
|
1854
|
+
debug?.(`slot wait start req=${requestTag} budget=${waitBudget}ms pool=${pool.list().map((a) => `${a.id}:${a.activeConcurrent}/${a.maxConcurrent}`).join(",")}`);
|
|
1855
|
+
const got = await pool.waitForFreeSlot(waitBudget, controller.signal);
|
|
1856
|
+
localSlotWaitedMs += Date.now() - waitingSince;
|
|
1857
|
+
debug?.(`slot wait ${got ? "done" : "timeout"} req=${requestTag} waited=${Date.now() - waitingSince}ms`);
|
|
1858
|
+
if (!got) break;
|
|
1859
|
+
}
|
|
1860
|
+
if (controller.signal.aborted) return;
|
|
1861
|
+
if (queuedAccount !== void 0 && options.waitInQueue?.() === true) {
|
|
1862
|
+
await waitForQueueTurn(queuedAccount);
|
|
1863
|
+
return;
|
|
1864
|
+
}
|
|
1865
|
+
const queueAccount = cappedAccount ?? tpmAccount ?? queuedAccount;
|
|
1866
|
+
if (queueAccount !== void 0) {
|
|
1867
|
+
if (pool.acquire(queueAccount)) try {
|
|
1868
|
+
const credential = await store.resolve(queueAccount);
|
|
1869
|
+
if (credential !== void 0) {
|
|
1870
|
+
const opened = await openStream(credential, raw, contextWindow, controller.signal, rotateDeadline);
|
|
1871
|
+
const { result } = opened;
|
|
1872
|
+
queueWaitedMs = opened.waitedMs;
|
|
1873
|
+
if (controller.signal.aborted) {
|
|
1874
|
+
if (result.ok) await result.stream.cancel().catch(() => {});
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
if (result.ok) {
|
|
1878
|
+
pool.noteCapRelease(queueAccount);
|
|
1879
|
+
pool.noteSuccess(queueAccount);
|
|
1880
|
+
serverStreaks.delete(queueAccount);
|
|
1881
|
+
await pipeToResponse(res, result.stream, controller.signal, {
|
|
1882
|
+
accountId: queueAccount,
|
|
1883
|
+
model: opened.prepared.model,
|
|
1884
|
+
startedAt: requestStartedAt
|
|
1885
|
+
}, opened.head);
|
|
1886
|
+
return;
|
|
1887
|
+
}
|
|
1888
|
+
lastKind = result.kind;
|
|
1889
|
+
lastAccountId = queueAccount;
|
|
1890
|
+
lastStatus = result.status;
|
|
1891
|
+
lastMessage = result.message;
|
|
1892
|
+
}
|
|
1893
|
+
} finally {
|
|
1894
|
+
pool.release(queueAccount);
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
if (lastKind === void 0) {
|
|
1898
|
+
const none = noAccountError(pool.list(), pool.pausedIds());
|
|
1899
|
+
usage?.noteFailure(none.kind);
|
|
1900
|
+
if (streamStarted) failStream(res, none.message, none.kind);
|
|
1901
|
+
else writeOpenAIError(res, none.status, none.kind, none.message);
|
|
1902
|
+
return;
|
|
1903
|
+
}
|
|
1904
|
+
const explanation = upstreamErrorMessage(lastMessage, lastStatus);
|
|
1905
|
+
const waits = [];
|
|
1906
|
+
if (queueWaitedMs >= 1e3) waits.push(`排队重试 ${Math.round(queueWaitedMs / 1e3)} 秒`);
|
|
1907
|
+
if (localSlotWaitedMs >= 1e3) waits.push(`等本地槽位 ${Math.round(localSlotWaitedMs / 1e3)} 秒`);
|
|
1908
|
+
if (cooldownWaitedMs >= 1e3) waits.push(`等冷却解冻 ${Math.round(cooldownWaitedMs / 1e3)} 秒`);
|
|
1909
|
+
const waited = waits.length > 0 ? `(本地已${waits.join("、")})` : "";
|
|
1910
|
+
const failedKind = isQueueRejectText(lastMessage) ? "queued" : lastKind;
|
|
1911
|
+
usage?.noteFailure(failedKind, lastAccountId);
|
|
1912
|
+
if (streamStarted) failStream(res, `${explanation}${waited}`, failedKind);
|
|
1913
|
+
else writeOpenAIError(res, KIND_STATUS[lastKind], failedKind, `${explanation}${waited}`);
|
|
1914
|
+
/**
|
|
1915
|
+
* 「一直等到轮到」:提前开流保住宿主连接,轮询这张票直到 working,再发请求。
|
|
1916
|
+
*
|
|
1917
|
+
* 和上面的兜底通道有一个本质区别:响应头已经发出去了,后面任何失败都**不能再
|
|
1918
|
+
* 换号、也不能回 HTTP 状态码**,只能以流内错误帧交代。所以只有上游明确回排队
|
|
1919
|
+
* 拒绝时才会走到这里 —— 那时换别的号去撞同一张票也没有意义。
|
|
1920
|
+
*/
|
|
1921
|
+
async function waitForQueueTurn(id) {
|
|
1922
|
+
const gate = queue;
|
|
1923
|
+
if (gate === void 0) return;
|
|
1924
|
+
const credential = await store.resolve(id);
|
|
1925
|
+
if (credential === void 0) return;
|
|
1926
|
+
const waitStartedAt = Date.now();
|
|
1927
|
+
const heartbeat = startHeartbeat(checked.model);
|
|
1928
|
+
try {
|
|
1929
|
+
const verdict = await gate.wait(credential, checked.chatId, checked.model, controller.signal, QUEUE_WAIT_LIMIT_MS);
|
|
1930
|
+
if (controller.signal.aborted || verdict.kind === "aborted") return;
|
|
1931
|
+
if (verdict.kind !== "working") {
|
|
1932
|
+
usage?.noteFailure(verdict.kind === "error" ? "queued" : verdict.kind, id);
|
|
1933
|
+
failStream(res, verdict.kind === "queued" ? `等了 ${Math.round(QUEUE_WAIT_LIMIT_MS / 6e4)} 分钟仍未轮到(第 ${verdict.position} 位,共 ${verdict.length} 条)。请稍后重试,或临时切换模型。` : verdict.message);
|
|
1934
|
+
return;
|
|
1935
|
+
}
|
|
1936
|
+
let acquired = pool.acquire(id);
|
|
1937
|
+
if (!acquired) acquired = await pool.waitForFreeSlot(1e4, controller.signal) && pool.acquire(id);
|
|
1938
|
+
if (!acquired) {
|
|
1939
|
+
failStream(res, "轮到排队后本地账号槽位仍被占用,请稍后重试。");
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1942
|
+
try {
|
|
1943
|
+
const opened = await openStream(credential, raw, contextWindow, controller.signal, Date.now() + 6e4);
|
|
1944
|
+
queueWaitedMs = opened.waitedMs;
|
|
1945
|
+
if (controller.signal.aborted) {
|
|
1946
|
+
if (opened.result.ok) await opened.result.stream.cancel().catch(() => {});
|
|
1947
|
+
return;
|
|
1948
|
+
}
|
|
1949
|
+
if (opened.result.ok) {
|
|
1950
|
+
pool.noteSuccess(id);
|
|
1951
|
+
serverStreaks.delete(id);
|
|
1952
|
+
await pipeToResponse(res, opened.result.stream, controller.signal, {
|
|
1953
|
+
accountId: id,
|
|
1954
|
+
model: opened.prepared.model,
|
|
1955
|
+
startedAt: requestStartedAt
|
|
1956
|
+
}, opened.head);
|
|
1957
|
+
return;
|
|
1958
|
+
}
|
|
1959
|
+
usage?.noteFailure(isQueueReject(opened.result) ? "queued" : opened.result.kind, id);
|
|
1960
|
+
const waitedSec = Math.round((Date.now() - waitStartedAt) / 1e3);
|
|
1961
|
+
const suffix = waitedSec >= 1 ? `(本地已排队 ${waitedSec} 秒)` : "";
|
|
1962
|
+
failStream(res, `${upstreamErrorMessage(opened.result.message, opened.result.status)}${suffix}`);
|
|
1963
|
+
} finally {
|
|
1964
|
+
pool.release(id);
|
|
1965
|
+
}
|
|
1966
|
+
} finally {
|
|
1967
|
+
heartbeat.stop();
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
/**
|
|
1971
|
+
* 等待期间的空帧:宿主只看「可解析的流事件」续空闲计时(SSE 注释不算),
|
|
1972
|
+
* 空 delta 不产生任何可见文字,但足以让连接活着。
|
|
1973
|
+
*/
|
|
1974
|
+
function startHeartbeat(model) {
|
|
1975
|
+
if (!res.headersSent) res.writeHead(200, {
|
|
1976
|
+
"Content-Type": "text/event-stream",
|
|
1977
|
+
"Cache-Control": "no-cache",
|
|
1978
|
+
"Connection": "keep-alive",
|
|
1979
|
+
"X-Accel-Buffering": "no"
|
|
1980
|
+
});
|
|
1981
|
+
const beat = () => {
|
|
1982
|
+
if (!res.writable || res.writableEnded) return;
|
|
1983
|
+
res.write(`data: ${JSON.stringify({
|
|
1984
|
+
id: "codearts-queue",
|
|
1985
|
+
object: "chat.completion.chunk",
|
|
1986
|
+
created: Math.floor(Date.now() / 1e3),
|
|
1987
|
+
model,
|
|
1988
|
+
choices: [{
|
|
1989
|
+
index: 0,
|
|
1990
|
+
delta: {},
|
|
1991
|
+
finish_reason: null
|
|
1992
|
+
}]
|
|
1993
|
+
})}\n\n`);
|
|
1994
|
+
};
|
|
1995
|
+
beat();
|
|
1996
|
+
const timer = setInterval(beat, QUEUE_HEARTBEAT_MS);
|
|
1997
|
+
timer.unref?.();
|
|
1998
|
+
return { stop: () => clearInterval(timer) };
|
|
1999
|
+
}
|
|
2000
|
+
/** 响应头已经发出之后的失败:只能作为流内错误帧交代,不能再改状态码。 */
|
|
2001
|
+
function failStream(response, message, code = "queued") {
|
|
2002
|
+
if (!response.writable || response.writableEnded) return;
|
|
2003
|
+
response.write(`data: ${JSON.stringify({
|
|
2004
|
+
choices: [{
|
|
2005
|
+
index: 0,
|
|
2006
|
+
delta: { content: "" },
|
|
2007
|
+
finish_reason: "stop"
|
|
2008
|
+
}],
|
|
2009
|
+
error: {
|
|
2010
|
+
code,
|
|
2011
|
+
message
|
|
2012
|
+
}
|
|
2013
|
+
})}\n\n`);
|
|
2014
|
+
response.end("data: [DONE]\n\n");
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
/**
|
|
2018
|
+
* 记下一帧里的上游流内错误。判据宽松(帧文本含 "error" 才解析),解析不出来就忽略 ——
|
|
2019
|
+
* 诊断不能影响转发。
|
|
2020
|
+
*/
|
|
2021
|
+
function logInStreamError(frame, model) {
|
|
2022
|
+
try {
|
|
2023
|
+
const payload = frame.startsWith("data:") ? frame.slice(5).trim() : frame;
|
|
2024
|
+
const ev = JSON.parse(payload);
|
|
2025
|
+
if (ev.error === void 0) return;
|
|
2026
|
+
const code = String(ev.error.code ?? "");
|
|
2027
|
+
const message = String(ev.error.message ?? "").slice(0, 200);
|
|
2028
|
+
logger?.error(`dsh-codearts: 上游流内报错 model=${model} 错误码 ${code} msg=${message}`);
|
|
2029
|
+
} catch {}
|
|
2030
|
+
}
|
|
2031
|
+
/** 把上游 SSE 按事件边界转发给 DSH,直到流结束或被中止。 */
|
|
2032
|
+
async function pipeToResponse(res, stream, signal, attribution, head) {
|
|
2033
|
+
if (!res.headersSent) res.writeHead(200, {
|
|
2034
|
+
"Content-Type": "text/event-stream",
|
|
2035
|
+
"Cache-Control": "no-cache",
|
|
2036
|
+
"Connection": "keep-alive",
|
|
2037
|
+
"X-Accel-Buffering": "no"
|
|
2038
|
+
});
|
|
2039
|
+
const reader = stream.getReader();
|
|
2040
|
+
const decoder = new TextDecoder();
|
|
2041
|
+
let buf = "";
|
|
2042
|
+
if (usage !== void 0 && attribution !== void 0) usage.noteRequest(attribution.accountId, attribution.model);
|
|
2043
|
+
let sawDone = false;
|
|
2044
|
+
/** 首个真正写出的帧记一次 TTFT;之后不再记。 */
|
|
2045
|
+
let firstFrame = true;
|
|
2046
|
+
const finish = () => {
|
|
2047
|
+
if (!res.writable || res.writableEnded) return;
|
|
2048
|
+
res.end(sawDone ? void 0 : "data: [DONE]\n\n");
|
|
2049
|
+
};
|
|
2050
|
+
try {
|
|
2051
|
+
for await (const value of drainFrames(reader, head)) {
|
|
2052
|
+
buf += decoder.decode(value, { stream: true });
|
|
2053
|
+
let idx;
|
|
2054
|
+
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
2055
|
+
const frame = buf.slice(0, idx);
|
|
2056
|
+
buf = buf.slice(idx + 2);
|
|
2057
|
+
if (!frame) continue;
|
|
2058
|
+
if (frame.trim() === "data: [DONE]") sawDone = true;
|
|
2059
|
+
if (frame.includes("\"error\"")) logInStreamError(frame, attribution?.model ?? "");
|
|
2060
|
+
if (usage !== void 0 && attribution !== void 0 && frame.includes("\"usage\"")) recordFrameUsage(frame, attribution);
|
|
2061
|
+
if (res.writable) {
|
|
2062
|
+
if (firstFrame) {
|
|
2063
|
+
firstFrame = false;
|
|
2064
|
+
if (usage !== void 0 && attribution?.startedAt !== void 0) usage.noteLatency(Date.now() - attribution.startedAt);
|
|
2065
|
+
}
|
|
2066
|
+
res.write(frame + "\n\n");
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
finish();
|
|
2071
|
+
} catch (error) {
|
|
2072
|
+
if (!signal.aborted) logger?.warn("dsh-codearts: upstream stream failed mid-flight", error);
|
|
2073
|
+
finish();
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
/** 从一帧 SSE 文本里取 usage 计入账本(解析失败就算了,不能影响转发)。 */
|
|
2077
|
+
function recordFrameUsage(frame, attribution) {
|
|
2078
|
+
if (usage === void 0) return;
|
|
2079
|
+
for (const line of frame.split("\n")) {
|
|
2080
|
+
const trimmed = line.trim();
|
|
2081
|
+
if (!trimmed.startsWith("data:")) continue;
|
|
2082
|
+
const payload = trimmed.slice(5).trim();
|
|
2083
|
+
if (payload === "" || payload === "[DONE]") continue;
|
|
2084
|
+
try {
|
|
2085
|
+
const parsed = JSON.parse(payload);
|
|
2086
|
+
if (parsed.usage !== void 0 && parsed.usage !== null) {
|
|
2087
|
+
usage.noteUsage(attribution.accountId, attribution.model, parsed.usage);
|
|
2088
|
+
recentUsages.push({
|
|
2089
|
+
at: Date.now(),
|
|
2090
|
+
accountId: attribution.accountId,
|
|
2091
|
+
model: attribution.model,
|
|
2092
|
+
usage: parsed.usage
|
|
2093
|
+
});
|
|
2094
|
+
while (recentUsages.length > USAGE_PROBE_LIMIT) recentUsages.shift();
|
|
2095
|
+
}
|
|
2096
|
+
} catch {}
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
return {
|
|
2100
|
+
ready,
|
|
2101
|
+
baseUrl,
|
|
2102
|
+
token: () => SHARED_SECRET,
|
|
2103
|
+
close: () => new Promise((resolve, reject) => {
|
|
2104
|
+
server.close(() => resolve());
|
|
2105
|
+
server.closeAllConnections();
|
|
2106
|
+
server.once("error", reject);
|
|
2107
|
+
})
|
|
2108
|
+
};
|
|
2109
|
+
}
|
|
2110
|
+
//#endregion
|
|
2111
|
+
//#region src/web-status.ts
|
|
2112
|
+
/** 登录后问身份的超时:它是「顺手做对」,不能拖住登录落库。 */
|
|
2113
|
+
const IDENTITY_TIMEOUT_MS = 8e3;
|
|
2114
|
+
/** Route paths (same-origin under the DSH web origin). */
|
|
2115
|
+
const CODEARTS_STATUS_PATH = "/api/codearts/status";
|
|
2116
|
+
const CODEARTS_MODELS_PATH = "/api/codearts/models";
|
|
2117
|
+
const CODEARTS_MODELS_SELECTION_PATH = "/api/codearts/enabled-models";
|
|
2118
|
+
/**
|
|
2119
|
+
* POST /api/codearts/context-window — 按模型设置/清除上下文窗口覆盖(issue #9)。
|
|
2120
|
+
* `{ id, window }`,`window: null` 表示删除覆盖、回到跟随上游。
|
|
2121
|
+
*/
|
|
2122
|
+
const CODEARTS_CONTEXT_WINDOW_PATH = "/api/codearts/context-window";
|
|
2123
|
+
/**
|
|
2124
|
+
* POST /api/codearts/max-tokens — 按模型设置/清除输出上限覆盖(issue #15)。
|
|
2125
|
+
* `{ id, tokens }`,`tokens: null` 表示删除覆盖、回到跟随上游。
|
|
2126
|
+
*/
|
|
2127
|
+
const CODEARTS_MAX_TOKENS_PATH = "/api/codearts/max-tokens";
|
|
2128
|
+
/**
|
|
2129
|
+
* GET/POST /api/codearts/concurrency — 每账号本地并发上限(issue #16)。
|
|
2130
|
+
* GET 回 `{ value, writable }`;POST 收 `{ value: number }`,改完立即生效。
|
|
2131
|
+
*/
|
|
2132
|
+
const CODEARTS_CONCURRENCY_PATH = "/api/codearts/concurrency";
|
|
2133
|
+
const CODEARTS_TOKEN_PATH = "/api/codearts/token";
|
|
2134
|
+
const CODEARTS_LOGIN_PATH = "/api/codearts/login";
|
|
2135
|
+
const CODEARTS_LOGIN_STATUS_PATH = "/api/codearts/login/status";
|
|
2136
|
+
/** 删除某个账号:DELETE /api/codearts/accounts?id=<accountId> */
|
|
2137
|
+
const CODEARTS_ACCOUNTS_PATH = "/api/codearts/accounts";
|
|
2138
|
+
/** POST /api/codearts/claim — 领一次福利中心的每日签到积分(幂等由上游按天去重)。 */
|
|
2139
|
+
const CODEARTS_CLAIM_PATH = "/api/codearts/claim";
|
|
2140
|
+
/** POST /api/codearts/refresh-models — 立刻重拉一次模型目录,并清掉「福利今日不可用」标记。 */
|
|
2141
|
+
const CODEARTS_REFRESH_MODELS_PATH = "/api/codearts/refresh-models";
|
|
2142
|
+
/**
|
|
2143
|
+
* POST /api/codearts/test-model — 用最小请求实测某个模型能不能调通。
|
|
2144
|
+
*
|
|
2145
|
+
* 存在理由:上游的模型清单会列出调不动的模型(`InferHub.ModelArts.81003.401`),
|
|
2146
|
+
* 刷新救不了;只有真发一次请求才知道。成功会清掉该模型的「异常」标记。
|
|
2147
|
+
*/
|
|
2148
|
+
const CODEARTS_TEST_MODEL_PATH = "/api/codearts/test-model";
|
|
2149
|
+
/** GET /api/codearts/queue — 上游排队位置(只在等开流期间有值,底部积分条旁边展示)。 */
|
|
2150
|
+
const CODEARTS_QUEUE_PATH = "/api/codearts/queue";
|
|
2151
|
+
/**
|
|
2152
|
+
* GET/POST /api/codearts/dock — 对话底部那一行的显隐开关。
|
|
2153
|
+
* GET 给当前值与 writable,POST 收 `{credits?, queue?}` 写进 settings。
|
|
2154
|
+
*/
|
|
2155
|
+
const CODEARTS_DOCK_PATH = "/api/codearts/dock";
|
|
2156
|
+
/**
|
|
2157
|
+
* POST /api/codearts/keeper/stop — 结束常驻守护进程,并把开关**同时**关掉。
|
|
2158
|
+
*
|
|
2159
|
+
* 为什么必须在服务端把开关一起关:进程被 kill 之后,「开关开着但没进程」是个自相
|
|
2160
|
+
* 矛盾的状态。若只杀进程不改开关,用户下次打开 DSH 会看到开关还是开的、PID 却是空
|
|
2161
|
+
* 的,以为功能坏了;而且插件会按「开关是开的」去重起它 —— 用户刚 kill 掉的东西自己
|
|
2162
|
+
* 又回来了。所以这两件事必须原子地一起做。
|
|
2163
|
+
*/
|
|
2164
|
+
const CODEARTS_KEEPER_STOP_PATH = "/api/codearts/keeper/stop";
|
|
2165
|
+
/** 最近出站请求的**形状**摘要(只有 role 名与计数,不含内容),排障用。 */
|
|
2166
|
+
const CODEARTS_DEBUG_PATH = "/api/codearts/debug";
|
|
2167
|
+
/**
|
|
2168
|
+
* GET /api/codearts/doctor — 把 CLI `doctor` 的静态体检搬进卡片。
|
|
2169
|
+
*
|
|
2170
|
+
* 只做本机可判定的检查(版本、账号、凭证有效期、目录、账本、pi-ai 兼容),
|
|
2171
|
+
* 不额外打上游 —— 卡片本来就每 60 秒刷一次状态,不该因为点了体检再等超时。
|
|
2172
|
+
*/
|
|
2173
|
+
const CODEARTS_DOCTOR_PATH = "/api/codearts/doctor";
|
|
2174
|
+
/**
|
|
2175
|
+
* 由完整目录 + 已存 enabled 计算 selection。
|
|
2176
|
+
* - enabled 为空/未存 => 全部勾选(restricted=false)
|
|
2177
|
+
* - enabled 为非空列表 => 仅勾选其中的(restricted=true),缺的按未勾选
|
|
2178
|
+
* 福利模型用 catalog 的 benefit 标记(这里靠 model.benefit 字段,由调用方注入)。
|
|
2179
|
+
*/
|
|
2180
|
+
function selectionOf(models, enabled, writable) {
|
|
2181
|
+
const allowed = new Set(enabled ?? []);
|
|
2182
|
+
const restricted = enabled !== void 0 && enabled.length > 0;
|
|
2183
|
+
return {
|
|
2184
|
+
choices: models.map((m) => ({
|
|
2185
|
+
id: m.id,
|
|
2186
|
+
name: m.name,
|
|
2187
|
+
benefit: m.benefit,
|
|
2188
|
+
blocked: m.blocked,
|
|
2189
|
+
ratio: m.ratio,
|
|
2190
|
+
supportsImages: m.supportsImages,
|
|
2191
|
+
contextWindow: m.contextWindow,
|
|
2192
|
+
contextWindowDiscovered: m.contextWindowDiscovered,
|
|
2193
|
+
contextWindowOverride: m.contextWindowOverride,
|
|
2194
|
+
maxTokens: m.maxTokens,
|
|
2195
|
+
maxTokensDiscovered: m.maxTokensDiscovered,
|
|
2196
|
+
maxTokensOverride: m.maxTokensOverride,
|
|
2197
|
+
...m.error === void 0 ? {} : { error: m.error },
|
|
2198
|
+
enabled: restricted ? allowed.has(m.id) : true
|
|
2199
|
+
})),
|
|
2200
|
+
restricted,
|
|
2201
|
+
writable
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
/** 目录 -> 勾选 UI 的选项(福利标记、今日不可用标记与倍率都在这里算)。 */
|
|
2205
|
+
function choicesOf(deps) {
|
|
2206
|
+
const overrides = deps.contextWindowOverrides?.();
|
|
2207
|
+
const maxOverrides = deps.maxTokensOverrides?.();
|
|
2208
|
+
return deps.models().map((m) => {
|
|
2209
|
+
const benefit = isBenefitModel(m.id);
|
|
2210
|
+
const ratio = creditRatioLabel(m.ratio, benefit);
|
|
2211
|
+
const error = modelUnavailableReason(m.id);
|
|
2212
|
+
const override = contextWindowOverrideFor(overrides, m.id);
|
|
2213
|
+
const maxOverride = overrideValueFor(maxOverrides, m.id);
|
|
2214
|
+
return {
|
|
2215
|
+
id: m.id,
|
|
2216
|
+
name: m.name,
|
|
2217
|
+
benefit,
|
|
2218
|
+
blocked: isBenefitBlocked(m.id),
|
|
2219
|
+
...ratio === void 0 ? {} : { ratio },
|
|
2220
|
+
...m.supportsImages === true ? { supportsImages: true } : {},
|
|
2221
|
+
...m.contextWindowKnown === true ? { contextWindow: m.contextWindow } : {},
|
|
2222
|
+
...m.contextWindowDiscovered === void 0 ? {} : { contextWindowDiscovered: m.contextWindowDiscovered },
|
|
2223
|
+
...override === void 0 ? {} : { contextWindowOverride: override },
|
|
2224
|
+
...m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {},
|
|
2225
|
+
...m.maxTokensDiscovered === void 0 ? {} : { maxTokensDiscovered: m.maxTokensDiscovered },
|
|
2226
|
+
...maxOverride === void 0 ? {} : { maxTokensOverride: maxOverride },
|
|
2227
|
+
...error === void 0 ? {} : { error }
|
|
2228
|
+
};
|
|
2229
|
+
});
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* 目录 -> 底栏/卡片用的模型徽章。
|
|
2233
|
+
*
|
|
2234
|
+
* 倍率在这里就算好(`creditRatioLabel`:福利恒为 `x0.00`),客户端拿到的是可以直接
|
|
2235
|
+
* 印出来的字符串 —— 底栏那一行要把它作为独立的一段,所以不能只给带尾巴的名字。
|
|
2236
|
+
*/
|
|
2237
|
+
function modelBadgesOf(models) {
|
|
2238
|
+
return models.map((m) => {
|
|
2239
|
+
const ratio = creditRatioLabel(m.ratio, isBenefitModel(m.id));
|
|
2240
|
+
return {
|
|
2241
|
+
id: m.id,
|
|
2242
|
+
name: m.name,
|
|
2243
|
+
...ratio === void 0 ? {} : { ratio }
|
|
2244
|
+
};
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
/**
|
|
2248
|
+
* 开关的默认值:没有 settings provider(或老配置没这两个键)时保持原有行为 ——
|
|
2249
|
+
* 底部两行都显示;侧边栏相反,缺省不开(那一格是所有插件共用的全局座位)。
|
|
2250
|
+
* `modelDetail` 缺省开(保持老版本的样子),`autoClaim` 缺省关。
|
|
2251
|
+
*/
|
|
2252
|
+
const DEFAULT_DOCK_FLAGS = {
|
|
2253
|
+
credits: true,
|
|
2254
|
+
queue: true,
|
|
2255
|
+
sidebar: false,
|
|
2256
|
+
settingsEntry: true,
|
|
2257
|
+
modelDetail: true,
|
|
2258
|
+
autoClaim: false,
|
|
2259
|
+
keepAliveDaemon: false,
|
|
2260
|
+
queueWait: false
|
|
2261
|
+
};
|
|
2262
|
+
/**
|
|
2263
|
+
* 把逐账号的领取结果汇总成一条:HTTP 层只看 ok,卡片看 results 逐号展示。
|
|
2264
|
+
* 有一个号失败就算整批 ok=false,但别的号领到的结果照样在 results 里。
|
|
2265
|
+
*/
|
|
2266
|
+
function summarizeClaims(results) {
|
|
2267
|
+
const failed = results.find((result) => result.state === "failed");
|
|
2268
|
+
const claimed = results.filter((result) => result.claimed);
|
|
2269
|
+
const messages = [...new Set(results.map((result) => result.message).filter((message) => message !== ""))];
|
|
2270
|
+
return {
|
|
2271
|
+
ok: results.length > 0 && failed === void 0,
|
|
2272
|
+
claimed: claimed.length > 0,
|
|
2273
|
+
state: claimed.length > 0 ? "claimed" : failed?.state ?? results[0]?.state ?? "failed",
|
|
2274
|
+
amount: claimed.reduce((sum, result) => sum + result.amount, 0),
|
|
2275
|
+
message: results.length === 1 ? results[0].message : messages.join("; ").slice(0, 300),
|
|
2276
|
+
results
|
|
2277
|
+
};
|
|
2278
|
+
}
|
|
2279
|
+
function json(res, status, body) {
|
|
2280
|
+
const payload = JSON.stringify(body);
|
|
2281
|
+
res.writeHead(status, {
|
|
2282
|
+
"Content-Type": "application/json",
|
|
2283
|
+
"Content-Length": Buffer.byteLength(payload)
|
|
2284
|
+
});
|
|
2285
|
+
res.end(payload);
|
|
2286
|
+
}
|
|
2287
|
+
function loopbackRequest(req) {
|
|
2288
|
+
const localAddress = req.socket?.localAddress;
|
|
2289
|
+
return hostIsTrusted(req.headers.host, localAddress) && originIsTrusted(req.headers.origin, localAddress);
|
|
2290
|
+
}
|
|
2291
|
+
function safeMessage(error) {
|
|
2292
|
+
return (error instanceof Error ? error.message : String(error)).slice(0, 500);
|
|
2293
|
+
}
|
|
2294
|
+
function readBody(req, limit = 1 << 20) {
|
|
2295
|
+
return new Promise((resolve, reject) => {
|
|
2296
|
+
const chunks = [];
|
|
2297
|
+
let size = 0;
|
|
2298
|
+
req.on("data", (chunk) => {
|
|
2299
|
+
size += chunk.length;
|
|
2300
|
+
if (size > limit) {
|
|
2301
|
+
reject(/* @__PURE__ */ new Error("request body too large"));
|
|
2302
|
+
req.destroy();
|
|
2303
|
+
return;
|
|
2304
|
+
}
|
|
2305
|
+
chunks.push(chunk);
|
|
2306
|
+
});
|
|
2307
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
2308
|
+
req.on("error", reject);
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
/** Build the status document (no token material crosses to the browser). */
|
|
2312
|
+
/**
|
|
2313
|
+
* 登录后立刻问一次身份(有超时,失败返回 null)。
|
|
2314
|
+
*
|
|
2315
|
+
* 这一步是「尽量做对」而不是必须:拿不到身份也要能把账号存下来,只是会退回
|
|
2316
|
+
* 「每次登录各自成一条」的旧行为。
|
|
2317
|
+
*/
|
|
2318
|
+
async function probeIdentity(token) {
|
|
2319
|
+
const credential = {
|
|
2320
|
+
token: token.securityToken,
|
|
2321
|
+
accessKeyId: token.accessKeyId,
|
|
2322
|
+
secretAccessKey: token.secretAccessKey,
|
|
2323
|
+
securityToken: token.securityToken
|
|
2324
|
+
};
|
|
2325
|
+
const controller = new AbortController();
|
|
2326
|
+
const timer = setTimeout(() => controller.abort(), IDENTITY_TIMEOUT_MS);
|
|
2327
|
+
timer.unref?.();
|
|
2328
|
+
try {
|
|
2329
|
+
return await fetchCallerIdentity(credential, controller.signal);
|
|
2330
|
+
} catch {
|
|
2331
|
+
return null;
|
|
2332
|
+
} finally {
|
|
2333
|
+
clearTimeout(timer);
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
/**
|
|
2337
|
+
* 落一次 OAuth 登录的凭证。
|
|
2338
|
+
*
|
|
2339
|
+
* 不带 `targetId` 是「添加账号」:同一账号更新,别的账号新增。
|
|
2340
|
+
*
|
|
2341
|
+
* 带 `targetId` 是「重新登录这个账号」:凭证写回原条目(保留 id、展示顺序和
|
|
2342
|
+
* 备注),而不是又长出一条 —— 以前卡片上只有「删除」,用户遇到凭证过期只能
|
|
2343
|
+
* 先把账号删掉再加回来,顺序和备注都丢。
|
|
2344
|
+
*
|
|
2345
|
+
* 上游只在 `fetchCallerIdentity` 成功时才给稳定 `userId`,拿不到身份就判断不了
|
|
2346
|
+
* 「是不是同一个人」。此时按用户意图替换(他点的就是这个账号的重登),并沿用
|
|
2347
|
+
* 旧条目的身份字段;只有两边 `userId` 都非空且不同,才判为登了另一个账号,
|
|
2348
|
+
* 退回「新增」,原账号原样不动。
|
|
2349
|
+
*/
|
|
2350
|
+
async function settleLogin(deps, token, targetId) {
|
|
2351
|
+
const identity = await probeIdentity(token);
|
|
2352
|
+
const target = targetId === void 0 ? void 0 : await deps.store.credential(targetId);
|
|
2353
|
+
if (targetId !== void 0 && target !== void 0) {
|
|
2354
|
+
const known = typeof target.userId === "string" && target.userId !== "";
|
|
2355
|
+
if (!(identity !== null && known && target.userId !== identity.userId)) {
|
|
2356
|
+
const cred = credentialFromOAuth(token, target.label);
|
|
2357
|
+
cred.userId = cred.userId || target.userId;
|
|
2358
|
+
cred.userName = cred.userName || target.userName;
|
|
2359
|
+
cred.domainId = cred.domainId || target.domainId;
|
|
2360
|
+
const id = await deps.store.upsert(cred, targetId);
|
|
2361
|
+
deps.reviveAccount?.(id);
|
|
2362
|
+
if (identity !== null && identity.userId !== "") {
|
|
2363
|
+
if (identity.userId !== id) await deps.store.adoptIdentity(id, identity);
|
|
2364
|
+
deps.reviveAccount?.(identity.userId);
|
|
2365
|
+
return {
|
|
2366
|
+
id: identity.userId,
|
|
2367
|
+
replaced: true,
|
|
2368
|
+
conflict: false
|
|
2369
|
+
};
|
|
2370
|
+
}
|
|
2371
|
+
return {
|
|
2372
|
+
id,
|
|
2373
|
+
replaced: true,
|
|
2374
|
+
conflict: false
|
|
2375
|
+
};
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
const id = await deps.store.upsertFromOAuth(token, void 0, identity ?? void 0);
|
|
2379
|
+
if (identity !== null && id !== identity.userId) await deps.store.adoptIdentity(id, identity);
|
|
2380
|
+
deps.reviveAccount?.(id);
|
|
2381
|
+
if (identity !== null && identity.userId !== id) deps.reviveAccount?.(identity.userId);
|
|
2382
|
+
return {
|
|
2383
|
+
id: identity?.userId ?? id,
|
|
2384
|
+
replaced: false,
|
|
2385
|
+
conflict: target !== void 0
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
/** 账号还能用吗(没被标 stale、也没过期)。 */
|
|
2389
|
+
function accountUsable(summary) {
|
|
2390
|
+
if (summary.stale) return false;
|
|
2391
|
+
if (typeof summary.expiration !== "string") return true;
|
|
2392
|
+
const at = Date.parse(summary.expiration);
|
|
2393
|
+
return !Number.isFinite(at) || at > Date.now();
|
|
2394
|
+
}
|
|
2395
|
+
/** 池状态 -> 卡片能直接渲染的槽位信息。 */
|
|
2396
|
+
function slotsOf(deps) {
|
|
2397
|
+
const runtime = deps.pool?.() ?? [];
|
|
2398
|
+
const now = Date.now();
|
|
2399
|
+
return runtime.map((account) => {
|
|
2400
|
+
const state = account.disabled ? "disabled" : now < account.coolUntil ? "cooling" : now < account.cappedUntil ? "capped" : "ok";
|
|
2401
|
+
const detail = state === "capped" ? `upstream session cap hit; avoiding it for ~${Math.ceil((account.cappedUntil - now) / 1e3)}s` : state === "cooling" ? `cooling down for ~${Math.ceil((account.coolUntil - now) / 1e3)}s` : state === "disabled" ? account.lastError ?? "disabled" : void 0;
|
|
2402
|
+
return {
|
|
2403
|
+
id: account.id,
|
|
2404
|
+
active: account.activeConcurrent,
|
|
2405
|
+
max: account.maxConcurrent,
|
|
2406
|
+
state,
|
|
2407
|
+
...detail === void 0 ? {} : { detail }
|
|
2408
|
+
};
|
|
2409
|
+
});
|
|
2410
|
+
}
|
|
2411
|
+
/** 用量账本 -> 卡片文档;没有账本(未注入)时给一份空壳,卡片就不会瞎显示。 */
|
|
2412
|
+
function usageOf(deps) {
|
|
2413
|
+
const snapshot = deps.usage?.();
|
|
2414
|
+
const noTotals = {
|
|
2415
|
+
requests: 0,
|
|
2416
|
+
promptTokens: 0,
|
|
2417
|
+
completionTokens: 0,
|
|
2418
|
+
totalTokens: 0,
|
|
2419
|
+
cachedTokens: 0,
|
|
2420
|
+
reasoningTokens: 0
|
|
2421
|
+
};
|
|
2422
|
+
return {
|
|
2423
|
+
today: snapshot?.today ?? noTotals,
|
|
2424
|
+
allTime: snapshot?.allTime ?? noTotals,
|
|
2425
|
+
last30: snapshot?.last30 ?? noTotals,
|
|
2426
|
+
byModelToday: snapshot?.byModelToday ?? [],
|
|
2427
|
+
byAccountToday: snapshot?.byAccountToday ?? {},
|
|
2428
|
+
days: snapshot?.days ?? 0,
|
|
2429
|
+
recentDays: snapshot?.recentDays ?? [],
|
|
2430
|
+
todayByHour: snapshot?.todayByHour ?? [],
|
|
2431
|
+
failuresToday: snapshot?.failuresToday ?? {
|
|
2432
|
+
total: 0,
|
|
2433
|
+
byKind: {}
|
|
2434
|
+
},
|
|
2435
|
+
failuresByAccountToday: snapshot?.failuresByAccountToday ?? {},
|
|
2436
|
+
latencyToday: snapshot?.latencyToday ?? {
|
|
2437
|
+
samples: 0,
|
|
2438
|
+
overflow: false
|
|
2439
|
+
},
|
|
2440
|
+
...snapshot?.lastAt === void 0 ? {} : { lastAt: snapshot.lastAt },
|
|
2441
|
+
slots: slotsOf(deps)
|
|
2442
|
+
};
|
|
2443
|
+
}
|
|
2444
|
+
/**
|
|
2445
|
+
* 积分区块。
|
|
2446
|
+
*
|
|
2447
|
+
* 积分是「锦上添花」:拉不到也绝不能把状态接口本身拖垮,所以失败一律降级成
|
|
2448
|
+
* `creditsError` 交给卡片显示原因(超时由注入方在自己的闭包里保证)。
|
|
2449
|
+
*
|
|
2450
|
+
* `force` 是给对话底部弹层那个「刷新积分」按钮用的:不强制的话它会命中 60 秒缓存,
|
|
2451
|
+
* 按钮点了数字不动 —— 那还不如不给这个按钮。
|
|
2452
|
+
*/
|
|
2453
|
+
async function creditsOf(deps, force) {
|
|
2454
|
+
const load = force ? deps.refreshCredits ?? deps.credits : deps.credits;
|
|
2455
|
+
if (load === void 0) return {};
|
|
2456
|
+
try {
|
|
2457
|
+
const entries = await load();
|
|
2458
|
+
const primary = entries.find((entry) => entry.credits !== void 0) ?? entries[0];
|
|
2459
|
+
return {
|
|
2460
|
+
...primary?.credits === void 0 ? {} : { credits: primary.credits },
|
|
2461
|
+
...primary?.credits === void 0 && primary?.creditsError !== void 0 ? { creditsError: primary.creditsError } : {},
|
|
2462
|
+
...entries.length === 0 ? {} : { creditsByAccount: entries }
|
|
2463
|
+
};
|
|
2464
|
+
} catch (error) {
|
|
2465
|
+
return { creditsError: safeMessage(error) };
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
async function buildStatus(deps, force = false) {
|
|
2469
|
+
const models = modelBadgesOf(deps.models());
|
|
2470
|
+
const accounts = await deps.store.list();
|
|
2471
|
+
const cred = await deps.store.current();
|
|
2472
|
+
const usage = usageOf(deps);
|
|
2473
|
+
const dock = deps.dock === void 0 ? {} : { dock: deps.dock() };
|
|
2474
|
+
const keeperView = deps.keeper === void 0 ? {} : { keeper: await deps.keeper() };
|
|
2475
|
+
const piAi = await probePiAiCompat();
|
|
2476
|
+
const compat = piAi === void 0 ? {} : { piAiError: piAi };
|
|
2477
|
+
if (accounts.length === 0 || cred === void 0) return {
|
|
2478
|
+
status: "signed-out",
|
|
2479
|
+
models,
|
|
2480
|
+
accounts,
|
|
2481
|
+
usage,
|
|
2482
|
+
...dock,
|
|
2483
|
+
...keeperView,
|
|
2484
|
+
...compat
|
|
2485
|
+
};
|
|
2486
|
+
const usable = accounts.some(accountUsable);
|
|
2487
|
+
const identity = {
|
|
2488
|
+
...cred.label === void 0 ? {} : { label: cred.label },
|
|
2489
|
+
...cred.storedAt === void 0 ? {} : { storedAt: cred.storedAt },
|
|
2490
|
+
models,
|
|
2491
|
+
accounts,
|
|
2492
|
+
usage,
|
|
2493
|
+
...dock,
|
|
2494
|
+
...keeperView
|
|
2495
|
+
};
|
|
2496
|
+
if (!usable) return {
|
|
2497
|
+
status: "expired",
|
|
2498
|
+
...identity,
|
|
2499
|
+
...compat
|
|
2500
|
+
};
|
|
2501
|
+
return {
|
|
2502
|
+
status: "signed-in",
|
|
2503
|
+
...identity,
|
|
2504
|
+
...compat,
|
|
2505
|
+
...await creditsOf(deps, force)
|
|
2506
|
+
};
|
|
2507
|
+
}
|
|
2508
|
+
/** GET /api/codearts/status */
|
|
2509
|
+
function statusHandler(deps) {
|
|
2510
|
+
return async (req, res) => {
|
|
2511
|
+
if (req.method !== "GET") {
|
|
2512
|
+
json(res, 405, { error: "method not allowed" });
|
|
2513
|
+
return;
|
|
2514
|
+
}
|
|
2515
|
+
if (!loopbackRequest(req)) {
|
|
2516
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2517
|
+
return;
|
|
2518
|
+
}
|
|
2519
|
+
try {
|
|
2520
|
+
json(res, 200, await buildStatus(deps, new URL(req.url ?? "", "http://localhost").searchParams.get("force") === "1"));
|
|
2521
|
+
} catch (error) {
|
|
2522
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2523
|
+
}
|
|
2524
|
+
};
|
|
2525
|
+
}
|
|
2526
|
+
/**
|
|
2527
|
+
* 本机体检:与 CLI 的 `doctor` 同一份判据,但只做不联网的检查。
|
|
2528
|
+
*
|
|
2529
|
+
* 这里的每一项都能在 1ms 内判定;需要网络的(凭证能不能续期、上游目录是否正常)
|
|
2530
|
+
* 已经在 /status 与 /refresh-models 里体现,重复做只会让「体检」按钮转圈。
|
|
2531
|
+
*/
|
|
2532
|
+
async function doctorReport(deps) {
|
|
2533
|
+
const accounts = await deps.store.list();
|
|
2534
|
+
const models = deps.models();
|
|
2535
|
+
const checks = [];
|
|
2536
|
+
const hints = /* @__PURE__ */ new Set();
|
|
2537
|
+
checks.push({
|
|
2538
|
+
id: "runtime",
|
|
2539
|
+
ok: true,
|
|
2540
|
+
detail: `dsh-codearts ${CODEARTS_VERSION} · node ${process.version} · ${process.platform}`
|
|
2541
|
+
});
|
|
2542
|
+
checks.push({
|
|
2543
|
+
id: "accounts",
|
|
2544
|
+
ok: accounts.length > 0,
|
|
2545
|
+
detail: `${accounts.length}`
|
|
2546
|
+
});
|
|
2547
|
+
if (accounts.length === 0) hints.add("no-account");
|
|
2548
|
+
for (const account of accounts) {
|
|
2549
|
+
const problems = [];
|
|
2550
|
+
if (account.stale) problems.push("stale");
|
|
2551
|
+
if (!account.signable) problems.push("no-key");
|
|
2552
|
+
if (account.expiration !== void 0) {
|
|
2553
|
+
const expiresAt = Date.parse(account.expiration);
|
|
2554
|
+
if (!Number.isNaN(expiresAt) && expiresAt <= Date.now()) problems.push("expired");
|
|
2555
|
+
}
|
|
2556
|
+
checks.push({
|
|
2557
|
+
id: `account:${account.id}`,
|
|
2558
|
+
ok: problems.length === 0,
|
|
2559
|
+
detail: problems.length > 0 ? problems.join(",") : account.label ?? account.userName ?? account.expiration ?? "ok"
|
|
2560
|
+
});
|
|
2561
|
+
for (const problem of problems) hints.add(`account-${problem}`);
|
|
2562
|
+
}
|
|
2563
|
+
checks.push({
|
|
2564
|
+
id: "models",
|
|
2565
|
+
ok: models.length > 0,
|
|
2566
|
+
detail: `${models.length}`
|
|
2567
|
+
});
|
|
2568
|
+
if (models.length === 0) hints.add("empty-catalog");
|
|
2569
|
+
const provider = deps.providerStatus?.();
|
|
2570
|
+
if (provider !== void 0) {
|
|
2571
|
+
checks.push({
|
|
2572
|
+
id: "provider",
|
|
2573
|
+
ok: provider.registered,
|
|
2574
|
+
detail: provider.registered ? `registered (stage=${provider.stage})` : `not registered (stage=${provider.stage}${provider.error === void 0 ? "" : `; ${provider.error}`})`
|
|
2575
|
+
});
|
|
2576
|
+
if (!provider.registered) hints.add("provider-not-registered");
|
|
2577
|
+
}
|
|
2578
|
+
checks.push({
|
|
2579
|
+
id: "usage",
|
|
2580
|
+
ok: deps.usage !== void 0,
|
|
2581
|
+
detail: deps.usage === void 0 ? "tracker not wired" : "local ledger"
|
|
2582
|
+
});
|
|
2583
|
+
if (deps.usage === void 0) hints.add("usage-missing");
|
|
2584
|
+
if (process.env.DSH_HOME === void 0) hints.add("dsh-home-missing");
|
|
2585
|
+
const piAi = await probePiAiCompat();
|
|
2586
|
+
checks.push({
|
|
2587
|
+
id: "pi-ai",
|
|
2588
|
+
ok: piAi === void 0,
|
|
2589
|
+
...piAi === void 0 ? {} : { detail: piAi }
|
|
2590
|
+
});
|
|
2591
|
+
if (piAi !== void 0) hints.add("pi-ai");
|
|
2592
|
+
return {
|
|
2593
|
+
ok: checks.every((check) => check.ok),
|
|
2594
|
+
version: CODEARTS_VERSION,
|
|
2595
|
+
node: process.version,
|
|
2596
|
+
checks,
|
|
2597
|
+
hints: [...hints]
|
|
2598
|
+
};
|
|
2599
|
+
}
|
|
2600
|
+
/** GET /api/codearts/doctor */
|
|
2601
|
+
function doctorHandler(deps) {
|
|
2602
|
+
return async (req, res) => {
|
|
2603
|
+
if (req.method !== "GET") {
|
|
2604
|
+
json(res, 405, { error: "method not allowed" });
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
if (!loopbackRequest(req)) {
|
|
2608
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2609
|
+
return;
|
|
2610
|
+
}
|
|
2611
|
+
try {
|
|
2612
|
+
json(res, 200, await doctorReport(deps));
|
|
2613
|
+
} catch (error) {
|
|
2614
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2615
|
+
}
|
|
2616
|
+
};
|
|
2617
|
+
}
|
|
2618
|
+
/**
|
|
2619
|
+
* GET/POST /api/codearts/dock — 对话底部那一行的显隐开关读写。
|
|
2620
|
+
*
|
|
2621
|
+
* 和 enabled-models 同一套规矩:GET 给当前值 + writable,POST 只收布尔、
|
|
2622
|
+
* 没接 settings provider 时回 403 让卡片把勾选框置灰。
|
|
2623
|
+
*/
|
|
2624
|
+
function dockHandler(deps) {
|
|
2625
|
+
return async (req, res) => {
|
|
2626
|
+
if (!loopbackRequest(req)) {
|
|
2627
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2628
|
+
return;
|
|
2629
|
+
}
|
|
2630
|
+
const current = deps.dock?.() ?? DEFAULT_DOCK_FLAGS;
|
|
2631
|
+
if (req.method === "GET") {
|
|
2632
|
+
json(res, 200, {
|
|
2633
|
+
dock: current,
|
|
2634
|
+
writable: deps.setDock !== void 0
|
|
2635
|
+
});
|
|
2636
|
+
return;
|
|
2637
|
+
}
|
|
2638
|
+
if (req.method === "POST") {
|
|
2639
|
+
if (deps.setDock === void 0) {
|
|
2640
|
+
json(res, 403, { error: "dock-not-writable" });
|
|
2641
|
+
return;
|
|
2642
|
+
}
|
|
2643
|
+
const type = req.headers["content-type"];
|
|
2644
|
+
if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
|
|
2645
|
+
json(res, 415, { error: "content-type must be application/json" });
|
|
2646
|
+
return;
|
|
2647
|
+
}
|
|
2648
|
+
try {
|
|
2649
|
+
const body = JSON.parse(await readBody(req));
|
|
2650
|
+
const touched = [
|
|
2651
|
+
"credits",
|
|
2652
|
+
"queue",
|
|
2653
|
+
"sidebar",
|
|
2654
|
+
"settingsEntry",
|
|
2655
|
+
"modelDetail",
|
|
2656
|
+
"autoClaim",
|
|
2657
|
+
"keepAliveDaemon",
|
|
2658
|
+
"queueWait"
|
|
2659
|
+
].filter((key) => body[key] !== void 0);
|
|
2660
|
+
if (touched.length === 0 || touched.some((key) => typeof body[key] !== "boolean")) {
|
|
2661
|
+
json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"settingsEntry\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean, \"queueWait\"?: boolean}" });
|
|
2662
|
+
return;
|
|
2663
|
+
}
|
|
2664
|
+
if (!await deps.setDock(Object.fromEntries(touched.map((key) => [key, body[key]])))) {
|
|
2665
|
+
json(res, 403, { error: "dock-not-writable" });
|
|
2666
|
+
return;
|
|
2667
|
+
}
|
|
2668
|
+
json(res, 200, {
|
|
2669
|
+
dock: deps.dock?.() ?? DEFAULT_DOCK_FLAGS,
|
|
2670
|
+
writable: true
|
|
2671
|
+
});
|
|
2672
|
+
} catch (error) {
|
|
2673
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2674
|
+
}
|
|
2675
|
+
return;
|
|
2676
|
+
}
|
|
2677
|
+
json(res, 405, { error: "method not allowed" });
|
|
2678
|
+
};
|
|
2679
|
+
}
|
|
2680
|
+
/**
|
|
2681
|
+
* POST /api/codearts/keeper/stop — 结束守护进程,并把开关一起关掉。
|
|
2682
|
+
*
|
|
2683
|
+
* 顺序不能反:先杀进程、再写开关。反过来的话,写开关的那一瞬间如果正好触发了插件的
|
|
2684
|
+
* 重排(`armKeepAliveDaemon`),它会按「开关是开的」再起一个 —— 用户点一次结束,
|
|
2685
|
+
* 结果又冒出来一个新 pid。杀完再写,重排看到的是 false,自然什么都不做。
|
|
2686
|
+
*/
|
|
2687
|
+
function keeperStopHandler(deps) {
|
|
2688
|
+
return async (req, res) => {
|
|
2689
|
+
if (!loopbackRequest(req)) {
|
|
2690
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2691
|
+
return;
|
|
2692
|
+
}
|
|
2693
|
+
if (req.method !== "POST") {
|
|
2694
|
+
json(res, 405, { error: "method not allowed" });
|
|
2695
|
+
return;
|
|
2696
|
+
}
|
|
2697
|
+
if (deps.stopKeeper === void 0) {
|
|
2698
|
+
json(res, 503, { error: "keeper-control-unavailable" });
|
|
2699
|
+
return;
|
|
2700
|
+
}
|
|
2701
|
+
try {
|
|
2702
|
+
const outcome = await deps.stopKeeper();
|
|
2703
|
+
const writable = deps.setDock === void 0 ? false : await deps.setDock({ keepAliveDaemon: false }).catch(() => false);
|
|
2704
|
+
json(res, outcome.ok ? 200 : 500, {
|
|
2705
|
+
ok: outcome.ok,
|
|
2706
|
+
...outcome.pid === void 0 ? {} : { pid: outcome.pid },
|
|
2707
|
+
...outcome.reason === void 0 ? {} : { reason: outcome.reason },
|
|
2708
|
+
writable,
|
|
2709
|
+
dock: deps.dock?.() ?? DEFAULT_DOCK_FLAGS
|
|
2710
|
+
});
|
|
2711
|
+
} catch (error) {
|
|
2712
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2713
|
+
}
|
|
2714
|
+
};
|
|
2715
|
+
}
|
|
2716
|
+
/** GET /api/codearts/models — currently offered model ids (honours allowlist). */
|
|
2717
|
+
function modelsHandler(deps) {
|
|
2718
|
+
return async (req, res) => {
|
|
2719
|
+
if (req.method !== "GET") {
|
|
2720
|
+
json(res, 405, { error: "method not allowed" });
|
|
2721
|
+
return;
|
|
2722
|
+
}
|
|
2723
|
+
if (!loopbackRequest(req)) {
|
|
2724
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2725
|
+
return;
|
|
2726
|
+
}
|
|
2727
|
+
json(res, 200, { models: modelBadgesOf(filterEnabledModels(deps.models(), deps.enabledModels?.())) });
|
|
2728
|
+
};
|
|
2729
|
+
}
|
|
2730
|
+
/**
|
|
2731
|
+
* GET/POST /api/codearts/enabled-models — 模型勾选的读写。
|
|
2732
|
+
* GET 返回 selection(choices + restricted + writable);POST 接收 {enabledModels}
|
|
2733
|
+
* 写入 settings(全选时传空数组表示"全部")。与 codebuddy 的 /plugins/<id>/enabled-models 对齐。
|
|
2734
|
+
*/
|
|
2735
|
+
function modelsSelectionHandler(deps) {
|
|
2736
|
+
return async (req, res) => {
|
|
2737
|
+
if (!loopbackRequest(req)) {
|
|
2738
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2739
|
+
return;
|
|
2740
|
+
}
|
|
2741
|
+
if (req.method === "GET") {
|
|
2742
|
+
const all = choicesOf(deps);
|
|
2743
|
+
const writable = deps.setEnabledModels !== void 0;
|
|
2744
|
+
json(res, 200, { selection: selectionOf(all, deps.enabledModels?.(), writable) });
|
|
2745
|
+
return;
|
|
2746
|
+
}
|
|
2747
|
+
if (req.method === "POST") {
|
|
2748
|
+
if (!deps.setEnabledModels) {
|
|
2749
|
+
json(res, 403, { error: "selection-not-writable" });
|
|
2750
|
+
return;
|
|
2751
|
+
}
|
|
2752
|
+
const type = req.headers["content-type"];
|
|
2753
|
+
if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
|
|
2754
|
+
json(res, 415, { error: "content-type must be application/json" });
|
|
2755
|
+
return;
|
|
2756
|
+
}
|
|
2757
|
+
try {
|
|
2758
|
+
const body = JSON.parse(await readBody(req));
|
|
2759
|
+
if (!Array.isArray(body.enabledModels) || !body.enabledModels.every((x) => typeof x === "string")) {
|
|
2760
|
+
json(res, 400, { error: "expected {\"enabledModels\": string[]}" });
|
|
2761
|
+
return;
|
|
2762
|
+
}
|
|
2763
|
+
if (!await deps.setEnabledModels(body.enabledModels)) {
|
|
2764
|
+
json(res, 403, { error: "selection-not-writable" });
|
|
2765
|
+
return;
|
|
2766
|
+
}
|
|
2767
|
+
json(res, 200, { selection: selectionOf(choicesOf(deps), deps.enabledModels?.(), true) });
|
|
2768
|
+
} catch (error) {
|
|
2769
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2770
|
+
}
|
|
2771
|
+
return;
|
|
2772
|
+
}
|
|
2773
|
+
json(res, 405, { error: "method not allowed" });
|
|
2774
|
+
};
|
|
2775
|
+
}
|
|
2776
|
+
/**
|
|
2777
|
+
* POST /api/codearts/context-window { id, window } — 按模型覆盖上下文窗口。
|
|
2778
|
+
*
|
|
2779
|
+
* 存在的理由(issue #9):目录给的是上游标称窗口,免费档实际能装下的往往差一半,
|
|
2780
|
+
* 而超限时上游只回一句「参数非法」、不指名参数。`window: null` 删除覆盖、回到跟随上游。
|
|
2781
|
+
*/
|
|
2782
|
+
function contextWindowHandler(deps) {
|
|
2783
|
+
return async (req, res) => {
|
|
2784
|
+
if (req.method !== "POST") {
|
|
2785
|
+
json(res, 405, { error: "method not allowed" });
|
|
2786
|
+
return;
|
|
2787
|
+
}
|
|
2788
|
+
if (!loopbackRequest(req)) {
|
|
2789
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2790
|
+
return;
|
|
2791
|
+
}
|
|
2792
|
+
if (deps.setContextWindowOverride === void 0) {
|
|
2793
|
+
json(res, 403, { error: "context-window-not-writable" });
|
|
2794
|
+
return;
|
|
2795
|
+
}
|
|
2796
|
+
const type = req.headers["content-type"];
|
|
2797
|
+
if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
|
|
2798
|
+
json(res, 415, { error: "content-type must be application/json" });
|
|
2799
|
+
return;
|
|
2800
|
+
}
|
|
2801
|
+
try {
|
|
2802
|
+
const body = JSON.parse(await readBody(req));
|
|
2803
|
+
const id = typeof body.id === "string" ? body.id.trim() : "";
|
|
2804
|
+
if (id === "") {
|
|
2805
|
+
json(res, 400, { error: "expected {\"id\": string, \"window\": number|null}" });
|
|
2806
|
+
return;
|
|
2807
|
+
}
|
|
2808
|
+
let window = null;
|
|
2809
|
+
if (body.window !== null && body.window !== void 0) {
|
|
2810
|
+
if (typeof body.window !== "number" || !Number.isFinite(body.window) || body.window <= 0) {
|
|
2811
|
+
json(res, 400, { error: "window must be a positive number or null" });
|
|
2812
|
+
return;
|
|
2813
|
+
}
|
|
2814
|
+
window = Math.floor(body.window);
|
|
2815
|
+
}
|
|
2816
|
+
if (!await deps.setContextWindowOverride(id, window)) {
|
|
2817
|
+
json(res, 403, { error: "context-window-not-writable" });
|
|
2818
|
+
return;
|
|
2819
|
+
}
|
|
2820
|
+
json(res, 200, { selection: selectionOf(choicesOf(deps), deps.enabledModels?.(), true) });
|
|
2821
|
+
} catch (error) {
|
|
2822
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2823
|
+
}
|
|
2824
|
+
};
|
|
2825
|
+
}
|
|
2826
|
+
/**
|
|
2827
|
+
* POST /api/codearts/max-tokens { id, tokens } — 按模型覆盖输出上限(issue #15)。
|
|
2828
|
+
*
|
|
2829
|
+
* 存在的理由:企业自定义模型实测能到 128K,而插件全局天花板是 65536(对福利模型
|
|
2830
|
+
* 实测的保守值),两道 `min` 把覆盖值压回去,手动设置就没意义。`tokens: null`
|
|
2831
|
+
* 删除覆盖、回到跟随上游(目录声明值)。
|
|
2832
|
+
*/
|
|
2833
|
+
function maxTokensHandler(deps) {
|
|
2834
|
+
return async (req, res) => {
|
|
2835
|
+
if (req.method !== "POST") {
|
|
2836
|
+
json(res, 405, { error: "method not allowed" });
|
|
2837
|
+
return;
|
|
2838
|
+
}
|
|
2839
|
+
if (!loopbackRequest(req)) {
|
|
2840
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2841
|
+
return;
|
|
2842
|
+
}
|
|
2843
|
+
if (deps.setMaxTokensOverride === void 0) {
|
|
2844
|
+
json(res, 403, { error: "max-tokens-not-writable" });
|
|
2845
|
+
return;
|
|
2846
|
+
}
|
|
2847
|
+
const type = req.headers["content-type"];
|
|
2848
|
+
if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
|
|
2849
|
+
json(res, 415, { error: "content-type must be application/json" });
|
|
2850
|
+
return;
|
|
2851
|
+
}
|
|
2852
|
+
try {
|
|
2853
|
+
const body = JSON.parse(await readBody(req));
|
|
2854
|
+
const id = typeof body.id === "string" ? body.id.trim() : "";
|
|
2855
|
+
if (id === "") {
|
|
2856
|
+
json(res, 400, { error: "expected {\"id\": string, \"tokens\": number|null}" });
|
|
2857
|
+
return;
|
|
2858
|
+
}
|
|
2859
|
+
let tokens = null;
|
|
2860
|
+
if (body.tokens !== null && body.tokens !== void 0) {
|
|
2861
|
+
if (typeof body.tokens !== "number" || !Number.isFinite(body.tokens) || body.tokens <= 0) {
|
|
2862
|
+
json(res, 400, { error: "tokens must be a positive number or null" });
|
|
2863
|
+
return;
|
|
2864
|
+
}
|
|
2865
|
+
tokens = Math.floor(body.tokens);
|
|
2866
|
+
}
|
|
2867
|
+
if (!await deps.setMaxTokensOverride(id, tokens)) {
|
|
2868
|
+
json(res, 403, { error: "max-tokens-not-writable" });
|
|
2869
|
+
return;
|
|
2870
|
+
}
|
|
2871
|
+
json(res, 200, { selection: selectionOf(choicesOf(deps), deps.enabledModels?.(), true) });
|
|
2872
|
+
} catch (error) {
|
|
2873
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2874
|
+
}
|
|
2875
|
+
};
|
|
2876
|
+
}
|
|
2877
|
+
/**
|
|
2878
|
+
* GET/POST /api/codearts/concurrency — 每个账号各自的并发上限(issue #16)。
|
|
2879
|
+
*
|
|
2880
|
+
* 上游会话槽位按账号算(个人 3 / 企业 5),所以上限也按账号设:`caps` 里的号用自己的,
|
|
2881
|
+
* 其余用 `default`。POST 只收 `{ id, value }`,`value: null` = 删掉覆盖、回到默认。
|
|
2882
|
+
* 真正的钳制与热更新在 `index.ts`(池逐账号改上限并唤醒等槽请求)。
|
|
2883
|
+
*/
|
|
2884
|
+
function concurrencyHandler(deps) {
|
|
2885
|
+
const snapshot = () => deps.concurrency?.() ?? {
|
|
2886
|
+
default: 2,
|
|
2887
|
+
caps: {}
|
|
2888
|
+
};
|
|
2889
|
+
return async (req, res) => {
|
|
2890
|
+
if (!loopbackRequest(req)) {
|
|
2891
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2892
|
+
return;
|
|
2893
|
+
}
|
|
2894
|
+
if (req.method === "GET") {
|
|
2895
|
+
const current = snapshot();
|
|
2896
|
+
json(res, 200, {
|
|
2897
|
+
default: current.default,
|
|
2898
|
+
caps: current.caps,
|
|
2899
|
+
writable: deps.setAccountConcurrency !== void 0
|
|
2900
|
+
});
|
|
2901
|
+
return;
|
|
2902
|
+
}
|
|
2903
|
+
if (req.method === "POST") {
|
|
2904
|
+
if (deps.setAccountConcurrency === void 0) {
|
|
2905
|
+
json(res, 403, { error: "concurrency-not-writable" });
|
|
2906
|
+
return;
|
|
2907
|
+
}
|
|
2908
|
+
const type = req.headers["content-type"];
|
|
2909
|
+
if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
|
|
2910
|
+
json(res, 415, { error: "content-type must be application/json" });
|
|
2911
|
+
return;
|
|
2912
|
+
}
|
|
2913
|
+
try {
|
|
2914
|
+
const body = JSON.parse(await readBody(req));
|
|
2915
|
+
const id = typeof body.id === "string" ? body.id.trim() : "";
|
|
2916
|
+
if (id === "") {
|
|
2917
|
+
json(res, 400, { error: "expected {\"id\": string, \"value\": number|null}" });
|
|
2918
|
+
return;
|
|
2919
|
+
}
|
|
2920
|
+
let value = null;
|
|
2921
|
+
if (body.value !== null && body.value !== void 0) {
|
|
2922
|
+
if (typeof body.value !== "number" || !Number.isInteger(body.value) || body.value < 1 || body.value > 16) {
|
|
2923
|
+
json(res, 400, { error: "value must be an integer between 1 and 16, or null" });
|
|
2924
|
+
return;
|
|
2925
|
+
}
|
|
2926
|
+
value = body.value;
|
|
2927
|
+
}
|
|
2928
|
+
if (!await deps.setAccountConcurrency(id, value)) {
|
|
2929
|
+
json(res, 403, { error: "concurrency-not-writable" });
|
|
2930
|
+
return;
|
|
2931
|
+
}
|
|
2932
|
+
const current = snapshot();
|
|
2933
|
+
json(res, 200, {
|
|
2934
|
+
default: current.default,
|
|
2935
|
+
caps: current.caps,
|
|
2936
|
+
writable: true
|
|
2937
|
+
});
|
|
2938
|
+
} catch (error) {
|
|
2939
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2940
|
+
}
|
|
2941
|
+
return;
|
|
2942
|
+
}
|
|
2943
|
+
json(res, 405, { error: "method not allowed" });
|
|
2944
|
+
};
|
|
2945
|
+
}
|
|
2946
|
+
/** POST /api/codearts/token { token, label? } — store a pasted token. */
|
|
2947
|
+
function tokenPostHandler(deps) {
|
|
2948
|
+
return async (req, res) => {
|
|
2949
|
+
if (req.method !== "POST") {
|
|
2950
|
+
json(res, 405, { error: "method not allowed" });
|
|
2951
|
+
return;
|
|
2952
|
+
}
|
|
2953
|
+
if (!loopbackRequest(req)) {
|
|
2954
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2955
|
+
return;
|
|
2956
|
+
}
|
|
2957
|
+
const type = req.headers["content-type"];
|
|
2958
|
+
if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
|
|
2959
|
+
json(res, 415, { error: "content-type must be application/json" });
|
|
2960
|
+
return;
|
|
2961
|
+
}
|
|
2962
|
+
try {
|
|
2963
|
+
const body = JSON.parse(await readBody(req));
|
|
2964
|
+
const token = typeof body?.token === "string" ? body.token.trim() : "";
|
|
2965
|
+
if (token === "") {
|
|
2966
|
+
json(res, 400, { error: "expected {\"token\": string}" });
|
|
2967
|
+
return;
|
|
2968
|
+
}
|
|
2969
|
+
const label = typeof body?.label === "string" && body.label.trim() !== "" ? body.label.trim() : void 0;
|
|
2970
|
+
await deps.store.set(token, label);
|
|
2971
|
+
deps.reviveAccount?.(MANUAL_ACCOUNT_ID);
|
|
2972
|
+
json(res, 200, await buildStatus(deps));
|
|
2973
|
+
} catch (error) {
|
|
2974
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2975
|
+
}
|
|
2976
|
+
};
|
|
2977
|
+
}
|
|
2978
|
+
/** DELETE /api/codearts/token — forget the stored token. */
|
|
2979
|
+
function tokenDeleteHandler(deps) {
|
|
2980
|
+
return async (req, res) => {
|
|
2981
|
+
if (req.method !== "DELETE") {
|
|
2982
|
+
json(res, 405, { error: "method not allowed" });
|
|
2983
|
+
return;
|
|
2984
|
+
}
|
|
2985
|
+
if (!loopbackRequest(req)) {
|
|
2986
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
2987
|
+
return;
|
|
2988
|
+
}
|
|
2989
|
+
try {
|
|
2990
|
+
await deps.store.clear();
|
|
2991
|
+
json(res, 200, await buildStatus(deps));
|
|
2992
|
+
} catch (error) {
|
|
2993
|
+
json(res, 500, { error: safeMessage(error) });
|
|
2994
|
+
}
|
|
2995
|
+
};
|
|
2996
|
+
}
|
|
2997
|
+
/**
|
|
2998
|
+
* DELETE /api/codearts/accounts?id=<accountId> — 删掉一个账号。
|
|
2999
|
+
* POST /api/codearts/accounts — 改账号标记:`{ id, paused?, pinned? }`。
|
|
3000
|
+
*
|
|
3001
|
+
* id 必须显式给:多账号下「删掉当前那个」是歧义的。改状态的路由,所以和
|
|
3002
|
+
* /token 一样走 Host + Origin 双校验。
|
|
3003
|
+
*/
|
|
3004
|
+
function accountsHandler(deps) {
|
|
3005
|
+
return async (req, res) => {
|
|
3006
|
+
if (req.method !== "DELETE" && req.method !== "POST") {
|
|
3007
|
+
json(res, 405, { error: "method not allowed" });
|
|
3008
|
+
return;
|
|
3009
|
+
}
|
|
3010
|
+
if (!loopbackRequest(req)) {
|
|
3011
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3012
|
+
return;
|
|
3013
|
+
}
|
|
3014
|
+
const url = new URL(req.url ?? "", "http://localhost");
|
|
3015
|
+
try {
|
|
3016
|
+
if (req.method === "POST") {
|
|
3017
|
+
const type = req.headers["content-type"];
|
|
3018
|
+
if (typeof type !== "string" || !type.trim().toLowerCase().startsWith("application/json")) {
|
|
3019
|
+
json(res, 415, { error: "content-type must be application/json" });
|
|
3020
|
+
return;
|
|
3021
|
+
}
|
|
3022
|
+
const body = JSON.parse(await readBody(req));
|
|
3023
|
+
const id = typeof body.id === "string" ? body.id.trim() : "";
|
|
3024
|
+
if (id === "") {
|
|
3025
|
+
json(res, 400, { error: "expected {\"id\": string}" });
|
|
3026
|
+
return;
|
|
3027
|
+
}
|
|
3028
|
+
let changed = false;
|
|
3029
|
+
if (typeof body.paused === "boolean") {
|
|
3030
|
+
if (!await deps.store.setPaused(id, body.paused)) {
|
|
3031
|
+
json(res, 404, { error: "unknown account" });
|
|
3032
|
+
return;
|
|
3033
|
+
}
|
|
3034
|
+
changed = true;
|
|
3035
|
+
}
|
|
3036
|
+
if (typeof body.pinned === "boolean") {
|
|
3037
|
+
if (!await deps.store.setPinned(id, body.pinned)) {
|
|
3038
|
+
json(res, 404, { error: "unknown account" });
|
|
3039
|
+
return;
|
|
3040
|
+
}
|
|
3041
|
+
changed = true;
|
|
3042
|
+
}
|
|
3043
|
+
if (!changed) {
|
|
3044
|
+
json(res, 400, { error: "expected paused and/or pinned boolean" });
|
|
3045
|
+
return;
|
|
3046
|
+
}
|
|
3047
|
+
json(res, 200, await buildStatus(deps));
|
|
3048
|
+
return;
|
|
3049
|
+
}
|
|
3050
|
+
const id = (url.searchParams.get("id") ?? "").trim();
|
|
3051
|
+
if (id === "") {
|
|
3052
|
+
json(res, 400, { error: "expected ?id=<accountId>" });
|
|
3053
|
+
return;
|
|
3054
|
+
}
|
|
3055
|
+
await deps.store.remove(id);
|
|
3056
|
+
json(res, 200, await buildStatus(deps));
|
|
3057
|
+
} catch (error) {
|
|
3058
|
+
json(res, 500, { error: safeMessage(error) });
|
|
3059
|
+
}
|
|
3060
|
+
};
|
|
3061
|
+
}
|
|
3062
|
+
/** POST /api/codearts/claim — 领一次每日签到积分;未领到也回 200(看 claimed/state)。 */
|
|
3063
|
+
function claimHandler(deps) {
|
|
3064
|
+
return async (req, res) => {
|
|
3065
|
+
if (req.method !== "POST") {
|
|
3066
|
+
json(res, 405, { error: "method not allowed" });
|
|
3067
|
+
return;
|
|
3068
|
+
}
|
|
3069
|
+
if (deps.claim === void 0) {
|
|
3070
|
+
json(res, 404, { error: "claim not available" });
|
|
3071
|
+
return;
|
|
3072
|
+
}
|
|
3073
|
+
if (!loopbackRequest(req)) {
|
|
3074
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3075
|
+
return;
|
|
3076
|
+
}
|
|
3077
|
+
let accountId;
|
|
3078
|
+
const type = req.headers["content-type"];
|
|
3079
|
+
if (typeof type === "string" && type.trim().toLowerCase().startsWith("application/json")) try {
|
|
3080
|
+
const body = JSON.parse(await readBody(req));
|
|
3081
|
+
if (typeof body?.id === "string" && body.id.trim() !== "") accountId = body.id.trim();
|
|
3082
|
+
} catch {
|
|
3083
|
+
json(res, 400, { error: "expected {\"id\"?: string}" });
|
|
3084
|
+
return;
|
|
3085
|
+
}
|
|
3086
|
+
try {
|
|
3087
|
+
const result = await deps.claim(accountId);
|
|
3088
|
+
json(res, result.ok ? 200 : 500, result);
|
|
3089
|
+
} catch (error) {
|
|
3090
|
+
json(res, 500, {
|
|
3091
|
+
ok: false,
|
|
3092
|
+
claimed: false,
|
|
3093
|
+
state: "failed",
|
|
3094
|
+
amount: 0,
|
|
3095
|
+
message: safeMessage(error)
|
|
3096
|
+
});
|
|
3097
|
+
}
|
|
3098
|
+
};
|
|
3099
|
+
}
|
|
3100
|
+
/**
|
|
3101
|
+
* POST /api/codearts/refresh-models — 立刻重拉目录,并清掉「福利今日不可用」标记。
|
|
3102
|
+
*
|
|
3103
|
+
* 清标记放在拉目录**之前**:福利回来时这是唯一的自救出口,不能让用户等到明天。
|
|
3104
|
+
* 代价是「今天确实领完了」的那种缺失也会被一并清掉,再点一次就重新记上。
|
|
3105
|
+
*/
|
|
3106
|
+
function refreshModelsHandler(deps) {
|
|
3107
|
+
return async (req, res) => {
|
|
3108
|
+
if (req.method !== "POST") {
|
|
3109
|
+
json(res, 405, { error: "method not allowed" });
|
|
3110
|
+
return;
|
|
3111
|
+
}
|
|
3112
|
+
if (!loopbackRequest(req)) {
|
|
3113
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3114
|
+
return;
|
|
3115
|
+
}
|
|
3116
|
+
if (deps.refreshModels === void 0) {
|
|
3117
|
+
json(res, 404, { error: "refresh not available" });
|
|
3118
|
+
return;
|
|
3119
|
+
}
|
|
3120
|
+
try {
|
|
3121
|
+
clearBenefitBlocked();
|
|
3122
|
+
const counted = await deps.refreshModels();
|
|
3123
|
+
const selection = selectionOf(choicesOf(deps), deps.enabledModels?.(), deps.setEnabledModels !== void 0);
|
|
3124
|
+
json(res, 200, {
|
|
3125
|
+
ok: true,
|
|
3126
|
+
...counted,
|
|
3127
|
+
selection
|
|
3128
|
+
});
|
|
3129
|
+
} catch (error) {
|
|
3130
|
+
json(res, 500, {
|
|
3131
|
+
ok: false,
|
|
3132
|
+
message: safeMessage(error)
|
|
3133
|
+
});
|
|
3134
|
+
}
|
|
3135
|
+
};
|
|
3136
|
+
}
|
|
3137
|
+
/**
|
|
3138
|
+
* 逐账号发一次最小聊天,验证模型**真的能调用**(清单里有 ≠ 能调)。
|
|
3139
|
+
*
|
|
3140
|
+
* 只发一句 ping、max_tokens 16:目的是让上游过一遍权限与路由检查,不是拿内容。
|
|
3141
|
+
* 必须逐账号试 —— 池里的正常请求也是这么轮的;只测第一个号会把「这个号没权限」
|
|
3142
|
+
* 误报成「模型不可用」。
|
|
3143
|
+
*/
|
|
3144
|
+
async function probeModel(deps, id, signal) {
|
|
3145
|
+
const ids = await deps.store.ids();
|
|
3146
|
+
if (ids.length === 0) return {
|
|
3147
|
+
ok: false,
|
|
3148
|
+
message: "没有已登录的账号,请先在设置卡片登录。"
|
|
3149
|
+
};
|
|
3150
|
+
const raw = JSON.stringify({
|
|
3151
|
+
model: id,
|
|
3152
|
+
stream: true,
|
|
3153
|
+
max_tokens: 16,
|
|
3154
|
+
messages: [{
|
|
3155
|
+
role: "user",
|
|
3156
|
+
content: "ping"
|
|
3157
|
+
}]
|
|
3158
|
+
});
|
|
3159
|
+
let last = "没有可用的账号";
|
|
3160
|
+
for (const accountId of ids.slice(0, 3)) {
|
|
3161
|
+
if (signal.aborted) break;
|
|
3162
|
+
const credential = await deps.store.resolve(accountId);
|
|
3163
|
+
if (credential === void 0) {
|
|
3164
|
+
last = "凭据不可用,请重新登录";
|
|
3165
|
+
continue;
|
|
3166
|
+
}
|
|
3167
|
+
const result = await chatStream(credential, prepareChatBody(raw), signal);
|
|
3168
|
+
if (!result.ok) {
|
|
3169
|
+
last = upstreamErrorMessage(result.message, result.status);
|
|
3170
|
+
if (result.kind === "iam_stale") await deps.store.forceRefresh(accountId, credential.token).catch(() => void 0);
|
|
3171
|
+
continue;
|
|
3172
|
+
}
|
|
3173
|
+
const reader = result.stream.getReader();
|
|
3174
|
+
try {
|
|
3175
|
+
for (let frame = 0; frame < 6; frame += 1) {
|
|
3176
|
+
const next = await reader.read();
|
|
3177
|
+
if (next.done) return {
|
|
3178
|
+
ok: true,
|
|
3179
|
+
message: "上游已响应",
|
|
3180
|
+
accountId
|
|
3181
|
+
};
|
|
3182
|
+
const text = new TextDecoder().decode(next.value);
|
|
3183
|
+
const error = firstFrameError(text);
|
|
3184
|
+
if (error !== void 0) {
|
|
3185
|
+
const detail = `${error.code}: ${error.message}`.replace(/^: /, "");
|
|
3186
|
+
if (isModelNotAccessible(detail)) markModelUnavailable(id, modelUnavailableReasonText(detail));
|
|
3187
|
+
return {
|
|
3188
|
+
ok: false,
|
|
3189
|
+
message: upstreamErrorMessage(detail),
|
|
3190
|
+
accountId
|
|
3191
|
+
};
|
|
3192
|
+
}
|
|
3193
|
+
if (text.includes("\"choices\"")) return {
|
|
3194
|
+
ok: true,
|
|
3195
|
+
message: "上游正常响应",
|
|
3196
|
+
accountId
|
|
3197
|
+
};
|
|
3198
|
+
}
|
|
3199
|
+
return {
|
|
3200
|
+
ok: true,
|
|
3201
|
+
message: "上游已开流",
|
|
3202
|
+
accountId
|
|
3203
|
+
};
|
|
3204
|
+
} finally {
|
|
3205
|
+
await reader.cancel().catch(() => void 0);
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
return {
|
|
3209
|
+
ok: false,
|
|
3210
|
+
message: last
|
|
3211
|
+
};
|
|
3212
|
+
}
|
|
3213
|
+
/**
|
|
3214
|
+
* POST /api/codearts/test-model — 实测一个模型现在能不能调用。
|
|
3215
|
+
*
|
|
3216
|
+
* 成功会清掉它的「异常」标记(测试就是重新验证一次);`81003.401` 会重新记上。
|
|
3217
|
+
* 失败也可能只是撞了并发上限/限流,所以除模型级错误外不动标记。
|
|
3218
|
+
*/
|
|
3219
|
+
function testModelHandler(deps) {
|
|
3220
|
+
return async (req, res) => {
|
|
3221
|
+
if (req.method !== "POST") {
|
|
3222
|
+
json(res, 405, { error: "method not allowed" });
|
|
3223
|
+
return;
|
|
3224
|
+
}
|
|
3225
|
+
if (!loopbackRequest(req)) {
|
|
3226
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3227
|
+
return;
|
|
3228
|
+
}
|
|
3229
|
+
let id = "";
|
|
3230
|
+
try {
|
|
3231
|
+
const body = JSON.parse(await readBody(req));
|
|
3232
|
+
if (typeof body.id === "string") id = body.id.trim();
|
|
3233
|
+
} catch {
|
|
3234
|
+
json(res, 400, { error: "expected {\"id\": string}" });
|
|
3235
|
+
return;
|
|
3236
|
+
}
|
|
3237
|
+
if (id === "") {
|
|
3238
|
+
json(res, 400, { error: "expected {\"id\": string}" });
|
|
3239
|
+
return;
|
|
3240
|
+
}
|
|
3241
|
+
if (!deps.models().some((model) => model.id === id)) {
|
|
3242
|
+
json(res, 404, { error: `unknown model: ${id}` });
|
|
3243
|
+
return;
|
|
3244
|
+
}
|
|
3245
|
+
const started = Date.now();
|
|
3246
|
+
try {
|
|
3247
|
+
const result = await probeModel(deps, id, AbortSignal.timeout(45e3));
|
|
3248
|
+
if (result.ok) forgetModelUnavailable(id);
|
|
3249
|
+
json(res, 200, {
|
|
3250
|
+
...result,
|
|
3251
|
+
ms: Date.now() - started
|
|
3252
|
+
});
|
|
3253
|
+
} catch (error) {
|
|
3254
|
+
json(res, 200, {
|
|
3255
|
+
ok: false,
|
|
3256
|
+
message: safeMessage(error),
|
|
3257
|
+
ms: Date.now() - started
|
|
3258
|
+
});
|
|
3259
|
+
}
|
|
3260
|
+
};
|
|
3261
|
+
}
|
|
3262
|
+
/** GET /api/codearts/queue — 排队位置快照(无跟踪器/无排队时给空数组)。 */
|
|
3263
|
+
function queueHandler(deps) {
|
|
3264
|
+
return async (req, res) => {
|
|
3265
|
+
if (req.method !== "GET") {
|
|
3266
|
+
json(res, 405, { error: "method not allowed" });
|
|
3267
|
+
return;
|
|
3268
|
+
}
|
|
3269
|
+
if (!loopbackRequest(req)) {
|
|
3270
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3271
|
+
return;
|
|
3272
|
+
}
|
|
3273
|
+
json(res, 200, { queue: deps.queue?.() ?? [] });
|
|
3274
|
+
};
|
|
3275
|
+
}
|
|
3276
|
+
/** GET /api/codearts/debug — 最近出站请求的形状摘要(只有 role 名与计数)。 */
|
|
3277
|
+
function debugHandler(deps) {
|
|
3278
|
+
return async (req, res) => {
|
|
3279
|
+
if (req.method !== "GET") {
|
|
3280
|
+
json(res, 405, { error: "method not allowed" });
|
|
3281
|
+
return;
|
|
3282
|
+
}
|
|
3283
|
+
if (!loopbackRequest(req)) {
|
|
3284
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3285
|
+
return;
|
|
3286
|
+
}
|
|
3287
|
+
json(res, 200, {
|
|
3288
|
+
requests: deps.recentRequests?.() ?? [],
|
|
3289
|
+
usages: deps.recentUsages?.() ?? []
|
|
3290
|
+
});
|
|
3291
|
+
};
|
|
3292
|
+
}
|
|
3293
|
+
/** Mount the status / models / token routes. */
|
|
3294
|
+
function registerCodeArtsStatusRoute(ctx, deps) {
|
|
3295
|
+
ctx.effect(() => {
|
|
3296
|
+
const activeLogins = /* @__PURE__ */ new Map();
|
|
3297
|
+
/** 已结束登录的终态,供迟到的轮询读取。被读一次即删。 */
|
|
3298
|
+
const recentLogins = /* @__PURE__ */ new Map();
|
|
3299
|
+
/** 本次登录是「重新登录」时,授权 URL → 目标账号 id。终态落库后即删。 */
|
|
3300
|
+
const reloginTargets = /* @__PURE__ */ new Map();
|
|
3301
|
+
const disposeStatus = ctx.webServer.register({
|
|
3302
|
+
kind: "exact",
|
|
3303
|
+
path: CODEARTS_STATUS_PATH,
|
|
3304
|
+
handler: statusHandler(deps)
|
|
3305
|
+
});
|
|
3306
|
+
const disposeModels = ctx.webServer.register({
|
|
3307
|
+
kind: "exact",
|
|
3308
|
+
path: CODEARTS_MODELS_PATH,
|
|
3309
|
+
handler: modelsHandler(deps)
|
|
3310
|
+
});
|
|
3311
|
+
const disposeModelsSelection = ctx.webServer.register({
|
|
3312
|
+
kind: "exact",
|
|
3313
|
+
path: CODEARTS_MODELS_SELECTION_PATH,
|
|
3314
|
+
handler: modelsSelectionHandler(deps)
|
|
3315
|
+
});
|
|
3316
|
+
const disposeContextWindow = ctx.webServer.register({
|
|
3317
|
+
kind: "exact",
|
|
3318
|
+
path: CODEARTS_CONTEXT_WINDOW_PATH,
|
|
3319
|
+
handler: contextWindowHandler(deps)
|
|
3320
|
+
});
|
|
3321
|
+
const disposeMaxTokens = ctx.webServer.register({
|
|
3322
|
+
kind: "exact",
|
|
3323
|
+
path: CODEARTS_MAX_TOKENS_PATH,
|
|
3324
|
+
handler: maxTokensHandler(deps)
|
|
3325
|
+
});
|
|
3326
|
+
const disposeConcurrency = ctx.webServer.register({
|
|
3327
|
+
kind: "exact",
|
|
3328
|
+
path: CODEARTS_CONCURRENCY_PATH,
|
|
3329
|
+
handler: concurrencyHandler(deps)
|
|
3330
|
+
});
|
|
3331
|
+
const disposeToken = ctx.webServer.register({
|
|
3332
|
+
kind: "exact",
|
|
3333
|
+
path: CODEARTS_TOKEN_PATH,
|
|
3334
|
+
handler: tokenHandler(deps)
|
|
3335
|
+
});
|
|
3336
|
+
const disposeLoginStart = ctx.webServer.register({
|
|
3337
|
+
kind: "exact",
|
|
3338
|
+
path: CODEARTS_LOGIN_PATH,
|
|
3339
|
+
handler: loginStartHandler(deps, activeLogins, recentLogins, reloginTargets)
|
|
3340
|
+
});
|
|
3341
|
+
const disposeLoginStatus = ctx.webServer.register({
|
|
3342
|
+
kind: "exact",
|
|
3343
|
+
path: CODEARTS_LOGIN_STATUS_PATH,
|
|
3344
|
+
handler: loginPollHandler(deps, activeLogins, recentLogins)
|
|
3345
|
+
});
|
|
3346
|
+
const disposeAccounts = ctx.webServer.register({
|
|
3347
|
+
kind: "exact",
|
|
3348
|
+
path: CODEARTS_ACCOUNTS_PATH,
|
|
3349
|
+
handler: accountsHandler(deps)
|
|
3350
|
+
});
|
|
3351
|
+
const disposeClaim = ctx.webServer.register({
|
|
3352
|
+
kind: "exact",
|
|
3353
|
+
path: CODEARTS_CLAIM_PATH,
|
|
3354
|
+
handler: claimHandler(deps)
|
|
3355
|
+
});
|
|
3356
|
+
const disposeRefresh = ctx.webServer.register({
|
|
3357
|
+
kind: "exact",
|
|
3358
|
+
path: CODEARTS_REFRESH_MODELS_PATH,
|
|
3359
|
+
handler: refreshModelsHandler(deps)
|
|
3360
|
+
});
|
|
3361
|
+
const disposeTestModel = ctx.webServer.register({
|
|
3362
|
+
kind: "exact",
|
|
3363
|
+
path: CODEARTS_TEST_MODEL_PATH,
|
|
3364
|
+
handler: testModelHandler(deps)
|
|
3365
|
+
});
|
|
3366
|
+
const disposeQueue = ctx.webServer.register({
|
|
3367
|
+
kind: "exact",
|
|
3368
|
+
path: CODEARTS_QUEUE_PATH,
|
|
3369
|
+
handler: queueHandler(deps)
|
|
3370
|
+
});
|
|
3371
|
+
const disposeDock = ctx.webServer.register({
|
|
3372
|
+
kind: "exact",
|
|
3373
|
+
path: CODEARTS_DOCK_PATH,
|
|
3374
|
+
handler: dockHandler(deps)
|
|
3375
|
+
});
|
|
3376
|
+
const disposeKeeperStop = ctx.webServer.register({
|
|
3377
|
+
kind: "exact",
|
|
3378
|
+
path: CODEARTS_KEEPER_STOP_PATH,
|
|
3379
|
+
handler: keeperStopHandler(deps)
|
|
3380
|
+
});
|
|
3381
|
+
const disposeDebug = ctx.webServer.register({
|
|
3382
|
+
kind: "exact",
|
|
3383
|
+
path: CODEARTS_DEBUG_PATH,
|
|
3384
|
+
handler: debugHandler(deps)
|
|
3385
|
+
});
|
|
3386
|
+
const disposeDoctor = ctx.webServer.register({
|
|
3387
|
+
kind: "exact",
|
|
3388
|
+
path: CODEARTS_DOCTOR_PATH,
|
|
3389
|
+
handler: doctorHandler(deps)
|
|
3390
|
+
});
|
|
3391
|
+
return () => {
|
|
3392
|
+
disposeStatus();
|
|
3393
|
+
disposeModels();
|
|
3394
|
+
disposeModelsSelection();
|
|
3395
|
+
disposeContextWindow();
|
|
3396
|
+
disposeMaxTokens();
|
|
3397
|
+
disposeConcurrency();
|
|
3398
|
+
disposeToken();
|
|
3399
|
+
disposeLoginStart();
|
|
3400
|
+
disposeLoginStatus();
|
|
3401
|
+
disposeAccounts();
|
|
3402
|
+
disposeClaim();
|
|
3403
|
+
disposeRefresh();
|
|
3404
|
+
disposeTestModel();
|
|
3405
|
+
disposeQueue();
|
|
3406
|
+
disposeDock();
|
|
3407
|
+
disposeKeeperStop();
|
|
3408
|
+
disposeDebug();
|
|
3409
|
+
disposeDoctor();
|
|
3410
|
+
for (const s of activeLogins.values()) s.close();
|
|
3411
|
+
activeLogins.clear();
|
|
3412
|
+
reloginTargets.clear();
|
|
3413
|
+
};
|
|
3414
|
+
}, "dsh-codearts: Web status route");
|
|
3415
|
+
}
|
|
3416
|
+
/** /api/codearts/token — 一个席位按方法分派(POST 写入,DELETE 清除)。 */
|
|
3417
|
+
function tokenHandler(deps) {
|
|
3418
|
+
const post = tokenPostHandler(deps);
|
|
3419
|
+
const remove = tokenDeleteHandler(deps);
|
|
3420
|
+
return (req, res) => req.method === "DELETE" ? remove(req, res) : post(req, res);
|
|
3421
|
+
}
|
|
3422
|
+
/** 记一次登录终态;超出容量就丢最旧的,别让这个表无限长。 */
|
|
3423
|
+
function recordLoginOutcome(recent, url, outcome) {
|
|
3424
|
+
if (recent.size >= 20 && !recent.has(url)) {
|
|
3425
|
+
const oldest = recent.keys().next().value;
|
|
3426
|
+
if (oldest !== void 0) recent.delete(oldest);
|
|
3427
|
+
}
|
|
3428
|
+
recent.set(url, outcome);
|
|
3429
|
+
}
|
|
3430
|
+
/**
|
|
3431
|
+
* POST /api/codearts/login — 启动本地 OAuth 回调,返回授权 URL。
|
|
3432
|
+
*
|
|
3433
|
+
* `?account=<id>` 表示「重新登录这个账号」(见 settleLogin);省略就是添加账号。
|
|
3434
|
+
*/
|
|
3435
|
+
function loginStartHandler(deps, active, recent, targets) {
|
|
3436
|
+
return async (req, res) => {
|
|
3437
|
+
if (req.method !== "POST") {
|
|
3438
|
+
json(res, 405, { error: "method not allowed" });
|
|
3439
|
+
return;
|
|
3440
|
+
}
|
|
3441
|
+
if (!loopbackRequest(req)) {
|
|
3442
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3443
|
+
return;
|
|
3444
|
+
}
|
|
3445
|
+
const targetId = (new URL(req.url ?? "", "http://localhost").searchParams.get("account") ?? "").trim();
|
|
3446
|
+
try {
|
|
3447
|
+
const session = await startLogin();
|
|
3448
|
+
active.set(session.url, session);
|
|
3449
|
+
if (targetId !== "") targets.set(session.url, targetId);
|
|
3450
|
+
session.promise.then(async (token) => {
|
|
3451
|
+
active.delete(session.url);
|
|
3452
|
+
const reloginId = targets.get(session.url);
|
|
3453
|
+
targets.delete(session.url);
|
|
3454
|
+
try {
|
|
3455
|
+
const result = await settleLogin(deps, token, reloginId);
|
|
3456
|
+
recordLoginOutcome(recent, session.url, {
|
|
3457
|
+
status: "done",
|
|
3458
|
+
...result
|
|
3459
|
+
});
|
|
3460
|
+
} catch {
|
|
3461
|
+
recordLoginOutcome(recent, session.url, { status: "error" });
|
|
3462
|
+
}
|
|
3463
|
+
}, () => {
|
|
3464
|
+
active.delete(session.url);
|
|
3465
|
+
targets.delete(session.url);
|
|
3466
|
+
recordLoginOutcome(recent, session.url, { status: "error" });
|
|
3467
|
+
});
|
|
3468
|
+
const timer = setTimeout(() => {
|
|
3469
|
+
session.close();
|
|
3470
|
+
targets.delete(session.url);
|
|
3471
|
+
if (active.delete(session.url)) recordLoginOutcome(recent, session.url, { status: "error" });
|
|
3472
|
+
}, 3e5);
|
|
3473
|
+
session.promise.finally(() => clearTimeout(timer)).catch(() => {});
|
|
3474
|
+
json(res, 200, {
|
|
3475
|
+
url: session.url,
|
|
3476
|
+
port: session.port
|
|
3477
|
+
});
|
|
3478
|
+
} catch (error) {
|
|
3479
|
+
json(res, 500, { error: safeMessage(error) });
|
|
3480
|
+
}
|
|
3481
|
+
};
|
|
3482
|
+
}
|
|
3483
|
+
/** GET /api/codearts/login/status — 轮询登录结果。 */
|
|
3484
|
+
function loginPollHandler(_deps, active, recent) {
|
|
3485
|
+
return async (req, res) => {
|
|
3486
|
+
if (req.method !== "GET") {
|
|
3487
|
+
json(res, 405, { error: "method not allowed" });
|
|
3488
|
+
return;
|
|
3489
|
+
}
|
|
3490
|
+
if (!loopbackRequest(req)) {
|
|
3491
|
+
json(res, 403, { error: "request-not-trusted" });
|
|
3492
|
+
return;
|
|
3493
|
+
}
|
|
3494
|
+
const key = new URL(req.url ?? "", "http://localhost").searchParams.get("url") ?? "";
|
|
3495
|
+
if (active.has(key)) {
|
|
3496
|
+
json(res, 200, { status: "pending" });
|
|
3497
|
+
return;
|
|
3498
|
+
}
|
|
3499
|
+
const outcome = recent.get(key);
|
|
3500
|
+
if (outcome !== void 0) {
|
|
3501
|
+
recent.delete(key);
|
|
3502
|
+
json(res, 200, { ...outcome });
|
|
3503
|
+
return;
|
|
3504
|
+
}
|
|
3505
|
+
json(res, 200, { status: "idle" });
|
|
3506
|
+
};
|
|
3507
|
+
}
|
|
3508
|
+
//#endregion
|
|
3509
|
+
//#region src/settings-compat.ts
|
|
3510
|
+
const compatModule = settingsModule;
|
|
3511
|
+
function plainSettingsSchema(schema) {
|
|
3512
|
+
const clone = structuredClone(schema.toJSON());
|
|
3513
|
+
for (const node of Object.values(clone.refs ?? {})) if (node !== null && typeof node === "object" && node.meta !== void 0) delete node.meta.volatile;
|
|
3514
|
+
return z(clone);
|
|
3515
|
+
}
|
|
3516
|
+
function entryNamespaceOf(ctx) {
|
|
3517
|
+
const compat = ctx;
|
|
3518
|
+
const entry = compat.fiber?.entry;
|
|
3519
|
+
const candidates = [
|
|
3520
|
+
entry?.options?.id,
|
|
3521
|
+
entry?.id,
|
|
3522
|
+
compat.loader?.locate?.(compat.fiber)
|
|
3523
|
+
];
|
|
3524
|
+
for (const candidate of candidates) if (typeof candidate === "string" && candidate !== "") return candidate;
|
|
3525
|
+
}
|
|
3526
|
+
/**
|
|
3527
|
+
* 从 settings 的某个 dict 字段里删键,并可顺带写入一个键(issue #17)。
|
|
3528
|
+
*
|
|
3529
|
+
* `update` 是**深合并**:传一份「过滤掉目标键的整表」删不掉那个键 —— 它还留在
|
|
3530
|
+
* `cordis.patch.yml` 里,重启后覆盖照常生效,用户以为清了其实没清。真正能删键的是
|
|
3531
|
+
* `mutate` + `unset`。老宿主没有这个方法时退回 `update`:只能设新值、删不掉,
|
|
3532
|
+
* 与 1.4.8 行为相同,至少设置路径不炸。
|
|
3533
|
+
*/
|
|
3534
|
+
async function writeSettingsDictKey(settings, ns, field, remove, put) {
|
|
3535
|
+
if (settings.mutate !== void 0) {
|
|
3536
|
+
const ops = remove.map((key) => ({
|
|
3537
|
+
op: "unset",
|
|
3538
|
+
path: [field, key]
|
|
3539
|
+
}));
|
|
3540
|
+
if (put !== void 0) ops.push({
|
|
3541
|
+
op: "set",
|
|
3542
|
+
path: [field, put.key],
|
|
3543
|
+
value: put.value
|
|
3544
|
+
});
|
|
3545
|
+
if (ops.length > 0) await settings.mutate(ns, ops);
|
|
3546
|
+
return;
|
|
3547
|
+
}
|
|
3548
|
+
if (put !== void 0) await settings.update(ns, { [field]: { [put.key]: put.value } });
|
|
3549
|
+
}
|
|
3550
|
+
function resolveSettingsNamespaceCompat(ctx, provider, fallback) {
|
|
3551
|
+
if (compatModule.installSettingsSection !== void 0) return fallback;
|
|
3552
|
+
const candidate = provider;
|
|
3553
|
+
if (candidate.installSection !== void 0) return fallback;
|
|
3554
|
+
if (candidate.configure !== void 0) return entryNamespaceOf(ctx) ?? fallback;
|
|
3555
|
+
return fallback;
|
|
3556
|
+
}
|
|
3557
|
+
function installSettingsSectionCompat(ctx, ns, schema, entry, hooks) {
|
|
3558
|
+
const legacyInstaller = compatModule.installSettingsSection;
|
|
3559
|
+
if (legacyInstaller !== void 0) {
|
|
3560
|
+
legacyInstaller(ctx, ns, plainSettingsSchema(schema), entry, hooks);
|
|
3561
|
+
return;
|
|
3562
|
+
}
|
|
3563
|
+
ctx.inject(["settings"], (sctx) => {
|
|
3564
|
+
const provider = sctx.get("settings");
|
|
3565
|
+
if (provider === void 0) return;
|
|
3566
|
+
if (provider.installSection !== void 0) {
|
|
3567
|
+
provider.installSection(ctx, ns, plainSettingsSchema(schema), entry, hooks);
|
|
3568
|
+
return;
|
|
3569
|
+
}
|
|
3570
|
+
if (provider.configure === void 0) throw new TypeError("dsh-settings exposes neither installSection nor configure");
|
|
3571
|
+
sctx.effect(() => {
|
|
3572
|
+
const dispose = provider.configure?.({ auto: false }, ctx.fiber);
|
|
3573
|
+
return typeof dispose === "function" ? dispose : () => {};
|
|
3574
|
+
});
|
|
3575
|
+
const namespace = entryNamespaceOf(ctx);
|
|
3576
|
+
if (namespace !== void 0) {
|
|
3577
|
+
const refresh = () => {
|
|
3578
|
+
const descriptor = provider.describe?.().find((entry) => String(entry.ns) === namespace);
|
|
3579
|
+
if (descriptor?.value !== void 0) hooks.setSource?.(() => descriptor.value);
|
|
3580
|
+
hooks.onChange();
|
|
3581
|
+
};
|
|
3582
|
+
const settingsEvents = sctx;
|
|
3583
|
+
sctx.effect(() => settingsEvents.on("settings/document-updated", (updated) => {
|
|
3584
|
+
if (String(updated) === namespace) refresh();
|
|
3585
|
+
}));
|
|
3586
|
+
}
|
|
3587
|
+
});
|
|
3588
|
+
}
|
|
3589
|
+
//#endregion
|
|
3590
|
+
//#region src/index.ts
|
|
3591
|
+
/** Stable Cordis plugin name. */
|
|
3592
|
+
const name = "llm-codearts";
|
|
3593
|
+
/** The llm service is required before the provider can register. */
|
|
3594
|
+
const inject = ["llm"];
|
|
3595
|
+
/** Settings namespace owning the configuration card. */
|
|
3596
|
+
const CODEARTS_SETTINGS_NS = "codearts";
|
|
3597
|
+
function unwrapVolatileValue(value) {
|
|
3598
|
+
if (typeof value === "object" && value !== null && typeof value.get === "function") return value.get();
|
|
3599
|
+
return value;
|
|
3600
|
+
}
|
|
3601
|
+
function unwrapConfig(value) {
|
|
3602
|
+
if (typeof value !== "object" || value === null) return {};
|
|
3603
|
+
const out = {};
|
|
3604
|
+
for (const [key, field] of Object.entries(value)) out[key] = unwrapVolatileValue(field);
|
|
3605
|
+
return out;
|
|
3606
|
+
}
|
|
3607
|
+
const Config = z.object({
|
|
3608
|
+
enabledModels: z.array(z.string()).description("Model ids offered in the model pickers (empty means every model)").volatile(),
|
|
3609
|
+
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(),
|
|
3610
|
+
maxTokensOverrides: z.dict(z.natural()).description("Per-model max output tokens (model id → tokens, issue #15). The override becomes that model's ceiling and may exceed the 65536 global cap; rejected values still self-heal by halving the ceiling.").volatile(),
|
|
3611
|
+
maxConcurrentPerAccount: z.natural().default(2).description("Default per-account in-flight request cap (default 2). Upstream session slots depend on the plan: measured 3 on the free tier and 5 on enterprise (issue #16); leave one spare for the CodeArts web console. Applies immediately.").volatile(),
|
|
3612
|
+
maxConcurrentOverrides: z.dict(z.natural()).description("Per-account overrides of the concurrency cap (account id → slots, issue #16). Accounts listed here ignore maxConcurrentPerAccount; the card stepper on each account writes this map.").volatile(),
|
|
3613
|
+
retryPolicy: z.object({
|
|
3614
|
+
maxRetries: z.natural(),
|
|
3615
|
+
initialDelayMs: z.natural(),
|
|
3616
|
+
maxDelayMs: z.natural()
|
|
3617
|
+
}).description("Host retry budget for this provider (issue #14). Defaults to 8 retries (≈45.5s of backoff) so it outlasts the 30s account cooldown; changes apply after the plugin reloads.").volatile(),
|
|
3618
|
+
showCreditDock: z.boolean().default(true).description("Show the remaining-credits line under the chat input box").volatile(),
|
|
3619
|
+
showQueueDock: z.boolean().default(true).description("Show the upstream queue position under the chat input box").volatile(),
|
|
3620
|
+
showSidebarPanel: z.boolean().default(false).description("Show a CodeArts icon in the DSH sidebar icon column, opening this page in the middle column").volatile(),
|
|
3621
|
+
showSettingsEntry: z.boolean().default(true).description("Show a CodeArts entry in the left navigation of DSH Settings (default: shown)").volatile(),
|
|
3622
|
+
showModelDetailDock: z.boolean().default(true).description("Show \"Model … · x ratio\" on the line under the chat input box (Provider CodeArts always shows)").volatile(),
|
|
3623
|
+
autoClaim: z.boolean().default(false).description("Automatically claim the daily sign-in credits for every signed-in account").volatile(),
|
|
3624
|
+
keepAliveDaemon: z.boolean().default(false).description("Keep a detached background process that refreshes the OAuth credential while DSH is closed").volatile(),
|
|
3625
|
+
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()
|
|
3626
|
+
});
|
|
3627
|
+
function settingsCompatNamespace(ctx) {
|
|
3628
|
+
return resolveSettingsNamespaceCompat(ctx, ctx.get("settings"), CODEARTS_SETTINGS_NS);
|
|
3629
|
+
}
|
|
3630
|
+
/**
|
|
3631
|
+
* 每账号并发上限的兜底解析:坏值(0 / 负数 / NaN)回默认,别把池子锁成 0 槽。
|
|
3632
|
+
* 上限 16 是拍得住的宽松值 —— 真实套餐最多也就个位数,再大只说明用户乱填。
|
|
3633
|
+
*/
|
|
3634
|
+
function concurrencyCap(value) {
|
|
3635
|
+
const n = value === void 0 ? 2 : Math.floor(value);
|
|
3636
|
+
return Number.isFinite(n) && n >= 1 ? Math.min(n, 16) : 2;
|
|
3637
|
+
}
|
|
3638
|
+
/** 按账号覆盖表:坏值丢掉、逐项钳制(值来自用户写的配置)。 */
|
|
3639
|
+
function concurrencyCaps(value) {
|
|
3640
|
+
const out = {};
|
|
3641
|
+
for (const [key, cap] of Object.entries(value ?? {})) {
|
|
3642
|
+
const id = key.trim();
|
|
3643
|
+
if (id === "") continue;
|
|
3644
|
+
if (typeof cap !== "number" || !Number.isFinite(cap)) continue;
|
|
3645
|
+
out[id] = Math.min(Math.max(1, Math.floor(cap)), 16);
|
|
3646
|
+
}
|
|
3647
|
+
return out;
|
|
3648
|
+
}
|
|
3649
|
+
async function apply(ctx, rawConfig) {
|
|
3650
|
+
const config = unwrapConfig(rawConfig);
|
|
3651
|
+
setMaxTokenOverrides(config.maxTokensOverrides);
|
|
3652
|
+
const accountsPath = codeartsAccountsPath();
|
|
3653
|
+
/**
|
|
3654
|
+
* 续期失败日志。
|
|
3655
|
+
*
|
|
3656
|
+
* 宿主对插件的 `info`/`debug` 没有任何出口,`warn` 会变成系统通知 —— 一次网络抖动
|
|
3657
|
+
* 就弹一次窗口显然不行。所以失败原因写插件自己的文件(issue #8 里 03:22 那次续期
|
|
3658
|
+
* 失败就是因为零日志而永远无法取证)。1MB 截断重来,避免长期运行无限增长。
|
|
3659
|
+
*/
|
|
3660
|
+
const appendRefreshLog = (message) => {
|
|
3661
|
+
try {
|
|
3662
|
+
const path = codeartsRefreshLogPath();
|
|
3663
|
+
try {
|
|
3664
|
+
if (statSync(path).size > 1e6) writeFileSync(path, "");
|
|
3665
|
+
} catch {}
|
|
3666
|
+
appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
|
|
3667
|
+
} catch {}
|
|
3668
|
+
};
|
|
3669
|
+
const store = new CodeArtsAccountStore(accountsPath, void 0, { log: appendRefreshLog });
|
|
3670
|
+
const pool = new CodeArtsAccountPool([], { maxConcurrent: concurrencyCap(config.maxConcurrentPerAccount) });
|
|
3671
|
+
/** 卡片按号显示的「默认并发 + 按账号覆盖」(配置可能因旧宿主不刷新,所以单独记一份)。 */
|
|
3672
|
+
let concurrencyNow = concurrencyCap(config.maxConcurrentPerAccount);
|
|
3673
|
+
let concurrencyCapsNow = concurrencyCaps(config.maxConcurrentOverrides);
|
|
3674
|
+
pool.setAccountCaps(concurrencyCapsNow);
|
|
3675
|
+
const catalog = new CodeArtsCatalog();
|
|
3676
|
+
const usage = new CodeArtsUsageTracker({ path: codeartsUsagePath() });
|
|
3677
|
+
const queue = new CodeArtsQueueGate();
|
|
3678
|
+
const credits = new CodeArtsCreditCache();
|
|
3679
|
+
/** /status 是卡片与对话底部都会轮询的接口,积分慢请求不能把它拖成转圈。 */
|
|
3680
|
+
const CREDIT_TIMEOUT_MS = 8e3;
|
|
3681
|
+
/**
|
|
3682
|
+
* 领取签到积分的单号预算。福利中心偶尔很慢(要拉活动列表再认领),给足 20 秒,
|
|
3683
|
+
* 但必须有个上限:自动领取是在后台跑的,卡死的请求会把这个号的后续重试全堵住。
|
|
3684
|
+
*/
|
|
3685
|
+
const CLAIM_TIMEOUT_MS = 2e4;
|
|
3686
|
+
/**
|
|
3687
|
+
* 拉一次积分(每个账号各自一份)。
|
|
3688
|
+
*
|
|
3689
|
+
* 积分是**账号级**属性:多账号下每个号的余额、到期、签到状态都不同,所以逐号
|
|
3690
|
+
* 并发拉、逐号缓存(缓存键就是账号 id)。一个号失败只影响它自己那一份。
|
|
3691
|
+
*/
|
|
3692
|
+
const loadCredits = async (signal) => {
|
|
3693
|
+
const ids = await store.ids();
|
|
3694
|
+
if (ids.length === 0) return [];
|
|
3695
|
+
const controller = new AbortController();
|
|
3696
|
+
const timer = setTimeout(() => controller.abort(), CREDIT_TIMEOUT_MS);
|
|
3697
|
+
timer.unref?.();
|
|
3698
|
+
signal?.addEventListener("abort", () => controller.abort(), { once: true });
|
|
3699
|
+
try {
|
|
3700
|
+
return await Promise.all(ids.map(async (id) => {
|
|
3701
|
+
const stored = await store.credential(id);
|
|
3702
|
+
if (stored === void 0) return {
|
|
3703
|
+
id,
|
|
3704
|
+
creditsError: "account no longer stored"
|
|
3705
|
+
};
|
|
3706
|
+
if (stored.stale === true) return {
|
|
3707
|
+
id,
|
|
3708
|
+
creditsError: "account needs sign-in"
|
|
3709
|
+
};
|
|
3710
|
+
try {
|
|
3711
|
+
const resolved = await store.resolve(id);
|
|
3712
|
+
if (resolved === void 0) return {
|
|
3713
|
+
id,
|
|
3714
|
+
creditsError: "no usable credential"
|
|
3715
|
+
};
|
|
3716
|
+
const state = await credits.get(id, resolved, controller.signal);
|
|
3717
|
+
return state.phase === "ok" ? {
|
|
3718
|
+
id,
|
|
3719
|
+
credits: state.value
|
|
3720
|
+
} : {
|
|
3721
|
+
id,
|
|
3722
|
+
creditsError: state.message
|
|
3723
|
+
};
|
|
3724
|
+
} catch (error) {
|
|
3725
|
+
return {
|
|
3726
|
+
id,
|
|
3727
|
+
creditsError: error instanceof Error ? error.message : String(error)
|
|
3728
|
+
};
|
|
3729
|
+
}
|
|
3730
|
+
}));
|
|
3731
|
+
} finally {
|
|
3732
|
+
clearTimeout(timer);
|
|
3733
|
+
}
|
|
3734
|
+
};
|
|
3735
|
+
let current = () => config;
|
|
3736
|
+
const enabledModels = () => current().enabledModels;
|
|
3737
|
+
/**
|
|
3738
|
+
* 把「改了立即生效」的配置推给运行时(issue #15 #16)。
|
|
3739
|
+
*
|
|
3740
|
+
* 走设置变更而不是重建组件:并发上限在池里逐账号生效,重建会把冷却/避让/槽位
|
|
3741
|
+
* 计数这些本进程学出来的状态全丢掉。
|
|
3742
|
+
*/
|
|
3743
|
+
const applyLiveConfig = () => {
|
|
3744
|
+
setMaxTokenOverrides(current().maxTokensOverrides);
|
|
3745
|
+
concurrencyNow = concurrencyCap(current().maxConcurrentPerAccount);
|
|
3746
|
+
concurrencyCapsNow = concurrencyCaps(current().maxConcurrentOverrides);
|
|
3747
|
+
pool.setMaxConcurrent(concurrencyNow);
|
|
3748
|
+
pool.setAccountCaps(concurrencyCapsNow);
|
|
3749
|
+
};
|
|
3750
|
+
/**
|
|
3751
|
+
* 卡片上某个账号的并发加减器(issue #16)。写配置 + 立刻改组运行中的池。
|
|
3752
|
+
*
|
|
3753
|
+
* `value: null` = 删掉这个号的覆盖、回到默认值。不需要重启也不用等设置事件:
|
|
3754
|
+
* 用户点一下就要看到槽位变化。
|
|
3755
|
+
*/
|
|
3756
|
+
const setAccountConcurrency = async (accountId, value) => {
|
|
3757
|
+
const settings = ctx.get("settings");
|
|
3758
|
+
if (settings === void 0) return false;
|
|
3759
|
+
const id = accountId.trim();
|
|
3760
|
+
if (id === "") return false;
|
|
3761
|
+
const lower = id.toLowerCase();
|
|
3762
|
+
const stored = Object.keys(current().maxConcurrentOverrides ?? {}).filter((key) => key.trim().toLowerCase() === lower);
|
|
3763
|
+
const cap = value === null ? null : concurrencyCap(value);
|
|
3764
|
+
await writeDictKey(settings, "maxConcurrentOverrides", value === null ? stored : stored.filter((key) => key !== id), cap === null ? void 0 : {
|
|
3765
|
+
key: id,
|
|
3766
|
+
value: cap
|
|
3767
|
+
});
|
|
3768
|
+
const next = { ...concurrencyCapsNow };
|
|
3769
|
+
for (const key of stored) delete next[key];
|
|
3770
|
+
if (cap === null) delete next[id];
|
|
3771
|
+
else next[id] = cap;
|
|
3772
|
+
concurrencyCapsNow = next;
|
|
3773
|
+
pool.setAccountCap(id, cap);
|
|
3774
|
+
return true;
|
|
3775
|
+
};
|
|
3776
|
+
/** 设置里 dict 字段的删键/写入(issue #17 的落地,见 `writeSettingsDictKey`)。 */
|
|
3777
|
+
const writeDictKey = async (settings, field, remove, put) => {
|
|
3778
|
+
await writeSettingsDictKey(settings, settingsCompatNamespace(ctx), field, remove, put);
|
|
3779
|
+
};
|
|
3780
|
+
const setEnabledModels = async (ids) => {
|
|
3781
|
+
const settings = ctx.get("settings");
|
|
3782
|
+
if (settings === void 0) return false;
|
|
3783
|
+
await settings.update(settingsCompatNamespace(ctx), { enabledModels: [...ids] });
|
|
3784
|
+
return true;
|
|
3785
|
+
};
|
|
3786
|
+
/**
|
|
3787
|
+
* 写/清某个模型的窗口覆盖(issue #9)。
|
|
3788
|
+
*
|
|
3789
|
+
* 除了落 settings,还**当场**把目录里那条改成新值:卡片保存后会立刻重拉 selection,
|
|
3790
|
+
* 目录不跟着变的话输入框会弹回旧数字,用户会以为没存上。
|
|
3791
|
+
* `window: null` = 删除覆盖,生效值退回上游标称值(`contextWindowDiscovered`)。
|
|
3792
|
+
*/
|
|
3793
|
+
const setContextWindowOverride = async (id, window) => {
|
|
3794
|
+
const settings = ctx.get("settings");
|
|
3795
|
+
if (settings === void 0) return false;
|
|
3796
|
+
const lower = id.trim().toLowerCase();
|
|
3797
|
+
const stored = Object.keys(current().contextWindowOverrides ?? {}).filter((key) => key.trim().toLowerCase() === lower);
|
|
3798
|
+
await writeDictKey(settings, "contextWindowOverrides", window === null ? stored : stored.filter((key) => key !== id.trim()), window === null ? void 0 : {
|
|
3799
|
+
key: id.trim(),
|
|
3800
|
+
value: window
|
|
3801
|
+
});
|
|
3802
|
+
if (window === null && stored.length === 0) return true;
|
|
3803
|
+
catalog.set(withContextWindowOverride(catalog.current(), id, window));
|
|
3804
|
+
return true;
|
|
3805
|
+
};
|
|
3806
|
+
/**
|
|
3807
|
+
* 写/清某个模型的输出上限覆盖(issue #15),语义与窗口覆盖一致。
|
|
3808
|
+
*
|
|
3809
|
+
* 生效值是模块级状态(`upstream.maxTokensCeilingFor`),必须同时更新它,否则
|
|
3810
|
+
* 卡片显示改了、下一条请求仍按旧天花板钳制。
|
|
3811
|
+
*/
|
|
3812
|
+
const setMaxTokensOverride = async (id, tokens) => {
|
|
3813
|
+
const settings = ctx.get("settings");
|
|
3814
|
+
if (settings === void 0) return false;
|
|
3815
|
+
const lower = id.trim().toLowerCase();
|
|
3816
|
+
const stored = Object.keys(current().maxTokensOverrides ?? {}).filter((key) => key.trim().toLowerCase() === lower);
|
|
3817
|
+
await writeDictKey(settings, "maxTokensOverrides", tokens === null ? stored : stored.filter((key) => key !== id.trim()), tokens === null ? void 0 : {
|
|
3818
|
+
key: id.trim(),
|
|
3819
|
+
value: tokens
|
|
3820
|
+
});
|
|
3821
|
+
if (tokens === null && stored.length === 0) return true;
|
|
3822
|
+
catalog.set(withMaxTokensOverride(catalog.current(), id, tokens));
|
|
3823
|
+
setMaxTokenOverride(id, tokens);
|
|
3824
|
+
return true;
|
|
3825
|
+
};
|
|
3826
|
+
const dock = () => ({
|
|
3827
|
+
credits: current().showCreditDock !== false,
|
|
3828
|
+
queue: current().showQueueDock !== false,
|
|
3829
|
+
sidebar: current().showSidebarPanel === true,
|
|
3830
|
+
settingsEntry: current().showSettingsEntry !== false,
|
|
3831
|
+
modelDetail: current().showModelDetailDock !== false,
|
|
3832
|
+
autoClaim: current().autoClaim === true,
|
|
3833
|
+
keepAliveDaemon: current().keepAliveDaemon === true,
|
|
3834
|
+
queueWait: current().queueWaitUntilReady === true
|
|
3835
|
+
});
|
|
3836
|
+
const setDock = async (patch) => {
|
|
3837
|
+
const settings = ctx.get("settings");
|
|
3838
|
+
if (settings === void 0) return false;
|
|
3839
|
+
await settings.update(settingsCompatNamespace(ctx), {
|
|
3840
|
+
...patch.credits === void 0 ? {} : { showCreditDock: patch.credits },
|
|
3841
|
+
...patch.queue === void 0 ? {} : { showQueueDock: patch.queue },
|
|
3842
|
+
...patch.sidebar === void 0 ? {} : { showSidebarPanel: patch.sidebar },
|
|
3843
|
+
...patch.settingsEntry === void 0 ? {} : { showSettingsEntry: patch.settingsEntry },
|
|
3844
|
+
...patch.modelDetail === void 0 ? {} : { showModelDetailDock: patch.modelDetail },
|
|
3845
|
+
...patch.autoClaim === void 0 ? {} : { autoClaim: patch.autoClaim },
|
|
3846
|
+
...patch.keepAliveDaemon === void 0 ? {} : { keepAliveDaemon: patch.keepAliveDaemon },
|
|
3847
|
+
...patch.queueWait === void 0 ? {} : { queueWaitUntilReady: patch.queueWait }
|
|
3848
|
+
});
|
|
3849
|
+
return true;
|
|
3850
|
+
};
|
|
3851
|
+
/** 手动「刷新模型列表」的预算:三路来源各打一次,比每小时的后台刷新更该给足时间。 */
|
|
3852
|
+
const MANUAL_REFRESH_MS = 6e4;
|
|
3853
|
+
/**
|
|
3854
|
+
* 守护进程:当前活着吗。
|
|
3855
|
+
*
|
|
3856
|
+
* 「活着」= 状态文件里心跳新鲜 **且** 那个 pid 真能探到(`keeper.ts` 里两个条件都查)。
|
|
3857
|
+
* 只看心跳会把刚被 kill 的进程当成活的 —— 心跳是它死前 30 秒内写的,不会自己消失。
|
|
3858
|
+
*/
|
|
3859
|
+
const keeperRunning = () => keeperStats().alive;
|
|
3860
|
+
/**
|
|
3861
|
+
* 刚点开开关、守护进程还没写出状态文件的那段时间。
|
|
3862
|
+
*
|
|
3863
|
+
* 秒级的进程启动 + 首次 `writeKeeperState` 之间确实有一段「探不到活」的窗口。
|
|
3864
|
+
* 不区分的话,卡片刚被勾上就会因为「没探到进程」而自己把开关关掉 —— 用户看到的是
|
|
3865
|
+
* 勾了一下马上弹回去。这段时间里 `alive` 仍是 false(它确实还没活),但带 `starting`。
|
|
3866
|
+
*/
|
|
3867
|
+
const KEEPER_START_GRACE_MS = KEEPER_STALE_MS;
|
|
3868
|
+
const keeperView = async () => {
|
|
3869
|
+
const logPath = keeperLogPath();
|
|
3870
|
+
const stats = keeperStats();
|
|
3871
|
+
if (stats.alive && stats.state !== void 0) {
|
|
3872
|
+
keeperLastError = void 0;
|
|
3873
|
+
return {
|
|
3874
|
+
alive: true,
|
|
3875
|
+
pid: stats.state.pid,
|
|
3876
|
+
startedAt: stats.state.startedAt,
|
|
3877
|
+
heartbeatAt: stats.state.heartbeatAt,
|
|
3878
|
+
...stats.state.lastPass === void 0 ? {} : { lastPass: stats.state.lastPass },
|
|
3879
|
+
logPath
|
|
3880
|
+
};
|
|
3881
|
+
}
|
|
3882
|
+
if (!(current().keepAliveDaemon === true)) return {
|
|
3883
|
+
alive: false,
|
|
3884
|
+
logPath
|
|
3885
|
+
};
|
|
3886
|
+
if (Date.now() - keeperSpawnedAt < KEEPER_START_GRACE_MS) return {
|
|
3887
|
+
alive: false,
|
|
3888
|
+
starting: true,
|
|
3889
|
+
...keeperLastError === void 0 ? {} : { error: keeperLastError },
|
|
3890
|
+
logPath
|
|
3891
|
+
};
|
|
3892
|
+
if (keeperHandoffRecent()) return {
|
|
3893
|
+
alive: false,
|
|
3894
|
+
error: "守护进程为更新安装让路,重启后会自动恢复",
|
|
3895
|
+
logPath
|
|
3896
|
+
};
|
|
3897
|
+
try {
|
|
3898
|
+
await setDock({ keepAliveDaemon: false });
|
|
3899
|
+
} catch {}
|
|
3900
|
+
return {
|
|
3901
|
+
alive: false,
|
|
3902
|
+
error: keeperLastError ?? "守护进程已退出,已自动关闭保活开关",
|
|
3903
|
+
logPath
|
|
3904
|
+
};
|
|
3905
|
+
};
|
|
3906
|
+
/**
|
|
3907
|
+
* 常驻守护进程:在 DSH 之外续 refresh_token。
|
|
3908
|
+
*
|
|
3909
|
+
* 与上面 `keepAliveLoop` 的分工:那个只在 DSH 活着时有用,关掉 DSH 就没了;这个起的是
|
|
3910
|
+
* 一个 detached 进程,DSH 退出后它还在,20 分钟续一次,把 30 天有效期的 refresh_token
|
|
3911
|
+
* 一直续下去 —— 这才是「十几天不用重新登录」的正解。
|
|
3912
|
+
*
|
|
3913
|
+
* refresh_token 是一次性的:两边同时刷会让后刷的一方拿着作废的 token 失败。所以开关
|
|
3914
|
+
* 打开时 `keepAliveLoop` 会主动让路(只从磁盘重读),刷新权独占在守护进程手里。
|
|
3915
|
+
*/
|
|
3916
|
+
const KEEPER_ENSURE_MS = 6e4;
|
|
3917
|
+
let keeperSpawnedAt = 0;
|
|
3918
|
+
let keeperLastError;
|
|
3919
|
+
let keeperTimer;
|
|
3920
|
+
/**
|
|
3921
|
+
* 按开关状态把守护进程拉起来。
|
|
3922
|
+
*
|
|
3923
|
+
* 只在「开关刚被打开」时调用(`armKeepAliveDaemon`)。**不做定时重起**:用户明确要求
|
|
3924
|
+
* 「被 kill 了开关就关掉」,而不是「被 kill 了自己又冒出来」—— 后者正是用户按了结束
|
|
3925
|
+
* 却看到进程又活了的那种体验。
|
|
3926
|
+
*/
|
|
3927
|
+
const ensureKeeper = () => {
|
|
3928
|
+
if (stopped) return;
|
|
3929
|
+
if (current().keepAliveDaemon !== true) return;
|
|
3930
|
+
if (keeperRunning()) return;
|
|
3931
|
+
const outcome = spawnKeeper({
|
|
3932
|
+
scriptPath: keeperScriptPath(),
|
|
3933
|
+
pluginVersion: CODEARTS_VERSION
|
|
3934
|
+
});
|
|
3935
|
+
keeperSpawnedAt = Date.now();
|
|
3936
|
+
if (outcome.ok) {
|
|
3937
|
+
keeperLastError = void 0;
|
|
3938
|
+
clearKeeperHandoff();
|
|
3939
|
+
ctx.logger.debug(`dsh-codearts: credential keeper running (pid ${outcome.pid ?? "?"})`);
|
|
3940
|
+
} else {
|
|
3941
|
+
keeperLastError = outcome.reason ?? "spawn failed";
|
|
3942
|
+
ctx.logger.debug(`dsh-codearts: credential keeper failed to start: ${keeperLastError}`);
|
|
3943
|
+
}
|
|
3944
|
+
};
|
|
3945
|
+
/**
|
|
3946
|
+
* 守护巡检:只在旁边看着,不重起。
|
|
3947
|
+
*
|
|
3948
|
+
* 三种结局:开关被关掉 → 收工;进程还活着 → 继续看;进程没了(超出启动宽限期)→
|
|
3949
|
+
* 把开关关掉并收工。判死必须在服务端做,不能只靠卡片轮询 —— 卡片没打开时也得让
|
|
3950
|
+
* 那个「开着却空转」的开关自己消失。
|
|
3951
|
+
*/
|
|
3952
|
+
const keeperLoop = async () => {
|
|
3953
|
+
if (stopped) return;
|
|
3954
|
+
if (current().keepAliveDaemon !== true) {
|
|
3955
|
+
keeperTimer = void 0;
|
|
3956
|
+
return;
|
|
3957
|
+
}
|
|
3958
|
+
if (!keeperRunning() && Date.now() - keeperSpawnedAt >= KEEPER_START_GRACE_MS) {
|
|
3959
|
+
keeperTimer = void 0;
|
|
3960
|
+
keeperSpawnedAt = 0;
|
|
3961
|
+
if (keeperHandoffRecent()) return;
|
|
3962
|
+
await setDock({ keepAliveDaemon: false }).catch(() => false);
|
|
3963
|
+
return;
|
|
3964
|
+
}
|
|
3965
|
+
keeperTimer = setTimeout(() => void keeperLoop(), KEEPER_ENSURE_MS);
|
|
3966
|
+
keeperTimer.unref?.();
|
|
3967
|
+
};
|
|
3968
|
+
/** 开关变化时立刻响应:打开就马上起,关掉就撤掉巡检(进程本身留给「结束」按钮)。 */
|
|
3969
|
+
const armKeepAliveDaemon = () => {
|
|
3970
|
+
if (stopped) return;
|
|
3971
|
+
if (current().keepAliveDaemon !== true) {
|
|
3972
|
+
if (keeperTimer !== void 0) clearTimeout(keeperTimer);
|
|
3973
|
+
keeperTimer = void 0;
|
|
3974
|
+
keeperSpawnedAt = 0;
|
|
3975
|
+
return;
|
|
3976
|
+
}
|
|
3977
|
+
if (keeperTimer !== void 0) return;
|
|
3978
|
+
ensureKeeper();
|
|
3979
|
+
keeperTimer = setTimeout(() => void keeperLoop(), KEEPER_ENSURE_MS);
|
|
3980
|
+
keeperTimer.unref?.();
|
|
3981
|
+
};
|
|
3982
|
+
/**
|
|
3983
|
+
* 逐号领取每日签到积分。
|
|
3984
|
+
*
|
|
3985
|
+
* 手动「领取」按钮和后台自动领取走的是**同一条**路径,只是入口不同:领的是什么、
|
|
3986
|
+
* 失败怎么归类、什么时候作废缓存,两处必须完全一致,否则「手动能领到、自动领不到」
|
|
3987
|
+
* 这种差异排查起来极其费劲。
|
|
3988
|
+
*/
|
|
3989
|
+
const claimAll = async (accountId) => {
|
|
3990
|
+
const ids = accountId === void 0 ? await store.ids() : [accountId];
|
|
3991
|
+
if (ids.length === 0) return {
|
|
3992
|
+
ok: false,
|
|
3993
|
+
claimed: false,
|
|
3994
|
+
state: "failed",
|
|
3995
|
+
amount: 0,
|
|
3996
|
+
message: "no usable credential"
|
|
3997
|
+
};
|
|
3998
|
+
const results = [];
|
|
3999
|
+
for (const id of ids) try {
|
|
4000
|
+
const stored = await store.credential(id);
|
|
4001
|
+
if (stored === void 0 || stored.stale === true) {
|
|
4002
|
+
results.push({
|
|
4003
|
+
id,
|
|
4004
|
+
ok: false,
|
|
4005
|
+
claimed: false,
|
|
4006
|
+
state: "failed",
|
|
4007
|
+
amount: 0,
|
|
4008
|
+
message: stored === void 0 ? "account not found" : "account needs sign-in"
|
|
4009
|
+
});
|
|
4010
|
+
continue;
|
|
4011
|
+
}
|
|
4012
|
+
const resolved = await store.resolve(id);
|
|
4013
|
+
if (resolved === void 0) {
|
|
4014
|
+
results.push({
|
|
4015
|
+
id,
|
|
4016
|
+
ok: false,
|
|
4017
|
+
claimed: false,
|
|
4018
|
+
state: "failed",
|
|
4019
|
+
amount: 0,
|
|
4020
|
+
message: "no usable credential"
|
|
4021
|
+
});
|
|
4022
|
+
continue;
|
|
4023
|
+
}
|
|
4024
|
+
const outcome = await claimDailyWelfare(resolved, AbortSignal.timeout(CLAIM_TIMEOUT_MS));
|
|
4025
|
+
if (outcome.state === "claimed") credits.invalidate(id);
|
|
4026
|
+
results.push({
|
|
4027
|
+
id,
|
|
4028
|
+
ok: outcome.state !== "failed",
|
|
4029
|
+
claimed: outcome.state === "claimed",
|
|
4030
|
+
state: outcome.state,
|
|
4031
|
+
amount: outcome.amount,
|
|
4032
|
+
message: outcome.message
|
|
4033
|
+
});
|
|
4034
|
+
} catch (error) {
|
|
4035
|
+
results.push({
|
|
4036
|
+
id,
|
|
4037
|
+
ok: false,
|
|
4038
|
+
claimed: false,
|
|
4039
|
+
state: "failed",
|
|
4040
|
+
amount: 0,
|
|
4041
|
+
message: error instanceof Error ? error.message : String(error)
|
|
4042
|
+
});
|
|
4043
|
+
}
|
|
4044
|
+
return summarizeClaims(results);
|
|
4045
|
+
};
|
|
4046
|
+
/**
|
|
4047
|
+
* 启动引导的进度(issue #19)。
|
|
4048
|
+
*
|
|
4049
|
+
* 「插件 HTTP 面全活、模型选择器里却没有 CodeArts」是宿主上真实出现过的分裂状态;
|
|
4050
|
+
* 那一刻唯一能区分「shim 没起来 / 注册被首轮发现拖住 / 注册抛错」的证据就在这里,
|
|
4051
|
+
* 由 /api/codearts/doctor 的 `provider` 一项读出去。
|
|
4052
|
+
*/
|
|
4053
|
+
const startup = {
|
|
4054
|
+
stage: "shim",
|
|
4055
|
+
registered: false
|
|
4056
|
+
};
|
|
4057
|
+
ctx.inject(["webServer"], (webCtx) => registerCodeArtsStatusRoute(webCtx, {
|
|
4058
|
+
store,
|
|
4059
|
+
models: () => catalog.current(),
|
|
4060
|
+
providerStatus: () => ({
|
|
4061
|
+
registered: startup.registered,
|
|
4062
|
+
stage: startup.stage,
|
|
4063
|
+
...startup.error === void 0 ? {} : { error: startup.error }
|
|
4064
|
+
}),
|
|
4065
|
+
enabledModels,
|
|
4066
|
+
setEnabledModels,
|
|
4067
|
+
contextWindowOverrides: () => current().contextWindowOverrides,
|
|
4068
|
+
setContextWindowOverride,
|
|
4069
|
+
maxTokensOverrides: () => current().maxTokensOverrides,
|
|
4070
|
+
setMaxTokensOverride,
|
|
4071
|
+
concurrency: () => ({
|
|
4072
|
+
default: concurrencyNow,
|
|
4073
|
+
caps: { ...concurrencyCapsNow }
|
|
4074
|
+
}),
|
|
4075
|
+
setAccountConcurrency,
|
|
4076
|
+
pool: () => pool.list(),
|
|
4077
|
+
reviveAccount: (id) => pool.revive(id),
|
|
4078
|
+
usage: () => usage.snapshot(),
|
|
4079
|
+
queue: () => queue.snapshot(),
|
|
4080
|
+
recentRequests: () => recentRequestShapes(),
|
|
4081
|
+
recentUsages: () => recentUsageShapes(),
|
|
4082
|
+
credits: (signal) => loadCredits(signal),
|
|
4083
|
+
refreshCredits: (signal) => {
|
|
4084
|
+
credits.invalidate();
|
|
4085
|
+
return loadCredits(signal);
|
|
4086
|
+
},
|
|
4087
|
+
dock,
|
|
4088
|
+
setDock,
|
|
4089
|
+
keeper: keeperView,
|
|
4090
|
+
stopKeeper: async () => {
|
|
4091
|
+
const outcome = await stopKeeper();
|
|
4092
|
+
keeperSpawnedAt = 0;
|
|
4093
|
+
return outcome;
|
|
4094
|
+
},
|
|
4095
|
+
claim: claimAll,
|
|
4096
|
+
autoClaim: async () => {
|
|
4097
|
+
const outcome = await claimAll();
|
|
4098
|
+
outcome.claimed, outcome.state, outcome.amount, outcome.message;
|
|
4099
|
+
return outcome;
|
|
4100
|
+
},
|
|
4101
|
+
refreshModels: async () => {
|
|
4102
|
+
const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS), current().contextWindowOverrides);
|
|
4103
|
+
const models = catalog.current();
|
|
4104
|
+
return {
|
|
4105
|
+
models: models.length,
|
|
4106
|
+
benefit: models.filter((model) => isBenefitModel(model.id)).length,
|
|
4107
|
+
refreshed: outcome?.anySucceeded === true
|
|
4108
|
+
};
|
|
4109
|
+
}
|
|
4110
|
+
}));
|
|
4111
|
+
installSettingsSectionCompat(ctx, CODEARTS_SETTINGS_NS, Config, config, {
|
|
4112
|
+
setSource(source) {
|
|
4113
|
+
current = () => unwrapConfig(source());
|
|
4114
|
+
applyLiveConfig();
|
|
4115
|
+
armAutoClaim();
|
|
4116
|
+
armKeepAliveDaemon();
|
|
4117
|
+
},
|
|
4118
|
+
onChange() {
|
|
4119
|
+
applyLiveConfig();
|
|
4120
|
+
armAutoClaim();
|
|
4121
|
+
armKeepAliveDaemon();
|
|
4122
|
+
}
|
|
4123
|
+
});
|
|
4124
|
+
let stopped = false;
|
|
4125
|
+
ctx.effect(() => () => {
|
|
4126
|
+
stopped = true;
|
|
4127
|
+
queue.dispose();
|
|
4128
|
+
usage.flush().catch(() => {});
|
|
4129
|
+
shim.close().catch(() => {});
|
|
4130
|
+
});
|
|
4131
|
+
const CATALOG_REFRESH_MS = 36e5;
|
|
4132
|
+
const CATALOG_EMPTY_RETRY_MS = 6e4;
|
|
4133
|
+
const CATALOG_EMPTY_RETRY_MAX_MS = 3e5;
|
|
4134
|
+
/**
|
|
4135
|
+
* 启动首轮发现的预算(issue #13)。
|
|
4136
|
+
*
|
|
4137
|
+
* 一次性宿主(`--list-models`、`dsh headless`、Multica 的本机运行时)在 profile
|
|
4138
|
+
* 加载完就列模型 / 解析模型,等不到后台的任何一轮重试 —— 目录空就是定论。所以
|
|
4139
|
+
* 首轮发现要挡在注册之前、并让 `apply` 等它。但上游挂住时不能把启动一起拖死:
|
|
4140
|
+
* 超时按空目录继续注册,循环随后照常补。手动刷新那条路是 60s,启动不能照抄。
|
|
4141
|
+
*/
|
|
4142
|
+
const STARTUP_DISCOVERY_MS = 1e4;
|
|
4143
|
+
/** 启动引导的总预算:发现另有 10s 自己的预算,这里防的是 shim 启动 / probe 卡住。 */
|
|
4144
|
+
const STARTUP_WAIT_MS = 15e3;
|
|
4145
|
+
const abort = new AbortController();
|
|
4146
|
+
const discover = async (signal = abort.signal) => {
|
|
4147
|
+
if (stopped) return;
|
|
4148
|
+
try {
|
|
4149
|
+
const outcome = await refreshCatalog(store, catalog, signal, current().contextWindowOverrides);
|
|
4150
|
+
if (outcome === void 0 || stopped) return;
|
|
4151
|
+
if (outcome.anySucceeded) {
|
|
4152
|
+
const free = outcome.models.filter((model) => model.benefit === true).length;
|
|
4153
|
+
ctx.logger.debug(`dsh-codearts: model discovery refreshed the catalog (${outcome.models.length} models, ${free} benefit)`);
|
|
4154
|
+
} else ctx.logger.warn("dsh-codearts: model discovery found nothing usable; keeping the current catalog", outcome.accounts.flatMap((account) => account.errors));
|
|
4155
|
+
} catch (error) {
|
|
4156
|
+
ctx.logger.debug("dsh-codearts: model discovery failed; keeping the current catalog", error);
|
|
4157
|
+
}
|
|
4158
|
+
};
|
|
4159
|
+
let discoveryTimer;
|
|
4160
|
+
/** 连续多少轮目录是空的(用来算退避);一旦有货就归零。 */
|
|
4161
|
+
let emptyStreak = 0;
|
|
4162
|
+
/** 下一轮发现该隔多久:目录为空时退避(60s → 5min 封顶),有货后回到每小时。 */
|
|
4163
|
+
const nextDiscoveryDelay = () => {
|
|
4164
|
+
if (catalog.current().length === 0) {
|
|
4165
|
+
const delay = Math.min(CATALOG_EMPTY_RETRY_MS * 2 ** emptyStreak, CATALOG_EMPTY_RETRY_MAX_MS);
|
|
4166
|
+
emptyStreak += 1;
|
|
4167
|
+
return delay;
|
|
4168
|
+
}
|
|
4169
|
+
emptyStreak = 0;
|
|
4170
|
+
return CATALOG_REFRESH_MS;
|
|
4171
|
+
};
|
|
4172
|
+
const scheduleDiscovery = (delay) => {
|
|
4173
|
+
discoveryTimer = setTimeout(() => void discoverLoop(), delay);
|
|
4174
|
+
discoveryTimer.unref?.();
|
|
4175
|
+
};
|
|
4176
|
+
/** 自我重排的发现循环:首轮由启动引导跑完后从这里接棒,不再立刻多打一轮上游。 */
|
|
4177
|
+
const discoverLoop = async () => {
|
|
4178
|
+
await discover();
|
|
4179
|
+
if (stopped) return;
|
|
4180
|
+
scheduleDiscovery(nextDiscoveryDelay());
|
|
4181
|
+
};
|
|
4182
|
+
ctx.effect(() => () => {
|
|
4183
|
+
abort.abort();
|
|
4184
|
+
if (discoveryTimer !== void 0) clearTimeout(discoveryTimer);
|
|
4185
|
+
});
|
|
4186
|
+
/**
|
|
4187
|
+
* 凭证保活:每 20 分钟把所有「快过期」的账号提前续掉。
|
|
4188
|
+
*
|
|
4189
|
+
* 为什么必须有这个循环:上游签发的 token 有效期是固定的 2 小时(实测,见
|
|
4190
|
+
* `auth.ts` 的 `REFRESH_SKEW_MS` 注释),而 `ensureFresh` 只在「有请求进来」时才被
|
|
4191
|
+
* 触发。用户开着 DSH 却不聊天时没有任何请求,凭证就一路裸奔到过期 —— 表现就是
|
|
4192
|
+
* 「隔天就要重新登录」。有了这个循环,只要 DSH 活着,凭证就不会真的到期。
|
|
4193
|
+
*
|
|
4194
|
+
* 间隔 20 分钟 + 续期阈值 30 分钟 = 剩 30 分钟以内一定会被扫到至少一次。
|
|
4195
|
+
* 关掉 DSH 就无从保活(插件不在进程里),那部分只能靠下次启动时重新登录,
|
|
4196
|
+
* 这是纯客户端方案的硬边界,卡片文案里必须讲明白。
|
|
4197
|
+
*/
|
|
4198
|
+
const KEEP_ALIVE_INTERVAL_MS = 12e5;
|
|
4199
|
+
let keepAliveTimer;
|
|
4200
|
+
/**
|
|
4201
|
+
* 这一轮该不该把续期让给守护进程。
|
|
4202
|
+
*
|
|
4203
|
+
* 原来只看 `keeperRunning()`(心跳新鲜 + pid 活着)。问题是那个条件在 keeper 的
|
|
4204
|
+
* **两轮 tick 之间(20 分钟空窗)同样成立**,于是插件整段时间完全不刷;万一 keeper
|
|
4205
|
+
* 那一轮撞上锁忙跳过了,两边就一起不刷,凭证一路裸奔到过期(2026-11-18 凌晨
|
|
4206
|
+
* 06:46–08:06 缺 4 轮 tick 时就是这样,见 `keeper-main.ts` 的睡眠补偿注释)。
|
|
4207
|
+
*
|
|
4208
|
+
* 现在改成「keeper 活着 **且** 它马上要来」才让路:只有当下一轮 tick 已到最后
|
|
4209
|
+
* 一个心跳周期的窗口里(或者已经过点了),才把续期权交给它。其余时间插件自己刷,
|
|
4210
|
+
* 反正跨进程锁会把两边串起来。
|
|
4211
|
+
*/
|
|
4212
|
+
const shouldDeferToKeeper = () => {
|
|
4213
|
+
const stats = keeperStats();
|
|
4214
|
+
if (!stats.alive) return false;
|
|
4215
|
+
return Date.now() >= keeperNextPassAt(stats.state) - KEEPER_STALE_MS;
|
|
4216
|
+
};
|
|
4217
|
+
const keepAliveLoop = async () => {
|
|
4218
|
+
if (stopped) return;
|
|
4219
|
+
if (shouldDeferToKeeper()) await store.reloadFromDisk().catch(() => {});
|
|
4220
|
+
else try {
|
|
4221
|
+
const outcome = await store.keepAlive();
|
|
4222
|
+
if (outcome.refreshed > 0) ctx.logger.debug(`dsh-codearts: refreshed ${outcome.refreshed} credential(s) in the background`);
|
|
4223
|
+
if (outcome.needsLogin.length > 0) ctx.logger.debug(`dsh-codearts: ${outcome.needsLogin.length} account(s) need a fresh sign-in`);
|
|
4224
|
+
} catch (error) {
|
|
4225
|
+
ctx.logger.debug("dsh-codearts: credential keep-alive failed; will retry", error);
|
|
4226
|
+
}
|
|
4227
|
+
if (stopped) return;
|
|
4228
|
+
keepAliveTimer = setTimeout(() => void keepAliveLoop(), KEEP_ALIVE_INTERVAL_MS);
|
|
4229
|
+
keepAliveTimer.unref?.();
|
|
4230
|
+
};
|
|
4231
|
+
/**
|
|
4232
|
+
* 自动领取每日签到积分。
|
|
4233
|
+
*
|
|
4234
|
+
* 节奏的取舍:上游按天去重(重复领返回 40001 → already),所以多领不会出事;
|
|
4235
|
+
* 但也正因为幂等,**没必要**高频轮询 —— 单号一天只值 200 分,每 10 秒刷一次的
|
|
4236
|
+
* 上行成本和风控风险都远大于收益。取「启动后 30 秒试一次 + 失败才退避重试
|
|
4237
|
+
* (30 分钟一次、最多 3 次)」:装了就领到,领不到也不无限缠着上游。
|
|
4238
|
+
*
|
|
4239
|
+
* 终止条件:任意一轮里「有号真领到」或「所有号都是 already/unavailable」就停。
|
|
4240
|
+
* 只有 genuinely 失败(网络、凭据异常)才值得再试。
|
|
4241
|
+
*/
|
|
4242
|
+
const AUTO_CLAIM_FIRST_DELAY_MS = 3e4;
|
|
4243
|
+
const AUTO_CLAIM_RETRY_MS = 18e5;
|
|
4244
|
+
const AUTO_CLAIM_MAX_TRIES = 3;
|
|
4245
|
+
let autoClaimTimer;
|
|
4246
|
+
let autoClaimTries = 0;
|
|
4247
|
+
/** 自我重排的自动领取循环;开关关掉时直接不排下一轮,下次打开才重新开始。 */
|
|
4248
|
+
const autoClaimLoop = async () => {
|
|
4249
|
+
if (stopped) return;
|
|
4250
|
+
if (!dock().autoClaim) {
|
|
4251
|
+
autoClaimTimer = void 0;
|
|
4252
|
+
return;
|
|
4253
|
+
}
|
|
4254
|
+
autoClaimTries += 1;
|
|
4255
|
+
let retry = false;
|
|
4256
|
+
try {
|
|
4257
|
+
const outcome = await claimAll();
|
|
4258
|
+
outcome.claimed, outcome.state, outcome.amount, outcome.message;
|
|
4259
|
+
if (outcome.claimed) ctx.logger.debug(`dsh-codearts: auto-claimed daily credits (${outcome.amount})`);
|
|
4260
|
+
else if (outcome.state === "failed") retry = true;
|
|
4261
|
+
} catch (error) {
|
|
4262
|
+
retry = true;
|
|
4263
|
+
ctx.logger.debug("dsh-codearts: auto-claim failed; will retry", error);
|
|
4264
|
+
}
|
|
4265
|
+
if (stopped) return;
|
|
4266
|
+
if (!retry || autoClaimTries >= AUTO_CLAIM_MAX_TRIES) {
|
|
4267
|
+
autoClaimTimer = void 0;
|
|
4268
|
+
return;
|
|
4269
|
+
}
|
|
4270
|
+
autoClaimTimer = setTimeout(() => void autoClaimLoop(), AUTO_CLAIM_RETRY_MS);
|
|
4271
|
+
autoClaimTimer.unref?.();
|
|
4272
|
+
};
|
|
4273
|
+
/** 按当前开关状态(重新)拉起自动领取;开关关掉时把在等的定时器撤掉。 */
|
|
4274
|
+
const armAutoClaim = () => {
|
|
4275
|
+
if (stopped) return;
|
|
4276
|
+
if (!dock().autoClaim) {
|
|
4277
|
+
if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
|
|
4278
|
+
autoClaimTimer = void 0;
|
|
4279
|
+
autoClaimTries = 0;
|
|
4280
|
+
return;
|
|
4281
|
+
}
|
|
4282
|
+
if (autoClaimTimer !== void 0) return;
|
|
4283
|
+
autoClaimTries = 0;
|
|
4284
|
+
autoClaimTimer = setTimeout(() => void autoClaimLoop(), AUTO_CLAIM_FIRST_DELAY_MS);
|
|
4285
|
+
autoClaimTimer.unref?.();
|
|
4286
|
+
};
|
|
4287
|
+
ctx.effect(() => () => {
|
|
4288
|
+
if (keepAliveTimer !== void 0) clearTimeout(keepAliveTimer);
|
|
4289
|
+
if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
|
|
4290
|
+
if (keeperTimer !== void 0) clearTimeout(keeperTimer);
|
|
4291
|
+
});
|
|
4292
|
+
/**
|
|
4293
|
+
* 槽位取证日志:acquire/release 的时间点与在飞计数。
|
|
4294
|
+
*
|
|
4295
|
+
* 默认关闭(只有 `DSH_CODEARTS_DEBUG=1` 时写)。issue #8 里「只剩一个在飞请求,
|
|
4296
|
+
* 但所有 acquire 都失败」的怀疑,只能靠这份日志证实或排除。
|
|
4297
|
+
*/
|
|
4298
|
+
const writeDebugLog = process.env.DSH_CODEARTS_DEBUG === "1" ? (message) => {
|
|
4299
|
+
try {
|
|
4300
|
+
const path = codeartsDebugLogPath();
|
|
4301
|
+
try {
|
|
4302
|
+
if (statSync(path).size > 2e6) writeFileSync(path, "");
|
|
4303
|
+
} catch {}
|
|
4304
|
+
appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
|
|
4305
|
+
} catch {}
|
|
4306
|
+
} : void 0;
|
|
4307
|
+
const shim = createCodeArtsShim({
|
|
4308
|
+
store,
|
|
4309
|
+
catalog,
|
|
4310
|
+
pool,
|
|
4311
|
+
usage,
|
|
4312
|
+
queue,
|
|
4313
|
+
logger: ctx.logger,
|
|
4314
|
+
debug: writeDebugLog,
|
|
4315
|
+
contextWindowOverrides: () => current().contextWindowOverrides,
|
|
4316
|
+
waitInQueue: () => current().queueWaitUntilReady === true
|
|
4317
|
+
});
|
|
4318
|
+
usage.load().catch(() => {});
|
|
4319
|
+
const settled = shim.ready.then(async () => {
|
|
4320
|
+
if (stopped) return;
|
|
4321
|
+
keepAliveLoop();
|
|
4322
|
+
armAutoClaim();
|
|
4323
|
+
armKeepAliveDaemon();
|
|
4324
|
+
startup.stage = "register";
|
|
4325
|
+
const incompatible = await probePiAiCompat();
|
|
4326
|
+
if (incompatible !== void 0) ctx.logger.error(`dsh-codearts: ${incompatible}`);
|
|
4327
|
+
writeDebugLog?.(`bootstrap: shim ready, registering provider (catalog=${catalog.current().length})`);
|
|
4328
|
+
const codearts = createCodeArtsAdapter({
|
|
4329
|
+
shim,
|
|
4330
|
+
catalog,
|
|
4331
|
+
enabledModels,
|
|
4332
|
+
retryPolicy: current().retryPolicy,
|
|
4333
|
+
resolveAttachments: () => ctx.get("attachments")
|
|
4334
|
+
});
|
|
4335
|
+
let releaseAdapter;
|
|
4336
|
+
let releaseDirectory;
|
|
4337
|
+
try {
|
|
4338
|
+
releaseAdapter = ctx.llm.registerAdapter([CODEARTS_PROVIDER], codearts.adapter);
|
|
4339
|
+
releaseDirectory = ctx.llm.registerConfigurableProviders([{
|
|
4340
|
+
provider: CODEARTS_PROVIDER,
|
|
4341
|
+
displayName: "CodeArts",
|
|
4342
|
+
settingsNs: settingsCompatNamespace(ctx),
|
|
4343
|
+
settingsPath: [],
|
|
4344
|
+
declared: false
|
|
4345
|
+
}]);
|
|
4346
|
+
startup.registered = true;
|
|
4347
|
+
writeDebugLog?.("bootstrap: provider registered");
|
|
4348
|
+
} catch (error) {
|
|
4349
|
+
startup.error = error instanceof Error ? error.message : String(error);
|
|
4350
|
+
throw error;
|
|
4351
|
+
} finally {
|
|
4352
|
+
if (releaseAdapter === void 0 || releaseDirectory === void 0) {
|
|
4353
|
+
releaseAdapter?.();
|
|
4354
|
+
releaseDirectory?.();
|
|
4355
|
+
}
|
|
4356
|
+
}
|
|
4357
|
+
try {
|
|
4358
|
+
ctx.effect(() => () => {
|
|
4359
|
+
releaseAdapter?.();
|
|
4360
|
+
releaseDirectory?.();
|
|
4361
|
+
});
|
|
4362
|
+
} catch {
|
|
4363
|
+
releaseAdapter?.();
|
|
4364
|
+
releaseDirectory?.();
|
|
4365
|
+
}
|
|
4366
|
+
startup.stage = "discovery";
|
|
4367
|
+
await discover(AbortSignal.any([abort.signal, AbortSignal.timeout(STARTUP_DISCOVERY_MS)]));
|
|
4368
|
+
if (stopped) return;
|
|
4369
|
+
if (catalog.current().length === 0) ctx.logger.warn("dsh-codearts: CodeArts provider registered with an empty model catalog; models stay unavailable until discovery succeeds");
|
|
4370
|
+
startup.stage = "ready";
|
|
4371
|
+
writeDebugLog?.(`bootstrap: ready (catalog=${catalog.current().length})`);
|
|
4372
|
+
if (!stopped) scheduleDiscovery(nextDiscoveryDelay());
|
|
4373
|
+
}).catch((error) => {
|
|
4374
|
+
startup.error = error instanceof Error ? error.message : String(error);
|
|
4375
|
+
ctx.logger.error("dsh-codearts: loopback shim failed to start; provider not registered", error);
|
|
4376
|
+
});
|
|
4377
|
+
let startupTimedOut = false;
|
|
4378
|
+
await Promise.race([settled, new Promise((resolve) => {
|
|
4379
|
+
setTimeout(() => {
|
|
4380
|
+
startupTimedOut = true;
|
|
4381
|
+
resolve();
|
|
4382
|
+
}, STARTUP_WAIT_MS).unref?.();
|
|
4383
|
+
})]);
|
|
4384
|
+
if (startupTimedOut) ctx.logger.warn(`dsh-codearts: 启动等待超时(阶段 ${startup.stage},provider ${startup.registered ? "已注册" : "尚未注册"}),引导链继续在后台执行;可打开设置卡片查看体检,或读取 /api/codearts/doctor 自查`);
|
|
4385
|
+
}
|
|
4386
|
+
//#endregion
|
|
4387
|
+
export { BENEFIT_GATEWAY_HOST, CODEARTS_PROVIDER, CODEARTS_SETTINGS_NS, CodeArtsAccountPool, CodeArtsAccountStore, CodeArtsCatalog, CodeArtsCredentialStore, CodeArtsCreditCache, CodeArtsUsageTracker, Config, FALLBACK_CODEARTS_MODELS, SNAP_HOST, apply, canonicalModel, chatStream, codeartsAccountsPath, codeartsAuthPath, codeartsUsagePath, createCodeArtsAdapter, createCodeArtsShim, discoverModels, fetchCredits, fetchModels, filterEnabledModels, inject, maxTokensCeilingFor, name, parseCreditStatistics, parseTokenBalance, prepareChatBody, refreshCatalog };
|