@try-works/dsh-minimal-router 0.2.9 → 0.2.11
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/client/index.js +1939 -1510
- package/lib/backend.js +40 -9
- package/lib/build-id.js +1 -1
- package/lib/engine-adapter.js +24 -8
- package/lib/engines/contract.js +59 -0
- package/lib/engines/mlx-serve.js +183 -0
- package/lib/engines/omlx.js +185 -0
- package/lib/engines/select.js +40 -0
- package/lib/engines/snapshot.js +345 -0
- package/lib/evidence.js +96 -1
- package/lib/index.js +127 -6
- package/lib/routing.js +22 -9
- package/lib/telemetry-series.js +275 -0
- package/lib/telemetry.js +30 -3
- package/package.json +1 -1
package/lib/backend.js
CHANGED
|
@@ -1,14 +1,45 @@
|
|
|
1
|
-
// Backend boundary for the DSH host process
|
|
2
|
-
//
|
|
1
|
+
// Backend boundary for the DSH host process (run 39, DEC-39-01/02).
|
|
2
|
+
//
|
|
3
|
+
// The connection's kind selects exactly ONE engine source through
|
|
4
|
+
// selectEngineSource; the host only ever sees read({signal}) => snapshot, so the
|
|
5
|
+
// routing core never learns about an engine's wire shape. An unknown kind is an
|
|
6
|
+
// error, not a fallback to another engine.
|
|
3
7
|
import { createOmlxTelemetry } from "./telemetry.js"
|
|
8
|
+
import { createOmlxSource } from "./engines/omlx.js"
|
|
9
|
+
import { createMlxServeSource } from "./engines/mlx-serve.js"
|
|
10
|
+
import { selectEngineSource, engineKindOf } from "./engines/select.js"
|
|
11
|
+
import { createSnapshotReader } from "./engines/snapshot.js"
|
|
12
|
+
|
|
13
|
+
/** True when the selected engine has the oMLX admin surface (memory, queue). */
|
|
14
|
+
export const hasAdminSurface = (kind) => kind === "omlx"
|
|
4
15
|
|
|
5
16
|
export const createLocalBackend = (options = {}) => {
|
|
6
|
-
const kind = options.kind ?? "omlx"
|
|
7
|
-
if (kind
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
17
|
+
const kind = engineKindOf({ kind: options.kind ?? "omlx" })
|
|
18
|
+
if (kind === null) throw new Error("unsupported local backend: " + String(options.kind))
|
|
19
|
+
const selected = selectEngineSource(
|
|
20
|
+
{ kind, endpoint: options.baseUrl, apiKey: options.apiKey },
|
|
21
|
+
{
|
|
22
|
+
getConnection: () => ({ kind, endpoint: options.baseUrl, apiKey: options.apiKey }),
|
|
23
|
+
fetchImpl: options.fetchImpl,
|
|
24
|
+
now: options.now
|
|
25
|
+
}
|
|
26
|
+
)
|
|
27
|
+
if (selected.error !== null || selected.source === null) {
|
|
28
|
+
throw new Error("unsupported local backend: " + String(options.kind))
|
|
13
29
|
}
|
|
30
|
+
const source = selected.source
|
|
31
|
+
// oMLX keeps its existing telemetry reader byte-for-byte (its tests lock the
|
|
32
|
+
// snapshot contract); the source-based reader is used for the others and is
|
|
33
|
+
// exercised for oMLX by the contract suite. This keeps run 39 from silently
|
|
34
|
+
// changing oMLX numbers while the seam lands.
|
|
35
|
+
// The reader is a FUNCTION, not a promise: r39-wire caught this integration bug
|
|
36
|
+
// (snapshotFromSource is async, so calling it eagerly made backend.read a Promise
|
|
37
|
+
// and index.js then treated the backend itself as the reader).
|
|
38
|
+
const read =
|
|
39
|
+
kind === "omlx" && options.useSourceReader !== true
|
|
40
|
+
? createOmlxTelemetry(options)
|
|
41
|
+
: createSnapshotReader(source, { now: options.now })
|
|
42
|
+
return { kind, source, read }
|
|
14
43
|
}
|
|
44
|
+
|
|
45
|
+
export { createOmlxSource, createMlxServeSource }
|
package/lib/build-id.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// GENERATED by scripts/build-id.mjs - do not edit by hand.
|
|
2
2
|
// sha256 over the canonical 19-file list (11 plugin lib + 8 domain contract
|
|
3
3
|
// sources), so a domain-contract change moves the id too (DEC-30-01).
|
|
4
|
-
export const buildId = "
|
|
4
|
+
export const buildId = "62ec21caf664d3f61dfa009f8b43e6b8fb29ccaf0e316a3edc4e661e140b701a"
|
package/lib/engine-adapter.js
CHANGED
|
@@ -274,6 +274,9 @@ export const readSseCompletion = async (response, now) => {
|
|
|
274
274
|
let content = ""
|
|
275
275
|
let reasoning = ""
|
|
276
276
|
let usage = null
|
|
277
|
+
// Run 39: mlx-serve reports its decode rate in a top-level timings block, not in
|
|
278
|
+
// usage. Capture it here so the source's speedOf can read either wire shape.
|
|
279
|
+
let timings = null
|
|
277
280
|
let deltas = 0
|
|
278
281
|
const toolCalls = []
|
|
279
282
|
const decoder = new TextDecoder()
|
|
@@ -292,6 +295,7 @@ export const readSseCompletion = async (response, now) => {
|
|
|
292
295
|
return
|
|
293
296
|
}
|
|
294
297
|
if (event?.usage) usage = event.usage
|
|
298
|
+
if (event?.timings !== null && typeof event?.timings === "object") timings = event.timings
|
|
295
299
|
if (typeof event?.model === "string") body.model = event.model
|
|
296
300
|
if (typeof event?.id === "string") body.id = event.id
|
|
297
301
|
const choice = Array.isArray(event?.choices) ? event.choices[0] : undefined
|
|
@@ -338,10 +342,18 @@ export const readSseCompletion = async (response, now) => {
|
|
|
338
342
|
const tokens = Number.isFinite(Number(usage?.completion_tokens)) && Number(usage.completion_tokens) > 0
|
|
339
343
|
? Number(usage.completion_tokens)
|
|
340
344
|
: deltas
|
|
341
|
-
|
|
345
|
+
if (timings !== null) body.timings = timings
|
|
346
|
+
return { body, decodeStart, decodeEnd, usage, timings, tokens }
|
|
342
347
|
}
|
|
343
348
|
|
|
344
|
-
export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now, modelCapabilities = {}, onRequestSpeed = null, onRequestObserved = null, roleWindowFor = null } = {}) => {
|
|
349
|
+
export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now, modelCapabilities = {}, onRequestSpeed = null, onRequestObserved = null, roleWindowFor = null, speedOf = null, observationOfRequest = null } = {}) => {
|
|
350
|
+
// Run 39 (DEC-39-01): the active engine source owns the speed and observation
|
|
351
|
+
// reads. The adapter never names a wire field; it falls back to the oMLX shape
|
|
352
|
+
// only when no source is wired (the pre-run-39 behaviour).
|
|
353
|
+
const speedRead = typeof speedOf === "function" ? speedOf : (body, usage) => ({
|
|
354
|
+
generationTps: Number.isFinite(Number(usage?.generation_tokens_per_second)) ? Number(usage.generation_tokens_per_second) : null
|
|
355
|
+
})
|
|
356
|
+
const observeRead = typeof observationOfRequest === "function" ? observationOfRequest : observationOf
|
|
345
357
|
// The role's configured context window for a role-scoped provider route, or null
|
|
346
358
|
// when the route is not role-scoped / the role has no finite window (the Advisor's
|
|
347
359
|
// "no cap", DEC-37-05).
|
|
@@ -622,16 +634,16 @@ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now,
|
|
|
622
634
|
if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
|
|
623
635
|
throw engineError("engine stream read failed: " + (error?.message ?? String(error)), "TRANSPORT")
|
|
624
636
|
}
|
|
625
|
-
//
|
|
626
|
-
//
|
|
627
|
-
//
|
|
628
|
-
const reported =
|
|
637
|
+
// The engine's own per-request measure wins (oMLX usage, mlx-serve
|
|
638
|
+
// timings); the decode window is only the fallback. Both land in the one
|
|
639
|
+
// sample store, so the floor gate sees a single scale (DEC-37-10/39-04).
|
|
640
|
+
const reported = speedRead(assembled.body, assembled.usage)?.generationTps
|
|
629
641
|
if (Number.isFinite(reported) && reported > 0) {
|
|
630
642
|
reportTps(model, reported)
|
|
631
643
|
} else if (assembled.decodeStart !== null && assembled.decodeEnd !== null) {
|
|
632
644
|
reportSpeed(model, assembled.decodeStart, assembled.decodeEnd, assembled.tokens)
|
|
633
645
|
}
|
|
634
|
-
reportObserved(model,
|
|
646
|
+
reportObserved(model, observeRead(assembled.body, assembled.usage))
|
|
635
647
|
for (const chunk of toChunks(assembled.body)) yield chunk
|
|
636
648
|
return
|
|
637
649
|
}
|
|
@@ -648,7 +660,11 @@ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now,
|
|
|
648
660
|
} catch {
|
|
649
661
|
throw engineError("engine returned a non-JSON chat response", "SERVER")
|
|
650
662
|
}
|
|
651
|
-
|
|
663
|
+
// Run 39: the non-streaming path used to report no speed at all, which left
|
|
664
|
+
// mlx-serve without a measured sample on this route.
|
|
665
|
+
const reportedSpeed = speedRead(body, body?.usage)?.generationTps
|
|
666
|
+
if (Number.isFinite(reportedSpeed) && reportedSpeed > 0) reportTps(model, reportedSpeed)
|
|
667
|
+
reportObserved(model, observeRead(body, body?.usage))
|
|
652
668
|
for (const chunk of toChunks(body)) yield chunk
|
|
653
669
|
})()
|
|
654
670
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run 39 (DEC-39-01/02/03/04): the Engine source contract.
|
|
3
|
+
*
|
|
4
|
+
* A source is the ONLY place an engine's wire shapes exist. Routing, telemetry
|
|
5
|
+
* and the pages read this normal form, so a second engine cannot fork the
|
|
6
|
+
* decision logic - and exactly one source is mounted at a time, chosen from the
|
|
7
|
+
* connection's kind (DEC-39-02).
|
|
8
|
+
*
|
|
9
|
+
* Every read either returns the documented value or a declared "unavailable"
|
|
10
|
+
* result (null plus a reason). A metric an engine cannot report is never
|
|
11
|
+
* fabricated and never a zero that looks measured (DEC-39-03).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** The one connected engine's kind. Anything else is a settings error, not a fallback. */
|
|
15
|
+
export const ENGINE_KINDS = Object.freeze(["omlx", "mlx-serve"])
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* True when a value is a usable finite number (not NaN, not a numeric string bluff).
|
|
19
|
+
*
|
|
20
|
+
* Run 39 (found by r39-wire): Number(null) === 0 and Number(true) === 1, so a naive
|
|
21
|
+
* Number() check turns "the engine reported nothing" into a fabricated zero - the
|
|
22
|
+
* exact failure this run exists to prevent. Only a real finite number, or a
|
|
23
|
+
* non-empty numeric string from a wire payload, passes.
|
|
24
|
+
*/
|
|
25
|
+
export const finiteOrNull = (value) => {
|
|
26
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null
|
|
27
|
+
if (typeof value === "string") {
|
|
28
|
+
if (value.trim().length === 0) return null
|
|
29
|
+
const parsed = Number(value)
|
|
30
|
+
return Number.isFinite(parsed) ? parsed : null
|
|
31
|
+
}
|
|
32
|
+
return null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Trim a trailing slash so path joins are stable. */
|
|
36
|
+
export const trimBase = (endpoint) => String(endpoint === undefined || endpoint === null ? "" : endpoint).replace(/\/+$/u, "")
|
|
37
|
+
|
|
38
|
+
/** A source read the engine does not implement, with the reason it cannot. */
|
|
39
|
+
export const unavailable = (reason) => ({ ok: false, reason })
|
|
40
|
+
|
|
41
|
+
/** The contract every engine source implements, as a runtime check for tests. */
|
|
42
|
+
export const SOURCE_MEMBERS = Object.freeze([
|
|
43
|
+
"kind",
|
|
44
|
+
"label",
|
|
45
|
+
"catalogue",
|
|
46
|
+
"contract",
|
|
47
|
+
"activity",
|
|
48
|
+
"memory",
|
|
49
|
+
"speedOf",
|
|
50
|
+
"observationOf",
|
|
51
|
+
"health"
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
/** Assert one object is a complete source; returns the missing members. */
|
|
55
|
+
export const missingSourceMembers = (source) =>
|
|
56
|
+
SOURCE_MEMBERS.filter((member) => {
|
|
57
|
+
if (member === "kind" || member === "label") return typeof source?.[member] !== "string"
|
|
58
|
+
return typeof source?.[member] !== "function"
|
|
59
|
+
})
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run 39: the mlx-serve Engine source.
|
|
3
|
+
*
|
|
4
|
+
* Every read is mapped to a probed endpoint of mlx-serve 26.12.2 (analysis in
|
|
5
|
+
* runs/39-mlx-serve-adapter/run.json):
|
|
6
|
+
* catalogue GET /v1/models (Ollama-shaped: models[] + data[])
|
|
7
|
+
* contract GET /props (n_ctx, total_slots, model_alias)
|
|
8
|
+
* activity GET /slots (per-slot is_processing)
|
|
9
|
+
* memory GET /metrics.json, only when the server was started --metrics
|
|
10
|
+
* speed the completion's own timings.predicted_per_second
|
|
11
|
+
* health GET /health
|
|
12
|
+
*
|
|
13
|
+
* mlx-serve has no admin API (/admin, /stats, /api/ps are 404), so memory,
|
|
14
|
+
* pressure, pinning and a waiting queue are declared unavailable with a reason
|
|
15
|
+
* rather than mapped onto an invented number (DEC-39-03).
|
|
16
|
+
*/
|
|
17
|
+
import { finiteOrNull, trimBase, unavailable } from "./contract.js"
|
|
18
|
+
|
|
19
|
+
export const MLX_SERVE_KIND = "mlx-serve"
|
|
20
|
+
|
|
21
|
+
/** The normal form for one catalogue entry. */
|
|
22
|
+
export const catalogueEntry = (raw) => {
|
|
23
|
+
const id = typeof raw?.id === "string" && raw.id.length > 0 ? raw.id : typeof raw?.model === "string" ? raw.model : null
|
|
24
|
+
if (id === null) return null
|
|
25
|
+
const aliases = Array.isArray(raw?.aliases) ? raw.aliases.filter((alias) => typeof alias === "string") : []
|
|
26
|
+
const architecture = raw?.architecture !== null && typeof raw?.architecture === "object" ? raw.architecture : {}
|
|
27
|
+
const window = finiteOrNull(architecture.context_length) ?? finiteOrNull(architecture.max_position_embeddings)
|
|
28
|
+
return { id, aliases, contextWindow: window }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The catalogue from an mlx-serve /v1/models payload, de-duplicated by id. */
|
|
32
|
+
export const catalogueOf = (payload) => {
|
|
33
|
+
const entries = []
|
|
34
|
+
const seen = new Set()
|
|
35
|
+
const push = (raw) => {
|
|
36
|
+
const entry = catalogueEntry(raw)
|
|
37
|
+
if (entry === null || seen.has(entry.id)) return
|
|
38
|
+
seen.add(entry.id)
|
|
39
|
+
entries.push(entry)
|
|
40
|
+
}
|
|
41
|
+
for (const raw of Array.isArray(payload?.data) ? payload.data : []) push(raw)
|
|
42
|
+
for (const raw of Array.isArray(payload?.models) ? payload.models : []) push(raw)
|
|
43
|
+
return entries
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The contract from a /props payload: the window actually served and the slot ceiling. */
|
|
47
|
+
export const contractOf = (props) => ({
|
|
48
|
+
contextWindow: finiteOrNull(props?.default_generation_settings?.n_ctx) ?? finiteOrNull(props?.n_ctx),
|
|
49
|
+
concurrency: finiteOrNull(props?.total_slots),
|
|
50
|
+
modelAlias: typeof props?.model_alias === "string" && props.model_alias.length > 0 ? props.model_alias : null
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
/** Activity from a /slots payload. mlx-serve exposes no waiting queue. */
|
|
54
|
+
export const activityOf = (slots) => {
|
|
55
|
+
const list = Array.isArray(slots) ? slots : []
|
|
56
|
+
const processing = list.filter((slot) => slot?.is_processing === true).length
|
|
57
|
+
const window = list.length > 0 ? finiteOrNull(list[0]?.n_ctx) : null
|
|
58
|
+
return { processing, waiting: null, contextWindow: window }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Memory and pressure. A 501/404 or a payload without the fields means the
|
|
63
|
+
* engine was not started with --metrics: unavailable, with that reason.
|
|
64
|
+
*/
|
|
65
|
+
export const memoryOf = (metrics, httpStatus) => {
|
|
66
|
+
if (httpStatus === 501 || httpStatus === 404 || metrics === null || metrics === undefined) {
|
|
67
|
+
return {
|
|
68
|
+
usedBytes: null,
|
|
69
|
+
maxBytes: null,
|
|
70
|
+
pressure: null,
|
|
71
|
+
unavailable: "mlx-serve exposes memory metrics only when started with --metrics"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const used = finiteOrNull(metrics?.memory_used_bytes) ?? finiteOrNull(metrics?.memory?.used_bytes)
|
|
75
|
+
const max = finiteOrNull(metrics?.memory_total_bytes) ?? finiteOrNull(metrics?.memory?.total_bytes)
|
|
76
|
+
const pressure = typeof metrics?.memory_pressure === "string" ? metrics.memory_pressure : null
|
|
77
|
+
if (used === null && max === null && pressure === null) {
|
|
78
|
+
return {
|
|
79
|
+
usedBytes: null,
|
|
80
|
+
maxBytes: null,
|
|
81
|
+
pressure: null,
|
|
82
|
+
unavailable: "mlx-serve reported no memory fields in metrics"
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { usedBytes: used, maxBytes: max, pressure, unavailable: null }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The fresh per-request speed from a completion body. mlx-serve reports
|
|
90
|
+
* timings.predicted_per_second; the wall clock is only a fallback.
|
|
91
|
+
*/
|
|
92
|
+
export const speedOf = (body, usage) => {
|
|
93
|
+
const u = usage !== null && typeof usage === "object" ? usage : body?.usage ?? {}
|
|
94
|
+
const timings = body?.timings !== null && typeof body?.timings === "object" ? body.timings : {}
|
|
95
|
+
return {
|
|
96
|
+
generationTps: finiteOrNull(timings.predicted_per_second),
|
|
97
|
+
promptTps: finiteOrNull(timings.prompt_per_second),
|
|
98
|
+
completionTokens: finiteOrNull(u.completion_tokens) ?? finiteOrNull(timings.predicted_n),
|
|
99
|
+
promptTokens: finiteOrNull(u.prompt_tokens) ?? finiteOrNull(timings.prompt_n)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The observation the ledger joins: the engine id and its per-request timings. */
|
|
104
|
+
export const observationOf = (body, usage) => {
|
|
105
|
+
const speed = speedOf(body, usage)
|
|
106
|
+
return {
|
|
107
|
+
engineRequestId: typeof body?.id === "string" && body.id.length > 0 ? body.id : null,
|
|
108
|
+
promptTokens: speed.promptTokens,
|
|
109
|
+
completionTokens: speed.completionTokens,
|
|
110
|
+
firstTokenMs: null,
|
|
111
|
+
promptEvalMs: finiteOrNull(body?.timings?.prompt_ms),
|
|
112
|
+
generationMs: finiteOrNull(body?.timings?.predicted_ms),
|
|
113
|
+
generationTps: speed.generationTps,
|
|
114
|
+
promptTps: speed.promptTps
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Build the source. One connection, one source: nothing here reads a second
|
|
120
|
+
* engine or falls back to one (DEC-39-02).
|
|
121
|
+
*/
|
|
122
|
+
export const createMlxServeSource = ({ getConnection, fetchImpl, now = Date.now } = {}) => {
|
|
123
|
+
const connectionOf = () => {
|
|
124
|
+
const connection = typeof getConnection === "function" ? getConnection() : {}
|
|
125
|
+
return connection !== null && typeof connection === "object" ? connection : {}
|
|
126
|
+
}
|
|
127
|
+
const doFetch = typeof fetchImpl === "function" ? fetchImpl : (...args) => globalThis.fetch(...args)
|
|
128
|
+
const request = async (path, init) => {
|
|
129
|
+
const connection = connectionOf()
|
|
130
|
+
const base = trimBase(connection.endpoint)
|
|
131
|
+
const headers = { accept: "application/json", ...(init?.headers ?? {}) }
|
|
132
|
+
const key = typeof connection.apiKey === "string" ? connection.apiKey : ""
|
|
133
|
+
if (key.length > 0 && !/^•+$/u.test(key)) headers.authorization = "Bearer " + key
|
|
134
|
+
const response = await doFetch(base + path, { ...init, headers })
|
|
135
|
+
let body = null
|
|
136
|
+
try {
|
|
137
|
+
body = await response.json()
|
|
138
|
+
} catch {
|
|
139
|
+
body = null
|
|
140
|
+
}
|
|
141
|
+
return { status: response.status, body }
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
kind: MLX_SERVE_KIND,
|
|
145
|
+
label: "mlx-serve",
|
|
146
|
+
async catalogue() {
|
|
147
|
+
const { status, body } = await request("/v1/models")
|
|
148
|
+
if (status < 200 || status >= 300) throw new Error("mlx-serve catalogue HTTP " + status)
|
|
149
|
+
return catalogueOf(body)
|
|
150
|
+
},
|
|
151
|
+
async contract() {
|
|
152
|
+
const { status, body } = await request("/props")
|
|
153
|
+
if (status < 200 || status >= 300) return { contextWindow: null, concurrency: null, modelAlias: null }
|
|
154
|
+
return contractOf(body)
|
|
155
|
+
},
|
|
156
|
+
async activity() {
|
|
157
|
+
const { status, body } = await request("/slots")
|
|
158
|
+
if (status < 200 || status >= 300) return { processing: null, waiting: null, contextWindow: null }
|
|
159
|
+
return activityOf(body)
|
|
160
|
+
},
|
|
161
|
+
async memory() {
|
|
162
|
+
const { status, body } = await request("/metrics.json")
|
|
163
|
+
return memoryOf(body, status)
|
|
164
|
+
},
|
|
165
|
+
speedOf,
|
|
166
|
+
observationOf,
|
|
167
|
+
async health() {
|
|
168
|
+
const started = now()
|
|
169
|
+
try {
|
|
170
|
+
const { status } = await request("/health")
|
|
171
|
+
return {
|
|
172
|
+
status: status >= 200 && status < 300 ? "healthy" : "unreachable",
|
|
173
|
+
httpStatus: status,
|
|
174
|
+
latencyMs: Math.max(0, now() - started)
|
|
175
|
+
}
|
|
176
|
+
} catch {
|
|
177
|
+
return { status: "unreachable", httpStatus: null, latencyMs: null }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export { unavailable }
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run 39: the oMLX Engine source.
|
|
3
|
+
*
|
|
4
|
+
* Same contract as mlx-serve (DEC-39-01), so routing and the pages never see an
|
|
5
|
+
* engine's wire shape. Every read is the one the existing adapter/telemetry code
|
|
6
|
+
* already uses:
|
|
7
|
+
* catalogue GET /v1/models (+ /admin/api/models for the served context window)
|
|
8
|
+
* contract GET /admin/api/global-settings engineMax + the model's window
|
|
9
|
+
* activity GET /admin/api/activity (active, waiting, memory, pressure)
|
|
10
|
+
* memory the same activity payload
|
|
11
|
+
* speed usage.generation_tokens_per_second (DEC-37-10: fresh per request)
|
|
12
|
+
* health GET /v1/models
|
|
13
|
+
*/
|
|
14
|
+
import { engineAdminBaseUrl, engineBaseUrl } from "../engine-adapter.js"
|
|
15
|
+
import { finiteOrNull, trimBase } from "./contract.js"
|
|
16
|
+
|
|
17
|
+
export const OMLX_KIND = "omlx"
|
|
18
|
+
|
|
19
|
+
/** The normal form for one catalogue entry, from either oMLX catalogue read. */
|
|
20
|
+
export const catalogueEntry = (raw, adminModel) => {
|
|
21
|
+
const id = typeof raw?.id === "string" && raw.id.length > 0 ? raw.id : null
|
|
22
|
+
if (id === null) return null
|
|
23
|
+
const window =
|
|
24
|
+
finiteOrNull(adminModel?.model_context_length)
|
|
25
|
+
?? finiteOrNull(raw?.max_model_len)
|
|
26
|
+
?? finiteOrNull(raw?.context_length)
|
|
27
|
+
return { id, aliases: [], contextWindow: window }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The catalogue of an oMLX /v1/models payload, merged with /admin/api/models. */
|
|
31
|
+
export const catalogueOf = (models, admin) => {
|
|
32
|
+
const adminModels = Array.isArray(admin?.models) ? admin.models : []
|
|
33
|
+
const byId = new Map()
|
|
34
|
+
for (const model of adminModels) {
|
|
35
|
+
if (typeof model?.id === "string") byId.set(model.id, model)
|
|
36
|
+
}
|
|
37
|
+
const entries = []
|
|
38
|
+
const seen = new Set()
|
|
39
|
+
for (const raw of Array.isArray(models?.data) ? models.data : Array.isArray(models?.models) ? models.models : []) {
|
|
40
|
+
const entry = catalogueEntry(raw, byId.get(raw?.id))
|
|
41
|
+
if (entry === null || seen.has(entry.id)) continue
|
|
42
|
+
seen.add(entry.id)
|
|
43
|
+
entries.push(entry)
|
|
44
|
+
}
|
|
45
|
+
for (const model of adminModels) {
|
|
46
|
+
if (typeof model?.id !== "string" || seen.has(model.id)) continue
|
|
47
|
+
seen.add(model.id)
|
|
48
|
+
entries.push(catalogueEntry(model, model))
|
|
49
|
+
}
|
|
50
|
+
return entries.filter((entry) => entry !== null)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The contract: the scheduler ceiling and the model's served window. */
|
|
54
|
+
export const contractOf = (settings, admin) => {
|
|
55
|
+
const models = Array.isArray(admin?.models) ? admin.models : []
|
|
56
|
+
const preferred = models.find((model) => model?.is_default === true && model?.pinned !== true)
|
|
57
|
+
?? models.find((model) => model?.pinned === true)
|
|
58
|
+
?? models[0]
|
|
59
|
+
return {
|
|
60
|
+
contextWindow: finiteOrNull(preferred?.model_context_length),
|
|
61
|
+
concurrency: finiteOrNull(settings?.engineMax),
|
|
62
|
+
modelAlias: typeof preferred?.id === "string" ? preferred.id : null
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Activity from /admin/api/activity. */
|
|
67
|
+
export const activityOf = (active) => ({
|
|
68
|
+
processing: finiteOrNull(active?.total_active_requests),
|
|
69
|
+
waiting: finiteOrNull(active?.total_waiting_requests),
|
|
70
|
+
contextWindow: null
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
/** Memory and pressure from the same activity payload. */
|
|
74
|
+
export const memoryOf = (active) => {
|
|
75
|
+
const used = finiteOrNull(active?.model_memory_used)
|
|
76
|
+
const max = finiteOrNull(active?.model_memory_max)
|
|
77
|
+
const pressure = typeof active?.memory_pressure?.pressure_level === "string" ? active.memory_pressure.pressure_level : null
|
|
78
|
+
if (used === null && max === null && pressure === null) {
|
|
79
|
+
return { usedBytes: null, maxBytes: null, pressure: null, unavailable: "oMLX reported no memory fields" }
|
|
80
|
+
}
|
|
81
|
+
return { usedBytes: used, maxBytes: max, pressure, unavailable: null }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Speed from an oMLX completion. oMLX reports the engine's own decode rate in
|
|
86
|
+
* usage; there is no wall-clock guess here (DEC-37-10).
|
|
87
|
+
*/
|
|
88
|
+
export const speedOf = (body, usage) => {
|
|
89
|
+
const u = usage !== null && typeof usage === "object" ? usage : body?.usage ?? {}
|
|
90
|
+
return {
|
|
91
|
+
generationTps: finiteOrNull(u.generation_tokens_per_second),
|
|
92
|
+
promptTps: finiteOrNull(u.prompt_tokens_per_second),
|
|
93
|
+
completionTokens: finiteOrNull(u.completion_tokens),
|
|
94
|
+
promptTokens: finiteOrNull(u.prompt_tokens)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The observation the ledger joins (same fields as the mlx-serve source). */
|
|
99
|
+
export const observationOf = (body, usage) => {
|
|
100
|
+
const u = usage !== null && typeof usage === "object" ? usage : body?.usage ?? {}
|
|
101
|
+
const secondsToMs = (value) => {
|
|
102
|
+
const number = Number(value)
|
|
103
|
+
return Number.isFinite(number) ? Math.round(number * 1000) : null
|
|
104
|
+
}
|
|
105
|
+
const speed = speedOf(body, u)
|
|
106
|
+
return {
|
|
107
|
+
engineRequestId: typeof body?.id === "string" && body.id.length > 0 ? body.id : null,
|
|
108
|
+
promptTokens: speed.promptTokens,
|
|
109
|
+
completionTokens: speed.completionTokens,
|
|
110
|
+
firstTokenMs: secondsToMs(u.time_to_first_token),
|
|
111
|
+
promptEvalMs: secondsToMs(u.prompt_eval_duration),
|
|
112
|
+
generationMs: secondsToMs(u.generation_duration),
|
|
113
|
+
generationTps: speed.generationTps,
|
|
114
|
+
promptTps: speed.promptTps
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Build the oMLX source against one connection. */
|
|
119
|
+
export const createOmlxSource = ({ getConnection, fetchImpl, now = Date.now } = {}) => {
|
|
120
|
+
const connectionOf = () => {
|
|
121
|
+
const connection = typeof getConnection === "function" ? getConnection() : {}
|
|
122
|
+
return connection !== null && typeof connection === "object" ? connection : {}
|
|
123
|
+
}
|
|
124
|
+
const doFetch = typeof fetchImpl === "function" ? fetchImpl : (...args) => globalThis.fetch(...args)
|
|
125
|
+
const request = async (url) => {
|
|
126
|
+
const connection = connectionOf()
|
|
127
|
+
const headers = { accept: "application/json" }
|
|
128
|
+
const key = typeof connection.apiKey === "string" ? connection.apiKey : ""
|
|
129
|
+
if (key.length > 0 && !/^•+$/u.test(key)) headers.authorization = "Bearer " + key
|
|
130
|
+
const response = await doFetch(url, { headers })
|
|
131
|
+
let body = null
|
|
132
|
+
try {
|
|
133
|
+
body = await response.json()
|
|
134
|
+
} catch {
|
|
135
|
+
body = null
|
|
136
|
+
}
|
|
137
|
+
return { status: response.status, body }
|
|
138
|
+
}
|
|
139
|
+
const base = () => trimBase(engineBaseUrl(connectionOf().endpoint))
|
|
140
|
+
const admin = () => engineAdminBaseUrl(connectionOf().endpoint)
|
|
141
|
+
return {
|
|
142
|
+
kind: OMLX_KIND,
|
|
143
|
+
label: "oMLX",
|
|
144
|
+
async catalogue() {
|
|
145
|
+
const models = await request(base() + "/v1/models")
|
|
146
|
+
if (models.status < 200 || models.status >= 300) throw new Error("oMLX catalogue HTTP " + models.status)
|
|
147
|
+
const adminModels = await request(admin() + "/models")
|
|
148
|
+
return catalogueOf(models.body, adminModels.body)
|
|
149
|
+
},
|
|
150
|
+
async contract() {
|
|
151
|
+
const [settings, models] = await Promise.all([request(admin() + "/global-settings"), request(admin() + "/models")])
|
|
152
|
+
if (settings.status < 200 || settings.status >= 300) {
|
|
153
|
+
return { contextWindow: finiteOrNull(contractOf(null, models.body).contextWindow), concurrency: null, modelAlias: contractOf(null, models.body).modelAlias }
|
|
154
|
+
}
|
|
155
|
+
return contractOf(settings.body, models.body)
|
|
156
|
+
},
|
|
157
|
+
async activity() {
|
|
158
|
+
const { status, body } = await request(admin() + "/activity")
|
|
159
|
+
if (status < 200 || status >= 300) return { processing: null, waiting: null, contextWindow: null }
|
|
160
|
+
return activityOf(body)
|
|
161
|
+
},
|
|
162
|
+
async memory() {
|
|
163
|
+
const { status, body } = await request(admin() + "/activity")
|
|
164
|
+
if (status < 200 || status >= 300) {
|
|
165
|
+
return { usedBytes: null, maxBytes: null, pressure: null, unavailable: "oMLX activity endpoint answered HTTP " + status }
|
|
166
|
+
}
|
|
167
|
+
return memoryOf(body)
|
|
168
|
+
},
|
|
169
|
+
speedOf,
|
|
170
|
+
observationOf,
|
|
171
|
+
async health() {
|
|
172
|
+
const started = now()
|
|
173
|
+
try {
|
|
174
|
+
const { status } = await request(base() + "/v1/models")
|
|
175
|
+
return {
|
|
176
|
+
status: status >= 200 && status < 300 ? "healthy" : "unreachable",
|
|
177
|
+
httpStatus: status,
|
|
178
|
+
latencyMs: Math.max(0, now() - started)
|
|
179
|
+
}
|
|
180
|
+
} catch {
|
|
181
|
+
return { status: "unreachable", httpStatus: null, latencyMs: null }
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run 39 (DEC-39-02): one connected engine at a time.
|
|
3
|
+
*
|
|
4
|
+
* The connection's kind selects exactly one Engine source. There is no
|
|
5
|
+
* fallback: an unknown kind is a settings error the pages surface, never a
|
|
6
|
+
* silent switch to the other engine.
|
|
7
|
+
*/
|
|
8
|
+
import { ENGINE_KINDS } from "./contract.js"
|
|
9
|
+
import { createMlxServeSource } from "./mlx-serve.js"
|
|
10
|
+
import { createOmlxSource } from "./omlx.js"
|
|
11
|
+
|
|
12
|
+
/** Normalise a configured kind: the settings value decides, never a guess. */
|
|
13
|
+
export const engineKindOf = (connection) => {
|
|
14
|
+
const kind = connection !== null && typeof connection === "object" ? connection.kind : undefined
|
|
15
|
+
if (typeof kind !== "string") return null
|
|
16
|
+
const normalised = kind.trim().toLowerCase()
|
|
17
|
+
if (normalised === "mlx-serve" || normalised === "mlx_serve" || normalised === "mlxserve") return "mlx-serve"
|
|
18
|
+
if (normalised === "omlx") return "omlx"
|
|
19
|
+
return null
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The single active source for a connection.
|
|
24
|
+
* @returns {{kind: string|null, source: object|null, error: string|null}}
|
|
25
|
+
*/
|
|
26
|
+
export const selectEngineSource = (connection, options = {}) => {
|
|
27
|
+
const kind = engineKindOf(connection)
|
|
28
|
+
if (kind === null) {
|
|
29
|
+
return {
|
|
30
|
+
kind: null,
|
|
31
|
+
source: null,
|
|
32
|
+
error: "unknown engine kind — expected one of " + ENGINE_KINDS.join(", ")
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (kind === "mlx-serve") {
|
|
36
|
+
return { kind, source: createMlxServeSource(options), error: null }
|
|
37
|
+
}
|
|
38
|
+
// R-39-05: oMLX is a source behind the same contract now, not a special case.
|
|
39
|
+
return { kind, source: options.omlxSource ?? createOmlxSource(options), error: null }
|
|
40
|
+
}
|