@try-works/dsh-minimal-router 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1107 @@
1
+ // @dsh-local-router/plugin — host evidence adapter and read-only routes.
2
+ //
3
+ // One backend-agnostic Evidence model (packages/domain/src/evidence.ts) is
4
+ // assembled from the in-memory policy runtime, the ledger, and the bounded
5
+ // telemetry cache the route application already maintains. The adapter never
6
+ // calls a backend: the cache is the only telemetry source, so a route request
7
+ // cannot trigger an oMLX read, and the oMLX base URL (`source`) is dropped from
8
+ // the snapshot before it crosses the host boundary.
9
+ //
10
+ // Routes are registered on ctx.webServer (see index.js) as exact, read-only
11
+ // handlers under /api/router/*. The web server owns no authentication, so the
12
+ // handler calls ctx.connection.requestRejection when the Connection service is
13
+ // available; without it the routes are unauthenticated (ROUTE_AUTH_LIMITATION).
14
+
15
+ import { initialPolicy } from "./host.js"
16
+ import { GATES, isPolicy } from "./routing.js"
17
+
18
+ // Run 36 (R-36-01/15, DEC-36-02/15): the scope gate is gone; the order is the
19
+ // four gates and Fallback means the next model in THIS role's configured chain.
20
+ export const GATE_DESCRIPTIONS = {
21
+ residency: "a resident local model is loaded",
22
+ headroom: "memory and concurrency headroom is available",
23
+ floor: "predicted local tps clears the floor",
24
+ fallback: "the next model in this role's chain"
25
+ }
26
+ export const GATE_SOURCES = { residency: "adapter", headroom: "adapter", floor: "derived", fallback: "router" }
27
+ const isoFromValue = (value) => {
28
+ if (value === null || value === undefined) return null
29
+ if (typeof value === "string") return value
30
+ if (value instanceof Date) return value.toISOString()
31
+ return null
32
+ }
33
+
34
+ const medianContextTokens = (rows) => {
35
+ const tokens = rows
36
+ .slice(0, 100)
37
+ .map((row) => (Number.isFinite(row.contextTokens) ? row.contextTokens : 0))
38
+ .sort((a, b) => a - b)
39
+ return tokens.length === 0 ? 0 : tokens[Math.floor(tokens.length / 2)]
40
+ }
41
+
42
+ /** Port of packages/domain/src/policy-rules.ts headroomCeiling (longer context, fewer slots). */
43
+ const headroomCeiling = (contextTokens) => (contextTokens <= 32_000 ? 3 : contextTokens <= 128_000 ? 2 : 1)
44
+
45
+ const CONTEXT_BUCKETS = [
46
+ { label: "≤8k", min: 0, max: 8_192 },
47
+ { label: "≤32k", min: 8_192, max: 32_768 },
48
+ { label: "≤128k", min: 32_768, max: 131_072 },
49
+ { label: "≤256k", min: 131_072, max: 262_144 },
50
+ { label: ">256k", min: 262_144, max: Number.POSITIVE_INFINITY }
51
+ ]
52
+
53
+ /** Exact read-only paths mounted on ctx.webServer. */
54
+ export const EVIDENCE_ROUTES = Object.freeze({
55
+ health: "/api/router/health",
56
+ models: "/api/router/models",
57
+ routing: "/api/router/routing",
58
+ activity: "/api/router/activity",
59
+ engine: "/api/router/engine",
60
+ overview: "/api/router/overview",
61
+ settings: "/api/router/settings"
62
+ })
63
+
64
+ /** The approved five-tab surfaces; Engine is the only writable-config-looking one. */
65
+ export const EVIDENCE_TABS = Object.freeze(["models", "routing", "activity", "engine"])
66
+
67
+ /** Response header naming the authentication source actually used per route. */
68
+ export const AUTH_HEADER = "x-router-auth"
69
+
70
+ export const ROUTE_AUTH_LIMITATION =
71
+ "ctx.webServer registers no authentication: the handler applies ctx.connection.requestRejection when Connection is available, otherwise the exact /api/router/* routes are unauthenticated"
72
+
73
+ export const defaultCacheMaxAgeMs = 10_000
74
+
75
+ const TELEMETRY_ERROR_KINDS = ["http", "network", "timeout", "parse", "validation"]
76
+
77
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
78
+
79
+ const finiteNumber = (value, fallback) =>
80
+ typeof value === "number" && Number.isFinite(value) ? value : fallback
81
+
82
+ const numberOrNull = (value) =>
83
+ typeof value === "number" && Number.isFinite(value) ? value : null
84
+
85
+ const stringOrNull = (value) => (typeof value === "string" ? value : null)
86
+
87
+ const isoOrNull = (value) => {
88
+ const ms = finiteNumber(value, null)
89
+ return ms === null ? null : new Date(ms).toISOString()
90
+ }
91
+
92
+ const normalizeRemoteModels = (value) => {
93
+ const list = Array.isArray(value) ? value : []
94
+ return list
95
+ .filter((entry) => isRecord(entry) && typeof entry.provider === "string" && typeof entry.model === "string")
96
+ .map((entry) => ({
97
+ provider: entry.provider,
98
+ model: entry.model,
99
+ role: entry.role === "advisory" ? "advisory" : "main",
100
+ ...(typeof entry.label === "string" && entry.label.length > 0 ? { label: entry.label } : {})
101
+ }))
102
+ }
103
+
104
+ /**
105
+ * Build one adapter over the host runtime, backend descriptor and telemetry
106
+ * cache. Everything time- or transport-facing is injectable so tests run on
107
+ * fixtures.
108
+ */
109
+ export function createEvidenceAdapter(options = {}) {
110
+ const runtime = options.runtime
111
+ if (runtime === undefined || typeof runtime.get !== "function" || typeof runtime.list !== "function") {
112
+ throw new TypeError("createEvidenceAdapter needs a routing runtime with get() and list()")
113
+ }
114
+ const backend = options.backend ?? { kind: "unknown" }
115
+ if (!isRecord(backend) || typeof backend.kind !== "string") {
116
+ throw new TypeError("createEvidenceAdapter needs a backend with a string kind")
117
+ }
118
+ const cache = options.cache ?? null
119
+ const now = options.now ?? (() => new Date())
120
+ const maxAgeMs = finiteNumber(options.cacheMaxAgeMs, defaultCacheMaxAgeMs)
121
+ const baseUrl = typeof backend.baseUrl === "string" ? backend.baseUrl : null
122
+ const engineInfo = isRecord(options.engine) ? options.engine : {}
123
+ const getConnection = typeof options.getConnection === "function" ? options.getConnection : null
124
+ // Run 34 (DEC-34-13): the Overview's role sentence and the Roles page read ONE
125
+ // settings document. The host injects the document read (already mirrored to
126
+ // policy.mainModel, DEC-25-18) so the two pages cannot disagree.
127
+ const getSettings = typeof options.getSettings === "function" ? options.getSettings : null
128
+ const probe = typeof options.probe === "function" ? options.probe : null
129
+ const getRemoteModels = typeof options.getRemoteModels === "function" ? options.getRemoteModels : null
130
+ const getModelCapabilities =
131
+ typeof options.getModelCapabilities === "function" ? options.getModelCapabilities : null
132
+ // Run 37 F-37-12: a request observation (engine id + prompt tokens) is recorded
133
+ // after the call returns, so a historical ledger row is joined at read time by
134
+ // its requestId. Absent observations simply leave the fields unknown.
135
+ const getObservations = typeof options.getObservations === "function" ? options.getObservations : null
136
+ // Run 37 DEC-37-09/14: the Overview's engine meter must show the FRESH speed the
137
+ // floor routes on, not the engine's lifetime average (which read 23.9 tps while
138
+ // the same model measured 230+ on real requests).
139
+ const getSpeed = typeof options.getSpeed === "function" ? options.getSpeed : null
140
+ // F-37-51: the recent-session rows the Overview's routing card lists (a cached
141
+ // read the host refreshes; the page never blocks on DSH session enumeration).
142
+ const readSessions = typeof options.readSessions === "function" ? options.readSessions : null
143
+ // Run 30 (DEC-30-02): the host's build id is optional — an adapter without one
144
+ // simply omits the field, so a pre-handshake host can never fail decodeHealth.
145
+ const buildId = typeof options.buildId === "string" && options.buildId.length > 0 ? options.buildId : null
146
+ const remoteModels = () =>
147
+ normalizeRemoteModels(getRemoteModels !== null ? getRemoteModels() : options.remoteModels).map((entry) => ({
148
+ ...entry,
149
+ roles: rolesForModel(entry.model)
150
+ }))
151
+
152
+ const at = () => {
153
+ const value = now()
154
+ return value instanceof Date ? value : new Date(value)
155
+ }
156
+
157
+ const redact = (message) => {
158
+ let text = String(message)
159
+ if (baseUrl !== null && baseUrl.length > 0) text = text.split(baseUrl).join("<backend>")
160
+ return text.replace(/https?:\/\/[^\s"'<>]+/gu, "<backend>")
161
+ }
162
+
163
+ const toError = (error) => {
164
+ if (error === null || error === undefined) return null
165
+ const kind = TELEMETRY_ERROR_KINDS.includes(error.kind) ? error.kind : "unknown"
166
+ const message =
167
+ typeof error.message === "string" && error.message.length > 0
168
+ ? redact(error.message)
169
+ : "telemetry read failed (" + kind + ")"
170
+ return {
171
+ kind,
172
+ message,
173
+ status: numberOrNull(error.status),
174
+ retryable: error.retryable === true
175
+ }
176
+ }
177
+
178
+ const toSnapshot = (raw) => {
179
+ if (!isRecord(raw) || !isRecord(raw.stats) || !isRecord(raw.activity) || !isRecord(raw.device)) {
180
+ return null
181
+ }
182
+ return {
183
+ fetchedAt: typeof raw.fetchedAt === "string" ? raw.fetchedAt : "",
184
+ observedTps: numberOrNull(raw.observedTps),
185
+ observedTpsSource: raw.observedTpsSource === "live" || raw.observedTpsSource === "historical" ? raw.observedTpsSource : null,
186
+ headroomRatio: finiteNumber(raw.headroomRatio, 0),
187
+ engineMax: numberOrNull(raw.engineMax),
188
+ pressureLevel: raw.pressureLevel === "ok" || raw.pressureLevel === "soft" || raw.pressureLevel === "hard" ? raw.pressureLevel : "ok",
189
+ residentModels: Array.isArray(raw.residentModels) ? raw.residentModels.filter((id) => typeof id === "string") : [],
190
+ models: Array.isArray(raw.models)
191
+ ? raw.models
192
+ .filter((model) => isRecord(model) && typeof model.id === "string")
193
+ .map((model) => ({
194
+ id: model.id,
195
+ preferred: model.preferred === true,
196
+ pinned: model.pinned === true,
197
+ contextLength: numberOrNull(model.contextLength),
198
+ sizeBytes: numberOrNull(model.sizeBytes),
199
+ tps: numberOrNull(model.tps)
200
+ }))
201
+ : [],
202
+ preferredModel: stringOrNull(raw.preferredModel),
203
+ stats: {
204
+ avgGenerationTps: finiteNumber(raw.stats.avgGenerationTps, 0),
205
+ avgPrefillTps: finiteNumber(raw.stats.avgPrefillTps, 0),
206
+ totalRequests: finiteNumber(raw.stats.totalRequests, 0),
207
+ totalCachedTokens: finiteNumber(raw.stats.totalCachedTokens, 0),
208
+ cacheEfficiency: finiteNumber(raw.stats.cacheEfficiency, 0),
209
+ uptimeSeconds: finiteNumber(raw.stats.uptimeSeconds, 0)
210
+ },
211
+ activity: {
212
+ activeRequests: finiteNumber(raw.activity.activeRequests, 0),
213
+ waitingRequests: finiteNumber(raw.activity.waitingRequests, 0),
214
+ memoryUsedBytes: finiteNumber(raw.activity.memoryUsedBytes, 0),
215
+ memoryMaxBytes: finiteNumber(raw.activity.memoryMaxBytes, 0)
216
+ },
217
+ device: {
218
+ chipName: typeof raw.device.chipName === "string" ? raw.device.chipName : "",
219
+ memoryGb: finiteNumber(raw.device.memoryGb, 0),
220
+ gpuCores: finiteNumber(raw.device.gpuCores, 0)
221
+ }
222
+ }
223
+ }
224
+
225
+ const readTelemetry = () => {
226
+ const raw = cache !== null && typeof cache.snapshot === "function" ? cache.snapshot() : null
227
+ const error = cache !== null && typeof cache.error === "function" ? toError(cache.error()) : null
228
+ const readAtMs = cache !== null && typeof cache.readAt === "function" ? finiteNumber(cache.readAt(), null) : null
229
+ if (raw === null || raw === undefined) {
230
+ return { snapshot: null, error, readAt: null, staleAt: null }
231
+ }
232
+ const snapshot = toSnapshot(raw)
233
+ if (snapshot === null) {
234
+ return {
235
+ snapshot: null,
236
+ error: {
237
+ kind: "validation",
238
+ message: "telemetry snapshot shape is invalid",
239
+ status: null,
240
+ retryable: false
241
+ },
242
+ readAt: null,
243
+ staleAt: null
244
+ }
245
+ }
246
+ const readAt = isoOrNull(readAtMs)
247
+ const staleAt = isoOrNull(readAtMs === null ? null : readAtMs + maxAgeMs)
248
+ return { snapshot, error, readAt, staleAt }
249
+ }
250
+
251
+ const readPolicy = () => {
252
+ const policy = runtime.get()
253
+ return isPolicy(policy) ? policy : initialPolicy()
254
+ }
255
+
256
+ const readSettings = () => {
257
+ if (getSettings === null) return null
258
+ try {
259
+ const settings = getSettings()
260
+ return isRecord(settings) ? settings : null
261
+ } catch {
262
+ return null
263
+ }
264
+ }
265
+
266
+ /**
267
+ * F-37-48: which roles route to a model. Read from the settings document (the
268
+ * same one the Roles page writes), so the Models page can label a row by the
269
+ * roles it actually serves instead of a hardcoded literal.
270
+ */
271
+ const rolesForModel = (modelId) => {
272
+ if (typeof modelId !== "string" || modelId.length === 0) return []
273
+ const settings = readSettings()
274
+ const roles = settings !== null && isRecord(settings.roles) ? settings.roles : null
275
+ if (roles === null) return []
276
+ const out = []
277
+ for (const role of ["l1", "l2", "l3", "advisor"]) {
278
+ const entry = roles[role]
279
+ if (isRecord(entry) && entry.model === modelId && entry.enabled !== false) out.push(role)
280
+ }
281
+ return out
282
+ }
283
+ /** The settings rev is the cache key the Overview projection follows. */
284
+ const settingsRev = () => {
285
+ const settings = readSettings()
286
+ return settings !== null && Number.isInteger(settings.rev) ? settings.rev : null
287
+ }
288
+
289
+ /**
290
+ * The local-engine line ("Local models run on [oMLX] at 127.0.0.1:8000."):
291
+ * the adapter the host actually runs and the endpoint it is configured with.
292
+ * The endpoint is a UI fact here exactly as it already is on the Engine page.
293
+ */
294
+ const engineProjection = () => {
295
+ const connection = getConnection !== null ? getConnection() : null
296
+ const endpoint =
297
+ isRecord(connection) && typeof connection.endpoint === "string" ? connection.endpoint : baseUrl
298
+ return {
299
+ kind: typeof engineInfo.kind === "string" ? engineInfo.kind : backend.kind,
300
+ label: typeof engineInfo.label === "string" ? engineInfo.label : null,
301
+ endpoint: typeof endpoint === "string" ? endpoint : null
302
+ }
303
+ }
304
+
305
+ const evidence = () => {
306
+ const fetchedAt = at().toISOString()
307
+ const telemetry = readTelemetry()
308
+ const listed = runtime.list()
309
+ const rows = isRecord(listed) && Array.isArray(listed.rows) ? listed.rows.slice() : []
310
+ return {
311
+ fetchedAt,
312
+ staleAt: telemetry.staleAt,
313
+ policy: readPolicy(),
314
+ ledger: { rows },
315
+ telemetry: {
316
+ snapshot: telemetry.snapshot,
317
+ error: telemetry.error,
318
+ readAt: telemetry.readAt
319
+ }
320
+ }
321
+ }
322
+
323
+ // p-A-0 S1: the first-screen projection. One object the Overview renders as a
324
+ // sentence plus floor, headroom and the recent decision tail.
325
+ const overview = () => {
326
+ const telemetry = readTelemetry()
327
+ const snapshot = telemetry.snapshot
328
+ const policy = readPolicy()
329
+ const listed = runtime.list()
330
+ const rows = isRecord(listed) && Array.isArray(listed.rows) ? listed.rows : []
331
+ const recent = rows.slice(0, 5).map((row) => ({
332
+ id: row.id,
333
+ requestId: row.requestId,
334
+ decision: row.decision,
335
+ gate: row.gate === undefined ? null : row.gate,
336
+ model: row.model,
337
+ provider: row.provider === undefined ? null : row.provider,
338
+ selectedModel: row.selectedModel === undefined ? null : row.selectedModel,
339
+ applied: row.applied === undefined ? null : row.applied,
340
+ at: row.at
341
+ }))
342
+ const tokens = rows
343
+ .slice(0, 100)
344
+ .map((row) => (Number.isFinite(row.contextTokens) ? row.contextTokens : 0))
345
+ .sort((a, b) => a - b)
346
+ const ctxTokens = tokens.length === 0 ? 0 : tokens[Math.floor(tokens.length / 2)]
347
+ const ctxBucket = (CONTEXT_BUCKETS.find((bucket) => ctxTokens <= bucket.max) ?? CONTEXT_BUCKETS[CONTEXT_BUCKETS.length - 1]).label
348
+ const used = snapshot === null ? null : snapshot.activity.activeRequests
349
+ const floorTps = policy.floorTps
350
+ const engineMax = snapshot !== null && Number.isFinite(snapshot.engineMax) ? snapshot.engineMax : null
351
+ // Slots come from the context rule, not from observed throughput.
352
+ const atFloor = headroomCeiling(ctxTokens)
353
+ return {
354
+ policy,
355
+ floorTps,
356
+ headroom: { used, atFloor, engineMax },
357
+ // P2: the Overview's engine status Meter reads the same observed
358
+ // throughput and memory headroom the Models/Routing evidence carries.
359
+ engineTps: (() => {
360
+ const fresh =
361
+ getSpeed !== null && snapshot !== null
362
+ ? getSpeed(typeof snapshot.preferredModel === "string" ? snapshot.preferredModel : null)
363
+ : null
364
+ if (fresh !== null && typeof fresh === "object" && Number.isFinite(fresh.tps)) return fresh.tps
365
+ return snapshot === null ? null : snapshot.observedTps
366
+ })(),
367
+ engineTpsSource: (() => {
368
+ const fresh =
369
+ getSpeed !== null && snapshot !== null
370
+ ? getSpeed(typeof snapshot.preferredModel === "string" ? snapshot.preferredModel : null)
371
+ : null
372
+ if (fresh !== null && typeof fresh === "object" && Number.isFinite(fresh.tps)) return "live"
373
+ if (snapshot === null) return null
374
+ return snapshot.observedTpsSource === "live" ? "live" : "historical"
375
+ })(),
376
+ headroomRatio: snapshot === null ? null : snapshot.headroomRatio,
377
+ ctxBucket,
378
+ recent,
379
+ staleAt: telemetry.staleAt,
380
+ fetchedAt: at().toISOString(),
381
+ // The four role chips read this document (roles.l1/l2/l3/advisor.model and
382
+ // roles.l3.enabled); the local-engine line reads the adapter block below.
383
+ settings: readSettings(),
384
+ engine: engineProjection(),
385
+ // F-37-51: routing is per session - the recent sessions and their state.
386
+ sessions: readSessions !== null ? readSessions() : []
387
+ }
388
+ }
389
+
390
+ const isStale = (model) => {
391
+ if (model.staleAt === null) return false
392
+ return Date.parse(model.staleAt) <= Date.parse(model.fetchedAt)
393
+ }
394
+
395
+ const telemetryState = (model) => {
396
+ if (model.telemetry.error !== null) return "error"
397
+ if (model.telemetry.snapshot === null) return "empty"
398
+ return isStale(model) ? "stale" : "ok"
399
+ }
400
+
401
+ const modelsView = (model) => {
402
+ const snapshot = model.telemetry.snapshot
403
+ const state = telemetryState(model)
404
+ const capabilityData = getModelCapabilities !== null ? getModelCapabilities() : null
405
+ const capabilityModels =
406
+ capabilityData !== null && isRecord(capabilityData.models) ? capabilityData.models : {}
407
+ const withCapabilities = (id, base) => {
408
+ const capability = isRecord(capabilityModels[id]) ? capabilityModels[id] : null
409
+ if (capability === null) return base
410
+ return {
411
+ ...base,
412
+ ...capability.inputModalities === undefined ? {} : { inputModalities: capability.inputModalities },
413
+ ...capability.contextWindow === undefined ? {} : { contextWindow: capability.contextWindow }
414
+ }
415
+ }
416
+ const status =
417
+ state === "error"
418
+ ? "error"
419
+ : state === "empty"
420
+ ? "empty"
421
+ : state === "stale"
422
+ ? "stale"
423
+ : snapshot.pressureLevel !== "ok"
424
+ ? "degraded"
425
+ : "ready"
426
+ const selectedModel = model.policy.mainModel?.model ?? ""
427
+ return {
428
+ status,
429
+ selectedModel,
430
+ preferredModel: snapshot === null ? null : snapshot.preferredModel,
431
+ residents:
432
+ snapshot === null
433
+ ? []
434
+ : snapshot.residentModels.map((id) =>
435
+ withCapabilities(id, {
436
+ id,
437
+ preferred: id === snapshot.preferredModel,
438
+ selected: id === selectedModel,
439
+ roles: rolesForModel(id),
440
+ // F-37-48: the fresh probe/measured reading when the model is idle.
441
+ tps: (() => {
442
+ const live = snapshot.models.find((model) => model.id === id)?.tps
443
+ if (Number.isFinite(live)) return live
444
+ const fresh = getSpeed !== null ? getSpeed(id) : null
445
+ return fresh !== null && Number.isFinite(fresh.tps) ? fresh.tps : null
446
+ })()
447
+ })
448
+ ),
449
+ remoteModels: remoteModels(),
450
+ // S2 contract fields (kept alongside the legacy view fields).
451
+ pool: {
452
+ models: snapshot === null ? 0 : snapshot.residentModels.length,
453
+ residents: snapshot === null ? 0 : snapshot.residentModels.length,
454
+ remote: remoteModels().length
455
+ },
456
+ models: [
457
+ ...(snapshot === null
458
+ ? []
459
+ : snapshot.residentModels.map((id) =>
460
+ withCapabilities(id, {
461
+ id,
462
+ local: true,
463
+ preferred: id === snapshot.preferredModel,
464
+ selected: id === selectedModel
465
+ })
466
+ )),
467
+ ...remoteModels().map((entry) => ({
468
+ id: entry.model,
469
+ local: false,
470
+ preferred: false,
471
+ selected: entry.model === selectedModel
472
+ }))
473
+ ],
474
+ selected: selectedModel,
475
+ pressure: snapshot === null ? null : snapshot.pressureLevel,
476
+ capabilities: capabilityData !== null && isRecord(capabilityData.report) ? capabilityData.report : null,
477
+ // Same meaning as evidence.staleAt: the freshness deadline, not the read time.
478
+ staleAt: isoFromValue(model.staleAt),
479
+ kpis:
480
+ snapshot === null
481
+ ? null
482
+ : {
483
+ observedTps: snapshot.observedTps,
484
+ observedTpsSource: snapshot.observedTpsSource,
485
+ headroomRatio: snapshot.headroomRatio,
486
+ pressureLevel: snapshot.pressureLevel,
487
+ activeRequests: snapshot.activity.activeRequests,
488
+ waitingRequests: snapshot.activity.waitingRequests,
489
+ totalRequests: snapshot.stats.totalRequests,
490
+ cacheEfficiency: snapshot.stats.cacheEfficiency,
491
+ uptimeSeconds: snapshot.stats.uptimeSeconds,
492
+ memoryUsedBytes: snapshot.activity.memoryUsedBytes,
493
+ memoryMaxBytes: snapshot.activity.memoryMaxBytes,
494
+ // F-37-48: the engine's soft limit (the guard) and its scheduler
495
+ // ceiling, so the header can show real numbers instead of em dashes.
496
+ memorySoftBytes:
497
+ typeof snapshot.activity.memorySoftBytes === "number" ? snapshot.activity.memorySoftBytes : null,
498
+ engineMax: typeof snapshot.engineMax === "number" && Number.isFinite(snapshot.engineMax) ? snapshot.engineMax : null
499
+ }
500
+ }
501
+ }
502
+
503
+ const routingView = (model) => {
504
+ const rows = model.ledger.rows
505
+ const newest = rows.length > 0 ? rows[0] : null
506
+ return {
507
+ gates: [...GATES],
508
+ policyRev: model.policy.rev,
509
+ current:
510
+ newest === null
511
+ ? null
512
+ : {
513
+ id: newest.id,
514
+ requestId: newest.requestId,
515
+ decision: newest.decision,
516
+ gate: newest.gate === undefined ? null : newest.gate,
517
+ model: newest.model,
518
+ reason: newest.reason,
519
+ at: newest.at,
520
+ applied: newest.applied === undefined ? null : newest.applied,
521
+ // R-36-08/DEC-36-15: the row IS the decision - role, skips and
522
+ // speed provenance render from it, never from a second guess.
523
+ ...(typeof newest.role === "string" ? { role: newest.role } : {}),
524
+ ...(Array.isArray(newest.skips) ? { skips: newest.skips } : {}),
525
+ ...(typeof newest.notAppliedReason === "string" ? { notAppliedReason: newest.notAppliedReason } : {}),
526
+ ...(typeof newest.tpsSource === "string" ? { tpsSource: newest.tpsSource } : {}),
527
+ // Run 36 F-36-V2: the binding ceiling that judged the row, null
528
+ // when the pool was uncapped or the row predates the field.
529
+ concurrencyCeiling:
530
+ typeof newest.concurrencyCeiling === "number" && Number.isFinite(newest.concurrencyCeiling)
531
+ ? newest.concurrencyCeiling
532
+ : null
533
+ },
534
+ counts: {
535
+ local: rows.filter((row) => row.decision === "local").length,
536
+ remote: rows.filter((row) => row.decision === "remote").length,
537
+ total: rows.length
538
+ },
539
+ // S3 contract fields (kept alongside the legacy view fields).
540
+ // R-36-03: the policy is scopeless; a stale document field is never emitted.
541
+ policy: {
542
+ floorTps: model.policy.floorTps,
543
+ mainModel: model.policy.mainModel?.model ?? "",
544
+ rev: model.policy.rev
545
+ },
546
+ order: [...GATES].map((gate, index) => ({
547
+ n: index + 1,
548
+ name: gate,
549
+ description: GATE_DESCRIPTIONS[gate] ?? gate,
550
+ source: GATE_SOURCES[gate] ?? "router"
551
+ })),
552
+ escapes: [...GATES].map((gate) => ({
553
+ gate,
554
+ count: rows.filter((row) => row.gate === gate).length
555
+ })),
556
+ ceiling:
557
+ model.telemetry.snapshot === null
558
+ ? null
559
+ : {
560
+ model: model.telemetry.snapshot.preferredModel,
561
+ observedTps: model.telemetry.snapshot.observedTps,
562
+ active: model.telemetry.snapshot.activity.activeRequests,
563
+ waiting: model.telemetry.snapshot.activity.waitingRequests,
564
+ slots: headroomCeiling(medianContextTokens(rows)),
565
+ contextBucket: (CONTEXT_BUCKETS.find((bucket) => medianContextTokens(rows) <= bucket.max) ??
566
+ CONTEXT_BUCKETS[CONTEXT_BUCKETS.length - 1]).label
567
+ },
568
+ contextBuckets: CONTEXT_BUCKETS.map((bucket) => ({
569
+ label: bucket.label,
570
+ admitted: rows.filter((row) => row.contextTokens > bucket.min && row.contextTokens <= bucket.max).length
571
+ })),
572
+ limits: {
573
+ floorTps: model.policy.floorTps,
574
+ engineMax:
575
+ model.telemetry.snapshot === null || model.telemetry.snapshot.engineMax === undefined
576
+ ? null
577
+ : model.telemetry.snapshot.engineMax,
578
+ memoryMaxBytes:
579
+ model.telemetry.snapshot === null ? null : model.telemetry.snapshot.activity.memoryMaxBytes
580
+ },
581
+ pinned:
582
+ model.telemetry.snapshot === null
583
+ ? []
584
+ : model.telemetry.snapshot.models.filter((entry) => entry.pinned).map((entry) => entry.id)
585
+ }
586
+ }
587
+
588
+ // Run 37 (F-37-12): the Activity row's local per-request detail is the joined
589
+ // observation, which index.js attaches to the ledger row once the engine
590
+ // completes the request. contextTokens is the observation's prompt tokens and
591
+ // omlxRequestId is its engine id. Both are surfaced exactly as recorded and
592
+ // never invented: an unattributed row stays 0 / null rather than a guess.
593
+ const observationFor = (row) => {
594
+ if (getObservations === null) return null
595
+ if (typeof row.requestId !== "string" || row.requestId.length === 0) return null
596
+ try {
597
+ const found = getObservations(row.requestId)
598
+ return isRecord(found) ? found : null
599
+ } catch {
600
+ return null
601
+ }
602
+ }
603
+ const activityRow = (row) => {
604
+ const observation = observationFor(row)
605
+ const promptTokens =
606
+ typeof row.contextTokens === "number" && Number.isFinite(row.contextTokens) && row.contextTokens > 0
607
+ ? row.contextTokens
608
+ : observation !== null && typeof observation.promptTokens === "number" && Number.isFinite(observation.promptTokens)
609
+ ? observation.promptTokens
610
+ : 0
611
+ const joined = typeof row.omlxRequestId === "string" && row.omlxRequestId.length > 0 ? row.omlxRequestId : null
612
+ const engineId =
613
+ joined ?? (observation !== null && typeof observation.engineRequestId === "string" && observation.engineRequestId.length > 0
614
+ ? observation.engineRequestId
615
+ : null)
616
+ return { ...row, contextTokens: promptTokens, omlxRequestId: engineId }
617
+ }
618
+ const activityView = (model) => {
619
+ const rows = model.ledger.rows.map(activityRow)
620
+ return {
621
+ // S4 contract: the endpoint returns the full ledger, so there is no next page yet.
622
+ nextCursor: null,
623
+ rows,
624
+ joined: {
625
+ total: rows.length,
626
+ linked: rows.filter((row) => row.omlxRequestId !== null).length,
627
+ missing: rows.filter((row) => row.omlxRequestId === null).length
628
+ },
629
+ kpis: {
630
+ total: rows.length,
631
+ local: rows.filter((row) => row.decision === "local").length,
632
+ remote: rows.filter((row) => row.decision === "remote").length,
633
+ applied: rows.filter((row) => row.applied === true).length,
634
+ lastAt: rows.length > 0 ? rows[0].at : null
635
+ }
636
+ }
637
+ }
638
+
639
+ const backendView = () => ({ kind: backend.kind })
640
+
641
+ const engineAdapterKind =
642
+ typeof engineInfo.kind === "string" && engineInfo.kind.length > 0 ? engineInfo.kind : backend.kind
643
+ const engineAdapter = () => ({
644
+ kind: engineAdapterKind,
645
+ label: typeof engineInfo.label === "string" ? engineInfo.label : engineAdapterKind,
646
+ version: typeof engineInfo.version === "string" ? engineInfo.version : "unknown",
647
+ adapters: [
648
+ { id: "omlx", label: "oMLX", current: engineAdapterKind === "omlx", enabled: engineAdapterKind === "omlx" },
649
+ { id: "mtplx", label: "mtplx", current: engineAdapterKind === "mtplx", enabled: engineAdapterKind === "mtplx" },
650
+ {
651
+ id: "mlx-serve",
652
+ label: "mlx-serve",
653
+ current: engineAdapterKind === "mlx-serve",
654
+ enabled: engineAdapterKind === "mlx-serve"
655
+ }
656
+ ]
657
+ })
658
+
659
+ const engineConnection = () => {
660
+ if (getConnection !== null) {
661
+ const live = getConnection()
662
+ if (isRecord(live)) {
663
+ const keyPresent = live.keyPresent === true
664
+ return {
665
+ endpoint: typeof live.endpoint === "string" ? live.endpoint : "",
666
+ authKind: live.authKind === "none" ? "none" : "bearer",
667
+ keyPresent,
668
+ keyHint: keyPresent ? "••••••••••" : "",
669
+ source: live.source === "config" || live.source === "environment" ? live.source : "default"
670
+ }
671
+ }
672
+ }
673
+ return {
674
+ endpoint: typeof engineInfo.endpoint === "string" ? engineInfo.endpoint : "",
675
+ authKind: engineInfo.authKind === "none" ? "none" : "bearer",
676
+ keyPresent: engineInfo.keyPresent === true,
677
+ keyHint: engineInfo.keyPresent === true ? "••••••••••" : "",
678
+ source:
679
+ engineInfo.source === "config" || engineInfo.source === "environment" ? engineInfo.source : "default"
680
+ }
681
+ }
682
+
683
+ const engineHealth = (model) => {
684
+ if (model.telemetry.error !== null) {
685
+ return {
686
+ status: "unreachable",
687
+ httpStatus: model.telemetry.error.status,
688
+ latencyMs: null,
689
+ checkedAt: model.telemetry.readAt,
690
+ message: model.telemetry.error.message
691
+ }
692
+ }
693
+ if (model.telemetry.snapshot !== null) {
694
+ return {
695
+ status: "healthy",
696
+ httpStatus: 200,
697
+ latencyMs: null,
698
+ checkedAt: model.telemetry.readAt ?? model.telemetry.snapshot.fetchedAt,
699
+ message: null
700
+ }
701
+ }
702
+ return { status: "unknown", httpStatus: null, latencyMs: null, checkedAt: null, message: null }
703
+ }
704
+
705
+ const engine = () => {
706
+ const model = evidence()
707
+ const snapshot = model.telemetry.snapshot
708
+ const engineCapabilities = getModelCapabilities !== null ? getModelCapabilities() : null
709
+ const models =
710
+ snapshot === null
711
+ ? []
712
+ : snapshot.residentModels.map((id) => ({
713
+ id,
714
+ default: id === snapshot.preferredModel,
715
+ loaded: true
716
+ }))
717
+ return {
718
+ kind: "engine",
719
+ backend: backendView(),
720
+ adapter: engineAdapter(),
721
+ connection: engineConnection(),
722
+ health: engineHealth(model),
723
+ models,
724
+ capabilities:
725
+ engineCapabilities !== null && isRecord(engineCapabilities.report) ? engineCapabilities.report : null,
726
+ discovery: { discovered: models.length, resident: models.length },
727
+ config: {
728
+ writable: true,
729
+ note: "Connection endpoint and API key can be updated; the adapter kind is fixed by the profile."
730
+ },
731
+ evidence: model
732
+ }
733
+ }
734
+
735
+ /** Cheap liveness payload; deliberately does not build the full model twice. */
736
+ const health = () => {
737
+ const model = evidence()
738
+ const capabilityData = getModelCapabilities !== null ? getModelCapabilities() : null
739
+ const capabilityReport =
740
+ capabilityData !== null && isRecord(capabilityData.report) ? capabilityData.report : null
741
+ const drift = capabilityReport !== null ? capabilityReport.drift : null
742
+ return {
743
+ ok: true,
744
+ name: "router",
745
+ ...(buildId === null ? {} : { buildId }),
746
+ now: model.fetchedAt,
747
+ backend: backendView(),
748
+ policyRev: model.policy.rev,
749
+ ledgerRows: model.ledger.rows.length,
750
+ telemetry: telemetryState(model),
751
+ staleAt: model.staleAt,
752
+ capabilities:
753
+ capabilityReport === null
754
+ ? null
755
+ : {
756
+ sources: capabilityReport.sources ?? {},
757
+ advertised: capabilityReport.advertised ?? 0,
758
+ excluded: Array.isArray(capabilityReport.excluded) ? capabilityReport.excluded.length : 0,
759
+ drift: drift !== null && drift !== undefined,
760
+ driftKeys:
761
+ drift !== null && drift !== undefined && Array.isArray(drift.missingKeys) ? drift.missingKeys : []
762
+ },
763
+ routing: {
764
+ enabled: typeof runtime.isEnabled === "function" ? runtime.isEnabled() : false
765
+ }
766
+ }
767
+ }
768
+
769
+ const models = () => {
770
+ const model = evidence()
771
+ return { kind: "models", backend: backendView(), evidence: model, view: modelsView(model) }
772
+ }
773
+
774
+ const routing = () => {
775
+ const model = evidence()
776
+ return { kind: "routing", backend: backendView(), evidence: model, view: routingView(model) }
777
+ }
778
+
779
+ const activity = () => {
780
+ const model = evidence()
781
+ return { kind: "activity", backend: backendView(), evidence: model, view: activityView(model) }
782
+ }
783
+
784
+ return {
785
+ backend: backendView(),
786
+ evidence,
787
+ health,
788
+ models,
789
+ routing,
790
+ overview,
791
+ activity,
792
+ engine,
793
+ probe,
794
+ // The overview projection's freshness key: a settings write moves the rev,
795
+ // and the handler rebuilds instead of serving the up-to-10s-old body.
796
+ settingsRev,
797
+ telemetryState: () => telemetryState(evidence())
798
+ }
799
+ }
800
+
801
+ // Deterministic strong-ish ETag for a JSON projection (djb2).
802
+ const etagOf = (value) => {
803
+ const text = JSON.stringify(value)
804
+ let hash = 5381
805
+ for (let index = 0; index < text.length; index += 1) {
806
+ hash = ((hash << 5) + hash) ^ text.charCodeAt(index)
807
+ }
808
+ return '"' + (hash >>> 0).toString(16) + '"'
809
+ }
810
+
811
+ const jsonHeaders = (auth, body) => ({
812
+ "content-type": "application/json; charset=utf-8",
813
+ "cache-control": "no-store",
814
+ "content-length": String(Buffer.byteLength(body)),
815
+ [AUTH_HEADER]: auth.label()
816
+ })
817
+
818
+ const writeJson = (res, status, auth, value, head = false) => {
819
+ const body = JSON.stringify(value)
820
+ res.writeHead(status, jsonHeaders(auth, body))
821
+ res.end(head ? undefined : body)
822
+ }
823
+
824
+ const writeText = (res, status, auth, text, extraHeaders = {}) => {
825
+ res.writeHead(status, {
826
+ "content-type": "text/plain; charset=utf-8",
827
+ "cache-control": "no-store",
828
+ "content-length": String(Buffer.byteLength(text)),
829
+ [AUTH_HEADER]: auth.label(),
830
+ ...extraHeaders
831
+ })
832
+ res.end(text)
833
+ }
834
+
835
+ const wantsProbe = (req) => {
836
+ try {
837
+ return new URL(req.url ?? "/", "http://router.local").searchParams.get("probe") === "1"
838
+ } catch {
839
+ return false
840
+ }
841
+ }
842
+
843
+ // Read a JSON request body from a node:http IncomingMessage. Tests may pass a
844
+ // pre-parsed object on req.body instead of simulating the stream.
845
+ const readJsonBody = (req, limit = 16_384) => {
846
+ if (req.body !== undefined && typeof req.body === "object" && req.body !== null) {
847
+ return Promise.resolve(req.body)
848
+ }
849
+ return new Promise((resolve, reject) => {
850
+ const chunks = []
851
+ let total = 0
852
+ req.on("data", (chunk) => {
853
+ total += chunk.length
854
+ if (total > limit) {
855
+ const error = new Error("request body too large")
856
+ error.code = "PAYLOAD_TOO_LARGE"
857
+ reject(error)
858
+ return
859
+ }
860
+ chunks.push(chunk)
861
+ })
862
+ req.on("end", () => {
863
+ try {
864
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"))
865
+ } catch (error) {
866
+ reject(error)
867
+ }
868
+ })
869
+ req.on("error", reject)
870
+ })
871
+ }
872
+
873
+ const createHandler = (build, auth) => async (req, res) => {
874
+ if (req.method !== "GET" && req.method !== "HEAD") {
875
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
876
+ return
877
+ }
878
+ if (auth.reject !== null) {
879
+ let rejection
880
+ try {
881
+ rejection = auth.reject(req)
882
+ } catch {
883
+ rejection = 403
884
+ }
885
+ if (rejection === 401 || rejection === 403) {
886
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
887
+ return
888
+ }
889
+ }
890
+ let payload
891
+ try {
892
+ payload = await build(req)
893
+ } catch {
894
+ writeJson(res, 500, auth, {
895
+ ok: false,
896
+ error: { kind: "internal", message: "evidence unavailable" }
897
+ })
898
+ return
899
+ }
900
+ writeJson(res, 200, auth, payload, req.method === "HEAD")
901
+ }
902
+
903
+ /**
904
+ * Compose the ctx.webServer registrations for the evidence routes.
905
+ * `options.authorize` is `(req) => 401 | 403 | undefined`; when it is omitted the
906
+ * routes answer without authentication and the response says so.
907
+ */
908
+ export function createRouterRoutes(adapter, options = {}) {
909
+ if (adapter === undefined || typeof adapter.health !== "function") {
910
+ throw new TypeError("createRouterRoutes needs an evidence adapter")
911
+ }
912
+ const reject = typeof options.authorize === "function" ? options.authorize : null
913
+ const label =
914
+ typeof options.authLabel === "function"
915
+ ? options.authLabel
916
+ : () => (reject === null ? "unauthenticated" : "connection")
917
+ const auth = { reject, label }
918
+ const onSave = typeof options.onSave === "function" ? options.onSave : null
919
+ const onToggle = typeof options.onToggle === "function" ? options.onToggle : null
920
+ const onSettingsGet = typeof options.onSettingsGet === "function" ? options.onSettingsGet : null
921
+ const onSettingsSave = typeof options.onSettingsSave === "function" ? options.onSettingsSave : null
922
+
923
+ const rejectRequest = (req, res) => {
924
+ if (auth.reject === null) return false
925
+ let rejection
926
+ try {
927
+ rejection = auth.reject(req)
928
+ } catch {
929
+ rejection = 403
930
+ }
931
+ if (rejection === 401 || rejection === 403) {
932
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
933
+ return true
934
+ }
935
+ return false
936
+ }
937
+
938
+ const routingHandler = async (req, res) => {
939
+ if (req.method === "POST") {
940
+ if (rejectRequest(req, res)) return
941
+ if (onToggle === null) {
942
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
943
+ return
944
+ }
945
+ let body
946
+ try {
947
+ body = await readJsonBody(req)
948
+ } catch {
949
+ writeJson(res, 400, auth, { ok: false, error: { field: "body", message: "invalid JSON body" } })
950
+ return
951
+ }
952
+ let result
953
+ try {
954
+ result = await onToggle(body)
955
+ } catch {
956
+ writeJson(res, 500, auth, { ok: false, error: { field: "routing", message: "could not update routing" } })
957
+ return
958
+ }
959
+ if (result.ok === true) {
960
+ writeJson(res, 200, auth, result.payload)
961
+ } else {
962
+ writeJson(res, result.status ?? 400, auth, { ok: false, error: result.error ?? { field: "routing", message: "invalid routing toggle" } })
963
+ }
964
+ return
965
+ }
966
+ await createHandler(() => adapter.routing(), auth)(req, res)
967
+ }
968
+
969
+ const engineHandler = async (req, res) => {
970
+ if (req.method === "POST") {
971
+ if (auth.reject !== null) {
972
+ let rejection
973
+ try {
974
+ rejection = auth.reject(req)
975
+ } catch {
976
+ rejection = 403
977
+ }
978
+ if (rejection === 401 || rejection === 403) {
979
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
980
+ return
981
+ }
982
+ }
983
+ if (onSave === null) {
984
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
985
+ return
986
+ }
987
+ let body
988
+ try {
989
+ body = await readJsonBody(req)
990
+ } catch {
991
+ writeJson(res, 400, auth, { ok: false, error: { field: "body", message: "invalid JSON body" } })
992
+ return
993
+ }
994
+ let result
995
+ try {
996
+ result = await onSave(body)
997
+ } catch {
998
+ writeJson(res, 500, auth, { ok: false, error: { field: "engine", message: "could not save connection" } })
999
+ return
1000
+ }
1001
+ if (result.ok === true) {
1002
+ writeJson(res, 200, auth, result.payload)
1003
+ } else {
1004
+ writeJson(res, result.status ?? 400, auth, { ok: false, error: result.error ?? { field: "engine", message: "invalid connection" } })
1005
+ }
1006
+ return
1007
+ }
1008
+ await createHandler(
1009
+ async (request) => {
1010
+ if (wantsProbe(request) && typeof adapter.probe === "function") {
1011
+ await adapter.probe()
1012
+ }
1013
+ return adapter.engine()
1014
+ },
1015
+ auth
1016
+ )(req, res)
1017
+ }
1018
+
1019
+ // S5 operational defaults: GET/PUT with If-Match; the policy sentence is never written here.
1020
+ const settingsHandler = async (req, res) => {
1021
+ if (rejectRequest(req, res)) return
1022
+ if (req.method === "GET" || req.method === "HEAD") {
1023
+ const view =
1024
+ onSettingsGet !== null
1025
+ ? onSettingsGet()
1026
+ : { endpoint: "", ledgerDir: "", pollSeconds: 2, advisory: false, version: 1 }
1027
+ writeJson(res, 200, auth, view, req.method === "HEAD")
1028
+ return
1029
+ }
1030
+ if (req.method !== "PUT") {
1031
+ writeText(res, 405, auth, "", { allow: "GET, HEAD, PUT" })
1032
+ return
1033
+ }
1034
+ if (onSettingsSave === null) {
1035
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
1036
+ return
1037
+ }
1038
+ let body
1039
+ try {
1040
+ body = await readJsonBody(req)
1041
+ } catch {
1042
+ writeJson(res, 400, auth, { ok: false, error: { field: "body", message: "invalid JSON body" } })
1043
+ return
1044
+ }
1045
+ const result = await onSettingsSave(body, req.headers?.["if-match"])
1046
+ if (result.ok === true) {
1047
+ writeJson(res, 200, auth, result.payload)
1048
+ return
1049
+ }
1050
+ if (result.status === 409) {
1051
+ writeJson(res, 409, auth, result.payload)
1052
+ return
1053
+ }
1054
+ writeJson(res, result.status ?? 400, auth, {
1055
+ ok: false,
1056
+ error: result.error ?? { field: "settings", message: "invalid settings" }
1057
+ })
1058
+ }
1059
+
1060
+ // S1 first-screen projection: ETag + 10s cache, 304 on a matching If-None-Match.
1061
+ let overviewCache = null
1062
+ const overviewHandler = (req, res) => {
1063
+ if (req.method !== "GET" && req.method !== "HEAD") {
1064
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
1065
+ return
1066
+ }
1067
+ if (auth.reject !== null) {
1068
+ let rejection
1069
+ try {
1070
+ rejection = auth.reject(req)
1071
+ } catch {
1072
+ rejection = 403
1073
+ }
1074
+ if (rejection === 401 || rejection === 403) {
1075
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
1076
+ return
1077
+ }
1078
+ }
1079
+ const nowMs = Date.now()
1080
+ // The settings rev is the projection's freshness key: a save on either page
1081
+ // moves it, so the next read is rebuilt instead of served from the cache.
1082
+ const revNow = typeof adapter.settingsRev === "function" ? adapter.settingsRev() : null
1083
+ if (overviewCache === null || nowMs - overviewCache.at > 10_000 || overviewCache.settingsRev !== revNow) {
1084
+ const body = adapter.overview()
1085
+ overviewCache = { at: nowMs, body, etag: etagOf(body), settingsRev: revNow }
1086
+ }
1087
+ const ifNoneMatch = req?.headers?.["if-none-match"]
1088
+ if (typeof ifNoneMatch === "string" && ifNoneMatch === overviewCache.etag) {
1089
+ res.writeHead(304, { etag: overviewCache.etag, [AUTH_HEADER]: auth.label() })
1090
+ res.end()
1091
+ return
1092
+ }
1093
+ const body = JSON.stringify(overviewCache.body)
1094
+ res.writeHead(200, { ...jsonHeaders(auth, body), etag: overviewCache.etag })
1095
+ res.end(req.method === "HEAD" ? undefined : body)
1096
+ }
1097
+
1098
+ return [
1099
+ { kind: "exact", path: EVIDENCE_ROUTES.health, handler: createHandler(() => adapter.health(), auth) },
1100
+ { kind: "exact", path: EVIDENCE_ROUTES.models, handler: createHandler(() => adapter.models(), auth) },
1101
+ { kind: "exact", path: EVIDENCE_ROUTES.routing, handler: routingHandler },
1102
+ { kind: "exact", path: EVIDENCE_ROUTES.activity, handler: createHandler(() => adapter.activity(), auth) },
1103
+ { kind: "exact", path: EVIDENCE_ROUTES.engine, handler: engineHandler },
1104
+ { kind: "exact", path: EVIDENCE_ROUTES.overview, handler: overviewHandler },
1105
+ { kind: "exact", path: EVIDENCE_ROUTES.settings, handler: settingsHandler }
1106
+ ]
1107
+ }