dsh-ustc-quota 2.0.2 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -55,7 +55,7 @@ window.__ModuleLoader__.load({
55
55
  return 0;
56
56
  }
57
57
  }
58
- const CLIENT_VERSION = '2.0.2';
58
+ const CLIENT_VERSION = '2.0.5';
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
@@ -39,11 +39,29 @@ let poolLastCall = null
39
39
  * Returns the selection to apply, or null when the agent must stay where it is. Only pool
40
40
  * providers are managed: a conversation the user pointed at a non-pool provider is left alone.
41
41
  */
42
- export function nextSelectionFor(current, keys, sessionId) {
42
+ export function nextSelectionFor(current, keys, sessionId, options = {}) {
43
43
  if (current === null || typeof current !== 'object') return null
44
- if (typeof current.provider !== 'string' || !current.provider.startsWith('ustc-')) return null
45
- const pick = pickPoolKey(keys, sessionId)
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)
46
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
+ }
47
65
  if (pick.provider === current.provider) return { provider: current.provider, model: current.model, reasoningEffort: current.reasoningEffort, changed: false, reason: pick.reason }
48
66
  return {
49
67
  provider: pick.provider,
@@ -54,10 +72,22 @@ export function nextSelectionFor(current, keys, sessionId) {
54
72
  }
55
73
  }
56
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
+
57
81
  /** Pick the key for one model call: sticky first, then the least-loaded healthy one. */
58
- 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))
59
89
  const all = (Array.isArray(keys) ? keys : []).filter((entry) =>
60
- entry && typeof entry.provider === 'string' && entry.provider.startsWith('ustc-') && entry.blocked !== true)
90
+ entry && owned(entry.provider) && entry.blocked !== true && entry.ok !== false)
61
91
  if (all.length === 0) return null
62
92
  // A key with no quota data is not "empty": treating an unmeasured key as 0% load moves
63
93
  // traffic onto a key nobody has verified. Measured keys win; unmeasured ones are the
@@ -77,7 +107,7 @@ export function pickPoolKey(keys, sessionId) {
77
107
  // Keep the conversation on its key until the wall is near: cache affinity matters more
78
108
  // than spreading perfectly.
79
109
  const heldWorst = held === undefined ? null : worstOf(held)
80
- 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' }
81
111
  }
82
112
  let best = entries[0]
83
113
  for (const entry of entries) {
@@ -133,7 +163,7 @@ function rejectGuard(response, reason) {
133
163
  const UPDATE_PATH = '/plugins/dsh-ustc-quota/update';
134
164
  const UPDATE_APPLY_PATH = '/plugins/dsh-ustc-quota/update/apply';
135
165
  const UPDATE_TOKEN_TTL_MS = 30 * 60 * 1000;
136
- const PLUGIN_VERSION = '2.0.2';
166
+ const PLUGIN_VERSION = '2.0.5';
137
167
  const KEY_INFO_PATH = 'key/info';
138
168
  const USER_INFO_PATH = 'user/info';
139
169
  const DISCOVERY_TTL_MS = 10_000;
@@ -147,6 +177,7 @@ export const inject = ['webServer'];
147
177
 
148
178
  export function apply(ctx, config) {
149
179
  const settings = normalizeConfig(config);
180
+ const poolProviders = () => new Set(keysFromConfig({ keys: ownKeys() }).map((key) => 'ustc-' + key.id))
150
181
  const ownKeys = () => {
151
182
  const stored = readStoredKeys()
152
183
  if (Array.isArray(stored) && stored.length > 0) return stored
@@ -159,7 +190,24 @@ export function apply(ctx, config) {
159
190
  // provider and a conversation can simply select it.
160
191
  const poolRowResults = []
161
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
+
162
205
  let lastPoolMove = null
206
+ const poolMoves = []
207
+ const noteMove = (record) => {
208
+ poolMoves.unshift(record)
209
+ while (poolMoves.length > 40) poolMoves.pop()
210
+ }
163
211
  // Observation only: the waterfall hands us the frozen options and the next() chain, so we
164
212
  // record and pass through. Rewriting here is impossible (the host's fallback keeps the
165
213
  // original options), which is why selection happens through selectModel instead.
@@ -198,7 +246,9 @@ export function apply(ctx, config) {
198
246
  try {
199
247
  const current = agent && agent.model && typeof agent.model.current === 'function' ? agent.model.current() : null
200
248
  const sessionId = agent && agent.session && typeof agent.session.id === 'string' ? agent.session.id : null
201
- const decision = nextSelectionFor(current, poolSnapshot === null ? [] : poolSnapshot.keys, sessionId)
249
+ const allowed = poolProviders()
250
+ const depth = agent && agent.options && Number.isFinite(agent.options.subagentDepth) ? agent.options.subagentDepth : 0
251
+ const decision = nextSelectionFor(current, poolSnapshot === null ? [] : poolSnapshot.keys, sessionId, { allowed, delegated: depth > 0 })
202
252
  if (decision !== null) {
203
253
  if (decision.changed) {
204
254
  agent.model.select({
@@ -207,7 +257,8 @@ export function apply(ctx, config) {
207
257
  ...(decision.reasoningEffort === undefined ? {} : { reasoningEffort: decision.reasoningEffort }),
208
258
  })
209
259
  }
210
- lastPoolMove = { sessionId, from: current.provider, to: decision.provider, reason: decision.reason, changed: decision.changed, step, at: Date.now() }
260
+ lastPoolMove = { sessionId, from: current.provider, to: decision.provider, reason: decision.reason, changed: decision.changed, delegated: depth > 0, depth, step, at: Date.now() }
261
+ noteMove(lastPoolMove)
211
262
  }
212
263
  } catch { /* never break a step */ }
213
264
  return next()
@@ -259,20 +310,20 @@ export function apply(ctx, config) {
259
310
  ctx.effect(() => ctx.webServer.register({
260
311
  kind: 'exact',
261
312
  path: POOL_ROWS_PATH,
262
- handler: (request, response) => {
313
+ handler: guarded((request, response) => {
263
314
  const body = JSON.stringify({ ok: true, rows: poolRowResults, configured: ownKeys().length, rotation: lastRotation })
264
315
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
265
316
  response.end(body)
266
- },
317
+ }, ['GET']),
267
318
  }), 'dsh-ustc-quota: pool rows')
268
319
  ctx.effect(() => ctx.webServer.register({
269
320
  kind: 'exact',
270
321
  path: '/plugins/dsh-ustc-quota/pool/last',
271
- handler: (request, response) => {
272
- const body = JSON.stringify({ ok: true, last: lastCall, move: lastPoolMove })
322
+ handler: guarded((request, response) => {
323
+ const body = JSON.stringify({ ok: true, last: lastCall, move: lastPoolMove, moves: poolMoves.slice(0, 25) })
273
324
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
274
325
  response.end(body)
275
- },
326
+ }, ['GET']),
276
327
  }), 'dsh-ustc-quota: pool last call')
277
328
  // Migrate conversations that still point at the retired edge provider onto a real key.
278
329
  // This must run BEFORE that provider row is withdrawn, otherwise their next turn has no
@@ -309,7 +360,7 @@ export function apply(ctx, config) {
309
360
  ctx.effect(() => ctx.webServer.register({
310
361
  kind: 'exact',
311
362
  path: '/plugins/dsh-ustc-quota/pool/sessions',
312
- handler: (request, response) => {
363
+ handler: guarded((request, response) => {
313
364
  void (async () => {
314
365
  const controller = ctx.get('sessionController')
315
366
  if (!controller || typeof controller.list !== 'function') {
@@ -343,12 +394,12 @@ export function apply(ctx, config) {
343
394
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
344
395
  response.end(body)
345
396
  })()
346
- },
397
+ }, ['GET']),
347
398
  }), 'dsh-ustc-quota: pool sessions')
348
399
  ctx.effect(() => ctx.webServer.register({
349
400
  kind: 'exact',
350
401
  path: '/plugins/dsh-ustc-quota/pool/migrate',
351
- handler: (request, response) => {
402
+ handler: guarded((request, response) => {
352
403
  void (async () => {
353
404
  const controller = ctx.get('sessionController')
354
405
  const migrated = []
@@ -391,14 +442,14 @@ export function apply(ctx, config) {
391
442
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
392
443
  response.end(body)
393
444
  })()
394
- },
445
+ }, ['POST']),
395
446
  }), 'dsh-ustc-quota: pool migrate')
396
447
  // Headless end-to-end probe: create a throwaway conversation and run one real turn, so the
397
448
  // pool can be verified without driving the UI.
398
449
  ctx.effect(() => ctx.webServer.register({
399
450
  kind: 'exact',
400
451
  path: '/plugins/dsh-ustc-quota/pool/probe',
401
- handler: (request, response) => {
452
+ handler: guarded((request, response) => {
402
453
  void (async () => {
403
454
  const result = { ok: false }
404
455
  try {
@@ -406,7 +457,12 @@ export function apply(ctx, config) {
406
457
  if (!controller || typeof controller.create !== 'function' || typeof controller.prompt !== 'function') {
407
458
  throw new Error('no-session-controller')
408
459
  }
409
- const created = await controller.create({ cwd: 'D:\\valentines\\workspace' })
460
+ // Callers may supply their own probe prompt (base64, because HTTP headers are
461
+ // latin1): that is how a delegation can be triggered without driving the UI.
462
+ const probeText = typeof request.headers['x-probe-b64'] === 'string' && request.headers['x-probe-b64'] !== ''
463
+ ? Buffer.from(request.headers['x-probe-b64'], 'base64').toString('utf8')
464
+ : '自动验收:请只回复 OK'
465
+ const created = await controller.create({})
410
466
  const sessionId = created && created.sessionId ? created.sessionId : null
411
467
  if (sessionId === null) throw new Error('create-returned-no-session')
412
468
  result.sessionId = sessionId
@@ -414,7 +470,7 @@ export function apply(ctx, config) {
414
470
  requestId: 'lb-probe-' + Date.now(),
415
471
  sessionId,
416
472
  mode: 'queue',
417
- content: [{ type: 'text', text: '自动验收:请只回复 OK' }],
473
+ content: [{ type: 'text', text: probeText }],
418
474
  }, new AbortController().signal)
419
475
  result.accepted = accepted !== null && accepted !== undefined
420
476
  result.ok = true
@@ -424,27 +480,27 @@ export function apply(ctx, config) {
424
480
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
425
481
  response.end(JSON.stringify(result))
426
482
  })()
427
- },
483
+ }, ['POST']),
428
484
  }), 'dsh-ustc-quota: pool probe')
429
485
  // Final retirement of the standalone pool plugin. Sessions must be migrated first; this
430
486
  // only strips the references and parks the old package under backups/.
431
487
  ctx.effect(() => ctx.webServer.register({
432
488
  kind: 'exact',
433
489
  path: '/plugins/dsh-ustc-quota/pool/retire-legacy',
434
- handler: (request, response) => {
490
+ handler: guarded((request, response) => {
435
491
  void (async () => {
436
492
  const profile = findProfile()
437
493
  const result = profile === null ? { profile: null, reason: 'profile-not-found' } : retireManager(profile)
438
494
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
439
495
  response.end(JSON.stringify({ ok: profile !== null, ...result }))
440
496
  })()
441
- },
497
+ }, ['POST']),
442
498
  }), 'dsh-ustc-quota: retire legacy pool')
443
499
  // One-shot clean-up of rows the pool no longer owns (renamed keys, the retired edge pool).
444
500
  ctx.effect(() => ctx.webServer.register({
445
501
  kind: 'exact',
446
502
  path: '/plugins/dsh-ustc-quota/pool/cleanup',
447
- handler: (request, response) => {
503
+ handler: guarded((request, response) => {
448
504
  void (async () => {
449
505
  const keep = new Set(ownKeys().map((key) => 'ustc-' + String(key.id)))
450
506
  const editor = ctx.get('configEditor')
@@ -455,8 +511,12 @@ export function apply(ctx, config) {
455
511
  if (!row || !row.entry || !row.entry.options || row.entry.options.name !== '@deepseek-ai/dsh-llm-pi-ai') continue
456
512
  const providers = row.entry.options.config && row.entry.options.config.providers
457
513
  if (!providers || typeof providers !== 'object') continue
458
- for (const providerId of Object.keys(providers)) {
514
+ for (const [providerId, definition] of Object.entries(providers)) {
459
515
  if (!providerId.startsWith('ustc-') || keep.has(providerId)) continue
516
+ // Only rows the pool itself wrote may be removed; a user-declared ustc-<name>
517
+ // row is theirs, and deleting it would break their own conversations.
518
+ const ref = definition && typeof definition.apiKeyEnv === 'string' ? definition.apiKeyEnv : ''
519
+ if (!ref.startsWith('USTC_POOL_')) { removed.push({ providerId, ok: false, reason: 'not-pool-owned' }); continue }
460
520
  const result = await removeProviderRow(ctx, providerId)
461
521
  removed.push({ providerId, ...result })
462
522
  }
@@ -465,19 +525,19 @@ export function apply(ctx, config) {
465
525
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
466
526
  response.end(body)
467
527
  })()
468
- },
528
+ }, ['POST']),
469
529
  }), 'dsh-ustc-quota: pool cleanup')
470
530
  ctx.effect(() => ctx.webServer.register({
471
531
  kind: 'exact',
472
532
  path: '/plugins/dsh-ustc-quota/pool/rotate',
473
- handler: (request, response) => {
533
+ handler: guarded((request, response) => {
474
534
  void (async () => {
475
535
  await rotateDefault()
476
536
  const body = JSON.stringify({ ok: true, rotation: lastRotation })
477
537
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
478
538
  response.end(body)
479
539
  })()
480
- },
540
+ }, ['POST']),
481
541
  }), 'dsh-ustc-quota: pool rotate')
482
542
  // Compatibility bridge: conversations created while the retired edge pool was the default
483
543
  // still select "ustc-lb". Until they are migrated, that id must resolve to a working row,
@@ -485,7 +545,7 @@ export function apply(ctx, config) {
485
545
  ctx.effect(() => ctx.webServer.register({
486
546
  kind: 'exact',
487
547
  path: '/plugins/dsh-ustc-quota/pool/compat',
488
- handler: (request, response) => {
548
+ handler: guarded((request, response) => {
489
549
  void (async () => {
490
550
  const keys = keysFromConfig({ keys: ownKeys() })
491
551
  const key = keys[0]
@@ -497,7 +557,7 @@ export function apply(ctx, config) {
497
557
  response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
498
558
  response.end(body)
499
559
  })()
500
- },
560
+ }, ['POST']),
501
561
  }), 'dsh-ustc-quota: legacy row bridge')
502
562
  const updateTokens = new Map();
503
563
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ustc-quota",
3
- "version": "2.0.2",
3
+ "version": "2.0.5",
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