@troed/oc-ls-stats 1.4.1 → 1.5.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 +84 -0
  4. package/tui.tsx +124 -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) is also supported: it exposes live prefill/decode rates under /metrics, and the plugin detects it 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"`. You can bypass detection when needed with a `serverType` option:
67
+
68
+ ```json
69
+ {
70
+ "plugin": [
71
+ ["@troed/oc-ls-stats@latest", { "serverType": "strata" }]
72
+ ]
73
+ }
74
+ ```
75
+
76
+ `serverType` accepts `"llama"` or `"strata"`; 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 server it calls `GET /health?model=<model>` (to identify the server) and `GET /metrics?model=<model>` (reading the `live` object). Plain llama.cpp and Strata 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 Support
122
+
123
+ Strata is a llama.cpp-derived server with its own Python HTTP layer. Its `/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 it.
124
+
125
+ Strata instead reports the live rates directly in `GET /metrics`, under `live`:
126
+
127
+ - `state` — `reading` (prompt processing), `generating`, `idle`, or `unloaded`
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 Strata per server URL from `GET /health` (`service: "strata"`) and maps these fields straight onto the display, so PP/TG are shown without delta estimation. Detection is cached per URL, and servers of both kinds can be polled side by side. Like the `/slots` requests, the plugin sends no API key; if Strata 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.5.0",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "tui.tsx",
package/src/stats.ts CHANGED
@@ -308,3 +308,87 @@ export function selectSessionUrls(
308
308
  }
309
309
  return []
310
310
  }
311
+
312
+ // --- Strata adapter ---------------------------------------------------------
313
+ // Strata is a llama.cpp-derived server whose HTTP layer is Python. Its /slots
314
+ // route is a minimal compatibility stub, but /metrics.live carries the live
315
+ // rates directly: prefill_tok_s_mean while reading, tok_s while generating.
316
+
317
+ export type ServerType = "llama" | "strata"
318
+
319
+ /** Returns the explicit server type from the plugin option, or undefined for auto. */
320
+ export function serverTypeOverride(value: unknown): ServerType | undefined {
321
+ if (value === "llama" || value === "strata") return value
322
+ return undefined
323
+ }
324
+
325
+ /** True when a parsed /health body identifies the server as Strata. */
326
+ export function isStrataHealth(health: unknown): boolean {
327
+ if (!health || typeof health !== "object") return false
328
+ return (health as Record<string, unknown>).service === "strata"
329
+ }
330
+
331
+ function finiteOrZero(value: unknown): number {
332
+ return typeof value === "number" && Number.isFinite(value) ? value : 0
333
+ }
334
+
335
+ /**
336
+ * Map a Strata `/metrics.live` object onto the shared tracker. Strata reports
337
+ * the rates itself, so no delta classification is needed: `state` says which
338
+ * phase is active and `prefill_tok_s_mean` / `tok_s` carry the rate.
339
+ */
340
+ export function mapStrataLive(live: unknown, tracker: TrackerState): void {
341
+ const l = live && typeof live === "object" ? (live as Record<string, unknown>) : {}
342
+ const state = typeof l.state === "string" ? l.state : ""
343
+
344
+ if (state === "reading") {
345
+ tracker.isPrefilling = true
346
+ tracker.isGenerating = false
347
+ tracker.prefillSlotId = 0
348
+ tracker.lastPrefillRate = finiteOrZero(l.prefill_tok_s_mean)
349
+ tracker.generateSlotId = null
350
+ tracker.generatePrevNd = 0
351
+ tracker.generateStartAt = 0
352
+ tracker.lastGeneratedTps = 0
353
+ } else if (state === "generating") {
354
+ tracker.isGenerating = true
355
+ tracker.isPrefilling = false
356
+ tracker.generateSlotId = 0
357
+ tracker.lastGeneratedTps = finiteOrZero(l.tok_s)
358
+ tracker.prefillSlotId = null
359
+ tracker.prefillCapturedTokens = null
360
+ tracker.prefillStartAt = 0
361
+ tracker.lastPrefillRate = 0
362
+ } else {
363
+ tracker.isPrefilling = false
364
+ tracker.isGenerating = false
365
+ tracker.prefillSlotId = null
366
+ tracker.prefillCapturedTokens = null
367
+ tracker.prefillStartAt = 0
368
+ tracker.lastPrefillRate = 0
369
+ tracker.generateSlotId = null
370
+ tracker.generatePrevNd = 0
371
+ tracker.generateStartAt = 0
372
+ tracker.lastGeneratedTps = 0
373
+ }
374
+ }
375
+
376
+ // --- Model-scoped stats URLs ------------------------------------------------
377
+ // Stats are requested with the session's model so a routing layer that
378
+ // dispatches by model (a LAN router in front of several nodes) can forward the
379
+ // call to the right backend. Plain llama.cpp / Strata servers ignore the extra
380
+ // query parameter.
381
+
382
+ /** Build a stats URL, adding the model as `?model=` when one is known. */
383
+ export function statsUrl(baseUrl: string, path: string, model?: string): string {
384
+ return model ? `${baseUrl}${path}?model=${encodeURIComponent(model)}` : `${baseUrl}${path}`
385
+ }
386
+
387
+ /**
388
+ * Cache key for the detected server kind. One URL can front different backends
389
+ * per model (e.g. a router), so the model belongs in the key: the same conduct
390
+ * URL may be a Strata node for one model and a llama.cpp node for another.
391
+ */
392
+ export function serverKindKey(baseUrl: string, model?: string): string {
393
+ return `${baseUrl}\u0000${model ?? ""}`
394
+ }
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
+ isStrataHealth,
12
+ mapStrataLive,
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,32 @@ 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 reports the live rates under /metrics.live (prefill_tok_s_mean while
78
+ // reading, tok_s while generating) rather than in the minimal /slots stub. The
79
+ // model is passed so a routing layer in front of the backend can forward the
80
+ // call; plain llama.cpp / Strata servers ignore the parameter.
81
+ async function fetchStrataLive(baseUrl: string, model?: string): Promise<unknown | null> {
82
+ try {
83
+ const resp = await fetch(statsUrl(baseUrl, "/metrics", model))
84
+ if (!resp.ok) return null
85
+ const body = await resp.json()
86
+ if (body && typeof body === "object" && "live" in body) return (body as { live: unknown }).live
87
+ return null
88
+ } catch {
89
+ return null
90
+ }
91
+ }
92
+
57
93
  function formatPps(value: number) {
58
94
  if (!Number.isFinite(value) || value <= 0) return undefined
59
95
  return `${Math.round(value)}`
@@ -179,6 +215,34 @@ const tui: TuiPlugin = async (api, options) => {
179
215
  let llamaServerUrls: string[] = []
180
216
  let llamaServerModel: string | undefined
181
217
  const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
218
+ const serverKindByUrl = new Map<string, ServerType>()
219
+ const forcedServerType = serverTypeOverride((options as Record<string, unknown> | undefined)?.serverType)
220
+
221
+ const resolveServerKind = async (baseUrl: string, model?: string): Promise<ServerType> => {
222
+ if (forcedServerType) return forcedServerType
223
+ const key = serverKindKey(baseUrl, model)
224
+ const cached = serverKindByUrl.get(key)
225
+ if (cached) return cached
226
+ const health = await fetchHealth(baseUrl, model)
227
+ if (health != null) {
228
+ const kind = isStrataHealth(health) ? "strata" : "llama"
229
+ serverKindByUrl.set(key, kind)
230
+ return kind
231
+ }
232
+ return "llama"
233
+ }
234
+
235
+ const noteServerFailure = (baseUrl: string) => {
236
+ const failures = (backoffByUrl.get(baseUrl)?.failures ?? 0) + 1
237
+ const delay = backoffDelayMs(failures, BACKOFF_BASE_MS, BACKOFF_MAX_MS)
238
+ const jitter = Math.floor(Math.random() * (delay / 4))
239
+ backoffByUrl.set(baseUrl, {
240
+ failures,
241
+ nextRetryAt: Date.now() + Math.min(delay + jitter, BACKOFF_MAX_MS),
242
+ })
243
+ tracker.failure = "n/a"
244
+ bump()
245
+ }
182
246
 
183
247
  const pollMetrics = async () => {
184
248
  if (!llamaServerUrls.length) return
@@ -211,17 +275,22 @@ const tui: TuiPlugin = async (api, options) => {
211
275
  continue
212
276
  }
213
277
 
278
+ if ((await resolveServerKind(baseUrl, model)) === "strata") {
279
+ const live = await fetchStrataLive(baseUrl, model)
280
+ if (live == null) {
281
+ noteServerFailure(baseUrl)
282
+ continue
283
+ }
284
+ backoffByUrl.delete(baseUrl)
285
+ tracker.failure = null
286
+ mapStrataLive(live, tracker)
287
+ bump()
288
+ continue
289
+ }
290
+
214
291
  const slots = await fetchSlots(baseUrl, model)
215
292
  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()
293
+ noteServerFailure(baseUrl)
225
294
  continue
226
295
  }
227
296
 
@@ -235,7 +304,7 @@ const tui: TuiPlugin = async (api, options) => {
235
304
  tracker.failure = null
236
305
  bump()
237
306
 
238
- const result = processPoll(slotList, tracker)
307
+ processPoll(slotList, tracker)
239
308
  bump()
240
309
  }
241
310
  }
@@ -436,6 +505,34 @@ const v2Setup = async (context: any) => {
436
505
  let llamaServerUrls: string[] = []
437
506
  let providerList: unknown[] = []
438
507
  const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
508
+ const serverKindByUrl = new Map<string, ServerType>()
509
+ const forcedServerType = serverTypeOverride((context.options as Record<string, unknown> | undefined)?.serverType)
510
+
511
+ const resolveServerKind = async (baseUrl: string, model?: string): Promise<ServerType> => {
512
+ if (forcedServerType) return forcedServerType
513
+ const key = serverKindKey(baseUrl, model)
514
+ const cached = serverKindByUrl.get(key)
515
+ if (cached) return cached
516
+ const health = await fetchHealth(baseUrl, model)
517
+ if (health != null) {
518
+ const kind = isStrataHealth(health) ? "strata" : "llama"
519
+ serverKindByUrl.set(key, kind)
520
+ return kind
521
+ }
522
+ return "llama"
523
+ }
524
+
525
+ const noteServerFailure = (baseUrl: string) => {
526
+ const failures = (backoffByUrl.get(baseUrl)?.failures ?? 0) + 1
527
+ const delay = backoffDelayMs(failures, BACKOFF_BASE_MS, BACKOFF_MAX_MS)
528
+ const jitter = Math.floor(Math.random() * (delay / 4))
529
+ backoffByUrl.set(baseUrl, {
530
+ failures,
531
+ nextRetryAt: Date.now() + Math.min(delay + jitter, BACKOFF_MAX_MS),
532
+ })
533
+ tracker.failure = "n/a"
534
+ bump()
535
+ }
439
536
 
440
537
  const currentSessionID = (): string | undefined => {
441
538
  const route = context.ui.router.current?.()
@@ -473,17 +570,22 @@ const v2Setup = async (context: any) => {
473
570
  continue
474
571
  }
475
572
 
573
+ if ((await resolveServerKind(baseUrl, model)) === "strata") {
574
+ const live = await fetchStrataLive(baseUrl, model)
575
+ if (live == null) {
576
+ noteServerFailure(baseUrl)
577
+ continue
578
+ }
579
+ backoffByUrl.delete(baseUrl)
580
+ tracker.failure = null
581
+ mapStrataLive(live, tracker)
582
+ bump()
583
+ continue
584
+ }
585
+
476
586
  const slots = await fetchSlots(baseUrl, model)
477
587
  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()
588
+ noteServerFailure(baseUrl)
487
589
  continue
488
590
  }
489
591