magpie-sparkdash 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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/icon.png +0 -0
  4. package/index.mjs +1044 -0
  5. package/package.json +31 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 G36maid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,208 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <img src="icon.png" width="110" alt="magpie-sparkdash — a lightning bolt on amber, sparkDash's mark">
4
+
5
+ # magpie-sparkdash
6
+
7
+ **Your DGX Spark fleet, as magpie models — with live queue-depth routing.**
8
+
9
+ A [magpie](https://github.com/yetone/magpie) plugin provider fed by
10
+ [sparkDash](https://github.com/MiaAI-Lab/sparkDash): point it at your sparkDash
11
+ dashboard and every engine in the fleet becomes a `sparkdash/<model>` provider —
12
+ and magpie stops standing in an engine's queue when other clients have filled it.
13
+
14
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
15
+ [![sparkDash](https://img.shields.io/badge/sparkDash-%E2%89%A52.31-orange)](https://github.com/MiaAI-Lab/sparkDash)
16
+ [![magpie](https://img.shields.io/badge/magpie-plugin-8A2BE2)](https://usemagpie.ai/docs/plugins)
17
+ [![tests](https://img.shields.io/badge/tests-smoke%2010%2F10-success)](test/smoke.mjs)
18
+
19
+ *Give it one thing — where sparkDash is. Everything else is discovered.*
20
+
21
+ </div>
22
+
23
+ ---
24
+
25
+ ## The one-minute version
26
+
27
+ Your engine's slots fill up. Someone's notebook is churning through a local job,
28
+ and every "fast local model" turn in magpie silently waits *minutes* in that
29
+ queue. magpie already has the fix — **Busy models last** — it just needs a
30
+ sensor. This plugin is the sensor:
31
+
32
+ | engine queue | load reported | routing |
33
+ |:---:|:---:|---|
34
+ | empty | `0` | spark leads, as usual |
35
+ | queueing | `100` | cloud candidates lead, at once |
36
+ | queue empties | `0` | spark leads again, next turn |
37
+
38
+ Nothing is rejected and the engine is never touched: local-only jobs that *want*
39
+ to queue keep queueing exactly as before. When sparkDash and the engines are
40
+ both unreachable, the plugin retracts its reports and magpie routes as it would
41
+ without the plugin (fail-open).
42
+
43
+ ## Quick start
44
+
45
+ ```bash
46
+ magpie plugin add github:G36maid/magpie-sparkdash # or a local path
47
+ magpie plugin login magpie-sparkdash # asks only: where is your sparkDash?
48
+ ```
49
+
50
+ …or skip the sign-in entirely:
51
+
52
+ ```bash
53
+ magpie plugin options magpie-sparkdash '{"dash": "http://your-sparkdash:5555"}'
54
+ ```
55
+
56
+ The sign-in checks sparkDash's `/api/health` before saving the address; a
57
+ token-protected dash (`SPARKDASH_TOKEN`) can be given as
58
+ `http://host:5555?token=…` or via the [`token` option](#options).
59
+
60
+ Then:
61
+
62
+ 1. Turn on **Busy models last** in magpie's Settings (`"busyLoad": 50` in
63
+ `~/.config/magpie/settings.json` is a good default; any threshold 1–99 works).
64
+ 2. Pick `sparkdash/<model>` in an agent or a routing group. The provider shows
65
+ up as **sparkDash**.
66
+
67
+ ## What it discovers
68
+
69
+ Everything, from sparkDash itself — nothing to configure per unit:
70
+
71
+ - the units online, and every LLM engine port each one monitors
72
+ (dash host for units on the dash's machine, `lanIp` for the rest),
73
+ - each engine's model id(s), `reasoning` and `tool_call` flags (from the
74
+ engine's own `/v1/models` capabilities) and context length,
75
+ - the queue depth of each port, once per second from the websocket.
76
+
77
+ Two engines serving the same model are one candidate pool: the request goes to
78
+ the one with the fewest waiting requests (ties broken by running requests, then
79
+ round-robin), and the model reads as free while at least one engine's queue is
80
+ empty.
81
+
82
+ ## Compatibility
83
+
84
+ Built and tested against **sparkDash 2.91** (current upstream). What it reads
85
+ and when that landed:
86
+
87
+ | what the plugin reads | in sparkDash since |
88
+ |---|---|
89
+ | unit snapshots' `lanIp` and per-port `metrics.llm` | 1.0 |
90
+ | `llmPorts` — several LLM ports on one unit | 1.0.5 |
91
+ | queue depth `metrics.llm[].requestsWaiting` (vLLM, SGLang) | 1.1.5 / 1.4.5 |
92
+ | `llmApiKeyPorts` — per-port API-key gateways (optional read) | 1.4.4 |
93
+ | TensorFold queue depth (`live.waiting`) | 1.9.0 |
94
+ | `/api/health` with `authMode` — the sign-in check | 1.8.6 (first tagged release with it: 2.31.0) |
95
+
96
+ In practice **sparkDash ≥ 2.31** signs in and reports load; an older dash fails
97
+ the sign-in check with a clear message. No minimum is claimed for magpie: the
98
+ plugin uses its plugin `load` API and `busyLoad` routing, both long-standing.
99
+
100
+ <details>
101
+ <summary>How the four <code>authMode</code> values map to sign-in</summary>
102
+
103
+ | `authMode` | what the dash is | signing in |
104
+ |---|---|---|
105
+ | `loopback-open` | bound to 127.0.0.1, no token | only from the dash's own machine |
106
+ | `open-remote` | remote bind, tokenless allowed | no token needed |
107
+ | `bearer` | token configured (`SPARKDASH_TOKEN`) | give it as `?token=…` or the `token` option |
108
+ | `required-missing` | remote bind with no token — refuses everything | reported at sign-in, with the fix spelled out |
109
+
110
+ The WebSocket takes the token as `?token=…` — sparkDash reads the query
111
+ parameter on purpose, because a browser socket cannot set headers.
112
+ </details>
113
+
114
+ ## Options
115
+
116
+ ```jsonc
117
+ {
118
+ "dash": "http://your-sparkdash:5555", // sparkDash URL (optional if signed in
119
+ // or `engines` is set; subpaths are kept)
120
+ "token": "…", // for a SPARKDASH_TOKEN-protected dash
121
+ // (or append ?token=… to the address)
122
+ "provider": "sparkdash", // provider id in magpie (optional)
123
+ "apiKey": "sk-…", // Bearer key sent to every engine (optional)
124
+ "engines": [ // optional: pin engines instead of (or in
125
+ "http://your-sparkdash:8888", // addition to) discovering them from
126
+ { "url": "http://spark-2:8888", // sparkDash; per-engine apiKey overrides
127
+ "apiKey": "sk-…" } // the global one
128
+ ]
129
+ }
130
+ ```
131
+
132
+ <details>
133
+ <summary>Notes on reaching the engines</summary>
134
+
135
+ - The plugin reaches each engine at the **dash host's** name for units running
136
+ on the dash host, and at each remote unit's `lanIp` for the rest — dash and
137
+ engines must be reachable from the machine magpie runs on, by those names.
138
+ Pin `engines` when that does not hold (dash behind a reverse proxy or NAT).
139
+ - Engine discovery works over sparkDash's websocket (`/ws`, token auth
140
+ included). With `engines` pinned, the plugin polls each engine's `/health`
141
+ directly and the websocket is not required; pinned engines are additionally
142
+ polled even while the websocket is up.
143
+ - Any OpenAI-compatible engine on a monitored port works (TensorFold answers
144
+ `owned_by: tensorfold`); a missing `/health` degrades gracefully — the engine
145
+ is still counted reachable via `/v1/models`, minus the queue depth.
146
+ - The provider editor's **Report queue depth as load** switch turns load
147
+ reporting off without touching discovery; on switch-off the last reports are
148
+ retracted.
149
+ - Several signed-in sparkDash addresses are watched in parallel, one monitor
150
+ each.
151
+ </details>
152
+
153
+ ## How it works
154
+
155
+ ```mermaid
156
+ flowchart LR
157
+ subgraph fleet[DGX Spark fleet]
158
+ E1[engine :8888]
159
+ E2[engine :8888 on another unit]
160
+ end
161
+ SD[sparkDash dashboard]
162
+ P[magpie-sparkdash]
163
+ M[magpie gateway]
164
+
165
+ SD -- "1 Hz snapshots<br/>requestsWaiting per port" --> P
166
+ P -- "load: waiting &gt; 0 ? 100 : 0" --> M
167
+ P -- "route requests<br/>to the least-busy engine" --> E1
168
+ P --> E2
169
+ P -. "/health fallback<br/>when the ws is away" .-> E1
170
+ M -- "Busy models last" --> CLOUD[cloud candidates]
171
+ ```
172
+
173
+ - The websocket is watched for silence: no snapshot for 20 s means a half-open
174
+ connection — it is closed (reconnect with exponential backoff, 5 s → 60 s
175
+ cap) and `/health` polling takes over every 10 s.
176
+ - Load reports are re-sent as a heartbeat every two minutes even when nothing
177
+ changes, well inside magpie's five-minute load TTL.
178
+ - A fresh model on a restarted engine is picked up by the websocket snapshot,
179
+ the `/health` poll, and the periodic re-discovery (6 h); capabilities are
180
+ fetched again whenever a model list changes.
181
+ - magpie's group setting `firstToken` (e.g. 120–150 s) still makes a good fuse
182
+ for a hung engine.
183
+
184
+ ## Testing
185
+
186
+ Zero dependencies, against in-process mock servers standing in for the engine
187
+ and the dashboard:
188
+
189
+ ```bash
190
+ npm test # node test/smoke.mjs — 10 checks: discovery, load flips,
191
+ # routing, sign-in, ws snapshot, pinned-mode isolation
192
+ ```
193
+
194
+ ## Sources
195
+
196
+ - [MiaAI-Lab/sparkDash](https://github.com/MiaAI-Lab/sparkDash) — the
197
+ multi-DGX-Spark monitoring dashboard this plugin is fed by; its TensorFold
198
+ probe and `/ws` snapshots are what `requestsWaiting` comes from.
199
+ - [MiaAI-Lab/GLM-5.3-Flash-DGX-Sparks-1104](https://github.com/MiaAI-Lab/GLM-5.3-Flash-DGX-Sparks-1104)
200
+ — the TensorFold recipe this was built against: GLM-5.3-Flash on two DGX
201
+ Sparks (`--parallel 4`), served on `:8888`.
202
+ - [yetone/magpie](https://github.com/yetone/magpie) — the gateway; its plugin
203
+ `load` API, `BusyLoad` setting and busy-last ordering are the consumer of
204
+ everything above (`internal/gateway/fallback.go: busyOf`, `affinity.go: busyBehind`).
205
+
206
+ ## License
207
+
208
+ MIT — see [LICENSE](LICENSE).
package/icon.png ADDED
Binary file
package/index.mjs ADDED
@@ -0,0 +1,1044 @@
1
+ // magpie-sparkdash — a magpie plugin provider fed by sparkDash.
2
+ //
3
+ // Sign in once, giving your sparkDash address; everything else is
4
+ // automatic. The plugin subscribes to sparkDash's /ws snapshots and, from
5
+ // each snapshot:
6
+ // - discovers every online unit and every LLM engine port it monitors
7
+ // (using the dash host for local units and each unit's lanIp for remote ones),
8
+ // - discovers each engine's model id(s), capabilities, and context length,
9
+ // - declares all of them as one magpie provider (sparkdash/<model>),
10
+ // - reports each model's load as the engine's queue depth
11
+ // (waiting > 0 => load past any BusyLoad threshold, so magpie's
12
+ // Busy-models-last routing sends the request to a ready candidate
13
+ // instead of standing in the engine's queue),
14
+ // and keeps those reports fresh while sparkDash streams (including a periodic
15
+ // heartbeat before magpie's 5-minute load TTL expires). When the websocket is
16
+ // away or stale it polls each engine's /health directly; when no source is
17
+ // reachable (or the GUI load-reporting toggle is off) it retracts its reports,
18
+ // and magpie routes as it would without the plugin (fail-open).
19
+ //
20
+ // The sign-in asks one question — where sparkDash is. No key is required for
21
+ // an open sparkDash; a token-protected dash can be given as
22
+ // http://host:5555?token=... or via the plugin "token" option. An "engines"
23
+ // option still exists to pin engines directly (with or without sparkDash),
24
+ // and an optional "apiKey" (global or per pinned engine) sets the Bearer key
25
+ // sent to engines behind authentication.
26
+ //
27
+ // Works with (see also the README):
28
+ // - sparkDash by Mia's AI Lab https://github.com/MiaAI-Lab/sparkDash
29
+ // - the TensorFold GLM-5.3-Flash pair recipe on 2x DGX Spark
30
+ // https://github.com/MiaAI-Lab/GLM-5.3-Flash-DGX-Sparks-1104
31
+ //
32
+ // Routing notes, from magpie's own docs and code:
33
+ // - settings' busyLoad ("Busy models last") is compared strictly greater:
34
+ // report 100 while waiting > 0 so any threshold from 1..99 marks it busy.
35
+ // - load reports expire after five minutes; this plugin refreshes before
36
+ // that even when load stays unchanged.
37
+ // - busyOf looks the model up by the plugin's own id of it (OwnModelID),
38
+ // so the loads map is keyed by the engine's model id as the engine
39
+ // names it, which is what discovery stores.
40
+
41
+ import { readFileSync } from "node:fs"
42
+
43
+ const PLUGIN_TAG = "[magpie-sparkdash]"
44
+ const DEFAULT_POLL_MS = 10_000 // /health fallback poll
45
+ const DEFAULT_RETRY_MS = 5_000 // initial websocket reconnect delay
46
+ const DEFAULT_MAX_RETRY_MS = 60_000 // cap for reconnect backoff
47
+ const DEFAULT_FETCH_TIMEOUT_MS = 4_000
48
+ const DEFAULT_DISCOVER_WAIT_MS = 5_000 // a listing waits this long for initial discovery
49
+ const DEFAULT_HEARTBEAT_MS = 120_000 // resend load before magpie's 5-minute TTL
50
+ const DEFAULT_STALE_WS_MS = 20_000 // 1 Hz snapshots; 20s silence => half-open ws
51
+ const DEFAULT_REFRESH_MS = 6 * 60 * 60 * 1000
52
+ const PLACEHOLDER_API_KEY = "sparkdash"
53
+
54
+ // Single source of truth for the icon: read icon.png bundled alongside this file
55
+ const ICON = (() => {
56
+ try {
57
+ const b64 = readFileSync(new URL("./icon.png", import.meta.url)).toString("base64")
58
+ return `data:image/png;base64,${b64}`
59
+ } catch {
60
+ return undefined
61
+ }
62
+ })()
63
+
64
+ const log = (...a) => console.log(PLUGIN_TAG, ...a)
65
+
66
+ // ---- small helpers ------------------------------------------------------
67
+
68
+ const positiveMs = (v, fallback) =>
69
+ typeof v === "number" && Number.isFinite(v) && v > 0 ? v : fallback
70
+
71
+ const formatHostPort = (host, port) => {
72
+ const clean = String(host ?? "").trim().replace(/^\[(.*)\]$/, "$1")
73
+ if (!clean) return null
74
+ const bracketed = clean.includes(":") ? `[${clean}]` : clean
75
+ return `${bracketed}:${port}`
76
+ }
77
+
78
+ // Parse a sparkDash URL, preserving any reverse-proxy subpath and extracting
79
+ // an optional ?token=... query parameter for SPARKDASH_TOKEN auth.
80
+ const parseDashInput = (u) => {
81
+ if (typeof u !== "string" || !u.trim()) return null
82
+ let s = u.trim()
83
+ if (!/^https?:\/\//i.test(s)) s = `http://${s}`
84
+ try {
85
+ const parsed = new URL(s)
86
+ if (!/^https?:$/i.test(parsed.protocol) || !parsed.hostname) return null
87
+ const token = parsed.searchParams.get("token")?.trim() || null
88
+ const pathname = parsed.pathname.replace(/\/+$/, "")
89
+ return {
90
+ url: `${parsed.origin}${pathname}`,
91
+ token,
92
+ host: parsed.host,
93
+ hostname: parsed.hostname,
94
+ protocol: parsed.protocol,
95
+ }
96
+ } catch {
97
+ return null
98
+ }
99
+ }
100
+
101
+ // Normalize an engine base URL (preserving any subpath, stripping trailing /v1
102
+ // so callers can consistently append /v1/... and /health).
103
+ const normalizeEngineBase = (u) => {
104
+ const parsed = parseDashInput(u)
105
+ if (!parsed) return null
106
+ return parsed.url.replace(/\/v1$/i, "")
107
+ }
108
+
109
+ async function fetchJson(url, { timeoutMs = DEFAULT_FETCH_TIMEOUT_MS, headers } = {}) {
110
+ const r = await fetch(url, {
111
+ signal: AbortSignal.timeout(timeoutMs),
112
+ ...(headers ? { headers } : {}),
113
+ })
114
+ if (!r.ok) {
115
+ const err = new Error(`HTTP ${r.status}`)
116
+ err.status = r.status
117
+ throw err
118
+ }
119
+ return r.json()
120
+ }
121
+
122
+ async function extractRequestedModel(req, init) {
123
+ const body = init?.body
124
+ if (typeof body === "string") {
125
+ return parseModelFromJson(body)
126
+ }
127
+ if (body instanceof Uint8Array || body instanceof ArrayBuffer) {
128
+ try {
129
+ const text = new TextDecoder().decode(body)
130
+ return parseModelFromJson(text)
131
+ } catch {
132
+ return null
133
+ }
134
+ }
135
+ if (req instanceof Request && body === undefined && req.body) {
136
+ const ct = req.headers.get("content-type") ?? ""
137
+ if (!ct || ct.includes("json")) {
138
+ try {
139
+ const text = await req.clone().text()
140
+ return parseModelFromJson(text)
141
+ } catch {
142
+ return null
143
+ }
144
+ }
145
+ }
146
+ return null
147
+ }
148
+
149
+ function parseModelFromJson(text) {
150
+ if (!text || text[0] !== "{") return null
151
+ try {
152
+ const parsed = JSON.parse(text)
153
+ return typeof parsed?.model === "string" && parsed.model.trim()
154
+ ? parsed.model.trim()
155
+ : null
156
+ } catch {
157
+ return null
158
+ }
159
+ }
160
+
161
+ // ---- one engine ---------------------------------------------------------
162
+
163
+ class Engine {
164
+ constructor(base, { pinned = false, apiKey = null, fetchTimeoutMs = DEFAULT_FETCH_TIMEOUT_MS } = {}) {
165
+ this.base = base // http://host:port (no trailing /v1)
166
+ this.pinned = pinned
167
+ this.apiKey = apiKey || null
168
+ this.fetchTimeoutMs = fetchTimeoutMs
169
+ this.models = new Map() // modelId -> { reasoning, toolCall }
170
+ this.modelId = null // primary model id
171
+ this.context = null
172
+ this.waiting = null // queue depth, last known (number | null)
173
+ this.running = null // active requests / connections (number | null)
174
+ this.available = false
175
+ this.seen = false // has at least one known model id
176
+ this.capsLoaded = false // /v1/models capabilities fetched for current models
177
+ this.wsManaged = false // true when sparkDash snapshots report this engine
178
+ this._discovering = null
179
+ }
180
+
181
+ _headers() {
182
+ return this.apiKey ? { authorization: `Bearer ${this.apiKey}` } : undefined
183
+ }
184
+
185
+ hasModel(id) {
186
+ return this.models.has(id)
187
+ }
188
+
189
+ modelIds() {
190
+ return [...this.models.keys()]
191
+ }
192
+
193
+ modelMeta(id) {
194
+ return this.models.get(id) ?? { reasoning: false, toolCall: false }
195
+ }
196
+
197
+ // Apply model list observed in a sparkDash snapshot while preserving any
198
+ // capabilities previously fetched from /v1/models. Returns true when a new
199
+ // model appeared and /v1/models should be probed for capabilities.
200
+ syncModelsFromSnapshot(ids) {
201
+ const clean = []
202
+ for (const id of ids) {
203
+ if (typeof id === "string" && id.trim() && !clean.includes(id.trim())) {
204
+ clean.push(id.trim())
205
+ }
206
+ }
207
+ if (!clean.length) return !this.seen
208
+
209
+ let changed = clean.length !== this.models.size
210
+ const next = new Map()
211
+ for (const id of clean) {
212
+ const existing = this.models.get(id)
213
+ if (!existing) changed = true
214
+ next.set(id, existing ?? { reasoning: false, toolCall: false })
215
+ }
216
+ this.models = next
217
+ this.modelId = clean[0]
218
+ this.seen = true
219
+ if (changed) this.capsLoaded = false
220
+ return changed || !this.capsLoaded
221
+ }
222
+
223
+ async discover() {
224
+ if (this._discovering) return this._discovering
225
+ this._discovering = this._discoverImpl().finally(() => {
226
+ this._discovering = null
227
+ })
228
+ return this._discovering
229
+ }
230
+
231
+ async _discoverImpl() {
232
+ // Any OpenAI-compatible engine with a /v1/models list will do;
233
+ // TensorFold answers owned_by on it and contextLength on /health.
234
+ let list = null
235
+ try {
236
+ list = await fetchJson(`${this.base}/v1/models`, {
237
+ timeoutMs: this.fetchTimeoutMs,
238
+ headers: this._headers(),
239
+ })
240
+ } catch {
241
+ return false
242
+ }
243
+ const entries = Array.isArray(list?.data) ? list.data : []
244
+ const next = new Map()
245
+ for (const item of entries) {
246
+ const id = typeof item?.id === "string" ? item.id.trim() : ""
247
+ if (!id) continue
248
+ const caps = item?.capabilities
249
+ const reasoning = !!(caps?.reasoning)
250
+ const toolCall = caps?.tool_call !== undefined
251
+ ? !!caps.tool_call
252
+ : !!(caps?.tools)
253
+ next.set(id, { reasoning, toolCall })
254
+ }
255
+ if (!next.size) {
256
+ return false
257
+ }
258
+ this.models = next
259
+ this.modelId = next.keys().next().value
260
+ this.seen = true
261
+ this.capsLoaded = true
262
+ this.available = true
263
+ try {
264
+ const h = await fetchJson(`${this.base}/health`, {
265
+ timeoutMs: this.fetchTimeoutMs,
266
+ headers: this._headers(),
267
+ })
268
+ if (typeof h?.contextLength === "number" && h.contextLength > 0) {
269
+ this.context = h.contextLength
270
+ }
271
+ } catch { /* context stays unknown; magpie uses its default */ }
272
+ return true
273
+ }
274
+
275
+ async readHealth() {
276
+ try {
277
+ const r = await fetch(`${this.base}/health`, {
278
+ signal: AbortSignal.timeout(this.fetchTimeoutMs),
279
+ ...(this._headers() ? { headers: this._headers() } : {}),
280
+ })
281
+ if (r.ok) {
282
+ let h = null
283
+ try { h = await r.json() } catch { /* non-JSON /health (e.g. plain "ok") */ }
284
+ if (h && typeof h === "object") {
285
+ const waiting = h?.live?.waiting
286
+ if (typeof waiting === "number" && Number.isFinite(waiting) && waiting >= 0) {
287
+ this.waiting = Math.round(waiting)
288
+ } else {
289
+ this.waiting = null
290
+ }
291
+ const conns = h?.live?.connections
292
+ if (typeof conns === "number" && Number.isFinite(conns) && conns >= 0) {
293
+ this.running = Math.round(conns)
294
+ }
295
+ if (typeof h?.contextLength === "number" && h.contextLength > 0) {
296
+ this.context = h.contextLength
297
+ }
298
+ } else {
299
+ this.waiting = null
300
+ }
301
+ return true
302
+ }
303
+ // Some OpenAI-compatible servers (e.g. Ollama / custom proxies) do not
304
+ // expose /health and return 404/405; verify reachability via /v1/models.
305
+ if (r.status === 404 || r.status === 405) {
306
+ this.waiting = null
307
+ return await this.discover()
308
+ }
309
+ } catch { /* engine away */ }
310
+ this.waiting = null
311
+ this.running = null
312
+ return false
313
+ }
314
+ }
315
+
316
+ // ---- one monitor: the ws into sparkDash, the engines it names -----------
317
+
318
+ function startMonitor({
319
+ dash,
320
+ dashToken,
321
+ provider,
322
+ input,
323
+ engines: pinned,
324
+ defaultApiKey,
325
+ isLoadEnabled,
326
+ timings,
327
+ }) {
328
+ const {
329
+ pollMs,
330
+ retryMs,
331
+ maxRetryMs,
332
+ fetchTimeoutMs,
333
+ discoverWaitMs,
334
+ heartbeatMs,
335
+ staleWsMs,
336
+ refreshMs,
337
+ } = timings
338
+
339
+ const dashParsed = dash ? parseDashInput(dash) : null
340
+ const engines = new Map() // base -> Engine
341
+ const reportedModels = new Set()
342
+ let lastReport = ""
343
+ let lastReportAt = 0
344
+ let ws = null
345
+ let wsUp = false
346
+ let wsOpenedAt = 0
347
+ let lastSnapshotAt = 0
348
+ let wsDownLogged = false
349
+ let currentRetryMs = retryMs
350
+ let wsTimer = null
351
+ let polling = false
352
+ let stopped = false
353
+ let gotInitial = false
354
+ let notifyReady = () => {}
355
+
356
+ // Resolved on the first snapshot (or first poll when pinned-only), or after
357
+ // discoverWaitMs so callers listing models never hang forever.
358
+ const firstReady = new Promise((r) => { notifyReady = r })
359
+ const markReady = () => {
360
+ if (gotInitial) return
361
+ gotInitial = true
362
+ notifyReady()
363
+ }
364
+ const readyTimer = setTimeout(markReady, discoverWaitMs)
365
+ readyTimer.unref?.()
366
+
367
+ for (const item of pinned) {
368
+ engines.set(
369
+ item.base,
370
+ new Engine(item.base, {
371
+ pinned: true,
372
+ apiKey: item.apiKey ?? defaultApiKey,
373
+ fetchTimeoutMs,
374
+ }),
375
+ )
376
+ }
377
+ const fixed = pinned.length > 0
378
+
379
+ const retract = (reason = "no source reachable; load reports retracted") => {
380
+ if (reportedModels.size === 0 && lastReport === "") return
381
+ const loads = {}
382
+ for (const modelId of reportedModels) loads[modelId] = null
383
+ try {
384
+ input.magpie?.load?.(provider, loads)
385
+ reportedModels.clear()
386
+ lastReport = ""
387
+ lastReportAt = 0
388
+ log(reason)
389
+ } catch (err) {
390
+ log("load retract failed:", err?.message ?? err)
391
+ }
392
+ }
393
+
394
+ const report = () => {
395
+ if (!isLoadEnabled()) {
396
+ retract("load reporting disabled; load reports retracted")
397
+ return
398
+ }
399
+ const activeLoads = {}
400
+ for (const e of engines.values()) {
401
+ if (!e.seen || !e.available || typeof e.waiting !== "number") continue
402
+ const load = e.waiting > 0 ? 100 : 0
403
+ for (const modelId of e.modelIds()) {
404
+ // Multiple engines serving the same model: free if at least one has an empty queue.
405
+ activeLoads[modelId] = activeLoads[modelId] === undefined
406
+ ? load
407
+ : Math.min(activeLoads[modelId], load)
408
+ }
409
+ }
410
+ const activeKeys = Object.keys(activeLoads).sort()
411
+ if (activeKeys.length === 0) {
412
+ retract()
413
+ return
414
+ }
415
+
416
+ const payload = {}
417
+ for (const k of activeKeys) payload[k] = activeLoads[k]
418
+ // Retract any model whose engine went away while other models stayed up.
419
+ for (const prev of reportedModels) {
420
+ if (payload[prev] === undefined) payload[prev] = null
421
+ }
422
+
423
+ const canonicalActive = {}
424
+ for (const k of activeKeys) canonicalActive[k] = activeLoads[k]
425
+ const key = JSON.stringify(canonicalActive)
426
+ const now = Date.now()
427
+ const changed = key !== lastReport
428
+ const stale = now - lastReportAt >= heartbeatMs
429
+ if (!changed && !stale) return
430
+
431
+ try {
432
+ input.magpie?.load?.(provider, payload)
433
+ lastReport = key
434
+ lastReportAt = now
435
+ reportedModels.clear()
436
+ for (const k of activeKeys) reportedModels.add(k)
437
+ if (changed) log("load report:", key)
438
+ } catch (err) {
439
+ log("load report failed:", err?.message ?? err)
440
+ }
441
+ }
442
+
443
+ // Resolve the engine's reachable HTTP host from a sparkDash unit snapshot:
444
+ // local units run on the sparkDash host itself; remote units expose lanIp.
445
+ const unitEngineBase = (spark, port) => {
446
+ const proto = dashParsed?.protocol ?? "http:"
447
+ const rawHost = !spark?.isLocal && typeof spark?.lanIp === "string" && spark.lanIp.trim()
448
+ ? spark.lanIp.trim()
449
+ : dashParsed?.hostname
450
+ const hostPort = formatHostPort(rawHost, port)
451
+ return hostPort ? `${proto}//${hostPort}` : null
452
+ }
453
+
454
+ // sparkDash /ws: { type: "snapshot", sparks: [ ... ] }
455
+ const readSnapshot = (data) => {
456
+ if (data?.type !== "snapshot" || !Array.isArray(data.sparks)) return
457
+ lastSnapshotAt = Date.now()
458
+
459
+ // Aggregate per base URL first so a worker unit reporting available: false
460
+ // on a shared port cannot clobber the head unit's available: true reading.
461
+ const observed = new Map() // base -> { available, waiting, running, modelIds, context, unitId }
462
+ for (const s of data.sparks) {
463
+ if (!s?.online) continue
464
+ const ports = new Set([...(s.llmPorts ?? []), ...(s.llmApiKeyPorts ?? [])])
465
+ const metrics = Array.isArray(s.metrics?.llm) ? s.metrics.llm : []
466
+ for (const port of ports) {
467
+ const m = metrics.find((x) => x?.port === port)
468
+ if (!m) continue
469
+ const base = unitEngineBase(s, port)
470
+ if (!base) continue
471
+ const mIds = []
472
+ if (typeof m.modelId === "string" && m.modelId.trim()) mIds.push(m.modelId.trim())
473
+ if (Array.isArray(m.models)) {
474
+ for (const id of m.models) {
475
+ if (typeof id === "string" && id.trim() && !mIds.includes(id.trim())) {
476
+ mIds.push(id.trim())
477
+ }
478
+ }
479
+ }
480
+ const waiting = typeof m.requestsWaiting === "number" && Number.isFinite(m.requestsWaiting)
481
+ ? m.requestsWaiting
482
+ : null
483
+ const running = typeof m.requestsRunning === "number" && Number.isFinite(m.requestsRunning)
484
+ ? m.requestsRunning
485
+ : (typeof m.slotsActive === "number" && Number.isFinite(m.slotsActive) ? m.slotsActive : null)
486
+ const context = typeof m.contextLength === "number" && m.contextLength > 0
487
+ ? m.contextLength
488
+ : null
489
+
490
+ const prev = observed.get(base)
491
+ if (!prev || (!prev.available && m.available)) {
492
+ observed.set(base, {
493
+ available: Boolean(m.available),
494
+ waiting,
495
+ running,
496
+ modelIds: mIds,
497
+ context,
498
+ unitId: s.id,
499
+ })
500
+ } else if (prev.available && m.available) {
501
+ // Both units claim available on the same base: keep conservative waiting
502
+ if (waiting !== null && (prev.waiting === null || waiting > prev.waiting)) {
503
+ prev.waiting = waiting
504
+ }
505
+ if (running !== null && (prev.running === null || running > prev.running)) {
506
+ prev.running = running
507
+ }
508
+ for (const id of mIds) {
509
+ if (!prev.modelIds.includes(id)) prev.modelIds.push(id)
510
+ }
511
+ if (context !== null && prev.context === null) prev.context = context
512
+ }
513
+ }
514
+ }
515
+
516
+ const discoverPromises = []
517
+ for (const [base, info] of observed) {
518
+ let e = engines.get(base)
519
+ if (!e) {
520
+ if (fixed) continue // engines pinned; ignore strays
521
+ e = new Engine(base, { apiKey: defaultApiKey, fetchTimeoutMs })
522
+ engines.set(base, e)
523
+ log(`discovered engine ${base} (unit ${info.unitId})`)
524
+ }
525
+ e.wsManaged = true
526
+ if (info.available) {
527
+ e.available = true
528
+ e.waiting = info.waiting
529
+ e.running = info.running
530
+ if (info.context !== null) e.context = info.context
531
+ const prevModelId = e.modelId
532
+ const needsDiscover = e.syncModelsFromSnapshot(info.modelIds)
533
+ if (e.modelId && e.modelId !== prevModelId) {
534
+ log(
535
+ prevModelId
536
+ ? `model switched on ${base}: ${prevModelId} -> ${e.modelId} (ctx ${e.context ?? "?"})`
537
+ : `model ${e.modelId} on ${base} (ctx ${e.context ?? "?"})`,
538
+ )
539
+ }
540
+ if (needsDiscover) {
541
+ // Fetch /v1/models in the background to pick up reasoning / tool_call
542
+ // capabilities (and model id if the first snapshot omitted it).
543
+ discoverPromises.push(
544
+ e.discover().then((ok) => {
545
+ if (ok && !stopped) report()
546
+ }).catch(() => {}),
547
+ )
548
+ }
549
+ } else {
550
+ e.available = false
551
+ e.waiting = null
552
+ e.running = null
553
+ }
554
+ }
555
+
556
+ // Any previously WS-discovered engine absent from the snapshot (e.g. unit
557
+ // went offline or port removed) must be marked unavailable.
558
+ for (const [base, e] of engines) {
559
+ if (observed.has(base)) continue
560
+ if (!e.pinned || e.wsManaged) {
561
+ e.available = false
562
+ e.waiting = null
563
+ e.running = null
564
+ }
565
+ }
566
+
567
+ markReady()
568
+ report()
569
+ return discoverPromises
570
+ }
571
+
572
+ const wsUrl = () => {
573
+ const base = `${dash.replace(/^http/i, "ws")}/ws`
574
+ return dashToken ? `${base}?token=${encodeURIComponent(dashToken)}` : base
575
+ }
576
+
577
+ const scheduleReconnect = () => {
578
+ if (stopped) return
579
+ clearTimeout(wsTimer)
580
+ const delay = currentRetryMs
581
+ currentRetryMs = Math.min(currentRetryMs * 2, maxRetryMs)
582
+ wsTimer = setTimeout(connect, delay)
583
+ wsTimer.unref?.()
584
+ }
585
+
586
+ const connect = () => {
587
+ if (stopped || !dash) return
588
+ try {
589
+ ws = new WebSocket(wsUrl())
590
+ } catch {
591
+ wsUp = false
592
+ if (!wsDownLogged) {
593
+ wsDownLogged = true
594
+ log("sparkDash websocket down; polling engines directly")
595
+ }
596
+ scheduleReconnect()
597
+ return
598
+ }
599
+ const socket = ws
600
+ socket.onopen = () => {
601
+ if (socket !== ws || stopped) return
602
+ wsUp = true
603
+ wsOpenedAt = Date.now()
604
+ wsDownLogged = false
605
+ currentRetryMs = retryMs
606
+ log(`sparkDash websocket up: ${dash}/ws`)
607
+ }
608
+ socket.onmessage = (ev) => {
609
+ if (socket !== ws || stopped) return
610
+ try {
611
+ readSnapshot(JSON.parse(typeof ev.data === "string" ? ev.data : String(ev.data)))
612
+ } catch { /* partial or non-JSON frame */ }
613
+ }
614
+ socket.onclose = () => {
615
+ if (socket !== ws) return
616
+ wsUp = false
617
+ if (stopped) return
618
+ if (!wsDownLogged) {
619
+ wsDownLogged = true
620
+ log("sparkDash websocket down; polling engines directly")
621
+ }
622
+ scheduleReconnect()
623
+ }
624
+ socket.onerror = () => {
625
+ try { socket.close() } catch { /* already */ }
626
+ }
627
+ }
628
+
629
+ // Fallback & pinned-engine poll:
630
+ // - Detects stale/half-open WS connections when snapshots stop arriving.
631
+ // - Polls all engines when WS is down/absent, or pinned engines not managed by WS.
632
+ const poll = async () => {
633
+ if (stopped || polling) return
634
+ polling = true
635
+ try {
636
+ const now = Date.now()
637
+ if (wsUp && dash) {
638
+ const refAt = lastSnapshotAt || wsOpenedAt
639
+ if (refAt > 0 && now - refAt > staleWsMs) {
640
+ log("sparkDash websocket stale; reconnecting and falling back to /health")
641
+ wsUp = false
642
+ wsDownLogged = true
643
+ try { ws?.close() } catch { /* already */ }
644
+ }
645
+ }
646
+
647
+ const targets = []
648
+ for (const e of engines.values()) {
649
+ if (!wsUp || (e.pinned && !e.wsManaged)) {
650
+ targets.push(e)
651
+ }
652
+ }
653
+
654
+ if (targets.length > 0) {
655
+ await Promise.allSettled(
656
+ targets.map(async (e) => {
657
+ if (!e.seen || !e.capsLoaded) await e.discover()
658
+ if (e.seen) {
659
+ e.available = await e.readHealth()
660
+ } else {
661
+ e.available = false
662
+ e.waiting = null
663
+ e.running = null
664
+ }
665
+ }),
666
+ )
667
+ }
668
+
669
+ if (!dash || fixed) markReady()
670
+ report()
671
+ } finally {
672
+ polling = false
673
+ }
674
+ }
675
+
676
+ // An engine may come back with another checkpoint: re-read its /v1/models
677
+ const refresh = async () => {
678
+ if (stopped) return
679
+ const targets = [...engines.values()].filter((e) => e.available)
680
+ await Promise.allSettled(targets.map((e) => e.discover()))
681
+ if (!stopped) report()
682
+ }
683
+
684
+ if (dash) connect()
685
+ // Immediately discover/poll when running without sparkDash or with pinned engines
686
+ // so provider.models() doesn't wait for the first interval tick.
687
+ if (!dash || fixed) void poll()
688
+
689
+ const pollTimer = setInterval(() => { void poll() }, pollMs)
690
+ const refreshTimer = setInterval(() => { void refresh() }, refreshMs)
691
+ pollTimer.unref?.()
692
+ refreshTimer.unref?.()
693
+
694
+ if (dash) {
695
+ log(`watching ${dash}/ws${fixed ? ` (${pinned.length} pinned engine${pinned.length > 1 ? "s" : ""})` : ""}`)
696
+ } else {
697
+ log(`polling ${pinned.length} pinned engine${pinned.length > 1 ? "s" : ""} directly`)
698
+ }
699
+
700
+ return {
701
+ dash,
702
+ engines,
703
+ ready: () => firstReady,
704
+ report,
705
+ stop() {
706
+ stopped = true
707
+ clearTimeout(readyTimer)
708
+ clearTimeout(wsTimer)
709
+ clearInterval(pollTimer)
710
+ clearInterval(refreshTimer)
711
+ try { ws?.close() } catch { /* already */ }
712
+ ws = null
713
+ wsUp = false
714
+ markReady()
715
+ retract("monitor stopped; load reports retracted")
716
+ },
717
+ }
718
+ }
719
+
720
+ // ---- the plugin ---------------------------------------------------------
721
+
722
+ export const SparkdashPlugin = async (input, options) => {
723
+ const opts = options ?? {}
724
+ const PROVIDER = typeof opts.provider === "string" && opts.provider.trim()
725
+ ? opts.provider.trim()
726
+ : "sparkdash"
727
+
728
+ const defaultApiKey = typeof opts.apiKey === "string" && opts.apiKey.trim()
729
+ ? opts.apiKey.trim()
730
+ : null
731
+ const optsDashParsed = parseDashInput(opts.dash)
732
+ const optsDashToken = (typeof opts.token === "string" && opts.token.trim()
733
+ ? opts.token.trim()
734
+ : null) ?? optsDashParsed?.token ?? null
735
+
736
+ const timings = {
737
+ pollMs: positiveMs(opts.pollMs, DEFAULT_POLL_MS),
738
+ retryMs: positiveMs(opts.retryMs, DEFAULT_RETRY_MS),
739
+ maxRetryMs: positiveMs(opts.maxRetryMs, DEFAULT_MAX_RETRY_MS),
740
+ fetchTimeoutMs: positiveMs(opts.fetchTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS),
741
+ discoverWaitMs: positiveMs(opts.discoverWaitMs, DEFAULT_DISCOVER_WAIT_MS),
742
+ heartbeatMs: positiveMs(opts.heartbeatMs, DEFAULT_HEARTBEAT_MS),
743
+ staleWsMs: positiveMs(opts.staleWsMs, DEFAULT_STALE_WS_MS),
744
+ refreshMs: positiveMs(opts.refreshMs, DEFAULT_REFRESH_MS),
745
+ }
746
+
747
+ // Engines pinned in options: {"engines": [{"url": ..., "apiKey": ...} | "http://..."]}
748
+ const pinnedEngines = []
749
+ const seenPinned = new Set()
750
+ for (const e of Array.isArray(opts.engines) ? opts.engines : []) {
751
+ const url = typeof e === "string" ? e : e?.url
752
+ const base = normalizeEngineBase(url)
753
+ if (!base || seenPinned.has(base)) continue
754
+ seenPinned.add(base)
755
+ const apiKey = typeof e === "object" && typeof e?.apiKey === "string" && e.apiKey.trim()
756
+ ? e.apiKey.trim()
757
+ : null
758
+ pinnedEngines.push({ base, apiKey })
759
+ }
760
+ if (pinnedEngines.length) {
761
+ log("engines pinned in options:", pinnedEngines.map((e) => e.base).join(", "))
762
+ }
763
+
764
+ // The GUI switch (auth.options): evaluated live so toggling it takes effect immediately.
765
+ const isLoadEnabled = () => input.magpie?.options?.(PROVIDER)?.report_load !== false
766
+
767
+ // One monitor per dash address (or "__pinned__" for pinned-only mode) so
768
+ // multiple signed-in sparkDash accounts don't stop/recreate each other.
769
+ const monitors = new Map()
770
+ let rrCursor = 0
771
+
772
+ const ensureMonitor = (auth) => {
773
+ const authDashParsed = parseDashInput(auth?.metadata?.dash)
774
+ const dash = optsDashParsed?.url ?? authDashParsed?.url ?? null
775
+ const dashToken = optsDashToken ??
776
+ (typeof auth?.metadata?.token === "string" && auth.metadata.token.trim()
777
+ ? auth.metadata.token.trim()
778
+ : null) ??
779
+ authDashParsed?.token ??
780
+ null
781
+
782
+ if (!dash && pinnedEngines.length === 0) return null
783
+ const key = dash ?? "__pinned__"
784
+ const existing = monitors.get(key)
785
+ if (existing) {
786
+ existing.report()
787
+ return existing
788
+ }
789
+ const monitor = startMonitor({
790
+ dash,
791
+ dashToken,
792
+ provider: PROVIDER,
793
+ input,
794
+ engines: pinnedEngines,
795
+ defaultApiKey,
796
+ isLoadEnabled,
797
+ timings,
798
+ })
799
+ monitors.set(key, monitor)
800
+ return monitor
801
+ }
802
+
803
+ const enginesOf = (monitor) => {
804
+ if (monitor) return [...monitor.engines.values()]
805
+ const out = []
806
+ for (const m of monitors.values()) out.push(...m.engines.values())
807
+ return out
808
+ }
809
+
810
+ const modelEntry = (e, modelId) => {
811
+ const meta = e.modelMeta(modelId)
812
+ return {
813
+ name: `${modelId} (local · sparkDash)`,
814
+ limit: { context: e.context ?? 131_072, output: 32_000 },
815
+ reasoning: meta.reasoning,
816
+ tool_call: meta.toolCall,
817
+ cost: { input: 0, output: 0, cache_read: 0 }, // own hardware
818
+ }
819
+ }
820
+
821
+ return {
822
+ auth: {
823
+ provider: PROVIDER,
824
+ ...(ICON ? { icon: ICON } : {}),
825
+ // One request at a time per engine is the engine's own admission;
826
+ // magpie's concurrency here only spaces agents' asks before that.
827
+ maxConcurrency: 4,
828
+ // magpie's own switches, as the provider editor's Plugin options
829
+ // (OpenCode never reads them)
830
+ options: [
831
+ {
832
+ key: "report_load",
833
+ label: "Report queue depth as load",
834
+ description: "When on, each engine's waiting-request count is reported to magpie as the model's load, so Busy models last sends requests elsewhere while the engine is queueing. Off: the plugin is a plain provider and magpie always routes to it as listed.",
835
+ labels: {
836
+ zh: "回报队列深度为负载",
837
+ "zh-TW": "回報佇列深度為負載",
838
+ ja: "キューの深さを負荷として報告",
839
+ de: "Warteschlange als Last melden",
840
+ },
841
+ descriptions: {
842
+ zh: "开启后,每台引擎的等待请求数会作为模型负载回报给 magpie,引擎排队时「忙碌模型靠后」会把请求发往别处。关闭后本插件只是普通供应商,magpie 始终按列表路由。",
843
+ "zh-TW": "開啟後,每台引擎的等待請求數會作為模型負載回報給 magpie,引擎排隊時「忙碌模型靠後」會把請求發往別處。關閉後本外掛只是普通供應商,magpie 始終按列表路由。",
844
+ ja: "オンにすると、各エンジンの待ちリクエスト数がモデルの負荷として magpie に報告され、エンジンがキューイングしている間「Busy models last」が他の候補へ振り分けます。オフでは普通のプロバイダーとして動作します。",
845
+ de: "Ist dies an, wird die Zahl wartender Anfragen jeder Engine als Last des Modells an magpie gemeldet, sodass „Busy models last“ Anfragen bei Warteschlangen umleitet. Aus: das Plugin ist ein gewöhnlicher Anbieter.",
846
+ },
847
+ default: true,
848
+ },
849
+ ],
850
+ methods: [
851
+ {
852
+ type: "api",
853
+ keyless: true, // no key asked: the prompts carry the address
854
+ label: "sparkDash dashboard",
855
+ prompts: [
856
+ {
857
+ type: "text",
858
+ key: "dash",
859
+ message: "Where is your sparkDash?",
860
+ placeholder: "http://your-sparkdash:5555",
861
+ validate: (v) => {
862
+ if (!parseDashInput(v)) return "That is not an http(s) address"
863
+ return undefined
864
+ },
865
+ },
866
+ ],
867
+ async authorize(inputs) {
868
+ const parsed = parseDashInput(inputs?.dash)
869
+ if (!parsed) return { type: "failed", error: "That is not an http(s) address" }
870
+ const token = parsed.token ?? optsDashToken
871
+ let health = null
872
+ try {
873
+ health = await fetchJson(`${parsed.url}/api/health`, {
874
+ timeoutMs: timings.fetchTimeoutMs,
875
+ headers: token ? { authorization: `Bearer ${token}` } : undefined,
876
+ })
877
+ } catch (e) {
878
+ return {
879
+ type: "failed",
880
+ error: `sparkDash did not answer at ${parsed.url}: ${e?.message ?? e}`,
881
+ }
882
+ }
883
+ if (!health?.ok) {
884
+ return { type: "failed", error: `${parsed.url} answered, but not like sparkDash` }
885
+ }
886
+ if (health.authMode === "bearer" && !token) {
887
+ return {
888
+ type: "failed",
889
+ error: `sparkDash at ${parsed.url} requires a token (SPARKDASH_TOKEN); append ?token=... to the address or set "token" in plugin options`,
890
+ }
891
+ }
892
+ if (health.authMode === "required-missing") {
893
+ return {
894
+ type: "failed",
895
+ error:
896
+ `sparkDash at ${parsed.url} is bound to a non-loopback address with no SPARKDASH_TOKEN set and refuses every request. ` +
897
+ `Set SPARKDASH_TOKEN on the dash, or bind it to 127.0.0.1, then sign in again`,
898
+ }
899
+ }
900
+ log(`sign-in checked: ${parsed.url} (sparkDash v${health.version ?? "?"})`)
901
+ return {
902
+ type: "success",
903
+ key: "sparkdash-local",
904
+ accountId: parsed.host,
905
+ metadata: {
906
+ dash: parsed.url,
907
+ email: parsed.host,
908
+ ...(token ? { token } : {}),
909
+ },
910
+ }
911
+ },
912
+ },
913
+ ],
914
+ async loader(getAuth) {
915
+ const auth = await getAuth().catch(() => null)
916
+ const m = ensureMonitor(auth)
917
+ if (!m) return {}
918
+ return {
919
+ baseURL: enginesBase(m),
920
+ apiKey: defaultApiKey ?? PLACEHOLDER_API_KEY,
921
+ async fetch(req, init) {
922
+ // Route to the least busy available engine serving the requested model.
923
+ const requestedModel = await extractRequestedModel(req, init)
924
+ const target = pickEngine(m, requestedModel)
925
+ if (target) {
926
+ const rawUrl = req instanceof Request ? req.url : String(req)
927
+ const url = new URL(rawUrl)
928
+ const targetUrl = `${target.base}${url.pathname}${url.search}`
929
+ const headers = mergeHeaders(req, init, target.apiKey ?? defaultApiKey)
930
+ if (req instanceof Request) {
931
+ const forwarded = new Request(targetUrl, req)
932
+ return fetch(forwarded, { ...init, headers })
933
+ }
934
+ return fetch(targetUrl, { ...init, headers })
935
+ }
936
+ return fetch(req, init)
937
+ },
938
+ }
939
+ },
940
+ },
941
+
942
+ config: async (cfg) => {
943
+ if (optsDashParsed || pinnedEngines.length > 0) {
944
+ ensureMonitor(null)
945
+ }
946
+ cfg.provider ??= {}
947
+ cfg.provider[PROVIDER] ??= {}
948
+ const p = cfg.provider[PROVIDER]
949
+ p.name ??= "sparkDash"
950
+ p.npm ??= "@ai-sdk/openai-compatible"
951
+ p.api ??= enginesBase(null)
952
+ p.models ??= {}
953
+ for (const e of enginesOf(null)) {
954
+ if (!e.seen) continue
955
+ for (const id of e.modelIds()) {
956
+ p.models[id] ??= modelEntry(e, id)
957
+ }
958
+ }
959
+ },
960
+
961
+ // Per-account model list; also where a restarted engine's new model shows up.
962
+ provider: {
963
+ id: PROVIDER,
964
+ async models(provider, { auth } = {}) {
965
+ const m = ensureMonitor(auth)
966
+ if (m) {
967
+ // Wait briefly for the first snapshot / initial pinned poll.
968
+ await m.ready()
969
+ }
970
+ const out = {}
971
+ for (const e of m ? m.engines.values() : []) {
972
+ if (!e.seen || !e.available) continue
973
+ for (const id of e.modelIds()) {
974
+ out[id] = { ...modelEntry(e, id), id }
975
+ }
976
+ }
977
+ return Object.keys(out).length ? out : provider.models
978
+ },
979
+ },
980
+
981
+ dispose() {
982
+ for (const m of monitors.values()) m.stop()
983
+ monitors.clear()
984
+ },
985
+ }
986
+
987
+ // ---- helpers used by the hooks above ----------------------------------
988
+
989
+ function mergeHeaders(req, init, apiKey) {
990
+ const h = new Headers(req instanceof Request ? req.headers : undefined)
991
+ if (init?.headers) {
992
+ const overrides = new Headers(init.headers)
993
+ for (const [k, v] of overrides.entries()) h.set(k, v)
994
+ }
995
+ if (apiKey) {
996
+ const existing = h.get("authorization")
997
+ if (!existing || existing === `Bearer ${PLACEHOLDER_API_KEY}`) {
998
+ h.set("authorization", `Bearer ${apiKey}`)
999
+ }
1000
+ }
1001
+ return h
1002
+ }
1003
+
1004
+ function enginesBase(monitor) {
1005
+ const list = enginesOf(monitor)
1006
+ for (const e of list) {
1007
+ if (e.available && e.seen) return `${e.base}/v1`
1008
+ }
1009
+ for (const e of list) return `${e.base}/v1`
1010
+ return "http://localhost:8888/v1"
1011
+ }
1012
+
1013
+ function pickEngine(monitor, requestedModel) {
1014
+ const candidates = []
1015
+ for (const e of enginesOf(monitor)) {
1016
+ if (!e.available || !e.seen) continue
1017
+ if (requestedModel && !e.hasModel(requestedModel)) continue
1018
+ candidates.push(e)
1019
+ }
1020
+ if (candidates.length === 0) return null
1021
+
1022
+ // Primary sort: fewest waiting requests; secondary: fewest running requests.
1023
+ let bestWaiting = Infinity
1024
+ let bestRunning = Infinity
1025
+ let tied = []
1026
+ for (const e of candidates) {
1027
+ const w = e.waiting ?? 0
1028
+ const r = e.running ?? 0
1029
+ if (w < bestWaiting || (w === bestWaiting && r < bestRunning)) {
1030
+ bestWaiting = w
1031
+ bestRunning = r
1032
+ tied = [e]
1033
+ } else if (w === bestWaiting && r === bestRunning) {
1034
+ tied.push(e)
1035
+ }
1036
+ }
1037
+ if (tied.length === 1) return tied[0]
1038
+ const chosen = tied[rrCursor % tied.length]
1039
+ rrCursor = (rrCursor + 1) % 1_000_000
1040
+ return chosen
1041
+ }
1042
+ }
1043
+
1044
+ export default { id: "magpie-sparkdash", server: SparkdashPlugin }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "magpie-sparkdash",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "scripts": {
5
+ "test": "node test/smoke.mjs"
6
+ },
7
+ "description": "magpie plugin provider fed by sparkDash: give it your sparkDash URL and it serves every model your DGX Spark fleet's engines expose, with each engine's live queue depth reported as model load — so magpie's Busy-models-last routing detours to the cloud while an engine is queueing and comes back the moment it is free. Everything else is discovered from sparkDash itself (units, engine ports, models, context lengths); engine health polling is the fallback when the websocket is away.",
8
+ "type": "module",
9
+ "main": "./index.mjs",
10
+ "license": "MIT",
11
+ "keywords": [
12
+ "magpie",
13
+ "magpie-plugin",
14
+ "sparkdash",
15
+ "dgx-spark",
16
+ "tensorfold",
17
+ "local-llm",
18
+ "queue-depth"
19
+ ],
20
+ "files": [
21
+ "index.mjs",
22
+ "README.md",
23
+ "LICENSE",
24
+ "icon.png"
25
+ ],
26
+ "magpie": {
27
+ "name": "magpie-sparkdash",
28
+ "summary": {
29
+ "en": "Point it at sparkDash: your fleet's local engines become magpie providers, with live queue-depth load routing"
30
+ },
31
+ "icon": "data:image/png;base64,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"
32
+ }
33
+ }