@troed/oc-ls-stats 1.5.0 → 1.6.1

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 +10 -10
  2. package/package.json +1 -1
  3. package/src/stats.ts +84 -17
  4. package/tui.tsx +32 -34
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. 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.
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,21 +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:
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
67
 
68
68
  ```json
69
69
  {
70
70
  "plugin": [
71
- ["@troed/oc-ls-stats@latest", { "serverType": "strata" }]
71
+ ["@troed/oc-ls-stats@latest", { "serverType": "basalt" }]
72
72
  ]
73
73
  }
74
74
  ```
75
75
 
76
- `serverType` accepts `"llama"` or `"strata"`; omit it (or set `"auto"`) for automatic detection.
76
+ `serverType` accepts `"llama"`, `"strata"` or `"basalt"`; omit it (or set `"auto"`) for automatic detection.
77
77
 
78
78
  ### Slot Polling
79
79
 
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`.
80
+ Every 500ms, the plugin polls each discovered server, always carrying the selected model as `?model=<model>` — the prompt's live selection, falling back to the session record. 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 no model is known yet, the plugin polls without it — direct servers still answer, while a model-dispatched router rejects the bare call and the plugin shows `n/a`.
81
81
 
82
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.
83
83
 
@@ -118,17 +118,17 @@ During generation, the plugin calculates the instantaneous token generation rate
118
118
 
119
119
  Slot reuse is tracked via `generateSlotId` to detect when a new generation starts on a different slot.
120
120
 
121
- ### Strata Support
121
+ ### Strata and Basalt Support
122
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.
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
124
 
125
- Strata instead reports the live rates directly in `GET /metrics`, under `live`:
125
+ Both instead report the live rates directly in `GET /metrics`, under `live`:
126
126
 
127
- - `state` — `reading` (prompt processing), `generating`, `idle`, or `unloaded`
127
+ - `state` — `reading` (prompt processing), `generating`, `idle`, or `unloaded`; Basalt also reports `loading` and `asleep`
128
128
  - `prefill_tok_s_mean` — prompt processing rate while `reading` (PP)
129
129
  - `tok_s` — instantaneous decode rate while `generating` (TG)
130
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.
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 model for a short TTL (10 s), and a failed `/metrics` read drops the cached kind immediately: a router that swaps the backend behind a stable URL (for example a conduct/bazinga profile swap between Basalt and llama.cpp) is re-detected instead of leaving the plugin polling the wrong endpoint. 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
132
 
133
133
  ## Limitations
134
134
 
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.5.0",
4
+ "version": "1.6.1",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "tui.tsx",
package/src/stats.ts CHANGED
@@ -309,23 +309,30 @@ export function selectSessionUrls(
309
309
  return []
310
310
  }
311
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.
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.
316
317
 
317
- export type ServerType = "llama" | "strata"
318
+ export type ServerType = "llama" | "strata" | "basalt"
318
319
 
319
320
  /** Returns the explicit server type from the plugin option, or undefined for auto. */
320
321
  export function serverTypeOverride(value: unknown): ServerType | undefined {
321
- if (value === "llama" || value === "strata") return value
322
+ if (value === "llama" || value === "strata" || value === "basalt") return value
322
323
  return undefined
323
324
  }
324
325
 
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"
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"
329
336
  }
330
337
 
331
338
  function finiteOrZero(value: unknown): number {
@@ -333,11 +340,12 @@ function finiteOrZero(value: unknown): number {
333
340
  }
334
341
 
335
342
  /**
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.
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.
339
347
  */
340
- export function mapStrataLive(live: unknown, tracker: TrackerState): void {
348
+ export function mapLiveMetrics(live: unknown, tracker: TrackerState): void {
341
349
  const l = live && typeof live === "object" ? (live as Record<string, unknown>) : {}
342
350
  const state = typeof l.state === "string" ? l.state : ""
343
351
 
@@ -376,8 +384,8 @@ export function mapStrataLive(live: unknown, tracker: TrackerState): void {
376
384
  // --- Model-scoped stats URLs ------------------------------------------------
377
385
  // Stats are requested with the session's model so a routing layer that
378
386
  // 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.
387
+ // call to the right backend. Plain llama.cpp / Strata / Basalt servers ignore
388
+ // the extra query parameter.
381
389
 
382
390
  /** Build a stats URL, adding the model as `?model=` when one is known. */
383
391
  export function statsUrl(baseUrl: string, path: string, model?: string): string {
@@ -387,8 +395,67 @@ export function statsUrl(baseUrl: string, path: string, model?: string): string
387
395
  /**
388
396
  * Cache key for the detected server kind. One URL can front different backends
389
397
  * 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.
398
+ * URL may be a Strata or Basalt node for one model and a llama.cpp node for
399
+ * another.
391
400
  */
392
401
  export function serverKindKey(baseUrl: string, model?: string): string {
393
402
  return `${baseUrl}\u0000${model ?? ""}`
394
403
  }
404
+
405
+ // --- Server-kind cache ------------------------------------------------------
406
+ // A routing layer (conduct) answers /health for whichever backend it currently
407
+ // has loaded, not per model, so the kind behind a stable URL changes when the
408
+ // router swaps backends (a bazinga basalt -> llama flavor swap). The cache must
409
+ // therefore expire, and a failed backend-specific probe must invalidate it, or
410
+ // the plugin keeps calling /metrics on a llama server and shows n/a.
411
+
412
+ export const SERVER_KIND_TTL_MS = 10_000
413
+
414
+ export class ServerKindCache {
415
+ private readonly entries = new Map<string, { kind: ServerType; at: number }>()
416
+
417
+ constructor(private readonly ttlMs: number = SERVER_KIND_TTL_MS) {}
418
+
419
+ /** Drop a cached kind so the next resolve probes /health again. */
420
+ invalidate(baseUrl: string, model?: string): void {
421
+ this.entries.delete(serverKindKey(baseUrl, model))
422
+ }
423
+
424
+ /**
425
+ * Return the cached kind while it is fresh, else probe. An unavailable
426
+ * /health is reported as "llama" (the historical fallback) and not cached,
427
+ * so a later probe can still identify a Strata or Basalt server.
428
+ */
429
+ async resolve(
430
+ baseUrl: string,
431
+ model: string | undefined,
432
+ probe: () => Promise<ServerType | null>,
433
+ now: number = Date.now(),
434
+ ): Promise<ServerType> {
435
+ const key = serverKindKey(baseUrl, model)
436
+ const cached = this.entries.get(key)
437
+ if (cached && now - cached.at < this.ttlMs) return cached.kind
438
+ const kind = await probe()
439
+ if (kind == null) return "llama"
440
+ this.entries.set(key, { kind, at: now })
441
+ return kind
442
+ }
443
+ }
444
+
445
+ export interface PollModel {
446
+ id: string
447
+ providerID?: string
448
+ }
449
+
450
+ /**
451
+ * The model to poll for. The prompt's live selection changes before the
452
+ * session record does, so prefer it and fall back to the session's model.
453
+ */
454
+ export function selectPollModel(
455
+ prompt: { modelID: string; providerID: string } | undefined,
456
+ session: { id: string; providerID: string } | undefined,
457
+ ): PollModel | undefined {
458
+ if (prompt && prompt.modelID) return { id: prompt.modelID, providerID: prompt.providerID }
459
+ if (session && session.id) return { id: session.id, providerID: session.providerID }
460
+ return undefined
461
+ }
package/tui.tsx CHANGED
@@ -8,10 +8,12 @@ import {
8
8
  resolveServerUrls,
9
9
  selectSessionUrls,
10
10
  serverTypeOverride,
11
- isStrataHealth,
12
- mapStrataLive,
11
+ serverTypeFromHealth,
12
+ mapLiveMetrics,
13
13
  statsUrl,
14
14
  serverKindKey,
15
+ ServerKindCache,
16
+ selectPollModel,
15
17
  type ServerType,
16
18
  } from "./src/stats.ts"
17
19
 
@@ -74,11 +76,12 @@ async function fetchHealth(baseUrl: string, model?: string): Promise<unknown | n
74
76
  }
75
77
  }
76
78
 
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> {
79
+ // Strata and Basalt report the live rates under /metrics.live
80
+ // (prefill_tok_s_mean while reading, tok_s while generating) rather than in
81
+ // the minimal /slots stub. The model is passed so a routing layer in front of
82
+ // the backend can forward the call; plain llama.cpp / Strata / Basalt servers
83
+ // ignore the parameter.
84
+ async function fetchLiveMetrics(baseUrl: string, model?: string): Promise<unknown | null> {
82
85
  try {
83
86
  const resp = await fetch(statsUrl(baseUrl, "/metrics", model))
84
87
  if (!resp.ok) return null
@@ -225,7 +228,7 @@ const tui: TuiPlugin = async (api, options) => {
225
228
  if (cached) return cached
226
229
  const health = await fetchHealth(baseUrl, model)
227
230
  if (health != null) {
228
- const kind = isStrataHealth(health) ? "strata" : "llama"
231
+ const kind = serverTypeFromHealth(health)
229
232
  serverKindByUrl.set(key, kind)
230
233
  return kind
231
234
  }
@@ -275,15 +278,15 @@ const tui: TuiPlugin = async (api, options) => {
275
278
  continue
276
279
  }
277
280
 
278
- if ((await resolveServerKind(baseUrl, model)) === "strata") {
279
- const live = await fetchStrataLive(baseUrl, model)
281
+ if ((await resolveServerKind(baseUrl, model)) !== "llama") {
282
+ const live = await fetchLiveMetrics(baseUrl, model)
280
283
  if (live == null) {
281
284
  noteServerFailure(baseUrl)
282
285
  continue
283
286
  }
284
287
  backoffByUrl.delete(baseUrl)
285
288
  tracker.failure = null
286
- mapStrataLive(live, tracker)
289
+ mapLiveMetrics(live, tracker)
287
290
  bump()
288
291
  continue
289
292
  }
@@ -505,21 +508,15 @@ const v2Setup = async (context: any) => {
505
508
  let llamaServerUrls: string[] = []
506
509
  let providerList: unknown[] = []
507
510
  const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
508
- const serverKindByUrl = new Map<string, ServerType>()
511
+ const serverKindCache = new ServerKindCache()
509
512
  const forcedServerType = serverTypeOverride((context.options as Record<string, unknown> | undefined)?.serverType)
510
513
 
511
514
  const resolveServerKind = async (baseUrl: string, model?: string): Promise<ServerType> => {
512
515
  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"
516
+ return serverKindCache.resolve(baseUrl, model, async () => {
517
+ const health = await fetchHealth(baseUrl, model)
518
+ return health == null ? null : serverTypeFromHealth(health)
519
+ })
523
520
  }
524
521
 
525
522
  const noteServerFailure = (baseUrl: string) => {
@@ -544,16 +541,13 @@ const v2Setup = async (context: any) => {
544
541
  const pollMetrics = async () => {
545
542
  if (!llamaServerUrls.length) return
546
543
 
547
- let model: string | undefined
548
- let sessionProviderId: string | undefined
549
544
  const routeSessionID = currentSessionID()
550
- if (routeSessionID) {
551
- const session = context.data.session.get(routeSessionID)
552
- if (session?.model?.id) {
553
- model = session.model.id
554
- }
555
- sessionProviderId = session?.model?.providerID
556
- }
545
+ const route = context.ui.router.current?.()
546
+ const promptModel = route?.sessionID ? context.ui.model?.current?.() : undefined
547
+ const session = routeSessionID ? context.data.session.get(routeSessionID) : undefined
548
+ const selected = selectPollModel(promptModel, session?.model)
549
+ const model = selected?.id
550
+ const sessionProviderId = selected?.providerID
557
551
 
558
552
  const activeUrls = selectSessionUrls(llamaServerUrls, providerList, sessionProviderId)
559
553
  if (!activeUrls.length) {
@@ -570,15 +564,19 @@ const v2Setup = async (context: any) => {
570
564
  continue
571
565
  }
572
566
 
573
- if ((await resolveServerKind(baseUrl, model)) === "strata") {
574
- const live = await fetchStrataLive(baseUrl, model)
567
+ if ((await resolveServerKind(baseUrl, model)) !== "llama") {
568
+ const live = await fetchLiveMetrics(baseUrl, model)
575
569
  if (live == null) {
570
+ // A router can swap the backend behind this URL (a bazinga flavor
571
+ // swap), and /health then reports the new one. Drop the cached kind
572
+ // so the next poll re-detects instead of polling /metrics forever.
573
+ serverKindCache.invalidate(baseUrl, model)
576
574
  noteServerFailure(baseUrl)
577
575
  continue
578
576
  }
579
577
  backoffByUrl.delete(baseUrl)
580
578
  tracker.failure = null
581
- mapStrataLive(live, tracker)
579
+ mapLiveMetrics(live, tracker)
582
580
  bump()
583
581
  continue
584
582
  }