dsh-injection-manager 1.10.4 → 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.
Files changed (49) hide show
  1. package/CHANGELOG.md +290 -0
  2. package/CONTRIBUTING.md +2 -2
  3. package/README.md +286 -94
  4. package/README.zh.md +238 -97
  5. package/client.js +3325 -295
  6. package/docs/ARCHITECTURE.md +123 -25
  7. package/docs/COMPATIBILITY.md +31 -7
  8. package/docs/DETAIL.md +148 -0
  9. package/docs/DETAIL.zh.md +105 -1
  10. package/docs/FAQ.md +53 -7
  11. package/docs/PERFORMANCE.md +60 -6
  12. package/docs/images/demo.gif +0 -0
  13. package/docs/images/dock.png +0 -0
  14. package/docs/images/panel-dark.png +0 -0
  15. package/docs/images/panel-drawer.png +0 -0
  16. package/docs/images/panel-insights.png +0 -0
  17. package/docs/images/panel-manage-expanded.png +0 -0
  18. package/docs/images/panel-manage.png +0 -0
  19. package/docs/images/panel-settings.png +0 -0
  20. package/docs/images/panel-sidebar.png +0 -0
  21. package/docs/preview.svg +177 -23
  22. package/icon.svg +19 -5
  23. package/index.js +107 -16
  24. package/lib/actions.js +12 -4
  25. package/lib/apply.js +14 -2
  26. package/lib/compaction.js +126 -0
  27. package/lib/content.js +360 -0
  28. package/lib/events.js +216 -0
  29. package/lib/health.js +210 -0
  30. package/lib/pressure.js +146 -0
  31. package/lib/routes.js +355 -9
  32. package/lib/snapshot.js +256 -29
  33. package/lib/stats.js +394 -0
  34. package/lib/text.js +160 -0
  35. package/lib/trend.js +168 -0
  36. package/locale/de.json +251 -6
  37. package/locale/en.json +251 -6
  38. package/locale/es.json +251 -6
  39. package/locale/fr.json +251 -6
  40. package/locale/ja.json +251 -6
  41. package/locale/pt.json +251 -6
  42. package/locale/ru.json +252 -7
  43. package/locale/zh.json +249 -4
  44. package/package.json +16 -3
  45. package/screenshots.json +7 -5
  46. package/docs/images/panel-about.png +0 -0
  47. package/docs/images/panel-budget.png +0 -0
  48. package/docs/images/panel-policy.png +0 -0
  49. package/docs/images/panel-suites.png +0 -0
package/lib/routes.js CHANGED
@@ -8,17 +8,31 @@ import { readFile } from 'node:fs/promises'
8
8
  import { dirname, join } from 'node:path'
9
9
  import { fileURLToPath } from 'node:url'
10
10
  import { applyPolicyForAgent, rewriteStats, savePolicy } from './apply.js'
11
+ import { collectContent } from './content.js'
12
+ import { buildHealth } from './health.js'
11
13
  import { pushUndo, undoState } from './history.js'
12
14
  import { restorePolicyAt, undoLastPolicy } from './actions.js'
13
15
  import { hostInfo } from './hostinfo.js'
14
16
  import { CHANNELS, defaultPolicy, isExcluded, normalizePolicy, policyFilePath, readPolicy } from './policy.js'
15
17
  import { PRESET_NAMES, presetPolicy } from './presets.js'
16
- import { buildSnapshot, planBudget, policyFromPlan, appliedAgents, lastApplicationState } from './snapshot.js'
18
+ import {
19
+ buildSnapshot,
20
+ estimateItemTokens,
21
+ appliedAgents,
22
+ lastApplicationState,
23
+ planBudget,
24
+ policyFromPlan,
25
+ } from './snapshot.js'
17
26
  import { getSettings } from './settings.js'
27
+ import { backfillState, readStats, requestBackfill } from './stats.js'
28
+ import { readEvents } from './events.js'
29
+ import { readTrend, TREND_RANGES, TREND_LIMIT } from './trend.js'
18
30
  import { renderCard, renderText } from './text.js'
19
31
 
20
32
  const PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)))
21
33
  export const ROUTE_PREFIX = '/plugins/dsh-injection-manager'
34
+ // Bumped when the HTTP contract gains fields the panel can feature-detect.
35
+ export const API_VERSION = 2
22
36
 
23
37
  export const ROUTES = {
24
38
  ping: `${ROUTE_PREFIX}/ping`,
@@ -31,6 +45,11 @@ export const ROUTES = {
31
45
  verify: `${ROUTE_PREFIX}/verify`,
32
46
  registrations: `${ROUTE_PREFIX}/registrations`,
33
47
  boot: `${ROUTE_PREFIX}/boot`,
48
+ stats: `${ROUTE_PREFIX}/stats`,
49
+ content: `${ROUTE_PREFIX}/content`,
50
+ trend: `${ROUTE_PREFIX}/trend`,
51
+ events: `${ROUTE_PREFIX}/events`,
52
+ health: `${ROUTE_PREFIX}/health`,
34
53
  }
35
54
 
36
55
  // In-memory diagnostics written by the browser half. Never persisted.
@@ -45,6 +64,68 @@ function harden(res) {
45
64
  res.setHeader('x-frame-options', 'DENY')
46
65
  }
47
66
 
67
+ // ---------------------------------------------------------------- trust fence
68
+
69
+ /**
70
+ * Resolve the host's `connection` service without making it a hard dependency.
71
+ * DSH 0.2.2+ exposes `ctx.connection`; older hosts do not, and the plugin must
72
+ * keep working there. `ctx.get()` is the public service accessor; the property
73
+ * read covers contexts where the service is exposed directly.
74
+ */
75
+ export function connectionOf(ctx) {
76
+ try {
77
+ const viaGet = typeof ctx?.get === 'function' ? ctx.get('connection') : undefined
78
+ if (viaGet !== undefined && viaGet !== null) return viaGet
79
+ } catch {
80
+ /* fall through to the property read */
81
+ }
82
+ try {
83
+ return Reflect.get(ctx, 'connection')
84
+ } catch {
85
+ return undefined
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Apply the host's Host/Origin (and browser-auth) fence to one registered
91
+ * route. Returns true when the request was answered with a 401/403 and the
92
+ * handler must not run; false when the caller may proceed.
93
+ *
94
+ * A missing service, a missing method and thrown errors all mean "proceed": a
95
+ * security fence must never turn the panel into a blank page on an older host
96
+ * or during early boot. The rejection is answered by the fence itself, before
97
+ * any route logic runs, so no JSON, file or policy data can leak.
98
+ */
99
+ export function fenceRequest(ctx, req, res) {
100
+ let rejection
101
+ try {
102
+ const connection = connectionOf(ctx)
103
+ if (connection === undefined || connection === null || typeof connection.requestRejection !== 'function') return false
104
+ rejection = connection.requestRejection(req)
105
+ } catch {
106
+ return false
107
+ }
108
+ if (rejection !== 401 && rejection !== 403) return false
109
+ try {
110
+ res.statusCode = rejection
111
+ // A rejected request carries no data and must not be cached or sniffed.
112
+ res.setHeader('cache-control', 'no-store')
113
+ harden(res)
114
+ res.end()
115
+ } catch {
116
+ /* the socket may already be gone; the request was still rejected */
117
+ }
118
+ return true
119
+ }
120
+
121
+ /** Wrap one route handler with the trust fence at registration time. */
122
+ export function makeFencedHandler(ctx, handler) {
123
+ return async function fenced(req, res) {
124
+ if (fenceRequest(ctx, req, res) === true) return undefined
125
+ return handler(req, res)
126
+ }
127
+ }
128
+
48
129
  function respondJson(res, statusCode, payload) {
49
130
  const body = Buffer.from(JSON.stringify(payload), 'utf8')
50
131
  res.statusCode = statusCode
@@ -173,26 +254,51 @@ function toggleItem(policy, channel, name, enabled) {
173
254
  if (!current.names.includes(name)) current.names.push(name)
174
255
  }
175
256
 
257
+ function sessionIdOf(agent) {
258
+ return typeof agent?.id === 'string' && agent.id.length > 0 ? agent.id : undefined
259
+ }
260
+
261
+ /**
262
+ * Name count and token size for a set of switched items. Sizes come from the
263
+ * inventory cache a previous snapshot measured; a name this process never saw
264
+ * still counts but contributes 0 tokens instead of a guessed number.
265
+ */
266
+ function switchNumbers(channel, names) {
267
+ const estimate = estimateItemTokens(channel, names)
268
+ return { count: names.length, tokens: estimate.tokens, known: estimate.known }
269
+ }
270
+
176
271
  async function applyAction(ctx, agent, action) {
272
+ const sessionId = sessionIdOf(agent)
177
273
  const state = await readPolicy()
178
274
  const policy = normalizePolicy(state.policy)
179
275
 
180
276
  if (action?.kind === 'undo') {
181
- return undoLastPolicy()
277
+ return undoLastPolicy({ sessionId, params: { via: 'panel' } })
182
278
  }
183
279
 
184
280
  if (action?.kind === 'restore') {
185
- return restorePolicyAt(Number(action.index))
281
+ return restorePolicyAt(Number(action.index), { sessionId, params: { via: 'panel' } })
186
282
  }
187
283
 
188
284
  // Everything below is a mutation; remember the pre-write policy so the panel
189
285
  // can offer one-click undo for a whole-suite switch.
190
286
  const before = JSON.parse(JSON.stringify(policy))
191
287
  const undoLabel = typeof action.label === 'string' && action.label.trim().length > 0 ? action.label : describeAction(action)
288
+ // The event row for the insights feed. Every mutation below overwrites the
289
+ // kind/params it can describe; savePolicy records it in the same atomic step.
290
+ const event = { kind: 'policy-saved', params: {}, tokensDelta: 0 }
192
291
 
193
292
  switch (action?.kind) {
194
293
  case 'item': {
195
- toggleItem(policy, action.channel, String(action.name ?? ''), action.enabled === true)
294
+ const channel = String(action.channel ?? '')
295
+ const name = String(action.name ?? '')
296
+ const enabled = action.enabled === true
297
+ toggleItem(policy, channel, name, enabled)
298
+ const numbers = switchNumbers(channel, [name])
299
+ event.kind = 'switch'
300
+ event.params = { channel, name, op: enabled ? 'on' : 'off', count: 1, tokens: numbers.tokens }
301
+ event.tokensDelta = enabled ? numbers.tokens : -numbers.tokens
196
302
  policy.preset = 'custom'
197
303
  break
198
304
  }
@@ -212,12 +318,18 @@ async function applyAction(ctx, agent, action) {
212
318
  rule.names = rule.mode === 'except' ? rule.names.filter((name) => !wanted.has(name)) : [...new Set(rule.names.concat(names))]
213
319
  }
214
320
  if (rule.mode === 'except' && rule.names.length === 0) rule.mode = 'all'
321
+ const numbers = switchNumbers(channel, names)
322
+ event.kind = 'switch'
323
+ event.params = { channel, op: action.enabled === false ? 'off' : 'on', count: numbers.count, tokens: numbers.tokens, suite: true }
324
+ event.tokensDelta = action.enabled === false ? -numbers.tokens : numbers.tokens
215
325
  policy.preset = 'custom'
216
326
  break
217
327
  }
218
328
  case 'channel': {
219
329
  if (!CHANNELS.includes(action.channel)) throw new Error(`unknown channel: ${action.channel}`)
220
330
  policy[action.channel] = action.enabled === true ? { mode: 'all', names: [] } : { mode: 'only', names: [] }
331
+ event.kind = 'switch'
332
+ event.params = { channel: String(action.channel), op: action.enabled === true ? 'on' : 'off', scope: 'channel' }
221
333
  policy.preset = 'custom'
222
334
  break
223
335
  }
@@ -236,6 +348,8 @@ async function applyAction(ctx, agent, action) {
236
348
  next.prompt = policy.prompt
237
349
  next.budget = policy.budget
238
350
  Object.assign(policy, next)
351
+ event.kind = 'preset'
352
+ event.params = { name, via: 'panel' }
239
353
  break
240
354
  }
241
355
  case 'group': {
@@ -243,10 +357,50 @@ async function applyAction(ctx, agent, action) {
243
357
  const group = String(action.group ?? '')
244
358
  if (!CHANNELS.includes(channel)) throw new Error(`unknown channel: ${channel}`)
245
359
  const snapshot = await buildSnapshot(ctx, agent, 'action', undefined)
246
- const names = snapshot.items
247
- .filter((item) => item.channel === channel && item.group === group && !item.locked)
248
- .map((item) => item.name)
360
+ const rows = snapshot.items.filter((item) => item.channel === channel && item.group === group && !item.locked)
361
+ const names = rows.map((item) => item.name)
249
362
  for (const name of names) toggleItem(policy, channel, name, action.enabled === true)
363
+ const tokens = rows.reduce((sum, item) => sum + item.tokens, 0)
364
+ event.kind = 'switch'
365
+ event.params = {
366
+ channel,
367
+ group: rows[0]?.groupLabel ?? group,
368
+ groupId: group,
369
+ op: action.enabled === true ? 'on' : 'off',
370
+ count: names.length,
371
+ tokens,
372
+ }
373
+ event.tokensDelta = action.enabled === true ? tokens : -tokens
374
+ policy.preset = 'custom'
375
+ break
376
+ }
377
+ case 'groups': {
378
+ // A suite can span channels (REA's MCP tools plus its prompt section), so
379
+ // one switch has to address several group ids at once.
380
+ const list = Array.isArray(action.groups) ? action.groups : []
381
+ const snapshot = await buildSnapshot(ctx, agent, 'action', undefined)
382
+ const labels = []
383
+ let count = 0
384
+ let tokens = 0
385
+ for (const entry of list) {
386
+ const channel = String(entry.channel ?? '')
387
+ const group = String(entry.group ?? '')
388
+ if (!CHANNELS.includes(channel)) continue
389
+ const rows = snapshot.items.filter((item) => item.channel === channel && item.group === group && !item.locked)
390
+ const names = rows.map((item) => item.name)
391
+ for (const name of names) toggleItem(policy, channel, name, action.enabled === true)
392
+ count += names.length
393
+ tokens += rows.reduce((sum, item) => sum + item.tokens, 0)
394
+ if (rows[0]?.groupLabel !== undefined && !labels.includes(rows[0].groupLabel)) labels.push(rows[0].groupLabel)
395
+ }
396
+ event.kind = 'switch'
397
+ event.params = {
398
+ op: action.enabled === true ? 'on' : 'off',
399
+ count,
400
+ tokens,
401
+ groups: labels,
402
+ }
403
+ event.tokensDelta = action.enabled === true ? tokens : -tokens
250
404
  policy.preset = 'custom'
251
405
  break
252
406
  }
@@ -260,17 +414,28 @@ async function applyAction(ctx, agent, action) {
260
414
  throw new Error('invalid-policy: expected a policy object')
261
415
  }
262
416
  Object.assign(policy, normalizePolicy(candidate))
417
+ event.kind = 'import'
418
+ event.params = { via: 'panel', format: source !== candidate ? 'manifest' : 'policy' }
263
419
  break
264
420
  }
265
421
  case 'prompt': {
266
422
  if (typeof action.prefix === 'string') policy.prompt.prefix = action.prefix
267
423
  if (typeof action.suffix === 'string') policy.prompt.suffix = action.suffix
424
+ event.kind = 'policy-saved'
425
+ event.params = {
426
+ via: 'panel',
427
+ prompt: true,
428
+ prefixChars: policy.prompt.prefix.length,
429
+ suffixChars: policy.prompt.suffix.length,
430
+ }
268
431
  policy.preset = 'custom'
269
432
  break
270
433
  }
271
434
  case 'budget': {
272
435
  const tokens = Number(action.tokens)
273
436
  policy.budget.tokens = Number.isFinite(tokens) && tokens > 0 ? Math.round(tokens) : 0
437
+ event.kind = 'budget'
438
+ event.params = { tokens: policy.budget.tokens, via: 'panel' }
274
439
  break
275
440
  }
276
441
  case 'budget.apply': {
@@ -281,19 +446,24 @@ async function applyAction(ctx, agent, action) {
281
446
  next.prompt = policy.prompt
282
447
  next.budget = { tokens: Math.round(target) }
283
448
  Object.assign(policy, next)
449
+ event.kind = 'budget'
450
+ event.params = { tokens: Math.round(target), dropped: plan.drop.length, saved: plan.savedTokens, via: 'plan' }
451
+ event.tokensDelta = -plan.savedTokens
284
452
  break
285
453
  }
286
454
  case 'reset': {
287
455
  const fresh = defaultPolicy()
288
456
  fresh.prompt = policy.prompt
289
457
  Object.assign(policy, fresh)
458
+ event.kind = 'policy-saved'
459
+ event.params = { via: 'panel', reset: true, preset: 'all' }
290
460
  break
291
461
  }
292
462
  default:
293
463
  throw new Error(`unknown action kind: ${action?.kind}`)
294
464
  }
295
465
 
296
- await savePolicy(policy)
466
+ await savePolicy(policy, { sessionId, ...event })
297
467
  pushUndo(before, undoLabel)
298
468
  return policy
299
469
  }
@@ -303,6 +473,8 @@ function describeAction(action) {
303
473
  switch (kind) {
304
474
  case 'group':
305
475
  return `group ${action.group} ${action.enabled ? 'on' : 'off'}`
476
+ case 'groups':
477
+ return `groups ${(action.groups || []).length} ${action.enabled ? 'on' : 'off'}`
306
478
  case 'item':
307
479
  return `${action.enabled ? 'on' : 'off'} ${action.name}`
308
480
  case 'names':
@@ -341,8 +513,14 @@ export function createRoutes(ctx) {
341
513
  scopeSource = agent === undefined ? 'route.none' : 'route.last-live'
342
514
  }
343
515
  const snapshot = await buildSnapshot(ctx, agent, scopeSource, undefined)
516
+ const health = buildHealth(snapshot)
344
517
  const payload = {
345
518
  ...snapshot,
519
+ ok: true,
520
+ apiVersion: API_VERSION,
521
+ // Counts only: the full check list has its own route, and a summary
522
+ // refresh should stay small.
523
+ healthSummary: { high: health.summary.high, warn: health.summary.warn, info: health.summary.info },
346
524
  text: renderText(snapshot),
347
525
  card: renderCard(snapshot),
348
526
  presets: PRESET_NAMES,
@@ -581,7 +759,175 @@ export function createRoutes(ctx) {
581
759
  }
582
760
  }
583
761
 
584
- return { summary, policy, locale, action, ping, diag, verify, export: exportRoute, boot: report('boot'), registrations: report('registrations') }
762
+ /**
763
+ * History for the 统计 tab. Everything here is what this plugin measured —
764
+ * the file is written by `recordSnapshot()` — so the response states its own
765
+ * coverage rather than claiming to describe conversations it never saw.
766
+ *
767
+ * The read path never replays durable logs: it answers from stats.json (and
768
+ * the session index once a background pass listed it) and asks for one
769
+ * bounded fill in the background. `backfilling:true` tells the panel that the
770
+ * corpus is still being priced; the next poll sees the new rows.
771
+ */
772
+ const stats = async (req, res) => {
773
+ try {
774
+ if (req.method !== 'GET') {
775
+ respondJson(res, 405, { error: 'method-not-allowed' })
776
+ return
777
+ }
778
+ const url = new URL(req.url ?? ROUTES.stats, 'http://localhost')
779
+ const request = url.searchParams.get('backfill') === '0' ? { started: false, running: false } : requestBackfill(ctx)
780
+ const history = await readStats()
781
+ const fill = backfillState()
782
+ respondJson(res, 200, {
783
+ ...history,
784
+ sessions: fill.sessions.slice(0, 60),
785
+ backfill: fill.last,
786
+ backfilling: request.started || request.running || fill.running,
787
+ coverage: { ...history.coverage, known: fill.known },
788
+ generatedAt: Date.now(),
789
+ })
790
+ } catch (error) {
791
+ respondJson(res, 500, { error: 'stats-failed', message: String(error?.message ?? error) })
792
+ }
793
+ }
794
+
795
+ /**
796
+ * Original text behind one snapshot row. This is the only route that opens a
797
+ * file, and it only opens paths that the snapshot collection registered
798
+ * (skill files, instruction files): the request cannot name a path.
799
+ * A 2s abort keeps the panel responsive; the response says `timeout` rather
800
+ * than serving a half-collected item.
801
+ */
802
+ const content = async (req, res) => {
803
+ try {
804
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
805
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
806
+ return
807
+ }
808
+ const url = new URL(req.url ?? ROUTES.content, 'http://localhost')
809
+ const channel = url.searchParams.get('channel') ?? ''
810
+ const id = url.searchParams.get('id') ?? ''
811
+ const picked = pickAgent(ctx, url.searchParams.get('session') ?? undefined)
812
+ let agent = picked.agent
813
+ if (agent === undefined) agent = pickLastLive(ctx)
814
+ const controller = new AbortController()
815
+ // The contract budgets a read at 2s. Race the collection against that
816
+ // budget so a slow assemble can never hold the drawer open; the abort
817
+ // signal additionally stops providers that honour it.
818
+ let timer
819
+ const deadline = new Promise((resolve) => {
820
+ timer = setTimeout(() => {
821
+ controller.abort()
822
+ resolve({ ok: false, status: 504, error: 'timeout', message: 'content collection exceeded the 2s budget' })
823
+ }, 2000)
824
+ })
825
+ let result
826
+ try {
827
+ result = await Promise.race([collectContent(ctx, agent, channel, id, controller.signal), deadline])
828
+ } finally {
829
+ clearTimeout(timer)
830
+ }
831
+ if (result.ok !== true) {
832
+ respondJson(res, result.status ?? 500, {
833
+ ok: false,
834
+ error: result.error ?? 'content-failed',
835
+ ...(result.message === undefined ? {} : { message: result.message }),
836
+ })
837
+ return
838
+ }
839
+ respondJson(res, 200, result)
840
+ } catch (error) {
841
+ respondJson(res, 500, { ok: false, error: 'content-failed', message: String(error?.message ?? error) })
842
+ }
843
+ }
844
+
845
+ /**
846
+ * Cross-session first-turn trend. Same measured rows the stats route reports,
847
+ * plus the bounded durable-log backfill; unknown channel splits stay null.
848
+ */
849
+ const trend = async (req, res) => {
850
+ try {
851
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
852
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
853
+ return
854
+ }
855
+ const url = new URL(req.url ?? ROUTES.trend, 'http://localhost')
856
+ const range = url.searchParams.get('range') ?? 'all'
857
+ if (!TREND_RANGES.includes(range)) {
858
+ respondJson(res, 400, { ok: false, error: 'invalid-range', message: `range must be one of ${TREND_RANGES.join('|')}` })
859
+ return
860
+ }
861
+ const limit = url.searchParams.get('limit') ?? String(TREND_LIMIT)
862
+ const payload = await readTrend(range, limit, ctx)
863
+ respondJson(res, 200, { ok: true, ...payload })
864
+ } catch (error) {
865
+ respondJson(res, 500, { ok: false, error: 'trend-failed', message: String(error?.message ?? error) })
866
+ }
867
+ }
868
+
869
+ /** Injection event feed: what changed, for one session or the whole install. */
870
+ const events = async (req, res) => {
871
+ try {
872
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
873
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
874
+ return
875
+ }
876
+ const url = new URL(req.url ?? ROUTES.events, 'http://localhost')
877
+ let sessionId = url.searchParams.get('session') ?? ''
878
+ if (sessionId.length === 0) {
879
+ const picked = pickAgent(ctx, undefined)
880
+ const agent = picked.agent ?? pickLastLive(ctx)
881
+ sessionId = typeof agent?.id === 'string' ? agent.id : ''
882
+ }
883
+ const limit = url.searchParams.get('limit') ?? '60'
884
+ const payload = await readEvents(sessionId.length > 0 ? sessionId : undefined, limit)
885
+ respondJson(res, 200, { ok: true, ...payload })
886
+ } catch (error) {
887
+ respondJson(res, 500, { ok: false, error: 'events-failed', message: String(error?.message ?? error) })
888
+ }
889
+ }
890
+
891
+ /** Health checks for the current session (the /summary counts come from here). */
892
+ const health = async (req, res) => {
893
+ try {
894
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
895
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
896
+ return
897
+ }
898
+ const url = new URL(req.url ?? ROUTES.health, 'http://localhost')
899
+ const picked = pickAgent(ctx, url.searchParams.get('session') ?? undefined)
900
+ let agent = picked.agent
901
+ let scopeSource = `health.${picked.source}`
902
+ if (agent === undefined) {
903
+ agent = pickLastLive(ctx)
904
+ scopeSource = agent === undefined ? 'health.none' : 'health.last-live'
905
+ }
906
+ const snapshot = await buildSnapshot(ctx, agent, scopeSource, undefined)
907
+ const report = buildHealth(snapshot)
908
+ respondJson(res, 200, { ok: true, summary: report.summary, checks: report.checks })
909
+ } catch (error) {
910
+ respondJson(res, 500, { ok: false, error: 'health-failed', message: String(error?.message ?? error) })
911
+ }
912
+ }
913
+
914
+ return {
915
+ summary,
916
+ policy,
917
+ locale,
918
+ action,
919
+ ping,
920
+ diag,
921
+ verify,
922
+ export: exportRoute,
923
+ stats,
924
+ content,
925
+ trend,
926
+ events,
927
+ health,
928
+ boot: report('boot'),
929
+ registrations: report('registrations'),
930
+ }
585
931
  }
586
932
 
587
933
  const countApplied = () => {