@try-works/dsh-minimal-router 0.0.0-stage → 0.1.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,1016 @@
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 30 (DEC-30-02): the host's build id is optional — an adapter without one
133
+ // simply omits the field, so a pre-handshake host can never fail decodeHealth.
134
+ const buildId = typeof options.buildId === "string" && options.buildId.length > 0 ? options.buildId : null
135
+ const remoteModels = () =>
136
+ normalizeRemoteModels(getRemoteModels !== null ? getRemoteModels() : options.remoteModels)
137
+
138
+ const at = () => {
139
+ const value = now()
140
+ return value instanceof Date ? value : new Date(value)
141
+ }
142
+
143
+ const redact = (message) => {
144
+ let text = String(message)
145
+ if (baseUrl !== null && baseUrl.length > 0) text = text.split(baseUrl).join("<backend>")
146
+ return text.replace(/https?:\/\/[^\s"'<>]+/gu, "<backend>")
147
+ }
148
+
149
+ const toError = (error) => {
150
+ if (error === null || error === undefined) return null
151
+ const kind = TELEMETRY_ERROR_KINDS.includes(error.kind) ? error.kind : "unknown"
152
+ const message =
153
+ typeof error.message === "string" && error.message.length > 0
154
+ ? redact(error.message)
155
+ : "telemetry read failed (" + kind + ")"
156
+ return {
157
+ kind,
158
+ message,
159
+ status: numberOrNull(error.status),
160
+ retryable: error.retryable === true
161
+ }
162
+ }
163
+
164
+ const toSnapshot = (raw) => {
165
+ if (!isRecord(raw) || !isRecord(raw.stats) || !isRecord(raw.activity) || !isRecord(raw.device)) {
166
+ return null
167
+ }
168
+ return {
169
+ fetchedAt: typeof raw.fetchedAt === "string" ? raw.fetchedAt : "",
170
+ observedTps: numberOrNull(raw.observedTps),
171
+ observedTpsSource: raw.observedTpsSource === "live" || raw.observedTpsSource === "historical" ? raw.observedTpsSource : null,
172
+ headroomRatio: finiteNumber(raw.headroomRatio, 0),
173
+ engineMax: numberOrNull(raw.engineMax),
174
+ pressureLevel: raw.pressureLevel === "ok" || raw.pressureLevel === "soft" || raw.pressureLevel === "hard" ? raw.pressureLevel : "ok",
175
+ residentModels: Array.isArray(raw.residentModels) ? raw.residentModels.filter((id) => typeof id === "string") : [],
176
+ models: Array.isArray(raw.models)
177
+ ? raw.models
178
+ .filter((model) => isRecord(model) && typeof model.id === "string")
179
+ .map((model) => ({
180
+ id: model.id,
181
+ preferred: model.preferred === true,
182
+ pinned: model.pinned === true,
183
+ contextLength: numberOrNull(model.contextLength),
184
+ sizeBytes: numberOrNull(model.sizeBytes),
185
+ tps: numberOrNull(model.tps)
186
+ }))
187
+ : [],
188
+ preferredModel: stringOrNull(raw.preferredModel),
189
+ stats: {
190
+ avgGenerationTps: finiteNumber(raw.stats.avgGenerationTps, 0),
191
+ avgPrefillTps: finiteNumber(raw.stats.avgPrefillTps, 0),
192
+ totalRequests: finiteNumber(raw.stats.totalRequests, 0),
193
+ totalCachedTokens: finiteNumber(raw.stats.totalCachedTokens, 0),
194
+ cacheEfficiency: finiteNumber(raw.stats.cacheEfficiency, 0),
195
+ uptimeSeconds: finiteNumber(raw.stats.uptimeSeconds, 0)
196
+ },
197
+ activity: {
198
+ activeRequests: finiteNumber(raw.activity.activeRequests, 0),
199
+ waitingRequests: finiteNumber(raw.activity.waitingRequests, 0),
200
+ memoryUsedBytes: finiteNumber(raw.activity.memoryUsedBytes, 0),
201
+ memoryMaxBytes: finiteNumber(raw.activity.memoryMaxBytes, 0)
202
+ },
203
+ device: {
204
+ chipName: typeof raw.device.chipName === "string" ? raw.device.chipName : "",
205
+ memoryGb: finiteNumber(raw.device.memoryGb, 0),
206
+ gpuCores: finiteNumber(raw.device.gpuCores, 0)
207
+ }
208
+ }
209
+ }
210
+
211
+ const readTelemetry = () => {
212
+ const raw = cache !== null && typeof cache.snapshot === "function" ? cache.snapshot() : null
213
+ const error = cache !== null && typeof cache.error === "function" ? toError(cache.error()) : null
214
+ const readAtMs = cache !== null && typeof cache.readAt === "function" ? finiteNumber(cache.readAt(), null) : null
215
+ if (raw === null || raw === undefined) {
216
+ return { snapshot: null, error, readAt: null, staleAt: null }
217
+ }
218
+ const snapshot = toSnapshot(raw)
219
+ if (snapshot === null) {
220
+ return {
221
+ snapshot: null,
222
+ error: {
223
+ kind: "validation",
224
+ message: "telemetry snapshot shape is invalid",
225
+ status: null,
226
+ retryable: false
227
+ },
228
+ readAt: null,
229
+ staleAt: null
230
+ }
231
+ }
232
+ const readAt = isoOrNull(readAtMs)
233
+ const staleAt = isoOrNull(readAtMs === null ? null : readAtMs + maxAgeMs)
234
+ return { snapshot, error, readAt, staleAt }
235
+ }
236
+
237
+ const readPolicy = () => {
238
+ const policy = runtime.get()
239
+ return isPolicy(policy) ? policy : initialPolicy()
240
+ }
241
+
242
+ const readSettings = () => {
243
+ if (getSettings === null) return null
244
+ try {
245
+ const settings = getSettings()
246
+ return isRecord(settings) ? settings : null
247
+ } catch {
248
+ return null
249
+ }
250
+ }
251
+
252
+ /** The settings rev is the cache key the Overview projection follows. */
253
+ const settingsRev = () => {
254
+ const settings = readSettings()
255
+ return settings !== null && Number.isInteger(settings.rev) ? settings.rev : null
256
+ }
257
+
258
+ /**
259
+ * The local-engine line ("Local models run on [oMLX] at 127.0.0.1:8000."):
260
+ * the adapter the host actually runs and the endpoint it is configured with.
261
+ * The endpoint is a UI fact here exactly as it already is on the Engine page.
262
+ */
263
+ const engineProjection = () => {
264
+ const connection = getConnection !== null ? getConnection() : null
265
+ const endpoint =
266
+ isRecord(connection) && typeof connection.endpoint === "string" ? connection.endpoint : baseUrl
267
+ return {
268
+ kind: typeof engineInfo.kind === "string" ? engineInfo.kind : backend.kind,
269
+ label: typeof engineInfo.label === "string" ? engineInfo.label : null,
270
+ endpoint: typeof endpoint === "string" ? endpoint : null
271
+ }
272
+ }
273
+
274
+ const evidence = () => {
275
+ const fetchedAt = at().toISOString()
276
+ const telemetry = readTelemetry()
277
+ const listed = runtime.list()
278
+ const rows = isRecord(listed) && Array.isArray(listed.rows) ? listed.rows.slice() : []
279
+ return {
280
+ fetchedAt,
281
+ staleAt: telemetry.staleAt,
282
+ policy: readPolicy(),
283
+ ledger: { rows },
284
+ telemetry: {
285
+ snapshot: telemetry.snapshot,
286
+ error: telemetry.error,
287
+ readAt: telemetry.readAt
288
+ }
289
+ }
290
+ }
291
+
292
+ // p-A-0 S1: the first-screen projection. One object the Overview renders as a
293
+ // sentence plus floor, headroom and the recent decision tail.
294
+ const overview = () => {
295
+ const telemetry = readTelemetry()
296
+ const snapshot = telemetry.snapshot
297
+ const policy = readPolicy()
298
+ const listed = runtime.list()
299
+ const rows = isRecord(listed) && Array.isArray(listed.rows) ? listed.rows : []
300
+ const recent = rows.slice(0, 5).map((row) => ({
301
+ id: row.id,
302
+ requestId: row.requestId,
303
+ decision: row.decision,
304
+ gate: row.gate === undefined ? null : row.gate,
305
+ model: row.model,
306
+ provider: row.provider === undefined ? null : row.provider,
307
+ selectedModel: row.selectedModel === undefined ? null : row.selectedModel,
308
+ applied: row.applied === undefined ? null : row.applied,
309
+ at: row.at
310
+ }))
311
+ const tokens = rows
312
+ .slice(0, 100)
313
+ .map((row) => (Number.isFinite(row.contextTokens) ? row.contextTokens : 0))
314
+ .sort((a, b) => a - b)
315
+ const ctxTokens = tokens.length === 0 ? 0 : tokens[Math.floor(tokens.length / 2)]
316
+ const ctxBucket = (CONTEXT_BUCKETS.find((bucket) => ctxTokens <= bucket.max) ?? CONTEXT_BUCKETS[CONTEXT_BUCKETS.length - 1]).label
317
+ const used = snapshot === null ? null : snapshot.activity.activeRequests
318
+ const floorTps = policy.floorTps
319
+ const engineMax = snapshot !== null && Number.isFinite(snapshot.engineMax) ? snapshot.engineMax : null
320
+ // Slots come from the context rule, not from observed throughput.
321
+ const atFloor = headroomCeiling(ctxTokens)
322
+ return {
323
+ policy,
324
+ floorTps,
325
+ headroom: { used, atFloor, engineMax },
326
+ // P2: the Overview's engine status Meter reads the same observed
327
+ // throughput and memory headroom the Models/Routing evidence carries.
328
+ engineTps: snapshot === null ? null : snapshot.observedTps,
329
+ engineTpsSource: snapshot === null ? null : snapshot.observedTpsSource,
330
+ headroomRatio: snapshot === null ? null : snapshot.headroomRatio,
331
+ ctxBucket,
332
+ recent,
333
+ staleAt: telemetry.staleAt,
334
+ fetchedAt: at().toISOString(),
335
+ // The four role chips read this document (roles.l1/l2/l3/advisor.model and
336
+ // roles.l3.enabled); the local-engine line reads the adapter block below.
337
+ settings: readSettings(),
338
+ engine: engineProjection()
339
+ }
340
+ }
341
+
342
+ const isStale = (model) => {
343
+ if (model.staleAt === null) return false
344
+ return Date.parse(model.staleAt) <= Date.parse(model.fetchedAt)
345
+ }
346
+
347
+ const telemetryState = (model) => {
348
+ if (model.telemetry.error !== null) return "error"
349
+ if (model.telemetry.snapshot === null) return "empty"
350
+ return isStale(model) ? "stale" : "ok"
351
+ }
352
+
353
+ const modelsView = (model) => {
354
+ const snapshot = model.telemetry.snapshot
355
+ const state = telemetryState(model)
356
+ const capabilityData = getModelCapabilities !== null ? getModelCapabilities() : null
357
+ const capabilityModels =
358
+ capabilityData !== null && isRecord(capabilityData.models) ? capabilityData.models : {}
359
+ const withCapabilities = (id, base) => {
360
+ const capability = isRecord(capabilityModels[id]) ? capabilityModels[id] : null
361
+ if (capability === null) return base
362
+ return {
363
+ ...base,
364
+ ...capability.inputModalities === undefined ? {} : { inputModalities: capability.inputModalities },
365
+ ...capability.contextWindow === undefined ? {} : { contextWindow: capability.contextWindow }
366
+ }
367
+ }
368
+ const status =
369
+ state === "error"
370
+ ? "error"
371
+ : state === "empty"
372
+ ? "empty"
373
+ : state === "stale"
374
+ ? "stale"
375
+ : snapshot.pressureLevel !== "ok"
376
+ ? "degraded"
377
+ : "ready"
378
+ const selectedModel = model.policy.mainModel?.model ?? ""
379
+ return {
380
+ status,
381
+ selectedModel,
382
+ preferredModel: snapshot === null ? null : snapshot.preferredModel,
383
+ residents:
384
+ snapshot === null
385
+ ? []
386
+ : snapshot.residentModels.map((id) =>
387
+ withCapabilities(id, {
388
+ id,
389
+ preferred: id === snapshot.preferredModel,
390
+ selected: id === selectedModel
391
+ })
392
+ ),
393
+ remoteModels: remoteModels(),
394
+ // S2 contract fields (kept alongside the legacy view fields).
395
+ pool: {
396
+ models: snapshot === null ? 0 : snapshot.residentModels.length,
397
+ residents: snapshot === null ? 0 : snapshot.residentModels.length,
398
+ remote: remoteModels().length
399
+ },
400
+ models: [
401
+ ...(snapshot === null
402
+ ? []
403
+ : snapshot.residentModels.map((id) =>
404
+ withCapabilities(id, {
405
+ id,
406
+ local: true,
407
+ preferred: id === snapshot.preferredModel,
408
+ selected: id === selectedModel
409
+ })
410
+ )),
411
+ ...remoteModels().map((entry) => ({
412
+ id: entry.model,
413
+ local: false,
414
+ preferred: false,
415
+ selected: entry.model === selectedModel
416
+ }))
417
+ ],
418
+ selected: selectedModel,
419
+ pressure: snapshot === null ? null : snapshot.pressureLevel,
420
+ capabilities: capabilityData !== null && isRecord(capabilityData.report) ? capabilityData.report : null,
421
+ // Same meaning as evidence.staleAt: the freshness deadline, not the read time.
422
+ staleAt: isoFromValue(model.staleAt),
423
+ kpis:
424
+ snapshot === null
425
+ ? null
426
+ : {
427
+ observedTps: snapshot.observedTps,
428
+ observedTpsSource: snapshot.observedTpsSource,
429
+ headroomRatio: snapshot.headroomRatio,
430
+ pressureLevel: snapshot.pressureLevel,
431
+ activeRequests: snapshot.activity.activeRequests,
432
+ waitingRequests: snapshot.activity.waitingRequests,
433
+ totalRequests: snapshot.stats.totalRequests,
434
+ cacheEfficiency: snapshot.stats.cacheEfficiency,
435
+ uptimeSeconds: snapshot.stats.uptimeSeconds,
436
+ memoryUsedBytes: snapshot.activity.memoryUsedBytes,
437
+ memoryMaxBytes: snapshot.activity.memoryMaxBytes
438
+ }
439
+ }
440
+ }
441
+
442
+ const routingView = (model) => {
443
+ const rows = model.ledger.rows
444
+ const newest = rows.length > 0 ? rows[0] : null
445
+ return {
446
+ gates: [...GATES],
447
+ policyRev: model.policy.rev,
448
+ current:
449
+ newest === null
450
+ ? null
451
+ : {
452
+ id: newest.id,
453
+ requestId: newest.requestId,
454
+ decision: newest.decision,
455
+ gate: newest.gate === undefined ? null : newest.gate,
456
+ model: newest.model,
457
+ reason: newest.reason,
458
+ at: newest.at,
459
+ applied: newest.applied === undefined ? null : newest.applied,
460
+ // R-36-08/DEC-36-15: the row IS the decision - role, skips and
461
+ // speed provenance render from it, never from a second guess.
462
+ ...(typeof newest.role === "string" ? { role: newest.role } : {}),
463
+ ...(Array.isArray(newest.skips) ? { skips: newest.skips } : {}),
464
+ ...(typeof newest.notAppliedReason === "string" ? { notAppliedReason: newest.notAppliedReason } : {}),
465
+ ...(typeof newest.tpsSource === "string" ? { tpsSource: newest.tpsSource } : {}),
466
+ // Run 36 F-36-V2: the binding ceiling that judged the row, null
467
+ // when the pool was uncapped or the row predates the field.
468
+ concurrencyCeiling:
469
+ typeof newest.concurrencyCeiling === "number" && Number.isFinite(newest.concurrencyCeiling)
470
+ ? newest.concurrencyCeiling
471
+ : null
472
+ },
473
+ counts: {
474
+ local: rows.filter((row) => row.decision === "local").length,
475
+ remote: rows.filter((row) => row.decision === "remote").length,
476
+ total: rows.length
477
+ },
478
+ // S3 contract fields (kept alongside the legacy view fields).
479
+ // R-36-03: the policy is scopeless; a stale document field is never emitted.
480
+ policy: {
481
+ floorTps: model.policy.floorTps,
482
+ mainModel: model.policy.mainModel?.model ?? "",
483
+ rev: model.policy.rev
484
+ },
485
+ order: [...GATES].map((gate, index) => ({
486
+ n: index + 1,
487
+ name: gate,
488
+ description: GATE_DESCRIPTIONS[gate] ?? gate,
489
+ source: GATE_SOURCES[gate] ?? "router"
490
+ })),
491
+ escapes: [...GATES].map((gate) => ({
492
+ gate,
493
+ count: rows.filter((row) => row.gate === gate).length
494
+ })),
495
+ ceiling:
496
+ model.telemetry.snapshot === null
497
+ ? null
498
+ : {
499
+ model: model.telemetry.snapshot.preferredModel,
500
+ observedTps: model.telemetry.snapshot.observedTps,
501
+ active: model.telemetry.snapshot.activity.activeRequests,
502
+ waiting: model.telemetry.snapshot.activity.waitingRequests,
503
+ slots: headroomCeiling(medianContextTokens(rows)),
504
+ contextBucket: (CONTEXT_BUCKETS.find((bucket) => medianContextTokens(rows) <= bucket.max) ??
505
+ CONTEXT_BUCKETS[CONTEXT_BUCKETS.length - 1]).label
506
+ },
507
+ contextBuckets: CONTEXT_BUCKETS.map((bucket) => ({
508
+ label: bucket.label,
509
+ admitted: rows.filter((row) => row.contextTokens > bucket.min && row.contextTokens <= bucket.max).length
510
+ })),
511
+ limits: {
512
+ floorTps: model.policy.floorTps,
513
+ engineMax:
514
+ model.telemetry.snapshot === null || model.telemetry.snapshot.engineMax === undefined
515
+ ? null
516
+ : model.telemetry.snapshot.engineMax,
517
+ memoryMaxBytes:
518
+ model.telemetry.snapshot === null ? null : model.telemetry.snapshot.activity.memoryMaxBytes
519
+ },
520
+ pinned:
521
+ model.telemetry.snapshot === null
522
+ ? []
523
+ : model.telemetry.snapshot.models.filter((entry) => entry.pinned).map((entry) => entry.id)
524
+ }
525
+ }
526
+
527
+ const activityView = (model) => {
528
+ const rows = model.ledger.rows
529
+ return {
530
+ // S4 contract: the endpoint returns the full ledger, so there is no next page yet.
531
+ nextCursor: null,
532
+ rows: rows,
533
+ joined: {
534
+ total: rows.length,
535
+ linked: rows.filter((row) => row.omlxRequestId !== null && row.omlxRequestId !== undefined).length,
536
+ missing: rows.filter((row) => row.omlxRequestId === null || row.omlxRequestId === undefined).length
537
+ },
538
+ kpis: {
539
+ total: rows.length,
540
+ local: rows.filter((row) => row.decision === "local").length,
541
+ remote: rows.filter((row) => row.decision === "remote").length,
542
+ applied: rows.filter((row) => row.applied === true).length,
543
+ lastAt: rows.length > 0 ? rows[0].at : null
544
+ }
545
+ }
546
+ }
547
+
548
+ const backendView = () => ({ kind: backend.kind })
549
+
550
+ const engineAdapterKind =
551
+ typeof engineInfo.kind === "string" && engineInfo.kind.length > 0 ? engineInfo.kind : backend.kind
552
+ const engineAdapter = () => ({
553
+ kind: engineAdapterKind,
554
+ label: typeof engineInfo.label === "string" ? engineInfo.label : engineAdapterKind,
555
+ version: typeof engineInfo.version === "string" ? engineInfo.version : "unknown",
556
+ adapters: [
557
+ { id: "omlx", label: "oMLX", current: engineAdapterKind === "omlx", enabled: engineAdapterKind === "omlx" },
558
+ { id: "mtplx", label: "mtplx", current: engineAdapterKind === "mtplx", enabled: engineAdapterKind === "mtplx" },
559
+ {
560
+ id: "mlx-serve",
561
+ label: "mlx-serve",
562
+ current: engineAdapterKind === "mlx-serve",
563
+ enabled: engineAdapterKind === "mlx-serve"
564
+ }
565
+ ]
566
+ })
567
+
568
+ const engineConnection = () => {
569
+ if (getConnection !== null) {
570
+ const live = getConnection()
571
+ if (isRecord(live)) {
572
+ const keyPresent = live.keyPresent === true
573
+ return {
574
+ endpoint: typeof live.endpoint === "string" ? live.endpoint : "",
575
+ authKind: live.authKind === "none" ? "none" : "bearer",
576
+ keyPresent,
577
+ keyHint: keyPresent ? "••••••••••" : "",
578
+ source: live.source === "config" || live.source === "environment" ? live.source : "default"
579
+ }
580
+ }
581
+ }
582
+ return {
583
+ endpoint: typeof engineInfo.endpoint === "string" ? engineInfo.endpoint : "",
584
+ authKind: engineInfo.authKind === "none" ? "none" : "bearer",
585
+ keyPresent: engineInfo.keyPresent === true,
586
+ keyHint: engineInfo.keyPresent === true ? "••••••••••" : "",
587
+ source:
588
+ engineInfo.source === "config" || engineInfo.source === "environment" ? engineInfo.source : "default"
589
+ }
590
+ }
591
+
592
+ const engineHealth = (model) => {
593
+ if (model.telemetry.error !== null) {
594
+ return {
595
+ status: "unreachable",
596
+ httpStatus: model.telemetry.error.status,
597
+ latencyMs: null,
598
+ checkedAt: model.telemetry.readAt,
599
+ message: model.telemetry.error.message
600
+ }
601
+ }
602
+ if (model.telemetry.snapshot !== null) {
603
+ return {
604
+ status: "healthy",
605
+ httpStatus: 200,
606
+ latencyMs: null,
607
+ checkedAt: model.telemetry.readAt ?? model.telemetry.snapshot.fetchedAt,
608
+ message: null
609
+ }
610
+ }
611
+ return { status: "unknown", httpStatus: null, latencyMs: null, checkedAt: null, message: null }
612
+ }
613
+
614
+ const engine = () => {
615
+ const model = evidence()
616
+ const snapshot = model.telemetry.snapshot
617
+ const engineCapabilities = getModelCapabilities !== null ? getModelCapabilities() : null
618
+ const models =
619
+ snapshot === null
620
+ ? []
621
+ : snapshot.residentModels.map((id) => ({
622
+ id,
623
+ default: id === snapshot.preferredModel,
624
+ loaded: true
625
+ }))
626
+ return {
627
+ kind: "engine",
628
+ backend: backendView(),
629
+ adapter: engineAdapter(),
630
+ connection: engineConnection(),
631
+ health: engineHealth(model),
632
+ models,
633
+ capabilities:
634
+ engineCapabilities !== null && isRecord(engineCapabilities.report) ? engineCapabilities.report : null,
635
+ discovery: { discovered: models.length, resident: models.length },
636
+ config: {
637
+ writable: true,
638
+ note: "Connection endpoint and API key can be updated; the adapter kind is fixed by the profile."
639
+ },
640
+ evidence: model
641
+ }
642
+ }
643
+
644
+ /** Cheap liveness payload; deliberately does not build the full model twice. */
645
+ const health = () => {
646
+ const model = evidence()
647
+ const capabilityData = getModelCapabilities !== null ? getModelCapabilities() : null
648
+ const capabilityReport =
649
+ capabilityData !== null && isRecord(capabilityData.report) ? capabilityData.report : null
650
+ const drift = capabilityReport !== null ? capabilityReport.drift : null
651
+ return {
652
+ ok: true,
653
+ name: "router",
654
+ ...(buildId === null ? {} : { buildId }),
655
+ now: model.fetchedAt,
656
+ backend: backendView(),
657
+ policyRev: model.policy.rev,
658
+ ledgerRows: model.ledger.rows.length,
659
+ telemetry: telemetryState(model),
660
+ staleAt: model.staleAt,
661
+ capabilities:
662
+ capabilityReport === null
663
+ ? null
664
+ : {
665
+ sources: capabilityReport.sources ?? {},
666
+ advertised: capabilityReport.advertised ?? 0,
667
+ excluded: Array.isArray(capabilityReport.excluded) ? capabilityReport.excluded.length : 0,
668
+ drift: drift !== null && drift !== undefined,
669
+ driftKeys:
670
+ drift !== null && drift !== undefined && Array.isArray(drift.missingKeys) ? drift.missingKeys : []
671
+ },
672
+ routing: {
673
+ enabled: typeof runtime.isEnabled === "function" ? runtime.isEnabled() : false
674
+ }
675
+ }
676
+ }
677
+
678
+ const models = () => {
679
+ const model = evidence()
680
+ return { kind: "models", backend: backendView(), evidence: model, view: modelsView(model) }
681
+ }
682
+
683
+ const routing = () => {
684
+ const model = evidence()
685
+ return { kind: "routing", backend: backendView(), evidence: model, view: routingView(model) }
686
+ }
687
+
688
+ const activity = () => {
689
+ const model = evidence()
690
+ return { kind: "activity", backend: backendView(), evidence: model, view: activityView(model) }
691
+ }
692
+
693
+ return {
694
+ backend: backendView(),
695
+ evidence,
696
+ health,
697
+ models,
698
+ routing,
699
+ overview,
700
+ activity,
701
+ engine,
702
+ probe,
703
+ // The overview projection's freshness key: a settings write moves the rev,
704
+ // and the handler rebuilds instead of serving the up-to-10s-old body.
705
+ settingsRev,
706
+ telemetryState: () => telemetryState(evidence())
707
+ }
708
+ }
709
+
710
+ // Deterministic strong-ish ETag for a JSON projection (djb2).
711
+ const etagOf = (value) => {
712
+ const text = JSON.stringify(value)
713
+ let hash = 5381
714
+ for (let index = 0; index < text.length; index += 1) {
715
+ hash = ((hash << 5) + hash) ^ text.charCodeAt(index)
716
+ }
717
+ return '"' + (hash >>> 0).toString(16) + '"'
718
+ }
719
+
720
+ const jsonHeaders = (auth, body) => ({
721
+ "content-type": "application/json; charset=utf-8",
722
+ "cache-control": "no-store",
723
+ "content-length": String(Buffer.byteLength(body)),
724
+ [AUTH_HEADER]: auth.label()
725
+ })
726
+
727
+ const writeJson = (res, status, auth, value, head = false) => {
728
+ const body = JSON.stringify(value)
729
+ res.writeHead(status, jsonHeaders(auth, body))
730
+ res.end(head ? undefined : body)
731
+ }
732
+
733
+ const writeText = (res, status, auth, text, extraHeaders = {}) => {
734
+ res.writeHead(status, {
735
+ "content-type": "text/plain; charset=utf-8",
736
+ "cache-control": "no-store",
737
+ "content-length": String(Buffer.byteLength(text)),
738
+ [AUTH_HEADER]: auth.label(),
739
+ ...extraHeaders
740
+ })
741
+ res.end(text)
742
+ }
743
+
744
+ const wantsProbe = (req) => {
745
+ try {
746
+ return new URL(req.url ?? "/", "http://router.local").searchParams.get("probe") === "1"
747
+ } catch {
748
+ return false
749
+ }
750
+ }
751
+
752
+ // Read a JSON request body from a node:http IncomingMessage. Tests may pass a
753
+ // pre-parsed object on req.body instead of simulating the stream.
754
+ const readJsonBody = (req, limit = 16_384) => {
755
+ if (req.body !== undefined && typeof req.body === "object" && req.body !== null) {
756
+ return Promise.resolve(req.body)
757
+ }
758
+ return new Promise((resolve, reject) => {
759
+ const chunks = []
760
+ let total = 0
761
+ req.on("data", (chunk) => {
762
+ total += chunk.length
763
+ if (total > limit) {
764
+ const error = new Error("request body too large")
765
+ error.code = "PAYLOAD_TOO_LARGE"
766
+ reject(error)
767
+ return
768
+ }
769
+ chunks.push(chunk)
770
+ })
771
+ req.on("end", () => {
772
+ try {
773
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"))
774
+ } catch (error) {
775
+ reject(error)
776
+ }
777
+ })
778
+ req.on("error", reject)
779
+ })
780
+ }
781
+
782
+ const createHandler = (build, auth) => async (req, res) => {
783
+ if (req.method !== "GET" && req.method !== "HEAD") {
784
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
785
+ return
786
+ }
787
+ if (auth.reject !== null) {
788
+ let rejection
789
+ try {
790
+ rejection = auth.reject(req)
791
+ } catch {
792
+ rejection = 403
793
+ }
794
+ if (rejection === 401 || rejection === 403) {
795
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
796
+ return
797
+ }
798
+ }
799
+ let payload
800
+ try {
801
+ payload = await build(req)
802
+ } catch {
803
+ writeJson(res, 500, auth, {
804
+ ok: false,
805
+ error: { kind: "internal", message: "evidence unavailable" }
806
+ })
807
+ return
808
+ }
809
+ writeJson(res, 200, auth, payload, req.method === "HEAD")
810
+ }
811
+
812
+ /**
813
+ * Compose the ctx.webServer registrations for the evidence routes.
814
+ * `options.authorize` is `(req) => 401 | 403 | undefined`; when it is omitted the
815
+ * routes answer without authentication and the response says so.
816
+ */
817
+ export function createRouterRoutes(adapter, options = {}) {
818
+ if (adapter === undefined || typeof adapter.health !== "function") {
819
+ throw new TypeError("createRouterRoutes needs an evidence adapter")
820
+ }
821
+ const reject = typeof options.authorize === "function" ? options.authorize : null
822
+ const label =
823
+ typeof options.authLabel === "function"
824
+ ? options.authLabel
825
+ : () => (reject === null ? "unauthenticated" : "connection")
826
+ const auth = { reject, label }
827
+ const onSave = typeof options.onSave === "function" ? options.onSave : null
828
+ const onToggle = typeof options.onToggle === "function" ? options.onToggle : null
829
+ const onSettingsGet = typeof options.onSettingsGet === "function" ? options.onSettingsGet : null
830
+ const onSettingsSave = typeof options.onSettingsSave === "function" ? options.onSettingsSave : null
831
+
832
+ const rejectRequest = (req, res) => {
833
+ if (auth.reject === null) return false
834
+ let rejection
835
+ try {
836
+ rejection = auth.reject(req)
837
+ } catch {
838
+ rejection = 403
839
+ }
840
+ if (rejection === 401 || rejection === 403) {
841
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
842
+ return true
843
+ }
844
+ return false
845
+ }
846
+
847
+ const routingHandler = async (req, res) => {
848
+ if (req.method === "POST") {
849
+ if (rejectRequest(req, res)) return
850
+ if (onToggle === null) {
851
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
852
+ return
853
+ }
854
+ let body
855
+ try {
856
+ body = await readJsonBody(req)
857
+ } catch {
858
+ writeJson(res, 400, auth, { ok: false, error: { field: "body", message: "invalid JSON body" } })
859
+ return
860
+ }
861
+ let result
862
+ try {
863
+ result = await onToggle(body)
864
+ } catch {
865
+ writeJson(res, 500, auth, { ok: false, error: { field: "routing", message: "could not update routing" } })
866
+ return
867
+ }
868
+ if (result.ok === true) {
869
+ writeJson(res, 200, auth, result.payload)
870
+ } else {
871
+ writeJson(res, result.status ?? 400, auth, { ok: false, error: result.error ?? { field: "routing", message: "invalid routing toggle" } })
872
+ }
873
+ return
874
+ }
875
+ await createHandler(() => adapter.routing(), auth)(req, res)
876
+ }
877
+
878
+ const engineHandler = async (req, res) => {
879
+ if (req.method === "POST") {
880
+ if (auth.reject !== null) {
881
+ let rejection
882
+ try {
883
+ rejection = auth.reject(req)
884
+ } catch {
885
+ rejection = 403
886
+ }
887
+ if (rejection === 401 || rejection === 403) {
888
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
889
+ return
890
+ }
891
+ }
892
+ if (onSave === null) {
893
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
894
+ return
895
+ }
896
+ let body
897
+ try {
898
+ body = await readJsonBody(req)
899
+ } catch {
900
+ writeJson(res, 400, auth, { ok: false, error: { field: "body", message: "invalid JSON body" } })
901
+ return
902
+ }
903
+ let result
904
+ try {
905
+ result = await onSave(body)
906
+ } catch {
907
+ writeJson(res, 500, auth, { ok: false, error: { field: "engine", message: "could not save connection" } })
908
+ return
909
+ }
910
+ if (result.ok === true) {
911
+ writeJson(res, 200, auth, result.payload)
912
+ } else {
913
+ writeJson(res, result.status ?? 400, auth, { ok: false, error: result.error ?? { field: "engine", message: "invalid connection" } })
914
+ }
915
+ return
916
+ }
917
+ await createHandler(
918
+ async (request) => {
919
+ if (wantsProbe(request) && typeof adapter.probe === "function") {
920
+ await adapter.probe()
921
+ }
922
+ return adapter.engine()
923
+ },
924
+ auth
925
+ )(req, res)
926
+ }
927
+
928
+ // S5 operational defaults: GET/PUT with If-Match; the policy sentence is never written here.
929
+ const settingsHandler = async (req, res) => {
930
+ if (rejectRequest(req, res)) return
931
+ if (req.method === "GET" || req.method === "HEAD") {
932
+ const view =
933
+ onSettingsGet !== null
934
+ ? onSettingsGet()
935
+ : { endpoint: "", ledgerDir: "", pollSeconds: 2, advisory: false, version: 1 }
936
+ writeJson(res, 200, auth, view, req.method === "HEAD")
937
+ return
938
+ }
939
+ if (req.method !== "PUT") {
940
+ writeText(res, 405, auth, "", { allow: "GET, HEAD, PUT" })
941
+ return
942
+ }
943
+ if (onSettingsSave === null) {
944
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
945
+ return
946
+ }
947
+ let body
948
+ try {
949
+ body = await readJsonBody(req)
950
+ } catch {
951
+ writeJson(res, 400, auth, { ok: false, error: { field: "body", message: "invalid JSON body" } })
952
+ return
953
+ }
954
+ const result = await onSettingsSave(body, req.headers?.["if-match"])
955
+ if (result.ok === true) {
956
+ writeJson(res, 200, auth, result.payload)
957
+ return
958
+ }
959
+ if (result.status === 409) {
960
+ writeJson(res, 409, auth, result.payload)
961
+ return
962
+ }
963
+ writeJson(res, result.status ?? 400, auth, {
964
+ ok: false,
965
+ error: result.error ?? { field: "settings", message: "invalid settings" }
966
+ })
967
+ }
968
+
969
+ // S1 first-screen projection: ETag + 10s cache, 304 on a matching If-None-Match.
970
+ let overviewCache = null
971
+ const overviewHandler = (req, res) => {
972
+ if (req.method !== "GET" && req.method !== "HEAD") {
973
+ writeText(res, 405, auth, "", { allow: "GET, HEAD" })
974
+ return
975
+ }
976
+ if (auth.reject !== null) {
977
+ let rejection
978
+ try {
979
+ rejection = auth.reject(req)
980
+ } catch {
981
+ rejection = 403
982
+ }
983
+ if (rejection === 401 || rejection === 403) {
984
+ writeText(res, rejection, auth, rejection === 401 ? "unauthorized" : "forbidden")
985
+ return
986
+ }
987
+ }
988
+ const nowMs = Date.now()
989
+ // The settings rev is the projection's freshness key: a save on either page
990
+ // moves it, so the next read is rebuilt instead of served from the cache.
991
+ const revNow = typeof adapter.settingsRev === "function" ? adapter.settingsRev() : null
992
+ if (overviewCache === null || nowMs - overviewCache.at > 10_000 || overviewCache.settingsRev !== revNow) {
993
+ const body = adapter.overview()
994
+ overviewCache = { at: nowMs, body, etag: etagOf(body), settingsRev: revNow }
995
+ }
996
+ const ifNoneMatch = req?.headers?.["if-none-match"]
997
+ if (typeof ifNoneMatch === "string" && ifNoneMatch === overviewCache.etag) {
998
+ res.writeHead(304, { etag: overviewCache.etag, [AUTH_HEADER]: auth.label() })
999
+ res.end()
1000
+ return
1001
+ }
1002
+ const body = JSON.stringify(overviewCache.body)
1003
+ res.writeHead(200, { ...jsonHeaders(auth, body), etag: overviewCache.etag })
1004
+ res.end(req.method === "HEAD" ? undefined : body)
1005
+ }
1006
+
1007
+ return [
1008
+ { kind: "exact", path: EVIDENCE_ROUTES.health, handler: createHandler(() => adapter.health(), auth) },
1009
+ { kind: "exact", path: EVIDENCE_ROUTES.models, handler: createHandler(() => adapter.models(), auth) },
1010
+ { kind: "exact", path: EVIDENCE_ROUTES.routing, handler: routingHandler },
1011
+ { kind: "exact", path: EVIDENCE_ROUTES.activity, handler: createHandler(() => adapter.activity(), auth) },
1012
+ { kind: "exact", path: EVIDENCE_ROUTES.engine, handler: engineHandler },
1013
+ { kind: "exact", path: EVIDENCE_ROUTES.overview, handler: overviewHandler },
1014
+ { kind: "exact", path: EVIDENCE_ROUTES.settings, handler: settingsHandler }
1015
+ ]
1016
+ }