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.
@@ -0,0 +1,489 @@
1
+ /**
2
+ * 账号池管理路由(供 Web UI 的 Client 半段调用)。
3
+ *
4
+ * ## 契约(照抄 @linxin666/dsh-client-ui-plugin-manager 的实证写法)
5
+ *
6
+ * - `inject: ['webServer']` → `ctx.webServer.register(route)` 逐条注册,返回 disposer;
7
+ * - route 形状:`{ kind: 'exact', path, handler(req, res) }`;
8
+ * - **loopback 防护**:仅允许本机回环地址访问(socket 与 Host 头都校验);
9
+ * - JSON 读写:请求体有上限,响应统一 `content-type: application/json`。
10
+ *
11
+ * ## 安全边界
12
+ *
13
+ * 这些路由能改账号池,因此:
14
+ * 1. 只监听回环(webServer 本身就只在本地)+ 请求级 loopback 判定;
15
+ * 2. **任何响应都不含凭据**(zcode_jwt / device_mid / token 一律不出网关);
16
+ * 设备授权流的 `flowSecret` 同样只留在 Host 内存(见 `/login/start`);
17
+ * 3. 写操作(enable/disable/remove/reset/reorder/use/login)逐条校验参数形状。
18
+ */
19
+
20
+ import { isIP } from 'node:net'
21
+ import { startZcodeLogin, pollZcodeLogin, normalizeLoginChannel } from './upstream-api.js'
22
+ import { generateDeviceMid, ZCODE_APP_VERSION_FALLBACK } from './upstream.js'
23
+
24
+ /** 路由前缀(Client 半段用同一常量拼 URL)。 */
25
+ export const MANAGE_PREFIX = '/api/zcode-start-plan'
26
+
27
+ /** 登录流寿命(上游 `expires_at` 语义:10 分钟)。 */
28
+ const LOGIN_FLOW_TTL_MS = 10 * 60_000
29
+ /** 同时挂起的登录流上限(防 Map 无限膨胀;超限驱逐最旧)。 */
30
+ const LOGIN_FLOW_MAX = 8
31
+
32
+ /**
33
+ * 判断一个 IP 字面量是否回环地址。
34
+ * ⚠ 不用 `node:net` 的 `isLoopbackAddress`:Node 22 没有该导出,静态 import
35
+ * 加载即崩(engines 允许 `^22.19 || >=24`,必须兼容);用 `isIP` 自己判。
36
+ */
37
+ function isLoopbackAddress(value) {
38
+ const text = String(value ?? '').trim()
39
+ const kind = isIP(text)
40
+ if (kind === 4) return text.startsWith('127.')
41
+ if (kind === 6) {
42
+ const lower = text.toLowerCase()
43
+ return lower === '::1' || lower === '::ffff:127.0.0.1'
44
+ }
45
+ return false
46
+ }
47
+
48
+ /** 简化的回环判定(socket 地址 + Host 头,镜像 plugin-manager 的栅栏思路)。 */
49
+ function isLoopbackRequest(req) {
50
+ const remote = req.socket?.remoteAddress ?? ''
51
+ if (!isLoopbackAddress(remote)) return false
52
+ const hostHeader = String(req.headers?.host ?? '')
53
+ const hostname = hostHeader.startsWith('[')
54
+ ? hostHeader.slice(1, hostHeader.indexOf(']'))
55
+ : hostHeader.split(':')[0] ?? ''
56
+ if (hostname.length === 0) return true
57
+ if (hostname === 'localhost') return true
58
+ return isLoopbackAddress(hostname)
59
+ }
60
+
61
+ /** 写一个 JSON 响应。 */
62
+ function writeJson(res, status, body) {
63
+ if (res.writableEnded || res.destroyed) return
64
+ const text = JSON.stringify(body)
65
+ res.writeHead(status, {
66
+ 'content-type': 'application/json; charset=utf-8',
67
+ 'referrer-policy': 'no-referrer',
68
+ 'cache-control': 'no-store',
69
+ })
70
+ res.end(text)
71
+ }
72
+
73
+ /** 读请求体(有上限),解析为对象;失败返回 null。 */
74
+ function readJsonBody(req, maxBytes = 64 * 1024) {
75
+ return new Promise((resolve) => {
76
+ const chunks = []
77
+ let size = 0
78
+ let settled = false
79
+ const finish = (value) => {
80
+ if (settled) return
81
+ settled = true
82
+ resolve(value)
83
+ }
84
+ req.on('data', (chunk) => {
85
+ size += chunk.length
86
+ if (size > maxBytes) {
87
+ finish(null)
88
+ req.destroy()
89
+ return
90
+ }
91
+ chunks.push(chunk)
92
+ })
93
+ req.on('end', () => {
94
+ const text = Buffer.concat(chunks).toString('utf8')
95
+ if (text.length === 0) return finish(null)
96
+ try {
97
+ const parsed = JSON.parse(text)
98
+ finish(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null)
99
+ } catch {
100
+ finish(null)
101
+ }
102
+ })
103
+ req.on('error', () => finish(null))
104
+ })
105
+ }
106
+
107
+ /** 把错误翻成字符串(不暴露堆栈给页面)。 */
108
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error))
109
+
110
+ /**
111
+ * 账号的脱敏视图:绝不包含凭据字段。
112
+ */
113
+ function publicAccount(entry, index) {
114
+ return {
115
+ index: index + 1,
116
+ id: entry.id,
117
+ nickname: entry.nickname,
118
+ enabled: entry.enabled === true,
119
+ userIdTail: typeof entry.user_id === 'string' && entry.user_id.length > 0 ? entry.user_id.slice(-6) : null,
120
+ channel: entry.credential?.login_channel ?? null,
121
+ addedAt: typeof entry.added_at === 'number' ? entry.added_at : null,
122
+ modelRateLimits: entry.model_rate_limits ?? {},
123
+ lastError: entry.last_error ?? null,
124
+ }
125
+ }
126
+
127
+ /**
128
+ * 构造管理路由。
129
+ *
130
+ * @param {{
131
+ * pool: import('./pool.js').AccountPool,
132
+ * fetchBalance?: (credential: any) => Promise<any>,
133
+ * log?: (message: string) => void,
134
+ * onChanged?: () => void,
135
+ * onSetUnifiedVisible?: (visible: boolean) => void,
136
+ * onSetAccountVisible?: (accountId: string, visible: boolean) => void,
137
+ * settings?: { unifiedModelList?: boolean, hiddenModelLists?: string[] },
138
+ * }} deps
139
+ * @returns {Array<{ kind: 'exact', path: string, handler: (req: any, res: any) => Promise<void> }>}
140
+ */
141
+ export function makeManageRoutes(deps) {
142
+ const pool = deps.pool
143
+ const fetchBalance = deps.fetchBalance
144
+ const log = deps.log ?? (() => {})
145
+ /**
146
+ * 池子变更后的通知:账号栏位的路由集合随启用账号增删而变 —— 通知
147
+ * assemble 用 `handle.replace()` 原子换路由(内部自动广播
148
+ * `llm/adapters-updated`,模型选择器随即重拉目录)。
149
+ */
150
+ const notifyChanged = () => {
151
+ try {
152
+ deps.onChanged?.()
153
+ } catch {
154
+ // 通知失败不影响管理操作本身。
155
+ }
156
+ }
157
+
158
+ /** 「统一选号」栏位开关(POST /unified-list)。 */
159
+ const unifiedListHandler = async (req, res) => {
160
+ const body = (await readJsonBody(req)) ?? {}
161
+ if (typeof body.visible !== 'boolean') {
162
+ writeJson(res, 400, { ok: false, error: '需要 visible(布尔)' })
163
+ return
164
+ }
165
+ try {
166
+ deps.onSetUnifiedVisible?.(body.visible)
167
+ } catch (error) {
168
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
169
+ return
170
+ }
171
+ writeJson(res, 200, { ok: true, visible: body.visible })
172
+ }
173
+
174
+ /** 单个账号「模型栏位」开关(POST /model-list-visible,每卡片右侧的开关)。 */
175
+ const modelListVisibleHandler = async (req, res) => {
176
+ const body = (await readJsonBody(req)) ?? {}
177
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
178
+ if (id.length === 0 || typeof body.visible !== 'boolean') {
179
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)与 visible(布尔)' })
180
+ return
181
+ }
182
+ if (!pool.list().some((entry) => entry.id === id)) {
183
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
184
+ return
185
+ }
186
+ try {
187
+ deps.onSetAccountVisible?.(id, body.visible)
188
+ } catch (error) {
189
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
190
+ return
191
+ }
192
+ writeJson(res, 200, { ok: true, id, visible: body.visible })
193
+ }
194
+
195
+ // ── 登录流(两段式设备授权:Client 拿 URL → 浏览器授权 → Client 轮询)──
196
+ //
197
+ // ⚠ `flowSecret` 是本轮授权会话的密钥,**必须留在 Host 内存**(和 CLI 的
198
+ // `beginZcodeLogin` 一样),绝不随 /login/start 响应下发 —— 下发它等于把
199
+ // 「完成别人授权」的能力交给页面里任意脚本。
200
+ // 流程:Client 先 POST /login/start {channel} 拿 authorizeUrl(自己渲染成链接,
201
+ // 不用 window.open 以免被弹窗拦截),再隔 pollIntervalMs POST /login/poll
202
+ // {flowId} 查状态;ready 时 Host 组装凭据入池,凭据不出网关。
203
+ // 每条流 10 分钟过期,Map 上限 8 条,随手清理。
204
+
205
+ /** 进行中的登录流:flowId → { flow, channel, createdAt }。 */
206
+ const loginFlows = new Map()
207
+
208
+ /** 驱逐过期/多余的流。 */
209
+ function pruneLoginFlows() {
210
+ const now = Date.now()
211
+ for (const [key, value] of loginFlows) {
212
+ if (now - value.createdAt > LOGIN_FLOW_TTL_MS) loginFlows.delete(key)
213
+ }
214
+ while (loginFlows.size > LOGIN_FLOW_MAX) {
215
+ const oldest = [...loginFlows.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt)[0]
216
+ loginFlows.delete(oldest[0])
217
+ }
218
+ }
219
+
220
+ /** 包一层 loopback 栅栏 + 异常兜底。 */
221
+ const guard = (handler) => async (req, res) => {
222
+ if (!isLoopbackRequest(req)) {
223
+ writeJson(res, 403, { ok: false, error: 'forbidden: loopback-only' })
224
+ return
225
+ }
226
+ try {
227
+ await handler(req, res)
228
+ } catch (error) {
229
+ log(`[manage] ${req.method} ${req.url} 失败:${messageOf(error)}`)
230
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
231
+ }
232
+ }
233
+
234
+ /** 池子当前状态(含每账号余额与栏位可见性,拉取失败给 null)。 */
235
+ const summaryHandler = async (_req, res) => {
236
+ const entries = pool.list({ withCredentials: true })
237
+ const hidden = new Set(Array.isArray(deps.settings?.hiddenModelLists) ? deps.settings.hiddenModelLists : [])
238
+ /**
239
+ * 余额并行拉取(纯读、账号间无依赖):串行时最坏 30s × N(fetchBalance
240
+ * 每账号超时 30s),面板会一直「加载中…」。
241
+ * fetchBalance 失败路径返回 undefined / 抛错都归一为 null —— 明确下发
242
+ * `balance: null`,客户端(client.js load)只对缺键的账号补拉 /balance,
243
+ * 避免同一端点被二次重试双倍消耗。
244
+ */
245
+ const balances = await Promise.all(
246
+ entries.map(async (entry) => {
247
+ if (typeof fetchBalance !== 'function' || entry.enabled !== true) return null
248
+ try {
249
+ const balance = await fetchBalance(entry.credential)
250
+ if (balance === undefined) return null
251
+ return balance.enterprise === true
252
+ ? { enterprise: true, remaining: null, total: null, planName: null }
253
+ : {
254
+ enterprise: false,
255
+ remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
256
+ total: typeof balance.total === 'number' ? balance.total : null,
257
+ planName: balance.planName ?? null,
258
+ }
259
+ } catch {
260
+ return null
261
+ }
262
+ }),
263
+ )
264
+ const accounts = entries.map((entry, index) => {
265
+ const view = publicAccount(entry, index)
266
+ /** 账号「模型栏位」是否显示(面板每卡片右侧的开关状态)。 */
267
+ view.modelListVisible = !hidden.has(entry.id)
268
+ view.balance = balances[index]
269
+ return view
270
+ })
271
+ writeJson(res, 200, {
272
+ ok: true,
273
+ accounts,
274
+ enabledCount: accounts.filter((account) => account.enabled).length,
275
+ unifiedModelList: deps.settings?.unifiedModelList !== false,
276
+ fetchedAt: Date.now(),
277
+ })
278
+ }
279
+
280
+ /** 单账号余额(点「刷新」时用,避免整表全拉)。 */
281
+ const balanceHandler = async (req, res) => {
282
+ const id = new URL(req.url ?? '/', 'http://localhost').searchParams.get('id')?.trim() ?? ''
283
+ const entry = id.length > 0 ? pool.list({ withCredentials: true }).find((item) => item.id === id) : undefined
284
+ if (entry === undefined) {
285
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
286
+ return
287
+ }
288
+ if (typeof fetchBalance !== 'function') {
289
+ writeJson(res, 200, { ok: true, balance: null })
290
+ return
291
+ }
292
+ try {
293
+ const balance = await fetchBalance(entry.credential)
294
+ writeJson(res, 200, {
295
+ ok: true,
296
+ balance: balance === undefined
297
+ ? null
298
+ : balance.enterprise === true
299
+ ? { enterprise: true, remaining: null, total: null, planName: null }
300
+ : {
301
+ enterprise: false,
302
+ remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
303
+ total: typeof balance.total === 'number' ? balance.total : null,
304
+ planName: balance.planName ?? null,
305
+ },
306
+ })
307
+ } catch (error) {
308
+ writeJson(res, 200, { ok: true, balance: null, error: messageOf(error) })
309
+ }
310
+ }
311
+
312
+ /** 启用 / 停用。 */
313
+ const setEnabledHandler = async (req, res) => {
314
+ const body = (await readJsonBody(req)) ?? {}
315
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
316
+ const enabled = body.enabled
317
+ if (id.length === 0 || typeof enabled !== 'boolean') {
318
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)与 enabled(布尔)' })
319
+ return
320
+ }
321
+ pool.setEnabled(id, enabled)
322
+ notifyChanged()
323
+ writeJson(res, 200, { ok: true, id, enabled })
324
+ }
325
+
326
+ /** 删除。 */
327
+ const removeHandler = async (req, res) => {
328
+ const body = (await readJsonBody(req)) ?? {}
329
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
330
+ if (id.length === 0) {
331
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
332
+ return
333
+ }
334
+ const removed = pool.remove(id)
335
+ if (!removed) {
336
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
337
+ return
338
+ }
339
+ notifyChanged()
340
+ writeJson(res, 200, { ok: true, id })
341
+ }
342
+
343
+ /** 清限流标记(当日额度误标时的自救)。 */
344
+ const resetLimitsHandler = async (req, res) => {
345
+ const body = (await readJsonBody(req)) ?? {}
346
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
347
+ const model = typeof body.model === 'string' ? body.model.trim() : ''
348
+ if (id.length === 0) {
349
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
350
+ return
351
+ }
352
+ const removed = pool.clearModelRateLimits(id, model.length > 0 ? [model] : undefined)
353
+ writeJson(res, 200, { ok: true, id, removed })
354
+ }
355
+
356
+ /** 重排(顺序即选号优先级)。 */
357
+ const reorderHandler = async (req, res) => {
358
+ const body = (await readJsonBody(req)) ?? {}
359
+ const ids = Array.isArray(body.ids) ? body.ids : []
360
+ if (!ids.every((id) => typeof id === 'string' && id.trim().length > 0)) {
361
+ writeJson(res, 400, { ok: false, error: '需要 ids(非空字符串数组,且为当前集合的排列)' })
362
+ return
363
+ }
364
+ pool.reorder(ids)
365
+ notifyChanged()
366
+ writeJson(res, 200, { ok: true, ids })
367
+ }
368
+
369
+ /** 重命名备注。 */
370
+ const renameHandler = async (req, res) => {
371
+ const body = (await readJsonBody(req)) ?? {}
372
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
373
+ const nickname = typeof body.nickname === 'string' ? body.nickname.trim() : ''
374
+ if (id.length === 0 || nickname.length === 0) {
375
+ writeJson(res, 400, { ok: false, error: '需要 id 与 nickname(均非空)' })
376
+ return
377
+ }
378
+ const entry = pool.get?.(id) ?? pool.list({ withCredentials: true }).find((item) => item.id === id)
379
+ if (entry === undefined) {
380
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
381
+ return
382
+ }
383
+ pool.patchAccount(id, { nickname })
384
+ notifyChanged()
385
+ writeJson(res, 200, { ok: true, id, nickname })
386
+ }
387
+
388
+ /**
389
+ * 置顶使用(「选择使用哪个账号」的落地)。
390
+ *
391
+ * 池子的既有约定:**手动顺序即选号优先级**(lib/pool.js 文件头第 1 条),
392
+ * `pick()` 永远取第一个「启用且未限流」的账号。因此「下次请求用这个号」
393
+ * = 把它排到首位。这里复用 `/reorder` 的集合校验,不另开写入口。
394
+ */
395
+ const useHandler = async (req, res) => {
396
+ const body = (await readJsonBody(req)) ?? {}
397
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
398
+ if (id.length === 0) {
399
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
400
+ return
401
+ }
402
+ const entries = pool.list()
403
+ if (!entries.some((item) => item.id === id)) {
404
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
405
+ return
406
+ }
407
+ const ids = [id, ...entries.map((item) => item.id).filter((existing) => existing !== id)]
408
+ pool.reorder(ids)
409
+ notifyChanged()
410
+ writeJson(res, 200, { ok: true, id, order: ids })
411
+ }
412
+
413
+ /** /login/start:向渠道申请设备授权,返回 authorizeUrl + flowId(不含 secret)。 */
414
+ const loginStartHandler = async (req, res) => {
415
+ const body = (await readJsonBody(req)) ?? {}
416
+ const channel = normalizeLoginChannel(body.channel)
417
+ const flow = await startZcodeLogin(globalThis.fetch, { channel })
418
+ pruneLoginFlows()
419
+ loginFlows.set(flow.flowId, { flow, channel, createdAt: Date.now() })
420
+ log(`[manage] 登录流已发起:${channel}(flowId=${flow.flowId.slice(0, 8)}…)`)
421
+ writeJson(res, 200, {
422
+ ok: true,
423
+ flowId: flow.flowId,
424
+ authorizeUrl: flow.authorizeUrl,
425
+ expiresAt: flow.expiresAt > 0 ? flow.expiresAt : Date.now() + LOGIN_FLOW_TTL_MS,
426
+ pollIntervalMs: Math.max(1, flow.pollIntervalSec) * 1_000,
427
+ })
428
+ }
429
+
430
+ /** /login/poll:查一次授权状态;ready 时组装凭据入池(凭据不回传)。 */
431
+ const loginPollHandler = async (req, res) => {
432
+ const body = (await readJsonBody(req)) ?? {}
433
+ const flowId = typeof body.flowId === 'string' ? body.flowId.trim() : ''
434
+ if (flowId.length === 0) {
435
+ writeJson(res, 400, { ok: false, error: '需要 flowId(字符串)' })
436
+ return
437
+ }
438
+ const record = loginFlows.get(flowId)
439
+ if (record === undefined) {
440
+ writeJson(res, 404, { ok: false, error: '登录流不存在或已过期,请重新发起' })
441
+ return
442
+ }
443
+ const outcome = await pollZcodeLogin(record.flow, globalThis.fetch, ZCODE_APP_VERSION_FALLBACK)
444
+ if (outcome.kind === 'pending') {
445
+ writeJson(res, 200, { ok: true, status: 'pending' })
446
+ return
447
+ }
448
+ loginFlows.delete(flowId)
449
+ if (outcome.kind === 'failed') {
450
+ writeJson(res, 200, { ok: true, status: 'failed', error: outcome.message })
451
+ return
452
+ }
453
+ // ready:凭据组装与 beginZcodeLogin 逐字段一致(绝不把凭据发回页面)。
454
+ const credential = {
455
+ zcode_jwt: outcome.result.zcodeJwt,
456
+ device_mid: generateDeviceMid(),
457
+ user_id: outcome.result.userId,
458
+ bigmodel_access_token: outcome.result.bigmodelAccessToken,
459
+ account_label: outcome.result.displayName,
460
+ app_version: ZCODE_APP_VERSION_FALLBACK,
461
+ login_channel: record.channel,
462
+ source: 'plugin-web',
463
+ }
464
+ const { entry, created } = pool.add(credential)
465
+ notifyChanged()
466
+ log(`[manage] 通过 Web UI ${created ? '添加' : '更新'}账号:${entry.nickname}(${record.channel})`)
467
+ writeJson(res, 200, {
468
+ ok: true,
469
+ status: 'ready',
470
+ created,
471
+ account: { id: entry.id, nickname: entry.nickname },
472
+ })
473
+ }
474
+
475
+ return [
476
+ { kind: 'exact', path: `${MANAGE_PREFIX}/summary`, handler: guard(summaryHandler) },
477
+ { kind: 'exact', path: `${MANAGE_PREFIX}/balance`, handler: guard(balanceHandler) },
478
+ { kind: 'exact', path: `${MANAGE_PREFIX}/set-enabled`, handler: guard(setEnabledHandler) },
479
+ { kind: 'exact', path: `${MANAGE_PREFIX}/remove`, handler: guard(removeHandler) },
480
+ { kind: 'exact', path: `${MANAGE_PREFIX}/reset-limits`, handler: guard(resetLimitsHandler) },
481
+ { kind: 'exact', path: `${MANAGE_PREFIX}/reorder`, handler: guard(reorderHandler) },
482
+ { kind: 'exact', path: `${MANAGE_PREFIX}/rename`, handler: guard(renameHandler) },
483
+ { kind: 'exact', path: `${MANAGE_PREFIX}/use`, handler: guard(useHandler) },
484
+ { kind: 'exact', path: `${MANAGE_PREFIX}/unified-list`, handler: guard(unifiedListHandler) },
485
+ { kind: 'exact', path: `${MANAGE_PREFIX}/model-list-visible`, handler: guard(modelListVisibleHandler) },
486
+ { kind: 'exact', path: `${MANAGE_PREFIX}/login/start`, handler: guard(loginStartHandler) },
487
+ { kind: 'exact', path: `${MANAGE_PREFIX}/login/poll`, handler: guard(loginPollHandler) },
488
+ ]
489
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 「钉定账号」模型 id 的编解码。
3
+ *
4
+ * ## 这个功能解决什么问题
5
+ *
6
+ * 默认选号是「手动顺序」:面板置顶谁,下一次请求就用谁。但用户有时想**同时**
7
+ * 用多个会话,各会话吃不同账号的额度 —— 顺序只有一个,做不到。
8
+ *
9
+ * 因此在模型选择器里为每个启用账号额外暴露一条「模型 × 账号」条目:
10
+ *
11
+ * ```
12
+ * GLM-5.3-Flash ← 普通条目:自动选号(手动顺序)
13
+ * GLM-5.3-Flash · 主号 ← 钉定条目:只消耗「主号」的额度
14
+ * ```
15
+ *
16
+ * ## id 编码
17
+ *
18
+ * 钉定条目的模型 id 形如 `GLM-5.3-Flash@acct:<账号id>`:
19
+ *
20
+ * - `@acct:` 之前是**发给上游的基础模型 id**(上游只认识 `GLM-5.3-Flash` 这类);
21
+ * - 之后是池内账号 id(`randomUUID`)。
22
+ *
23
+ * 上游合法模型 id 与账号 id 都不含 `@acct:`,该分隔符无歧义;用 `lastIndexOf`
24
+ * 解析,即便未来 id 里再出现该串也取最后一个分隔段。
25
+ *
26
+ * ⚠ 这个 id 会对宿主/上游/持久化(会话保存的模型名)三方可见,**编码格式一经
27
+ * 发布就不能变**,否则老会话里保存的钉定模型全部失效。
28
+ */
29
+
30
+ /** 分隔符(发布后不可更改,见文件头)。 */
31
+ export const PINNED_MODEL_SUFFIX = '@acct:'
32
+
33
+ /** 拼一个钉定模型 id。 */
34
+ export function makePinnedModelId(baseModelId, accountId) {
35
+ return `${baseModelId}${PINNED_MODEL_SUFFIX}${accountId}`
36
+ }
37
+
38
+ /**
39
+ * 解析钉定模型 id。
40
+ *
41
+ * @returns {{ baseModelId: string, accountId: string } | null} 非钉定 id 或形状不完整时返回 null
42
+ */
43
+ export function parsePinnedModelId(modelId) {
44
+ const raw = String(modelId ?? '')
45
+ const at = raw.lastIndexOf(PINNED_MODEL_SUFFIX)
46
+ if (at <= 0) return null
47
+ const baseModelId = raw.slice(0, at)
48
+ const accountId = raw.slice(at + PINNED_MODEL_SUFFIX.length)
49
+ if (baseModelId.length === 0 || accountId.length === 0) return null
50
+ return { baseModelId, accountId }
51
+ }
52
+
53
+ /** 是否是钉定模型 id。 */
54
+ export function isPinnedModelId(modelId) {
55
+ return parsePinnedModelId(modelId) !== null
56
+ }