@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,993 @@
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
+ },
257
+ device: {
258
+ chipName: device.chip_name,
259
+ memoryGb: device.memory_gb,
260
+ gpuCores: device.gpu_cores
261
+ }
262
+ }
263
+ }
264
+
265
+ const fetchRequest = async (url, init) => {
266
+ const response = await fetch(url, {
267
+ method: "GET",
268
+ headers: { ...init.headers },
269
+ signal: init.signal
270
+ })
271
+ return { status: response.status, text: await response.text() }
272
+ }
273
+
274
+ const normalizeInteger = (value, fallback, min, max) =>
275
+ typeof value === "number" && Number.isFinite(value)
276
+ ? Math.min(max, Math.max(min, Math.trunc(value)))
277
+ : fallback
278
+
279
+ /**
280
+ * Build a telemetry reader. Everything network-facing is injectable so host
281
+ * tests run on fixtures; the default transport uses global fetch.
282
+ */
283
+ export const createOmlxTelemetry = (options = {}) => {
284
+ const source = (options.baseUrl ?? DEFAULT_OMLX_BASE_URL).replace(/\/+$/u, "")
285
+ const request = options.request ?? fetchRequest
286
+ const now = options.now ?? (() => new Date())
287
+ const timeoutMs = normalizeInteger(options.timeoutMs, 1500, 1, 60_000)
288
+ const maxAttempts = normalizeInteger(options.retries, 1, 0, 5) + 1
289
+ const headers = { Accept: "application/json" }
290
+ if (typeof options.apiKey === "string" && options.apiKey.trim().length > 0) {
291
+ headers.Authorization = `Bearer ${options.apiKey}`
292
+ }
293
+
294
+ const toReadError = (error, endpoint, attempts) => {
295
+ if (error instanceof TelemetryReadError) return error
296
+ if (error instanceof AttemptFailure) {
297
+ return new TelemetryReadError({
298
+ kind: error.kind,
299
+ endpoint,
300
+ status: error.status,
301
+ attempts,
302
+ message: `oMLX ${endpoint} ${error.message}`,
303
+ cause: error
304
+ })
305
+ }
306
+ const detail = error instanceof Error ? error.message : String(error)
307
+ return new TelemetryReadError({
308
+ kind: "network",
309
+ endpoint,
310
+ status: null,
311
+ attempts,
312
+ message: `oMLX ${endpoint} request failed: ${detail}`,
313
+ cause: error
314
+ })
315
+ }
316
+
317
+ const perform = async (url, signal) => {
318
+ const controller = new AbortController()
319
+ const abort = () => controller.abort()
320
+ if (signal !== undefined && signal.aborted) abort()
321
+ else if (signal !== undefined) signal.addEventListener("abort", abort, { once: true })
322
+
323
+ let timer = null
324
+ const deadline = new Promise((_, reject) => {
325
+ timer = setTimeout(() => {
326
+ controller.abort()
327
+ reject(new AttemptFailure("timeout", `timed out after ${timeoutMs}ms`))
328
+ }, timeoutMs)
329
+ })
330
+
331
+ try {
332
+ const response = await Promise.race([
333
+ request(url, { headers, signal: controller.signal }),
334
+ deadline
335
+ ])
336
+ if (response.status < 200 || response.status >= 300) {
337
+ throw new AttemptFailure("http", `returned HTTP ${response.status}`, response.status)
338
+ }
339
+ try {
340
+ return JSON.parse(response.text)
341
+ } catch (cause) {
342
+ throw new AttemptFailure("parse", "response was not valid JSON", null, cause)
343
+ }
344
+ } finally {
345
+ if (timer !== null) clearTimeout(timer)
346
+ if (signal !== undefined) signal.removeEventListener("abort", abort)
347
+ }
348
+ }
349
+
350
+ const readPath = async (path, validate, signal) => {
351
+ const endpoint = source + path
352
+ let last = null
353
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
354
+ try {
355
+ const body = await perform(endpoint, signal)
356
+ try {
357
+ return validate(body)
358
+ } catch (cause) {
359
+ throw new TelemetryReadError({
360
+ kind: "validation",
361
+ endpoint,
362
+ status: null,
363
+ attempts: attempt,
364
+ message: `oMLX ${endpoint} payload failed validation: ${cause instanceof Error ? cause.message : String(cause)}`,
365
+ cause
366
+ })
367
+ }
368
+ } catch (error) {
369
+ const typed = toReadError(error, endpoint, attempt)
370
+ if (!typed.retryable || attempt >= maxAttempts) throw typed
371
+ last = typed
372
+ }
373
+ }
374
+ throw last ?? new TelemetryReadError({
375
+ kind: "network",
376
+ endpoint,
377
+ status: null,
378
+ attempts: maxAttempts,
379
+ message: `oMLX ${endpoint} failed`
380
+ })
381
+ }
382
+
383
+ return async ({ signal } = {}) => {
384
+ const stats = await readPath("/admin/api/stats", validateStats, signal)
385
+ const activity = await readPath("/admin/api/activity", validateActivity, signal)
386
+ const models = await readPath("/admin/api/models", validateModels, signal)
387
+ const device = await readPath("/admin/api/device-info", validateDevice, signal)
388
+ // Optional: a missing or invalid global-settings endpoint keeps engineMax null.
389
+ let settings = null
390
+ try {
391
+ settings = await readPath("/admin/api/global-settings", validateGlobalSettings, signal)
392
+ } catch {
393
+ settings = null
394
+ }
395
+ return buildSnapshot(source, now().toISOString(), stats, activity, models, device, settings)
396
+ }
397
+ }
398
+
399
+ // ---------------------------------------------------------------------------
400
+ // Run 36 (DEC-36-06/07, R-36-07): model speed samples and the probe runner.
401
+ //
402
+ // A speed sample is one local model's measured generation throughput, with the
403
+ // source that produced it and when it was taken. Samples expire; an expired
404
+ // sample is unknown and must never be used to skip a model.
405
+ //
406
+ // A probe is a tiny timed generation against the local engine, bounded by a
407
+ // timeout. Probes run only in background sweeps — boot, catalogue change and a
408
+ // ten-minute re-probe of a model that is below its floor — never inside a
409
+ // request path and never against a remote model. Routing reads sampleFor(),
410
+ // which is synchronous and never waits on the network.
411
+
412
+ export const SPEED_SAMPLE_TTL_MS = 15 * 60 * 1000
413
+ export const BELOW_FLOOR_REPROBE_MS = 10 * 60 * 1000
414
+ export const SPEED_SOURCES = ["measured", "probe", "unknown"]
415
+ export const PROBE_MAX_TOKENS = 8
416
+ export const PROBE_PROMPT = "Reply with the single word pong."
417
+ export const DEFAULT_PROBE_TIMEOUT_MS = 20_000
418
+
419
+ const roundTps = (value) => Math.round(value * 10) / 10
420
+
421
+ const asDate = (value, fallback) => {
422
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value
423
+ if (typeof value === "string" || typeof value === "number") {
424
+ const parsed = new Date(value)
425
+ if (!Number.isNaN(parsed.getTime())) return parsed
426
+ }
427
+ const resolved = typeof fallback === "function" ? fallback() : fallback
428
+ if (resolved instanceof Date && !Number.isNaN(resolved.getTime())) return resolved
429
+ return new Date()
430
+ }
431
+
432
+ const normalizeSpeedError = (error) => {
433
+ if (error === null || error === undefined) return null
434
+ if (typeof error !== "object") return { kind: "error", message: String(error) }
435
+ const out = {
436
+ kind: typeof error.kind === "string" ? error.kind : "error",
437
+ message: typeof error.message === "string" ? error.message : String(error.message ?? error)
438
+ }
439
+ if (error.status !== undefined) out.status = error.status
440
+ if (error.retryable !== undefined) out.retryable = error.retryable
441
+ return out
442
+ }
443
+
444
+ /**
445
+ * Per-model speed sample store with a TTL. Reads are synchronous and never
446
+ * touch the network, so a routing decision can always consult it.
447
+ */
448
+ export const createSpeedSamples = (options = {}) => {
449
+ const now = options.now ?? (() => new Date())
450
+ const ttlMs = normalizeInteger(options.ttlMs, SPEED_SAMPLE_TTL_MS, 1, 24 * 60 * 60 * 1000)
451
+ const belowFloorReprobeMs = normalizeInteger(
452
+ options.belowFloorReprobeMs,
453
+ BELOW_FLOOR_REPROBE_MS,
454
+ 1,
455
+ 24 * 60 * 60 * 1000
456
+ )
457
+ const samples = new Map()
458
+
459
+ const ageOf = (sample, reference = asDate(undefined, now)) =>
460
+ Math.max(0, reference.getTime() - asDate(sample.at, now).getTime())
461
+
462
+ const record = (input = {}) => {
463
+ const modelId = input.modelId
464
+ if (typeof modelId !== "string" || modelId.length === 0) {
465
+ throw new TypeError("a speed sample needs a model id")
466
+ }
467
+ if (!SPEED_SOURCES.includes(input.source)) {
468
+ throw new TypeError("a speed sample needs a known source")
469
+ }
470
+ const unknown = input.source === "unknown"
471
+ const tps = unknown ? null : input.tps
472
+ if (!unknown && !(typeof tps === "number" && Number.isFinite(tps) && tps >= 0)) {
473
+ throw new TypeError("a measured speed sample needs a finite tps")
474
+ }
475
+ const sample = {
476
+ modelId,
477
+ tps: unknown ? null : roundTps(tps),
478
+ source: input.source,
479
+ at: asDate(input.at, now).toISOString(),
480
+ error: normalizeSpeedError(input.error)
481
+ }
482
+ if (!unknown && Number.isFinite(input.tokens)) sample.tokens = Math.max(0, Math.trunc(input.tokens))
483
+ if (Number.isFinite(input.elapsedMs)) sample.elapsedMs = Math.max(0, Math.trunc(input.elapsedMs))
484
+ // R-37-02 / DEC-37-06 (Owner): the engine's own speed measure gates the floor
485
+ // at routing time, but the engine average is slow to move, so a model that fell
486
+ // below the floor needs a PROBE to show its recovery. Both are evidence that
487
+ // the model is AT LEAST that fast, so a fresh reading is never lowered or
488
+ // nulled by a weaker or failed one; once it expires the next reading rules.
489
+ const existing = samples.get(modelId)
490
+ const existingAt = existing === undefined ? null : asDate(existing.at, now)
491
+ const existingFresh =
492
+ existing !== undefined &&
493
+ existingAt !== null &&
494
+ ageOf(existing, asDate(sample.at, now)) < ttlMs &&
495
+ typeof existing.tps === "number"
496
+ if (existingFresh && (unknown || existing.tps > sample.tps)) {
497
+ return { ...existing }
498
+ }
499
+ samples.set(modelId, sample)
500
+ return { ...sample }
501
+ }
502
+
503
+ const measured = (modelId, tps, at) => record({ modelId, tps, source: "measured", at })
504
+ const unknown = (modelId, error, at) =>
505
+ record({ modelId, tps: null, source: "unknown", error, at })
506
+
507
+ /** The stored reading, expired or not. Evidence only; never a gate input. */
508
+ const latest = (modelId) => {
509
+ const sample = samples.get(modelId)
510
+ return sample === undefined ? null : { ...sample }
511
+ }
512
+
513
+ /**
514
+ * The gate view of a model's speed. An expired sample is unknown: tps is
515
+ * null, source is "unknown" and expired is true, so it can never skip a
516
+ * model. Null means no sample was ever taken.
517
+ */
518
+ const sampleFor = (modelId, at) => {
519
+ const sample = samples.get(modelId)
520
+ if (sample === undefined) return null
521
+ const ageMs = ageOf(sample, asDate(at, now))
522
+ const expired = ageMs >= ttlMs
523
+ if (expired) return { ...sample, tps: null, source: "unknown", ageMs, expired: true }
524
+ return { ...sample, ageMs, expired: false }
525
+ }
526
+
527
+ const floorOf = (floorFor, modelId) => (typeof floorFor === "function" ? floorFor(modelId) : floorFor)
528
+
529
+ /**
530
+ * Models whose newest reading is below the floor and at least ten minutes
531
+ * old. Only models that already have a reading are due: a model with no
532
+ * sample belongs to the boot or catalogue-change sweep instead.
533
+ */
534
+ const dueForBelowFloorReprobe = (models, floorFor, at) => {
535
+ const reference = asDate(at, now)
536
+ const due = []
537
+ const seen = new Set()
538
+ for (const entry of Array.isArray(models) ? models : []) {
539
+ const modelId = typeof entry === "string" ? entry : entry?.id
540
+ if (typeof modelId !== "string" || modelId.length === 0 || seen.has(modelId)) continue
541
+ seen.add(modelId)
542
+ const sample = samples.get(modelId)
543
+ if (sample === undefined || sample.tps === null) continue
544
+ const floor = floorOf(floorFor, modelId)
545
+ if (typeof floor !== "number" || !Number.isFinite(floor) || floor < 0) continue
546
+ if (sample.tps >= floor) continue
547
+ if (ageOf(sample, reference) < belowFloorReprobeMs) continue
548
+ due.push(modelId)
549
+ }
550
+ return due
551
+ }
552
+
553
+ /**
554
+ * Models whose newest reading is at least "staleMs" old, whatever its source
555
+ * (measured, probe or a failed unknown). DEC-37-07: the engine's averaged
556
+ * speed is a lagging indicator, so a probe sample must be renewed before it
557
+ * expires and lets the engine average fill the slot. A model with no reading
558
+ * belongs to the boot or catalogue-change sweep instead.
559
+ */
560
+ const dueForAgedRefresh = (models, staleMs, at) => {
561
+ const reference = asDate(at, now)
562
+ const stale = normalizeInteger(staleMs, ttlMs / 2, 1, 24 * 60 * 60 * 1000)
563
+ const due = []
564
+ const seen = new Set()
565
+ for (const entry of Array.isArray(models) ? models : []) {
566
+ const modelId = typeof entry === "string" ? entry : entry?.id
567
+ if (typeof modelId !== "string" || modelId.length === 0 || seen.has(modelId)) continue
568
+ seen.add(modelId)
569
+ const sample = samples.get(modelId)
570
+ if (sample === undefined) continue
571
+ if (ageOf(sample, reference) < stale) continue
572
+ due.push(modelId)
573
+ }
574
+ return due
575
+ }
576
+
577
+ const snapshot = (at) => {
578
+ const out = {}
579
+ for (const modelId of [...samples.keys()].sort()) {
580
+ const view = sampleFor(modelId, at)
581
+ if (view !== null) out[modelId] = view
582
+ }
583
+ return out
584
+ }
585
+
586
+ return {
587
+ record,
588
+ measured,
589
+ unknown,
590
+ latest,
591
+ sampleFor,
592
+ dueForBelowFloorReprobe,
593
+ dueForAgedRefresh,
594
+ snapshot,
595
+ ttlMs,
596
+ belowFloorReprobeMs
597
+ }
598
+ }
599
+
600
+ /** OpenAI chat base for an engine endpoint (tolerates a trailing /v1 or /admin). */
601
+ const probeBaseUrl = (baseUrl) => {
602
+ const raw = typeof baseUrl === "string" && baseUrl.length > 0 ? baseUrl : DEFAULT_OMLX_BASE_URL
603
+ const trimmed = raw.replace(/\/+$/u, "").replace(/\/admin(\/api)?$/u, "")
604
+ return /\/v1$/u.test(trimmed) ? trimmed : trimmed + "/v1"
605
+ }
606
+
607
+ const probeFetch = async (url, init) => {
608
+ const response = await fetch(url, {
609
+ method: init.method,
610
+ headers: { ...init.headers },
611
+ body: init.body,
612
+ signal: init.signal
613
+ })
614
+ if (response.body !== null && response.body !== undefined) {
615
+ return { status: response.status, stream: response.body }
616
+ }
617
+ return { status: response.status, text: await response.text() }
618
+ }
619
+
620
+ const estimateTokens = (text) => {
621
+ const trimmed = typeof text === "string" ? text.trim() : ""
622
+ return trimmed.length === 0 ? 1 : Math.max(1, Math.round(trimmed.length / 4))
623
+ }
624
+
625
+ const completionOf = (body) => {
626
+ const choice = Array.isArray(body?.choices) ? body.choices[0] : undefined
627
+ if (typeof choice?.message?.content === "string") return choice.message.content
628
+ if (typeof choice?.text === "string") return choice.text
629
+ return null
630
+ }
631
+
632
+ const isAsyncIterable = (value) =>
633
+ value !== null && value !== undefined && typeof value[Symbol.asyncIterator] === "function"
634
+
635
+ const deltaHasTokens = (delta) => {
636
+ if (!isRecord(delta)) return false
637
+ if (typeof delta.content === "string" && delta.content.length > 0) return true
638
+ if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0) return true
639
+ return Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0
640
+ }
641
+
642
+ /**
643
+ * Read a chat-completions SSE body and record the wall-clock timestamps of the
644
+ * first generated delta and the finish marker. Streaming lets the probe measure
645
+ * decode-only throughput: request setup and prefill happen before the first
646
+ * delta and must not be charged to generation speed. A server that ignored
647
+ * stream:true and sent a non-SSE body accumulates its text here so the caller
648
+ * can fall back to JSON parsing.
649
+ */
650
+ const readSseStream = async (stream, now) => {
651
+ const state = { text: "", content: "", firstDeltaAt: null, finishAt: null, usageTokens: null }
652
+ const decoder = new TextDecoder()
653
+ let buffer = ""
654
+ const consumeLine = (line, atMs) => {
655
+ const trimmed = line.trim()
656
+ if (!trimmed.startsWith("data:")) return
657
+ const data = trimmed.slice("data:".length).trim()
658
+ if (data === "[DONE]") {
659
+ if (state.finishAt === null) state.finishAt = atMs
660
+ return
661
+ }
662
+ let payload
663
+ try {
664
+ payload = JSON.parse(data)
665
+ } catch {
666
+ return
667
+ }
668
+ if (!isRecord(payload)) return
669
+ const choice = Array.isArray(payload.choices) ? payload.choices[0] : undefined
670
+ const delta = choice?.delta
671
+ if (isRecord(delta) && typeof delta.content === "string" && delta.content.length > 0) {
672
+ state.content += delta.content
673
+ }
674
+ // The decode window starts at the first delta of ANY kind: a reasoning model
675
+ // streams delta.reasoning_content (and possibly delta.tool_calls) before any
676
+ // content, and usage.completion_tokens counts those generated tokens too.
677
+ if (deltaHasTokens(delta) && state.firstDeltaAt === null) state.firstDeltaAt = atMs
678
+ const finish = choice?.finish_reason
679
+ if (typeof finish === "string" && finish.length > 0 && state.finishAt === null) {
680
+ state.finishAt = atMs
681
+ }
682
+ const usageTokens = payload?.usage?.completion_tokens
683
+ if (typeof usageTokens === "number" && Number.isFinite(usageTokens) && usageTokens > 0) {
684
+ state.usageTokens = Math.trunc(usageTokens)
685
+ }
686
+ }
687
+ for await (const chunk of stream) {
688
+ const atMs = now().getTime()
689
+ const piece = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true })
690
+ state.text += piece
691
+ buffer += piece
692
+ let index
693
+ while ((index = buffer.indexOf("\n")) !== -1) {
694
+ const line = buffer.slice(0, index).replace(/\r$/u, "")
695
+ buffer = buffer.slice(index + 1)
696
+ consumeLine(line, atMs)
697
+ }
698
+ }
699
+ const tail = decoder.decode()
700
+ state.text += tail
701
+ buffer += tail
702
+ if (buffer.trim().length > 0) consumeLine(buffer, now().getTime())
703
+ if (state.firstDeltaAt !== null && state.finishAt === null) state.finishAt = now().getTime()
704
+ return state
705
+ }
706
+
707
+ /**
708
+ * Tiny timed generation against one local model. The probe is bounded by a
709
+ * timeout and returns the sample or a typed error; it never throws.
710
+ */
711
+ export const createModelProbe = (options = {}) => {
712
+ const base = probeBaseUrl(options.baseUrl)
713
+ const request = options.request ?? probeFetch
714
+ const now = options.now ?? (() => new Date())
715
+ const timeoutMs = normalizeInteger(options.timeoutMs, DEFAULT_PROBE_TIMEOUT_MS, 1, 120_000)
716
+ const maxTokens = normalizeInteger(options.maxTokens, PROBE_MAX_TOKENS, 1, 16)
717
+ const prompt =
718
+ typeof options.prompt === "string" && options.prompt.length > 0 ? options.prompt : PROBE_PROMPT
719
+ const headers = { Accept: "application/json", "Content-Type": "application/json" }
720
+ if (typeof options.apiKey === "string" && options.apiKey.trim().length > 0) {
721
+ headers.Authorization = `Bearer ${options.apiKey}`
722
+ }
723
+
724
+ const probeModel = async (modelId, callOptions = {}) => {
725
+ if (typeof modelId !== "string" || modelId.length === 0) {
726
+ return { ok: false, error: { kind: "invalid", message: "a probe needs a model id" } }
727
+ }
728
+ const url = base + "/chat/completions"
729
+ const body = JSON.stringify({
730
+ model: modelId,
731
+ messages: [{ role: "user", content: prompt }],
732
+ max_tokens: maxTokens,
733
+ stream: true,
734
+ stream_options: { include_usage: true },
735
+ temperature: 0
736
+ })
737
+ const controller = new AbortController()
738
+ const abort = () => controller.abort()
739
+ const outer = callOptions.signal
740
+ if (outer !== undefined) {
741
+ if (outer.aborted) abort()
742
+ else outer.addEventListener("abort", abort, { once: true })
743
+ }
744
+ let timer = null
745
+ const startedAt = now().getTime()
746
+ const makeSample = (tokens, elapsedMs) => ({
747
+ ok: true,
748
+ sample: {
749
+ modelId,
750
+ tps: roundTps(tokens / (elapsedMs / 1000)),
751
+ source: "probe",
752
+ at: now().toISOString(),
753
+ error: null,
754
+ tokens,
755
+ elapsedMs
756
+ }
757
+ })
758
+ try {
759
+ const deadline = new Promise((_, reject) => {
760
+ timer = setTimeout(() => {
761
+ controller.abort()
762
+ reject(new AttemptFailure("timeout", `probe timed out after ${timeoutMs}ms`))
763
+ }, timeoutMs)
764
+ })
765
+ const pending = Promise.resolve().then(() =>
766
+ request(url, { method: "POST", headers, body, signal: controller.signal })
767
+ )
768
+ // After a timeout the aborted request may still reject; never leave it unhandled.
769
+ pending.catch(() => {})
770
+ const response = await Promise.race([pending, deadline])
771
+ if (response === null || typeof response.status !== "number" || response.status < 200 || response.status >= 300) {
772
+ throw new AttemptFailure("http", `probe returned HTTP ${response?.status}`, response?.status ?? null)
773
+ }
774
+ // A streaming body lets decode time be measured token-by-token. A buffered
775
+ // or non-SSE body falls back to the total-time measurement below.
776
+ const stream = response?.stream ?? response?.body
777
+ let sse = null
778
+ let text = null
779
+ if (isAsyncIterable(stream)) {
780
+ const reading = readSseStream(stream, now)
781
+ reading.catch(() => {})
782
+ sse = await Promise.race([reading, deadline])
783
+ text = sse.text
784
+ } else if (typeof response?.text === "string") {
785
+ text = response.text
786
+ } else if (response !== null && typeof response?.text === "function") {
787
+ text = await Promise.race([Promise.resolve(response.text()), deadline])
788
+ }
789
+ if (sse !== null && sse.firstDeltaAt !== null && sse.finishAt !== null) {
790
+ // completion_tokens comes from the stream's usage when the engine sends it;
791
+ // otherwise the accumulated content is estimated as before.
792
+ const tokens = sse.usageTokens !== null ? sse.usageTokens : estimateTokens(sse.content)
793
+ if (sse.finishAt > sse.firstDeltaAt) {
794
+ // Decode-only: request setup and prefill are excluded from the throughput.
795
+ return makeSample(tokens, Math.max(1, sse.finishAt - sse.firstDeltaAt))
796
+ }
797
+ // A whole completion delivered in one chunk has no observable decode
798
+ // window; fall back to total wall time rather than failing the probe.
799
+ return makeSample(tokens, Math.max(1, now().getTime() - startedAt))
800
+ }
801
+ // Fallback: a server that ignored stream:true (or a non-SSE body) is timed
802
+ // over total wall time, exactly as before streaming probes existed.
803
+ if (text === null) throw new AttemptFailure("invalid", "probe response had no body", null)
804
+ let payload
805
+ try {
806
+ payload = JSON.parse(text)
807
+ } catch (cause) {
808
+ throw new AttemptFailure("parse", "probe response was not valid JSON", null, cause)
809
+ }
810
+ const content = completionOf(payload)
811
+ if (content === null) throw new AttemptFailure("invalid", "probe response had no completion", null)
812
+ const usageTokens = payload?.usage?.completion_tokens
813
+ const tokens =
814
+ typeof usageTokens === "number" && Number.isFinite(usageTokens) && usageTokens > 0
815
+ ? Math.trunc(usageTokens)
816
+ : estimateTokens(content)
817
+ const elapsedMs = Math.max(1, now().getTime() - startedAt)
818
+ return makeSample(tokens, elapsedMs)
819
+ } catch (error) {
820
+ const kind = error instanceof AttemptFailure ? error.kind : "network"
821
+ const out = { kind, message: error instanceof Error ? error.message : String(error) }
822
+ if (error instanceof AttemptFailure && error.status !== null) out.status = error.status
823
+ return { ok: false, error: out }
824
+ } finally {
825
+ if (timer !== null) clearTimeout(timer)
826
+ if (outer !== undefined) outer.removeEventListener("abort", abort)
827
+ }
828
+ }
829
+
830
+ return { probeModel, baseUrl: base, timeoutMs, maxTokens }
831
+ }
832
+
833
+ /**
834
+ * The sweep host surface: a sample store plus the probe. A sweep probes every
835
+ * local model without a sample (boot and catalogue change); a rebuild sweeps
836
+ * only the models that are below floor and ten minutes old. Routing only ever
837
+ * calls sampleFor().
838
+ */
839
+ export const createSpeedProber = (options = {}) => {
840
+ const samples =
841
+ options.samples !== undefined && typeof options.samples?.sampleFor === "function"
842
+ ? options.samples
843
+ : createSpeedSamples({
844
+ now: options.now,
845
+ ttlMs: options.ttlMs,
846
+ belowFloorReprobeMs: options.belowFloorReprobeMs
847
+ })
848
+ const providedProbe =
849
+ options.probe !== undefined && typeof options.probe === "object" && options.probe !== null
850
+ ? options.probe
851
+ : {}
852
+ const probeFn =
853
+ typeof options.probe === "function"
854
+ ? options.probe
855
+ : typeof providedProbe.probeModel === "function"
856
+ ? (modelId) => providedProbe.probeModel(modelId)
857
+ : createModelProbe(
858
+ typeof options.probe === "object" && options.probe !== null
859
+ ? options.probe
860
+ : {
861
+ // F-37-02 (decisive): a caller passes the live engine endpoint
862
+ // and key as top-level options; the default probe must honour
863
+ // them instead of falling back to the 8000 default with no auth.
864
+ baseUrl: options.baseUrl,
865
+ apiKey: options.apiKey,
866
+ now: options.now,
867
+ timeoutMs: options.timeoutMs,
868
+ maxTokens: options.maxTokens,
869
+ prompt: options.prompt
870
+ }
871
+ ).probeModel
872
+ const isLocalModel = typeof options.isLocalModel === "function" ? options.isLocalModel : null
873
+ const inFlight = new Set()
874
+
875
+ const listOf = (models) => {
876
+ if (Array.isArray(models)) return models
877
+ if (models !== null && typeof models === "object" && typeof models[Symbol.iterator] === "function") {
878
+ return [...models]
879
+ }
880
+ return []
881
+ }
882
+
883
+ const normalizeTargets = (models) => {
884
+ const targets = []
885
+ for (const entry of listOf(models)) {
886
+ if (typeof entry === "string") {
887
+ if (entry.length > 0) targets.push({ id: entry, local: undefined })
888
+ continue
889
+ }
890
+ if (entry === null || typeof entry !== "object") continue
891
+ if (typeof entry.id !== "string" || entry.id.length === 0) continue
892
+ targets.push({ id: entry.id, local: entry.local })
893
+ }
894
+ return targets
895
+ }
896
+
897
+ const isLocal = (target) => {
898
+ if (target.local === false) return false
899
+ if (isLocalModel === null) return true
900
+ return isLocalModel(target.id) === true
901
+ }
902
+
903
+ const probeOne = async (modelId) => {
904
+ inFlight.add(modelId)
905
+ try {
906
+ let result
907
+ try {
908
+ result = await probeFn(modelId)
909
+ } catch (error) {
910
+ result = {
911
+ ok: false,
912
+ error: { kind: "network", message: error instanceof Error ? error.message : String(error) }
913
+ }
914
+ }
915
+ if (result !== null && typeof result === "object" && result.ok === true && result.sample !== undefined) {
916
+ samples.record({
917
+ modelId,
918
+ tps: result.sample.tps,
919
+ source: "probe",
920
+ at: result.sample.at,
921
+ error: null,
922
+ tokens: result.sample.tokens,
923
+ elapsedMs: result.sample.elapsedMs
924
+ })
925
+ return { modelId, ok: true, tps: result.sample.tps, error: null }
926
+ }
927
+ const error = result?.error ?? { kind: "unknown", message: "a probe returned no sample" }
928
+ samples.unknown(modelId, error)
929
+ return { modelId, ok: false, tps: null, error }
930
+ } finally {
931
+ inFlight.delete(modelId)
932
+ }
933
+ }
934
+
935
+ const runSweep = async (targets, { requireMissing = false } = {}) => {
936
+ const probed = []
937
+ const skipped = []
938
+ const results = []
939
+ for (const target of targets) {
940
+ if (!isLocal(target)) {
941
+ skipped.push({ modelId: target.id, reason: "remote" })
942
+ continue
943
+ }
944
+ if (inFlight.has(target.id)) {
945
+ skipped.push({ modelId: target.id, reason: "in flight" })
946
+ continue
947
+ }
948
+ // A boot/catalogue sweep only fills gaps - but an engine-average
949
+ // "measured" reading is NOT a probe measurement (DEC-37-07: it lags and
950
+ // recovers slowly). Treat only a probe/unknown sample as the gap being
951
+ // filled, so the engine's lagging average can never suppress the probe.
952
+ const latest = samples.latest(target.id)
953
+ if (requireMissing && latest !== null && latest.source !== "measured") {
954
+ skipped.push({ modelId: target.id, reason: "has a probe sample" })
955
+ continue
956
+ }
957
+ probed.push(target.id)
958
+ results.push(await probeOne(target.id))
959
+ }
960
+ return { probed, skipped, results }
961
+ }
962
+
963
+ const sweep = (models) => runSweep(normalizeTargets(models), { requireMissing: true })
964
+
965
+ const reprobeBelowFloor = (models, floorFor, at) => {
966
+ const targets = normalizeTargets(models)
967
+ const due = new Set(samples.dueForBelowFloorReprobe(targets.map((target) => target.id), floorFor, at))
968
+ return runSweep(targets.filter((target) => due.has(target.id)))
969
+ }
970
+
971
+ /**
972
+ * Re-probe every model whose current sample is at least "staleMs" old,
973
+ * whatever its source. DEC-37-07: this keeps a fresh decode reading ahead of
974
+ * the sample TTL so the engine's lagging average never fills an expired slot
975
+ * as "measured" and pushes routing back to remote. Unlike the catalogue
976
+ * sweep, an existing (but stale) sample is refreshed, not skipped.
977
+ */
978
+ const refreshAged = (models, staleMs, at) => {
979
+ const targets = normalizeTargets(models)
980
+ const due = new Set(samples.dueForAgedRefresh(targets.map((target) => target.id), staleMs, at))
981
+ return runSweep(targets.filter((target) => due.has(target.id)))
982
+ }
983
+
984
+ return {
985
+ samples,
986
+ sampleFor: (modelId, at) => samples.sampleFor(modelId, at),
987
+ latest: (modelId) => samples.latest(modelId),
988
+ dueForBelowFloorReprobe: (models, floorFor, at) => samples.dueForBelowFloorReprobe(models, floorFor, at),
989
+ sweep,
990
+ reprobeBelowFloor,
991
+ refreshAged
992
+ }
993
+ }