dsh-ustc-quota 1.3.36 → 2.0.1

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/README.md CHANGED
@@ -2,13 +2,28 @@
2
2
 
3
3
  [GitHub](https://github.com/Awenforever/dsh-ustc-quota) · MIT
4
4
 
5
- 在 **DeepSeek Harness(DSH)** 和 **中国科大「词元工坊」TokenWorks** 的左侧栏里,显示 USTC 模型额度的 **3h / 12h / 24h** 进度、已用额度、上限、百分比和重置时间。
5
+ 在 **DeepSeek Harness(DSH)** 和 **中国科大「词元工坊」TokenWorks** 的左侧栏里,显示 USTC 模型额度的 **3h / 12h / 24h** 进度、已用额度、上限、百分比和重置时间;从 **2.0.0** 起,它同时是 USTC 多账号的**号池**:
6
6
 
7
- 卡片位于会话列表与账户/设置行之间;侧边栏收起时自动隐藏。
7
+ - 每把 Key 是一个**原生 provider 行**(`ustc-<id>`),流量照常走 DSH 自己的模型调用,**没有代理、没有转发、没有请求重编码**。
8
+ - 新会话自动落到当前**最闲的 Key**(默认模型轮转),已有会话在当前 Key 接近撞墙(≥90%)时自动迁移到下一把。
9
+ - 卡片里当前会话用的那把 Key 带 `*`,与模型选择器里选中的 provider 一致。
10
+ - 2.0.0 之前由独立的 `dsh-ustc-provider-manager` 插件承担号池;该插件已归档,功能并入本插件。
8
11
 
9
- - DSH:按 `baseURL` 自动发现所有指向 USTC 网关的 `@deepseek-ai/dsh-llm-pi-ai` provider(provider id/显示名随便取,不需要以 `ustc-` 开头;`/v1` 会自动归一到站点根),每把 key 一行。
10
- - TokenWorks:直接使用词元工坊内置的 `tokenworksUsage` Host 服务,不读取 Key,不额外请求学校网关;未登录时提示先登录。
11
- - 只读展示:不拦截模型请求、不换 Key、不改 provider。
12
+ ## 号池怎么工作
13
+
14
+ 1. **Key 列表**保存在 `~/.dsh/dsh-ustc-quota.keys.json`(插件自有,重启不丢);每把 Key 在 `llm-pi-ai` 里对应一行 `ustc-<id>`,带完整模型表(含 `deepseek-flash`)。
15
+ 2. **选 key**:按快照里的三窗口用量算“最闲的一把”,跳过打不通/被墙的 Key;没有任何可用 Key 时不抢占。
16
+ 3. **生效**:新会话继承 `agent-default-model`,插件把默认 provider 轮转到最闲的 Key;已有会话通过宿主 `selectModel` 切换(客户端探针每 60 秒检查一次,超过 90% 才动)。
17
+ 4. **粘性**:同一会话尽量留在同一把 Key(缓存友好),只有接近撞墙或该 Key 不可用时才迁移。
18
+
19
+ ## 支持的 Key 管理
20
+
21
+ - `GET /plugins/dsh-ustc-quota/keys`:当前 Key 列表
22
+ - `POST /plugins/dsh-ustc-quota/key`:新增(`{"label":"wmw","secret":"sk-..."}`)
23
+ - `POST /plugins/dsh-ustc-quota/key/import`:从现有 `ustc-*` provider 行导入
24
+ - `POST /plugins/dsh-ustc-quota/key/delete`:删除(`{"id":"wmw"}`)
25
+ - `GET /plugins/dsh-ustc-quota/pool/sessions` / `POST /pool/migrate`:查看/迁移仍在旧 provider 上的会话
26
+ - `GET /plugins/dsh-ustc-quota/pool/probe`:无界面验收(建一个临时会话跑一轮真实消息)
12
27
 
13
28
  ## 支持的环境
14
29
 
@@ -40,7 +55,7 @@ github:Awenforever/dsh-ustc-quota
40
55
  github:Awenforever/dsh-ustc-quota#vX.Y.Z
41
56
  ```
42
57
 
43
- npm 上的 `dsh-ustc-quota` **长期停在 1.1.59**,不含 1.3.x 的任何修复;除非你确认 npm 上已有与本文一致的新版本,否则不要用它:
58
+ npm 上的 `dsh-ustc-quota` 自 **1.3.36** 起与本仓库同步(此前的 1.1.59 不含 1.3.x 的任何修复)。从 npm 安装还能走 DSH 官方更新通道:
44
59
 
45
60
  ```text
46
61
  dsh-ustc-quota
@@ -62,7 +77,7 @@ target = github:Awenforever/dsh-ustc-quota
62
77
  TokenWorks 是 USTC 基于 DSH 的发行版,自带 **插件** 页面和 `@deepseek-ai/dsh-plugin-manager`:
63
78
 
64
79
  1. 在左侧栏打开 **插件** → 点右上角 **+ 添加插件**;
65
- 2. 填入 `github:Awenforever/dsh-ustc-quota#vX.Y.Z`(推荐,换成 Release 标签);只有在 npm 上确认到同版本时再用 `dsh-ustc-quota`;
80
+ 2. 填入 `dsh-ustc-quota`(走 npm,可自动更新)或 `github:Awenforever/dsh-ustc-quota#vX.Y.Z`(锁定某个 Release 标签);
66
81
  3. **全新安装**后只需让插件页加载/刷新一次;**从旧版本升级**则必须完全退出并重新打开词元工坊。TokenWorks 的插件页「更新」只应用 Host bundle,页面刷新不能清掉 DSH client-module 缓存;若刷新后插件仍未恢复,请完全退出并重开词元工坊;
67
82
  4. 用学校统一身份登录后,卡片会自动出现。
68
83
 
package/client.js CHANGED
@@ -55,7 +55,7 @@ window.__ModuleLoader__.load({
55
55
  return 0;
56
56
  }
57
57
  }
58
- const CLIENT_VERSION = '1.3.36';
58
+ const CLIENT_VERSION = '2.0.1';
59
59
  const UPDATE_INTERVAL_MS = 24 * 60 * 60 * 1000;
60
60
  const CLIENT_VERSION_KEY = `${NS}:client-version`;
61
61
  const CLIENT_RELOAD_KEY = `${NS}:client-reload`;
@@ -394,6 +394,7 @@ window.__ModuleLoader__.load({
394
394
  };
395
395
 
396
396
  const STYLE = {
397
+ autoLine: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', padding: '2px 0' },
397
398
  root: {
398
399
  width: '100%',
399
400
  minWidth: 0,
@@ -1132,6 +1133,122 @@ function formatCountdown(iso, now) {
1132
1133
  );
1133
1134
  }
1134
1135
 
1136
+
1137
+ /**
1138
+ * Pick the least-loaded pool key for a conversation and select its native provider row.
1139
+ *
1140
+ * The pool does not proxy traffic: "using a key" means the conversation's model selection
1141
+ * names that key's provider row. This component only writes that selection.
1142
+ */
1143
+ function worstRatioOf(entry) {
1144
+ if (!entry || !Array.isArray(entry.windows)) return null
1145
+ let worst = null
1146
+ for (const window of entry.windows) {
1147
+ if (!window || typeof window.ratio !== 'number') continue
1148
+ if (worst === null || window.ratio > worst) worst = window.ratio
1149
+ }
1150
+ return worst
1151
+ }
1152
+
1153
+ function bestPoolEntry(keys) {
1154
+ let best = null
1155
+ for (const entry of Array.isArray(keys) ? keys : []) {
1156
+ if (!entry || typeof entry.provider !== 'string' || !entry.provider.startsWith('ustc-')) continue
1157
+ if (entry.blocked === true) continue
1158
+ const worst = worstRatioOf(entry) ?? 0
1159
+ if (best === null || worst < best.worst) best = { provider: entry.provider, worst }
1160
+ }
1161
+ return best
1162
+ }
1163
+
1164
+ const AUTO_SELECT_THRESHOLD = 0.9
1165
+ let lastAutoSelect = null
1166
+ const autoSelectListeners = new Set()
1167
+ function reportAutoSelect(text) {
1168
+ lastAutoSelect = text
1169
+ for (const listener of autoSelectListeners) listener()
1170
+ }
1171
+ // A blank conversation inherits the previous default selection; the pool must choose for
1172
+ // it instead, otherwise "new conversation" keeps whatever key the last one used.
1173
+ function isBlankSession(sessions, sessionId) {
1174
+ try {
1175
+ const binding = sessions.binding(sessionId)
1176
+ const snapshot = binding && binding.session && typeof binding.session.getSnapshot === 'function'
1177
+ ? binding.session.getSnapshot()
1178
+ : null
1179
+ return snapshot !== null && snapshot.blank === true
1180
+ } catch { return false }
1181
+ }
1182
+
1183
+ function PoolAutoSelect(props) {
1184
+ const sessionId = props && typeof props.sessionId === 'string' ? props.sessionId : null
1185
+ React.useEffect(() => {
1186
+ if (sessionId === null || clientCtx === null) return undefined
1187
+ let alive = true
1188
+ const run = async () => {
1189
+ try {
1190
+ reportAutoSelect('AUTO run ' + sessionId.slice(0, 8))
1191
+ const remote = clientCtx.remote && clientCtx.remote.session
1192
+ if (!remote || typeof remote.selectModel !== 'function') { reportAutoSelect('AUTO no-remote'); return }
1193
+ const sessions = typeof clientCtx.get === 'function' ? clientCtx.get('sessions') : null
1194
+ if (!sessions || typeof sessions.binding !== 'function') { reportAutoSelect('AUTO no-sessions'); return }
1195
+ const binding = sessions.binding(sessionId)
1196
+ const projections = binding && binding.session ? binding.session.projections : null
1197
+ const face = projections && typeof projections.faceOf === 'function' ? projections.faceOf('modelSelection') : null
1198
+ const selection = face && typeof face.getSnapshot === 'function' ? face.getSnapshot() : null
1199
+ const current = selection ? (selection.pending || selection.lastUsed) : null
1200
+ const currentProvider = current && typeof current.provider === 'string' ? current.provider : null
1201
+ // Never fight a manual choice: only act when nothing is selected, or when the
1202
+ // conversation sits on one of our keys that is at (or past) the wall.
1203
+ reportAutoSelect('AUTO cur=' + String(currentProvider))
1204
+ if (currentProvider !== null && !currentProvider.startsWith('ustc-')) { reportAutoSelect('AUTO skip ' + String(currentProvider)); return }
1205
+ const response = await fetch(ENDPOINT, { cache: 'no-store', headers: { accept: 'application/json' } })
1206
+ if (!response.ok) return
1207
+ const body = await response.json()
1208
+ if (!alive) return
1209
+ const keys = body && Array.isArray(body.keys) ? body.keys : []
1210
+ const blank = isBlankSession(sessions, sessionId)
1211
+ const currentEntry = currentProvider === null ? null : keys.find((entry) => entry && entry.provider === currentProvider)
1212
+ const currentWorst = currentEntry === null ? null : worstRatioOf(currentEntry)
1213
+ const overWall = currentProvider === null
1214
+ || currentEntry === undefined
1215
+ || currentEntry.blocked === true
1216
+ || (currentWorst !== null && currentWorst >= AUTO_SELECT_THRESHOLD)
1217
+ const mustMove = blank ? true : overWall
1218
+ if (!mustMove) { reportAutoSelect('AUTO keep ' + String(currentProvider)); return }
1219
+ const best = bestPoolEntry(keys)
1220
+ if (best === null) { reportAutoSelect('AUTO no-key'); return }
1221
+ if (best.provider === currentProvider) { reportAutoSelect('AUTO best ' + best.provider); return }
1222
+ // Keep the conversation's model and effort; only the provider changes. A brand-new
1223
+ // conversation may have no selection yet, so ask the catalog for the model id.
1224
+ let model = current && typeof current.model === 'string' ? current.model : null
1225
+ let effort = current && typeof current.reasoningEffort === 'string' ? current.reasoningEffort : null
1226
+ if (model === null) {
1227
+ const catalog = await remote.modelCatalog()
1228
+ const groups = catalog && catalog.ok === true && catalog.value ? catalog.value.groups : null
1229
+ const group = Array.isArray(groups) ? groups.find((item) => item && item.id === best.provider) : null
1230
+ if (!group || !Array.isArray(group.models) || group.models.length === 0) return
1231
+ model = group.models[0].id
1232
+ effort = null
1233
+ }
1234
+ const result = await remote.selectModel({
1235
+ sessionId,
1236
+ provider: best.provider,
1237
+ model,
1238
+ ...(effort === null ? {} : { reasoningEffort: effort }),
1239
+ })
1240
+ reportAutoSelect('AUTO ' + (blank ? 'new' : 'move') + '→' + best.provider + ' ' + (result && result.ok === false ? 'ERR' : 'ok'))
1241
+ } catch (error) {
1242
+ reportAutoSelect('AUTO err ' + String(error && (error.message || error)).slice(0, 40))
1243
+ }
1244
+ }
1245
+ void run()
1246
+ const timer = setInterval(run, 60_000)
1247
+ return () => { alive = false; clearInterval(timer) }
1248
+ }, [sessionId])
1249
+ return null
1250
+ }
1251
+
1135
1252
  function QuotaStrip(props) {
1136
1253
  // Everything the card does not consume is forwarded to its root element, so
1137
1254
  // the dock can tag the panel (data-panel-dock-*) without a wrapper element.
@@ -1158,6 +1275,12 @@ function formatCountdown(iso, now) {
1158
1275
  }, []);
1159
1276
  activeRef.current = active;
1160
1277
  const [snapshot, setSnapshot] = React.useState(null);
1278
+ const [, bumpAuto] = React.useState(0);
1279
+ React.useEffect(() => {
1280
+ const listener = () => bumpAuto((value) => value + 1);
1281
+ autoSelectListeners.add(listener);
1282
+ return () => { autoSelectListeners.delete(listener) };
1283
+ }, []);
1161
1284
  const [poolKeys, setPoolKeys] = React.useState(null);
1162
1285
  const [error, setError] = React.useState(null);
1163
1286
  const [loading, setLoading] = React.useState(true);
@@ -1388,6 +1511,7 @@ function formatCountdown(iso, now) {
1388
1511
  }, [wideProp]);
1389
1512
 
1390
1513
 
1514
+ const autoLine = lastAutoSelect === null ? null : h('div', { style: STYLE.autoLine, title: '自动选择结果' }, lastAutoSelect);
1391
1515
  const keys = snapshot && Array.isArray(snapshot.keys) ? snapshot.keys : [];
1392
1516
  const warnings = snapshot && Array.isArray(snapshot.warnings) ? snapshot.warnings : [];
1393
1517
  const defaultProvider = snapshot && typeof snapshot.defaultProvider === 'string' ? snapshot.defaultProvider : null;
@@ -1850,6 +1974,7 @@ function formatCountdown(iso, now) {
1850
1974
  : null,
1851
1975
  updateNotice ? h('span', { style: STYLE.versionNote }, updateNotice) : null
1852
1976
  ),
1977
+ lastAutoSelect === null ? null : h('span', { style: STYLE.versionNote, title: '自动选择结果' }, lastAutoSelect),
1853
1978
  warnings.length > 0
1854
1979
  ? h('span', { style: STYLE.warn, title: warnings.join('\n'), 'aria-label': t('warnings') }, '!')
1855
1980
  : null,
@@ -2021,6 +2146,7 @@ function formatCountdown(iso, now) {
2021
2146
  onMouseLeave: () => { setCardHovered(false); setMarkHovered(false); },
2022
2147
  }),
2023
2148
  header,
2149
+ autoLine,
2024
2150
  restartBanner,
2025
2151
  body,
2026
2152
  updateModal
@@ -2158,7 +2284,7 @@ function formatCountdown(iso, now) {
2158
2284
  }
2159
2285
 
2160
2286
  return {
2161
- inject: ['slots', 'locale'],
2287
+ inject: ['slots', 'locale', 'remote', 'remote.session'],
2162
2288
  apply(ctx) {
2163
2289
  clientCtx = ctx;
2164
2290
  reloadOnceAfterClientUpdate();
@@ -2170,6 +2296,11 @@ function formatCountdown(iso, now) {
2170
2296
  id: SESSION_PROBE_ID,
2171
2297
  order: -1000,
2172
2298
  }, SessionProbe));
2299
+ ctx.slots.inject(SESSION_SLOT, () => ctx.slots.register({
2300
+ name: SESSION_SLOT,
2301
+ id: 'ustc-quota-auto-select',
2302
+ order: -900,
2303
+ }, PoolAutoSelect));
2173
2304
  ctx.slots.inject(SLOT, () => ctx.slots.register({
2174
2305
  name: SLOT,
2175
2306
  id: 'ustc-quota',
package/index.js CHANGED
@@ -20,8 +20,52 @@ import {
20
20
  normalizeConfig,
21
21
  } from './quota.js';
22
22
  import { UpdateService } from './update.js';
23
-
24
- const ROUTE_PATH = '/plugins/dsh-ustc-quota/snapshot';
23
+ import { keysFromConfig, removeProviderRow, syncKeyRow } from './pool-config.js';
24
+ import { readKeys as readStoredKeys } from './pool-store.js';
25
+ import { registerPoolApi } from './pool-api.js';
26
+ import { findProfile, retireManager } from './retire.js';
27
+
28
+ const ROUTE_PATH = '/plugins/dsh-ustc-quota/snapshot'
29
+ const POOL_CALL_PATH = '/plugins/dsh-ustc-quota/pool/last'
30
+ const POOL_ROWS_PATH = '/plugins/dsh-ustc-quota/pool/rows'
31
+
32
+ /** session -> key provider, so a conversation stays on the same key until it must move. */
33
+ const poolSticky = new Map()
34
+ let poolLastCall = null
35
+
36
+ /** Pick the key for one model call: sticky first, then the least-loaded healthy one. */
37
+ export function pickPoolKey(keys, sessionId) {
38
+ const all = (Array.isArray(keys) ? keys : []).filter((entry) =>
39
+ entry && typeof entry.provider === 'string' && entry.provider.startsWith('ustc-') && entry.blocked !== true)
40
+ if (all.length === 0) return null
41
+ // A key with no quota data is not "empty": treating an unmeasured key as 0% load moves
42
+ // traffic onto a key nobody has verified. Measured keys win; unmeasured ones are the
43
+ // fallback only when nothing has data yet.
44
+ const worstOf = (entry) => {
45
+ let worst = null
46
+ for (const window of Array.isArray(entry.windows) ? entry.windows : []) {
47
+ if (window && typeof window.ratio === 'number' && (worst === null || window.ratio > worst)) worst = window.ratio
48
+ }
49
+ return worst
50
+ }
51
+ const measured = all.filter((entry) => worstOf(entry) !== null)
52
+ const entries = measured.length > 0 ? measured : all
53
+ const stickyProvider = typeof sessionId === 'string' ? poolSticky.get(sessionId) : undefined
54
+ if (typeof stickyProvider === 'string') {
55
+ const held = entries.find((entry) => entry.provider === stickyProvider)
56
+ // Keep the conversation on its key until the wall is near: cache affinity matters more
57
+ // than spreading perfectly.
58
+ const heldWorst = held === undefined ? null : worstOf(held)
59
+ if (held && heldWorst !== null && heldWorst < 0.9) return { provider: held.provider, reason: 'sticky' }
60
+ }
61
+ let best = entries[0]
62
+ for (const entry of entries) {
63
+ const score = worstOf(entry) ?? 0
64
+ if (score < (worstOf(best) ?? 0)) best = entry
65
+ }
66
+ if (typeof sessionId === 'string') poolSticky.set(sessionId, best.provider)
67
+ return { provider: best.provider, reason: stickyProvider === undefined ? 'new' : 'migrate' }
68
+ };
25
69
  const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
26
70
 
27
71
  /**
@@ -68,7 +112,7 @@ function rejectGuard(response, reason) {
68
112
  const UPDATE_PATH = '/plugins/dsh-ustc-quota/update';
69
113
  const UPDATE_APPLY_PATH = '/plugins/dsh-ustc-quota/update/apply';
70
114
  const UPDATE_TOKEN_TTL_MS = 30 * 60 * 1000;
71
- const PLUGIN_VERSION = '1.3.36';
115
+ const PLUGIN_VERSION = '2.0.1';
72
116
  const KEY_INFO_PATH = 'key/info';
73
117
  const USER_INFO_PATH = 'user/info';
74
118
  const DISCOVERY_TTL_MS = 10_000;
@@ -82,9 +126,322 @@ export const inject = ['webServer'];
82
126
 
83
127
  export function apply(ctx, config) {
84
128
  const settings = normalizeConfig(config);
85
- const poolKeySource = createPoolKeySource(ctx);
129
+ const ownKeys = () => {
130
+ const stored = readStoredKeys()
131
+ if (Array.isArray(stored) && stored.length > 0) return stored
132
+ return config && Array.isArray(config.keys) ? config.keys : []
133
+ }
134
+ const poolKeySource = createPoolKeySource(ctx, ownKeys);
86
135
  const reader = createReader(ctx, settings, poolKeySource);
87
136
  const updates = new UpdateService(ctx, { currentVersion: PLUGIN_VERSION });
137
+ // Every configured key gets its native provider row, so the host lists it like any other
138
+ // provider and a conversation can simply select it.
139
+ const poolRowResults = []
140
+ // Observation only: the waterfall hands us the frozen options and the next() chain, so we
141
+ // record and pass through. Rewriting here is impossible (the host's fallback keeps the
142
+ // original options), which is why selection happens through selectModel instead.
143
+ let lastCall = null
144
+ ctx.on('llm/stream', (options, next) => {
145
+ try {
146
+ lastCall = {
147
+ provider: options && typeof options.provider === 'string' ? options.provider : null,
148
+ model: options && typeof options.model === 'string' ? options.model : null,
149
+ sessionId: options && typeof options.sessionId === 'string' ? options.sessionId : null,
150
+ at: Date.now(),
151
+ }
152
+ } catch { /* never break a call */ }
153
+ return next()
154
+ })
155
+ ctx.effect(() => {
156
+ for (const key of keysFromConfig({ keys: ownKeys() })) {
157
+ void syncKeyRow(ctx, { id: key.id, label: key.label, ref: key.credential }).then((result) => {
158
+ poolRowResults.push({ id: key.id, credential: key.credential, ...result, at: Date.now() })
159
+ })
160
+ }
161
+ }, 'dsh-ustc-quota: pool provider rows')
162
+ registerPoolApi(ctx, {
163
+ routeBase: '/plugins/dsh-ustc-quota',
164
+ readKeys: ownKeys,
165
+ onChange: () => {},
166
+ })
167
+ // New conversations inherit the agent default model, so that default is the only lever
168
+ // the pool has over a conversation's FIRST call. Keep it on the least loaded key.
169
+ let lastRotation = null
170
+ const rotateDefault = async () => {
171
+ try {
172
+ const snapshot = await reader.snapshot(false, 'zh')
173
+ const pick = pickPoolKey(snapshot && snapshot.keys, null)
174
+ if (pick === null) return
175
+ const editor = ctx.get('configEditor')
176
+ if (!editor || typeof editor.configuration !== 'function' || typeof editor.edit !== 'function') return
177
+ const rows = editor.configuration()
178
+ const target = (Array.isArray(rows) ? rows : []).find((row) => row && row.entry && row.entry.options
179
+ && row.entry.options.name === '@deepseek-ai/dsh-agent-default-model')
180
+ const entry = target && target.entry ? target.entry : null
181
+ if (entry === null) return
182
+ const composed = entry.options && entry.options.config && Object.keys(entry.options.config).length > 0
183
+ ? entry.options.config
184
+ : (target.override || {})
185
+ const changed = composed.provider !== pick.provider
186
+ let error = null
187
+ if (changed) {
188
+ try {
189
+ await editor.edit(entry, (current) => Object.assign({}, current, { provider: pick.provider }))
190
+ } catch (failure) {
191
+ error = String(failure && (failure.message || failure)).slice(0, 160)
192
+ }
193
+ }
194
+ lastRotation = { pick: pick.provider, defaultProvider: composed.provider, reason: pick.reason, changed, error, at: Date.now() }
195
+ } catch { /* rotation must never break the host */ }
196
+ }
197
+ ctx.effect(() => {
198
+ void rotateDefault()
199
+ const timer = setInterval(() => { void rotateDefault() }, 5 * 60 * 1000)
200
+ return () => clearInterval(timer)
201
+ }, 'dsh-ustc-quota: default model rotation')
202
+ ctx.effect(() => ctx.webServer.register({
203
+ kind: 'exact',
204
+ path: POOL_ROWS_PATH,
205
+ handler: (request, response) => {
206
+ const body = JSON.stringify({ ok: true, rows: poolRowResults, configured: ownKeys().length, rotation: lastRotation })
207
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
208
+ response.end(body)
209
+ },
210
+ }), 'dsh-ustc-quota: pool rows')
211
+ ctx.effect(() => ctx.webServer.register({
212
+ kind: 'exact',
213
+ path: '/plugins/dsh-ustc-quota/pool/last',
214
+ handler: (request, response) => {
215
+ const body = JSON.stringify({ ok: true, last: lastCall })
216
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
217
+ response.end(body)
218
+ },
219
+ }), 'dsh-ustc-quota: pool last call')
220
+ // Migrate conversations that still point at the retired edge provider onto a real key.
221
+ // This must run BEFORE that provider row is withdrawn, otherwise their next turn has no
222
+ // adapter and fails outright.
223
+ const agentSelection = (sessionId) => {
224
+ try {
225
+ const agents = ctx.get('agents')
226
+ const agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : null
227
+ const model = agent && agent.model ? agent.model : null
228
+ if (!model || typeof model.current !== 'function') return null
229
+ const current = model.current()
230
+ if (current === null || typeof current !== 'object' || typeof current.provider !== 'string') return null
231
+ return {
232
+ provider: current.provider,
233
+ model: typeof current.model === 'string' ? current.model : null,
234
+ reasoningEffort: typeof current.reasoningEffort === 'string' ? current.reasoningEffort : null,
235
+ }
236
+ } catch { return null }
237
+ }
238
+ const readSelection = (projections) => {
239
+ if (projections === null || typeof projections !== 'object') return null
240
+ // summaryFor returns { kind, asOfSeq, values } and the projection values live inside it.
241
+ const bag = projections.values && typeof projections.values === 'object' ? projections.values : projections
242
+ const raw = bag.modelSelection !== undefined ? bag.modelSelection : bag['modelSelection']
243
+ if (raw === null || raw === undefined) return null
244
+ const source = raw && typeof raw === 'object' && raw.value !== undefined && raw.ok !== undefined ? raw.value : raw
245
+ // The projection's wire view is { lastUsed, next }; the internal fold is { lastUsed, pending }.
246
+ const chosen = source && typeof source === 'object'
247
+ ? (source.next ?? source.pending ?? source.lastUsed ?? source)
248
+ : source
249
+ if (chosen === null || typeof chosen !== 'object' || typeof chosen.provider !== 'string') return null
250
+ return { provider: chosen.provider, model: typeof chosen.model === 'string' ? chosen.model : null, reasoningEffort: typeof chosen.reasoningEffort === 'string' ? chosen.reasoningEffort : null }
251
+ }
252
+ ctx.effect(() => ctx.webServer.register({
253
+ kind: 'exact',
254
+ path: '/plugins/dsh-ustc-quota/pool/sessions',
255
+ handler: (request, response) => {
256
+ void (async () => {
257
+ const controller = ctx.get('sessionController')
258
+ if (!controller || typeof controller.list !== 'function') {
259
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
260
+ response.end(JSON.stringify({ ok: false, reason: 'no-session-controller' }))
261
+ return
262
+ }
263
+ const listed = await controller.list(undefined)
264
+ const envelope = listed && typeof listed === 'object' && (listed.ok !== undefined || listed.value !== undefined)
265
+ ? (listed.ok === false ? null : listed.value)
266
+ : listed
267
+ const items = envelope && Array.isArray(envelope.sessions) ? envelope.sessions
268
+ : envelope && Array.isArray(envelope.items) ? envelope.items
269
+ : Array.isArray(envelope) ? envelope : []
270
+ const body = JSON.stringify({
271
+ ok: true,
272
+ rawKeys: listed && typeof listed === 'object' ? Object.keys(listed).slice(0, 12) : typeof listed,
273
+ count: items.length,
274
+ sessions: items.slice(0, 50).map((item) => {
275
+ const proj = item && item.projections
276
+ return {
277
+ id: item && item.sessionId ? item.sessionId : null,
278
+ blank: item && item.blank === true,
279
+ selection: agentSelection(item && item.sessionId ? item.sessionId : null) || readSelection(proj),
280
+ projType: proj === null || proj === undefined ? String(proj) : (proj instanceof Map ? 'Map' : Object.prototype.toString.call(proj)),
281
+ projKeys: proj instanceof Map ? [...proj.keys()].slice(0, 8) : (proj && typeof proj === 'object' ? Object.keys(proj).slice(0, 8) : []),
282
+ projSample: (() => { try { return JSON.stringify(proj instanceof Map ? [...proj.values()] : proj).slice(0, 240) } catch { return 'unserializable' } })(),
283
+ }
284
+ }),
285
+ })
286
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
287
+ response.end(body)
288
+ })()
289
+ },
290
+ }), 'dsh-ustc-quota: pool sessions')
291
+ ctx.effect(() => ctx.webServer.register({
292
+ kind: 'exact',
293
+ path: '/plugins/dsh-ustc-quota/pool/migrate',
294
+ handler: (request, response) => {
295
+ void (async () => {
296
+ const controller = ctx.get('sessionController')
297
+ const migrated = []
298
+ const failed = []
299
+ try {
300
+ if (!controller || typeof controller.list !== 'function' || typeof controller.selectModel !== 'function') {
301
+ throw new Error('no-session-controller')
302
+ }
303
+ const snapshot = await reader.snapshot(false, 'zh')
304
+ const pick = pickPoolKey(snapshot && snapshot.keys, null)
305
+ if (pick === null) throw new Error('no-usable-key')
306
+ const listed = await controller.list(undefined)
307
+ const envelope = listed && typeof listed === 'object' && (listed.ok !== undefined || listed.value !== undefined)
308
+ ? (listed.ok === false ? null : listed.value)
309
+ : listed
310
+ const items = envelope && Array.isArray(envelope.items) ? envelope.items
311
+ : envelope && Array.isArray(envelope.sessions) ? envelope.sessions
312
+ : Array.isArray(envelope) ? envelope : []
313
+ for (const item of items) {
314
+ const selection = agentSelection(item && item.sessionId ? item.sessionId : null) || readSelection(item && item.projections)
315
+ if (selection === null || selection.provider !== 'ustc-lb') continue
316
+ const sessionId = item && item.sessionId ? item.sessionId : null
317
+ if (sessionId === null) continue
318
+ try {
319
+ await controller.selectModel({
320
+ sessionId,
321
+ provider: pick.provider,
322
+ model: selection.model || 'deepseek-flash',
323
+ ...(selection.reasoningEffort === null ? {} : { reasoningEffort: selection.reasoningEffort }),
324
+ })
325
+ migrated.push({ sessionId, provider: pick.provider })
326
+ } catch (error) {
327
+ failed.push({ sessionId, reason: String(error && (error.message || error)).slice(0, 120) })
328
+ }
329
+ }
330
+ } catch (error) {
331
+ failed.push({ reason: String(error && (error.message || error)).slice(0, 160) })
332
+ }
333
+ const body = JSON.stringify({ ok: failed.length === 0, migrated, failed })
334
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
335
+ response.end(body)
336
+ })()
337
+ },
338
+ }), 'dsh-ustc-quota: pool migrate')
339
+ // Headless end-to-end probe: create a throwaway conversation and run one real turn, so the
340
+ // pool can be verified without driving the UI.
341
+ ctx.effect(() => ctx.webServer.register({
342
+ kind: 'exact',
343
+ path: '/plugins/dsh-ustc-quota/pool/probe',
344
+ handler: (request, response) => {
345
+ void (async () => {
346
+ const result = { ok: false }
347
+ try {
348
+ const controller = ctx.get('sessionController')
349
+ if (!controller || typeof controller.create !== 'function' || typeof controller.prompt !== 'function') {
350
+ throw new Error('no-session-controller')
351
+ }
352
+ const created = await controller.create({ cwd: 'D:\\valentines\\workspace' })
353
+ const sessionId = created && created.sessionId ? created.sessionId : null
354
+ if (sessionId === null) throw new Error('create-returned-no-session')
355
+ result.sessionId = sessionId
356
+ const accepted = await controller.prompt({
357
+ requestId: 'lb-probe-' + Date.now(),
358
+ sessionId,
359
+ mode: 'queue',
360
+ content: [{ type: 'text', text: '自动验收:请只回复 OK' }],
361
+ }, new AbortController().signal)
362
+ result.accepted = accepted !== null && accepted !== undefined
363
+ result.ok = true
364
+ } catch (error) {
365
+ result.reason = String(error && (error.message || error)).slice(0, 160)
366
+ }
367
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
368
+ response.end(JSON.stringify(result))
369
+ })()
370
+ },
371
+ }), 'dsh-ustc-quota: pool probe')
372
+ // Final retirement of the standalone pool plugin. Sessions must be migrated first; this
373
+ // only strips the references and parks the old package under backups/.
374
+ ctx.effect(() => ctx.webServer.register({
375
+ kind: 'exact',
376
+ path: '/plugins/dsh-ustc-quota/pool/retire-legacy',
377
+ handler: (request, response) => {
378
+ void (async () => {
379
+ const profile = findProfile()
380
+ const result = profile === null ? { profile: null, reason: 'profile-not-found' } : retireManager(profile)
381
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
382
+ response.end(JSON.stringify({ ok: profile !== null, ...result }))
383
+ })()
384
+ },
385
+ }), 'dsh-ustc-quota: retire legacy pool')
386
+ // One-shot clean-up of rows the pool no longer owns (renamed keys, the retired edge pool).
387
+ ctx.effect(() => ctx.webServer.register({
388
+ kind: 'exact',
389
+ path: '/plugins/dsh-ustc-quota/pool/cleanup',
390
+ handler: (request, response) => {
391
+ void (async () => {
392
+ const keep = new Set(ownKeys().map((key) => 'ustc-' + String(key.id)))
393
+ const editor = ctx.get('configEditor')
394
+ let rows = []
395
+ try { rows = editor && typeof editor.configuration === 'function' ? editor.configuration() : [] } catch { rows = [] }
396
+ const removed = []
397
+ for (const row of Array.isArray(rows) ? rows : []) {
398
+ if (!row || !row.entry || !row.entry.options || row.entry.options.name !== '@deepseek-ai/dsh-llm-pi-ai') continue
399
+ const providers = row.entry.options.config && row.entry.options.config.providers
400
+ if (!providers || typeof providers !== 'object') continue
401
+ for (const providerId of Object.keys(providers)) {
402
+ if (!providerId.startsWith('ustc-') || keep.has(providerId)) continue
403
+ const result = await removeProviderRow(ctx, providerId)
404
+ removed.push({ providerId, ...result })
405
+ }
406
+ }
407
+ const body = JSON.stringify({ ok: true, removed })
408
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
409
+ response.end(body)
410
+ })()
411
+ },
412
+ }), 'dsh-ustc-quota: pool cleanup')
413
+ ctx.effect(() => ctx.webServer.register({
414
+ kind: 'exact',
415
+ path: '/plugins/dsh-ustc-quota/pool/rotate',
416
+ handler: (request, response) => {
417
+ void (async () => {
418
+ await rotateDefault()
419
+ const body = JSON.stringify({ ok: true, rotation: lastRotation })
420
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
421
+ response.end(body)
422
+ })()
423
+ },
424
+ }), 'dsh-ustc-quota: pool rotate')
425
+ // Compatibility bridge: conversations created while the retired edge pool was the default
426
+ // still select "ustc-lb". Until they are migrated, that id must resolve to a working row,
427
+ // otherwise their next turn dies with a missing adapter.
428
+ ctx.effect(() => ctx.webServer.register({
429
+ kind: 'exact',
430
+ path: '/plugins/dsh-ustc-quota/pool/compat',
431
+ handler: (request, response) => {
432
+ void (async () => {
433
+ const keys = keysFromConfig({ keys: ownKeys() })
434
+ const key = keys[0]
435
+ let result = { ok: false, reason: 'no-key' }
436
+ if (key !== undefined) {
437
+ result = await syncKeyRow(ctx, { id: key.id, label: key.label, ref: key.credential, rowId: 'ustc-lb' })
438
+ }
439
+ const body = JSON.stringify({ ok: true, row: result })
440
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
441
+ response.end(body)
442
+ })()
443
+ },
444
+ }), 'dsh-ustc-quota: legacy row bridge')
88
445
  const updateTokens = new Map();
89
446
 
90
447
  ctx.effect(() => ctx.webServer.register({
@@ -152,40 +509,15 @@ function isLocalPeer(address) {
152
509
  return ownAddresses().has(bareAddress(plain))
153
510
  }
154
511
 
155
- function createPoolKeySource(ctx) {
156
- const resolveOrigins = () => {
157
- const web = ctx.get('webServer')
158
- const port = web && (web.port ?? web.listenPort ?? web.server?.address?.()?.port)
159
- if (!Number.isFinite(port)) return []
160
- // DSH listens on ONE address. With a LAN/tailnet bind, 127.0.0.1 is refused outright,
161
- // so the bind origin must be a candidate too — the pool accepts a local peer.
162
- const protocol = typeof web.protocol === 'string' ? web.protocol.replace(/:$/, '') : 'http'
163
- const list = [protocol + '://127.0.0.1:' + port, protocol + '://[::1]:' + port]
164
- if (typeof web.getOrigin === 'function') {
165
- try {
166
- const value = web.getOrigin()
167
- if (typeof value === 'string' && value !== '') list.push(value.replace(/\/$/, ''))
168
- } catch { /* ignore */ }
169
- }
170
- return list
171
- }
512
+ function createPoolKeySource(ctx, readOwnKeys) {
513
+ // The pool owns its key list; there is no second plugin to ask any more.
172
514
  return async function poolKeys() {
173
- for (const base of resolveOrigins()) {
174
- const controller = new AbortController()
175
- const timer = setTimeout(() => controller.abort(), 4_000)
176
- try {
177
- const response = await fetch(base + '/plugins/dsh-ustc-provider-manager/keys', {
178
- headers: { accept: 'application/json' },
179
- signal: controller.signal,
180
- })
181
- if (!response.ok) continue
182
- const body = await response.json()
183
- if (body && Array.isArray(body.keys)) return body.keys
184
- } catch { /* try the next origin */ } finally {
185
- clearTimeout(timer)
186
- }
515
+ try {
516
+ const own = typeof readOwnKeys === 'function' ? readOwnKeys() : []
517
+ return Array.isArray(own) ? own : []
518
+ } catch {
519
+ return []
187
520
  }
188
- return []
189
521
  }
190
522
  }
191
523
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ustc-quota",
3
- "version": "1.3.36",
3
+ "version": "2.0.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Live 3h/12h/24h USTC token quota card in the DSH sidebar (works with the USTC TokenWorks distribution).",
@@ -43,7 +43,11 @@
43
43
  "locale/*.json",
44
44
  "icon.svg",
45
45
  "LICENSE",
46
- "README.md"
46
+ "README.md",
47
+ "pool-config.js",
48
+ "pool-api.js",
49
+ "pool-store.js",
50
+ "retire.js"
47
51
  ],
48
52
  "dsh": {
49
53
  "bundle": {
package/pool-api.js ADDED
@@ -0,0 +1,177 @@
1
+ // Key management for the USTC pool, served by dsh-ustc-quota itself.
2
+ //
3
+ // The pool is no longer a proxy: a key is "using it" means the conversation selected the
4
+ // native provider row this module writes. These routes only maintain that list.
5
+
6
+ import { readKeys as readStoredKeys, writeKeys as writeStoredKeys } from './pool-store.js'
7
+ import {
8
+ PI_AI_PLUGIN,
9
+ RESERVED_KEY_IDS,
10
+ keysFromConfig,
11
+ normalizeLabel,
12
+ refFor,
13
+ syncKeyRow,
14
+ } from './pool-config.js'
15
+
16
+ const MAX_BODY = 64 * 1024
17
+
18
+ function readBody(request) {
19
+ return new Promise((resolve) => {
20
+ const chunks = []
21
+ let bytes = 0
22
+ let done = false
23
+ const finish = (value) => { if (!done) { done = true; resolve(value) } }
24
+ const timer = setTimeout(() => finish(null), 5000)
25
+ request.on('data', (chunk) => {
26
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8')
27
+ bytes += buffer.length
28
+ if (bytes > MAX_BODY) { finish(null); return }
29
+ chunks.push(buffer)
30
+ })
31
+ request.on('end', () => {
32
+ clearTimeout(timer)
33
+ try { finish(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { finish(null) }
34
+ })
35
+ request.on('error', () => { clearTimeout(timer); finish(null) })
36
+ })
37
+ }
38
+
39
+ function json(response, body, status = 200) {
40
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
41
+ response.end(JSON.stringify(body))
42
+ }
43
+
44
+ /** Rename a human label into the id the provider row and the credential ref share. */
45
+ export function idForLabel(label) {
46
+ const normalized = normalizeLabel(label)
47
+ if (normalized === '') return ''
48
+ let id = normalized.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')
49
+ if (id === '') id = refFor(normalized).toLowerCase().replace(/^ustc_pool_|_api_key$/g, '').replace(/_/g, '-').slice(0, 40)
50
+ return RESERVED_KEY_IDS.has(id) ? '' : id
51
+ }
52
+
53
+ /** Persist the key list to the plugin's own store. */
54
+ export async function persistKeys(ctx, mutate) {
55
+ const base = readStoredKeys()
56
+ const next = mutate(base.map((key) => Object.assign({}, key)))
57
+ if (!Array.isArray(next)) return { ok: false, reason: 'mutation did not return a key list' }
58
+ const written = writeStoredKeys(next)
59
+ if (written.ok !== true) return { ok: false, reason: written.reason }
60
+ return { ok: true, keys: next }
61
+ }
62
+
63
+ export function registerPoolApi(ctx, options) {
64
+ const base = options && typeof options.routeBase === 'string' ? options.routeBase : '/plugins/dsh-ustc-quota'
65
+ const readKeys = options && typeof options.readKeys === 'function' ? options.readKeys : () => []
66
+ const changed = options && typeof options.onChange === 'function' ? options.onChange : () => {}
67
+
68
+ const list = async () => keysFromConfig({ keys: readKeys() })
69
+
70
+ const saveKey = async (request, response) => {
71
+ const body = await readBody(request)
72
+ if (body === null || typeof body !== 'object') { json(response, { ok: false, reason: 'invalid-body' }, 400); return }
73
+ const label = normalizeLabel(body.label ?? body.name ?? '')
74
+ const secret = typeof body.secret === 'string' ? body.secret.trim() : ''
75
+ if (label === '' || secret === '') { json(response, { ok: false, reason: 'label-and-secret-required' }, 400); return }
76
+ const id = idForLabel(label)
77
+ if (id === '') { json(response, { ok: false, reason: 'reserved-key-id' }, 400); return }
78
+ const ref = refFor(label)
79
+ const store = ctx.get('credentials')
80
+ if (!store || typeof store.set !== 'function') { json(response, { ok: false, reason: 'credentials-unavailable' }, 503); return }
81
+ try { await store.set(ref, secret) } catch { json(response, { ok: false, reason: 'credential-write-failed' }, 500); return }
82
+ const persisted = await persistKeys(ctx, (keys) => {
83
+ const rest = keys.filter((key) => String(key.id) !== id && String(key.credential) !== ref)
84
+ rest.push({ id, label, credential: ref })
85
+ return rest
86
+ })
87
+ if (persisted.ok !== true) { json(response, { ok: false, reason: persisted.reason }, 500); return }
88
+ const row = await syncKeyRow(ctx, { id, label, ref })
89
+ if (row.ok !== true) { json(response, { ok: false, reason: row.reason, key: { id, label, credential: ref } }, 500); return }
90
+ changed()
91
+ json(response, { ok: true, key: { id, label, credential: ref } })
92
+ }
93
+
94
+ const deleteKey = async (request, response) => {
95
+ const body = await readBody(request)
96
+ if (body === null || typeof body !== 'object') { json(response, { ok: false, reason: 'invalid-body' }, 400); return }
97
+ const id = typeof body.id === 'string' ? body.id : ''
98
+ if (id === '') { json(response, { ok: false, reason: 'id-required' }, 400); return }
99
+ const current = await list()
100
+ const target = current.find((key) => key.id === id)
101
+ if (target === undefined) { json(response, { ok: false, reason: 'unknown-key' }, 404); return }
102
+ const persisted = await persistKeys(ctx, (keys) => keys.filter((key) => String(key.id) !== id))
103
+ if (persisted.ok !== true) { json(response, { ok: false, reason: persisted.reason }, 500); return }
104
+ await syncKeyRow(ctx, { id, label: target.label, ref: target.credential, remove: true })
105
+ changed()
106
+ json(response, { ok: true, removed: id })
107
+ }
108
+
109
+ const importKeys = async (request, response) => {
110
+ const existing = await list()
111
+ const store = ctx.get('credentials')
112
+ const seen = new Set(existing.map((key) => key.credential))
113
+ const editor = ctx.get('configEditor')
114
+ let rows = []
115
+ try { rows = editor && typeof editor.configuration === 'function' ? editor.configuration() : [] } catch { rows = [] }
116
+ const candidates = new Map()
117
+ for (const row of Array.isArray(rows) ? rows : []) {
118
+ const name = row && row.entry && row.entry.options ? row.entry.options.name : null
119
+ if (name !== PI_AI_PLUGIN) continue
120
+ const providers = row.entry.options.config && row.entry.options.config.providers
121
+ if (!providers || typeof providers !== 'object') continue
122
+ for (const [providerId, definition] of Object.entries(providers)) {
123
+ const ref = definition && typeof definition.apiKeyEnv === 'string' ? definition.apiKeyEnv.trim() : ''
124
+ // The provider id is the source of truth: a row named ustc-wmw owns the key "wmw",
125
+ // whoever wrote it. Deriving the id from the credential ref turned USTC_API_KEY into
126
+ // "api_key" and produced a second provider row for the same key.
127
+ if (ref === '' || ref === 'USTC_POOL_LB_EDGE_TOKEN') continue
128
+ const bare = providerId.startsWith('ustc-') ? providerId.slice(5) : ''
129
+ if (bare === '' || bare === 'lb') continue
130
+ candidates.set(bare, { ref, label: definition && typeof definition.displayName === 'string' ? definition.displayName : bare })
131
+ }
132
+ }
133
+ const adopted = []
134
+ for (const [bare, entry] of candidates) {
135
+ if (seen.has(entry.ref)) continue
136
+ let resolved = null
137
+ if (store && typeof store.resolve === 'function') {
138
+ try { resolved = await store.resolve(entry.ref) } catch { resolved = null }
139
+ }
140
+ if (!resolved || typeof resolved.value !== 'string' || resolved.value === '') continue
141
+ const id = idForLabel(bare)
142
+ if (id === '') continue
143
+ adopted.push({ id, label: normalizeLabel(entry.label || bare), credential: entry.ref })
144
+ }
145
+ if (adopted.length > 0) {
146
+ const persisted = await persistKeys(ctx, (keys) => keys.concat(adopted))
147
+ if (persisted.ok !== true) { json(response, { ok: false, reason: persisted.reason }, 500); return }
148
+ for (const key of adopted) await syncKeyRow(ctx, { id: key.id, label: key.label, ref: key.credential })
149
+ changed()
150
+ }
151
+ json(response, { ok: true, adopted: adopted.map((key) => key.id) })
152
+ }
153
+
154
+ ctx.effect(() => ctx.webServer.register({
155
+ kind: 'exact',
156
+ path: base + '/keys',
157
+ handler: (request, response) => { void (async () => json(response, { ok: true, keys: await list() }))() },
158
+ }), 'dsh-ustc-quota: key list')
159
+
160
+ ctx.effect(() => ctx.webServer.register({
161
+ kind: 'exact',
162
+ path: base + '/key',
163
+ handler: (request, response) => { void saveKey(request, response) },
164
+ }), 'dsh-ustc-quota: key save')
165
+
166
+ ctx.effect(() => ctx.webServer.register({
167
+ kind: 'exact',
168
+ path: base + '/key/delete',
169
+ handler: (request, response) => { void deleteKey(request, response) },
170
+ }), 'dsh-ustc-quota: key delete')
171
+
172
+ ctx.effect(() => ctx.webServer.register({
173
+ kind: 'exact',
174
+ path: base + '/key/import',
175
+ handler: (request, response) => { void importKeys(request, response) },
176
+ }), 'dsh-ustc-quota: key import')
177
+ }
package/pool-config.js ADDED
@@ -0,0 +1,244 @@
1
+ // Key storage and native provider rows for the USTC pool.
2
+ //
3
+ // Ported from dsh-ustc-provider-manager when the pool was folded back into
4
+ // dsh-ustc-quota: the pool no longer proxies traffic, it only decides which native
5
+ // provider row a conversation should use, so this file holds the row bookkeeping and
6
+ // nothing else.
7
+
8
+ export const PI_AI_PLUGIN = '@deepseek-ai/dsh-llm-pi-ai'
9
+ /** The single provider id the old pool advertised; must never be a per-key row id. */
10
+ export const PROVIDER = 'ustc-lb'
11
+ /** Gateway every pool key talks to; a key may override it explicitly. */
12
+ export const DEFAULT_BASE_URL = 'https://api.llm.ustc.edu.cn'
13
+
14
+ export const CATALOG = [
15
+ {
16
+ id: 'deepseek-v4-flash-ascend',
17
+ name: 'deepseek-v4-flash-ascend',
18
+ description: 'USTC 网关上的 DeepSeek Flash(Ascend 后端)',
19
+ contextWindow: 1000000,
20
+ maxTokens: 8192,
21
+ },
22
+ {
23
+ id: 'smart/default',
24
+ name: 'smart/default',
25
+ description: 'USTC 网关的自动路由模型',
26
+ contextWindow: 1000000,
27
+ maxTokens: 8192,
28
+ },
29
+ {
30
+ // The id the official USTC DSH guide uses; without it users following the guide hit
31
+ // UNKNOWN_MODEL and no key is ever tried.
32
+ id: 'deepseek-flash',
33
+ name: 'deepseek-flash',
34
+ description: 'DeepSeek Flash(USTC 官方 DSH 指南模型)',
35
+ contextWindow: 393216,
36
+ maxTokens: 32768,
37
+ },
38
+ ]
39
+
40
+ export const RESERVED_KEY_IDS = new Set(['lb', 'llm'])
41
+
42
+ export const POOL_REF_PREFIX = 'USTC_POOL_'
43
+
44
+ export function rowConfig(row) {
45
+ // Prefer the loader's composed value: the home layer is applied last, so reading
46
+ // override() first would report a value the host has already superseded.
47
+ const composed = row && row.entry && row.entry.options ? row.entry.options.config : null
48
+ if (composed && typeof composed === 'object' && Object.keys(composed).length > 0) return composed
49
+ const override = row && row.override && typeof row.override === 'object' ? row.override : null
50
+ if (override && Object.keys(override).length > 0) return override
51
+ const inherited = row && row.inherited && typeof row.inherited === 'object' ? row.inherited : null
52
+ if (inherited && Object.keys(inherited).length > 0) return inherited
53
+ const direct = row && row.entry && row.entry.options && row.entry.options.config
54
+ return direct && typeof direct === 'object' ? direct : {}
55
+ }
56
+
57
+ export function normalizeLabel(raw) {
58
+ return String(raw)
59
+ .normalize('NFC')
60
+ // Everything Unicode classifies as control, format, or line/paragraph separator.
61
+ .replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, '')
62
+ .trim()
63
+ .slice(0, 64)
64
+ }
65
+
66
+ export function refFor(label) {
67
+ const stem = String(label).toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '')
68
+ if (stem !== '') return POOL_REF_PREFIX + stem + '_API_KEY'
69
+ let hash = 0
70
+ for (const char of String(label)) hash = (hash * 31 + char.codePointAt(0)) >>> 0
71
+ return POOL_REF_PREFIX + 'KEY_' + hash.toString(36).toUpperCase() + '_API_KEY'
72
+ }
73
+
74
+ export function desiredProviderRow(existing, action) {
75
+ if (action.remove === true) {
76
+ const poolOwned = existing && typeof existing.apiKeyEnv === 'string'
77
+ && existing.apiKeyEnv.startsWith(POOL_REF_PREFIX)
78
+ && existing.apiKeyEnv === action.ref
79
+ // Not ours: leave the table exactly as it is. Returning row:null here would write
80
+ // null over a provider the user declared.
81
+ return poolOwned ? { remove: true, skip: null, row: null } : { keep: true, remove: false, skip: null, row: null }
82
+ }
83
+ // 'ustc-lb' is this plugin's own adapter id: advertising a provider with that name makes
84
+ // the host's registerAdapter throw DUPLICATE_ADAPTER and drop the entire group.
85
+ // 'ustc-llm' is the row a TokenWorks host publishes for its own account; a pool key
86
+ // with that id would be merged away and silently lose its quota data.
87
+ if (RESERVED_KEY_IDS.has(action.id) || 'ustc-' + action.id === PROVIDER) {
88
+ return { remove: false, skip: 'provider-id-reserved', row: null }
89
+ }
90
+ if (existing !== undefined && existing !== null && existing.apiKeyEnv !== action.ref) {
91
+ return { remove: false, skip: 'provider-route-owned-by-user', row: null }
92
+ }
93
+ const base = existing && typeof existing === 'object' ? existing : {}
94
+ const EFFORTS = { low: 'low', medium: 'medium', high: 'high' }
95
+ // Existing rows are kept, but the pool's own catalogue is merged in: a row written by an
96
+ // older pool version advertises model ids the current default may no longer resolve, and a
97
+ // provider that cannot resolve the conversation's model fails the call outright.
98
+ const declaredById = new Map()
99
+ for (const model of Array.isArray(base.models) ? base.models : []) {
100
+ if (model && typeof model.id === 'string') declaredById.set(model.id, model)
101
+ }
102
+ for (const model of CATALOG) {
103
+ if (!declaredById.has(model.id)) declaredById.set(model.id, { id: model.id, name: model.name })
104
+ }
105
+ const declared = declaredById.size > 0
106
+ ? [...declaredById.values()]
107
+ : CATALOG.map((model) => ({ id: model.id, name: model.name }))
108
+ // A row written by an older version carries only id/name, and pi-ai falls back to its own
109
+ // defaults for the rest — which is why effort was not selectable. Fill every field, keeping
110
+ // whatever the user already set.
111
+ const models = declared.map((model) => {
112
+ const known = CATALOG.find((entry) => entry && entry.id === model.id) || CATALOG[0]
113
+ return Object.assign({}, model, {
114
+ name: typeof model.name === 'string' && model.name !== '' ? model.name : model.id,
115
+ contextWindow: Number.isFinite(model.contextWindow) ? model.contextWindow : known.contextWindow,
116
+ maxTokens: Number.isFinite(model.maxTokens) ? model.maxTokens : known.maxTokens,
117
+ input: Array.isArray(model.input) ? model.input : (Array.isArray(known.input) ? known.input : ['text']),
118
+ reasoningEfforts: model.reasoningEfforts !== undefined ? model.reasoningEfforts : EFFORTS,
119
+ })
120
+ })
121
+ // Preserve anything else the row carries (headers, compat flags, pricing); this pool
122
+ // only owns the routing fields it needs to set.
123
+ return {
124
+ remove: false,
125
+ skip: null,
126
+ row: Object.assign({}, base, {
127
+ displayName: typeof base.displayName === 'string' && base.displayName !== '' ? base.displayName : action.label,
128
+ api: typeof base.api === 'string' && base.api !== '' ? base.api : 'openai-completions',
129
+ baseURL: typeof action.baseURL === 'string' && action.baseURL !== ''
130
+ ? action.baseURL
131
+ : (typeof base.baseURL === 'string' && base.baseURL !== '' ? base.baseURL : DEFAULT_BASE_URL),
132
+ apiKeyEnv: action.ref,
133
+ models,
134
+ // Provider-level defaults: the settings page shows these for any model that does not
135
+ // override them, and the runtime falls back to them when building a request.
136
+ defaultContextWindow: typeof base.defaultContextWindow === 'number' ? base.defaultContextWindow : CATALOG[0].contextWindow,
137
+ defaultMaxTokens: typeof base.defaultMaxTokens === 'number' ? base.defaultMaxTokens : CATALOG[0].maxTokens,
138
+ defaultInput: Array.isArray(base.defaultInput) ? base.defaultInput : ['text'],
139
+ }),
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Write (or withdraw) one pool key's native provider row.
145
+ *
146
+ * The pool no longer proxies traffic, so this row is the whole mechanism: the host lists
147
+ * "ustc-<id>" as a normal provider, and selecting it for a conversation is what "using
148
+ * that key" means.
149
+ */
150
+ export async function syncKeyRow(ctx, action) {
151
+ const editor = ctx.get('configEditor')
152
+ if (!editor || typeof editor.configuration !== 'function' || typeof editor.edit !== 'function') {
153
+ return { ok: false, reason: 'no-config-editor' }
154
+ }
155
+ let target = null
156
+ try {
157
+ const rows = editor.configuration()
158
+ target = (Array.isArray(rows) ? rows : []).find((row) => {
159
+ const name = row && row.entry && row.entry.options ? row.entry.options.name : null
160
+ return name === PI_AI_PLUGIN
161
+ }) ?? null
162
+ } catch { return { ok: false, reason: 'no-pi-ai-row' } }
163
+ const entry = target && target.entry ? target.entry : null
164
+ if (entry === null) return { ok: false, reason: 'no-pi-ai-entry' }
165
+ const providerId = action.rowId !== undefined ? action.rowId : 'ustc-' + action.id
166
+ const composed = entry.options && entry.options.config && Object.keys(entry.options.config).length > 0
167
+ ? entry.options.config
168
+ : null
169
+ const currentConfig = composed ?? target.override ?? {}
170
+ const currentProviders = currentConfig && typeof currentConfig.providers === 'object' && currentConfig.providers !== null
171
+ ? currentConfig.providers
172
+ : {}
173
+ const wanted = desiredProviderRow(currentProviders[providerId], action)
174
+ if (wanted.skip !== null) return { ok: false, reason: wanted.skip }
175
+ if (wanted.keep === true) return { ok: true, unchanged: true }
176
+ if (wanted.remove === true) {
177
+ if (currentProviders[providerId] === undefined) return { ok: true, unchanged: true }
178
+ } else if (JSON.stringify(currentProviders[providerId]) === JSON.stringify(wanted.row)) {
179
+ return { ok: true, unchanged: true }
180
+ }
181
+ try {
182
+ await editor.edit(entry, (current) => {
183
+ const next = Object.assign({}, current)
184
+ const providers = Object.assign({}, next.providers && typeof next.providers === 'object' ? next.providers : {})
185
+ if (wanted.remove === true) delete providers[providerId]
186
+ else providers[providerId] = wanted.row
187
+ next.providers = providers
188
+ return next
189
+ })
190
+ return { ok: true, unchanged: false }
191
+ } catch (error) {
192
+ return { ok: false, reason: String(error && error.message || error).slice(0, 160) }
193
+ }
194
+ }
195
+
196
+ /** Normalize the configured key list (ids, labels and credential refs only). */
197
+ export function keysFromConfig(config) {
198
+ const raw = config && Array.isArray(config.keys) ? config.keys : []
199
+ const seen = new Set()
200
+ const keys = []
201
+ for (const entry of raw) {
202
+ if (entry === null || typeof entry !== 'object') continue
203
+ const label = normalizeLabel(entry.label ?? entry.id ?? '')
204
+ if (label === '') continue
205
+ // A label that slugs to nothing (e.g. 中文) still needs a stable id, otherwise the key
206
+ // would be silently dropped when the user only typed a name.
207
+ let id = String(entry.id ?? label).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')
208
+ if (id === '') id = refFor(label).toLowerCase().replace(/^ustc_pool_|_api_key$/g, '').replace(/_/g, '-').slice(0, 40)
209
+ if (id === '' || RESERVED_KEY_IDS.has(id) || seen.has(id)) continue
210
+ seen.add(id)
211
+ const credential = typeof entry.credential === 'string' && entry.credential !== ''
212
+ ? entry.credential
213
+ : refFor(label)
214
+ keys.push({ id, label, credential, enabled: entry.enabled !== false })
215
+ }
216
+ return keys
217
+ }
218
+
219
+ /** Remove one provider row by id, whatever credential ref it carries. */
220
+ export async function removeProviderRow(ctx, providerId) {
221
+ const editor = ctx.get('configEditor')
222
+ if (!editor || typeof editor.configuration !== 'function' || typeof editor.edit !== 'function') {
223
+ return { ok: false, reason: 'no-config-editor' }
224
+ }
225
+ let target = null
226
+ try {
227
+ target = (Array.isArray(editor.configuration()) ? editor.configuration() : []).find((row) =>
228
+ row && row.entry && row.entry.options && row.entry.options.name === PI_AI_PLUGIN) ?? null
229
+ } catch { return { ok: false, reason: 'no-pi-ai-row' } }
230
+ const entry = target && target.entry ? target.entry : null
231
+ if (entry === null) return { ok: false, reason: 'no-pi-ai-entry' }
232
+ try {
233
+ await editor.edit(entry, (current) => {
234
+ const next = Object.assign({}, current)
235
+ const providers = Object.assign({}, next.providers && typeof next.providers === 'object' ? next.providers : {})
236
+ delete providers[providerId]
237
+ next.providers = providers
238
+ return next
239
+ })
240
+ return { ok: true }
241
+ } catch (error) {
242
+ return { ok: false, reason: String(error && error.message || error).slice(0, 160) }
243
+ }
244
+ }
package/pool-store.js ADDED
@@ -0,0 +1,40 @@
1
+ // Durable key list for the pool.
2
+ //
3
+ // The plugin's own config row proved transient: writes landed in a composed layer that a
4
+ // restart discarded, which silently emptied the pool. A small JSON file next to the host's
5
+ // home is boring and survives restarts.
6
+
7
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
8
+ import { homedir } from 'node:os'
9
+ import { dirname, join } from 'node:path'
10
+
11
+ export function keysFilePath() {
12
+ const home = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
13
+ ? process.env.DSH_HOME
14
+ : join(homedir(), '.dsh')
15
+ return join(home, 'dsh-ustc-quota.keys.json')
16
+ }
17
+
18
+ export function readKeys() {
19
+ try {
20
+ const raw = readFileSync(keysFilePath(), 'utf8')
21
+ const parsed = JSON.parse(raw)
22
+ return parsed && Array.isArray(parsed.keys) ? parsed.keys : []
23
+ } catch {
24
+ return []
25
+ }
26
+ }
27
+
28
+ export function writeKeys(keys) {
29
+ const file = keysFilePath()
30
+ const body = JSON.stringify({ version: 1, keys: Array.isArray(keys) ? keys : [] }, null, 2) + '\n'
31
+ try {
32
+ mkdirSync(dirname(file), { recursive: true })
33
+ const tmp = file + '.tmp-' + process.pid
34
+ writeFileSync(tmp, body, 'utf8')
35
+ renameSync(tmp, file)
36
+ return { ok: true, file }
37
+ } catch (error) {
38
+ return { ok: false, reason: String(error && (error.message || error)).slice(0, 160) }
39
+ }
40
+ }
package/retire.js ADDED
@@ -0,0 +1,120 @@
1
+ // One-shot retirement of the standalone pool plugin.
2
+ //
3
+ // Every historical session that still selects "ustc-lb" must be migrated before the row and
4
+ // the plugin disappear, otherwise its next turn fails; the caller migrates first, then calls
5
+ // this module to strip the remaining references.
6
+
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
8
+ import { homedir } from 'node:os'
9
+ import { dirname, join, resolve } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+
12
+ export const MANAGER_PACKAGE = 'dsh-ustc-provider-manager'
13
+
14
+ function stamp() {
15
+ const now = new Date()
16
+ const pad = (value) => String(value).padStart(2, '0')
17
+ return now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + '-' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds())
18
+ }
19
+
20
+ /** Remove the manager from a profile manifest, returning the new text (or null when absent). */
21
+ export function stripManifest(text) {
22
+ const parsed = JSON.parse(text)
23
+ const profile = parsed && parsed.dsh && parsed.dsh.profile ? parsed.dsh.profile : null
24
+ if (profile === null) return null
25
+ let changed = false
26
+ if (Array.isArray(profile.bundles)) {
27
+ const next = profile.bundles.filter((name) => name !== MANAGER_PACKAGE)
28
+ if (next.length !== profile.bundles.length) { profile.bundles = next; changed = true }
29
+ }
30
+ if (profile.dependencies && typeof profile.dependencies === 'object' && profile.dependencies[MANAGER_PACKAGE] !== undefined) {
31
+ const next = Object.assign({}, profile.dependencies)
32
+ delete next[MANAGER_PACKAGE]
33
+ profile.dependencies = next
34
+ changed = true
35
+ }
36
+ return changed ? JSON.stringify(parsed, null, 2) + '\n' : null
37
+ }
38
+
39
+ /** Remove the manager's entry (and its indented block) from a patch document. */
40
+ export function stripPatchEntry(text) {
41
+ const pattern = /^- id: ustc-provider-manager\r?\n(?:[ \t]+.*\r?\n)*/m
42
+ return pattern.test(text) ? text.replace(pattern, '') : null
43
+ }
44
+
45
+ /**
46
+ * Find the profile that runs dsh-ustc-quota.
47
+ *
48
+ * This module lives at <profile>/node_modules/dsh-ustc-quota/retire.js, so the plugin's own
49
+ * location identifies the running profile exactly. Scanning ~/.dsh/profiles can hit another
50
+ * profile that merely lists the plugin, which is how the first attempt retired the wrong one.
51
+ */
52
+ export function findProfile(root = join(homedir(), '.dsh', 'profiles')) {
53
+ try {
54
+ const here = dirname(fileURLToPath(import.meta.url))
55
+ const candidate = resolve(here, '..', '..')
56
+ const manifest = join(candidate, 'package.json')
57
+ if (existsSync(manifest)) {
58
+ const parsed = JSON.parse(readFileSync(manifest, 'utf8'))
59
+ const bundles = parsed && parsed.dsh && parsed.dsh.profile ? parsed.dsh.profile.bundles : null
60
+ if (Array.isArray(bundles) && bundles.includes('dsh-ustc-quota')) return candidate
61
+ }
62
+ } catch { /* fall back to scanning */ }
63
+ let names = []
64
+ try { names = readdirSync(root) } catch { return null }
65
+ const candidates = []
66
+ for (const name of names) {
67
+ const dir = join(root, name)
68
+ try {
69
+ const parsed = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'))
70
+ const bundles = parsed && parsed.dsh && parsed.dsh.profile ? parsed.dsh.profile.bundles : null
71
+ if (!Array.isArray(bundles) || !bundles.includes('dsh-ustc-quota')) continue
72
+ // The profile that actually has the plugin (and the old pool) installed is the live one.
73
+ const score = (existsSync(join(dir, 'node_modules', 'dsh-ustc-quota')) ? 2 : 0)
74
+ + (existsSync(join(dir, 'node_modules', MANAGER_PACKAGE)) ? 1 : 0)
75
+ candidates.push({ dir, score })
76
+ } catch { /* not a profile */ }
77
+ }
78
+ if (candidates.length === 0) return null
79
+ candidates.sort((a, b) => b.score - a.score)
80
+ return candidates[0].dir
81
+ }
82
+
83
+ export function retireManager(profileDir) {
84
+ const result = { profile: profileDir, manifest: false, patch: false, nodeModules: false, backups: [] }
85
+ if (typeof profileDir !== 'string' || !existsSync(profileDir)) return result
86
+ const backupDir = join(profileDir, 'backups', 'retire-manager-' + stamp())
87
+ mkdirSync(backupDir, { recursive: true })
88
+ const manifestPath = join(profileDir, 'package.json')
89
+ const patchPath = join(profileDir, 'cordis.patch.yml')
90
+ try {
91
+ const text = readFileSync(manifestPath, 'utf8')
92
+ const next = stripManifest(text)
93
+ if (next !== null) {
94
+ const backup = join(backupDir, 'package.json')
95
+ writeFileSync(backup, text, 'utf8')
96
+ result.backups.push(backup)
97
+ writeFileSync(manifestPath, next, 'utf8')
98
+ result.manifest = true
99
+ }
100
+ } catch { /* leave the manifest alone on any error */ }
101
+ try {
102
+ const text = readFileSync(patchPath, 'utf8')
103
+ const next = stripPatchEntry(text)
104
+ if (next !== null) {
105
+ const backup = join(backupDir, 'cordis.patch.yml')
106
+ writeFileSync(backup, text, 'utf8')
107
+ result.backups.push(backup)
108
+ writeFileSync(patchPath, next, 'utf8')
109
+ result.patch = true
110
+ }
111
+ } catch { /* leave the patch alone on any error */ }
112
+ try {
113
+ const dir = join(profileDir, 'node_modules', MANAGER_PACKAGE)
114
+ if (existsSync(dir) && statSync(dir).isDirectory()) {
115
+ renameSync(dir, join(backupDir, 'dsh-ustc-provider-manager'))
116
+ result.nodeModules = true
117
+ }
118
+ } catch { /* keep the copy if it cannot be moved */ }
119
+ return result
120
+ }