@troed/oc-ls-stats 1.2.1 → 1.4.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.
- package/README.md +18 -2
- package/package.json +6 -2
- package/src/stats.ts +102 -0
- package/tui.tsx +306 -47
package/README.md
CHANGED
|
@@ -47,12 +47,28 @@ The plugin renders a single line in the session prompt right slot:
|
|
|
47
47
|
|
|
48
48
|
### Server Discovery
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
By default the plugin discovers the llama-server URL from OpenCode's resolved provider list (`id` or `name` containing "llama", excluding "ollama"), extracting `baseURL`/`base_url` from the provider options. This covers providers from all sources (config, environment, API). If the provider list is unavailable, it falls back to parsing the OpenCode configuration directly, and finally to `http://localhost:8080`.
|
|
51
|
+
|
|
52
|
+
When several llama-server providers are detected, stats follow the provider used by the current session; until a session has picked a model, every detected server is polled.
|
|
53
|
+
|
|
54
|
+
If your llama-server provider is named differently, configure the endpoint explicitly via the plugin's `server` option in `tui.json`. An explicit server replaces discovery entirely:
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{
|
|
58
|
+
"plugin": [
|
|
59
|
+
["@troed/oc-ls-stats@latest", { "server": "http://<server-host>:8080" }]
|
|
60
|
+
]
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
A `baseURL`-style value ending in `/v1` is also accepted.
|
|
51
65
|
|
|
52
66
|
### Slot Polling
|
|
53
67
|
|
|
54
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.
|
|
55
69
|
|
|
70
|
+
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
|
+
|
|
56
72
|
### State Classification
|
|
57
73
|
|
|
58
74
|
Each processing slot is classified as prefill (PP) or generation (TG) by comparing `n_decoded` and `n_prompt_tokens` against per-slot/per-task baselines. The plugin tracks two baseline maps keyed by slot ID:
|
|
@@ -114,7 +130,7 @@ The following changes to the `/slots` endpoint would improve the plugin's functi
|
|
|
114
130
|
|
|
115
131
|
For known issues, posting new ones, forking or contributing:
|
|
116
132
|
|
|
117
|
-
https://
|
|
133
|
+
https://git.sync.wtf/troed/oc-ls-stats
|
|
118
134
|
|
|
119
135
|
## Debug Logging
|
|
120
136
|
|
package/package.json
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@troed/oc-ls-stats",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.4.1",
|
|
5
5
|
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"tui.tsx",
|
|
8
|
+
"src"
|
|
9
|
+
],
|
|
6
10
|
"exports": {
|
|
7
11
|
"./tui": {
|
|
8
12
|
"import": "./tui.tsx"
|
|
9
13
|
}
|
|
10
14
|
},
|
|
11
15
|
"scripts": {
|
|
12
|
-
"prepack": "npx -y tsx test-
|
|
16
|
+
"prepack": "npx -y tsx test-backoff.ts"
|
|
13
17
|
},
|
|
14
18
|
"engines": {
|
|
15
19
|
"opencode": ">=1.3.14"
|
package/src/stats.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
export function backoffDelayMs(failures: number, baseMs: number = 1000, maxMs: number = 10000): number {
|
|
2
|
+
return Math.min(maxMs, baseMs * 2 ** (failures - 1))
|
|
3
|
+
}
|
|
4
|
+
|
|
1
5
|
export interface SlotState {
|
|
2
6
|
id: number
|
|
3
7
|
is_processing: boolean
|
|
@@ -206,3 +210,101 @@ export function processPoll(
|
|
|
206
210
|
tgEnded,
|
|
207
211
|
}
|
|
208
212
|
}
|
|
213
|
+
|
|
214
|
+
export function stripBaseUrlPath(baseURL: string): string {
|
|
215
|
+
try {
|
|
216
|
+
const url = new URL(baseURL)
|
|
217
|
+
return `${url.origin}`
|
|
218
|
+
} catch {
|
|
219
|
+
return baseURL.replace(/\/v1(\/.*)?$/, "").replace(/\/$/, "") || baseURL
|
|
220
|
+
}
|
|
221
|
+
}
|
|
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
|
+
|
|
239
|
+
export function extractProviderUrls(config: unknown): string[] {
|
|
240
|
+
if (!config || typeof config !== "object") return []
|
|
241
|
+
const obj = config as Record<string, unknown>
|
|
242
|
+
const provider = obj.providers ?? obj.provider
|
|
243
|
+
if (!provider || typeof provider !== "object") return []
|
|
244
|
+
|
|
245
|
+
const urls: string[] = []
|
|
246
|
+
for (const [key, val] of Object.entries(provider as Record<string, unknown>)) {
|
|
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))
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return urls
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function extractProviderUrlsFromList(providers: unknown): string[] {
|
|
257
|
+
if (!Array.isArray(providers)) return []
|
|
258
|
+
const urls: string[] = []
|
|
259
|
+
for (const entry of providers) {
|
|
260
|
+
if (!entry || typeof entry !== "object") continue
|
|
261
|
+
const provider = entry as Record<string, unknown>
|
|
262
|
+
const id = typeof provider.id === "string" ? provider.id.toLowerCase() : ""
|
|
263
|
+
const name = typeof provider.name === "string" ? provider.name.toLowerCase() : ""
|
|
264
|
+
const hay = `${id} ${name}`
|
|
265
|
+
if (!hay.includes("llama") || hay.includes("ollama")) continue
|
|
266
|
+
const baseURL = extractBaseURL(provider)
|
|
267
|
+
if (typeof baseURL === "string") {
|
|
268
|
+
urls.push(stripBaseUrlPath(baseURL))
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return urls
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function resolveServerUrls(options: unknown, providers: unknown, config: unknown): string[] {
|
|
275
|
+
const opts = options && typeof options === "object" ? (options as Record<string, unknown>) : undefined
|
|
276
|
+
const server = opts?.server
|
|
277
|
+
const explicit = typeof server === "string" && server.trim() !== "" ? stripBaseUrlPath(server) : undefined
|
|
278
|
+
if (explicit && /^https?:\/\//.test(explicit)) {
|
|
279
|
+
return [explicit]
|
|
280
|
+
}
|
|
281
|
+
if (server !== undefined) {
|
|
282
|
+
console.warn("[oc-ls-stats] ignoring invalid 'server' plugin option, falling back to provider detection")
|
|
283
|
+
}
|
|
284
|
+
const detected = [...new Set(extractProviderUrlsFromList(providers))]
|
|
285
|
+
if (detected.length > 0) return detected
|
|
286
|
+
const legacy = [...new Set(extractProviderUrls(config))]
|
|
287
|
+
return legacy.length > 0 ? legacy : ["http://localhost:8080"]
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function selectSessionUrls(
|
|
291
|
+
candidates: string[],
|
|
292
|
+
providers: unknown,
|
|
293
|
+
providerID: string | undefined,
|
|
294
|
+
): string[] {
|
|
295
|
+
if (typeof providerID !== "string" || providerID.trim() === "" || candidates.length === 0)
|
|
296
|
+
return candidates
|
|
297
|
+
if (!Array.isArray(providers) || providers.length === 0) return candidates
|
|
298
|
+
for (const entry of providers) {
|
|
299
|
+
if (!entry || typeof entry !== "object") continue
|
|
300
|
+
const provider = entry as Record<string, unknown>
|
|
301
|
+
if (provider.id !== providerID) continue
|
|
302
|
+
const baseURL = extractBaseURL(provider)
|
|
303
|
+
if (typeof baseURL === "string") {
|
|
304
|
+
const normalized = stripBaseUrlPath(baseURL)
|
|
305
|
+
if (candidates.includes(normalized)) return [normalized]
|
|
306
|
+
}
|
|
307
|
+
return []
|
|
308
|
+
}
|
|
309
|
+
return []
|
|
310
|
+
}
|
package/tui.tsx
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
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 { processPoll } from "./src/stats.ts"
|
|
4
|
+
import { onCleanup, createSignal } from "solid-js"
|
|
5
|
+
import { backoffDelayMs, processPoll, resolveServerUrls, selectSessionUrls } from "./src/stats.ts"
|
|
6
6
|
|
|
7
7
|
type StreamSample = {
|
|
8
8
|
at: number
|
|
@@ -11,6 +11,8 @@ type StreamSample = {
|
|
|
11
11
|
|
|
12
12
|
const STREAM_WINDOW_MS = 5_000
|
|
13
13
|
const SLOT_POLL_MS = 500
|
|
14
|
+
const BACKOFF_BASE_MS = 1_000
|
|
15
|
+
const BACKOFF_MAX_MS = 10_000
|
|
14
16
|
type MessageTiming = {
|
|
15
17
|
sessionID: string
|
|
16
18
|
requestStartAt: number
|
|
@@ -41,44 +43,6 @@ function estimateStreamTokens(delta: string) {
|
|
|
41
43
|
return Math.max(1, Math.ceil(Buffer.byteLength(delta, "utf8") / 5))
|
|
42
44
|
}
|
|
43
45
|
|
|
44
|
-
function stripBaseUrlPath(baseURL: string): string {
|
|
45
|
-
try {
|
|
46
|
-
const url = new URL(baseURL)
|
|
47
|
-
return `${url.origin}`
|
|
48
|
-
} catch {
|
|
49
|
-
return baseURL.replace(/\/v1(\/.*)?$/, "").replace(/\/$/, "") || baseURL
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function extractProviderUrls(config: unknown): string[] {
|
|
54
|
-
if (!config || typeof config !== "object") return []
|
|
55
|
-
const obj = config as Record<string, unknown>
|
|
56
|
-
const provider = obj.provider
|
|
57
|
-
if (!provider || typeof provider !== "object") return []
|
|
58
|
-
|
|
59
|
-
const urls: string[] = []
|
|
60
|
-
for (const [key, val] of Object.entries(provider as Record<string, unknown>)) {
|
|
61
|
-
if (val && typeof val === "object") {
|
|
62
|
-
const opts = (val as Record<string, unknown>).options
|
|
63
|
-
if (opts && typeof opts === "object") {
|
|
64
|
-
const baseURL = (opts as Record<string, unknown>).baseURL || (opts as Record<string, unknown>).base_url
|
|
65
|
-
if (typeof baseURL === "string" && key.toLowerCase().includes("llama") && !key.toLowerCase().includes("ollama")) {
|
|
66
|
-
urls.push(stripBaseUrlPath(baseURL))
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
return urls
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
async function loadConfigUrls(api: Parameters<TuiPlugin>[0]): Promise<string[]> {
|
|
75
|
-
try {
|
|
76
|
-
return extractProviderUrls(api.state.config as unknown)
|
|
77
|
-
} catch (e) {
|
|
78
|
-
return []
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
46
|
async function fetchSlots(baseUrl: string, model?: string): Promise<unknown | null> {
|
|
83
47
|
try {
|
|
84
48
|
const url = model ? `${baseUrl}/slots?model=${encodeURIComponent(model)}` : `${baseUrl}/slots`
|
|
@@ -146,7 +110,7 @@ function SessionPromptRight(props: {
|
|
|
146
110
|
}
|
|
147
111
|
}
|
|
148
112
|
|
|
149
|
-
const tui: TuiPlugin = async (api) => {
|
|
113
|
+
const tui: TuiPlugin = async (api, options) => {
|
|
150
114
|
console.log("[oc-ls-stats] TUI plugin loaded!")
|
|
151
115
|
const tracker: TrackerState = {
|
|
152
116
|
streamSamplesBySession: {},
|
|
@@ -214,11 +178,13 @@ const tui: TuiPlugin = async (api) => {
|
|
|
214
178
|
|
|
215
179
|
let llamaServerUrls: string[] = []
|
|
216
180
|
let llamaServerModel: string | undefined
|
|
181
|
+
const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
|
|
217
182
|
|
|
218
183
|
const pollMetrics = async () => {
|
|
219
184
|
if (!llamaServerUrls.length) return
|
|
220
185
|
|
|
221
186
|
let model = llamaServerModel
|
|
187
|
+
let sessionProviderId: string | undefined
|
|
222
188
|
if (!model) {
|
|
223
189
|
const routeSessionID = api.route.current.params?.sessionID
|
|
224
190
|
if (routeSessionID) {
|
|
@@ -226,12 +192,41 @@ const tui: TuiPlugin = async (api) => {
|
|
|
226
192
|
if (session?.model?.id) {
|
|
227
193
|
model = session.model.id
|
|
228
194
|
}
|
|
195
|
+
sessionProviderId = session?.model?.providerID
|
|
229
196
|
}
|
|
230
197
|
}
|
|
231
198
|
|
|
232
|
-
|
|
199
|
+
const activeUrls = selectSessionUrls(llamaServerUrls, api.state.provider, sessionProviderId)
|
|
200
|
+
if (!activeUrls.length) {
|
|
201
|
+
tracker.failure = "n/a"
|
|
202
|
+
bump()
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
for (const baseUrl of activeUrls) {
|
|
206
|
+
const now = Date.now()
|
|
207
|
+
const backoff = backoffByUrl.get(baseUrl)
|
|
208
|
+
if (backoff && now < backoff.nextRetryAt) {
|
|
209
|
+
tracker.failure = "n/a"
|
|
210
|
+
bump()
|
|
211
|
+
continue
|
|
212
|
+
}
|
|
213
|
+
|
|
233
214
|
const slots = await fetchSlots(baseUrl, model)
|
|
234
|
-
|
|
215
|
+
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()
|
|
225
|
+
continue
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
backoffByUrl.delete(baseUrl)
|
|
229
|
+
const slotList = Array.isArray(slots) ? slots : Object.values(slots)
|
|
235
230
|
if (slotList.length === 0) {
|
|
236
231
|
tracker.failure = "n/a"
|
|
237
232
|
bump()
|
|
@@ -318,10 +313,9 @@ const tui: TuiPlugin = async (api) => {
|
|
|
318
313
|
})
|
|
319
314
|
|
|
320
315
|
try {
|
|
321
|
-
|
|
322
|
-
llamaServerUrls = configUrls.length > 0 ? configUrls : ["http://localhost:8080"]
|
|
316
|
+
llamaServerUrls = resolveServerUrls(options, api.state.provider, api.state.config)
|
|
323
317
|
} catch (e) {
|
|
324
|
-
console.error("[oc-ls-stats]
|
|
318
|
+
console.error("[oc-ls-stats] resolveServerUrls error:", e)
|
|
325
319
|
llamaServerUrls = ["http://localhost:8080"]
|
|
326
320
|
}
|
|
327
321
|
|
|
@@ -339,9 +333,274 @@ const tui: TuiPlugin = async (api) => {
|
|
|
339
333
|
})
|
|
340
334
|
}
|
|
341
335
|
|
|
342
|
-
|
|
336
|
+
// ---------------------------------------------------------------------------
|
|
337
|
+
// V2 (opencode >= 2.0) implementation
|
|
338
|
+
//
|
|
339
|
+
// V2 TUI plugin system replaces the V1 tui(api) function with
|
|
340
|
+
// setup(context): the readout registers through context.ui.slot on
|
|
341
|
+
// prompt.footer.status (the V2 successor of session_prompt_right), events
|
|
342
|
+
// arrive through context.data.on, and provider/session state comes from
|
|
343
|
+
// context.data.location / context.data.session. The V1 tui() above is kept
|
|
344
|
+
// untouched; both implementations are exposed from the same default export
|
|
345
|
+
// (V1 calls tui, V2 calls setup) and share the tracker helpers from
|
|
346
|
+
// src/stats.ts.
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
const v2Setup = async (context: any) => {
|
|
350
|
+
const location = context.location ?? context.data.location.default()
|
|
351
|
+
const themeMuted = context.theme?.text?.muted
|
|
352
|
+
|
|
353
|
+
const tracker: TrackerState = {
|
|
354
|
+
streamSamplesBySession: {},
|
|
355
|
+
messageTimingByID: {},
|
|
356
|
+
lastPrefillRate: 0,
|
|
357
|
+
lastGeneratedTps: 0,
|
|
358
|
+
isPrefilling: false,
|
|
359
|
+
prefillSlotId: null,
|
|
360
|
+
prefillCapturedTokens: null,
|
|
361
|
+
prefillStartAt: 0,
|
|
362
|
+
isGenerating: false,
|
|
363
|
+
generateSlotId: null,
|
|
364
|
+
generatePrevNd: 0,
|
|
365
|
+
generateStartAt: 0,
|
|
366
|
+
prevNdBySlot: {},
|
|
367
|
+
prevPromptTokensBySlot: {},
|
|
368
|
+
failure: null,
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// part id -> part type, learned from message.part.updated; used to skip
|
|
372
|
+
// non-text/reasoning deltas (e.g. tool output) like the V1 part lookup
|
|
373
|
+
const partTypeByID = new Map<string, string>()
|
|
374
|
+
|
|
375
|
+
function getStatusText() {
|
|
376
|
+
const s = tracker
|
|
377
|
+
if (s.failure) {
|
|
378
|
+
return s.failure
|
|
379
|
+
}
|
|
380
|
+
const pp = s.isPrefilling && s.lastPrefillRate > 0 ? formatPps(s.lastPrefillRate) : undefined
|
|
381
|
+
const tps = s.isGenerating && s.lastGeneratedTps > 0 ? formatTps(s.lastGeneratedTps) : undefined
|
|
382
|
+
let result = "- tps (TG)"
|
|
383
|
+
if (s.isPrefilling && pp) {
|
|
384
|
+
result = `${pp} tps (PP)`
|
|
385
|
+
} else if (s.isGenerating && tps) {
|
|
386
|
+
result = `${tps} tps (TG)`
|
|
387
|
+
}
|
|
388
|
+
return result
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const [statusText, setStatusText] = createSignal<string>("- tps (TG)")
|
|
392
|
+
|
|
393
|
+
const bump = () => {
|
|
394
|
+
setStatusText(getStatusText())
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const pruneSamples = (now = Date.now()) => {
|
|
398
|
+
let changed = false
|
|
399
|
+
for (const [sessionID, samples] of Object.entries(tracker.streamSamplesBySession)) {
|
|
400
|
+
const next = samples.filter((sample) => now - sample.at <= STREAM_WINDOW_MS)
|
|
401
|
+
if (next.length !== samples.length) {
|
|
402
|
+
changed = true
|
|
403
|
+
if (next.length > 0) tracker.streamSamplesBySession[sessionID] = next
|
|
404
|
+
else delete tracker.streamSamplesBySession[sessionID]
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (changed) bump()
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const clearLiveSamples = (sessionID: string) => {
|
|
411
|
+
if (!tracker.streamSamplesBySession[sessionID]?.length) return
|
|
412
|
+
delete tracker.streamSamplesBySession[sessionID]
|
|
413
|
+
bump()
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const appendSample = (sessionID: string, messageID: string, sample: StreamSample) => {
|
|
417
|
+
const now = sample.at
|
|
418
|
+
tracker.streamSamplesBySession[sessionID] = [
|
|
419
|
+
...(tracker.streamSamplesBySession[sessionID] ?? []).filter((item) => now - item.at <= STREAM_WINDOW_MS),
|
|
420
|
+
sample,
|
|
421
|
+
]
|
|
422
|
+
const timing = tracker.messageTimingByID[messageID]
|
|
423
|
+
if (timing) {
|
|
424
|
+
tracker.messageTimingByID[messageID] = timing.firstTokenAt
|
|
425
|
+
? { ...timing, lastTokenAt: now }
|
|
426
|
+
: {
|
|
427
|
+
...timing,
|
|
428
|
+
firstResponseAt: timing.firstResponseAt ?? now,
|
|
429
|
+
firstTokenAt: now,
|
|
430
|
+
lastTokenAt: now,
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
bump()
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
let llamaServerUrls: string[] = []
|
|
437
|
+
let providerList: unknown[] = []
|
|
438
|
+
const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
|
|
439
|
+
|
|
440
|
+
const currentSessionID = (): string | undefined => {
|
|
441
|
+
const route = context.ui.router.current?.()
|
|
442
|
+
if (route?.sessionID) return route.sessionID
|
|
443
|
+
const loc = context.location ?? context.data.location.default()
|
|
444
|
+
return loc?.sessionID
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const pollMetrics = async () => {
|
|
448
|
+
if (!llamaServerUrls.length) return
|
|
449
|
+
|
|
450
|
+
let model: string | undefined
|
|
451
|
+
let sessionProviderId: string | undefined
|
|
452
|
+
const routeSessionID = currentSessionID()
|
|
453
|
+
if (routeSessionID) {
|
|
454
|
+
const session = context.data.session.get(routeSessionID)
|
|
455
|
+
if (session?.model?.id) {
|
|
456
|
+
model = session.model.id
|
|
457
|
+
}
|
|
458
|
+
sessionProviderId = session?.model?.providerID
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const activeUrls = selectSessionUrls(llamaServerUrls, providerList, sessionProviderId)
|
|
462
|
+
if (!activeUrls.length) {
|
|
463
|
+
tracker.failure = "n/a"
|
|
464
|
+
bump()
|
|
465
|
+
return
|
|
466
|
+
}
|
|
467
|
+
for (const baseUrl of activeUrls) {
|
|
468
|
+
const now = Date.now()
|
|
469
|
+
const backoff = backoffByUrl.get(baseUrl)
|
|
470
|
+
if (backoff && now < backoff.nextRetryAt) {
|
|
471
|
+
tracker.failure = "n/a"
|
|
472
|
+
bump()
|
|
473
|
+
continue
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const slots = await fetchSlots(baseUrl, model)
|
|
477
|
+
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()
|
|
487
|
+
continue
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
backoffByUrl.delete(baseUrl)
|
|
491
|
+
const slotList = Array.isArray(slots) ? slots : Object.values(slots)
|
|
492
|
+
if (slotList.length === 0) {
|
|
493
|
+
tracker.failure = "n/a"
|
|
494
|
+
bump()
|
|
495
|
+
continue
|
|
496
|
+
}
|
|
497
|
+
tracker.failure = null
|
|
498
|
+
bump()
|
|
499
|
+
|
|
500
|
+
processPoll(slotList, tracker)
|
|
501
|
+
bump()
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const propsOf = (evt: any) => evt?.data ?? evt?.properties ?? {}
|
|
506
|
+
|
|
507
|
+
const offDelta = context.data.on("message.part.delta", (evt: any) => {
|
|
508
|
+
const p = propsOf(evt)
|
|
509
|
+
if (p.field !== "text") return
|
|
510
|
+
const partType = partTypeByID.get(p.partID)
|
|
511
|
+
if (partType && partType !== "text" && partType !== "reasoning") return
|
|
512
|
+
appendSample(p.sessionID, p.messageID, {
|
|
513
|
+
at: Date.now(),
|
|
514
|
+
tokens: estimateStreamTokens(String(p.delta ?? "")),
|
|
515
|
+
})
|
|
516
|
+
})
|
|
517
|
+
|
|
518
|
+
const offMessage = context.data.on("message.updated", (evt: any) => {
|
|
519
|
+
const p = propsOf(evt)
|
|
520
|
+
if (p.info?.role !== "assistant") return
|
|
521
|
+
|
|
522
|
+
if (!p.info?.time?.completed) {
|
|
523
|
+
const existing = tracker.messageTimingByID[p.info.id]
|
|
524
|
+
tracker.messageTimingByID[p.info.id] = {
|
|
525
|
+
sessionID: p.sessionID,
|
|
526
|
+
requestStartAt: p.info.time.created,
|
|
527
|
+
firstResponseAt: existing?.firstResponseAt,
|
|
528
|
+
firstTokenAt: existing?.firstTokenAt,
|
|
529
|
+
lastTokenAt: existing?.lastTokenAt,
|
|
530
|
+
}
|
|
531
|
+
bump()
|
|
532
|
+
return
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
delete tracker.messageTimingByID[p.info.id]
|
|
536
|
+
pruneSamples(p.info?.time?.completed)
|
|
537
|
+
bump()
|
|
538
|
+
})
|
|
539
|
+
|
|
540
|
+
const offPart = context.data.on("message.part.updated", (evt: any) => {
|
|
541
|
+
const p = propsOf(evt)
|
|
542
|
+
const part = p.part
|
|
543
|
+
if (!part?.id) return
|
|
544
|
+
if (typeof part.type === "string") partTypeByID.set(part.id, part.type)
|
|
545
|
+
if (part.type !== "tool") return
|
|
546
|
+
if (
|
|
547
|
+
part.state?.status === "running" ||
|
|
548
|
+
part.state?.status === "completed" ||
|
|
549
|
+
part.state?.status === "error"
|
|
550
|
+
) {
|
|
551
|
+
clearLiveSamples(p.sessionID)
|
|
552
|
+
}
|
|
553
|
+
const messageID = part.messageID
|
|
554
|
+
if (!messageID) return
|
|
555
|
+
const timing = tracker.messageTimingByID[messageID]
|
|
556
|
+
if (!timing) return
|
|
557
|
+
if (part.state?.status === "pending") {
|
|
558
|
+
tracker.messageTimingByID[messageID] = {
|
|
559
|
+
...timing,
|
|
560
|
+
firstResponseAt: timing.firstResponseAt ?? p.time,
|
|
561
|
+
}
|
|
562
|
+
bump()
|
|
563
|
+
return
|
|
564
|
+
}
|
|
565
|
+
if (part.state?.status === "running") bump()
|
|
566
|
+
})
|
|
567
|
+
|
|
568
|
+
const timer = setInterval(() => {
|
|
569
|
+
pruneSamples()
|
|
570
|
+
}, 1000)
|
|
571
|
+
|
|
572
|
+
const slotTimer = setInterval(() => {
|
|
573
|
+
void pollMetrics()
|
|
574
|
+
}, SLOT_POLL_MS)
|
|
575
|
+
|
|
576
|
+
try {
|
|
577
|
+
await context.data.location.provider.sync(location)
|
|
578
|
+
providerList = context.data.location.provider.list(location) ?? []
|
|
579
|
+
llamaServerUrls = resolveServerUrls(context.options, providerList, undefined)
|
|
580
|
+
} catch (e) {
|
|
581
|
+
console.error("[oc-ls-stats] resolveServerUrls error:", e)
|
|
582
|
+
llamaServerUrls = ["http://localhost:8080"]
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const unregisterSlot = context.ui.slot({
|
|
586
|
+
append: "prompt.footer.status",
|
|
587
|
+
render: () => <text fg={themeMuted}>{statusText()}</text>,
|
|
588
|
+
})
|
|
589
|
+
|
|
590
|
+
return () => {
|
|
591
|
+
offDelta()
|
|
592
|
+
offMessage()
|
|
593
|
+
offPart()
|
|
594
|
+
clearInterval(timer)
|
|
595
|
+
clearInterval(slotTimer)
|
|
596
|
+
if (typeof unregisterSlot === "function") unregisterSlot()
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const plugin = {
|
|
343
601
|
id: "@troed/oc-ls-stats",
|
|
344
602
|
tui,
|
|
603
|
+
setup: v2Setup,
|
|
345
604
|
}
|
|
346
605
|
|
|
347
606
|
export default plugin
|