dsh-ustc-quota 2.0.1 → 2.0.4

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/client.js CHANGED
@@ -55,7 +55,7 @@ window.__ModuleLoader__.load({
55
55
  return 0;
56
56
  }
57
57
  }
58
- const CLIENT_VERSION = '2.0.1';
58
+ const CLIENT_VERSION = '2.0.4';
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`;
package/index.js CHANGED
@@ -33,10 +33,61 @@ const POOL_ROWS_PATH = '/plugins/dsh-ustc-quota/pool/rows'
33
33
  const poolSticky = new Map()
34
34
  let poolLastCall = null
35
35
 
36
+ /**
37
+ * Decide whether the step about to run should switch keys.
38
+ *
39
+ * Returns the selection to apply, or null when the agent must stay where it is. Only pool
40
+ * providers are managed: a conversation the user pointed at a non-pool provider is left alone.
41
+ */
42
+ export function nextSelectionFor(current, keys, sessionId, options = {}) {
43
+ if (current === null || typeof current !== 'object') return null
44
+ const allowed = options.allowed === undefined ? null : options.allowed
45
+ const delegated = options.delegated === true
46
+ const owned = typeof current.provider === 'string'
47
+ && current.provider.startsWith('ustc-')
48
+ && current.provider !== PROVIDER
49
+ && (allowed === null || allowed === undefined || allowed.has(current.provider))
50
+ if (!owned) return null
51
+ const pick = pickPoolKey(keys, sessionId, allowed)
52
+ if (pick === null) return null
53
+ // A conversation the user pointed at a healthy key stays there; only a delegated child is
54
+ // allocated immediately, and any agent moves once its key reaches the wall.
55
+ const worst = (Array.isArray(keys) ? keys : [])
56
+ .filter((entry) => entry && entry.provider === current.provider)
57
+ .map((entry) => Math.max(0, ...(Array.isArray(entry.windows) ? entry.windows : []).map((window) => (window && typeof window.ratio === 'number' ? window.ratio : 0)), 0))
58
+ .reduce((a, b) => Math.max(a, b), 0)
59
+ if (!delegated && worst < WALL_RATIO) {
60
+ // Respect the key this conversation is already on: a manual choice must survive, and a
61
+ // healthy key must not be abandoned just because another one is quieter.
62
+ if (typeof sessionId === 'string') poolSticky.set(sessionId, current.provider)
63
+ return { provider: current.provider, model: current.model, reasoningEffort: current.reasoningEffort, changed: false, reason: 'sticky' }
64
+ }
65
+ if (pick.provider === current.provider) return { provider: current.provider, model: current.model, reasoningEffort: current.reasoningEffort, changed: false, reason: pick.reason }
66
+ return {
67
+ provider: pick.provider,
68
+ model: current.model,
69
+ ...(current.reasoningEffort === undefined ? {} : { reasoningEffort: current.reasoningEffort }),
70
+ changed: true,
71
+ reason: pick.reason,
72
+ }
73
+ }
74
+
75
+ /** The retired edge-pool provider id: never a per-key row, never chosen again. */
76
+ const PROVIDER = 'ustc-lb'
77
+
78
+ /** Load ratio above which a key must hand the conversation to another one. */
79
+ export const WALL_RATIO = 0.9
80
+
36
81
  /** Pick the key for one model call: sticky first, then the least-loaded healthy one. */
37
- export function pickPoolKey(keys, sessionId) {
82
+ export function pickPoolKey(keys, sessionId, allowed = null) {
83
+ // Only providers the pool owns take part: a user-declared ustc-<name> row is theirs, and
84
+ // the retired 'ustc-lb' must never be chosen again.
85
+ const owned = (provider) => typeof provider === 'string'
86
+ && provider.startsWith('ustc-')
87
+ && provider !== PROVIDER
88
+ && (allowed === null || allowed === undefined || allowed.has(provider))
38
89
  const all = (Array.isArray(keys) ? keys : []).filter((entry) =>
39
- entry && typeof entry.provider === 'string' && entry.provider.startsWith('ustc-') && entry.blocked !== true)
90
+ entry && owned(entry.provider) && entry.blocked !== true && entry.ok !== false)
40
91
  if (all.length === 0) return null
41
92
  // A key with no quota data is not "empty": treating an unmeasured key as 0% load moves
42
93
  // traffic onto a key nobody has verified. Measured keys win; unmeasured ones are the
@@ -56,7 +107,7 @@ export function pickPoolKey(keys, sessionId) {
56
107
  // Keep the conversation on its key until the wall is near: cache affinity matters more
57
108
  // than spreading perfectly.
58
109
  const heldWorst = held === undefined ? null : worstOf(held)
59
- if (held && heldWorst !== null && heldWorst < 0.9) return { provider: held.provider, reason: 'sticky' }
110
+ if (held && heldWorst !== null && heldWorst < WALL_RATIO) return { provider: held.provider, reason: 'sticky' }
60
111
  }
61
112
  let best = entries[0]
62
113
  for (const entry of entries) {
@@ -112,7 +163,7 @@ function rejectGuard(response, reason) {
112
163
  const UPDATE_PATH = '/plugins/dsh-ustc-quota/update';
113
164
  const UPDATE_APPLY_PATH = '/plugins/dsh-ustc-quota/update/apply';
114
165
  const UPDATE_TOKEN_TTL_MS = 30 * 60 * 1000;
115
- const PLUGIN_VERSION = '2.0.1';
166
+ const PLUGIN_VERSION = '2.0.4';
116
167
  const KEY_INFO_PATH = 'key/info';
117
168
  const USER_INFO_PATH = 'user/info';
118
169
  const DISCOVERY_TTL_MS = 10_000;
@@ -126,6 +177,7 @@ export const inject = ['webServer'];
126
177
 
127
178
  export function apply(ctx, config) {
128
179
  const settings = normalizeConfig(config);
180
+ const poolProviders = () => new Set(keysFromConfig({ keys: ownKeys() }).map((key) => 'ustc-' + key.id))
129
181
  const ownKeys = () => {
130
182
  const stored = readStoredKeys()
131
183
  if (Array.isArray(stored) && stored.length > 0) return stored
@@ -137,6 +189,20 @@ export function apply(ctx, config) {
137
189
  // Every configured key gets its native provider row, so the host lists it like any other
138
190
  // provider and a conversation can simply select it.
139
191
  const poolRowResults = []
192
+ let poolSnapshot = null
193
+ const guarded = (handler, methods) => (request, response) => {
194
+ const reason = guardRequest(request)
195
+ if (reason !== null) { rejectGuard(response, reason); return }
196
+ const method = typeof request.method === 'string' ? request.method.toUpperCase() : 'GET'
197
+ if (!methods.includes(method)) {
198
+ response.writeHead(405, { 'content-type': 'application/json; charset=utf-8', allow: methods.join(', ') })
199
+ response.end(JSON.stringify({ ok: false, reason: 'method-not-allowed' }))
200
+ return
201
+ }
202
+ return handler(request, response)
203
+ }
204
+
205
+ let lastPoolMove = null
140
206
  // Observation only: the waterfall hands us the frozen options and the next() chain, so we
141
207
  // record and pass through. Rewriting here is impossible (the host's fallback keeps the
142
208
  // original options), which is why selection happens through selectModel instead.
@@ -164,6 +230,42 @@ export function apply(ctx, config) {
164
230
  readKeys: ownKeys,
165
231
  onChange: () => {},
166
232
  })
233
+ // Every agent — top-level or delegated child — gets its key here.
234
+ //
235
+ // A subagent inherits the parent's provider at creation (dsh-subagent
236
+ // parentAgentOptionsForDelegation) and the controller's selectModel refuses child sessions
237
+ // with a subagent-ownership error, but the agent's own model cursor is writable: appending
238
+ // a model/selection event is exactly what the model picker does. Doing it in pre-step means
239
+ // the very step about to run already uses the chosen key.
240
+ ctx.on('agent/pre-step', ({ agent, step }, next) => {
241
+ try {
242
+ const current = agent && agent.model && typeof agent.model.current === 'function' ? agent.model.current() : null
243
+ const sessionId = agent && agent.session && typeof agent.session.id === 'string' ? agent.session.id : null
244
+ const allowed = poolProviders()
245
+ const depth = agent && agent.options && Number.isFinite(agent.options.subagentDepth) ? agent.options.subagentDepth : 0
246
+ const decision = nextSelectionFor(current, poolSnapshot === null ? [] : poolSnapshot.keys, sessionId, { allowed, delegated: depth > 0 })
247
+ if (decision !== null) {
248
+ if (decision.changed) {
249
+ agent.model.select({
250
+ provider: decision.provider,
251
+ model: decision.model,
252
+ ...(decision.reasoningEffort === undefined ? {} : { reasoningEffort: decision.reasoningEffort }),
253
+ })
254
+ }
255
+ lastPoolMove = { sessionId, from: current.provider, to: decision.provider, reason: decision.reason, changed: decision.changed, step, at: Date.now() }
256
+ }
257
+ } catch { /* never break a step */ }
258
+ return next()
259
+ })
260
+ // Keep a fresh snapshot for the pre-step hook without awaiting inside it.
261
+ ctx.effect(() => {
262
+ const refresh = () => {
263
+ void reader.snapshot(false, 'zh').then((snap) => { poolSnapshot = snap && Array.isArray(snap.keys) ? snap : null }).catch(() => {})
264
+ }
265
+ refresh()
266
+ const timer = setInterval(refresh, 60_000)
267
+ return () => clearInterval(timer)
268
+ }, 'dsh-ustc-quota: pool snapshot cache')
167
269
  // New conversations inherit the agent default model, so that default is the only lever
168
270
  // the pool has over a conversation's FIRST call. Keep it on the least loaded key.
169
271
  let lastRotation = null
@@ -202,20 +304,20 @@ export function apply(ctx, config) {
202
304
  ctx.effect(() => ctx.webServer.register({
203
305
  kind: 'exact',
204
306
  path: POOL_ROWS_PATH,
205
- handler: (request, response) => {
307
+ handler: guarded((request, response) => {
206
308
  const body = JSON.stringify({ ok: true, rows: poolRowResults, configured: ownKeys().length, rotation: lastRotation })
207
309
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
208
310
  response.end(body)
209
- },
311
+ }, ['GET']),
210
312
  }), 'dsh-ustc-quota: pool rows')
211
313
  ctx.effect(() => ctx.webServer.register({
212
314
  kind: 'exact',
213
315
  path: '/plugins/dsh-ustc-quota/pool/last',
214
- handler: (request, response) => {
215
- const body = JSON.stringify({ ok: true, last: lastCall })
316
+ handler: guarded((request, response) => {
317
+ const body = JSON.stringify({ ok: true, last: lastCall, move: lastPoolMove })
216
318
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
217
319
  response.end(body)
218
- },
320
+ }, ['GET']),
219
321
  }), 'dsh-ustc-quota: pool last call')
220
322
  // Migrate conversations that still point at the retired edge provider onto a real key.
221
323
  // This must run BEFORE that provider row is withdrawn, otherwise their next turn has no
@@ -252,7 +354,7 @@ export function apply(ctx, config) {
252
354
  ctx.effect(() => ctx.webServer.register({
253
355
  kind: 'exact',
254
356
  path: '/plugins/dsh-ustc-quota/pool/sessions',
255
- handler: (request, response) => {
357
+ handler: guarded((request, response) => {
256
358
  void (async () => {
257
359
  const controller = ctx.get('sessionController')
258
360
  if (!controller || typeof controller.list !== 'function') {
@@ -286,12 +388,12 @@ export function apply(ctx, config) {
286
388
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
287
389
  response.end(body)
288
390
  })()
289
- },
391
+ }, ['GET']),
290
392
  }), 'dsh-ustc-quota: pool sessions')
291
393
  ctx.effect(() => ctx.webServer.register({
292
394
  kind: 'exact',
293
395
  path: '/plugins/dsh-ustc-quota/pool/migrate',
294
- handler: (request, response) => {
396
+ handler: guarded((request, response) => {
295
397
  void (async () => {
296
398
  const controller = ctx.get('sessionController')
297
399
  const migrated = []
@@ -334,14 +436,14 @@ export function apply(ctx, config) {
334
436
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
335
437
  response.end(body)
336
438
  })()
337
- },
439
+ }, ['POST']),
338
440
  }), 'dsh-ustc-quota: pool migrate')
339
441
  // Headless end-to-end probe: create a throwaway conversation and run one real turn, so the
340
442
  // pool can be verified without driving the UI.
341
443
  ctx.effect(() => ctx.webServer.register({
342
444
  kind: 'exact',
343
445
  path: '/plugins/dsh-ustc-quota/pool/probe',
344
- handler: (request, response) => {
446
+ handler: guarded((request, response) => {
345
447
  void (async () => {
346
448
  const result = { ok: false }
347
449
  try {
@@ -349,7 +451,7 @@ export function apply(ctx, config) {
349
451
  if (!controller || typeof controller.create !== 'function' || typeof controller.prompt !== 'function') {
350
452
  throw new Error('no-session-controller')
351
453
  }
352
- const created = await controller.create({ cwd: 'D:\\valentines\\workspace' })
454
+ const created = await controller.create({})
353
455
  const sessionId = created && created.sessionId ? created.sessionId : null
354
456
  if (sessionId === null) throw new Error('create-returned-no-session')
355
457
  result.sessionId = sessionId
@@ -367,27 +469,27 @@ export function apply(ctx, config) {
367
469
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
368
470
  response.end(JSON.stringify(result))
369
471
  })()
370
- },
472
+ }, ['POST']),
371
473
  }), 'dsh-ustc-quota: pool probe')
372
474
  // Final retirement of the standalone pool plugin. Sessions must be migrated first; this
373
475
  // only strips the references and parks the old package under backups/.
374
476
  ctx.effect(() => ctx.webServer.register({
375
477
  kind: 'exact',
376
478
  path: '/plugins/dsh-ustc-quota/pool/retire-legacy',
377
- handler: (request, response) => {
479
+ handler: guarded((request, response) => {
378
480
  void (async () => {
379
481
  const profile = findProfile()
380
482
  const result = profile === null ? { profile: null, reason: 'profile-not-found' } : retireManager(profile)
381
483
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
382
484
  response.end(JSON.stringify({ ok: profile !== null, ...result }))
383
485
  })()
384
- },
486
+ }, ['POST']),
385
487
  }), 'dsh-ustc-quota: retire legacy pool')
386
488
  // One-shot clean-up of rows the pool no longer owns (renamed keys, the retired edge pool).
387
489
  ctx.effect(() => ctx.webServer.register({
388
490
  kind: 'exact',
389
491
  path: '/plugins/dsh-ustc-quota/pool/cleanup',
390
- handler: (request, response) => {
492
+ handler: guarded((request, response) => {
391
493
  void (async () => {
392
494
  const keep = new Set(ownKeys().map((key) => 'ustc-' + String(key.id)))
393
495
  const editor = ctx.get('configEditor')
@@ -398,8 +500,12 @@ export function apply(ctx, config) {
398
500
  if (!row || !row.entry || !row.entry.options || row.entry.options.name !== '@deepseek-ai/dsh-llm-pi-ai') continue
399
501
  const providers = row.entry.options.config && row.entry.options.config.providers
400
502
  if (!providers || typeof providers !== 'object') continue
401
- for (const providerId of Object.keys(providers)) {
503
+ for (const [providerId, definition] of Object.entries(providers)) {
402
504
  if (!providerId.startsWith('ustc-') || keep.has(providerId)) continue
505
+ // Only rows the pool itself wrote may be removed; a user-declared ustc-<name>
506
+ // row is theirs, and deleting it would break their own conversations.
507
+ const ref = definition && typeof definition.apiKeyEnv === 'string' ? definition.apiKeyEnv : ''
508
+ if (!ref.startsWith('USTC_POOL_')) { removed.push({ providerId, ok: false, reason: 'not-pool-owned' }); continue }
403
509
  const result = await removeProviderRow(ctx, providerId)
404
510
  removed.push({ providerId, ...result })
405
511
  }
@@ -408,19 +514,19 @@ export function apply(ctx, config) {
408
514
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
409
515
  response.end(body)
410
516
  })()
411
- },
517
+ }, ['POST']),
412
518
  }), 'dsh-ustc-quota: pool cleanup')
413
519
  ctx.effect(() => ctx.webServer.register({
414
520
  kind: 'exact',
415
521
  path: '/plugins/dsh-ustc-quota/pool/rotate',
416
- handler: (request, response) => {
522
+ handler: guarded((request, response) => {
417
523
  void (async () => {
418
524
  await rotateDefault()
419
525
  const body = JSON.stringify({ ok: true, rotation: lastRotation })
420
526
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
421
527
  response.end(body)
422
528
  })()
423
- },
529
+ }, ['POST']),
424
530
  }), 'dsh-ustc-quota: pool rotate')
425
531
  // Compatibility bridge: conversations created while the retired edge pool was the default
426
532
  // still select "ustc-lb". Until they are migrated, that id must resolve to a working row,
@@ -428,7 +534,7 @@ export function apply(ctx, config) {
428
534
  ctx.effect(() => ctx.webServer.register({
429
535
  kind: 'exact',
430
536
  path: '/plugins/dsh-ustc-quota/pool/compat',
431
- handler: (request, response) => {
537
+ handler: guarded((request, response) => {
432
538
  void (async () => {
433
539
  const keys = keysFromConfig({ keys: ownKeys() })
434
540
  const key = keys[0]
@@ -440,7 +546,7 @@ export function apply(ctx, config) {
440
546
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
441
547
  response.end(body)
442
548
  })()
443
- },
549
+ }, ['POST']),
444
550
  }), 'dsh-ustc-quota: legacy row bridge')
445
551
  const updateTokens = new Map();
446
552
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ustc-quota",
3
- "version": "2.0.1",
3
+ "version": "2.0.4",
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).",
package/pool-config.js CHANGED
@@ -91,7 +91,7 @@ export function desiredProviderRow(existing, action) {
91
91
  return { remove: false, skip: 'provider-route-owned-by-user', row: null }
92
92
  }
93
93
  const base = existing && typeof existing === 'object' ? existing : {}
94
- const EFFORTS = { low: 'low', medium: 'medium', high: 'high' }
94
+ const EFFORTS = { off: 'none', low: 'low', high: 'high', max: 'max' }
95
95
  // Existing rows are kept, but the pool's own catalogue is merged in: a row written by an
96
96
  // older pool version advertises model ids the current default may no longer resolve, and a
97
97
  // provider that cannot resolve the conversation's model fails the call outright.
package/retire.js CHANGED
@@ -33,6 +33,16 @@ export function stripManifest(text) {
33
33
  profile.dependencies = next
34
34
  changed = true
35
35
  }
36
+ // Real profiles declare the plugin in the top-level dependency map, not inside the profile
37
+ // block; leaving it there lets a later install pull the retired package back.
38
+ for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {
39
+ const map = parsed[field]
40
+ if (!map || typeof map !== 'object' || map[MANAGER_PACKAGE] === undefined) continue
41
+ const next = Object.assign({}, map)
42
+ delete next[MANAGER_PACKAGE]
43
+ parsed[field] = next
44
+ changed = true
45
+ }
36
46
  return changed ? JSON.stringify(parsed, null, 2) + '\n' : null
37
47
  }
38
48