@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,657 @@
1
+ /**
2
+ * Engine provider adapter: DSH talks to the connected engine directly.
3
+ *
4
+ * The engine is the source of truth for its model list, so listModels reads the
5
+ * engine each call and prepareCall proxies chat completions. This is what lets a
6
+ * connection alone make every served model routable, with no provider or model
7
+ * configuration in DSH.
8
+ *
9
+ * @module @dsh-local-router/plugin/engine-adapter
10
+ */
11
+
12
+ export const ENGINE_PROVIDER = "engine"
13
+ export const ENGINE_PROVIDER_NAME = "Engine"
14
+
15
+ // DEC-37-11 (Owner, option C): the router owns this adapter, and DSH reads a
16
+ // model's context window ONLY from adapter.resolveModel(...).context.contextWindow
17
+ // (dsh-llm:2226/2231/2248 -> agent-loop:1079/1088 and compaction-basic:955-959).
18
+ // Registering role-scoped provider routes therefore gives a per-role window at
19
+ // spawn time, and the same number prices the role's compaction budget.
20
+ export const ROLE_PROVIDER_ROUTES = Object.freeze({
21
+ "engine-l1": "l1",
22
+ "engine-l2": "l2",
23
+ "engine-l3": "l3",
24
+ "engine-advisor": "advisor"
25
+ })
26
+ export const ROLE_PROVIDER_IDS = Object.freeze(Object.keys(ROLE_PROVIDER_ROUTES))
27
+ export const roleOfProviderRoute = (provider) => ROLE_PROVIDER_ROUTES[provider] ?? null
28
+
29
+ /** Join the text blocks of one DSH message. */
30
+ const textOf = (message) =>
31
+ Array.isArray(message?.content)
32
+ ? message.content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("")
33
+ : ""
34
+
35
+ /** OpenAI chat-completions base for an engine endpoint (tolerates a trailing /v1 or /admin). */
36
+ export const engineBaseUrl = (endpoint) => {
37
+ const raw = typeof endpoint === "string" && endpoint.length > 0 ? endpoint : "http://127.0.0.1:8000"
38
+ const trimmed = raw.replace(/\/+$/u, "").replace(/\/admin(\/api)?$/u, "")
39
+ return /\/v1$/u.test(trimmed) ? trimmed : trimmed + "/v1"
40
+ }
41
+ /** Engine admin base (model metadata such as context length lives here). */
42
+ export const engineAdminBaseUrl = (endpoint) => engineBaseUrl(endpoint).replace(/\/v1$/u, "") + "/admin/api"
43
+
44
+ /**
45
+ * Serialize DSH request messages into OpenAI chat-completions messages.
46
+ * @param {object} options - GenerateOptions from the harness.
47
+ * @returns {Array<object>} OpenAI messages, in order.
48
+ */
49
+ export const serializeMessages = (options) => {
50
+ const out = []
51
+ const source = Array.isArray(options?.messages) ? options.messages : []
52
+ let system = typeof options?.system === "string" && options.system.length > 0 ? options.system : ""
53
+ for (const message of source) {
54
+ if (message === null || typeof message !== "object") continue
55
+ switch (message.role) {
56
+ case "system": {
57
+ const text = textOf(message)
58
+ if (text.length > 0) system = system.length > 0 ? system + "\n\n" + text : text
59
+ break
60
+ }
61
+ case "developer": {
62
+ const text = textOf(message)
63
+ if (text.length > 0) out.push({ role: "system", content: text })
64
+ break
65
+ }
66
+ case "assistant": {
67
+ const content = textOf(message)
68
+ const toolCalls = []
69
+ for (const block of Array.isArray(message.content) ? message.content : []) {
70
+ if (block?.type !== "tool-call") continue
71
+ toolCalls.push({
72
+ id: typeof block.id === "string" ? block.id : "",
73
+ type: "function",
74
+ function: {
75
+ name: typeof block.name === "string" ? block.name : "",
76
+ arguments: typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {})
77
+ }
78
+ })
79
+ }
80
+ // An interrupted or reasoning-only turn has no text and no calls; sending
81
+ // an assistant message with neither content nor tool_calls is rejected by
82
+ // OpenAI-compatible servers, so drop it.
83
+ if (content.length === 0 && toolCalls.length === 0) break
84
+ out.push({
85
+ role: "assistant",
86
+ ...content.length > 0 ? { content } : { content: "" },
87
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
88
+ })
89
+ break
90
+ }
91
+ case "tool": {
92
+ out.push({
93
+ role: "tool",
94
+ tool_call_id: typeof message.toolCallId === "string" ? message.toolCallId : "",
95
+ content: textOf(message).length > 0 ? textOf(message) : "(no output)"
96
+ })
97
+ break
98
+ }
99
+ default: {
100
+ // Preserve multimodal parts: DSH image blocks carry mimeType + base64 data
101
+ // and OpenAI-compatible engines expect a data URL image_url part.
102
+ const parts = []
103
+ let hasImage = false
104
+ for (const block of Array.isArray(message.content) ? message.content : []) {
105
+ if (block === null || typeof block !== "object") continue
106
+ if (block.type === "text" && typeof block.text === "string" && block.text.length > 0) {
107
+ parts.push({ type: "text", text: block.text })
108
+ } else if (
109
+ block.type === "image" &&
110
+ typeof block.mimeType === "string" &&
111
+ block.mimeType.length > 0 &&
112
+ typeof block.data === "string" &&
113
+ block.data.length > 0
114
+ ) {
115
+ hasImage = true
116
+ parts.push({
117
+ type: "image_url",
118
+ image_url: { url: "data:" + block.mimeType + ";base64," + block.data }
119
+ })
120
+ }
121
+ }
122
+ if (!hasImage) {
123
+ const content = textOf(message)
124
+ if (content.length > 0) out.push({ role: "user", content })
125
+ } else {
126
+ out.push({ role: "user", content: parts })
127
+ }
128
+ }
129
+ }
130
+ }
131
+ if (system.length > 0) out.unshift({ role: "system", content: system })
132
+ return out
133
+ }
134
+
135
+ /** OpenAI tool declarations from DSH ToolSchema[]. */
136
+ export const serializeTools = (tools) =>
137
+ Array.isArray(tools)
138
+ ? tools.filter((tool) => typeof tool?.name === "string" && tool.name.length > 0).map((tool) => ({
139
+ type: "function",
140
+ function: {
141
+ name: tool.name,
142
+ description: typeof tool.description === "string" ? tool.description : "",
143
+ parameters: tool.parameters !== null && typeof tool.parameters === "object" ? tool.parameters : { type: "object", properties: {} }
144
+ }
145
+ }))
146
+ : []
147
+
148
+ /** Map an engine finish_reason to the harness finish reason. */
149
+ const finishReason = (reason, hasContent) => {
150
+ if (reason === "length") return { kind: "max-tokens" }
151
+ if (reason === "tool_calls" || reason === "tool_use") return { kind: "tool-calls" }
152
+ if (!hasContent) {
153
+ return { kind: "error", failure: { message: "engine returned a completed response with no content", code: "EMPTY_RESPONSE" } }
154
+ }
155
+ return { kind: "stop" }
156
+ }
157
+
158
+ /** Disjoint harness token counts (cached input is not uncached input). */
159
+ const usageOf = (usage) => {
160
+ const prompt = Number.isFinite(usage?.prompt_tokens) ? usage.prompt_tokens : 0
161
+ const cached = Number.isFinite(usage?.prompt_tokens_details?.cached_tokens) ? usage.prompt_tokens_details.cached_tokens : 0
162
+ const completion = Number.isFinite(usage?.completion_tokens) ? usage.completion_tokens : 0
163
+ const reasoning = Number.isFinite(usage?.completion_tokens_details?.reasoning_tokens) ? usage.completion_tokens_details.reasoning_tokens : 0
164
+ const total = Number.isFinite(usage?.total_tokens) ? usage.total_tokens : prompt + completion
165
+ return {
166
+ inputTokens: Math.max(0, prompt - cached),
167
+ outputTokens: completion,
168
+ totalTokens: total,
169
+ ...cached > 0 ? { cacheReadTokens: cached } : {},
170
+ ...reasoning > 0 ? { reasoningTokens: reasoning } : {}
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Build the per-request observation the adapter reports after a completion.
176
+ * Every field is null unless the engine actually reports it - the adapter never
177
+ * invents a token count or a timing. oMLX reports durations in seconds (a live
178
+ * 64-token request read generation_duration 0.34 s), so the observation carries
179
+ * milliseconds; the per-second rates pass through unchanged.
180
+ * @param {object} body - the assembled chat-completion body (carries the id).
181
+ * @param {object} [usage] - the engine's usage block.
182
+ * @returns {{ engineRequestId: string|null, promptTokens: number|null, completionTokens: number|null, firstTokenMs: number|null, promptEvalMs: number|null, generationMs: number|null, generationTps: number|null, promptTps: number|null }}
183
+ */
184
+ export const observationOf = (body, usage) => {
185
+ const u = usage !== null && typeof usage === "object" ? usage : body?.usage ?? {}
186
+ const finite = (value) => {
187
+ const number = Number(value)
188
+ return Number.isFinite(number) ? number : null
189
+ }
190
+ const secondsToMs = (value) => {
191
+ const number = Number(value)
192
+ return Number.isFinite(number) ? Math.round(number * 1000) : null
193
+ }
194
+ const id = typeof body?.id === "string" && body.id.length > 0 ? body.id : null
195
+ return {
196
+ engineRequestId: id,
197
+ promptTokens: finite(u.prompt_tokens),
198
+ completionTokens: finite(u.completion_tokens),
199
+ firstTokenMs: secondsToMs(u.time_to_first_token),
200
+ promptEvalMs: secondsToMs(u.prompt_eval_duration),
201
+ generationMs: secondsToMs(u.generation_duration),
202
+ generationTps: finite(u.generation_tokens_per_second),
203
+ promptTps: finite(u.prompt_tokens_per_second)
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Convert one non-streaming chat-completion body into the harness chunk protocol.
209
+ * @param {object} body - engine response JSON.
210
+ * @returns {Array<object>} StreamChunk sequence ending with finish.
211
+ */
212
+ export const toChunks = (body) => {
213
+ const choice = Array.isArray(body?.choices) ? body.choices[0] : undefined
214
+ const message = choice?.message ?? {}
215
+ const chunks = []
216
+ let index = 0
217
+ const reasoning = typeof message.reasoning_content === "string" ? message.reasoning_content : ""
218
+ if (reasoning.length > 0) {
219
+ chunks.push({ type: "block-start", index, blockType: "reasoning" })
220
+ chunks.push({ type: "reasoning-delta", index, text: reasoning })
221
+ chunks.push({ type: "block-end", index, block: { type: "reasoning", text: reasoning } })
222
+ index += 1
223
+ }
224
+ const content = typeof message.content === "string" ? message.content : ""
225
+ let emitted = reasoning.length > 0 ? 1 : 0
226
+ if (content.length > 0) {
227
+ chunks.push({ type: "block-start", index, blockType: "text" })
228
+ chunks.push({ type: "text-delta", index, text: content })
229
+ chunks.push({ type: "block-end", index, block: { type: "text", text: content } })
230
+ index += 1
231
+ emitted += 1
232
+ }
233
+ const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : []
234
+ for (const call of toolCalls) {
235
+ const id = typeof call?.id === "string" ? call.id : ""
236
+ const name = typeof call?.function?.name === "string" ? call.function.name : ""
237
+ const args = typeof call?.function?.arguments === "string" ? call.function.arguments : JSON.stringify(call?.function?.arguments ?? {})
238
+ if (id.length === 0 || name.length === 0) continue
239
+ chunks.push({ type: "block-start", index, blockType: "tool-call" })
240
+ chunks.push({ type: "tool-call-delta", index, id, name, argumentsDelta: args })
241
+ chunks.push({ type: "block-end", index, block: { type: "tool-call", id, name, arguments: args } })
242
+ index += 1
243
+ emitted += 1
244
+ }
245
+ chunks.push({ type: "usage", usage: usageOf(body?.usage) })
246
+ chunks.push({ type: "finish", reason: finishReason(choice?.finish_reason, emitted > 0) })
247
+ return chunks
248
+ }
249
+
250
+ /** Throw a typed engine failure so DSH classifies and retries it. */
251
+ const engineError = (message, code) => {
252
+ const error = new Error(message)
253
+ error.code = code
254
+ error.failure = { message, code }
255
+ return error
256
+ }
257
+
258
+ /**
259
+ * Build the duck-typed LlmAdapter the host registers for the engine provider.
260
+ * @param {object} options - getConnection() and optional fetch/now injection.
261
+ * @returns {object} adapter
262
+ */
263
+
264
+ /**
265
+ * DEC-37-10: read an SSE chat-completions stream and assemble the full completion.
266
+ * Returns the assembled body plus the DECODE window (first delta -> last delta) and
267
+ * the engine's usage, so a request can be measured without the prefill/queue time
268
+ * that made the wall-clock number meaningless (live: 5 s wall for a cold model).
269
+ */
270
+ export const readSseCompletion = async (response, now) => {
271
+ const body = { choices: [{ index: 0, message: { role: "assistant" }, finish_reason: null }] }
272
+ let decodeStart = null
273
+ let decodeEnd = null
274
+ let content = ""
275
+ let reasoning = ""
276
+ let usage = null
277
+ let deltas = 0
278
+ const toolCalls = []
279
+ const decoder = new TextDecoder()
280
+ let buffer = ""
281
+ const note = () => {
282
+ const at = now()
283
+ if (decodeStart === null) decodeStart = at
284
+ decodeEnd = at
285
+ }
286
+ const handle = (data) => {
287
+ if (data.length === 0 || data === "[DONE]") return
288
+ let event
289
+ try {
290
+ event = JSON.parse(data)
291
+ } catch {
292
+ return
293
+ }
294
+ if (event?.usage) usage = event.usage
295
+ if (typeof event?.model === "string") body.model = event.model
296
+ if (typeof event?.id === "string") body.id = event.id
297
+ const choice = Array.isArray(event?.choices) ? event.choices[0] : undefined
298
+ if (choice === undefined || choice === null) return
299
+ if (choice.finish_reason) body.choices[0].finish_reason = choice.finish_reason
300
+ const delta = choice.delta ?? {}
301
+ const hasText = typeof delta.content === "string" && delta.content.length > 0
302
+ const hasReasoning = typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0
303
+ const hasTools = Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0
304
+ if (!hasText && !hasReasoning && !hasTools) return
305
+ note()
306
+ deltas += 1
307
+ if (hasReasoning) reasoning += delta.reasoning_content
308
+ if (hasText) content += delta.content
309
+ if (hasTools) {
310
+ for (const call of delta.tool_calls) {
311
+ const index = Number.isInteger(call?.index) ? call.index : toolCalls.length
312
+ const slot = toolCalls[index] ?? (toolCalls[index] = { id: "", type: "function", function: { name: "", arguments: "" } })
313
+ if (typeof call?.id === "string" && call.id.length > 0) slot.id = call.id
314
+ if (typeof call?.function?.name === "string" && call.function.name.length > 0) slot.function.name += call.function.name
315
+ if (typeof call?.function?.arguments === "string" && call.function.arguments.length > 0) slot.function.arguments += call.function.arguments
316
+ }
317
+ }
318
+ }
319
+ const reader = response.body.getReader()
320
+ for (;;) {
321
+ const { done, value } = await reader.read()
322
+ if (done === true) break
323
+ buffer += decoder.decode(value, { stream: true })
324
+ let newline = buffer.indexOf("\n")
325
+ while (newline >= 0) {
326
+ const line = buffer.slice(0, newline).trimEnd()
327
+ buffer = buffer.slice(newline + 1)
328
+ if (line.startsWith("data:")) handle(line.slice(5).trim())
329
+ newline = buffer.indexOf("\n")
330
+ }
331
+ }
332
+ if (buffer.startsWith("data:")) handle(buffer.slice(5).trim())
333
+ const message = body.choices[0].message
334
+ if (reasoning.length > 0) message.reasoning_content = reasoning
335
+ if (content.length > 0) message.content = content
336
+ const calls = toolCalls.filter((call) => call !== undefined && call !== null)
337
+ if (calls.length > 0) message.tool_calls = calls
338
+ const tokens = Number.isFinite(Number(usage?.completion_tokens)) && Number(usage.completion_tokens) > 0
339
+ ? Number(usage.completion_tokens)
340
+ : deltas
341
+ return { body, decodeStart, decodeEnd, usage, tokens }
342
+ }
343
+
344
+ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now, modelCapabilities = {}, onRequestSpeed = null, onRequestObserved = null, roleWindowFor = null } = {}) => {
345
+ // The role's configured context window for a role-scoped provider route, or null
346
+ // when the route is not role-scoped / the role has no finite window (the Advisor's
347
+ // "no cap", DEC-37-05).
348
+ const roleWindowOf = (provider) => {
349
+ const role = roleOfProviderRoute(provider)
350
+ if (role === null || typeof roleWindowFor !== "function") return null
351
+ try {
352
+ const window = roleWindowFor(role)
353
+ return Number.isFinite(window) && window > 0 ? Math.trunc(window) : null
354
+ } catch {
355
+ return null
356
+ }
357
+ }
358
+ // DEC-37-10 (Owner): the engine's /admin/api/stats only exposes LIFETIME
359
+ // aggregates (722,359 completion tokens over 63,347 s -> 18.2 tps), which must
360
+ // never drive routing. Every request this adapter proxies is therefore measured
361
+ // as a fresh observation: completion tokens over the wall time of the call.
362
+ // Non-streaming on the wire (stream:false below), so the decode window cannot be
363
+ // isolated exactly; this is a real per-request observation, not an average.
364
+ const reportTps = (model, tps) => {
365
+ if (typeof onRequestSpeed !== "function") return
366
+ if (!Number.isFinite(tps) || tps <= 0) return
367
+ try {
368
+ onRequestSpeed(model, tps)
369
+ } catch {}
370
+ }
371
+ const reportSpeed = (model, decodeStart, decodeEnd, tokens) => {
372
+ if (typeof onRequestSpeed !== "function") return
373
+ if (!Number.isFinite(tokens) || tokens <= 0) return
374
+ const elapsedMs = decodeEnd - decodeStart
375
+ if (!Number.isFinite(elapsedMs) || elapsedMs <= 0) return
376
+ try {
377
+ onRequestSpeed(model, tokens / (elapsedMs / 1000))
378
+ } catch {}
379
+ }
380
+ // DEC-37-12: every proxied request also forwards its engine id and token/timing
381
+ // usage as one observation, so the ledger can join the local per-request facts
382
+ // (context tokens, oMLX request id) that the Activity page otherwise cannot see.
383
+ const reportObserved = (model, observation) => {
384
+ if (typeof onRequestObserved !== "function") return
385
+ try {
386
+ onRequestObserved(model, observation)
387
+ } catch {}
388
+ }
389
+ const doFetch = typeof fetchImpl === "function" ? fetchImpl : (...args) => globalThis.fetch(...args)
390
+ let cache = { at: Number.NEGATIVE_INFINITY, base: "", models: [] }
391
+ // Last capability reconciliation: which sources answered, what was excluded.
392
+ let capabilityReport = { fetchedAt: null, sources: { models: false, admin: false }, advertised: 0, excluded: [] }
393
+ // Keys the capability mapping depends on. A disappearing key means the
394
+ // engine payload changed shape; keep the last-good catalog instead of
395
+ // silently degrading to text-only / no-context models.
396
+ const requiredKeys = { models: ["model_type", "max_model_len"], admin: ["model_context_length"] }
397
+ let lastGoodKeys = { models: new Set(), admin: new Set() }
398
+ let lastGoodModels = []
399
+ const connectionOf = () => (typeof getConnection === "function" ? getConnection() : { endpoint: "", apiKey: "" })
400
+
401
+ const authorized = () => {
402
+ const connection = connectionOf() ?? {}
403
+ const key = typeof connection.apiKey === "string" && connection.apiKey.length > 0 ? connection.apiKey : ""
404
+ return {
405
+ base: engineBaseUrl(connection.endpoint),
406
+ headers: {
407
+ "content-type": "application/json",
408
+ accept: "application/json",
409
+ ...key.length > 0 ? { authorization: "Bearer " + key } : {}
410
+ }
411
+ }
412
+ }
413
+
414
+ // Context length comes from the engine's own admin metadata; when the engine
415
+ // does not report one it stays omitted rather than invented.
416
+ const modelInfo = (provider, entry) => {
417
+ const engineWindow = Number.isFinite(entry.contextWindow)
418
+ ? entry.contextWindow
419
+ : Number.isFinite(entry.context?.contextWindow)
420
+ ? entry.context.contextWindow
421
+ : null
422
+ // DEC-37-11: a role route wins over the engine's advertised window.
423
+ const contextWindow = roleWindowOf(provider) ?? engineWindow
424
+ const modalities = Array.isArray(entry.inputModalities) ? entry.inputModalities : ["text"]
425
+ return {
426
+ id: entry.id,
427
+ name: entry.name,
428
+ provider,
429
+ ...contextWindow === null ? {} : { context: { contextWindow } },
430
+ inputModalities: modalities
431
+ }
432
+ }
433
+
434
+ return {
435
+ providerInfo: (provider) => ({ id: provider, name: ENGINE_PROVIDER_NAME }),
436
+ providerRetryPolicy: () => undefined,
437
+ imageRequestPricing: () => undefined,
438
+ imageRequestTarget: (_provider, _model, image) => ({
439
+ width: Number.isFinite(image?.width) ? image.width : 0,
440
+ height: Number.isFinite(image?.height) ? image.height : 0,
441
+ maxBytes: Number.isFinite(image?.bytes) ? image.bytes : Number.isFinite(image?.maxBytes) ? image.maxBytes : 0
442
+ }),
443
+ async listModels(provider) {
444
+ const currentBase = engineBaseUrl(connectionOf()?.endpoint)
445
+ if (cache.base === currentBase && now() - cache.at < 5000) return cache.models
446
+ const { base, headers } = authorized()
447
+ const adminUrl = engineAdminBaseUrl(connectionOf()?.endpoint) + "/models"
448
+ // Read both engine surfaces: /v1/models carries model_type + max_model_len,
449
+ // /admin/api/models carries model_context_length and runtime flags.
450
+ const [modelsResult, adminResult] = await Promise.allSettled([
451
+ doFetch(base + "/models", { method: "GET", headers }),
452
+ doFetch(adminUrl, { method: "GET", headers })
453
+ ])
454
+ let body
455
+ if (modelsResult.status === "fulfilled" && modelsResult.value.ok) {
456
+ try {
457
+ body = await modelsResult.value.json()
458
+ } catch {
459
+ body = undefined
460
+ }
461
+ }
462
+ if (body === undefined) return cache.base === currentBase ? cache.models : []
463
+ const adminContexts = new Map()
464
+ let adminOk = false
465
+ if (adminResult.status === "fulfilled" && adminResult.value.ok) {
466
+ try {
467
+ const adminBody = await adminResult.value.json()
468
+ adminOk = true
469
+ for (const entry of Array.isArray(adminBody?.models) ? adminBody.models : []) {
470
+ if (
471
+ entry !== null &&
472
+ typeof entry === "object" &&
473
+ typeof entry.id === "string" &&
474
+ Number.isFinite(entry.model_context_length)
475
+ ) {
476
+ adminContexts.set(entry.id, entry.model_context_length)
477
+ }
478
+ }
479
+ } catch {}
480
+ }
481
+ const modelRows = Array.isArray(body?.data) ? body.data : []
482
+ const currentKeys = { models: new Set(), admin: new Set() }
483
+ for (const row of modelRows) {
484
+ if (row === null || typeof row !== "object") continue
485
+ for (const key of requiredKeys.models) if (row[key] !== undefined) currentKeys.models.add(key)
486
+ }
487
+ for (const key of requiredKeys.admin) {
488
+ if (Array.from(adminContexts.keys()).length > 0) currentKeys.admin.add(key)
489
+ }
490
+ const missingKeys = []
491
+ for (const surface of ["models", "admin"]) {
492
+ for (const key of requiredKeys[surface]) {
493
+ if (lastGoodKeys[surface].has(key) && !currentKeys[surface].has(key)) missingKeys.push(key)
494
+ }
495
+ }
496
+ if (missingKeys.length > 0) {
497
+ capabilityReport = {
498
+ fetchedAt: now(),
499
+ sources: { models: true, admin: adminOk },
500
+ advertised: lastGoodModels.length,
501
+ excluded: capabilityReport.excluded,
502
+ stale: true,
503
+ drift: { missingKeys, at: now() }
504
+ }
505
+ cache = { at: now(), base: currentBase, models: lastGoodModels }
506
+ return lastGoodModels
507
+ }
508
+ lastGoodKeys = currentKeys
509
+ const seen = new Set()
510
+ const entries = []
511
+ const excluded = []
512
+ for (const model of modelRows) {
513
+ const id = typeof model?.id === "string" ? model.id : ""
514
+ if (id.length === 0 || seen.has(id)) continue
515
+ seen.add(id)
516
+ const modelType = typeof model.model_type === "string" ? model.model_type.toLowerCase() : ""
517
+ const vision = ["vlm", "vision", "multimodal", "image"].some((kind) => modelType.includes(kind))
518
+ const override = modelCapabilities !== null && typeof modelCapabilities === "object" ? modelCapabilities[id] : undefined
519
+ const contextWindow = Number.isFinite(override?.contextWindow)
520
+ ? override.contextWindow
521
+ : Number.isFinite(adminContexts.get(id))
522
+ ? adminContexts.get(id)
523
+ : Number.isFinite(model.max_model_len)
524
+ ? model.max_model_len
525
+ : undefined
526
+ const modalities = Array.isArray(override?.inputModalities)
527
+ ? override.inputModalities
528
+ : vision
529
+ ? ["text", "image"]
530
+ : undefined
531
+ entries.push({
532
+ id,
533
+ name: typeof model.name === "string" && model.name.length > 0 ? model.name : id,
534
+ provider,
535
+ ...modalities === undefined ? {} : { inputModalities: modalities },
536
+ ...Number.isFinite(contextWindow) ? { context: { contextWindow } } : {},
537
+ contextKnown: Number.isFinite(contextWindow)
538
+ })
539
+ }
540
+ // DSH cannot switch a session to a model without a contextWindow
541
+ // (MODEL_SWITCH_COMPACTION_FAILED). When the engine reports context for at
542
+ // least one model, treat that as the contract and only advertise models
543
+ // that satisfy it; models with no known context are reported, not guessed.
544
+ const someKnown = entries.some((entry) => entry.contextKnown)
545
+ const models = []
546
+ for (const entry of entries) {
547
+ if (someKnown && !entry.contextKnown) {
548
+ excluded.push({ id: entry.id, reason: "no contextWindow from engine metadata" })
549
+ continue
550
+ }
551
+ const { contextKnown, ...model } = entry
552
+ models.push(model)
553
+ }
554
+ capabilityReport = {
555
+ fetchedAt: now(),
556
+ sources: { models: true, admin: adminOk },
557
+ advertised: models.length,
558
+ excluded,
559
+ stale: false,
560
+ drift: null
561
+ }
562
+ lastGoodModels = models
563
+ cache = { at: now(), base: currentBase, models }
564
+ return models
565
+ },
566
+ capabilitiesReport: () => ({ ...capabilityReport, sources: { ...capabilityReport.sources }, excluded: capabilityReport.excluded.slice() }),
567
+ /** A model load/unload changes what the engine serves; drop the cache. */
568
+ invalidateCapabilities: () => {
569
+ cache = { at: Number.NEGATIVE_INFINITY, base: "", models: [] }
570
+ },
571
+ async resolveModel(provider, model, signal) {
572
+ if (signal?.aborted === true) throw engineError("engine resolve aborted", "ABORTED")
573
+ const models = await this.listModels(provider)
574
+ const found = models.find((entry) => entry.id === model)
575
+ if (found === undefined) {
576
+ throw engineError('engine does not serve model "' + String(model) + '"', "INVALID_REQUEST")
577
+ }
578
+ return modelInfo(provider, found)
579
+ },
580
+ prepareCall(provider, model) {
581
+ const cached = cache.models.find((entry) => entry.id === model)
582
+ return {
583
+ model: modelInfo(provider, cached ?? { id: model, name: model }),
584
+ stream: (options) => (async function* () {
585
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
586
+ const { base, headers } = authorized()
587
+ const payload = {
588
+ model,
589
+ messages: serializeMessages(options),
590
+ stream: true,
591
+ stream_options: { include_usage: true },
592
+ ...Array.isArray(options?.tools) && options.tools.length > 0 ? { tools: serializeTools(options.tools) } : {},
593
+ ...Number.isFinite(options?.temperature) ? { temperature: options.temperature } : {},
594
+ ...Number.isFinite(options?.maxTokens) ? { max_tokens: options.maxTokens } : {},
595
+ ...Array.isArray(options?.stop) && options.stop.length > 0 ? { stop: options.stop } : {}
596
+ }
597
+ let response
598
+ try {
599
+ response = await doFetch(base + "/chat/completions", { method: "POST", headers, body: JSON.stringify(payload), signal: options?.signal })
600
+ } catch (error) {
601
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
602
+ throw engineError("engine transport failed: " + (error?.message ?? String(error)), "TRANSPORT")
603
+ }
604
+ if (!response.ok) {
605
+ let detail = ""
606
+ try {
607
+ detail = String(await response.text()).slice(0, 240)
608
+ } catch {}
609
+ const code = response.status === 401 || response.status === 403 ? "AUTH" : response.status === 429 ? "RATE_LIMIT" : response.status >= 500 ? "SERVER" : "INVALID_REQUEST"
610
+ throw engineError("engine chat request failed (" + response.status + "): " + detail, code)
611
+ }
612
+ // DEC-37-10 (Owner): the engine exposes only LIFETIME aggregates, so every
613
+ // proxied request is measured itself: decode window (first delta -> last
614
+ // delta) over the engine's completion tokens. Streaming is what makes the
615
+ // window observable; a non-streaming body falls back to no measurement
616
+ // rather than recording the wall time (which includes model load/prefill).
617
+ if (typeof response.body?.getReader === "function") {
618
+ let assembled
619
+ try {
620
+ assembled = await readSseCompletion(response, now)
621
+ } catch (error) {
622
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
623
+ throw engineError("engine stream read failed: " + (error?.message ?? String(error)), "TRANSPORT")
624
+ }
625
+ // oMLX reports the per-request generation speed in the usage block
626
+ // (generation_tokens_per_second) - a true fresh observation from a past
627
+ // request. Prefer it; fall back to our own decode-window measurement.
628
+ const reported = Number(assembled.usage?.generation_tokens_per_second)
629
+ if (Number.isFinite(reported) && reported > 0) {
630
+ reportTps(model, reported)
631
+ } else if (assembled.decodeStart !== null && assembled.decodeEnd !== null) {
632
+ reportSpeed(model, assembled.decodeStart, assembled.decodeEnd, assembled.tokens)
633
+ }
634
+ reportObserved(model, observationOf(assembled.body, assembled.usage))
635
+ for (const chunk of toChunks(assembled.body)) yield chunk
636
+ return
637
+ }
638
+ let text
639
+ try {
640
+ text = await response.text()
641
+ } catch (error) {
642
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
643
+ throw engineError("engine body read failed: " + (error?.message ?? String(error)), "TRANSPORT")
644
+ }
645
+ let body
646
+ try {
647
+ body = JSON.parse(text)
648
+ } catch {
649
+ throw engineError("engine returned a non-JSON chat response", "SERVER")
650
+ }
651
+ reportObserved(model, observationOf(body, body?.usage))
652
+ for (const chunk of toChunks(body)) yield chunk
653
+ })()
654
+ }
655
+ }
656
+ }
657
+ }