dsh-zcode-startplan 0.4.5 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1963 -405
- package/README.md +88 -405
- package/bin/cli.mjs +509 -450
- package/client.js +2459 -716
- package/cordis.patch.yml +4 -2
- package/index.js +144 -14
- package/lib/adapter.js +476 -422
- package/lib/anthropic-body.js +513 -469
- package/lib/assemble.js +808 -420
- package/lib/auto-claim.js +229 -0
- package/lib/captcha/minter.js +61 -7
- package/lib/distribution-keys.js +202 -0
- package/lib/errors.js +281 -125
- package/lib/fallback.js +120 -0
- package/lib/local-endpoint.js +367 -352
- package/lib/manage-routes.js +1245 -489
- package/lib/model-catalog.js +57 -0
- package/lib/openai-gateway.js +776 -0
- package/lib/plan-client.js +942 -532
- package/lib/pool.js +771 -478
- package/lib/sse.js +429 -317
- package/lib/upstream-api.js +948 -570
- package/lib/upstream.js +294 -134
- package/lib/version-probe.js +110 -0
- package/package.json +84 -80
- package/scripts/analyze-grant-intervals.mjs +171 -0
- package/scripts/check-compat-rc3.mjs +21 -11
- package/scripts/debug-claimable.mjs +130 -0
- package/scripts/probe-marketing.mjs +203 -0
- package/scripts/restart-dsh.ps1 +119 -76
- package/scripts/test-claimed-pending.mjs +152 -0
- package/scripts/verify_compat.mjs +75 -64
- package/scripts/watch-marketing.mjs +155 -0
- package/tests/anthropic-body.test.mjs +305 -0
- package/tests/assembler-contract.test.mjs +256 -0
- package/tests/auto-claim.test.mjs +318 -0
- package/tests/claim-routes.test.mjs +438 -0
- package/tests/client-panel.test.mjs +1141 -0
- package/tests/distribution-keys.test.mjs +123 -0
- package/tests/e2e.test.mjs +388 -0
- package/tests/fallback-scrub.test.mjs +105 -0
- package/tests/fixtures/quota-200.json +1 -0
- package/tests/launch-command.test.mjs +68 -0
- package/tests/login-channel.test.mjs +102 -0
- package/tests/openai-gateway.test.mjs +454 -0
- package/tests/pinned-models.test.mjs +505 -0
- package/tests/plan-client.test.mjs +582 -0
- package/tests/pool.test.mjs +319 -0
- package/tests/quota-blackhole.test.mjs +409 -0
- package/tests/restart-script.test.mjs +53 -0
- package/tests/routing-quota.test.mjs +251 -0
- package/tests/sse.test.mjs +86 -0
- package/tests/stream-translator.test.mjs +137 -0
- package/tests/support/hanging-stream.mjs +48 -0
- package/tests/support/resolve-profile-deps.mjs +52 -0
- package/tests/upstream-error-200.test.mjs +164 -0
- package/tests/upstream.test.mjs +330 -0
- package/tests/version-probe.test.mjs +172 -0
package/lib/pool.js
CHANGED
|
@@ -1,478 +1,771 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 凭据库与账号池(多账号 + 手动顺序 + 账号×模型限流标记)。
|
|
3
|
-
*
|
|
4
|
-
* ## 与参考实现的差异
|
|
5
|
-
*
|
|
6
|
-
* 参考实现用 AES-256-GCM + DPAPI/钥匙串加密 `credentials.enc`。DSH 侧这里改为
|
|
7
|
-
* **Node 内置 `node:sqlite`**(Node ≥22.5)里的一张表,并把文件权限压到 600:
|
|
8
|
-
*
|
|
9
|
-
* - 不引入原生依赖(koffi/DPAPI 绑定在纯 ESM 插件里不可移植);
|
|
10
|
-
* - 账号池天然是「结构化状态」,SQLite 的原子写比「整体重写 JSON」安全;
|
|
11
|
-
* - 与 DSH 自己的 `.credentials.yaml` 互不干扰(各自独立文件)。
|
|
12
|
-
*
|
|
13
|
-
* ⚠ 不要把 DSH 的账号凭据贴进本文件所在的共享目录:它和 DSH 的凭据是**两套**,
|
|
14
|
-
* 一个是 DeepSeek 平台账号,一个是 ZCode 平台账号。
|
|
15
|
-
*
|
|
16
|
-
* ## 两条不可违背的既有约定(来自参考实现的实测教训)
|
|
17
|
-
*
|
|
18
|
-
* 1. **手动顺序即优先级**:不按「限流重置最早」重排 —— 那会让用户把某账号拖到
|
|
19
|
-
* 首位后,只要别的账号重置更早,选中的仍是后者(拖拽排序变成纯装饰)。
|
|
20
|
-
* 2. **绝不跨账号写凭据**:刷新 = 读该账号自己的凭据写回自己。参考实现曾因
|
|
21
|
-
* 「用 current() 的凭据覆盖每个账号」把两条账号记录变成同一个账号。
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
|
-
import { existsSync, mkdirSync, chmodSync } from 'node:fs'
|
|
25
|
-
import { dirname, join } from 'node:path'
|
|
26
|
-
import { randomUUID } from 'node:crypto'
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
'
|
|
32
|
-
'
|
|
33
|
-
'
|
|
34
|
-
'
|
|
35
|
-
'
|
|
36
|
-
'
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
return
|
|
43
|
-
|
|
44
|
-
typeof value.
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
#
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
this.#db
|
|
103
|
-
this.#db.exec(
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
this.#db
|
|
119
|
-
this.
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
*
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
.
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
.
|
|
160
|
-
|
|
161
|
-
return
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
if (
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
entry.
|
|
202
|
-
entry.
|
|
203
|
-
entry.
|
|
204
|
-
|
|
205
|
-
entry.
|
|
206
|
-
entry.
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
if (
|
|
216
|
-
this.#db
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
...
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
* `
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
/**
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
*
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
*
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
this
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
const
|
|
339
|
-
if (
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
this.#
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
return
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
1
|
+
/**
|
|
2
|
+
* 凭据库与账号池(多账号 + 手动顺序 + 账号×模型限流标记)。
|
|
3
|
+
*
|
|
4
|
+
* ## 与参考实现的差异
|
|
5
|
+
*
|
|
6
|
+
* 参考实现用 AES-256-GCM + DPAPI/钥匙串加密 `credentials.enc`。DSH 侧这里改为
|
|
7
|
+
* **Node 内置 `node:sqlite`**(Node ≥22.5)里的一张表,并把文件权限压到 600:
|
|
8
|
+
*
|
|
9
|
+
* - 不引入原生依赖(koffi/DPAPI 绑定在纯 ESM 插件里不可移植);
|
|
10
|
+
* - 账号池天然是「结构化状态」,SQLite 的原子写比「整体重写 JSON」安全;
|
|
11
|
+
* - 与 DSH 自己的 `.credentials.yaml` 互不干扰(各自独立文件)。
|
|
12
|
+
*
|
|
13
|
+
* ⚠ 不要把 DSH 的账号凭据贴进本文件所在的共享目录:它和 DSH 的凭据是**两套**,
|
|
14
|
+
* 一个是 DeepSeek 平台账号,一个是 ZCode 平台账号。
|
|
15
|
+
*
|
|
16
|
+
* ## 两条不可违背的既有约定(来自参考实现的实测教训)
|
|
17
|
+
*
|
|
18
|
+
* 1. **手动顺序即优先级**:不按「限流重置最早」重排 —— 那会让用户把某账号拖到
|
|
19
|
+
* 首位后,只要别的账号重置更早,选中的仍是后者(拖拽排序变成纯装饰)。
|
|
20
|
+
* 2. **绝不跨账号写凭据**:刷新 = 读该账号自己的凭据写回自己。参考实现曾因
|
|
21
|
+
* 「用 current() 的凭据覆盖每个账号」把两条账号记录变成同一个账号。
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { existsSync, mkdirSync, chmodSync } from 'node:fs'
|
|
25
|
+
import { dirname, join } from 'node:path'
|
|
26
|
+
import { randomUUID } from 'node:crypto'
|
|
27
|
+
import { MODEL_BUSY_TTL_MS } from './errors.js'
|
|
28
|
+
|
|
29
|
+
/** 账号条目(非敏感部分)。 */
|
|
30
|
+
export const ACCOUNT_FIELDS = Object.freeze([
|
|
31
|
+
'id',
|
|
32
|
+
'nickname',
|
|
33
|
+
'enabled',
|
|
34
|
+
'user_id',
|
|
35
|
+
'model_rate_limits',
|
|
36
|
+
'added_at',
|
|
37
|
+
'last_error',
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
/** 判断一份凭据对象是否可用(两个硬字段)。 */
|
|
41
|
+
export function isUsableCredential(value) {
|
|
42
|
+
if (typeof value !== 'object' || value === null) return false
|
|
43
|
+
return (
|
|
44
|
+
typeof value.zcode_jwt === 'string' && value.zcode_jwt.length > 0 &&
|
|
45
|
+
typeof value.device_mid === 'string' && value.device_mid.length > 0
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* SQLite 落盘实现(node:sqlite,Node ≥22.5)。
|
|
51
|
+
*
|
|
52
|
+
* ⚠ 目录建不出来(沙箱只读、权限不足、盘符不存在)时**回退到内存库**并明确告警:
|
|
53
|
+
* 此时账号池是「本进程内有效、重启即失」的 —— 不让「写不了磁盘」把整个插件变成不可用,
|
|
54
|
+
* 也不要静默吞掉(否则用户会以为账号保存成功了)。
|
|
55
|
+
*/
|
|
56
|
+
export class SqliteStore {
|
|
57
|
+
#db
|
|
58
|
+
#file
|
|
59
|
+
/** 本次用的库是不是内存库(供状态工具报告)。 */
|
|
60
|
+
inMemory = false
|
|
61
|
+
|
|
62
|
+
constructor(file) {
|
|
63
|
+
this.#file = file
|
|
64
|
+
let existed = false
|
|
65
|
+
try {
|
|
66
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
67
|
+
existed = existsSync(file)
|
|
68
|
+
} catch (error) {
|
|
69
|
+
/** 目录不可写:先记下原因,下面改用内存库。 */
|
|
70
|
+
this.mkdirError = error instanceof Error ? error : new Error(String(error))
|
|
71
|
+
}
|
|
72
|
+
// 动态 import 以便在旧运行时给出可读的降级,而不是模块加载即崩。
|
|
73
|
+
return this.#init(file, existed)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async #init(file, existed) {
|
|
77
|
+
let DatabaseSync
|
|
78
|
+
try {
|
|
79
|
+
;({ DatabaseSync } = await import('node:sqlite'))
|
|
80
|
+
} catch (error) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`node:sqlite 不可用(${error instanceof Error ? error.message : String(error)});` +
|
|
83
|
+
'请使用 Node ≥22.5',
|
|
84
|
+
)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const schema = `
|
|
88
|
+
CREATE TABLE IF NOT EXISTS accounts (
|
|
89
|
+
id TEXT PRIMARY KEY,
|
|
90
|
+
nickname TEXT NOT NULL,
|
|
91
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
92
|
+
user_id TEXT,
|
|
93
|
+
model_rate_limits TEXT NOT NULL DEFAULT '{}',
|
|
94
|
+
added_at INTEGER NOT NULL,
|
|
95
|
+
last_error TEXT,
|
|
96
|
+
credential TEXT NOT NULL
|
|
97
|
+
);
|
|
98
|
+
`
|
|
99
|
+
|
|
100
|
+
if (this.mkdirError === undefined) {
|
|
101
|
+
try {
|
|
102
|
+
this.#db = new DatabaseSync(file)
|
|
103
|
+
this.#db.exec(`PRAGMA journal_mode = WAL;`)
|
|
104
|
+
this.#db.exec(schema)
|
|
105
|
+
} catch (error) {
|
|
106
|
+
/** 文件打不开(权限 / 被占用 / 只读盘):降级到内存库。 */
|
|
107
|
+
this.mkdirError = error instanceof Error ? error : new Error(String(error))
|
|
108
|
+
try {
|
|
109
|
+
this.#db?.close()
|
|
110
|
+
} catch {
|
|
111
|
+
// 没打开成功。
|
|
112
|
+
}
|
|
113
|
+
this.#db = undefined
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (this.#db === undefined) {
|
|
118
|
+
this.#db = new DatabaseSync(':memory:')
|
|
119
|
+
this.#db.exec(schema)
|
|
120
|
+
this.inMemory = true
|
|
121
|
+
} else {
|
|
122
|
+
try {
|
|
123
|
+
if (!existed) chmodSync(file, 0o600)
|
|
124
|
+
} catch {
|
|
125
|
+
// Windows 上 chmod 语义有限;失败不阻塞。
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return this
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 读全部账号(按 added_at 升序 = 用户手动顺序)。
|
|
133
|
+
* @param {{ withCredentials?: boolean }} [options]
|
|
134
|
+
*/
|
|
135
|
+
list(options = {}) {
|
|
136
|
+
if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
|
|
137
|
+
const rows = this.#db
|
|
138
|
+
.prepare('SELECT id, nickname, enabled, user_id, model_rate_limits, added_at, last_error, credential FROM accounts ORDER BY added_at ASC, rowid ASC')
|
|
139
|
+
.all()
|
|
140
|
+
return rows.map((row) => {
|
|
141
|
+
const entry = {
|
|
142
|
+
id: row.id,
|
|
143
|
+
nickname: row.nickname,
|
|
144
|
+
enabled: row.enabled === 1,
|
|
145
|
+
user_id: row.user_id ?? undefined,
|
|
146
|
+
model_rate_limits: safeJson(row.model_rate_limits, {}),
|
|
147
|
+
added_at: row.added_at,
|
|
148
|
+
last_error: row.last_error ?? undefined,
|
|
149
|
+
}
|
|
150
|
+
if (options.withCredentials === true) entry.credential = safeJson(row.credential, undefined)
|
|
151
|
+
return entry
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 按 id 取一条(含凭据)。 */
|
|
156
|
+
get(id) {
|
|
157
|
+
if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
|
|
158
|
+
const row = this.#db
|
|
159
|
+
.prepare('SELECT id, nickname, enabled, user_id, model_rate_limits, added_at, last_error, credential FROM accounts WHERE id = ?')
|
|
160
|
+
.get(id)
|
|
161
|
+
if (row === undefined) return undefined
|
|
162
|
+
return {
|
|
163
|
+
id: row.id,
|
|
164
|
+
nickname: row.nickname,
|
|
165
|
+
enabled: row.enabled === 1,
|
|
166
|
+
user_id: row.user_id ?? undefined,
|
|
167
|
+
model_rate_limits: safeJson(row.model_rate_limits, {}),
|
|
168
|
+
added_at: row.added_at,
|
|
169
|
+
last_error: row.last_error ?? undefined,
|
|
170
|
+
credential: safeJson(row.credential, undefined),
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 按 user_id 找已有账号(去重判据是服务端下发的稳定 user_id)。
|
|
176
|
+
*/
|
|
177
|
+
findByUserId(userId) {
|
|
178
|
+
if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
|
|
179
|
+
const row = this.#db.prepare('SELECT id FROM accounts WHERE user_id = ?').get(userId)
|
|
180
|
+
return row?.id
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 插入或更新(必须带凭据)。 */
|
|
184
|
+
upsert(entry) {
|
|
185
|
+
if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
|
|
186
|
+
if (!isUsableCredential(entry.credential)) {
|
|
187
|
+
throw new Error('凭据形状不合法:必须同时有非空的 zcode_jwt 与 device_mid')
|
|
188
|
+
}
|
|
189
|
+
this.#db.prepare(`
|
|
190
|
+
INSERT INTO accounts (id, nickname, enabled, user_id, model_rate_limits, added_at, last_error, credential)
|
|
191
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
192
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
193
|
+
nickname = excluded.nickname,
|
|
194
|
+
enabled = excluded.enabled,
|
|
195
|
+
user_id = excluded.user_id,
|
|
196
|
+
model_rate_limits = excluded.model_rate_limits,
|
|
197
|
+
added_at = excluded.added_at,
|
|
198
|
+
last_error = excluded.last_error,
|
|
199
|
+
credential = excluded.credential
|
|
200
|
+
`).run(
|
|
201
|
+
entry.id,
|
|
202
|
+
entry.nickname,
|
|
203
|
+
entry.enabled ? 1 : 0,
|
|
204
|
+
entry.user_id ?? null,
|
|
205
|
+
JSON.stringify(entry.model_rate_limits ?? {}),
|
|
206
|
+
entry.added_at,
|
|
207
|
+
entry.last_error ?? null,
|
|
208
|
+
JSON.stringify(entry.credential),
|
|
209
|
+
)
|
|
210
|
+
return entry.id
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** 只更新凭据(**绝不跨账号**:调用方必须传该账号自己的 id)。 */
|
|
214
|
+
updateCredential(id, credential) {
|
|
215
|
+
if (!isUsableCredential(credential)) throw new Error('凭据形状不合法')
|
|
216
|
+
if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
|
|
217
|
+
this.#db.prepare('UPDATE accounts SET credential = ? WHERE id = ?').run(JSON.stringify(credential), id)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 部分字段更新。 */
|
|
221
|
+
patch(id, patch) {
|
|
222
|
+
if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
|
|
223
|
+
const current = this.get(id)
|
|
224
|
+
if (current === undefined) return false
|
|
225
|
+
this.upsert({
|
|
226
|
+
...current,
|
|
227
|
+
...patch,
|
|
228
|
+
id: current.id,
|
|
229
|
+
credential: patch.credential ?? current.credential,
|
|
230
|
+
})
|
|
231
|
+
return true
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 删除账号。返回是否真的删掉了。 */
|
|
235
|
+
remove(id) {
|
|
236
|
+
if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
|
|
237
|
+
const result = this.#db.prepare('DELETE FROM accounts WHERE id = ?').run(id)
|
|
238
|
+
return Number(result.changes) > 0
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** 关闭数据库。 */
|
|
242
|
+
close() {
|
|
243
|
+
try {
|
|
244
|
+
this.#db?.close()
|
|
245
|
+
} catch {
|
|
246
|
+
// 已关闭。
|
|
247
|
+
}
|
|
248
|
+
this.#db = undefined
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function safeJson(text, fallback) {
|
|
253
|
+
try {
|
|
254
|
+
return JSON.parse(text)
|
|
255
|
+
} catch {
|
|
256
|
+
return fallback
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* 账号池:选号 / 换号 / 限流标记 / CRUD。
|
|
262
|
+
*
|
|
263
|
+
* 选号规则(两档,排序由 `selectionOrder` 决定:**默认 `expiry`**——额度桶
|
|
264
|
+
* 快过期的先用;`manual` 才按用户拖拽的手动顺序):
|
|
265
|
+
* 1. `enabled=true` 且「该模型不在限流期」且**不忙** → 按选号顺序取第一个;
|
|
266
|
+
* 2. 全都不忙的没有时,回落到「忙」(3009 短窗标记)的账号 —— 忙是软状态,
|
|
267
|
+
* 排队等它好过空手报错;
|
|
268
|
+
* `exclude` 允许调用方在请求内逐个换号(否则换号形同虚设)。
|
|
269
|
+
*/
|
|
270
|
+
export class AccountPool {
|
|
271
|
+
#store
|
|
272
|
+
#log
|
|
273
|
+
#now
|
|
274
|
+
/** 进程内忙标记:`"${accountId}|${modelId}"` → busyUntil(不落库,见 markModelBusy)。 */
|
|
275
|
+
#busy = new Map()
|
|
276
|
+
/**
|
|
277
|
+
* 进程内「零内容观察窗」:`"${accountId}|${modelId}"` → until(1.0.1,不落库)。
|
|
278
|
+
*
|
|
279
|
+
* ⚠ 与 `markModelRateLimited`(当日硬过滤)不同级:这里只是**软优先**——
|
|
280
|
+
* 选号先避开观察中的账号,但所有账号都在观察时仍照常选(避免唯一账号
|
|
281
|
+
* 被一次抖动锁死整条链路)。`plan-client` 借它实现零内容两级证据:
|
|
282
|
+
* 窗口内再吃一次零内容才升级当日硬标记。
|
|
283
|
+
*/
|
|
284
|
+
#emptyContentWatch = new Map()
|
|
285
|
+
/**
|
|
286
|
+
* 进程内到期缓存:accountId → 最早的有余额桶到期时间(毫秒)。
|
|
287
|
+
* 由 manage-routes 的 /balance 拉取成功时回填(noteExpiry),pick 按「快过期先用」
|
|
288
|
+
* 排序消费。不落库:余额是上游现拉的数据,落库只会引入过期快照。
|
|
289
|
+
*/
|
|
290
|
+
#expiry = new Map()
|
|
291
|
+
/** 选号顺序:'expiry'(默认,快过期先用)| 'manual'(手动置顶优先)。 */
|
|
292
|
+
#selectionOrder = 'expiry'
|
|
293
|
+
/**
|
|
294
|
+
* **最近一次真实派发**的账号(1.0.0):`{ accountId, nickname, modelId, at }`。
|
|
295
|
+
*
|
|
296
|
+
* 统一选号意味着「选中的模型栏位」≠「真正吃额度的账号」—— 每次请求都可能换号。
|
|
297
|
+
* 模型栏旁的「当前使用账号」必须显示**这个**,而不是配置里的钉定账号。
|
|
298
|
+
* 由 plan-client 在选出账号后、发请求前回填;进程内状态,不落库。
|
|
299
|
+
*/
|
|
300
|
+
#lastRouted
|
|
301
|
+
|
|
302
|
+
constructor(options) {
|
|
303
|
+
this.#store = options.store
|
|
304
|
+
this.#log = options.log ?? (() => {})
|
|
305
|
+
this.#now = options.now ?? (() => Date.now())
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** 账号列表(默认脱敏,不含凭据)。 */
|
|
309
|
+
list(options = {}) {
|
|
310
|
+
return this.#store.list(options)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* 按 id 取单个账号。`store.get` 总是带凭据,这里按 `withCredentials` 决定
|
|
315
|
+
* 是否外发(与 `list` 的脱敏约定一致)。
|
|
316
|
+
*/
|
|
317
|
+
get(id, options = {}) {
|
|
318
|
+
const entry = this.#store.get(id)
|
|
319
|
+
if (entry === undefined) return undefined
|
|
320
|
+
if (options.withCredentials !== true) delete entry.credential
|
|
321
|
+
return entry
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** 启用中的账号数。 */
|
|
325
|
+
enabledCount() {
|
|
326
|
+
return this.list().filter((entry) => entry.enabled).length
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 添加账号(按 user_id 去重:已存在则只更新凭据与昵称)。
|
|
331
|
+
* @param {any} credential
|
|
332
|
+
* @param {string} [nickname]
|
|
333
|
+
* @returns {{ entry: any, created: boolean }}
|
|
334
|
+
*/
|
|
335
|
+
add(credential, nickname) {
|
|
336
|
+
if (!isUsableCredential(credential)) throw new Error('凭据形状不合法:需要 zcode_jwt 与 device_mid')
|
|
337
|
+
const label = (nickname ?? '').trim() || (credential.account_label ?? '').trim() || '未命名账号'
|
|
338
|
+
const userId = typeof credential.user_id === 'string' ? credential.user_id.trim() : ''
|
|
339
|
+
if (userId.length > 0) {
|
|
340
|
+
const existingId = this.#store.findByUserId(userId)
|
|
341
|
+
if (existingId !== undefined) {
|
|
342
|
+
this.#store.updateCredential(existingId, credential)
|
|
343
|
+
this.#store.patch(existingId, { nickname: label })
|
|
344
|
+
this.#log(`[pool] 账号已存在(user_id=${userId}),已更新凭据:${label}`)
|
|
345
|
+
return { entry: this.#store.get(existingId), created: false }
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
const id = randomUUID()
|
|
349
|
+
const entry = {
|
|
350
|
+
id,
|
|
351
|
+
nickname: label,
|
|
352
|
+
enabled: true,
|
|
353
|
+
user_id: userId.length > 0 ? userId : undefined,
|
|
354
|
+
model_rate_limits: {},
|
|
355
|
+
added_at: this.#now(),
|
|
356
|
+
credential,
|
|
357
|
+
}
|
|
358
|
+
this.#store.upsert(entry)
|
|
359
|
+
this.#log(`[pool] 已添加账号:${label}(${id})`)
|
|
360
|
+
return { entry: this.#store.get(id), created: true }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** 按序号 / id 前缀 / 昵称尾号找账号(CLI 与工具共用)。 */
|
|
364
|
+
resolve(reference) {
|
|
365
|
+
const needle = String(reference ?? '').trim()
|
|
366
|
+
if (needle.length === 0) return undefined
|
|
367
|
+
const entries = this.list()
|
|
368
|
+
const byIndex = Number(needle)
|
|
369
|
+
if (Number.isInteger(byIndex) && byIndex >= 1 && byIndex <= entries.length) return entries[byIndex - 1]
|
|
370
|
+
const exact = entries.find((entry) => entry.id === needle)
|
|
371
|
+
if (exact !== undefined) return exact
|
|
372
|
+
const prefixed = entries.find((entry) => entry.id.startsWith(needle))
|
|
373
|
+
if (prefixed !== undefined) return prefixed
|
|
374
|
+
const byName = entries.find((entry) => entry.nickname.includes(needle))
|
|
375
|
+
return byName
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** 启用 / 停用。 */
|
|
379
|
+
setEnabled(id, enabled) {
|
|
380
|
+
if (!this.#store.patch(id, { enabled })) throw new Error(`账号不存在:${id}`)
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 部分更新账号的**非敏感**字段(管理面板改备注走这里)。
|
|
385
|
+
* ⚠ 只白名单放行 `nickname`:凭据不允许从这条路改(改凭据必须走
|
|
386
|
+
* `updateCredential`,且只许用该账号自己的 id —— 见文件头第 2 条约定)。
|
|
387
|
+
*/
|
|
388
|
+
patchAccount(id, patch) {
|
|
389
|
+
const nickname = typeof patch?.nickname === 'string' ? patch.nickname.trim() : ''
|
|
390
|
+
if (nickname.length === 0) return false
|
|
391
|
+
return this.#store.patch(id, { nickname })
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** 删除。 */
|
|
395
|
+
remove(id) {
|
|
396
|
+
return this.#store.remove(id)
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** 重排(必须同一集合的一个排列,否则报错而不是尽力而为)。 */
|
|
400
|
+
reorder(orderedIds) {
|
|
401
|
+
const entries = this.list()
|
|
402
|
+
const expected = new Set(entries.map((entry) => entry.id))
|
|
403
|
+
const sameSet =
|
|
404
|
+
orderedIds.length === entries.length &&
|
|
405
|
+
new Set(orderedIds).size === orderedIds.length &&
|
|
406
|
+
orderedIds.every((id) => expected.has(id))
|
|
407
|
+
if (!sameSet) {
|
|
408
|
+
throw new Error(`账号列表已变化,请刷新后重试(期望 ${entries.length} 个账号,收到 ${orderedIds.length} 个)`)
|
|
409
|
+
}
|
|
410
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry]))
|
|
411
|
+
const base = this.#now()
|
|
412
|
+
orderedIds.forEach((id, index) => {
|
|
413
|
+
const entry = byId.get(id)
|
|
414
|
+
this.#store.patch(id, { added_at: base + index })
|
|
415
|
+
})
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 取下一个可用账号(两档)。
|
|
420
|
+
*
|
|
421
|
+
* 第一档:启用 + 未被 `exclude` + 该模型不在限流期 + **不忙**(3009 短窗标记)
|
|
422
|
+
* → 按选号顺序(默认 `expiry`)取第一个 —— 「另一个账号空闲时,请求路由到
|
|
423
|
+
* 空闲账号」就靠这一档。
|
|
424
|
+
* 第二档:第一档为空时,放宽忙标记(限流标记仍硬过滤),回落到忙账号排队。
|
|
425
|
+
*
|
|
426
|
+
* @param {string} modelId 目标模型(空串表示不按限流/忙过滤)
|
|
427
|
+
* @param {Set<string> | readonly string[]} [exclude] 本次请求已尝试过的账号 id
|
|
428
|
+
* @returns {{ entry: any, credential: any } | null}
|
|
429
|
+
*/
|
|
430
|
+
pick(modelId, exclude) {
|
|
431
|
+
for (const entry of this.candidates(modelId, exclude)) {
|
|
432
|
+
if (isUsableCredential(entry.credential)) return { entry, credential: entry.credential }
|
|
433
|
+
this.#log(`[pool] 账号 ${entry.id} 凭据不可用,已跳过`)
|
|
434
|
+
}
|
|
435
|
+
return null
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* 选号顺序策略:'expiry'(默认,快过期先用)| 'manual'(手动置顶优先)。
|
|
440
|
+
* 由 Config 下发(config.selectionOrder);两种策略下「使用」按钮语义见
|
|
441
|
+
* client.js —— expiry 模式下置顶不再决定取号顺序。
|
|
442
|
+
*/
|
|
443
|
+
setSelectionOrder(order) {
|
|
444
|
+
this.#selectionOrder = order === 'manual' ? 'manual' : 'expiry'
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
get selectionOrder() {
|
|
448
|
+
return this.#selectionOrder
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* 回填账号的「最早有余额桶到期时间」(/balance 拉取成功时调用)。
|
|
453
|
+
* expiresAtMs <= 0(全用光/未知)= 移除缓存条目(按无穷大排序)。
|
|
454
|
+
*/
|
|
455
|
+
noteExpiry(accountId, expiresAtMs) {
|
|
456
|
+
if (Number.isFinite(expiresAtMs) && expiresAtMs > 0) {
|
|
457
|
+
this.#expiry.set(accountId, expiresAtMs)
|
|
458
|
+
} else {
|
|
459
|
+
this.#expiry.delete(accountId)
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** 某账号当前的到期缓存值(观测用;无缓存 = undefined)。 */
|
|
464
|
+
expiryOf(accountId) {
|
|
465
|
+
return this.#expiry.get(accountId)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* 记一次**真实派发**(统一选号每请求都会调;钉定栏位同样回填 ——
|
|
470
|
+
* 「当前使用账号」对两种栏位都成立,只是文案不同)。
|
|
471
|
+
*
|
|
472
|
+
* ⚠ 审计修复(1.0.1):`outcome` 必须由调用方在**每次尝试真正发出去之前**
|
|
473
|
+
* 提供 —— 此前只在进入账号轮次时记一次,若该账号随后被上游判额度用尽、
|
|
474
|
+
* 换号成功,徽标会一直显示那个**没在服务**的账号(正是最需要看准的时刻)。
|
|
475
|
+
* 约定:
|
|
476
|
+
* - `'outcome'` 缺省 = 派发前占位(`attempting`);
|
|
477
|
+
* - 命中即 `'ok'`;被判额度用尽 `'exhausted'`;其它失败仍为 `'attempting'`。
|
|
478
|
+
*
|
|
479
|
+
* @param {string} accountId 实际吃这次请求额度的账号
|
|
480
|
+
* @param {string} [modelId] 实际发出的模型 id(基础模型,不含 @acct: 后缀)
|
|
481
|
+
* @param {{ outcome?: 'attempting' | 'ok' | 'exhausted', reason?: string }} [detail]
|
|
482
|
+
* @returns {{ accountId: string, nickname: string, modelId: string, at: number, outcome: string } | undefined}
|
|
483
|
+
*/
|
|
484
|
+
noteRouted(accountId, modelId, detail = {}) {
|
|
485
|
+
if (typeof accountId !== 'string' || accountId.length === 0) return this.#lastRouted
|
|
486
|
+
const entry = this.#store.get(accountId)
|
|
487
|
+
this.#lastRouted = {
|
|
488
|
+
accountId,
|
|
489
|
+
nickname: typeof entry?.nickname === 'string' ? entry.nickname : accountId.slice(0, 8),
|
|
490
|
+
modelId: typeof modelId === 'string' ? modelId : '',
|
|
491
|
+
at: this.#now(),
|
|
492
|
+
outcome: detail.outcome ?? 'attempting',
|
|
493
|
+
...(typeof detail.reason === 'string' && detail.reason.length > 0 ? { reason: detail.reason } : {}),
|
|
494
|
+
}
|
|
495
|
+
return this.#lastRouted
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** 最近一次真实派发(观测用;启动后尚未发过请求时为 undefined)。 */
|
|
499
|
+
lastRouted() {
|
|
500
|
+
return this.#lastRouted
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* 候选账号(**`pick` 与 `previewOrder` 的唯一来源**)。
|
|
505
|
+
*
|
|
506
|
+
* 审计结论(1.0.1):预览曾经只按排序截取列表,不复刻 `pick` 的筛选 ——
|
|
507
|
+
* 于是「本模型限流中 / 凭据不可用 / 忙」的账号会被预览成「下一条会用它」,
|
|
508
|
+
* 而真实派发会跳过它,徽标在第一次请求前必说谎。这里把筛选收敛到一处,
|
|
509
|
+
* 两个消费者共用,**不允许**再各写一套。
|
|
510
|
+
*
|
|
511
|
+
* 两档语义与 `pick` 一一对应:
|
|
512
|
+
* - 第一档:启用 + 未 exclude + 该模型未限流 + **不忙**;
|
|
513
|
+
* - 第二档:仅当第一档为空时放宽忙标记(限流标记仍硬过滤)。
|
|
514
|
+
*
|
|
515
|
+
* @param {string} modelId 空串表示不按限流/忙过滤(与 `pick` 一致)
|
|
516
|
+
* @param {Set<string> | readonly string[]} [exclude]
|
|
517
|
+
* @returns {Array<any>} 已按选号顺序排好的候选
|
|
518
|
+
*/
|
|
519
|
+
candidates(modelId, exclude) {
|
|
520
|
+
const excluded = exclude instanceof Set ? exclude : new Set(exclude ?? [])
|
|
521
|
+
const now = this.#now()
|
|
522
|
+
const byModel = (entry) => {
|
|
523
|
+
if (!entry.enabled) return false
|
|
524
|
+
if (excluded.has(entry.id)) return false
|
|
525
|
+
if (typeof modelId !== 'string' || modelId.length === 0) return true
|
|
526
|
+
const resetAt = entry.model_rate_limits?.[modelId]
|
|
527
|
+
if (resetAt !== undefined && resetAt !== 0 && now < resetAt) return false
|
|
528
|
+
/** 过了硬标记就一律放行 —— `last_error` **不是**选号判据(历史文本、无时间戳)。 */
|
|
529
|
+
return true
|
|
530
|
+
}
|
|
531
|
+
const withCredentials = this.list({ withCredentials: true })
|
|
532
|
+
/**
|
|
533
|
+
* 排序(0.7.0,默认策略 = expiry):**快过期的先用**。
|
|
534
|
+
* 每个账号的额度桶到期时间不同 —— 先吃快过期账号的额度,能减少
|
|
535
|
+
* 「到期作废」的浪费;没有到期数据的账号(还没拉过余额)按无穷大排后,
|
|
536
|
+
* 但仍参与选号(不因缺数据被跳过)。手动排序(/use 置顶)在 expiry 模式
|
|
537
|
+
* 下不再决定取号顺序 —— 两种策略互斥,见 selectionOrder。
|
|
538
|
+
*/
|
|
539
|
+
const order = this.#selectionOrder === 'expiry' ? 'expiry' : 'manual'
|
|
540
|
+
const byOrder = (a, b) => {
|
|
541
|
+
if (order === 'expiry') {
|
|
542
|
+
const ea = this.#expiry.get(a.id) ?? Number.POSITIVE_INFINITY
|
|
543
|
+
const eb = this.#expiry.get(b.id) ?? Number.POSITIVE_INFINITY
|
|
544
|
+
if (ea !== eb) return ea - eb
|
|
545
|
+
}
|
|
546
|
+
return a.added_at - b.added_at
|
|
547
|
+
}
|
|
548
|
+
const tier = (entries) => [...entries].sort(byOrder)
|
|
549
|
+
/** 第一档:避开忙账号与零内容观察中的账号(两者都是软优先)。 */
|
|
550
|
+
const candidates = tier(
|
|
551
|
+
withCredentials.filter(
|
|
552
|
+
(entry) => byModel(entry) && !this.isModelBusy(entry.id, modelId) && !this.isEmptyContentWatched(entry.id, modelId),
|
|
553
|
+
),
|
|
554
|
+
)
|
|
555
|
+
/** 第二档:全部忙/观察中时放宽(限流标记仍硬过滤),排队等待。 */
|
|
556
|
+
if (candidates.length === 0 && typeof modelId === 'string' && modelId.length > 0) {
|
|
557
|
+
candidates.push(...tier(withCredentials.filter((entry) => byModel(entry))))
|
|
558
|
+
}
|
|
559
|
+
return candidates
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* 下一次取号的候选顺序(**只读预览**,与 `pick` 同一套筛选与排序,不消耗状态)。
|
|
564
|
+
*
|
|
565
|
+
* 用途:模型栏旁的「当前使用账号」在**还没派发过**时,显示「下一条会用谁」——
|
|
566
|
+
* 比显示「未知」有用得多。`pick` 有 modelId 时才有完整语义,所以调用方
|
|
567
|
+
* **必须**带上当前选中的模型;缺省空串只表示「不按模型过滤」,不是等价物。
|
|
568
|
+
*
|
|
569
|
+
* `expiresAt` 语义:`null` = 该账号**没有**有效的到期数据(`pick` 按无穷大排序,
|
|
570
|
+
* 与「未知」无关),`number` = `pick` 实际用于排序的毫秒时间戳。
|
|
571
|
+
*
|
|
572
|
+
* @param {string} [modelId] 当前选中的基础模型 id
|
|
573
|
+
* @param {number} [limit] 最多返回几个
|
|
574
|
+
* @returns {Array<{ accountId: string, nickname: string, expiresAt: number | null }>}
|
|
575
|
+
*/
|
|
576
|
+
previewOrder(modelId = '', limit = 3) {
|
|
577
|
+
/** `candidates` 已按选号顺序排好;凭据不可用者与 `pick` 一样跳过。 */
|
|
578
|
+
const sorted = this.candidates(typeof modelId === 'string' ? modelId : '', undefined)
|
|
579
|
+
.filter((entry) => isUsableCredential(entry.credential))
|
|
580
|
+
.slice(0, Math.max(0, limit))
|
|
581
|
+
return sorted.map((entry) => {
|
|
582
|
+
const expiresAt = this.#expiry.get(entry.id)
|
|
583
|
+
return {
|
|
584
|
+
accountId: entry.id,
|
|
585
|
+
nickname: entry.nickname,
|
|
586
|
+
expiresAt: Number.isFinite(expiresAt) ? expiresAt : null,
|
|
587
|
+
}
|
|
588
|
+
})
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** 标记「账号 × 模型」在 resetAt 之前不可用(**额度用尽**级:硬过滤)。 */
|
|
592
|
+
markModelRateLimited(accountId, modelId, resetAtMs) {
|
|
593
|
+
const entry = this.#store.get(accountId)
|
|
594
|
+
if (entry === undefined) {
|
|
595
|
+
this.#log(`[pool] markModelRateLimited: 账号 ${accountId} 不在池中,已忽略`)
|
|
596
|
+
return
|
|
597
|
+
}
|
|
598
|
+
const limits = { ...(entry.model_rate_limits ?? {}), [modelId]: resetAtMs }
|
|
599
|
+
this.#store.patch(accountId, { model_rate_limits: limits })
|
|
600
|
+
this.#log(`[pool] 已标记限流:${entry.nickname} × ${modelId} → ${new Date(resetAtMs).toISOString()}`)
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* 标记「账号 × 模型」忙(**3009 并发限流**级:软优先级,硬过滤的是额度标记)。
|
|
605
|
+
*
|
|
606
|
+
* 进程内存放,**刻意不落库**:忙是秒级瞬态,写库只会让重启后的残留标记
|
|
607
|
+
* 平白多绕开账号一分钟;额度用尽那种要跨重启的状态才值得落盘。
|
|
608
|
+
* resetAtMs 缺省 = now + MODEL_BUSY_TTL_MS。
|
|
609
|
+
*/
|
|
610
|
+
markModelBusy(accountId, modelId, resetAtMs) {
|
|
611
|
+
const now = this.#now()
|
|
612
|
+
const until = typeof resetAtMs === 'number' && resetAtMs > now ? resetAtMs : now + MODEL_BUSY_TTL_MS
|
|
613
|
+
const previous = this.#busy.get(`${accountId}|${modelId}`) ?? 0
|
|
614
|
+
if (until <= previous) return
|
|
615
|
+
this.#busy.set(`${accountId}|${modelId}`, until)
|
|
616
|
+
this.#log(`[pool] 已标记忙(3009):${accountId} × ${modelId},${Math.ceil((until - now) / 1000)}s 内优先绕开`)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* 「账号 × 模型」的**启用侧额度视图**(`/routing` 与徽标用)。
|
|
621
|
+
*
|
|
622
|
+
* ⚠ 审计根因(1.0.1):面板的「额度开启」来自 `/balance`,它统计的是上游
|
|
623
|
+
* `data.balances` 里**所有已激活 plan 的桶**;而对话准入看的是**当前生效**的
|
|
624
|
+
* 那一桶 —— 上游 `balances` 可以列出余额为 0 的桶(尚未生效的 entitlement、
|
|
625
|
+
* 已过期的旧桶),于是出现「面板显示有额度、对话立刻 1005/零内容」。
|
|
626
|
+
*
|
|
627
|
+
* 这里不改上游数据,只把「准入判定依据」显式化,**三个口径各说各的**:
|
|
628
|
+
* - `available`:面板口径(上游余额接口的生效桶还有没有余额),
|
|
629
|
+
* **原样透传**:`true`/`false`/`null`(未知),绝不被准入否决洗掉 ——
|
|
630
|
+
* 否则「面板有额度但被拒」这个冲突组合无法在 UI 上呈现;
|
|
631
|
+
* - `limited`:被 1005 之类的当日标记硬过滤;
|
|
632
|
+
* - `expired`:当前时间已过 `expiresAt`(缓存值,可能滞后一个 TTL);
|
|
633
|
+
* - `usable`:综合结论 = `available === true` 且无否决位;未知保持 `null`。
|
|
634
|
+
*
|
|
635
|
+
* @param {object} quota 面板口径缓存 `{ available: boolean | null, expiresAt: number | null }`
|
|
636
|
+
* @returns {{ available: boolean | null, limited: boolean, expired: boolean, usable: boolean | null, reason: string | null }}
|
|
637
|
+
*/
|
|
638
|
+
quotaState(accountId, modelId, quota) {
|
|
639
|
+
const now = this.#now()
|
|
640
|
+
const resetAt = this.get(accountId)?.model_rate_limits?.[modelId]
|
|
641
|
+
const limited = typeof resetAt === 'number' && resetAt > 0 && now < resetAt
|
|
642
|
+
const expiresAt = quota?.expiresAt
|
|
643
|
+
const expired = Number.isFinite(expiresAt) && expiresAt > 0 && now >= expiresAt
|
|
644
|
+
/** 面板口径原样透传;「未知」是独立语义,不许洗成 true 或 false。 */
|
|
645
|
+
const available = typeof quota?.available === 'boolean' ? quota.available : null
|
|
646
|
+
const vetoed = limited || expired
|
|
647
|
+
const usable = vetoed ? false : available
|
|
648
|
+
let reason = null
|
|
649
|
+
if (limited) reason = '上游已判额度用尽(1005/1113)——等待重置或换号'
|
|
650
|
+
else if (expired) reason = '额度桶已过期(缓存值,可能滞后)'
|
|
651
|
+
return { available, limited, expired, usable, reason }
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** 「账号 × 模型」当前是否忙(标记不存在或已过期 = 不忙)。 */
|
|
655
|
+
isModelBusy(accountId, modelId) {
|
|
656
|
+
const until = this.#busy.get(`${accountId}|${modelId}`) ?? 0
|
|
657
|
+
return this.#now() < until
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** 清除某账号的忙标记(modelId 缺省清该账号全部)。 */
|
|
661
|
+
clearModelBusy(accountId, modelId) {
|
|
662
|
+
if (typeof modelId === 'string' && modelId.length > 0) {
|
|
663
|
+
this.#busy.delete(`${accountId}|${modelId}`)
|
|
664
|
+
return
|
|
665
|
+
}
|
|
666
|
+
for (const key of this.#busy.keys()) {
|
|
667
|
+
if (key.startsWith(`${accountId}|`)) this.#busy.delete(key)
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** 当前处于忙标记中的「账号 × 模型」数(状态工具观测用)。 */
|
|
672
|
+
busyCount() {
|
|
673
|
+
const now = this.#now()
|
|
674
|
+
let count = 0
|
|
675
|
+
for (const until of this.#busy.values()) {
|
|
676
|
+
if (now < until) count += 1
|
|
677
|
+
}
|
|
678
|
+
return count
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* 零内容观察窗(1.0.1,软优先):标记「该账号×模型刚吃过一次零内容」,
|
|
683
|
+
* pick 第一档先避开它;全部账号都在观察时仍照常选(避免唯一账号被
|
|
684
|
+
* 一次抖动锁死)。until 缺省 = now + windowMs。
|
|
685
|
+
*
|
|
686
|
+
* ⚠ 刻意**不进** `model_rate_limits`:那张表是当日级硬过滤(落库),
|
|
687
|
+
* 短窗放进去会让唯一账号被选不到 → 两级证据永远走不到第二次。
|
|
688
|
+
*/
|
|
689
|
+
noteEmptyContentWatch(accountId, modelId, untilMs) {
|
|
690
|
+
if (typeof accountId !== 'string' || accountId.length === 0) return
|
|
691
|
+
const now = this.#now()
|
|
692
|
+
const until = typeof untilMs === 'number' && untilMs > now ? untilMs : now + MODEL_BUSY_TTL_MS
|
|
693
|
+
const previous = this.#emptyContentWatch.get(`${accountId}|${modelId}`) ?? 0
|
|
694
|
+
if (until <= previous) return
|
|
695
|
+
this.#emptyContentWatch.set(`${accountId}|${modelId}`, until)
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** 该账号×模型是否在零内容观察窗内(pick 第一档避开用;也是两级证据的第二级判据)。 */
|
|
699
|
+
isEmptyContentWatched(accountId, modelId) {
|
|
700
|
+
const until = this.#emptyContentWatch.get(`${accountId}|${modelId}`) ?? 0
|
|
701
|
+
return this.#now() < until
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/** 清除某账号的零内容观察窗(modelId 缺省清该账号全部;命中产出时调用)。 */
|
|
705
|
+
clearEmptyContentWatch(accountId, modelId) {
|
|
706
|
+
if (typeof modelId === 'string' && modelId.length > 0) {
|
|
707
|
+
this.#emptyContentWatch.delete(`${accountId}|${modelId}`)
|
|
708
|
+
return
|
|
709
|
+
}
|
|
710
|
+
for (const key of this.#emptyContentWatch.keys()) {
|
|
711
|
+
if (key.startsWith(`${accountId}|`)) this.#emptyContentWatch.delete(key)
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/** 清除某账号的限流标记(默认全清)。 */
|
|
716
|
+
clearModelRateLimits(accountId, modelIds) {
|
|
717
|
+
const entry = this.#store.get(accountId)
|
|
718
|
+
if (entry === undefined) return 0
|
|
719
|
+
const limits = { ...(entry.model_rate_limits ?? {}) }
|
|
720
|
+
let removed = 0
|
|
721
|
+
for (const modelId of modelIds ?? Object.keys(limits)) {
|
|
722
|
+
if (Object.prototype.hasOwnProperty.call(limits, modelId)) {
|
|
723
|
+
delete limits[modelId]
|
|
724
|
+
removed += 1
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (removed > 0) this.#store.patch(accountId, { model_rate_limits: limits })
|
|
728
|
+
return removed
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** 清理已过期的标记。 */
|
|
732
|
+
sweepExpired() {
|
|
733
|
+
for (const entry of this.list()) {
|
|
734
|
+
const limits = { ...(entry.model_rate_limits ?? {}) }
|
|
735
|
+
let changed = false
|
|
736
|
+
for (const [modelId, resetAt] of Object.entries(limits)) {
|
|
737
|
+
if (resetAt > 0 && this.#now() >= resetAt) {
|
|
738
|
+
delete limits[modelId]
|
|
739
|
+
changed = true
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (changed) this.#store.patch(entry.id, { model_rate_limits: limits })
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** 记下某个账号最近一次失败原因(面板/状态工具展示用)。 */
|
|
747
|
+
noteError(accountId, message) {
|
|
748
|
+
this.#store.patch(accountId, { last_error: message })
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** 默认数据目录:`~/.dsh/zcode-start-plan`(可用环境变量覆盖)。 */
|
|
753
|
+
export function resolveDataDir(env = process.env) {
|
|
754
|
+
const fromEnv = env['ZCODE_START_PLAN_DATA_DIR']
|
|
755
|
+
if (typeof fromEnv === 'string' && fromEnv.trim().length > 0) return fromEnv.trim()
|
|
756
|
+
const home = env['USERPROFILE'] ?? env['HOME'] ?? '.'
|
|
757
|
+
return join(home, '.dsh', 'zcode-start-plan')
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* 账号库文件路径。
|
|
762
|
+
*
|
|
763
|
+
* `dataDir` 显式传入时以它为准(Config 的 `dataDir` 走这条路)——
|
|
764
|
+
* 否则插件在测试/多实例场景下会悄悄读写**用户的真实账号库**。
|
|
765
|
+
*/
|
|
766
|
+
export function resolveDbFile(env = process.env, dataDir) {
|
|
767
|
+
if (typeof dataDir === 'string' && dataDir.trim().length > 0) {
|
|
768
|
+
return join(dataDir.trim(), 'accounts.db')
|
|
769
|
+
}
|
|
770
|
+
return join(resolveDataDir(env), 'accounts.db')
|
|
771
|
+
}
|