@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,147 @@
1
+ - insert:
2
+ - id: router
3
+ name: "@try-works/dsh-minimal-router"
4
+ config:
5
+ localSelectionProvider: engine
6
+ policy:
7
+ floorTps: 30
8
+ # Run 24 (DEC-24-03/04): tool-result pruning, OFF until the cap is approved.
9
+ prune:
10
+ mode: off
11
+ maxChars: 20000
12
+ headChars: 10000
13
+ tailChars: 4000
14
+
15
+ # Run 37 · R-37-01 — lean role presets ship WITH the plugin: installing the
16
+ # @dsh-local-router/plugin bundle registers them, no profile hand-edit needed.
17
+ # The advisor reuses the built-in 'ptc' preset (full capability, no cap).
18
+ - insert:
19
+ - id: preset-lean-worker
20
+ name: '@deepseek-ai/dsh-agent-preset'
21
+ config:
22
+ id: lean-worker
23
+ name: Lean worker (PTC)
24
+ description: Lean PTC worker for L2 subagents - run_code plus the 9 core tools with lean instructions.
25
+ order: 10
26
+ plugins:
27
+ - id: persona
28
+ name: '@deepseek-ai/dsh-persona'
29
+ config:
30
+ prefix: You are a coding agent powered by the {{model}} model.
31
+ - id: agent-instructions
32
+ name: '@deepseek-ai/dsh-agent-instructions'
33
+ config:
34
+ maxBytes: 16384
35
+ - id: time-context
36
+ name: '@deepseek-ai/dsh-time-context'
37
+ - id: tool-bash
38
+ name: '@deepseek-ai/dsh-tool-bash'
39
+ disabled: !!js process.platform === 'win32'
40
+ - id: tool-pwsh
41
+ name: '@deepseek-ai/dsh-tool-pwsh'
42
+ disabled: !!js process.platform !== 'win32'
43
+ - id: tool-fs
44
+ name: '@deepseek-ai/dsh-tool-fs'
45
+ config:
46
+ applyPatch: false
47
+ - id: tool-fs-search
48
+ name: '@deepseek-ai/dsh-tool-fs-search'
49
+ config:
50
+ sampleOverCapGlobResults: false
51
+ - id: tool-working-directory
52
+ name: '@deepseek-ai/dsh-tool-working-directory'
53
+ - id: tool-todo
54
+ name: '@deepseek-ai/dsh-tool-todo'
55
+ config:
56
+ allowParallelInProgress: true
57
+ # tool-subagent registers delegation services, so it lives in an isolate
58
+ # group like the built-in ptc preset's 'delegation' row; a bare Service
59
+ # row leaks to the root realm and fails the mount.
60
+ - id: delegation
61
+ name: cordis:group
62
+ group: true
63
+ isolate:
64
+ workflowEngine: true
65
+ config:
66
+ - id: tool-subagent
67
+ name: '@deepseek-ai/dsh-tool-subagent'
68
+ config:
69
+ provider: spawn
70
+ toolName: subagent
71
+ modelSelection: true
72
+ modelDiscovery: true
73
+ - id: compaction
74
+ name: cordis:group
75
+ group: true
76
+ isolate:
77
+ compaction: true
78
+ config:
79
+ - id: compaction-basic
80
+ name: '@deepseek-ai/dsh-compaction-basic'
81
+ - id: tool-executor-ptc
82
+ name: '@deepseek-ai/dsh-tool-executor-ptc'
83
+
84
+ - id: preset-lean-assistant
85
+ name: '@deepseek-ai/dsh-agent-preset'
86
+ config:
87
+ id: lean-assistant
88
+ name: Lean assistant (PTC)
89
+ description: Lean PTC assistant for L3 assistants - run_code plus the 9 core tools with lean instructions.
90
+ order: 11
91
+ plugins:
92
+ - id: persona
93
+ name: '@deepseek-ai/dsh-persona'
94
+ config:
95
+ prefix: You are a coding agent powered by the {{model}} model.
96
+ - id: agent-instructions
97
+ name: '@deepseek-ai/dsh-agent-instructions'
98
+ config:
99
+ maxBytes: 16384
100
+ - id: time-context
101
+ name: '@deepseek-ai/dsh-time-context'
102
+ - id: tool-bash
103
+ name: '@deepseek-ai/dsh-tool-bash'
104
+ disabled: !!js process.platform === 'win32'
105
+ - id: tool-pwsh
106
+ name: '@deepseek-ai/dsh-tool-pwsh'
107
+ disabled: !!js process.platform !== 'win32'
108
+ - id: tool-fs
109
+ name: '@deepseek-ai/dsh-tool-fs'
110
+ config:
111
+ applyPatch: false
112
+ - id: tool-fs-search
113
+ name: '@deepseek-ai/dsh-tool-fs-search'
114
+ config:
115
+ sampleOverCapGlobResults: false
116
+ - id: tool-working-directory
117
+ name: '@deepseek-ai/dsh-tool-working-directory'
118
+ - id: tool-todo
119
+ name: '@deepseek-ai/dsh-tool-todo'
120
+ config:
121
+ allowParallelInProgress: true
122
+ # tool-subagent registers delegation services, so it lives in an isolate
123
+ # group like the built-in ptc preset's 'delegation' row; a bare Service
124
+ # row leaks to the root realm and fails the mount.
125
+ - id: delegation
126
+ name: cordis:group
127
+ group: true
128
+ isolate:
129
+ workflowEngine: true
130
+ config:
131
+ - id: tool-subagent
132
+ name: '@deepseek-ai/dsh-tool-subagent'
133
+ config:
134
+ provider: spawn
135
+ toolName: subagent
136
+ modelSelection: true
137
+ modelDiscovery: true
138
+ - id: compaction
139
+ name: cordis:group
140
+ group: true
141
+ isolate:
142
+ compaction: true
143
+ config:
144
+ - id: compaction-basic
145
+ name: '@deepseek-ai/dsh-compaction-basic'
146
+ - id: tool-executor-ptc
147
+ name: '@deepseek-ai/dsh-tool-executor-ptc'
package/lib/backend.js ADDED
@@ -0,0 +1,14 @@
1
+ // Backend boundary for the DSH host process. oMLX is the only adapter today;
2
+ // future mtplx / mlx-serve adapters return the same normalized snapshot.
3
+ import { createOmlxTelemetry } from "./telemetry.js"
4
+
5
+ export const createLocalBackend = (options = {}) => {
6
+ const kind = options.kind ?? "omlx"
7
+ if (kind !== "omlx") {
8
+ throw new Error("unsupported local backend: " + kind)
9
+ }
10
+ return {
11
+ kind,
12
+ read: createOmlxTelemetry(options)
13
+ }
14
+ }
@@ -0,0 +1,4 @@
1
+ // GENERATED by scripts/build-id.mjs - do not edit by hand.
2
+ // sha256 over the canonical 19-file list (11 plugin lib + 8 domain contract
3
+ // sources), so a domain-contract change moves the id too (DEC-30-01).
4
+ export const buildId = "6a887da8bca27c824da9667ccc532d49f3509c0935d3928128876c18932c22a4"
@@ -0,0 +1,27 @@
1
+ /** Signature of the engine's resident model set (order-insensitive). */
2
+ export const residentSignature = (snapshot) =>
3
+ snapshot !== null && typeof snapshot === "object" && Array.isArray(snapshot.residentModels)
4
+ ? snapshot.residentModels.slice().sort().join("|")
5
+ : null
6
+
7
+ /** Decide whether a telemetry snapshot requires a capability refresh. */
8
+ export const capabilitySyncDecision = (previous, snapshot) => {
9
+ const signature = residentSignature(snapshot)
10
+ if (signature === null) return { changed: false, signature: previous }
11
+ return { changed: previous !== null && signature !== previous, signature }
12
+ }
13
+
14
+ /** Wire the sync: snapshotOf -> invalidate + refresh only when the set changed. */
15
+ export const createCapabilitySync = ({ snapshotOf, invalidate, refresh }) => {
16
+ let previous = null
17
+ return () => {
18
+ const snapshot = typeof snapshotOf === "function" ? snapshotOf() : null
19
+ const decision = capabilitySyncDecision(previous, snapshot)
20
+ if (decision.signature === null) return
21
+ if (decision.changed) {
22
+ if (typeof invalidate === "function") invalidate()
23
+ if (typeof refresh === "function") refresh()
24
+ }
25
+ previous = decision.signature
26
+ }
27
+ }
@@ -0,0 +1,451 @@
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
+ /** Join the text blocks of one DSH message. */
16
+ const textOf = (message) =>
17
+ Array.isArray(message?.content)
18
+ ? message.content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("")
19
+ : ""
20
+
21
+ /** OpenAI chat-completions base for an engine endpoint (tolerates a trailing /v1 or /admin). */
22
+ export const engineBaseUrl = (endpoint) => {
23
+ const raw = typeof endpoint === "string" && endpoint.length > 0 ? endpoint : "http://127.0.0.1:8000"
24
+ const trimmed = raw.replace(/\/+$/u, "").replace(/\/admin(\/api)?$/u, "")
25
+ return /\/v1$/u.test(trimmed) ? trimmed : trimmed + "/v1"
26
+ }
27
+ /** Engine admin base (model metadata such as context length lives here). */
28
+ export const engineAdminBaseUrl = (endpoint) => engineBaseUrl(endpoint).replace(/\/v1$/u, "") + "/admin/api"
29
+
30
+ /**
31
+ * Serialize DSH request messages into OpenAI chat-completions messages.
32
+ * @param {object} options - GenerateOptions from the harness.
33
+ * @returns {Array<object>} OpenAI messages, in order.
34
+ */
35
+ export const serializeMessages = (options) => {
36
+ const out = []
37
+ const source = Array.isArray(options?.messages) ? options.messages : []
38
+ let system = typeof options?.system === "string" && options.system.length > 0 ? options.system : ""
39
+ for (const message of source) {
40
+ if (message === null || typeof message !== "object") continue
41
+ switch (message.role) {
42
+ case "system": {
43
+ const text = textOf(message)
44
+ if (text.length > 0) system = system.length > 0 ? system + "\n\n" + text : text
45
+ break
46
+ }
47
+ case "developer": {
48
+ const text = textOf(message)
49
+ if (text.length > 0) out.push({ role: "system", content: text })
50
+ break
51
+ }
52
+ case "assistant": {
53
+ const content = textOf(message)
54
+ const toolCalls = []
55
+ for (const block of Array.isArray(message.content) ? message.content : []) {
56
+ if (block?.type !== "tool-call") continue
57
+ toolCalls.push({
58
+ id: typeof block.id === "string" ? block.id : "",
59
+ type: "function",
60
+ function: {
61
+ name: typeof block.name === "string" ? block.name : "",
62
+ arguments: typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {})
63
+ }
64
+ })
65
+ }
66
+ // An interrupted or reasoning-only turn has no text and no calls; sending
67
+ // an assistant message with neither content nor tool_calls is rejected by
68
+ // OpenAI-compatible servers, so drop it.
69
+ if (content.length === 0 && toolCalls.length === 0) break
70
+ out.push({
71
+ role: "assistant",
72
+ ...content.length > 0 ? { content } : { content: "" },
73
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
74
+ })
75
+ break
76
+ }
77
+ case "tool": {
78
+ out.push({
79
+ role: "tool",
80
+ tool_call_id: typeof message.toolCallId === "string" ? message.toolCallId : "",
81
+ content: textOf(message).length > 0 ? textOf(message) : "(no output)"
82
+ })
83
+ break
84
+ }
85
+ default: {
86
+ // Preserve multimodal parts: DSH image blocks carry mimeType + base64 data
87
+ // and OpenAI-compatible engines expect a data URL image_url part.
88
+ const parts = []
89
+ let hasImage = false
90
+ for (const block of Array.isArray(message.content) ? message.content : []) {
91
+ if (block === null || typeof block !== "object") continue
92
+ if (block.type === "text" && typeof block.text === "string" && block.text.length > 0) {
93
+ parts.push({ type: "text", text: block.text })
94
+ } else if (
95
+ block.type === "image" &&
96
+ typeof block.mimeType === "string" &&
97
+ block.mimeType.length > 0 &&
98
+ typeof block.data === "string" &&
99
+ block.data.length > 0
100
+ ) {
101
+ hasImage = true
102
+ parts.push({
103
+ type: "image_url",
104
+ image_url: { url: "data:" + block.mimeType + ";base64," + block.data }
105
+ })
106
+ }
107
+ }
108
+ if (!hasImage) {
109
+ const content = textOf(message)
110
+ if (content.length > 0) out.push({ role: "user", content })
111
+ } else {
112
+ out.push({ role: "user", content: parts })
113
+ }
114
+ }
115
+ }
116
+ }
117
+ if (system.length > 0) out.unshift({ role: "system", content: system })
118
+ return out
119
+ }
120
+
121
+ /** OpenAI tool declarations from DSH ToolSchema[]. */
122
+ export const serializeTools = (tools) =>
123
+ Array.isArray(tools)
124
+ ? tools.filter((tool) => typeof tool?.name === "string" && tool.name.length > 0).map((tool) => ({
125
+ type: "function",
126
+ function: {
127
+ name: tool.name,
128
+ description: typeof tool.description === "string" ? tool.description : "",
129
+ parameters: tool.parameters !== null && typeof tool.parameters === "object" ? tool.parameters : { type: "object", properties: {} }
130
+ }
131
+ }))
132
+ : []
133
+
134
+ /** Map an engine finish_reason to the harness finish reason. */
135
+ const finishReason = (reason, hasContent) => {
136
+ if (reason === "length") return { kind: "max-tokens" }
137
+ if (reason === "tool_calls" || reason === "tool_use") return { kind: "tool-calls" }
138
+ if (!hasContent) {
139
+ return { kind: "error", failure: { message: "engine returned a completed response with no content", code: "EMPTY_RESPONSE" } }
140
+ }
141
+ return { kind: "stop" }
142
+ }
143
+
144
+ /** Disjoint harness token counts (cached input is not uncached input). */
145
+ const usageOf = (usage) => {
146
+ const prompt = Number.isFinite(usage?.prompt_tokens) ? usage.prompt_tokens : 0
147
+ const cached = Number.isFinite(usage?.prompt_tokens_details?.cached_tokens) ? usage.prompt_tokens_details.cached_tokens : 0
148
+ const completion = Number.isFinite(usage?.completion_tokens) ? usage.completion_tokens : 0
149
+ const reasoning = Number.isFinite(usage?.completion_tokens_details?.reasoning_tokens) ? usage.completion_tokens_details.reasoning_tokens : 0
150
+ const total = Number.isFinite(usage?.total_tokens) ? usage.total_tokens : prompt + completion
151
+ return {
152
+ inputTokens: Math.max(0, prompt - cached),
153
+ outputTokens: completion,
154
+ totalTokens: total,
155
+ ...cached > 0 ? { cacheReadTokens: cached } : {},
156
+ ...reasoning > 0 ? { reasoningTokens: reasoning } : {}
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Convert one non-streaming chat-completion body into the harness chunk protocol.
162
+ * @param {object} body - engine response JSON.
163
+ * @returns {Array<object>} StreamChunk sequence ending with finish.
164
+ */
165
+ export const toChunks = (body) => {
166
+ const choice = Array.isArray(body?.choices) ? body.choices[0] : undefined
167
+ const message = choice?.message ?? {}
168
+ const chunks = []
169
+ let index = 0
170
+ const reasoning = typeof message.reasoning_content === "string" ? message.reasoning_content : ""
171
+ if (reasoning.length > 0) {
172
+ chunks.push({ type: "block-start", index, blockType: "reasoning" })
173
+ chunks.push({ type: "reasoning-delta", index, text: reasoning })
174
+ chunks.push({ type: "block-end", index, block: { type: "reasoning", text: reasoning } })
175
+ index += 1
176
+ }
177
+ const content = typeof message.content === "string" ? message.content : ""
178
+ let emitted = reasoning.length > 0 ? 1 : 0
179
+ if (content.length > 0) {
180
+ chunks.push({ type: "block-start", index, blockType: "text" })
181
+ chunks.push({ type: "text-delta", index, text: content })
182
+ chunks.push({ type: "block-end", index, block: { type: "text", text: content } })
183
+ index += 1
184
+ emitted += 1
185
+ }
186
+ const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : []
187
+ for (const call of toolCalls) {
188
+ const id = typeof call?.id === "string" ? call.id : ""
189
+ const name = typeof call?.function?.name === "string" ? call.function.name : ""
190
+ const args = typeof call?.function?.arguments === "string" ? call.function.arguments : JSON.stringify(call?.function?.arguments ?? {})
191
+ if (id.length === 0 || name.length === 0) continue
192
+ chunks.push({ type: "block-start", index, blockType: "tool-call" })
193
+ chunks.push({ type: "tool-call-delta", index, id, name, argumentsDelta: args })
194
+ chunks.push({ type: "block-end", index, block: { type: "tool-call", id, name, arguments: args } })
195
+ index += 1
196
+ emitted += 1
197
+ }
198
+ chunks.push({ type: "usage", usage: usageOf(body?.usage) })
199
+ chunks.push({ type: "finish", reason: finishReason(choice?.finish_reason, emitted > 0) })
200
+ return chunks
201
+ }
202
+
203
+ /** Throw a typed engine failure so DSH classifies and retries it. */
204
+ const engineError = (message, code) => {
205
+ const error = new Error(message)
206
+ error.code = code
207
+ error.failure = { message, code }
208
+ return error
209
+ }
210
+
211
+ /**
212
+ * Build the duck-typed LlmAdapter the host registers for the engine provider.
213
+ * @param {object} options - getConnection() and optional fetch/now injection.
214
+ * @returns {object} adapter
215
+ */
216
+ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now, modelCapabilities = {} } = {}) => {
217
+ const doFetch = typeof fetchImpl === "function" ? fetchImpl : (...args) => globalThis.fetch(...args)
218
+ let cache = { at: Number.NEGATIVE_INFINITY, base: "", models: [] }
219
+ // Last capability reconciliation: which sources answered, what was excluded.
220
+ let capabilityReport = { fetchedAt: null, sources: { models: false, admin: false }, advertised: 0, excluded: [] }
221
+ // Keys the capability mapping depends on. A disappearing key means the
222
+ // engine payload changed shape; keep the last-good catalog instead of
223
+ // silently degrading to text-only / no-context models.
224
+ const requiredKeys = { models: ["model_type", "max_model_len"], admin: ["model_context_length"] }
225
+ let lastGoodKeys = { models: new Set(), admin: new Set() }
226
+ let lastGoodModels = []
227
+ const connectionOf = () => (typeof getConnection === "function" ? getConnection() : { endpoint: "", apiKey: "" })
228
+
229
+ const authorized = () => {
230
+ const connection = connectionOf() ?? {}
231
+ const key = typeof connection.apiKey === "string" && connection.apiKey.length > 0 ? connection.apiKey : ""
232
+ return {
233
+ base: engineBaseUrl(connection.endpoint),
234
+ headers: {
235
+ "content-type": "application/json",
236
+ accept: "application/json",
237
+ ...key.length > 0 ? { authorization: "Bearer " + key } : {}
238
+ }
239
+ }
240
+ }
241
+
242
+ // Context length comes from the engine's own admin metadata; when the engine
243
+ // does not report one it stays omitted rather than invented.
244
+ const modelInfo = (provider, entry) => {
245
+ const contextWindow = Number.isFinite(entry.contextWindow)
246
+ ? entry.contextWindow
247
+ : Number.isFinite(entry.context?.contextWindow)
248
+ ? entry.context.contextWindow
249
+ : null
250
+ const modalities = Array.isArray(entry.inputModalities) ? entry.inputModalities : ["text"]
251
+ return {
252
+ id: entry.id,
253
+ name: entry.name,
254
+ provider,
255
+ ...contextWindow === null ? {} : { context: { contextWindow } },
256
+ inputModalities: modalities
257
+ }
258
+ }
259
+
260
+ return {
261
+ providerInfo: (provider) => ({ id: provider, name: ENGINE_PROVIDER_NAME }),
262
+ providerRetryPolicy: () => undefined,
263
+ imageRequestPricing: () => undefined,
264
+ imageRequestTarget: (_provider, _model, image) => ({
265
+ width: Number.isFinite(image?.width) ? image.width : 0,
266
+ height: Number.isFinite(image?.height) ? image.height : 0,
267
+ maxBytes: Number.isFinite(image?.bytes) ? image.bytes : Number.isFinite(image?.maxBytes) ? image.maxBytes : 0
268
+ }),
269
+ async listModels(provider) {
270
+ const currentBase = engineBaseUrl(connectionOf()?.endpoint)
271
+ if (cache.base === currentBase && now() - cache.at < 5000) return cache.models
272
+ const { base, headers } = authorized()
273
+ const adminUrl = engineAdminBaseUrl(connectionOf()?.endpoint) + "/models"
274
+ // Read both engine surfaces: /v1/models carries model_type + max_model_len,
275
+ // /admin/api/models carries model_context_length and runtime flags.
276
+ const [modelsResult, adminResult] = await Promise.allSettled([
277
+ doFetch(base + "/models", { method: "GET", headers }),
278
+ doFetch(adminUrl, { method: "GET", headers })
279
+ ])
280
+ let body
281
+ if (modelsResult.status === "fulfilled" && modelsResult.value.ok) {
282
+ try {
283
+ body = await modelsResult.value.json()
284
+ } catch {
285
+ body = undefined
286
+ }
287
+ }
288
+ if (body === undefined) return cache.base === currentBase ? cache.models : []
289
+ const adminContexts = new Map()
290
+ let adminOk = false
291
+ if (adminResult.status === "fulfilled" && adminResult.value.ok) {
292
+ try {
293
+ const adminBody = await adminResult.value.json()
294
+ adminOk = true
295
+ for (const entry of Array.isArray(adminBody?.models) ? adminBody.models : []) {
296
+ if (
297
+ entry !== null &&
298
+ typeof entry === "object" &&
299
+ typeof entry.id === "string" &&
300
+ Number.isFinite(entry.model_context_length)
301
+ ) {
302
+ adminContexts.set(entry.id, entry.model_context_length)
303
+ }
304
+ }
305
+ } catch {}
306
+ }
307
+ const modelRows = Array.isArray(body?.data) ? body.data : []
308
+ const currentKeys = { models: new Set(), admin: new Set() }
309
+ for (const row of modelRows) {
310
+ if (row === null || typeof row !== "object") continue
311
+ for (const key of requiredKeys.models) if (row[key] !== undefined) currentKeys.models.add(key)
312
+ }
313
+ for (const key of requiredKeys.admin) {
314
+ if (Array.from(adminContexts.keys()).length > 0) currentKeys.admin.add(key)
315
+ }
316
+ const missingKeys = []
317
+ for (const surface of ["models", "admin"]) {
318
+ for (const key of requiredKeys[surface]) {
319
+ if (lastGoodKeys[surface].has(key) && !currentKeys[surface].has(key)) missingKeys.push(key)
320
+ }
321
+ }
322
+ if (missingKeys.length > 0) {
323
+ capabilityReport = {
324
+ fetchedAt: now(),
325
+ sources: { models: true, admin: adminOk },
326
+ advertised: lastGoodModels.length,
327
+ excluded: capabilityReport.excluded,
328
+ stale: true,
329
+ drift: { missingKeys, at: now() }
330
+ }
331
+ cache = { at: now(), base: currentBase, models: lastGoodModels }
332
+ return lastGoodModels
333
+ }
334
+ lastGoodKeys = currentKeys
335
+ const seen = new Set()
336
+ const entries = []
337
+ const excluded = []
338
+ for (const model of modelRows) {
339
+ const id = typeof model?.id === "string" ? model.id : ""
340
+ if (id.length === 0 || seen.has(id)) continue
341
+ seen.add(id)
342
+ const modelType = typeof model.model_type === "string" ? model.model_type.toLowerCase() : ""
343
+ const vision = ["vlm", "vision", "multimodal", "image"].some((kind) => modelType.includes(kind))
344
+ const override = modelCapabilities !== null && typeof modelCapabilities === "object" ? modelCapabilities[id] : undefined
345
+ const contextWindow = Number.isFinite(override?.contextWindow)
346
+ ? override.contextWindow
347
+ : Number.isFinite(adminContexts.get(id))
348
+ ? adminContexts.get(id)
349
+ : Number.isFinite(model.max_model_len)
350
+ ? model.max_model_len
351
+ : undefined
352
+ const modalities = Array.isArray(override?.inputModalities)
353
+ ? override.inputModalities
354
+ : vision
355
+ ? ["text", "image"]
356
+ : undefined
357
+ entries.push({
358
+ id,
359
+ name: typeof model.name === "string" && model.name.length > 0 ? model.name : id,
360
+ provider,
361
+ ...modalities === undefined ? {} : { inputModalities: modalities },
362
+ ...Number.isFinite(contextWindow) ? { context: { contextWindow } } : {},
363
+ contextKnown: Number.isFinite(contextWindow)
364
+ })
365
+ }
366
+ // DSH cannot switch a session to a model without a contextWindow
367
+ // (MODEL_SWITCH_COMPACTION_FAILED). When the engine reports context for at
368
+ // least one model, treat that as the contract and only advertise models
369
+ // that satisfy it; models with no known context are reported, not guessed.
370
+ const someKnown = entries.some((entry) => entry.contextKnown)
371
+ const models = []
372
+ for (const entry of entries) {
373
+ if (someKnown && !entry.contextKnown) {
374
+ excluded.push({ id: entry.id, reason: "no contextWindow from engine metadata" })
375
+ continue
376
+ }
377
+ const { contextKnown, ...model } = entry
378
+ models.push(model)
379
+ }
380
+ capabilityReport = {
381
+ fetchedAt: now(),
382
+ sources: { models: true, admin: adminOk },
383
+ advertised: models.length,
384
+ excluded,
385
+ stale: false,
386
+ drift: null
387
+ }
388
+ lastGoodModels = models
389
+ cache = { at: now(), base: currentBase, models }
390
+ return models
391
+ },
392
+ capabilitiesReport: () => ({ ...capabilityReport, sources: { ...capabilityReport.sources }, excluded: capabilityReport.excluded.slice() }),
393
+ /** A model load/unload changes what the engine serves; drop the cache. */
394
+ invalidateCapabilities: () => {
395
+ cache = { at: Number.NEGATIVE_INFINITY, base: "", models: [] }
396
+ },
397
+ async resolveModel(provider, model, signal) {
398
+ if (signal?.aborted === true) throw engineError("engine resolve aborted", "ABORTED")
399
+ const models = await this.listModels(provider)
400
+ const found = models.find((entry) => entry.id === model)
401
+ if (found === undefined) {
402
+ throw engineError('engine does not serve model "' + String(model) + '"', "INVALID_REQUEST")
403
+ }
404
+ return modelInfo(provider, found)
405
+ },
406
+ prepareCall(provider, model) {
407
+ const cached = cache.models.find((entry) => entry.id === model)
408
+ return {
409
+ model: modelInfo(provider, cached ?? { id: model, name: model }),
410
+ stream: (options) => (async function* () {
411
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
412
+ const { base, headers } = authorized()
413
+ const payload = {
414
+ model,
415
+ messages: serializeMessages(options),
416
+ stream: false,
417
+ ...Array.isArray(options?.tools) && options.tools.length > 0 ? { tools: serializeTools(options.tools) } : {},
418
+ ...Number.isFinite(options?.temperature) ? { temperature: options.temperature } : {},
419
+ ...Number.isFinite(options?.maxTokens) ? { max_tokens: options.maxTokens } : {},
420
+ ...Array.isArray(options?.stop) && options.stop.length > 0 ? { stop: options.stop } : {}
421
+ }
422
+ let response
423
+ try {
424
+ response = await doFetch(base + "/chat/completions", { method: "POST", headers, body: JSON.stringify(payload), signal: options?.signal })
425
+ } catch (error) {
426
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
427
+ throw engineError("engine transport failed: " + (error?.message ?? String(error)), "TRANSPORT")
428
+ }
429
+ let text
430
+ try {
431
+ text = await response.text()
432
+ } catch (error) {
433
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
434
+ throw engineError("engine body read failed: " + (error?.message ?? String(error)), "TRANSPORT")
435
+ }
436
+ if (!response.ok) {
437
+ const code = response.status === 401 || response.status === 403 ? "AUTH" : response.status === 429 ? "RATE_LIMIT" : response.status >= 500 ? "SERVER" : "INVALID_REQUEST"
438
+ throw engineError("engine chat request failed (" + response.status + "): " + text.slice(0, 240), code)
439
+ }
440
+ let body
441
+ try {
442
+ body = JSON.parse(text)
443
+ } catch {
444
+ throw engineError("engine returned a non-JSON chat response", "SERVER")
445
+ }
446
+ for (const chunk of toChunks(body)) yield chunk
447
+ })()
448
+ }
449
+ }
450
+ }
451
+ }