@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,1019 @@
1
+ // Plain-JS oMLX telemetry reader for the DSH profile.
2
+ //
3
+ // The canonical, Effect-typed client is packages/plugin/host/telemetry.ts
4
+ // (18 tests). The DSH host cannot load TypeScript or the workspace's effect
5
+ // package, so this file is a faithful transport/schema/normalization port for
6
+ // the host process. It reads the same four oMLX 0.8.3 admin endpoints:
7
+ //
8
+ // GET /admin/api/stats serving totals and averages
9
+ // GET /admin/api/activity live requests, memory pressure and live decode rates
10
+ // GET /admin/api/models residency, default model and visibility flags
11
+ // GET /admin/api/device-info chip, memory and GPU facts
12
+ //
13
+ // Failures are typed TelemetryReadError values with a kind, endpoint, status,
14
+ // attempts and retryable flag. A partial snapshot is never returned.
15
+
16
+ export const DEFAULT_OMLX_BASE_URL = "http://127.0.0.1:8000"
17
+
18
+ export class TelemetryReadError extends Error {
19
+ constructor(args) {
20
+ super(args.message)
21
+ this.name = "TelemetryReadError"
22
+ this._tag = "TelemetryError"
23
+ this.kind = args.kind
24
+ this.endpoint = args.endpoint
25
+ this.status = args.status ?? null
26
+ this.attempts = args.attempts ?? 1
27
+ this.retryable =
28
+ args.kind === "network" ||
29
+ args.kind === "timeout" ||
30
+ (args.kind === "http" &&
31
+ this.status !== null &&
32
+ (this.status === 408 || this.status === 429 || this.status >= 500))
33
+ if (args.cause !== undefined) this.cause = args.cause
34
+ }
35
+ }
36
+
37
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
38
+
39
+ const hasNumbers = (value, keys) =>
40
+ isRecord(value) && keys.every((key) => typeof value[key] === "number" && Number.isFinite(value[key]))
41
+
42
+ const hasOptionalBooleans = (value, keys) =>
43
+ isRecord(value) && keys.every((key) => value[key] === undefined || typeof value[key] === "boolean")
44
+
45
+ const hasOptionalString = (value, key) =>
46
+ isRecord(value) && (value[key] === undefined || typeof value[key] === "string")
47
+
48
+ const hasOptionalNumbers = (value, keys) =>
49
+ isRecord(value) &&
50
+ keys.every(
51
+ (key) => value[key] === undefined || (typeof value[key] === "number" && Number.isFinite(value[key]))
52
+ )
53
+
54
+ const validateStats = (body) => {
55
+ if (
56
+ !hasNumbers(body, [
57
+ "avg_generation_tps",
58
+ "avg_prefill_tps",
59
+ "total_requests",
60
+ "total_cached_tokens",
61
+ "cache_efficiency",
62
+ "uptime_seconds"
63
+ ])
64
+ ) {
65
+ throw new Error("stats payload is missing a required numeric field")
66
+ }
67
+ return body
68
+ }
69
+
70
+ const validateActivityModel = (model) => {
71
+ if (
72
+ !isRecord(model) ||
73
+ typeof model.id !== "string" ||
74
+ !hasNumbers(model, ["active_requests", "waiting_requests"]) ||
75
+ !hasOptionalBooleans(model, ["is_loading"]) ||
76
+ (model.generating !== undefined && !Array.isArray(model.generating))
77
+ ) {
78
+ throw new Error("activity model payload is invalid")
79
+ }
80
+ if (
81
+ model.generating !== undefined &&
82
+ !model.generating.every((generating) => hasNumbers(generating, ["tokens_per_second"]))
83
+ ) {
84
+ throw new Error("activity generating payload is invalid")
85
+ }
86
+ return model
87
+ }
88
+
89
+ const validateActivity = (body) => {
90
+ if (!isRecord(body) || !isRecord(body.active_models)) {
91
+ throw new Error("activity payload is missing active_models")
92
+ }
93
+ const active = body.active_models
94
+ if (
95
+ !Array.isArray(active.models) ||
96
+ !hasNumbers(active, [
97
+ "model_memory_used",
98
+ "model_memory_max",
99
+ "total_active_requests",
100
+ "total_waiting_requests"
101
+ ]) ||
102
+ !isRecord(active.memory_pressure) ||
103
+ !["ok", "soft", "hard"].includes(active.memory_pressure.pressure_level) ||
104
+ !hasNumbers(active.memory_pressure, ["current_bytes", "soft_bytes", "hard_bytes"])
105
+ ) {
106
+ throw new Error("activity payload is invalid")
107
+ }
108
+ active.models.forEach(validateActivityModel)
109
+ return body
110
+ }
111
+
112
+ const validateModels = (body) => {
113
+ if (!isRecord(body) || !Array.isArray(body.models)) {
114
+ throw new Error("models payload is missing models")
115
+ }
116
+ for (const model of body.models) {
117
+ if (
118
+ !isRecord(model) ||
119
+ typeof model.id !== "string" ||
120
+ typeof model.loaded !== "boolean" ||
121
+ typeof model.is_loading !== "boolean" ||
122
+ !hasOptionalBooleans(model, ["is_default", "is_hidden", "is_helper", "pinned"]) ||
123
+ !hasOptionalString(model, "source_type") ||
124
+ !hasOptionalNumbers(model, ["estimated_size", "actual_size", "model_context_length"])
125
+ ) {
126
+ throw new Error("models payload entry is invalid")
127
+ }
128
+ }
129
+ return body
130
+ }
131
+
132
+ const validateDevice = (body) => {
133
+ if (!isRecord(body) || typeof body.chip_name !== "string" || !hasNumbers(body, ["memory_gb", "gpu_cores"])) {
134
+ throw new Error("device payload is invalid")
135
+ }
136
+ return body
137
+ }
138
+
139
+ // S1 headroom.engineMax: the engine's scheduler ceiling. Optional — a profile
140
+ // without the endpoint keeps engineMax null rather than failing the snapshot.
141
+ const validateGlobalSettings = (body) => {
142
+ if (!isRecord(body)) throw new Error("global-settings payload is invalid")
143
+ const scheduler = isRecord(body.scheduler) ? body.scheduler : null
144
+ const raw = scheduler === null ? null : scheduler.max_concurrent_requests
145
+ return { engineMax: Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : null }
146
+ }
147
+
148
+ class AttemptFailure extends Error {
149
+ constructor(kind, message, status, cause) {
150
+ super(message)
151
+ this.name = "AttemptFailure"
152
+ this.kind = kind
153
+ this.status = status ?? null
154
+ this.cause = cause
155
+ }
156
+ }
157
+
158
+ const clamp01 = (value) => Math.min(1, Math.max(0, value))
159
+
160
+ const buildSnapshot = (source, fetchedAt, stats, activity, models, device, settings) => {
161
+ const active = activity.active_models
162
+
163
+ const residents = [
164
+ ...new Set(
165
+ models.models
166
+ .filter(
167
+ (model) =>
168
+ model.loaded &&
169
+ model.is_loading !== true &&
170
+ model.is_hidden !== true &&
171
+ model.is_helper !== true &&
172
+ model.source_type !== "builtin"
173
+ )
174
+ .map((model) => model.id)
175
+ )
176
+ ].sort()
177
+
178
+ const preferredModel =
179
+ residents.find((id) =>
180
+ models.models.some((model) => model.id === id && model.is_default === true)
181
+ ) ?? null
182
+
183
+ const liveTps = active.models
184
+ .flatMap((model) => model.generating ?? [])
185
+ .map((generating) => generating.tokens_per_second)
186
+ .filter((tps) => Number.isFinite(tps) && tps >= 0)
187
+
188
+ const observedTps =
189
+ liveTps.length > 0
190
+ ? Math.max(...liveTps)
191
+ : stats.total_requests > 0
192
+ ? stats.avg_generation_tps
193
+ : null
194
+ const observedTpsSource =
195
+ liveTps.length > 0 ? "live" : observedTps !== null ? "historical" : null
196
+
197
+ const memoryUsedBytes = active.model_memory_used
198
+ const memoryMaxBytes = active.model_memory_max
199
+ const headroomRatio =
200
+ memoryMaxBytes > 0 && Number.isFinite(memoryMaxBytes)
201
+ ? clamp01((memoryMaxBytes - memoryUsedBytes) / memoryMaxBytes)
202
+ : 1
203
+
204
+ // Per-model evidence the approved Models page needs: resident context window,
205
+ // resident size and the live decode rate when the model is generating. KV
206
+ // cache stays unavailable because the admin API does not expose it.
207
+ const modelDetails = residents.map((id) => {
208
+ const model = models.models.find((entry) => entry.id === id)
209
+ const activeModel = active.models.find((entry) => entry.id === id)
210
+ const modelTps = (activeModel?.generating ?? [])
211
+ .map((generating) => generating.tokens_per_second)
212
+ .filter((tps) => Number.isFinite(tps) && tps >= 0)
213
+ const sizeBytes =
214
+ typeof model?.actual_size === "number" && model.actual_size > 0
215
+ ? model.actual_size
216
+ : typeof model?.estimated_size === "number" && model.estimated_size > 0
217
+ ? model.estimated_size
218
+ : null
219
+ return {
220
+ id,
221
+ preferred: id === preferredModel,
222
+ pinned: model?.pinned === true,
223
+ contextLength:
224
+ typeof model?.model_context_length === "number" && model.model_context_length > 0
225
+ ? model.model_context_length
226
+ : null,
227
+ sizeBytes,
228
+ tps: modelTps.length > 0 ? Math.max(...modelTps) : null
229
+ }
230
+ })
231
+
232
+ return {
233
+ fetchedAt,
234
+ source,
235
+ observedTps,
236
+ observedTpsSource,
237
+ headroomRatio,
238
+ engineMax: settings !== null && settings !== undefined && Number.isFinite(settings.engineMax) ? settings.engineMax : null,
239
+ pressureLevel: active.memory_pressure.pressure_level,
240
+ residentModels: residents,
241
+ models: modelDetails,
242
+ preferredModel,
243
+ stats: {
244
+ avgGenerationTps: stats.avg_generation_tps,
245
+ avgPrefillTps: stats.avg_prefill_tps,
246
+ totalRequests: stats.total_requests,
247
+ totalCachedTokens: stats.total_cached_tokens,
248
+ cacheEfficiency: stats.cache_efficiency,
249
+ uptimeSeconds: stats.uptime_seconds
250
+ },
251
+ activity: {
252
+ activeRequests: active.total_active_requests,
253
+ waitingRequests: active.total_waiting_requests,
254
+ memoryUsedBytes,
255
+ memoryMaxBytes,
256
+ // F-37-48: the engine's own soft limit is the memory guard the page shows
257
+ // (memory_pressure.soft_bytes); absent stays null, never invented.
258
+ memorySoftBytes:
259
+ typeof active.memory_pressure?.soft_bytes === "number" && active.memory_pressure.soft_bytes > 0
260
+ ? active.memory_pressure.soft_bytes
261
+ : null
262
+ },
263
+ device: {
264
+ chipName: device.chip_name,
265
+ memoryGb: device.memory_gb,
266
+ gpuCores: device.gpu_cores
267
+ }
268
+ }
269
+ }
270
+
271
+ const fetchRequest = async (url, init) => {
272
+ const response = await fetch(url, {
273
+ method: "GET",
274
+ headers: { ...init.headers },
275
+ signal: init.signal
276
+ })
277
+ return { status: response.status, text: await response.text() }
278
+ }
279
+
280
+ const normalizeInteger = (value, fallback, min, max) =>
281
+ typeof value === "number" && Number.isFinite(value)
282
+ ? Math.min(max, Math.max(min, Math.trunc(value)))
283
+ : fallback
284
+
285
+ /**
286
+ * Build a telemetry reader. Everything network-facing is injectable so host
287
+ * tests run on fixtures; the default transport uses global fetch.
288
+ */
289
+ export const createOmlxTelemetry = (options = {}) => {
290
+ const source = (options.baseUrl ?? DEFAULT_OMLX_BASE_URL).replace(/\/+$/u, "")
291
+ const request = options.request ?? fetchRequest
292
+ const now = options.now ?? (() => new Date())
293
+ const timeoutMs = normalizeInteger(options.timeoutMs, 1500, 1, 60_000)
294
+ const maxAttempts = normalizeInteger(options.retries, 1, 0, 5) + 1
295
+ const headers = { Accept: "application/json" }
296
+ if (typeof options.apiKey === "string" && options.apiKey.trim().length > 0) {
297
+ headers.Authorization = `Bearer ${options.apiKey}`
298
+ }
299
+
300
+ const toReadError = (error, endpoint, attempts) => {
301
+ if (error instanceof TelemetryReadError) return error
302
+ if (error instanceof AttemptFailure) {
303
+ return new TelemetryReadError({
304
+ kind: error.kind,
305
+ endpoint,
306
+ status: error.status,
307
+ attempts,
308
+ message: `oMLX ${endpoint} ${error.message}`,
309
+ cause: error
310
+ })
311
+ }
312
+ const detail = error instanceof Error ? error.message : String(error)
313
+ return new TelemetryReadError({
314
+ kind: "network",
315
+ endpoint,
316
+ status: null,
317
+ attempts,
318
+ message: `oMLX ${endpoint} request failed: ${detail}`,
319
+ cause: error
320
+ })
321
+ }
322
+
323
+ const perform = async (url, signal) => {
324
+ const controller = new AbortController()
325
+ const abort = () => controller.abort()
326
+ if (signal !== undefined && signal.aborted) abort()
327
+ else if (signal !== undefined) signal.addEventListener("abort", abort, { once: true })
328
+
329
+ let timer = null
330
+ const deadline = new Promise((_, reject) => {
331
+ timer = setTimeout(() => {
332
+ controller.abort()
333
+ reject(new AttemptFailure("timeout", `timed out after ${timeoutMs}ms`))
334
+ }, timeoutMs)
335
+ })
336
+
337
+ try {
338
+ const response = await Promise.race([
339
+ request(url, { headers, signal: controller.signal }),
340
+ deadline
341
+ ])
342
+ if (response.status < 200 || response.status >= 300) {
343
+ throw new AttemptFailure("http", `returned HTTP ${response.status}`, response.status)
344
+ }
345
+ try {
346
+ return JSON.parse(response.text)
347
+ } catch (cause) {
348
+ throw new AttemptFailure("parse", "response was not valid JSON", null, cause)
349
+ }
350
+ } finally {
351
+ if (timer !== null) clearTimeout(timer)
352
+ if (signal !== undefined) signal.removeEventListener("abort", abort)
353
+ }
354
+ }
355
+
356
+ const readPath = async (path, validate, signal) => {
357
+ const endpoint = source + path
358
+ let last = null
359
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
360
+ try {
361
+ const body = await perform(endpoint, signal)
362
+ try {
363
+ return validate(body)
364
+ } catch (cause) {
365
+ throw new TelemetryReadError({
366
+ kind: "validation",
367
+ endpoint,
368
+ status: null,
369
+ attempts: attempt,
370
+ message: `oMLX ${endpoint} payload failed validation: ${cause instanceof Error ? cause.message : String(cause)}`,
371
+ cause
372
+ })
373
+ }
374
+ } catch (error) {
375
+ const typed = toReadError(error, endpoint, attempt)
376
+ if (!typed.retryable || attempt >= maxAttempts) throw typed
377
+ last = typed
378
+ }
379
+ }
380
+ throw last ?? new TelemetryReadError({
381
+ kind: "network",
382
+ endpoint,
383
+ status: null,
384
+ attempts: maxAttempts,
385
+ message: `oMLX ${endpoint} failed`
386
+ })
387
+ }
388
+
389
+ return async ({ signal } = {}) => {
390
+ const stats = await readPath("/admin/api/stats", validateStats, signal)
391
+ const activity = await readPath("/admin/api/activity", validateActivity, signal)
392
+ const models = await readPath("/admin/api/models", validateModels, signal)
393
+ const device = await readPath("/admin/api/device-info", validateDevice, signal)
394
+ // Optional: a missing or invalid global-settings endpoint keeps engineMax null.
395
+ let settings = null
396
+ try {
397
+ settings = await readPath("/admin/api/global-settings", validateGlobalSettings, signal)
398
+ } catch {
399
+ settings = null
400
+ }
401
+ return buildSnapshot(source, now().toISOString(), stats, activity, models, device, settings)
402
+ }
403
+ }
404
+
405
+ // ---------------------------------------------------------------------------
406
+ // Run 36 (DEC-36-06/07, R-36-07): model speed samples and the probe runner.
407
+ //
408
+ // A speed sample is one local model's measured generation throughput, with the
409
+ // source that produced it and when it was taken. Samples expire; an expired
410
+ // sample is unknown and must never be used to skip a model.
411
+ //
412
+ // A probe is a tiny timed generation against the local engine, bounded by a
413
+ // timeout. Probes run only in background sweeps — boot, catalogue change and a
414
+ // ten-minute re-probe of a model that is below its floor — never inside a
415
+ // request path and never against a remote model. Routing reads sampleFor(),
416
+ // which is synchronous and never waits on the network.
417
+
418
+ // DEC-37-09 (Owner): the probe reading is the router's floor evidence and the
419
+ // engine's own average is a lagging, outdated indicator. A probe result therefore
420
+ // stays valid much longer (30 min) and the sweep re-probes on a short cycle, so a
421
+ // fresh probe reading is essentially always present at decision time.
422
+ export const SPEED_SAMPLE_TTL_MS = 30 * 60 * 1000
423
+ export const BELOW_FLOOR_REPROBE_MS = 2 * 60 * 1000
424
+ export const SPEED_SOURCES = ["measured", "probe", "unknown"]
425
+ // DEC-37-13: an 8-token completion is too short to measure decode speed - the
426
+ // engine's own usage for the same model reports 189.9 tps over 64 tokens while an
427
+ // 8-token probe window can read 9-19 tps, because token startup and scheduling
428
+ // dominate a few-token window. The probe therefore asks for a run of tokens and
429
+ // prefers the engine's own generation_tokens_per_second.
430
+ export const PROBE_MAX_TOKENS = 64
431
+ export const PROBE_PROMPT = "Count from 1 to 40, separated by commas, digits only."
432
+ export const DEFAULT_PROBE_TIMEOUT_MS = 20_000
433
+
434
+ const roundTps = (value) => Math.round(value * 10) / 10
435
+
436
+ const asDate = (value, fallback) => {
437
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value
438
+ if (typeof value === "string" || typeof value === "number") {
439
+ const parsed = new Date(value)
440
+ if (!Number.isNaN(parsed.getTime())) return parsed
441
+ }
442
+ const resolved = typeof fallback === "function" ? fallback() : fallback
443
+ if (resolved instanceof Date && !Number.isNaN(resolved.getTime())) return resolved
444
+ return new Date()
445
+ }
446
+
447
+ const normalizeSpeedError = (error) => {
448
+ if (error === null || error === undefined) return null
449
+ if (typeof error !== "object") return { kind: "error", message: String(error) }
450
+ const out = {
451
+ kind: typeof error.kind === "string" ? error.kind : "error",
452
+ message: typeof error.message === "string" ? error.message : String(error.message ?? error)
453
+ }
454
+ if (error.status !== undefined) out.status = error.status
455
+ if (error.retryable !== undefined) out.retryable = error.retryable
456
+ return out
457
+ }
458
+
459
+ /**
460
+ * Per-model speed sample store with a TTL. Reads are synchronous and never
461
+ * touch the network, so a routing decision can always consult it.
462
+ */
463
+ export const createSpeedSamples = (options = {}) => {
464
+ const now = options.now ?? (() => new Date())
465
+ const ttlMs = normalizeInteger(options.ttlMs, SPEED_SAMPLE_TTL_MS, 1, 24 * 60 * 60 * 1000)
466
+ const belowFloorReprobeMs = normalizeInteger(
467
+ options.belowFloorReprobeMs,
468
+ BELOW_FLOOR_REPROBE_MS,
469
+ 1,
470
+ 24 * 60 * 60 * 1000
471
+ )
472
+ const samples = new Map()
473
+
474
+ const ageOf = (sample, reference = asDate(undefined, now)) =>
475
+ Math.max(0, reference.getTime() - asDate(sample.at, now).getTime())
476
+
477
+ const record = (input = {}) => {
478
+ const modelId = input.modelId
479
+ if (typeof modelId !== "string" || modelId.length === 0) {
480
+ throw new TypeError("a speed sample needs a model id")
481
+ }
482
+ if (!SPEED_SOURCES.includes(input.source)) {
483
+ throw new TypeError("a speed sample needs a known source")
484
+ }
485
+ const unknown = input.source === "unknown"
486
+ const tps = unknown ? null : input.tps
487
+ if (!unknown && !(typeof tps === "number" && Number.isFinite(tps) && tps >= 0)) {
488
+ throw new TypeError("a measured speed sample needs a finite tps")
489
+ }
490
+ const sample = {
491
+ modelId,
492
+ tps: unknown ? null : roundTps(tps),
493
+ source: input.source,
494
+ at: asDate(input.at, now).toISOString(),
495
+ error: normalizeSpeedError(input.error)
496
+ }
497
+ if (!unknown && Number.isFinite(input.tokens)) sample.tokens = Math.max(0, Math.trunc(input.tokens))
498
+ if (Number.isFinite(input.elapsedMs)) sample.elapsedMs = Math.max(0, Math.trunc(input.elapsedMs))
499
+ // R-37-02 / DEC-37-06 (Owner): the engine's own speed measure gates the floor
500
+ // at routing time, but the engine average is slow to move, so a model that fell
501
+ // below the floor needs a PROBE to show its recovery. Both are evidence that
502
+ // the model is AT LEAST that fast, so a fresh reading is never lowered or
503
+ // nulled by a weaker or failed one; once it expires the next reading rules.
504
+ const existing = samples.get(modelId)
505
+ const existingAt = existing === undefined ? null : asDate(existing.at, now)
506
+ const existingFresh =
507
+ existing !== undefined &&
508
+ existingAt !== null &&
509
+ ageOf(existing, asDate(sample.at, now)) < ttlMs &&
510
+ typeof existing.tps === "number"
511
+ if (existingFresh && (unknown || existing.tps > sample.tps)) {
512
+ return { ...existing }
513
+ }
514
+ samples.set(modelId, sample)
515
+ return { ...sample }
516
+ }
517
+
518
+ const measured = (modelId, tps, at) => record({ modelId, tps, source: "measured", at })
519
+ const unknown = (modelId, error, at) =>
520
+ record({ modelId, tps: null, source: "unknown", error, at })
521
+
522
+ /** The stored reading, expired or not. Evidence only; never a gate input. */
523
+ const latest = (modelId) => {
524
+ const sample = samples.get(modelId)
525
+ return sample === undefined ? null : { ...sample }
526
+ }
527
+
528
+ /**
529
+ * The gate view of a model's speed. An expired sample is unknown: tps is
530
+ * null, source is "unknown" and expired is true, so it can never skip a
531
+ * model. Null means no sample was ever taken.
532
+ */
533
+ const sampleFor = (modelId, at) => {
534
+ const sample = samples.get(modelId)
535
+ if (sample === undefined) return null
536
+ const ageMs = ageOf(sample, asDate(at, now))
537
+ const expired = ageMs >= ttlMs
538
+ if (expired) return { ...sample, tps: null, source: "unknown", ageMs, expired: true }
539
+ return { ...sample, ageMs, expired: false }
540
+ }
541
+
542
+ const floorOf = (floorFor, modelId) => (typeof floorFor === "function" ? floorFor(modelId) : floorFor)
543
+
544
+ /**
545
+ * Models whose newest reading is below the floor and at least ten minutes
546
+ * old. Only models that already have a reading are due: a model with no
547
+ * sample belongs to the boot or catalogue-change sweep instead.
548
+ */
549
+ const dueForBelowFloorReprobe = (models, floorFor, at) => {
550
+ const reference = asDate(at, now)
551
+ const due = []
552
+ const seen = new Set()
553
+ for (const entry of Array.isArray(models) ? models : []) {
554
+ const modelId = typeof entry === "string" ? entry : entry?.id
555
+ if (typeof modelId !== "string" || modelId.length === 0 || seen.has(modelId)) continue
556
+ seen.add(modelId)
557
+ const sample = samples.get(modelId)
558
+ if (sample === undefined || sample.tps === null) continue
559
+ const floor = floorOf(floorFor, modelId)
560
+ if (typeof floor !== "number" || !Number.isFinite(floor) || floor < 0) continue
561
+ if (sample.tps >= floor) continue
562
+ if (ageOf(sample, reference) < belowFloorReprobeMs) continue
563
+ due.push(modelId)
564
+ }
565
+ return due
566
+ }
567
+
568
+ /**
569
+ * Models whose newest reading is at least "staleMs" old, whatever its source
570
+ * (measured, probe or a failed unknown). DEC-37-07: the engine's averaged
571
+ * speed is a lagging indicator, so a probe sample must be renewed before it
572
+ * expires and lets the engine average fill the slot. A model with no reading
573
+ * belongs to the boot or catalogue-change sweep instead.
574
+ */
575
+ const dueForAgedRefresh = (models, staleMs, at) => {
576
+ const reference = asDate(at, now)
577
+ const stale = normalizeInteger(staleMs, ttlMs / 2, 1, 24 * 60 * 60 * 1000)
578
+ const due = []
579
+ const seen = new Set()
580
+ for (const entry of Array.isArray(models) ? models : []) {
581
+ const modelId = typeof entry === "string" ? entry : entry?.id
582
+ if (typeof modelId !== "string" || modelId.length === 0 || seen.has(modelId)) continue
583
+ seen.add(modelId)
584
+ const sample = samples.get(modelId)
585
+ if (sample === undefined) continue
586
+ if (ageOf(sample, reference) < stale) continue
587
+ due.push(modelId)
588
+ }
589
+ return due
590
+ }
591
+
592
+ const snapshot = (at) => {
593
+ const out = {}
594
+ for (const modelId of [...samples.keys()].sort()) {
595
+ const view = sampleFor(modelId, at)
596
+ if (view !== null) out[modelId] = view
597
+ }
598
+ return out
599
+ }
600
+
601
+ return {
602
+ record,
603
+ measured,
604
+ unknown,
605
+ latest,
606
+ sampleFor,
607
+ dueForBelowFloorReprobe,
608
+ dueForAgedRefresh,
609
+ snapshot,
610
+ ttlMs,
611
+ belowFloorReprobeMs
612
+ }
613
+ }
614
+
615
+ /** OpenAI chat base for an engine endpoint (tolerates a trailing /v1 or /admin). */
616
+ const probeBaseUrl = (baseUrl) => {
617
+ const raw = typeof baseUrl === "string" && baseUrl.length > 0 ? baseUrl : DEFAULT_OMLX_BASE_URL
618
+ const trimmed = raw.replace(/\/+$/u, "").replace(/\/admin(\/api)?$/u, "")
619
+ return /\/v1$/u.test(trimmed) ? trimmed : trimmed + "/v1"
620
+ }
621
+
622
+ const probeFetch = async (url, init) => {
623
+ const response = await fetch(url, {
624
+ method: init.method,
625
+ headers: { ...init.headers },
626
+ body: init.body,
627
+ signal: init.signal
628
+ })
629
+ if (response.body !== null && response.body !== undefined) {
630
+ return { status: response.status, stream: response.body }
631
+ }
632
+ return { status: response.status, text: await response.text() }
633
+ }
634
+
635
+ const estimateTokens = (text) => {
636
+ const trimmed = typeof text === "string" ? text.trim() : ""
637
+ return trimmed.length === 0 ? 1 : Math.max(1, Math.round(trimmed.length / 4))
638
+ }
639
+
640
+ const completionOf = (body) => {
641
+ const choice = Array.isArray(body?.choices) ? body.choices[0] : undefined
642
+ if (typeof choice?.message?.content === "string") return choice.message.content
643
+ if (typeof choice?.text === "string") return choice.text
644
+ return null
645
+ }
646
+
647
+ const isAsyncIterable = (value) =>
648
+ value !== null && value !== undefined && typeof value[Symbol.asyncIterator] === "function"
649
+
650
+ const deltaHasTokens = (delta) => {
651
+ if (!isRecord(delta)) return false
652
+ if (typeof delta.content === "string" && delta.content.length > 0) return true
653
+ if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0) return true
654
+ return Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0
655
+ }
656
+
657
+ /**
658
+ * Read a chat-completions SSE body and record the wall-clock timestamps of the
659
+ * first generated delta and the finish marker. Streaming lets the probe measure
660
+ * decode-only throughput: request setup and prefill happen before the first
661
+ * delta and must not be charged to generation speed. A server that ignored
662
+ * stream:true and sent a non-SSE body accumulates its text here so the caller
663
+ * can fall back to JSON parsing.
664
+ */
665
+ const readSseStream = async (stream, now) => {
666
+ const state = { text: "", content: "", firstDeltaAt: null, finishAt: null, usageTokens: null }
667
+ const decoder = new TextDecoder()
668
+ let buffer = ""
669
+ const consumeLine = (line, atMs) => {
670
+ const trimmed = line.trim()
671
+ if (!trimmed.startsWith("data:")) return
672
+ const data = trimmed.slice("data:".length).trim()
673
+ if (data === "[DONE]") {
674
+ if (state.finishAt === null) state.finishAt = atMs
675
+ return
676
+ }
677
+ let payload
678
+ try {
679
+ payload = JSON.parse(data)
680
+ } catch {
681
+ return
682
+ }
683
+ if (!isRecord(payload)) return
684
+ const choice = Array.isArray(payload.choices) ? payload.choices[0] : undefined
685
+ const delta = choice?.delta
686
+ if (isRecord(delta) && typeof delta.content === "string" && delta.content.length > 0) {
687
+ state.content += delta.content
688
+ }
689
+ // The decode window starts at the first delta of ANY kind: a reasoning model
690
+ // streams delta.reasoning_content (and possibly delta.tool_calls) before any
691
+ // content, and usage.completion_tokens counts those generated tokens too.
692
+ if (deltaHasTokens(delta) && state.firstDeltaAt === null) state.firstDeltaAt = atMs
693
+ const finish = choice?.finish_reason
694
+ if (typeof finish === "string" && finish.length > 0 && state.finishAt === null) {
695
+ state.finishAt = atMs
696
+ }
697
+ const usageTokens = payload?.usage?.completion_tokens
698
+ if (typeof usageTokens === "number" && Number.isFinite(usageTokens) && usageTokens > 0) {
699
+ state.usageTokens = Math.trunc(usageTokens)
700
+ }
701
+ // The engine reports the decode-only speed of this very request; prefer it over
702
+ // our own delta window, which is sensitive to a short completion.
703
+ const reportedTps = payload?.usage?.generation_tokens_per_second
704
+ if (typeof reportedTps === "number" && Number.isFinite(reportedTps) && reportedTps > 0) {
705
+ state.reportedTps = reportedTps
706
+ }
707
+ }
708
+ for await (const chunk of stream) {
709
+ const atMs = now().getTime()
710
+ const piece = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true })
711
+ state.text += piece
712
+ buffer += piece
713
+ let index
714
+ while ((index = buffer.indexOf("\n")) !== -1) {
715
+ const line = buffer.slice(0, index).replace(/\r$/u, "")
716
+ buffer = buffer.slice(index + 1)
717
+ consumeLine(line, atMs)
718
+ }
719
+ }
720
+ const tail = decoder.decode()
721
+ state.text += tail
722
+ buffer += tail
723
+ if (buffer.trim().length > 0) consumeLine(buffer, now().getTime())
724
+ if (state.firstDeltaAt !== null && state.finishAt === null) state.finishAt = now().getTime()
725
+ return state
726
+ }
727
+
728
+ /**
729
+ * Tiny timed generation against one local model. The probe is bounded by a
730
+ * timeout and returns the sample or a typed error; it never throws.
731
+ */
732
+ export const createModelProbe = (options = {}) => {
733
+ const base = probeBaseUrl(options.baseUrl)
734
+ const request = options.request ?? probeFetch
735
+ const now = options.now ?? (() => new Date())
736
+ const timeoutMs = normalizeInteger(options.timeoutMs, DEFAULT_PROBE_TIMEOUT_MS, 1, 120_000)
737
+ const maxTokens = normalizeInteger(options.maxTokens, PROBE_MAX_TOKENS, 1, 128)
738
+ const prompt =
739
+ typeof options.prompt === "string" && options.prompt.length > 0 ? options.prompt : PROBE_PROMPT
740
+ const headers = { Accept: "application/json", "Content-Type": "application/json" }
741
+ if (typeof options.apiKey === "string" && options.apiKey.trim().length > 0) {
742
+ headers.Authorization = `Bearer ${options.apiKey}`
743
+ }
744
+
745
+ const probeModel = async (modelId, callOptions = {}) => {
746
+ if (typeof modelId !== "string" || modelId.length === 0) {
747
+ return { ok: false, error: { kind: "invalid", message: "a probe needs a model id" } }
748
+ }
749
+ const url = base + "/chat/completions"
750
+ const body = JSON.stringify({
751
+ model: modelId,
752
+ messages: [{ role: "user", content: prompt }],
753
+ max_tokens: maxTokens,
754
+ stream: true,
755
+ stream_options: { include_usage: true },
756
+ temperature: 0
757
+ })
758
+ const controller = new AbortController()
759
+ const abort = () => controller.abort()
760
+ const outer = callOptions.signal
761
+ if (outer !== undefined) {
762
+ if (outer.aborted) abort()
763
+ else outer.addEventListener("abort", abort, { once: true })
764
+ }
765
+ let timer = null
766
+ const startedAt = now().getTime()
767
+ const makeSample = (tokens, elapsedMs) => ({
768
+ ok: true,
769
+ sample: {
770
+ modelId,
771
+ tps: roundTps(tokens / (elapsedMs / 1000)),
772
+ source: "probe",
773
+ at: now().toISOString(),
774
+ error: null,
775
+ tokens,
776
+ elapsedMs
777
+ }
778
+ })
779
+ try {
780
+ const deadline = new Promise((_, reject) => {
781
+ timer = setTimeout(() => {
782
+ controller.abort()
783
+ reject(new AttemptFailure("timeout", `probe timed out after ${timeoutMs}ms`))
784
+ }, timeoutMs)
785
+ })
786
+ const pending = Promise.resolve().then(() =>
787
+ request(url, { method: "POST", headers, body, signal: controller.signal })
788
+ )
789
+ // After a timeout the aborted request may still reject; never leave it unhandled.
790
+ pending.catch(() => {})
791
+ const response = await Promise.race([pending, deadline])
792
+ if (response === null || typeof response.status !== "number" || response.status < 200 || response.status >= 300) {
793
+ throw new AttemptFailure("http", `probe returned HTTP ${response?.status}`, response?.status ?? null)
794
+ }
795
+ // A streaming body lets decode time be measured token-by-token. A buffered
796
+ // or non-SSE body falls back to the total-time measurement below.
797
+ const stream = response?.stream ?? response?.body
798
+ let sse = null
799
+ let text = null
800
+ if (isAsyncIterable(stream)) {
801
+ const reading = readSseStream(stream, now)
802
+ reading.catch(() => {})
803
+ sse = await Promise.race([reading, deadline])
804
+ text = sse.text
805
+ } else if (typeof response?.text === "string") {
806
+ text = response.text
807
+ } else if (response !== null && typeof response?.text === "function") {
808
+ text = await Promise.race([Promise.resolve(response.text()), deadline])
809
+ }
810
+ if (sse !== null && typeof sse.reportedTps === "number" && Number.isFinite(sse.reportedTps) && sse.reportedTps > 0) {
811
+ // DEC-37-13: the engine's own per-request decode speed wins.
812
+ const tokens = sse.usageTokens !== null ? sse.usageTokens : estimateTokens(sse.content)
813
+ return makeSample(tokens, Math.max(1, Math.round((tokens / sse.reportedTps) * 1000)))
814
+ }
815
+ if (sse !== null && sse.firstDeltaAt !== null && sse.finishAt !== null) {
816
+ // completion_tokens comes from the stream's usage when the engine sends it;
817
+ // otherwise the accumulated content is estimated as before.
818
+ const tokens = sse.usageTokens !== null ? sse.usageTokens : estimateTokens(sse.content)
819
+ if (sse.finishAt > sse.firstDeltaAt) {
820
+ // Decode-only: request setup and prefill are excluded from the throughput.
821
+ return makeSample(tokens, Math.max(1, sse.finishAt - sse.firstDeltaAt))
822
+ }
823
+ // A whole completion delivered in one chunk has no observable decode
824
+ // window; fall back to total wall time rather than failing the probe.
825
+ return makeSample(tokens, Math.max(1, now().getTime() - startedAt))
826
+ }
827
+ // Fallback: a server that ignored stream:true (or a non-SSE body) is timed
828
+ // over total wall time, exactly as before streaming probes existed.
829
+ if (text === null) throw new AttemptFailure("invalid", "probe response had no body", null)
830
+ let payload
831
+ try {
832
+ payload = JSON.parse(text)
833
+ } catch (cause) {
834
+ throw new AttemptFailure("parse", "probe response was not valid JSON", null, cause)
835
+ }
836
+ const content = completionOf(payload)
837
+ if (content === null) throw new AttemptFailure("invalid", "probe response had no completion", null)
838
+ const usageTokens = payload?.usage?.completion_tokens
839
+ const tokens =
840
+ typeof usageTokens === "number" && Number.isFinite(usageTokens) && usageTokens > 0
841
+ ? Math.trunc(usageTokens)
842
+ : estimateTokens(content)
843
+ const elapsedMs = Math.max(1, now().getTime() - startedAt)
844
+ return makeSample(tokens, elapsedMs)
845
+ } catch (error) {
846
+ const kind = error instanceof AttemptFailure ? error.kind : "network"
847
+ const out = { kind, message: error instanceof Error ? error.message : String(error) }
848
+ if (error instanceof AttemptFailure && error.status !== null) out.status = error.status
849
+ return { ok: false, error: out }
850
+ } finally {
851
+ if (timer !== null) clearTimeout(timer)
852
+ if (outer !== undefined) outer.removeEventListener("abort", abort)
853
+ }
854
+ }
855
+
856
+ return { probeModel, baseUrl: base, timeoutMs, maxTokens }
857
+ }
858
+
859
+ /**
860
+ * The sweep host surface: a sample store plus the probe. A sweep probes every
861
+ * local model without a sample (boot and catalogue change); a rebuild sweeps
862
+ * only the models that are below floor and ten minutes old. Routing only ever
863
+ * calls sampleFor().
864
+ */
865
+ export const createSpeedProber = (options = {}) => {
866
+ const samples =
867
+ options.samples !== undefined && typeof options.samples?.sampleFor === "function"
868
+ ? options.samples
869
+ : createSpeedSamples({
870
+ now: options.now,
871
+ ttlMs: options.ttlMs,
872
+ belowFloorReprobeMs: options.belowFloorReprobeMs
873
+ })
874
+ const providedProbe =
875
+ options.probe !== undefined && typeof options.probe === "object" && options.probe !== null
876
+ ? options.probe
877
+ : {}
878
+ const probeFn =
879
+ typeof options.probe === "function"
880
+ ? options.probe
881
+ : typeof providedProbe.probeModel === "function"
882
+ ? (modelId) => providedProbe.probeModel(modelId)
883
+ : createModelProbe(
884
+ typeof options.probe === "object" && options.probe !== null
885
+ ? options.probe
886
+ : {
887
+ // F-37-02 (decisive): a caller passes the live engine endpoint
888
+ // and key as top-level options; the default probe must honour
889
+ // them instead of falling back to the 8000 default with no auth.
890
+ baseUrl: options.baseUrl,
891
+ apiKey: options.apiKey,
892
+ now: options.now,
893
+ timeoutMs: options.timeoutMs,
894
+ maxTokens: options.maxTokens,
895
+ prompt: options.prompt
896
+ }
897
+ ).probeModel
898
+ const isLocalModel = typeof options.isLocalModel === "function" ? options.isLocalModel : null
899
+ const inFlight = new Set()
900
+
901
+ const listOf = (models) => {
902
+ if (Array.isArray(models)) return models
903
+ if (models !== null && typeof models === "object" && typeof models[Symbol.iterator] === "function") {
904
+ return [...models]
905
+ }
906
+ return []
907
+ }
908
+
909
+ const normalizeTargets = (models) => {
910
+ const targets = []
911
+ for (const entry of listOf(models)) {
912
+ if (typeof entry === "string") {
913
+ if (entry.length > 0) targets.push({ id: entry, local: undefined })
914
+ continue
915
+ }
916
+ if (entry === null || typeof entry !== "object") continue
917
+ if (typeof entry.id !== "string" || entry.id.length === 0) continue
918
+ targets.push({ id: entry.id, local: entry.local })
919
+ }
920
+ return targets
921
+ }
922
+
923
+ const isLocal = (target) => {
924
+ if (target.local === false) return false
925
+ if (isLocalModel === null) return true
926
+ return isLocalModel(target.id) === true
927
+ }
928
+
929
+ const probeOne = async (modelId) => {
930
+ inFlight.add(modelId)
931
+ try {
932
+ let result
933
+ try {
934
+ result = await probeFn(modelId)
935
+ } catch (error) {
936
+ result = {
937
+ ok: false,
938
+ error: { kind: "network", message: error instanceof Error ? error.message : String(error) }
939
+ }
940
+ }
941
+ if (result !== null && typeof result === "object" && result.ok === true && result.sample !== undefined) {
942
+ samples.record({
943
+ modelId,
944
+ tps: result.sample.tps,
945
+ source: "probe",
946
+ at: result.sample.at,
947
+ error: null,
948
+ tokens: result.sample.tokens,
949
+ elapsedMs: result.sample.elapsedMs
950
+ })
951
+ return { modelId, ok: true, tps: result.sample.tps, error: null }
952
+ }
953
+ const error = result?.error ?? { kind: "unknown", message: "a probe returned no sample" }
954
+ samples.unknown(modelId, error)
955
+ return { modelId, ok: false, tps: null, error }
956
+ } finally {
957
+ inFlight.delete(modelId)
958
+ }
959
+ }
960
+
961
+ const runSweep = async (targets, { requireMissing = false } = {}) => {
962
+ const probed = []
963
+ const skipped = []
964
+ const results = []
965
+ for (const target of targets) {
966
+ if (!isLocal(target)) {
967
+ skipped.push({ modelId: target.id, reason: "remote" })
968
+ continue
969
+ }
970
+ if (inFlight.has(target.id)) {
971
+ skipped.push({ modelId: target.id, reason: "in flight" })
972
+ continue
973
+ }
974
+ // A boot/catalogue sweep only fills gaps - but an engine-average
975
+ // "measured" reading is NOT a probe measurement (DEC-37-07: it lags and
976
+ // recovers slowly). Treat only a probe/unknown sample as the gap being
977
+ // filled, so the engine's lagging average can never suppress the probe.
978
+ const latest = samples.latest(target.id)
979
+ if (requireMissing && latest !== null && latest.source !== "measured") {
980
+ skipped.push({ modelId: target.id, reason: "has a probe sample" })
981
+ continue
982
+ }
983
+ probed.push(target.id)
984
+ results.push(await probeOne(target.id))
985
+ }
986
+ return { probed, skipped, results }
987
+ }
988
+
989
+ const sweep = (models) => runSweep(normalizeTargets(models), { requireMissing: true })
990
+
991
+ const reprobeBelowFloor = (models, floorFor, at) => {
992
+ const targets = normalizeTargets(models)
993
+ const due = new Set(samples.dueForBelowFloorReprobe(targets.map((target) => target.id), floorFor, at))
994
+ return runSweep(targets.filter((target) => due.has(target.id)))
995
+ }
996
+
997
+ /**
998
+ * Re-probe every model whose current sample is at least "staleMs" old,
999
+ * whatever its source. DEC-37-07: this keeps a fresh decode reading ahead of
1000
+ * the sample TTL so the engine's lagging average never fills an expired slot
1001
+ * as "measured" and pushes routing back to remote. Unlike the catalogue
1002
+ * sweep, an existing (but stale) sample is refreshed, not skipped.
1003
+ */
1004
+ const refreshAged = (models, staleMs, at) => {
1005
+ const targets = normalizeTargets(models)
1006
+ const due = new Set(samples.dueForAgedRefresh(targets.map((target) => target.id), staleMs, at))
1007
+ return runSweep(targets.filter((target) => due.has(target.id)))
1008
+ }
1009
+
1010
+ return {
1011
+ samples,
1012
+ sampleFor: (modelId, at) => samples.sampleFor(modelId, at),
1013
+ latest: (modelId) => samples.latest(modelId),
1014
+ dueForBelowFloorReprobe: (models, floorFor, at) => samples.dueForBelowFloorReprobe(models, floorFor, at),
1015
+ sweep,
1016
+ reprobeBelowFloor,
1017
+ refreshAged
1018
+ }
1019
+ }