@troed/oc-ls-stats 1.3.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.
- package/README.md +27 -3
- package/package.json +1 -1
- package/src/stats.ts +110 -20
- package/tui.tsx +382 -15
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,
|
|
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
|
|
|
@@ -56,16 +56,28 @@ If your llama-server provider is named differently, configure the endpoint expli
|
|
|
56
56
|
```json
|
|
57
57
|
{
|
|
58
58
|
"plugin": [
|
|
59
|
-
["@troed/oc-ls-stats@latest", { "server": "http
|
|
59
|
+
["@troed/oc-ls-stats@latest", { "server": "http://<server-host>:8080" }]
|
|
60
60
|
]
|
|
61
61
|
}
|
|
62
62
|
```
|
|
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>`
|
|
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
package/src/stats.ts
CHANGED
|
@@ -220,22 +220,34 @@ export function stripBaseUrlPath(baseURL: string): string {
|
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
222
|
|
|
223
|
+
// V1 stores a provider endpoint under options; V2 under settings
|
|
224
|
+
// (migrate-v1: "api becomes settings.baseURL", "provider options are separated
|
|
225
|
+
// into settings, headers, and body"). Read whichever is present.
|
|
226
|
+
function extractBaseURL(entry: unknown): string | undefined {
|
|
227
|
+
if (!entry || typeof entry !== "object") return undefined
|
|
228
|
+
const record = entry as Record<string, unknown>
|
|
229
|
+
for (const key of ["settings", "options"]) {
|
|
230
|
+
const section = record[key]
|
|
231
|
+
if (!section || typeof section !== "object") continue
|
|
232
|
+
const baseURL =
|
|
233
|
+
(section as Record<string, unknown>).baseURL || (section as Record<string, unknown>).base_url
|
|
234
|
+
if (typeof baseURL === "string") return baseURL
|
|
235
|
+
}
|
|
236
|
+
return undefined
|
|
237
|
+
}
|
|
238
|
+
|
|
223
239
|
export function extractProviderUrls(config: unknown): string[] {
|
|
224
240
|
if (!config || typeof config !== "object") return []
|
|
225
241
|
const obj = config as Record<string, unknown>
|
|
226
|
-
const provider = obj.provider
|
|
242
|
+
const provider = obj.providers ?? obj.provider
|
|
227
243
|
if (!provider || typeof provider !== "object") return []
|
|
228
244
|
|
|
229
245
|
const urls: string[] = []
|
|
230
246
|
for (const [key, val] of Object.entries(provider as Record<string, unknown>)) {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (typeof baseURL === "string" && key.toLowerCase().includes("llama") && !key.toLowerCase().includes("ollama")) {
|
|
236
|
-
urls.push(stripBaseUrlPath(baseURL))
|
|
237
|
-
}
|
|
238
|
-
}
|
|
247
|
+
const baseURL = extractBaseURL(val)
|
|
248
|
+
const hay = key.toLowerCase()
|
|
249
|
+
if (typeof baseURL === "string" && hay.includes("llama") && !hay.includes("ollama")) {
|
|
250
|
+
urls.push(stripBaseUrlPath(baseURL))
|
|
239
251
|
}
|
|
240
252
|
}
|
|
241
253
|
return urls
|
|
@@ -251,9 +263,7 @@ export function extractProviderUrlsFromList(providers: unknown): string[] {
|
|
|
251
263
|
const name = typeof provider.name === "string" ? provider.name.toLowerCase() : ""
|
|
252
264
|
const hay = `${id} ${name}`
|
|
253
265
|
if (!hay.includes("llama") || hay.includes("ollama")) continue
|
|
254
|
-
const
|
|
255
|
-
if (!opts || typeof opts !== "object") continue
|
|
256
|
-
const baseURL = (opts as Record<string, unknown>).baseURL || (opts as Record<string, unknown>).base_url
|
|
266
|
+
const baseURL = extractBaseURL(provider)
|
|
257
267
|
if (typeof baseURL === "string") {
|
|
258
268
|
urls.push(stripBaseUrlPath(baseURL))
|
|
259
269
|
}
|
|
@@ -289,16 +299,96 @@ export function selectSessionUrls(
|
|
|
289
299
|
if (!entry || typeof entry !== "object") continue
|
|
290
300
|
const provider = entry as Record<string, unknown>
|
|
291
301
|
if (provider.id !== providerID) continue
|
|
292
|
-
const
|
|
293
|
-
if (
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
if (typeof baseURL === "string") {
|
|
297
|
-
const normalized = stripBaseUrlPath(baseURL)
|
|
298
|
-
if (candidates.includes(normalized)) return [normalized]
|
|
299
|
-
}
|
|
302
|
+
const baseURL = extractBaseURL(provider)
|
|
303
|
+
if (typeof baseURL === "string") {
|
|
304
|
+
const normalized = stripBaseUrlPath(baseURL)
|
|
305
|
+
if (candidates.includes(normalized)) return [normalized]
|
|
300
306
|
}
|
|
301
307
|
return []
|
|
302
308
|
}
|
|
303
309
|
return []
|
|
304
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
|
@@ -1,8 +1,19 @@
|
|
|
1
1
|
/** @jsxImportSource @opentui/solid */
|
|
2
2
|
import type { TextRenderable } from "@opentui/core"
|
|
3
3
|
import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
|
|
4
|
-
import { onCleanup } from "solid-js"
|
|
5
|
-
import {
|
|
4
|
+
import { onCleanup, createSignal } from "solid-js"
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
307
|
+
processPoll(slotList, tracker)
|
|
239
308
|
bump()
|
|
240
309
|
}
|
|
241
310
|
}
|
|
@@ -333,9 +402,307 @@ const tui: TuiPlugin = async (api, options) => {
|
|
|
333
402
|
})
|
|
334
403
|
}
|
|
335
404
|
|
|
336
|
-
|
|
405
|
+
// ---------------------------------------------------------------------------
|
|
406
|
+
// V2 (opencode >= 2.0) implementation
|
|
407
|
+
//
|
|
408
|
+
// V2 TUI plugin system replaces the V1 tui(api) function with
|
|
409
|
+
// setup(context): the readout registers through context.ui.slot on
|
|
410
|
+
// prompt.footer.status (the V2 successor of session_prompt_right), events
|
|
411
|
+
// arrive through context.data.on, and provider/session state comes from
|
|
412
|
+
// context.data.location / context.data.session. The V1 tui() above is kept
|
|
413
|
+
// untouched; both implementations are exposed from the same default export
|
|
414
|
+
// (V1 calls tui, V2 calls setup) and share the tracker helpers from
|
|
415
|
+
// src/stats.ts.
|
|
416
|
+
// ---------------------------------------------------------------------------
|
|
417
|
+
|
|
418
|
+
const v2Setup = async (context: any) => {
|
|
419
|
+
const location = context.location ?? context.data.location.default()
|
|
420
|
+
const themeMuted = context.theme?.text?.muted
|
|
421
|
+
|
|
422
|
+
const tracker: TrackerState = {
|
|
423
|
+
streamSamplesBySession: {},
|
|
424
|
+
messageTimingByID: {},
|
|
425
|
+
lastPrefillRate: 0,
|
|
426
|
+
lastGeneratedTps: 0,
|
|
427
|
+
isPrefilling: false,
|
|
428
|
+
prefillSlotId: null,
|
|
429
|
+
prefillCapturedTokens: null,
|
|
430
|
+
prefillStartAt: 0,
|
|
431
|
+
isGenerating: false,
|
|
432
|
+
generateSlotId: null,
|
|
433
|
+
generatePrevNd: 0,
|
|
434
|
+
generateStartAt: 0,
|
|
435
|
+
prevNdBySlot: {},
|
|
436
|
+
prevPromptTokensBySlot: {},
|
|
437
|
+
failure: null,
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// part id -> part type, learned from message.part.updated; used to skip
|
|
441
|
+
// non-text/reasoning deltas (e.g. tool output) like the V1 part lookup
|
|
442
|
+
const partTypeByID = new Map<string, string>()
|
|
443
|
+
|
|
444
|
+
function getStatusText() {
|
|
445
|
+
const s = tracker
|
|
446
|
+
if (s.failure) {
|
|
447
|
+
return s.failure
|
|
448
|
+
}
|
|
449
|
+
const pp = s.isPrefilling && s.lastPrefillRate > 0 ? formatPps(s.lastPrefillRate) : undefined
|
|
450
|
+
const tps = s.isGenerating && s.lastGeneratedTps > 0 ? formatTps(s.lastGeneratedTps) : undefined
|
|
451
|
+
let result = "- tps (TG)"
|
|
452
|
+
if (s.isPrefilling && pp) {
|
|
453
|
+
result = `${pp} tps (PP)`
|
|
454
|
+
} else if (s.isGenerating && tps) {
|
|
455
|
+
result = `${tps} tps (TG)`
|
|
456
|
+
}
|
|
457
|
+
return result
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const [statusText, setStatusText] = createSignal<string>("- tps (TG)")
|
|
461
|
+
|
|
462
|
+
const bump = () => {
|
|
463
|
+
setStatusText(getStatusText())
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const pruneSamples = (now = Date.now()) => {
|
|
467
|
+
let changed = false
|
|
468
|
+
for (const [sessionID, samples] of Object.entries(tracker.streamSamplesBySession)) {
|
|
469
|
+
const next = samples.filter((sample) => now - sample.at <= STREAM_WINDOW_MS)
|
|
470
|
+
if (next.length !== samples.length) {
|
|
471
|
+
changed = true
|
|
472
|
+
if (next.length > 0) tracker.streamSamplesBySession[sessionID] = next
|
|
473
|
+
else delete tracker.streamSamplesBySession[sessionID]
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (changed) bump()
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const clearLiveSamples = (sessionID: string) => {
|
|
480
|
+
if (!tracker.streamSamplesBySession[sessionID]?.length) return
|
|
481
|
+
delete tracker.streamSamplesBySession[sessionID]
|
|
482
|
+
bump()
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const appendSample = (sessionID: string, messageID: string, sample: StreamSample) => {
|
|
486
|
+
const now = sample.at
|
|
487
|
+
tracker.streamSamplesBySession[sessionID] = [
|
|
488
|
+
...(tracker.streamSamplesBySession[sessionID] ?? []).filter((item) => now - item.at <= STREAM_WINDOW_MS),
|
|
489
|
+
sample,
|
|
490
|
+
]
|
|
491
|
+
const timing = tracker.messageTimingByID[messageID]
|
|
492
|
+
if (timing) {
|
|
493
|
+
tracker.messageTimingByID[messageID] = timing.firstTokenAt
|
|
494
|
+
? { ...timing, lastTokenAt: now }
|
|
495
|
+
: {
|
|
496
|
+
...timing,
|
|
497
|
+
firstResponseAt: timing.firstResponseAt ?? now,
|
|
498
|
+
firstTokenAt: now,
|
|
499
|
+
lastTokenAt: now,
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
bump()
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
let llamaServerUrls: string[] = []
|
|
506
|
+
let providerList: unknown[] = []
|
|
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
|
+
}
|
|
536
|
+
|
|
537
|
+
const currentSessionID = (): string | undefined => {
|
|
538
|
+
const route = context.ui.router.current?.()
|
|
539
|
+
if (route?.sessionID) return route.sessionID
|
|
540
|
+
const loc = context.location ?? context.data.location.default()
|
|
541
|
+
return loc?.sessionID
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
const pollMetrics = async () => {
|
|
545
|
+
if (!llamaServerUrls.length) return
|
|
546
|
+
|
|
547
|
+
let model: string | undefined
|
|
548
|
+
let sessionProviderId: string | undefined
|
|
549
|
+
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
|
+
}
|
|
557
|
+
|
|
558
|
+
const activeUrls = selectSessionUrls(llamaServerUrls, providerList, sessionProviderId)
|
|
559
|
+
if (!activeUrls.length) {
|
|
560
|
+
tracker.failure = "n/a"
|
|
561
|
+
bump()
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
for (const baseUrl of activeUrls) {
|
|
565
|
+
const now = Date.now()
|
|
566
|
+
const backoff = backoffByUrl.get(baseUrl)
|
|
567
|
+
if (backoff && now < backoff.nextRetryAt) {
|
|
568
|
+
tracker.failure = "n/a"
|
|
569
|
+
bump()
|
|
570
|
+
continue
|
|
571
|
+
}
|
|
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
|
+
|
|
586
|
+
const slots = await fetchSlots(baseUrl, model)
|
|
587
|
+
if (slots == null) {
|
|
588
|
+
noteServerFailure(baseUrl)
|
|
589
|
+
continue
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
backoffByUrl.delete(baseUrl)
|
|
593
|
+
const slotList = Array.isArray(slots) ? slots : Object.values(slots)
|
|
594
|
+
if (slotList.length === 0) {
|
|
595
|
+
tracker.failure = "n/a"
|
|
596
|
+
bump()
|
|
597
|
+
continue
|
|
598
|
+
}
|
|
599
|
+
tracker.failure = null
|
|
600
|
+
bump()
|
|
601
|
+
|
|
602
|
+
processPoll(slotList, tracker)
|
|
603
|
+
bump()
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const propsOf = (evt: any) => evt?.data ?? evt?.properties ?? {}
|
|
608
|
+
|
|
609
|
+
const offDelta = context.data.on("message.part.delta", (evt: any) => {
|
|
610
|
+
const p = propsOf(evt)
|
|
611
|
+
if (p.field !== "text") return
|
|
612
|
+
const partType = partTypeByID.get(p.partID)
|
|
613
|
+
if (partType && partType !== "text" && partType !== "reasoning") return
|
|
614
|
+
appendSample(p.sessionID, p.messageID, {
|
|
615
|
+
at: Date.now(),
|
|
616
|
+
tokens: estimateStreamTokens(String(p.delta ?? "")),
|
|
617
|
+
})
|
|
618
|
+
})
|
|
619
|
+
|
|
620
|
+
const offMessage = context.data.on("message.updated", (evt: any) => {
|
|
621
|
+
const p = propsOf(evt)
|
|
622
|
+
if (p.info?.role !== "assistant") return
|
|
623
|
+
|
|
624
|
+
if (!p.info?.time?.completed) {
|
|
625
|
+
const existing = tracker.messageTimingByID[p.info.id]
|
|
626
|
+
tracker.messageTimingByID[p.info.id] = {
|
|
627
|
+
sessionID: p.sessionID,
|
|
628
|
+
requestStartAt: p.info.time.created,
|
|
629
|
+
firstResponseAt: existing?.firstResponseAt,
|
|
630
|
+
firstTokenAt: existing?.firstTokenAt,
|
|
631
|
+
lastTokenAt: existing?.lastTokenAt,
|
|
632
|
+
}
|
|
633
|
+
bump()
|
|
634
|
+
return
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
delete tracker.messageTimingByID[p.info.id]
|
|
638
|
+
pruneSamples(p.info?.time?.completed)
|
|
639
|
+
bump()
|
|
640
|
+
})
|
|
641
|
+
|
|
642
|
+
const offPart = context.data.on("message.part.updated", (evt: any) => {
|
|
643
|
+
const p = propsOf(evt)
|
|
644
|
+
const part = p.part
|
|
645
|
+
if (!part?.id) return
|
|
646
|
+
if (typeof part.type === "string") partTypeByID.set(part.id, part.type)
|
|
647
|
+
if (part.type !== "tool") return
|
|
648
|
+
if (
|
|
649
|
+
part.state?.status === "running" ||
|
|
650
|
+
part.state?.status === "completed" ||
|
|
651
|
+
part.state?.status === "error"
|
|
652
|
+
) {
|
|
653
|
+
clearLiveSamples(p.sessionID)
|
|
654
|
+
}
|
|
655
|
+
const messageID = part.messageID
|
|
656
|
+
if (!messageID) return
|
|
657
|
+
const timing = tracker.messageTimingByID[messageID]
|
|
658
|
+
if (!timing) return
|
|
659
|
+
if (part.state?.status === "pending") {
|
|
660
|
+
tracker.messageTimingByID[messageID] = {
|
|
661
|
+
...timing,
|
|
662
|
+
firstResponseAt: timing.firstResponseAt ?? p.time,
|
|
663
|
+
}
|
|
664
|
+
bump()
|
|
665
|
+
return
|
|
666
|
+
}
|
|
667
|
+
if (part.state?.status === "running") bump()
|
|
668
|
+
})
|
|
669
|
+
|
|
670
|
+
const timer = setInterval(() => {
|
|
671
|
+
pruneSamples()
|
|
672
|
+
}, 1000)
|
|
673
|
+
|
|
674
|
+
const slotTimer = setInterval(() => {
|
|
675
|
+
void pollMetrics()
|
|
676
|
+
}, SLOT_POLL_MS)
|
|
677
|
+
|
|
678
|
+
try {
|
|
679
|
+
await context.data.location.provider.sync(location)
|
|
680
|
+
providerList = context.data.location.provider.list(location) ?? []
|
|
681
|
+
llamaServerUrls = resolveServerUrls(context.options, providerList, undefined)
|
|
682
|
+
} catch (e) {
|
|
683
|
+
console.error("[oc-ls-stats] resolveServerUrls error:", e)
|
|
684
|
+
llamaServerUrls = ["http://localhost:8080"]
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
const unregisterSlot = context.ui.slot({
|
|
688
|
+
append: "prompt.footer.status",
|
|
689
|
+
render: () => <text fg={themeMuted}>{statusText()}</text>,
|
|
690
|
+
})
|
|
691
|
+
|
|
692
|
+
return () => {
|
|
693
|
+
offDelta()
|
|
694
|
+
offMessage()
|
|
695
|
+
offPart()
|
|
696
|
+
clearInterval(timer)
|
|
697
|
+
clearInterval(slotTimer)
|
|
698
|
+
if (typeof unregisterSlot === "function") unregisterSlot()
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
const plugin = {
|
|
337
703
|
id: "@troed/oc-ls-stats",
|
|
338
704
|
tui,
|
|
705
|
+
setup: v2Setup,
|
|
339
706
|
}
|
|
340
707
|
|
|
341
708
|
export default plugin
|