@troed/oc-ls-stats 1.4.1 → 1.6.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 (4) hide show
  1. package/README.md +26 -2
  2. package/package.json +1 -1
  3. package/src/stats.ts +93 -0
  4. package/tui.tsx +125 -22
package/README.md CHANGED
@@ -6,7 +6,7 @@ There are many plugins to show tokens per second, but the reason for this one is
6
6
 
7
7
  Another motivation was to display the data of interest, but in a non-intrusive way with no UI elements jumping around. This plugin thus only shows a single numeric value, tokens per second, with an indicator as to whether the model is currently doing prompt processing or inference (token generation).
8
8
 
9
- I'm using the llama-server /slots endpoint to get the needed data, which means if you connect opencode to another provider the plugin will just display "-" since it's not getting any data to display.
9
+ I'm using the llama-server /slots endpoint to get the needed data. Strata (a llama.cpp-derived server with its own HTTP layer) and Basalt (a Strata fork) are also supported: they expose live prefill/decode rates under /metrics, and the plugin detects them automatically. If you connect opencode to an unrelated provider the plugin will just display "-" since it's not getting any data to display.
10
10
 
11
11
  Note: As explained in further detail below the data that's displayed has to be deduced from llama-server's output. Sometimes the plugin might display PP for prompt processing while in reality the model is doing TG. If additional developments are made to the llama-server output data the plugin might be able to discern between them in a better way, but I think is as good as it gets for now.
12
12
 
@@ -63,9 +63,21 @@ If your llama-server provider is named differently, configure the endpoint expli
63
63
 
64
64
  A `baseURL`-style value ending in `/v1` is also accepted.
65
65
 
66
+ The plugin detects each server's type automatically by probing `GET /health`: a Strata server reports `"service": "strata"` and a Basalt server reports `"service": "basalt"`. You can bypass detection when needed with a `serverType` option:
67
+
68
+ ```json
69
+ {
70
+ "plugin": [
71
+ ["@troed/oc-ls-stats@latest", { "serverType": "basalt" }]
72
+ ]
73
+ }
74
+ ```
75
+
76
+ `serverType` accepts `"llama"`, `"strata"` or `"basalt"`; omit it (or set `"auto"`) for automatic detection.
77
+
66
78
  ### Slot Polling
67
79
 
68
- Every 500ms, the plugin polls `GET /slots?model=<model>` on each discovered server. The model parameter is required by the `/slots` endpoint. If the model cannot be discovered from the current route's session, the plugin skips polling.
80
+ Every 500ms, the plugin polls each discovered server, always carrying the current session's model as `?model=<model>`. For a llama.cpp server it calls `GET /slots?model=<model>`; for a Strata or Basalt server it calls `GET /health?model=<model>` (to identify the server) and `GET /metrics?model=<model>` (reading the `live` object). Plain llama.cpp, Strata and Basalt servers ignore the extra parameter; a routing layer that dispatches by model (e.g. one fronting several nodes) uses it to forward the call to the backend serving that model. If the model cannot be discovered from the current route's session, the plugin polls without it — direct servers still answer, while a model-dispatched router rejects the bare call and the plugin shows `n/a`.
69
81
 
70
82
  When a server returns an error (e.g. HTTP 502) or is unreachable, the plugin backs off with an exponentially increasing delay per server (1s, 2s, 4s, ...) capped at 10s, with a small random jitter to stagger multiple servers. Backoff resets as soon as the server responds successfully again.
71
83
 
@@ -106,6 +118,18 @@ During generation, the plugin calculates the instantaneous token generation rate
106
118
 
107
119
  Slot reuse is tracked via `generateSlotId` to detect when a new generation starts on a different slot.
108
120
 
121
+ ### Strata and Basalt Support
122
+
123
+ Strata is a llama.cpp-derived server with its own Python HTTP layer. Basalt is a fork of Strata with the same stats surface. Their `/slots` route is a minimal llama-server compatibility stub (`id`, `n_ctx`, `is_processing` only) with no `next_token`, `id_task`, or `n_prompt_tokens`, so the delta-based classification above cannot produce a rate against them.
124
+
125
+ Both instead report the live rates directly in `GET /metrics`, under `live`:
126
+
127
+ - `state` — `reading` (prompt processing), `generating`, `idle`, or `unloaded`; Basalt also reports `loading` and `asleep`
128
+ - `prefill_tok_s_mean` — prompt processing rate while `reading` (PP)
129
+ - `tok_s` — instantaneous decode rate while `generating` (TG)
130
+
131
+ The plugin detects them per server URL from `GET /health` (`service: "strata"` or `service: "basalt"`) and maps these fields straight onto the display, so PP/TG are shown without delta estimation. Detection is cached per URL, and servers of all kinds can be polled side by side. Like the `/slots` requests, the plugin sends no API key; if Strata or Basalt is configured to require one, it cannot read the stats.
132
+
109
133
  ## Limitations
110
134
 
111
135
  ### Progress Percentage
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@troed/oc-ls-stats",
4
- "version": "1.4.1",
4
+ "version": "1.6.0",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "tui.tsx",
package/src/stats.ts CHANGED
@@ -308,3 +308,96 @@ export function selectSessionUrls(
308
308
  }
309
309
  return []
310
310
  }
311
+
312
+ // --- Live-metrics adapter ---------------------------------------------------
313
+ // Strata is a llama.cpp-derived server whose HTTP layer is Python; Basalt is a
314
+ // fork of Strata. Both expose a minimal /slots compatibility stub, but
315
+ // /metrics.live carries the live rates directly: prefill_tok_s_mean while
316
+ // reading, tok_s while generating.
317
+
318
+ export type ServerType = "llama" | "strata" | "basalt"
319
+
320
+ /** Returns the explicit server type from the plugin option, or undefined for auto. */
321
+ export function serverTypeOverride(value: unknown): ServerType | undefined {
322
+ if (value === "llama" || value === "strata" || value === "basalt") return value
323
+ return undefined
324
+ }
325
+
326
+ /**
327
+ * Identify a server from its parsed /health body. Strata and Basalt both report
328
+ * their own `service`; anything else is treated as a plain llama.cpp server.
329
+ */
330
+ export function serverTypeFromHealth(health: unknown): ServerType {
331
+ if (!health || typeof health !== "object") return "llama"
332
+ const service = (health as Record<string, unknown>).service
333
+ if (service === "strata") return "strata"
334
+ if (service === "basalt") return "basalt"
335
+ return "llama"
336
+ }
337
+
338
+ function finiteOrZero(value: unknown): number {
339
+ return typeof value === "number" && Number.isFinite(value) ? value : 0
340
+ }
341
+
342
+ /**
343
+ * Map a Strata or Basalt `/metrics.live` object onto the shared tracker. Both
344
+ * report the rates themselves, so no delta classification is needed: `state`
345
+ * says which phase is active and `prefill_tok_s_mean` / `tok_s` carry the rate.
346
+ * Basalt adds `loading` and `asleep` states; any non-active state clears them.
347
+ */
348
+ export function mapLiveMetrics(live: unknown, tracker: TrackerState): void {
349
+ const l = live && typeof live === "object" ? (live as Record<string, unknown>) : {}
350
+ const state = typeof l.state === "string" ? l.state : ""
351
+
352
+ if (state === "reading") {
353
+ tracker.isPrefilling = true
354
+ tracker.isGenerating = false
355
+ tracker.prefillSlotId = 0
356
+ tracker.lastPrefillRate = finiteOrZero(l.prefill_tok_s_mean)
357
+ tracker.generateSlotId = null
358
+ tracker.generatePrevNd = 0
359
+ tracker.generateStartAt = 0
360
+ tracker.lastGeneratedTps = 0
361
+ } else if (state === "generating") {
362
+ tracker.isGenerating = true
363
+ tracker.isPrefilling = false
364
+ tracker.generateSlotId = 0
365
+ tracker.lastGeneratedTps = finiteOrZero(l.tok_s)
366
+ tracker.prefillSlotId = null
367
+ tracker.prefillCapturedTokens = null
368
+ tracker.prefillStartAt = 0
369
+ tracker.lastPrefillRate = 0
370
+ } else {
371
+ tracker.isPrefilling = false
372
+ tracker.isGenerating = false
373
+ tracker.prefillSlotId = null
374
+ tracker.prefillCapturedTokens = null
375
+ tracker.prefillStartAt = 0
376
+ tracker.lastPrefillRate = 0
377
+ tracker.generateSlotId = null
378
+ tracker.generatePrevNd = 0
379
+ tracker.generateStartAt = 0
380
+ tracker.lastGeneratedTps = 0
381
+ }
382
+ }
383
+
384
+ // --- Model-scoped stats URLs ------------------------------------------------
385
+ // Stats are requested with the session's model so a routing layer that
386
+ // dispatches by model (a LAN router in front of several nodes) can forward the
387
+ // call to the right backend. Plain llama.cpp / Strata / Basalt servers ignore
388
+ // the extra query parameter.
389
+
390
+ /** Build a stats URL, adding the model as `?model=` when one is known. */
391
+ export function statsUrl(baseUrl: string, path: string, model?: string): string {
392
+ return model ? `${baseUrl}${path}?model=${encodeURIComponent(model)}` : `${baseUrl}${path}`
393
+ }
394
+
395
+ /**
396
+ * Cache key for the detected server kind. One URL can front different backends
397
+ * per model (e.g. a router), so the model belongs in the key: the same conduct
398
+ * URL may be a Strata or Basalt node for one model and a llama.cpp node for
399
+ * another.
400
+ */
401
+ export function serverKindKey(baseUrl: string, model?: string): string {
402
+ return `${baseUrl}\u0000${model ?? ""}`
403
+ }
package/tui.tsx CHANGED
@@ -2,7 +2,18 @@
2
2
  import type { TextRenderable } from "@opentui/core"
3
3
  import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
4
4
  import { onCleanup, createSignal } from "solid-js"
5
- import { backoffDelayMs, processPoll, resolveServerUrls, selectSessionUrls } from "./src/stats.ts"
5
+ import {
6
+ backoffDelayMs,
7
+ processPoll,
8
+ resolveServerUrls,
9
+ selectSessionUrls,
10
+ serverTypeOverride,
11
+ serverTypeFromHealth,
12
+ mapLiveMetrics,
13
+ statsUrl,
14
+ serverKindKey,
15
+ type ServerType,
16
+ } from "./src/stats.ts"
6
17
 
7
18
  type StreamSample = {
8
19
  at: number
@@ -45,8 +56,7 @@ function estimateStreamTokens(delta: string) {
45
56
 
46
57
  async function fetchSlots(baseUrl: string, model?: string): Promise<unknown | null> {
47
58
  try {
48
- const url = model ? `${baseUrl}/slots?model=${encodeURIComponent(model)}` : `${baseUrl}/slots`
49
- const resp = await fetch(url)
59
+ const resp = await fetch(statsUrl(baseUrl, "/slots", model))
50
60
  if (!resp.ok) return null
51
61
  return await resp.json()
52
62
  } catch {
@@ -54,6 +64,33 @@ async function fetchSlots(baseUrl: string, model?: string): Promise<unknown | nu
54
64
  }
55
65
  }
56
66
 
67
+ async function fetchHealth(baseUrl: string, model?: string): Promise<unknown | null> {
68
+ try {
69
+ const resp = await fetch(statsUrl(baseUrl, "/health", model))
70
+ if (!resp.ok) return null
71
+ return await resp.json()
72
+ } catch {
73
+ return null
74
+ }
75
+ }
76
+
77
+ // Strata and Basalt report the live rates under /metrics.live
78
+ // (prefill_tok_s_mean while reading, tok_s while generating) rather than in
79
+ // the minimal /slots stub. The model is passed so a routing layer in front of
80
+ // the backend can forward the call; plain llama.cpp / Strata / Basalt servers
81
+ // ignore the parameter.
82
+ async function fetchLiveMetrics(baseUrl: string, model?: string): Promise<unknown | null> {
83
+ try {
84
+ const resp = await fetch(statsUrl(baseUrl, "/metrics", model))
85
+ if (!resp.ok) return null
86
+ const body = await resp.json()
87
+ if (body && typeof body === "object" && "live" in body) return (body as { live: unknown }).live
88
+ return null
89
+ } catch {
90
+ return null
91
+ }
92
+ }
93
+
57
94
  function formatPps(value: number) {
58
95
  if (!Number.isFinite(value) || value <= 0) return undefined
59
96
  return `${Math.round(value)}`
@@ -179,6 +216,34 @@ const tui: TuiPlugin = async (api, options) => {
179
216
  let llamaServerUrls: string[] = []
180
217
  let llamaServerModel: string | undefined
181
218
  const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
219
+ const serverKindByUrl = new Map<string, ServerType>()
220
+ const forcedServerType = serverTypeOverride((options as Record<string, unknown> | undefined)?.serverType)
221
+
222
+ const resolveServerKind = async (baseUrl: string, model?: string): Promise<ServerType> => {
223
+ if (forcedServerType) return forcedServerType
224
+ const key = serverKindKey(baseUrl, model)
225
+ const cached = serverKindByUrl.get(key)
226
+ if (cached) return cached
227
+ const health = await fetchHealth(baseUrl, model)
228
+ if (health != null) {
229
+ const kind = serverTypeFromHealth(health)
230
+ serverKindByUrl.set(key, kind)
231
+ return kind
232
+ }
233
+ return "llama"
234
+ }
235
+
236
+ const noteServerFailure = (baseUrl: string) => {
237
+ const failures = (backoffByUrl.get(baseUrl)?.failures ?? 0) + 1
238
+ const delay = backoffDelayMs(failures, BACKOFF_BASE_MS, BACKOFF_MAX_MS)
239
+ const jitter = Math.floor(Math.random() * (delay / 4))
240
+ backoffByUrl.set(baseUrl, {
241
+ failures,
242
+ nextRetryAt: Date.now() + Math.min(delay + jitter, BACKOFF_MAX_MS),
243
+ })
244
+ tracker.failure = "n/a"
245
+ bump()
246
+ }
182
247
 
183
248
  const pollMetrics = async () => {
184
249
  if (!llamaServerUrls.length) return
@@ -211,17 +276,22 @@ const tui: TuiPlugin = async (api, options) => {
211
276
  continue
212
277
  }
213
278
 
279
+ if ((await resolveServerKind(baseUrl, model)) !== "llama") {
280
+ const live = await fetchLiveMetrics(baseUrl, model)
281
+ if (live == null) {
282
+ noteServerFailure(baseUrl)
283
+ continue
284
+ }
285
+ backoffByUrl.delete(baseUrl)
286
+ tracker.failure = null
287
+ mapLiveMetrics(live, tracker)
288
+ bump()
289
+ continue
290
+ }
291
+
214
292
  const slots = await fetchSlots(baseUrl, model)
215
293
  if (slots == null) {
216
- const failures = (backoff?.failures ?? 0) + 1
217
- const delay = backoffDelayMs(failures, BACKOFF_BASE_MS, BACKOFF_MAX_MS)
218
- const jitter = Math.floor(Math.random() * (delay / 4))
219
- backoffByUrl.set(baseUrl, {
220
- failures,
221
- nextRetryAt: Date.now() + Math.min(delay + jitter, BACKOFF_MAX_MS),
222
- })
223
- tracker.failure = "n/a"
224
- bump()
294
+ noteServerFailure(baseUrl)
225
295
  continue
226
296
  }
227
297
 
@@ -235,7 +305,7 @@ const tui: TuiPlugin = async (api, options) => {
235
305
  tracker.failure = null
236
306
  bump()
237
307
 
238
- const result = processPoll(slotList, tracker)
308
+ processPoll(slotList, tracker)
239
309
  bump()
240
310
  }
241
311
  }
@@ -436,6 +506,34 @@ const v2Setup = async (context: any) => {
436
506
  let llamaServerUrls: string[] = []
437
507
  let providerList: unknown[] = []
438
508
  const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
509
+ const serverKindByUrl = new Map<string, ServerType>()
510
+ const forcedServerType = serverTypeOverride((context.options as Record<string, unknown> | undefined)?.serverType)
511
+
512
+ const resolveServerKind = async (baseUrl: string, model?: string): Promise<ServerType> => {
513
+ if (forcedServerType) return forcedServerType
514
+ const key = serverKindKey(baseUrl, model)
515
+ const cached = serverKindByUrl.get(key)
516
+ if (cached) return cached
517
+ const health = await fetchHealth(baseUrl, model)
518
+ if (health != null) {
519
+ const kind = serverTypeFromHealth(health)
520
+ serverKindByUrl.set(key, kind)
521
+ return kind
522
+ }
523
+ return "llama"
524
+ }
525
+
526
+ const noteServerFailure = (baseUrl: string) => {
527
+ const failures = (backoffByUrl.get(baseUrl)?.failures ?? 0) + 1
528
+ const delay = backoffDelayMs(failures, BACKOFF_BASE_MS, BACKOFF_MAX_MS)
529
+ const jitter = Math.floor(Math.random() * (delay / 4))
530
+ backoffByUrl.set(baseUrl, {
531
+ failures,
532
+ nextRetryAt: Date.now() + Math.min(delay + jitter, BACKOFF_MAX_MS),
533
+ })
534
+ tracker.failure = "n/a"
535
+ bump()
536
+ }
439
537
 
440
538
  const currentSessionID = (): string | undefined => {
441
539
  const route = context.ui.router.current?.()
@@ -473,17 +571,22 @@ const v2Setup = async (context: any) => {
473
571
  continue
474
572
  }
475
573
 
574
+ if ((await resolveServerKind(baseUrl, model)) !== "llama") {
575
+ const live = await fetchLiveMetrics(baseUrl, model)
576
+ if (live == null) {
577
+ noteServerFailure(baseUrl)
578
+ continue
579
+ }
580
+ backoffByUrl.delete(baseUrl)
581
+ tracker.failure = null
582
+ mapLiveMetrics(live, tracker)
583
+ bump()
584
+ continue
585
+ }
586
+
476
587
  const slots = await fetchSlots(baseUrl, model)
477
588
  if (slots == null) {
478
- const failures = (backoff?.failures ?? 0) + 1
479
- const delay = backoffDelayMs(failures, BACKOFF_BASE_MS, BACKOFF_MAX_MS)
480
- const jitter = Math.floor(Math.random() * (delay / 4))
481
- backoffByUrl.set(baseUrl, {
482
- failures,
483
- nextRetryAt: Date.now() + Math.min(delay + jitter, BACKOFF_MAX_MS),
484
- })
485
- tracker.failure = "n/a"
486
- bump()
589
+ noteServerFailure(baseUrl)
487
590
  continue
488
591
  }
489
592