@troed/oc-ls-stats 1.0.5 → 1.0.18

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 (3) hide show
  1. package/README.md +22 -13
  2. package/package.json +1 -4
  3. package/tui.tsx +43 -92
package/README.md CHANGED
@@ -16,6 +16,22 @@ I made this for my own usage. If you find it useful as well I'm just happy.
16
16
 
17
17
  _thanks to Tarquinen for their [oc-tps](https://github.com/Tarquinen/oc-tps), which I used as a base although I guess most of the code has now been replaced_
18
18
 
19
+ ## Installation
20
+
21
+ ```bash
22
+ opencode plugin @troed/oc-ls-stats@latest --global
23
+ ```
24
+
25
+ Requires `opencode` `1.3.14` or newer.
26
+
27
+ TUI plugins are loaded from `~/.config/opencode/tui.json`, which after installation should look like this:
28
+
29
+ ```json
30
+ {
31
+ "plugin": ["@troed/oc-ls-stats@latest"]
32
+ }
33
+ ```
34
+
19
35
  ## Display Format
20
36
 
21
37
  The plugin renders a single line in the session prompt right slot:
@@ -23,14 +39,15 @@ The plugin renders a single line in the session prompt right slot:
23
39
  ```
24
40
  1247 tps (PP) -- during prefill
25
41
  25 tps (TG) -- during generation
26
- - tps (TG) -- idle
42
+ - tps (TG) -- idle
43
+ n/a -- unable to reach llama-server
27
44
  ```
28
45
 
29
46
  ## Detection and Calculation
30
47
 
31
48
  ### Server Discovery
32
49
 
33
- The plugin discovers the llama-server URL by reading the OpenCode configuration file (parsed as JSONC) and extracting `baseURL`/`base_url` fields from provider options that contain "localhost". Falls back to `http://localhost:8080`.
50
+ The plugin discovers the llama-server URL by reading the OpenCode configuration via the TUI API and extracting `baseURL`/`base_url` fields from provider options whose name contains "llama" (but excludes providers whose name contains "ollama"). Falls back to `http://localhost:8080` if no matching provider is found.
34
51
 
35
52
  ### Slot Polling
36
53
 
@@ -88,19 +105,11 @@ The following changes to the `/slots` endpoint would improve the plugin's functi
88
105
 
89
106
  5. **Model-agnostic slot data**: The `/slots` endpoint requires a model parameter. Returning all slots without model filtering, or supporting `*` as a wildcard, would simplify discovery when multiple models are loaded.
90
107
 
91
- ## Installation
92
-
93
- ```bash
94
- opencode plugin @troed/oc-ls-stats@latest --global
95
- ```
96
-
97
- Requires `opencode` `1.3.14` or newer.
108
+ ## Source code repo
98
109
 
99
- TUI plugins are loaded from `~/.config/opencode/tui.json`:
110
+ For known issues, posting new ones, forking or contributing:
100
111
 
101
- ```json
102
- {"plugin": ["@troed/oc-ls-stats@latest"]}
103
- ```
112
+ https://codeberg.org/troed/oc-ls-stats
104
113
 
105
114
  ## Debug Logging
106
115
 
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.0.5",
4
+ "version": "1.0.18",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./tui": {
@@ -16,8 +16,5 @@
16
16
  "@opentui/core": "*",
17
17
  "@opentui/solid": "*",
18
18
  "solid-js": "*"
19
- },
20
- "dependencies": {
21
- "@troed/oc-ls-stats": "https://registry.npmjs.org/@troed/oc-ls-stats/-/oc-ls-stats-1.0.3.tgz"
22
19
  }
23
20
  }
package/tui.tsx CHANGED
@@ -3,7 +3,7 @@ import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
3
3
  import { createMemo, createSignal } from "solid-js"
4
4
  import { appendFileSync } from "fs"
5
5
 
6
- const DEBUG_ENABLED = false
6
+ const DEBUG_ENABLED = true
7
7
  const DEBUG_LOG = "/tmp/oc-ls-stats-debug.log"
8
8
  function debug(...args: unknown[]) {
9
9
  if (!DEBUG_ENABLED) return
@@ -28,7 +28,7 @@ type MessageTiming = {
28
28
  lastTokenAt?: number
29
29
  }
30
30
 
31
- type TrackerState = {
31
+ type TrackerState = {
32
32
  streamSamplesBySession: Record<string, StreamSample[]>
33
33
  messageTimingByID: Record<string, MessageTiming>
34
34
  lastPrefillRate: number
@@ -41,7 +41,7 @@ type TrackerState = {
41
41
  generateSlotId: number | null
42
42
  generatePrevNd: number
43
43
  generateStartAt: number
44
- prevNdBySlot: Record<number, { baseline: number; hasIncreased: boolean }>
44
+ prevNdBySlot: Record<number, { baseline: number; hasIncreased: boolean; idTask: number }>
45
45
  failure: string | null
46
46
  }
47
47
 
@@ -49,70 +49,6 @@ function estimateStreamTokens(delta: string) {
49
49
  return Math.max(1, Math.ceil(Buffer.byteLength(delta, "utf8") / 5))
50
50
  }
51
51
 
52
- function parseJSONC(text: string): unknown {
53
- let result = ""
54
- let inString = false
55
- let escape = false
56
- let i = 0
57
-
58
- while (i < text.length) {
59
- const ch = text[i]
60
-
61
- if (escape) {
62
- result += ch
63
- escape = false
64
- i++
65
- continue
66
- }
67
-
68
- if (ch === "\\") {
69
- result += ch
70
- escape = true
71
- i++
72
- continue
73
- }
74
-
75
- if (ch === '"') {
76
- result += ch
77
- inString = !inString
78
- i++
79
- continue
80
- }
81
-
82
- if (inString) {
83
- result += ch
84
- i++
85
- continue
86
- }
87
-
88
- if (ch === "/" && text[i + 1] === "/") {
89
- while (i < text.length && text[i] !== "\n") i++
90
- continue
91
- }
92
-
93
- if (ch === "/" && text[i + 1] === "*") {
94
- i += 2
95
- while (i < text.length - 1 && !(text[i] === "*" && text[i + 1] === "/")) i++
96
- i += 2
97
- result += " "
98
- continue
99
- }
100
-
101
- if (ch === ",") {
102
- const next = text.indexOf(/[\s}\]]/, i + 1)
103
- if (next !== -1 && /[\s}\]]/.test(text[next])) {
104
- i++
105
- continue
106
- }
107
- }
108
-
109
- result += ch
110
- i++
111
- }
112
-
113
- return JSON.parse(result)
114
- }
115
-
116
52
  function stripBaseUrlPath(baseURL: string): string {
117
53
  try {
118
54
  const url = new URL(baseURL)
@@ -123,35 +59,39 @@ function stripBaseUrlPath(baseURL: string): string {
123
59
  }
124
60
 
125
61
  function extractProviderUrls(config: unknown): string[] {
126
- if (!config || typeof config !== "object") return []
62
+ if (!config || typeof config !== "object") { debug("extractProviderUrls: config is null/undefined or not object"); return [] }
127
63
  const obj = config as Record<string, unknown>
128
64
  const provider = obj.provider
129
- if (!provider || typeof provider !== "object") return []
65
+ if (!provider || typeof provider !== "object") { debug("extractProviderUrls: no provider in config"); return [] }
130
66
 
131
67
  const urls: string[] = []
132
- for (const [_key, val] of Object.entries(provider as Record<string, unknown>)) {
68
+ let total = 0
69
+ let matched = 0
70
+ for (const [key, val] of Object.entries(provider as Record<string, unknown>)) {
71
+ total++
133
72
  if (val && typeof val === "object") {
134
73
  const opts = (val as Record<string, unknown>).options
135
74
  if (opts && typeof opts === "object") {
136
75
  const baseURL = (opts as Record<string, unknown>).baseURL || (opts as Record<string, unknown>).base_url
137
- if (typeof baseURL === "string" && baseURL.includes("localhost")) {
76
+ debug(`extractProviderUrls: provider="${key}" baseURL=${baseURL}`)
77
+ if (typeof baseURL === "string" && key.toLowerCase().includes("llama") && !key.toLowerCase().includes("ollama")) {
138
78
  urls.push(stripBaseUrlPath(baseURL))
79
+ matched++
80
+ debug(`extractProviderUrls: MATCH provider="${key}" -> ${urls[urls.length-1]}`)
81
+ } else {
82
+ debug(`extractProviderUrls: SKIP provider="${key}" (llama=${key.toLowerCase().includes("llama")} ollama=${key.toLowerCase().includes("ollama")})`)
139
83
  }
140
84
  }
141
85
  }
142
86
  }
87
+ debug(`extractProviderUrls: total=${total} matched=${matched} urls=${JSON.stringify(urls)}`)
143
88
  return urls
144
89
  }
145
90
 
146
91
  async function loadConfigUrls(api: Parameters<TuiPlugin>[0]): Promise<string[]> {
147
92
  try {
148
- const configPath = api.state.path.config
149
- const resp = await fetch(`file://${configPath}`)
150
- if (!resp.ok) return []
151
- const text = await resp.text()
152
- const config = parseJSONC(text)
153
- return extractProviderUrls(config)
154
- } catch {
93
+ return extractProviderUrls(api.state.config as unknown)
94
+ } catch (e) {
155
95
  return []
156
96
  }
157
97
  }
@@ -280,7 +220,7 @@ const tui: TuiPlugin = async (api) => {
280
220
  bump()
281
221
  }
282
222
 
283
- let llamaServerUrls: string[] = ["http://localhost:8080"]
223
+ let llamaServerUrls: string[] = []
284
224
  let llamaServerModel: string | undefined
285
225
 
286
226
  const pollMetrics = async () => {
@@ -304,17 +244,22 @@ const tui: TuiPlugin = async (api) => {
304
244
  const prevProcessingSlotIds = new Set(Object.keys(tracker.prevNdBySlot).map(Number))
305
245
  const currProcessingSlotIds = new Set<number>()
306
246
 
247
+ debug(`pollMetrics: urls=${JSON.stringify(llamaServerUrls)} model=${model}`)
307
248
  for (const baseUrl of llamaServerUrls) {
249
+ debug(`pollMetrics: polling ${baseUrl}`)
308
250
  const slots = await fetchSlots(baseUrl, model)
251
+ debug(`pollMetrics: ${baseUrl} response=${JSON.stringify(slots)?.slice(0, 500)}`)
309
252
  const slotList = Array.isArray(slots) ? slots : slots ? Object.values(slots) : []
253
+ debug(`pollMetrics: ${baseUrl} slotList.length=${slotList.length}`)
310
254
  if (slotList.length === 0) {
311
255
  tracker.failure = "n/a"
312
256
  bump()
313
257
  continue
314
258
  }
315
259
  tracker.failure = null
260
+ bump()
316
261
 
317
- debug(`poll baseUrl=${baseUrl} slots=${JSON.stringify(slotList)}`)
262
+
318
263
 
319
264
  for (const slot of slotList) {
320
265
  if (slot?.is_processing) {
@@ -334,15 +279,20 @@ const tui: TuiPlugin = async (api) => {
334
279
  if (!slot?.is_processing) continue
335
280
  const slotId = slot.id
336
281
  const nd = slot.next_token?.[0]?.n_decoded ?? 0
282
+ const idTask = slot.id_task ?? 0
337
283
  const entry = tracker.prevNdBySlot[slotId]
338
- const baseline = entry?.baseline ?? nd
339
- const hasIncreased = entry?.hasIncreased ?? false
284
+ const baseline = entry?.idTask === idTask ? entry.baseline : nd
285
+ const hasIncreased = entry?.idTask === idTask ? entry.hasIncreased : false
286
+
287
+ if (entry && entry.idTask !== idTask) {
288
+ debug(`slot ${slotId} id_task changed from ${entry.idTask} to ${idTask}, resetting state`)
289
+ }
340
290
 
341
291
  if (!hasIncreased && nd <= baseline) {
342
292
  prefillSlot = slot
343
293
  break
344
294
  } else if (nd > baseline) {
345
- tracker.prevNdBySlot[slotId] = { baseline, hasIncreased: true }
295
+ tracker.prevNdBySlot[slotId] = { baseline, hasIncreased: true, idTask }
346
296
  generateSlot = slot
347
297
  }
348
298
  }
@@ -351,9 +301,10 @@ const tui: TuiPlugin = async (api) => {
351
301
  if (slot?.is_processing) {
352
302
  const slotId = slot.id
353
303
  const nd = slot.next_token?.[0]?.n_decoded ?? 0
304
+ const idTask = slot.id_task ?? 0
354
305
  const entry = tracker.prevNdBySlot[slotId]
355
- if (entry === undefined) {
356
- tracker.prevNdBySlot[slotId] = { baseline: nd, hasIncreased: false }
306
+ if (entry === undefined || entry.idTask !== idTask) {
307
+ tracker.prevNdBySlot[slotId] = { baseline: nd, hasIncreased: false, idTask }
357
308
  }
358
309
  }
359
310
  }
@@ -375,7 +326,7 @@ const tui: TuiPlugin = async (api) => {
375
326
  tracker.prefillCapturedTokens = nt
376
327
  tracker.prefillStartAt = now
377
328
  tracker.lastPrefillRate = 0
378
- debug(`prefill new slot id=${slotId} nt=${nt}`)
329
+
379
330
  }
380
331
  } else {
381
332
  if (tracker.isPrefilling) {
@@ -396,7 +347,7 @@ const tui: TuiPlugin = async (api) => {
396
347
  const delta = nd - tracker.generatePrevNd
397
348
  if (dt > 0 && delta > 0) {
398
349
  tracker.lastGeneratedTps = delta / dt
399
- debug(`gen slot=${slotId} nd=${nd} prev=${tracker.generatePrevNd} delta=${delta} dt=${dt.toFixed(2)} tps=${tracker.lastGeneratedTps.toFixed(1)}`)
350
+
400
351
  }
401
352
  tracker.generatePrevNd = nd
402
353
  tracker.generateStartAt = now
@@ -405,7 +356,7 @@ const tui: TuiPlugin = async (api) => {
405
356
  tracker.generatePrevNd = nd
406
357
  tracker.generateStartAt = now
407
358
  tracker.lastGeneratedTps = 0
408
- debug(`gen new slot id=${slotId} nd=${nd}`)
359
+
409
360
  }
410
361
  } else {
411
362
  if (tracker.isGenerating) {
@@ -414,7 +365,7 @@ const tui: TuiPlugin = async (api) => {
414
365
  tracker.generateStartAt = 0
415
366
  tracker.lastGeneratedTps = 0
416
367
  genEnded = true
417
- debug(`gen no slot found ending`)
368
+
418
369
  }
419
370
  }
420
371
 
@@ -501,11 +452,11 @@ const tui: TuiPlugin = async (api) => {
501
452
  })
502
453
 
503
454
  try {
504
- if (!llamaServerUrls.length) {
505
- llamaServerUrls = await loadConfigUrls(api)
506
- }
455
+ const configUrls = await loadConfigUrls(api)
456
+ llamaServerUrls = configUrls.length > 0 ? configUrls : ["http://localhost:8080"]
507
457
  } catch (e) {
508
458
  console.error("[oc-ls-stats] loadConfigUrls error:", e)
459
+ llamaServerUrls = ["http://localhost:8080"]
509
460
  }
510
461
 
511
462
  api.slots.register({