@troed/oc-ls-stats 1.3.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 CHANGED
@@ -56,7 +56,7 @@ 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://headless.local:8080" }]
59
+ ["@troed/oc-ls-stats@latest", { "server": "http://<server-host>:8080" }]
60
60
  ]
61
61
  }
62
62
  ```
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.3.1",
4
+ "version": "1.4.1",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "tui.tsx",
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
- if (val && typeof val === "object") {
232
- const opts = (val as Record<string, unknown>).options
233
- if (opts && typeof opts === "object") {
234
- const baseURL = (opts as Record<string, unknown>).baseURL || (opts as Record<string, unknown>).base_url
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 opts = provider.options
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,14 +299,10 @@ 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 opts = provider.options
293
- if (opts && typeof opts === "object") {
294
- const baseURL =
295
- (opts as Record<string, unknown>).baseURL || (opts as Record<string, unknown>).base_url
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
  }
package/tui.tsx CHANGED
@@ -1,7 +1,7 @@
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"
4
+ import { onCleanup, createSignal } from "solid-js"
5
5
  import { backoffDelayMs, processPoll, resolveServerUrls, selectSessionUrls } from "./src/stats.ts"
6
6
 
7
7
  type StreamSample = {
@@ -333,9 +333,274 @@ const tui: TuiPlugin = async (api, options) => {
333
333
  })
334
334
  }
335
335
 
336
- const plugin: TuiPluginModule & { id: string } = {
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 = {
337
601
  id: "@troed/oc-ls-stats",
338
602
  tui,
603
+ setup: v2Setup,
339
604
  }
340
605
 
341
606
  export default plugin