dsh-zcode-startplan 0.0.0-stage → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/pool.js ADDED
@@ -0,0 +1,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
+
28
+ /** 账号条目(非敏感部分)。 */
29
+ export const ACCOUNT_FIELDS = Object.freeze([
30
+ 'id',
31
+ 'nickname',
32
+ 'enabled',
33
+ 'user_id',
34
+ 'model_rate_limits',
35
+ 'added_at',
36
+ 'last_error',
37
+ ])
38
+
39
+ /** 判断一份凭据对象是否可用(两个硬字段)。 */
40
+ export function isUsableCredential(value) {
41
+ if (typeof value !== 'object' || value === null) return false
42
+ return (
43
+ typeof value.zcode_jwt === 'string' && value.zcode_jwt.length > 0 &&
44
+ typeof value.device_mid === 'string' && value.device_mid.length > 0
45
+ )
46
+ }
47
+
48
+ /**
49
+ * SQLite 落盘实现(node:sqlite,Node ≥22.5)。
50
+ *
51
+ * ⚠ 目录建不出来(沙箱只读、权限不足、盘符不存在)时**回退到内存库**并明确告警:
52
+ * 此时账号池是「本进程内有效、重启即失」的 —— 不让「写不了磁盘」把整个插件变成不可用,
53
+ * 也不要静默吞掉(否则用户会以为账号保存成功了)。
54
+ */
55
+ export class SqliteStore {
56
+ #db
57
+ #file
58
+ /** 本次用的库是不是内存库(供状态工具报告)。 */
59
+ inMemory = false
60
+
61
+ constructor(file) {
62
+ this.#file = file
63
+ let existed = false
64
+ try {
65
+ mkdirSync(dirname(file), { recursive: true })
66
+ existed = existsSync(file)
67
+ } catch (error) {
68
+ /** 目录不可写:先记下原因,下面改用内存库。 */
69
+ this.mkdirError = error instanceof Error ? error : new Error(String(error))
70
+ }
71
+ // 动态 import 以便在旧运行时给出可读的降级,而不是模块加载即崩。
72
+ return this.#init(file, existed)
73
+ }
74
+
75
+ async #init(file, existed) {
76
+ let DatabaseSync
77
+ try {
78
+ ;({ DatabaseSync } = await import('node:sqlite'))
79
+ } catch (error) {
80
+ throw new Error(
81
+ `node:sqlite 不可用(${error instanceof Error ? error.message : String(error)});` +
82
+ '请使用 Node ≥22.5',
83
+ )
84
+ }
85
+
86
+ const schema = `
87
+ CREATE TABLE IF NOT EXISTS accounts (
88
+ id TEXT PRIMARY KEY,
89
+ nickname TEXT NOT NULL,
90
+ enabled INTEGER NOT NULL DEFAULT 1,
91
+ user_id TEXT,
92
+ model_rate_limits TEXT NOT NULL DEFAULT '{}',
93
+ added_at INTEGER NOT NULL,
94
+ last_error TEXT,
95
+ credential TEXT NOT NULL
96
+ );
97
+ `
98
+
99
+ if (this.mkdirError === undefined) {
100
+ try {
101
+ this.#db = new DatabaseSync(file)
102
+ this.#db.exec(`PRAGMA journal_mode = WAL;`)
103
+ this.#db.exec(schema)
104
+ } catch (error) {
105
+ /** 文件打不开(权限 / 被占用 / 只读盘):降级到内存库。 */
106
+ this.mkdirError = error instanceof Error ? error : new Error(String(error))
107
+ try {
108
+ this.#db?.close()
109
+ } catch {
110
+ // 没打开成功。
111
+ }
112
+ this.#db = undefined
113
+ }
114
+ }
115
+
116
+ if (this.#db === undefined) {
117
+ this.#db = new DatabaseSync(':memory:')
118
+ this.#db.exec(schema)
119
+ this.inMemory = true
120
+ } else {
121
+ try {
122
+ if (!existed) chmodSync(file, 0o600)
123
+ } catch {
124
+ // Windows 上 chmod 语义有限;失败不阻塞。
125
+ }
126
+ }
127
+ return this
128
+ }
129
+
130
+ /**
131
+ * 读全部账号(按 added_at 升序 = 用户手动顺序)。
132
+ * @param {{ withCredentials?: boolean }} [options]
133
+ */
134
+ list(options = {}) {
135
+ if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
136
+ const rows = this.#db
137
+ .prepare('SELECT id, nickname, enabled, user_id, model_rate_limits, added_at, last_error, credential FROM accounts ORDER BY added_at ASC, rowid ASC')
138
+ .all()
139
+ return rows.map((row) => {
140
+ const entry = {
141
+ id: row.id,
142
+ nickname: row.nickname,
143
+ enabled: row.enabled === 1,
144
+ user_id: row.user_id ?? undefined,
145
+ model_rate_limits: safeJson(row.model_rate_limits, {}),
146
+ added_at: row.added_at,
147
+ last_error: row.last_error ?? undefined,
148
+ }
149
+ if (options.withCredentials === true) entry.credential = safeJson(row.credential, undefined)
150
+ return entry
151
+ })
152
+ }
153
+
154
+ /** 按 id 取一条(含凭据)。 */
155
+ get(id) {
156
+ if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
157
+ const row = this.#db
158
+ .prepare('SELECT id, nickname, enabled, user_id, model_rate_limits, added_at, last_error, credential FROM accounts WHERE id = ?')
159
+ .get(id)
160
+ if (row === undefined) return undefined
161
+ return {
162
+ id: row.id,
163
+ nickname: row.nickname,
164
+ enabled: row.enabled === 1,
165
+ user_id: row.user_id ?? undefined,
166
+ model_rate_limits: safeJson(row.model_rate_limits, {}),
167
+ added_at: row.added_at,
168
+ last_error: row.last_error ?? undefined,
169
+ credential: safeJson(row.credential, undefined),
170
+ }
171
+ }
172
+
173
+ /**
174
+ * 按 user_id 找已有账号(去重判据是服务端下发的稳定 user_id)。
175
+ */
176
+ findByUserId(userId) {
177
+ if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
178
+ const row = this.#db.prepare('SELECT id FROM accounts WHERE user_id = ?').get(userId)
179
+ return row?.id
180
+ }
181
+
182
+ /** 插入或更新(必须带凭据)。 */
183
+ upsert(entry) {
184
+ if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
185
+ if (!isUsableCredential(entry.credential)) {
186
+ throw new Error('凭据形状不合法:必须同时有非空的 zcode_jwt 与 device_mid')
187
+ }
188
+ this.#db.prepare(`
189
+ INSERT INTO accounts (id, nickname, enabled, user_id, model_rate_limits, added_at, last_error, credential)
190
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
191
+ ON CONFLICT(id) DO UPDATE SET
192
+ nickname = excluded.nickname,
193
+ enabled = excluded.enabled,
194
+ user_id = excluded.user_id,
195
+ model_rate_limits = excluded.model_rate_limits,
196
+ added_at = excluded.added_at,
197
+ last_error = excluded.last_error,
198
+ credential = excluded.credential
199
+ `).run(
200
+ entry.id,
201
+ entry.nickname,
202
+ entry.enabled ? 1 : 0,
203
+ entry.user_id ?? null,
204
+ JSON.stringify(entry.model_rate_limits ?? {}),
205
+ entry.added_at,
206
+ entry.last_error ?? null,
207
+ JSON.stringify(entry.credential),
208
+ )
209
+ return entry.id
210
+ }
211
+
212
+ /** 只更新凭据(**绝不跨账号**:调用方必须传该账号自己的 id)。 */
213
+ updateCredential(id, credential) {
214
+ if (!isUsableCredential(credential)) throw new Error('凭据形状不合法')
215
+ if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
216
+ this.#db.prepare('UPDATE accounts SET credential = ? WHERE id = ?').run(JSON.stringify(credential), id)
217
+ }
218
+
219
+ /** 部分字段更新。 */
220
+ patch(id, patch) {
221
+ if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
222
+ const current = this.get(id)
223
+ if (current === undefined) return false
224
+ this.upsert({
225
+ ...current,
226
+ ...patch,
227
+ id: current.id,
228
+ credential: patch.credential ?? current.credential,
229
+ })
230
+ return true
231
+ }
232
+
233
+ /** 删除账号。返回是否真的删掉了。 */
234
+ remove(id) {
235
+ if (this.#db === undefined) throw new Error('SqliteStore 尚未初始化')
236
+ const result = this.#db.prepare('DELETE FROM accounts WHERE id = ?').run(id)
237
+ return Number(result.changes) > 0
238
+ }
239
+
240
+ /** 关闭数据库。 */
241
+ close() {
242
+ try {
243
+ this.#db?.close()
244
+ } catch {
245
+ // 已关闭。
246
+ }
247
+ this.#db = undefined
248
+ }
249
+ }
250
+
251
+ function safeJson(text, fallback) {
252
+ try {
253
+ return JSON.parse(text)
254
+ } catch {
255
+ return fallback
256
+ }
257
+ }
258
+
259
+ /**
260
+ * 账号池:选号 / 换号 / 限流标记 / CRUD。
261
+ *
262
+ * 选号规则:`enabled=true` 且「该模型不在限流期」→ 按**手动顺序**取第一个;
263
+ * `exclude` 允许调用方在请求内逐个换号(否则换号形同虚设)。
264
+ */
265
+ export class AccountPool {
266
+ #store
267
+ #log
268
+ #now
269
+
270
+ constructor(options) {
271
+ this.#store = options.store
272
+ this.#log = options.log ?? (() => {})
273
+ this.#now = options.now ?? (() => Date.now())
274
+ }
275
+
276
+ /** 账号列表(默认脱敏,不含凭据)。 */
277
+ list(options = {}) {
278
+ return this.#store.list(options)
279
+ }
280
+
281
+ /**
282
+ * 按 id 取单个账号。`store.get` 总是带凭据,这里按 `withCredentials` 决定
283
+ * 是否外发(与 `list` 的脱敏约定一致)。
284
+ */
285
+ get(id, options = {}) {
286
+ const entry = this.#store.get(id)
287
+ if (entry === undefined) return undefined
288
+ if (options.withCredentials !== true) delete entry.credential
289
+ return entry
290
+ }
291
+
292
+ /** 启用中的账号数。 */
293
+ enabledCount() {
294
+ return this.list().filter((entry) => entry.enabled).length
295
+ }
296
+
297
+ /**
298
+ * 添加账号(按 user_id 去重:已存在则只更新凭据与昵称)。
299
+ * @param {any} credential
300
+ * @param {string} [nickname]
301
+ * @returns {{ entry: any, created: boolean }}
302
+ */
303
+ add(credential, nickname) {
304
+ if (!isUsableCredential(credential)) throw new Error('凭据形状不合法:需要 zcode_jwt 与 device_mid')
305
+ const label = (nickname ?? '').trim() || (credential.account_label ?? '').trim() || '未命名账号'
306
+ const userId = typeof credential.user_id === 'string' ? credential.user_id.trim() : ''
307
+ if (userId.length > 0) {
308
+ const existingId = this.#store.findByUserId(userId)
309
+ if (existingId !== undefined) {
310
+ this.#store.updateCredential(existingId, credential)
311
+ this.#store.patch(existingId, { nickname: label })
312
+ this.#log(`[pool] 账号已存在(user_id=${userId}),已更新凭据:${label}`)
313
+ return { entry: this.#store.get(existingId), created: false }
314
+ }
315
+ }
316
+ const id = randomUUID()
317
+ const entry = {
318
+ id,
319
+ nickname: label,
320
+ enabled: true,
321
+ user_id: userId.length > 0 ? userId : undefined,
322
+ model_rate_limits: {},
323
+ added_at: this.#now(),
324
+ credential,
325
+ }
326
+ this.#store.upsert(entry)
327
+ this.#log(`[pool] 已添加账号:${label}(${id})`)
328
+ return { entry: this.#store.get(id), created: true }
329
+ }
330
+
331
+ /** 按序号 / id 前缀 / 昵称尾号找账号(CLI 与工具共用)。 */
332
+ resolve(reference) {
333
+ const needle = String(reference ?? '').trim()
334
+ if (needle.length === 0) return undefined
335
+ const entries = this.list()
336
+ const byIndex = Number(needle)
337
+ if (Number.isInteger(byIndex) && byIndex >= 1 && byIndex <= entries.length) return entries[byIndex - 1]
338
+ const exact = entries.find((entry) => entry.id === needle)
339
+ if (exact !== undefined) return exact
340
+ const prefixed = entries.find((entry) => entry.id.startsWith(needle))
341
+ if (prefixed !== undefined) return prefixed
342
+ const byName = entries.find((entry) => entry.nickname.includes(needle))
343
+ return byName
344
+ }
345
+
346
+ /** 启用 / 停用。 */
347
+ setEnabled(id, enabled) {
348
+ if (!this.#store.patch(id, { enabled })) throw new Error(`账号不存在:${id}`)
349
+ }
350
+
351
+ /**
352
+ * 部分更新账号的**非敏感**字段(管理面板改备注走这里)。
353
+ * ⚠ 只白名单放行 `nickname`:凭据不允许从这条路改(改凭据必须走
354
+ * `updateCredential`,且只许用该账号自己的 id —— 见文件头第 2 条约定)。
355
+ */
356
+ patchAccount(id, patch) {
357
+ const nickname = typeof patch?.nickname === 'string' ? patch.nickname.trim() : ''
358
+ if (nickname.length === 0) return false
359
+ return this.#store.patch(id, { nickname })
360
+ }
361
+
362
+ /** 删除。 */
363
+ remove(id) {
364
+ return this.#store.remove(id)
365
+ }
366
+
367
+ /** 重排(必须同一集合的一个排列,否则报错而不是尽力而为)。 */
368
+ reorder(orderedIds) {
369
+ const entries = this.list()
370
+ const expected = new Set(entries.map((entry) => entry.id))
371
+ const sameSet =
372
+ orderedIds.length === entries.length &&
373
+ new Set(orderedIds).size === orderedIds.length &&
374
+ orderedIds.every((id) => expected.has(id))
375
+ if (!sameSet) {
376
+ throw new Error(`账号列表已变化,请刷新后重试(期望 ${entries.length} 个账号,收到 ${orderedIds.length} 个)`)
377
+ }
378
+ const byId = new Map(entries.map((entry) => [entry.id, entry]))
379
+ const base = this.#now()
380
+ orderedIds.forEach((id, index) => {
381
+ const entry = byId.get(id)
382
+ this.#store.patch(id, { added_at: base + index })
383
+ })
384
+ }
385
+
386
+ /**
387
+ * 取下一个可用账号。
388
+ *
389
+ * @param {string} modelId 目标模型(空串表示不按限流过滤)
390
+ * @param {Set<string> | readonly string[]} [exclude] 本次请求已尝试过的账号 id
391
+ * @returns {{ entry: any, credential: any } | null}
392
+ */
393
+ pick(modelId, exclude) {
394
+ const excluded = exclude instanceof Set ? exclude : new Set(exclude ?? [])
395
+ const now = this.#now()
396
+ const candidates = this.list({ withCredentials: true }).filter((entry) => {
397
+ if (!entry.enabled) return false
398
+ if (excluded.has(entry.id)) return false
399
+ if (typeof modelId !== 'string' || modelId.length === 0) return true
400
+ const resetAt = entry.model_rate_limits?.[modelId]
401
+ return resetAt === undefined || resetAt === 0 || now >= resetAt
402
+ })
403
+ for (const entry of candidates) {
404
+ if (isUsableCredential(entry.credential)) return { entry, credential: entry.credential }
405
+ this.#log(`[pool] 账号 ${entry.id} 凭据不可用,已跳过`)
406
+ }
407
+ return null
408
+ }
409
+
410
+ /** 标记「账号 × 模型」在 resetAt 之前不可用。 */
411
+ markModelRateLimited(accountId, modelId, resetAtMs) {
412
+ const entry = this.#store.get(accountId)
413
+ if (entry === undefined) {
414
+ this.#log(`[pool] markModelRateLimited: 账号 ${accountId} 不在池中,已忽略`)
415
+ return
416
+ }
417
+ const limits = { ...(entry.model_rate_limits ?? {}), [modelId]: resetAtMs }
418
+ this.#store.patch(accountId, { model_rate_limits: limits })
419
+ this.#log(`[pool] 已标记限流:${entry.nickname} × ${modelId} → ${new Date(resetAtMs).toISOString()}`)
420
+ }
421
+
422
+ /** 清除某账号的限流标记(默认全清)。 */
423
+ clearModelRateLimits(accountId, modelIds) {
424
+ const entry = this.#store.get(accountId)
425
+ if (entry === undefined) return 0
426
+ const limits = { ...(entry.model_rate_limits ?? {}) }
427
+ let removed = 0
428
+ for (const modelId of modelIds ?? Object.keys(limits)) {
429
+ if (Object.prototype.hasOwnProperty.call(limits, modelId)) {
430
+ delete limits[modelId]
431
+ removed += 1
432
+ }
433
+ }
434
+ if (removed > 0) this.#store.patch(accountId, { model_rate_limits: limits })
435
+ return removed
436
+ }
437
+
438
+ /** 清理已过期的标记。 */
439
+ sweepExpired() {
440
+ for (const entry of this.list()) {
441
+ const limits = { ...(entry.model_rate_limits ?? {}) }
442
+ let changed = false
443
+ for (const [modelId, resetAt] of Object.entries(limits)) {
444
+ if (resetAt > 0 && this.#now() >= resetAt) {
445
+ delete limits[modelId]
446
+ changed = true
447
+ }
448
+ }
449
+ if (changed) this.#store.patch(entry.id, { model_rate_limits: limits })
450
+ }
451
+ }
452
+
453
+ /** 记下某个账号最近一次失败原因(面板/状态工具展示用)。 */
454
+ noteError(accountId, message) {
455
+ this.#store.patch(accountId, { last_error: message })
456
+ }
457
+ }
458
+
459
+ /** 默认数据目录:`~/.dsh/zcode-start-plan`(可用环境变量覆盖)。 */
460
+ export function resolveDataDir(env = process.env) {
461
+ const fromEnv = env['ZCODE_START_PLAN_DATA_DIR']
462
+ if (typeof fromEnv === 'string' && fromEnv.trim().length > 0) return fromEnv.trim()
463
+ const home = env['USERPROFILE'] ?? env['HOME'] ?? '.'
464
+ return join(home, '.dsh', 'zcode-start-plan')
465
+ }
466
+
467
+ /**
468
+ * 账号库文件路径。
469
+ *
470
+ * `dataDir` 显式传入时以它为准(Config 的 `dataDir` 走这条路)——
471
+ * 否则插件在测试/多实例场景下会悄悄读写**用户的真实账号库**。
472
+ */
473
+ export function resolveDbFile(env = process.env, dataDir) {
474
+ if (typeof dataDir === 'string' && dataDir.trim().length > 0) {
475
+ return join(dataDir.trim(), 'accounts.db')
476
+ }
477
+ return join(resolveDataDir(env), 'accounts.db')
478
+ }