@try-works/dsh-minimal-router 0.2.10 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -24,6 +24,7 @@ import { createRouteApplication, createRouteMapper, DEFAULT_LOCAL_PROVIDERS } fr
24
24
  import { createEngineAdapter, ROLE_PROVIDER_IDS } from "./engine-adapter.js"
25
25
  import { createCapabilitySync } from "./capability-sync.js"
26
26
  import { createLocalBackend } from "./backend.js"
27
+ import { selectEngineSource } from "./engines/select.js"
27
28
  import { BELOW_FLOOR_REPROBE_MS, createSpeedProber, DEFAULT_OMLX_BASE_URL, SPEED_SAMPLE_TTL_MS } from "./telemetry.js"
28
29
  import {
29
30
  AUTH_HEADER,
@@ -491,7 +492,10 @@ export function apply(ctx, config = {}) {
491
492
  speedProberInstance = createSpeedProber({
492
493
  baseUrl: connection.endpoint,
493
494
  apiKey: effectiveApiKey(),
494
- now: config.now
495
+ now: config.now,
496
+ // Run 39: the probe reads the active engine's own timing field through the
497
+ // source, so both engines feed one sample store (DEC-39-04).
498
+ speedOf: activeEngineSource()?.speedOf
495
499
  })
496
500
  return speedProberInstance
497
501
  }
@@ -547,13 +551,36 @@ export function apply(ctx, config = {}) {
547
551
  } catch {}
548
552
  return floors.length === 0 ? 0 : Math.max(...floors)
549
553
  }
554
+ // Run 39 (DEC-39-01/02): ONE active engine source for the whole host, chosen from
555
+ // the connection kind. Everything engine-specific - the adapter's speed and
556
+ // observation reads, the probe, the engine label - goes through it, so a second
557
+ // engine cannot drift into a parallel path.
558
+ let engineSourceInstance = null
559
+ const activeEngineSource = () => {
560
+ if (engineSourceInstance !== null) return engineSourceInstance
561
+ try {
562
+ const selected = selectEngineSource(
563
+ { kind: backendKind, endpoint: connection.endpoint, apiKey: effectiveApiKey() },
564
+ {
565
+ getConnection: () => ({ kind: backendKind, endpoint: connection.endpoint, apiKey: effectiveApiKey() }),
566
+ now: config.now
567
+ }
568
+ )
569
+ engineSourceInstance = selected.source
570
+ } catch {
571
+ engineSourceInstance = null
572
+ }
573
+ return engineSourceInstance
574
+ }
550
575
  const buildLocalRead = () =>
551
576
  createLocalBackend({
552
577
  kind: backendKind,
553
578
  baseUrl: connection.endpoint,
554
579
  apiKey: effectiveApiKey(),
555
580
  timeoutMs: config.timeoutMs,
556
- retries: config.retries
581
+ retries: config.retries,
582
+ fetchImpl: config.fetchImpl,
583
+ now: config.now
557
584
  }).read
558
585
  const backend =
559
586
  config.backend ??
@@ -856,6 +883,22 @@ export function apply(ctx, config = {}) {
856
883
  // DEC-37-12: every proxied request also forwards its engine id and token/timing
857
884
  // usage; the host joins it onto the issuing session's ledger row.
858
885
  onRequestObserved: handleRequestObserved,
886
+ // Run 39: the active engine source owns the speed and observation reads, so
887
+ // mlx-serve's timings and oMLX's usage land in the same sample store.
888
+ speedOf: (body, usage) => {
889
+ try {
890
+ return activeEngineSource()?.speedOf(body, usage) ?? null
891
+ } catch {
892
+ return null
893
+ }
894
+ },
895
+ observationOfRequest: (body, usage) => {
896
+ try {
897
+ return activeEngineSource()?.observationOf?.(body, usage) ?? null
898
+ } catch {
899
+ return null
900
+ }
901
+ },
859
902
  getConnection: () => connection,
860
903
  // Injectable transport so a test can serve the engine surfaces without a
861
904
  // live engine; production leaves it undefined and uses global fetch.
@@ -1247,6 +1290,48 @@ export function apply(ctx, config = {}) {
1247
1290
  } catch {}
1248
1291
  return null
1249
1292
  }
1293
+ // Run 40 (R-40-01): the two files the Telemetry series are computed from. The
1294
+ // read is bounded and tolerant: a missing or unreadable file is reported with
1295
+ // its reason so the page can say what is missing instead of drawing zeroes.
1296
+ const TELEMETRY_MAX_ROWS = 20_000
1297
+ const readJsonlRows = (file) => {
1298
+ try {
1299
+ if (!fs.existsSync(file)) return { rows: [], error: null, missing: true }
1300
+ const text = fs.readFileSync(file, "utf8")
1301
+ const lines = text.split("\n").filter((line) => line.trim() !== "")
1302
+ const kept = lines.length > TELEMETRY_MAX_ROWS ? lines.slice(lines.length - TELEMETRY_MAX_ROWS) : lines
1303
+ const rows = []
1304
+ for (const line of kept) {
1305
+ try {
1306
+ const parsed = JSON.parse(line)
1307
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) rows.push(parsed)
1308
+ } catch {}
1309
+ }
1310
+ return { rows, error: null, missing: false }
1311
+ } catch (error) {
1312
+ return { rows: [], error: error?.message ?? "unreadable", missing: false }
1313
+ }
1314
+ }
1315
+ const readTelemetrySources = () => {
1316
+ const ledgerRead = readJsonlRows(ledgerFile)
1317
+ const observationsRead = readJsonlRows(observationsFile)
1318
+ return {
1319
+ ledger: ledgerRead.rows,
1320
+ observations: observationsRead.rows,
1321
+ sources: {
1322
+ ledger: ledgerRead.error !== null
1323
+ ? { available: false, reason: "ledger.jsonl is unreadable: " + ledgerRead.error }
1324
+ : ledgerRead.missing
1325
+ ? { available: false, reason: "ledger.jsonl does not exist yet" }
1326
+ : { available: true, reason: null },
1327
+ observations: observationsRead.error !== null
1328
+ ? { available: false, reason: "request-observations.jsonl is unreadable: " + observationsRead.error }
1329
+ : observationsRead.missing
1330
+ ? { available: false, reason: "request-observations.jsonl does not exist yet" }
1331
+ : { available: true, reason: null }
1332
+ }
1333
+ }
1334
+ }
1250
1335
  const evidenceAdapter = createEvidenceAdapter({
1251
1336
  buildId,
1252
1337
  runtime,
@@ -1258,6 +1343,7 @@ export function apply(ctx, config = {}) {
1258
1343
  // Run 37 F-37-12: join a historical ledger row to its recorded request
1259
1344
  // observation so Prefill and the oMLX join survive a restart.
1260
1345
  getObservations: observationsForRequest,
1346
+ getTelemetrySources: readTelemetrySources,
1261
1347
  // F-37-51: the Overview's sessions card reads the cached recent-session list.
1262
1348
  readSessions: () => recentSessionsCache,
1263
1349
  // DEC-37-09/14: the Overview's engine meter shows the fresh probe/measured
@@ -1283,9 +1369,15 @@ export function apply(ctx, config = {}) {
1283
1369
  typeof engineAdapter.capabilitiesReport === "function" ? engineAdapter.capabilitiesReport() : null
1284
1370
  }),
1285
1371
  engine: {
1372
+ // Run 39 (DEC-39-02): the engine fact names the ACTIVE engine. The label comes
1373
+ // from the selected source, so an mlx-serve install never reads "oMLX".
1286
1374
  kind: typeof backend.kind === "string" ? backend.kind : "omlx",
1287
- label: "oMLX",
1288
- version: config.backendVersion ?? "0.8.3"
1375
+ label: (() => {
1376
+ const source = activeEngineSource()
1377
+ if (source !== null && typeof source.label === "string") return source.label
1378
+ return typeof backend.kind === "string" && backend.kind !== "omlx" ? backend.kind : "oMLX"
1379
+ })(),
1380
+ version: config.backendVersion ?? (typeof backend.kind === "string" && backend.kind !== "omlx" ? "unknown" : "0.8.3")
1289
1381
  },
1290
1382
  getConnection: () => ({
1291
1383
  endpoint: connection.endpoint,
@@ -1544,6 +1636,18 @@ export function apply(ctx, config = {}) {
1544
1636
  noteTitleMiss(sessionId, tried)
1545
1637
  return null
1546
1638
  }
1639
+ // F-37-52 (Owner, 2026-12-06): live sessions reverted to hashed ids because the
1640
+ // title was only read from record.header.title. The session query's record shape
1641
+ // has moved before, so read the title from every known place before falling back
1642
+ // to the id tail - a shortened id is the last resort, never the first.
1643
+ const titleFromSessionRecord = (record) => {
1644
+ const header = record !== null && typeof record === "object" ? record.header ?? {} : {}
1645
+ const candidates = [header.title, header.name, header.summary, record?.title, record?.name]
1646
+ for (const candidate of candidates) {
1647
+ if (typeof candidate === "string" && candidate.trim().length > 0) return candidate.trim()
1648
+ }
1649
+ return null
1650
+ }
1547
1651
  const recentSessionRouting = async () => {
1548
1652
  const limit = 5
1549
1653
  const entries = []
@@ -1566,8 +1670,8 @@ export function apply(ctx, config = {}) {
1566
1670
  for (const record of Array.isArray(records) ? records : []) {
1567
1671
  const header = record?.header ?? {}
1568
1672
  const at = Number.isFinite(header.updatedAt) ? header.updatedAt : header.createdAt
1569
- const headerTitle = typeof header.title === "string" && header.title.length > 0 ? header.title : null
1570
- push(header.id, headerTitle ?? titleOfSession(header.id), at, record?.live === true)
1673
+ const headerId = typeof header.id === "string" && header.id.length > 0 ? header.id : record?.id
1674
+ push(headerId, titleFromSessionRecord(record) ?? titleOfSession(headerId), at, record?.live === true)
1571
1675
  if (entries.length >= limit) break
1572
1676
  }
1573
1677
  }
package/lib/routing.js CHANGED
@@ -324,16 +324,24 @@ const localGateFailure = (candidate, telemetry, floorTps, speedFor, evidence, lo
324
324
  ceilingBlocked: true
325
325
  }
326
326
  }
327
- if (typeof telemetry.headroomRatio !== "number" || !Number.isFinite(telemetry.headroomRatio)) {
328
- return { gate: "headroom", reason: "local memory headroom is unknown" }
329
- }
330
- if (telemetry.headroomRatio < MIN_HEADROOM_RATIO) {
327
+ // Run 39 (DEC-39-05): a null headroom means the engine has no memory view at all
328
+ // (mlx-serve without --metrics). That is not a violation: the candidate carries on
329
+ // and the decision records the unknown, exactly as the ceiling and floor gates
330
+ // still apply. Coercing it to 0 would look measured and skip local forever.
331
+ const headroomUnknown =
332
+ telemetry.headroomRatio === null || typeof telemetry.headroomRatio !== "number" || !Number.isFinite(telemetry.headroomRatio)
333
+ if (!headroomUnknown && telemetry.headroomRatio < MIN_HEADROOM_RATIO) {
331
334
  return {
332
335
  gate: "headroom",
333
336
  reason: `local memory headroom ${formatPercent(telemetry.headroomRatio)} is below ${formatPercent(MIN_HEADROOM_RATIO)}`
334
337
  }
335
338
  }
336
- if (telemetry.pressureLevel !== "ok") {
339
+ // DEC-39-05: the unknown is recorded on the decision, not swallowed.
340
+ evidence.memoryUnknown = headroomUnknown
341
+ // Run 39 (DEC-39-05): null pressure means the engine cannot report it, so the
342
+ // pressure gate is skipped (the reason is already on the headroom line) rather
343
+ // than treating "unknown" as a violation.
344
+ if (telemetry.pressureLevel !== null && telemetry.pressureLevel !== "ok") {
337
345
  return { gate: "headroom", reason: `local memory pressure is ${telemetry.pressureLevel}` }
338
346
  }
339
347
  const speed = resolveFloorSpeed(candidate.model, telemetry, speedFor)
@@ -451,9 +459,11 @@ export const decide = (policy, telemetry, context = {}) => {
451
459
  continue
452
460
  }
453
461
  const trigger = skips.length === 0 ? null : skips[skips.length - 1]
454
- const met = evidence.contended
462
+ const floorLine = evidence.contended
455
463
  ? `local ${candidate.model} ${formatTpsValue(evidence.observedTps)} effective (${formatTpsValue(evidence.poolTps)} pool, ${evidence.activeLocalSessions} sessions) meets floor ${formatTps(floorTps)}`
456
464
  : `local ${candidate.model} ${formatTps(evidence.observedTps)} meets floor ${formatTps(floorTps)}`
465
+ // DEC-39-05: an engine with no memory view admits with the unknown recorded.
466
+ const met = evidence.memoryUnknown === true ? floorLine + " (headroom unknown: this engine reports no memory)" : floorLine
457
467
  return decisionOf({
458
468
  target: "local",
459
469
  provider: null,
@@ -579,9 +589,12 @@ export const isTelemetry = (telemetry) =>
579
589
  typeof telemetry === "object" &&
580
590
  (telemetry.observedTps === null ||
581
591
  (typeof telemetry.observedTps === "number" && Number.isFinite(telemetry.observedTps))) &&
582
- typeof telemetry.headroomRatio === "number" &&
583
- Number.isFinite(telemetry.headroomRatio) &&
584
- PRESSURE_LEVELS.includes(telemetry.pressureLevel) &&
592
+ // Run 39 (DEC-39-05): an engine without a memory view reports headroom and
593
+ // pressure as null. That is a fact ("unknown"), not malformed telemetry - the
594
+ // gates below decide what to do with it.
595
+ (telemetry.headroomRatio === null ||
596
+ (typeof telemetry.headroomRatio === "number" && Number.isFinite(telemetry.headroomRatio))) &&
597
+ (telemetry.pressureLevel === null || PRESSURE_LEVELS.includes(telemetry.pressureLevel)) &&
585
598
  Array.isArray(telemetry.residentModels) &&
586
599
  telemetry.residentModels.every((id) => typeof id === "string") &&
587
600
  (telemetry.preferredModel === null || typeof telemetry.preferredModel === "string")
@@ -0,0 +1,275 @@
1
+ // @dsh-local-router/plugin — telemetry series (run 40, DEC-40-02).
2
+ //
3
+ // Pure functions over ledger rows and request observations. The host reads the
4
+ // files; this module only counts. Every series is a fresh per-request
5
+ // observation, never an engine lifetime average (DEC-39-04), and a series that
6
+ // cannot be computed is returned as unavailable WITH a reason rather than as
7
+ // zeros or empty axes.
8
+ //
9
+ // Row shapes (read from the committed files, not assumed):
10
+ // ledger.jsonl { at, latencyMs, gate, decision, role, model, ... }
11
+ // request-observations.jsonl { observedAt, promptTokens, completionTokens, generationTps, model }
12
+
13
+ /** The approved ranges. 7d is the default (DEC-39-08 A3). */
14
+ export const TELEMETRY_RANGES = Object.freeze(["24h", "7d", "all"])
15
+ export const DEFAULT_RANGE = "7d"
16
+
17
+ const DAY_MS = 86_400_000
18
+ export const RANGE_MS = Object.freeze({ "24h": DAY_MS, "7d": 7 * DAY_MS, all: null })
19
+
20
+ // `all` is an explicit null span, so the lookup must not use ?? (which would
21
+ // treat null as missing and silently fall back to 7d, dropping older rows).
22
+ const spanOf = (range) =>
23
+ Object.prototype.hasOwnProperty.call(RANGE_MS, range) ? RANGE_MS[range] : RANGE_MS[DEFAULT_RANGE]
24
+
25
+ /** The speed floor, from the policy's floor gate. */
26
+ export const FLOOR_TPS = 30
27
+
28
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
29
+ const finite = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null)
30
+ const numeric = (value) => {
31
+ const n = finite(value) ?? (typeof value === "string" && value.trim() !== "" ? finite(Number(value)) : null)
32
+ return n
33
+ }
34
+ const msOf = (value) => {
35
+ if (typeof value === "number" && Number.isFinite(value)) return value
36
+ if (typeof value === "string" && value.length > 0) {
37
+ const parsed = Date.parse(value)
38
+ return Number.isNaN(parsed) ? null : parsed
39
+ }
40
+ return null
41
+ }
42
+
43
+ const quantile = (sorted, q) => {
44
+ if (sorted.length === 0) return null
45
+ const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))
46
+ return sorted[index]
47
+ }
48
+
49
+ const round = (value, digits = 1) => (value === null ? null : Number(value.toFixed(digits)))
50
+
51
+ /** Ledger rows inside the range, oldest first. */
52
+ export const rowsInRange = (rows, { range = DEFAULT_RANGE, now = Date.now() } = {}) => {
53
+ const list = Array.isArray(rows) ? rows.filter(isRecord) : []
54
+ const span = spanOf(range)
55
+ const kept = span === null ? list : list.filter((row) => {
56
+ const at = msOf(row.at)
57
+ return at !== null && at >= now - span
58
+ })
59
+ return kept.slice().sort((a, b) => (msOf(a.at) ?? 0) - (msOf(b.at) ?? 0))
60
+ }
61
+
62
+ /** Observations inside the range, oldest first. */
63
+ export const observationsInRange = (observations, { range = DEFAULT_RANGE, now = Date.now() } = {}) => {
64
+ const list = Array.isArray(observations) ? observations.filter(isRecord) : []
65
+ const span = spanOf(range)
66
+ const kept = span === null ? list : list.filter((row) => {
67
+ const at = msOf(row.observedAt)
68
+ return at !== null && at >= now - span
69
+ })
70
+ return kept.slice().sort((a, b) => (msOf(a.observedAt) ?? 0) - (msOf(b.observedAt) ?? 0))
71
+ }
72
+
73
+ /** Decode speed bands of 20 tps, from each request's own generationTps. */
74
+ export const speedBands = (observations, { binSize = 20, maxBins = 12 } = {}) => {
75
+ const speeds = observations.map((row) => numeric(row.generationTps)).filter((value) => value !== null && value > 0)
76
+ if (speeds.length === 0) {
77
+ return { available: false, reason: "no request carried a decode speed in this window", n: 0, bands: [] }
78
+ }
79
+ const bands = Array.from({ length: maxBins }, (_, i) => ({
80
+ band: `${i * binSize}-${(i + 1) * binSize}`,
81
+ from: i * binSize,
82
+ count: 0
83
+ }))
84
+ let over = 0
85
+ for (const speed of speeds) {
86
+ const index = Math.floor(speed / binSize)
87
+ if (index >= maxBins) over += 1
88
+ else bands[index].count += 1
89
+ }
90
+ const sorted = speeds.slice().sort((a, b) => a - b)
91
+ return {
92
+ available: true,
93
+ n: speeds.length,
94
+ bands,
95
+ over,
96
+ median: round(quantile(sorted, 0.5)),
97
+ p90: round(quantile(sorted, 0.9)),
98
+ max: round(sorted[sorted.length - 1]),
99
+ floor: FLOOR_TPS,
100
+ belowFloor: speeds.filter((speed) => speed < FLOOR_TPS).length
101
+ }
102
+ }
103
+
104
+ const PROMPT_BANDS = [
105
+ { band: "<=16k", from: 0, to: 16_384 },
106
+ { band: "<=32k", from: 16_384, to: 32_768 },
107
+ { band: "<=48k", from: 32_768, to: 49_152 },
108
+ { band: "<=64k", from: 49_152, to: 65_536 },
109
+ { band: "<=80k", from: 65_536, to: 81_920 },
110
+ { band: "<=128k", from: 81_920, to: 131_072 }
111
+ ]
112
+
113
+ /** Prompt-token bands, from each request's promptTokens. */
114
+ export const promptBands = (observations) => {
115
+ const tokens = observations.map((row) => numeric(row.promptTokens)).filter((value) => value !== null && value > 0)
116
+ if (tokens.length === 0) {
117
+ return { available: false, reason: "no request reported its prompt size in this window", n: 0, bands: [] }
118
+ }
119
+ const bands = PROMPT_BANDS.map((entry) => ({ ...entry, count: 0 }))
120
+ let over = 0
121
+ for (const value of tokens) {
122
+ const band = bands.find((entry) => value > entry.from && value <= entry.to)
123
+ if (band === undefined) over += 1
124
+ else band.count += 1
125
+ }
126
+ const sorted = tokens.slice().sort((a, b) => a - b)
127
+ return {
128
+ available: true,
129
+ n: tokens.length,
130
+ bands: bands.map(({ band, count }) => ({ band, count })),
131
+ over,
132
+ median: Math.round(quantile(sorted, 0.5)),
133
+ p90: Math.round(quantile(sorted, 0.9)),
134
+ max: sorted[sorted.length - 1],
135
+ window: 131_072
136
+ }
137
+ }
138
+
139
+ /** Gate attribution: which gate ended each decision. */
140
+ export const gateCounts = (ledgerRows) => {
141
+ const counts = new Map()
142
+ for (const row of ledgerRows) {
143
+ if (typeof row.gate !== "string" || row.gate.length === 0) continue
144
+ counts.set(row.gate, (counts.get(row.gate) ?? 0) + 1)
145
+ }
146
+ if (counts.size === 0) {
147
+ return { available: false, reason: "no decision in this window recorded its gate", total: 0, gates: [] }
148
+ }
149
+ const total = [...counts.values()].reduce((sum, value) => sum + value, 0)
150
+ const gates = [...counts.entries()]
151
+ .map(([gate, count]) => ({ gate, count }))
152
+ .sort((a, b) => b.count - a.count)
153
+ return { available: true, total, gates }
154
+ }
155
+
156
+ /** The router's own decision cost, in ms. */
157
+ export const decisionLatency = (ledgerRows) => {
158
+ const values = ledgerRows.map((row) => numeric(row.latencyMs)).filter((value) => value !== null && value >= 0)
159
+ if (values.length === 0) {
160
+ return { available: false, reason: "no decision recorded its latency in this window", n: 0 }
161
+ }
162
+ const sorted = values.slice().sort((a, b) => a - b)
163
+ return {
164
+ available: true,
165
+ n: sorted.length,
166
+ p50: Math.round(quantile(sorted, 0.5)),
167
+ p90: Math.round(quantile(sorted, 0.9)),
168
+ p99: Math.round(quantile(sorted, 0.99)),
169
+ max: Math.round(sorted[sorted.length - 1])
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Decisions per hour over the window, oldest hour first. Hours with no
175
+ * decisions are kept with count 0 and a `quiet` flag so a reader can see the
176
+ * shape of the day; a chart may omit them but must not present them as traffic.
177
+ */
178
+ export const trafficPerHour = (ledgerRows, { range = DEFAULT_RANGE, now = Date.now() } = {}) => {
179
+ const span = spanOf(range)
180
+ const hours = span === null ? 24 : Math.max(1, Math.round(span / 3_600_000))
181
+ if (ledgerRows.length === 0) {
182
+ return { available: false, reason: "no decision in this window", hours: [], busiest: null }
183
+ }
184
+ const buckets = new Array(hours).fill(0)
185
+ const end = new Date(now)
186
+ end.setMinutes(0, 0, 0)
187
+ const endMs = end.getTime()
188
+ for (const row of ledgerRows) {
189
+ const at = msOf(row.at)
190
+ if (at === null) continue
191
+ const index = hours - 1 - Math.floor((endMs - at) / 3_600_000)
192
+ if (index >= 0 && index < hours) buckets[index] += 1
193
+ }
194
+ const series = buckets.map((count, index) => ({
195
+ hour: new Date(endMs - (hours - 1 - index) * 3_600_000).toISOString().slice(0, 13) + ":00",
196
+ count,
197
+ quiet: count === 0
198
+ }))
199
+ const busiest = series.reduce((best, entry) => (entry.count > (best?.count ?? -1) ? entry : best), null)
200
+ return { available: true, hours: series, busiest, quiet: series.filter((entry) => entry.quiet).length }
201
+ }
202
+
203
+ /**
204
+ * The scatter: prompt size against decode speed, one point per request that
205
+ * reported both. Sampled to at most `limit` points by even stride so the shape
206
+ * survives and the card stays legible (DEC-39-08 A7).
207
+ */
208
+ export const speedVsContext = (observations, { limit = 48 } = {}) => {
209
+ const pairs = observations
210
+ .map((row) => ({ promptTokens: numeric(row.promptTokens), tps: numeric(row.generationTps), model: row.model ?? null }))
211
+ .filter((point) => point.promptTokens !== null && point.promptTokens > 0 && point.tps !== null && point.tps > 0)
212
+ if (pairs.length === 0) {
213
+ return { available: false, reason: "no request reported both a prompt size and a decode speed", n: 0, points: [] }
214
+ }
215
+ const stride = Math.max(1, Math.ceil(pairs.length / limit))
216
+ const points = pairs.filter((_, index) => index % stride === 0).slice(0, limit)
217
+ return {
218
+ available: true,
219
+ n: pairs.length,
220
+ plotted: points.length,
221
+ points,
222
+ floor: FLOOR_TPS,
223
+ xMax: 131_072
224
+ }
225
+ }
226
+
227
+ /** The four approved KPIs. */
228
+ export const kpis = (ledgerRows, observations, { remoteShare } = {}) => {
229
+ const speed = speedBands(observations)
230
+ const latency = decisionLatency(ledgerRows)
231
+ const remote = typeof remoteShare === "number"
232
+ ? remoteShare
233
+ : ledgerRows.length === 0
234
+ ? null
235
+ : round((ledgerRows.filter((row) => row.decision === "remote").length / ledgerRows.length) * 100, 0)
236
+ return {
237
+ medianDecodeTps: speed.available ? speed.median : null,
238
+ p90DecodeTps: speed.available ? speed.p90 : null,
239
+ remoteShare: remote,
240
+ medianDecisionMs: latency.available ? latency.p50 : null,
241
+ p99DecisionMs: latency.available ? latency.p99 : null,
242
+ observations: observations.length,
243
+ decisions: ledgerRows.length,
244
+ unavailable: [
245
+ ...(speed.available ? [] : ["medianDecodeTps", "p90DecodeTps"]),
246
+ ...(latency.available ? [] : ["medianDecisionMs", "p99DecisionMs"]),
247
+ ...(remote === null ? ["remoteShare"] : [])
248
+ ]
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Assemble the whole payload. `sources` says whether the host could read each
254
+ * file at all; a missing file is unavailable with a reason, never empty data.
255
+ */
256
+ export const buildTelemetrySeries = ({ ledger = [], observations = [], range = DEFAULT_RANGE, now = Date.now(), sources = {} } = {}) => {
257
+ const ledgerRows = rowsInRange(ledger, { range, now })
258
+ const obsRows = observationsInRange(observations, { range, now })
259
+ return {
260
+ range: TELEMETRY_RANGES.includes(range) ? range : DEFAULT_RANGE,
261
+ windowStart: RANGE_MS[range] === null || RANGE_MS[range] === undefined ? null : new Date(now - RANGE_MS[range]).toISOString(),
262
+ fetchedAt: new Date(now).toISOString(),
263
+ sources: {
264
+ ledger: sources.ledger ?? { available: true, reason: null },
265
+ observations: sources.observations ?? { available: true, reason: null }
266
+ },
267
+ kpis: kpis(ledgerRows, obsRows),
268
+ speed: speedBands(obsRows),
269
+ prompt: promptBands(obsRows),
270
+ gates: gateCounts(ledgerRows),
271
+ latency: decisionLatency(ledgerRows),
272
+ traffic: trafficPerHour(ledgerRows, { range, now }),
273
+ scatter: speedVsContext(obsRows)
274
+ }
275
+ }
package/lib/telemetry.js CHANGED
@@ -662,7 +662,7 @@ const deltaHasTokens = (delta) => {
662
662
  * stream:true and sent a non-SSE body accumulates its text here so the caller
663
663
  * can fall back to JSON parsing.
664
664
  */
665
- const readSseStream = async (stream, now) => {
665
+ const readSseStream = async (stream, now, speedOf = null) => {
666
666
  const state = { text: "", content: "", firstDeltaAt: null, finishAt: null, usageTokens: null }
667
667
  const decoder = new TextDecoder()
668
668
  let buffer = ""
@@ -700,7 +700,12 @@ const readSseStream = async (stream, now) => {
700
700
  }
701
701
  // The engine reports the decode-only speed of this very request; prefer it over
702
702
  // our own delta window, which is sensitive to a short completion.
703
- const reportedTps = payload?.usage?.generation_tokens_per_second
703
+ const reportedTps =
704
+ typeof speedOf === "function"
705
+ ? speedOf(payload, payload?.usage)?.generationTps
706
+ : Number.isFinite(Number(payload?.usage?.generation_tokens_per_second))
707
+ ? Number(payload.usage.generation_tokens_per_second)
708
+ : null
704
709
  if (typeof reportedTps === "number" && Number.isFinite(reportedTps) && reportedTps > 0) {
705
710
  state.reportedTps = reportedTps
706
711
  }
@@ -730,6 +735,16 @@ const readSseStream = async (stream, now) => {
730
735
  * timeout and returns the sample or a typed error; it never throws.
731
736
  */
732
737
  export const createModelProbe = (options = {}) => {
738
+ // Run 39 (DEC-39-04): the engine's own timing field is read through the active
739
+ // source (oMLX: usage.generation_tokens_per_second, mlx-serve:
740
+ // timings.predicted_per_second), so the probe never names a wire shape.
741
+ const speedOf =
742
+ typeof options.speedOf === "function"
743
+ ? options.speedOf
744
+ : (body, usage) => ({
745
+ generationTps:
746
+ Number.isFinite(Number(usage?.generation_tokens_per_second)) ? Number(usage.generation_tokens_per_second) : null
747
+ })
733
748
  const base = probeBaseUrl(options.baseUrl)
734
749
  const request = options.request ?? probeFetch
735
750
  const now = options.now ?? (() => new Date())
@@ -798,7 +813,7 @@ export const createModelProbe = (options = {}) => {
798
813
  let sse = null
799
814
  let text = null
800
815
  if (isAsyncIterable(stream)) {
801
- const reading = readSseStream(stream, now)
816
+ const reading = readSseStream(stream, now, speedOf)
802
817
  reading.catch(() => {})
803
818
  sse = await Promise.race([reading, deadline])
804
819
  text = sse.text
@@ -863,6 +878,16 @@ export const createModelProbe = (options = {}) => {
863
878
  * calls sampleFor().
864
879
  */
865
880
  export const createSpeedProber = (options = {}) => {
881
+ // Run 39 (DEC-39-01/39-04): the active engine source owns the speed read. oMLX
882
+ // reports usage.generation_tokens_per_second; mlx-serve reports
883
+ // timings.predicted_per_second. The prober asks the source, never a wire field.
884
+ const speedOf =
885
+ typeof options.speedOf === "function"
886
+ ? options.speedOf
887
+ : (body, usage) => ({
888
+ generationTps:
889
+ Number.isFinite(Number(usage?.generation_tokens_per_second)) ? Number(usage.generation_tokens_per_second) : null
890
+ })
866
891
  const samples =
867
892
  options.samples !== undefined && typeof options.samples?.sampleFor === "function"
868
893
  ? options.samples
@@ -889,6 +914,8 @@ export const createSpeedProber = (options = {}) => {
889
914
  // them instead of falling back to the 8000 default with no auth.
890
915
  baseUrl: options.baseUrl,
891
916
  apiKey: options.apiKey,
917
+ // Run 39: forward the active source's speed read to the probe.
918
+ speedOf: options.speedOf,
892
919
  now: options.now,
893
920
  timeoutMs: options.timeoutMs,
894
921
  maxTokens: options.maxTokens,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@try-works/dsh-minimal-router",
3
- "version": "0.2.10",
3
+ "version": "0.2.12",
4
4
  "description": "DSH local router plugin: per-session auto-routing between a local engine and remote models, evidence pages, and a plugin-owned engine provider.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",