@troed/oc-ls-stats 1.0.17 → 1.1.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.
Files changed (4) hide show
  1. package/README.md +21 -12
  2. package/package.json +4 -1
  3. package/src/stats.ts +208 -0
  4. package/tui.tsx +30 -119
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,7 +39,8 @@ 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
@@ -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,13 +1,16 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@troed/oc-ls-stats",
4
- "version": "1.0.17",
4
+ "version": "1.1.0",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./tui": {
8
8
  "import": "./tui.tsx"
9
9
  }
10
10
  },
11
+ "scripts": {
12
+ "prepack": "npx -y tsx test-stats.ts"
13
+ },
11
14
  "engines": {
12
15
  "opencode": ">=1.3.14"
13
16
  },
package/src/stats.ts ADDED
@@ -0,0 +1,208 @@
1
+ export interface SlotState {
2
+ id: number
3
+ is_processing: boolean
4
+ n_prompt_tokens: number
5
+ next_token: { n_decoded: number }[]
6
+ id_task: number
7
+ }
8
+
9
+ export interface TrackerState {
10
+ prevNdBySlot: Record<number, { prevNd: number; idTask: number; classification: "TG" | "PP" | "neither" }>
11
+ prevPromptTokensBySlot: Record<number, { tokens: number; idTask: number }>
12
+ isPrefilling: boolean
13
+ isGenerating: boolean
14
+ prefillSlotId: number | null
15
+ prefillCapturedTokens: number | null
16
+ prefillStartAt: number
17
+ lastPrefillRate: number
18
+ generateSlotId: number | null
19
+ generatePrevNd: number
20
+ generateStartAt: number
21
+ lastGeneratedTps: number
22
+ }
23
+
24
+ export interface ClassificationResult {
25
+ slotId: number
26
+ nd: number
27
+ prevNd: number
28
+ nt: number
29
+ prevNt: number
30
+ classification: "TG" | "PP" | "neither"
31
+ }
32
+
33
+ export interface PollResult {
34
+ classifications: ClassificationResult[]
35
+ isPrefilling: boolean
36
+ isGenerating: boolean
37
+ lastPrefillRate: number
38
+ lastGeneratedTps: number
39
+ ppEnded: boolean
40
+ tgEnded: boolean
41
+ }
42
+
43
+ export function classifySlot(
44
+ slot: SlotState,
45
+ tracker: TrackerState,
46
+ ): ClassificationResult {
47
+ const slotId = slot.id
48
+ const nd = slot.next_token?.[0]?.n_decoded ?? 0
49
+ const nt = slot.n_prompt_tokens ?? 0
50
+ const idTask = slot.id_task ?? 0
51
+
52
+ const ndEntry = tracker.prevNdBySlot[slotId]
53
+ const ntEntry = tracker.prevPromptTokensBySlot[slotId]
54
+
55
+ // Check if we have valid baseline for this slot/task
56
+ const hasBaseline = ndEntry && ndEntry.idTask === idTask && ntEntry && ntEntry.idTask === idTask
57
+ const baselineNd = hasBaseline ? ndEntry.prevNd : nd
58
+ const baselineNt = hasBaseline ? ntEntry.tokens : nt
59
+
60
+ // Check if values have reset (dropped below baseline) - indicates slot reuse or new request
61
+ const hasReset = hasBaseline && (nd < baselineNd || nt < baselineNt)
62
+
63
+ let classification: "TG" | "PP" | "neither" = "neither"
64
+ let prevNd = nd
65
+ let prevNt = nt
66
+
67
+ if (!hasBaseline || hasReset) {
68
+ // First time seeing this slot/task, or values have reset
69
+ // Use heuristic: if n_decoded > 0, we likely caught it mid-generation
70
+ if (nd > 0) {
71
+ classification = "TG"
72
+ } else {
73
+ classification = "PP"
74
+ }
75
+ } else {
76
+ // Compare against baseline values
77
+ if (nd > baselineNd) {
78
+ classification = "TG"
79
+ } else if (nt > baselineNt) {
80
+ classification = "PP"
81
+ } else {
82
+ // Neither has increased from baseline - persist previous classification
83
+ // This handles frequent polling where we don't see increases every poll
84
+ const prevClassification = ndEntry?.classification
85
+ if (prevClassification) {
86
+ classification = prevClassification
87
+ }
88
+ }
89
+ prevNd = baselineNd
90
+ prevNt = baselineNt
91
+ }
92
+
93
+ return { slotId, nd, prevNd, nt, prevNt, classification }
94
+ }
95
+
96
+ export function processPoll(
97
+ slots: SlotState[],
98
+ tracker: TrackerState,
99
+ now: number = Date.now(),
100
+ ): PollResult {
101
+ const processingSlots = slots.filter(s => s.is_processing)
102
+ const processingSlotIds = new Set(processingSlots.map(s => s.id))
103
+
104
+ // Clean up tracking state for slots that went idle
105
+ for (const key of Object.keys(tracker.prevNdBySlot)) {
106
+ const slotId = Number(key)
107
+ if (!processingSlotIds.has(slotId)) {
108
+ delete tracker.prevNdBySlot[slotId]
109
+ }
110
+ }
111
+ for (const key of Object.keys(tracker.prevPromptTokensBySlot)) {
112
+ const slotId = Number(key)
113
+ if (!processingSlotIds.has(slotId)) {
114
+ delete tracker.prevPromptTokensBySlot[slotId]
115
+ }
116
+ }
117
+
118
+ // Classify each processing slot
119
+ const classifications: ClassificationResult[] = []
120
+ let prefillSlot: ClassificationResult | null = null
121
+ let generateSlot: ClassificationResult | null = null
122
+
123
+ for (const slot of processingSlots) {
124
+ const result = classifySlot(slot, tracker)
125
+ classifications.push(result)
126
+
127
+ if (result.classification === "TG") {
128
+ generateSlot = result
129
+ } else if (result.classification === "PP") {
130
+ prefillSlot = result
131
+ }
132
+
133
+ // Update tracker state - store baseline values and classification
134
+ tracker.prevNdBySlot[slot.id] = { prevNd: result.nd, idTask: slot.id_task, classification: result.classification }
135
+ tracker.prevPromptTokensBySlot[slot.id] = { tokens: result.nt, idTask: slot.id_task }
136
+ }
137
+
138
+ let anyPrefilling = false
139
+ let anyGenerating = false
140
+ let ppEnded = false
141
+ let tgEnded = false
142
+
143
+ // Handle PP phase
144
+ if (prefillSlot) {
145
+ anyPrefilling = true
146
+ const nt = prefillSlot.nt
147
+ if (tracker.prefillSlotId === prefillSlot.slotId) {
148
+ const dt = (now - tracker.prefillStartAt) / 1000
149
+ const delta = nt - (tracker.prefillCapturedTokens ?? 0)
150
+ if (dt > 0 && delta > 0) {
151
+ tracker.lastPrefillRate = delta / dt
152
+ }
153
+ } else {
154
+ tracker.prefillSlotId = prefillSlot.slotId
155
+ tracker.prefillCapturedTokens = nt
156
+ tracker.prefillStartAt = now
157
+ tracker.lastPrefillRate = 0
158
+ }
159
+ } else if (processingSlotIds.size > 0 && !generateSlot) {
160
+ anyPrefilling = tracker.isPrefilling
161
+ } else if (tracker.isPrefilling) {
162
+ tracker.prefillSlotId = null
163
+ tracker.prefillCapturedTokens = null
164
+ tracker.prefillStartAt = 0
165
+ ppEnded = true
166
+ }
167
+
168
+ // Handle TG phase
169
+ if (generateSlot) {
170
+ anyGenerating = true
171
+ const nd = generateSlot.nd
172
+ if (tracker.generateSlotId === generateSlot.slotId) {
173
+ const dt = (now - tracker.generateStartAt) / 1000
174
+ const delta = nd - tracker.generatePrevNd
175
+ if (dt > 0 && delta > 0) {
176
+ tracker.lastGeneratedTps = delta / dt
177
+ }
178
+ tracker.generatePrevNd = nd
179
+ tracker.generateStartAt = now
180
+ } else {
181
+ tracker.generateSlotId = generateSlot.slotId
182
+ tracker.generatePrevNd = nd
183
+ tracker.generateStartAt = now
184
+ tracker.lastGeneratedTps = 0
185
+ }
186
+ } else if (processingSlotIds.size > 0 && !prefillSlot) {
187
+ anyGenerating = tracker.isGenerating
188
+ } else if (tracker.isGenerating) {
189
+ tracker.generateSlotId = null
190
+ tracker.generatePrevNd = 0
191
+ tracker.generateStartAt = 0
192
+ tracker.lastGeneratedTps = 0
193
+ tgEnded = true
194
+ }
195
+
196
+ tracker.isPrefilling = anyPrefilling
197
+ tracker.isGenerating = anyGenerating
198
+
199
+ return {
200
+ classifications,
201
+ isPrefilling: tracker.isPrefilling,
202
+ isGenerating: tracker.isGenerating,
203
+ lastPrefillRate: tracker.lastPrefillRate,
204
+ lastGeneratedTps: tracker.lastGeneratedTps,
205
+ ppEnded,
206
+ tgEnded,
207
+ }
208
+ }
package/tui.tsx CHANGED
@@ -2,6 +2,7 @@
2
2
  import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
3
3
  import { createMemo, createSignal } from "solid-js"
4
4
  import { appendFileSync } from "fs"
5
+ import { processPoll } from "./src/stats.ts"
5
6
 
6
7
  const DEBUG_ENABLED = false
7
8
  const DEBUG_LOG = "/tmp/oc-ls-stats-debug.log"
@@ -28,7 +29,7 @@ type MessageTiming = {
28
29
  lastTokenAt?: number
29
30
  }
30
31
 
31
- type TrackerState = {
32
+ type TrackerState = {
32
33
  streamSamplesBySession: Record<string, StreamSample[]>
33
34
  messageTimingByID: Record<string, MessageTiming>
34
35
  lastPrefillRate: number
@@ -41,7 +42,8 @@ type TrackerState = {
41
42
  generateSlotId: number | null
42
43
  generatePrevNd: number
43
44
  generateStartAt: number
44
- prevNdBySlot: Record<number, { baseline: number; hasIncreased: boolean }>
45
+ prevNdBySlot: Record<number, { prevNd: number; idTask: number; classification: "TG" | "PP" | "neither" }>
46
+ prevPromptTokensBySlot: Record<number, { tokens: number; idTask: number }>
45
47
  failure: string | null
46
48
  }
47
49
 
@@ -59,23 +61,32 @@ function stripBaseUrlPath(baseURL: string): string {
59
61
  }
60
62
 
61
63
  function extractProviderUrls(config: unknown): string[] {
62
- if (!config || typeof config !== "object") return []
64
+ if (!config || typeof config !== "object") { debug("extractProviderUrls: config is null/undefined or not object"); return [] }
63
65
  const obj = config as Record<string, unknown>
64
66
  const provider = obj.provider
65
- if (!provider || typeof provider !== "object") return []
67
+ if (!provider || typeof provider !== "object") { debug("extractProviderUrls: no provider in config"); return [] }
66
68
 
67
69
  const urls: string[] = []
70
+ let total = 0
71
+ let matched = 0
68
72
  for (const [key, val] of Object.entries(provider as Record<string, unknown>)) {
73
+ total++
69
74
  if (val && typeof val === "object") {
70
75
  const opts = (val as Record<string, unknown>).options
71
76
  if (opts && typeof opts === "object") {
72
77
  const baseURL = (opts as Record<string, unknown>).baseURL || (opts as Record<string, unknown>).base_url
78
+ debug(`extractProviderUrls: provider="${key}" baseURL=${baseURL}`)
73
79
  if (typeof baseURL === "string" && key.toLowerCase().includes("llama") && !key.toLowerCase().includes("ollama")) {
74
80
  urls.push(stripBaseUrlPath(baseURL))
81
+ matched++
82
+ debug(`extractProviderUrls: MATCH provider="${key}" -> ${urls[urls.length-1]}`)
83
+ } else {
84
+ debug(`extractProviderUrls: SKIP provider="${key}" (llama=${key.toLowerCase().includes("llama")} ollama=${key.toLowerCase().includes("ollama")})`)
75
85
  }
76
86
  }
77
87
  }
78
88
  }
89
+ debug(`extractProviderUrls: total=${total} matched=${matched} urls=${JSON.stringify(urls)}`)
79
90
  return urls
80
91
  }
81
92
 
@@ -163,6 +174,7 @@ const tui: TuiPlugin = async (api) => {
163
174
  generatePrevNd: 0,
164
175
  generateStartAt: 0,
165
176
  prevNdBySlot: {},
177
+ prevPromptTokensBySlot: {},
166
178
  failure: null,
167
179
  }
168
180
  const [version, setVersion] = createSignal(0)
@@ -228,16 +240,13 @@ const tui: TuiPlugin = async (api) => {
228
240
  }
229
241
  }
230
242
 
231
- let anyPrefilling = false
232
- let anyGenerating = false
233
- let genEnded = false
234
-
235
- const prevProcessingSlotIds = new Set(Object.keys(tracker.prevNdBySlot).map(Number))
236
- const currProcessingSlotIds = new Set<number>()
237
-
243
+ debug(`pollMetrics: urls=${JSON.stringify(llamaServerUrls)} model=${model}`)
238
244
  for (const baseUrl of llamaServerUrls) {
245
+ debug(`pollMetrics: polling ${baseUrl}`)
239
246
  const slots = await fetchSlots(baseUrl, model)
247
+ debug(`pollMetrics: ${baseUrl} response=${JSON.stringify(slots)}`)
240
248
  const slotList = Array.isArray(slots) ? slots : slots ? Object.values(slots) : []
249
+ debug(`pollMetrics: ${baseUrl} slotList.length=${slotList.length}`)
241
250
  if (slotList.length === 0) {
242
251
  tracker.failure = "n/a"
243
252
  bump()
@@ -246,121 +255,23 @@ const tui: TuiPlugin = async (api) => {
246
255
  tracker.failure = null
247
256
  bump()
248
257
 
249
-
258
+ const result = processPoll(slotList, tracker)
250
259
 
251
- for (const slot of slotList) {
252
- if (slot?.is_processing) {
253
- currProcessingSlotIds.add(slot.id)
254
- }
260
+ if (result.isPrefilling) {
261
+ debug(`PP rate=${Math.round(result.lastPrefillRate)} tps`)
255
262
  }
256
-
257
- for (const slotId of prevProcessingSlotIds) {
258
- if (!currProcessingSlotIds.has(slotId)) {
259
- const prev = tracker.prevNdBySlot[slotId]
260
- if (prev) {
261
- prev.hasIncreased = false
262
- prev.baseline = 0
263
- } else {
264
- delete tracker.prevNdBySlot[slotId]
265
- }
266
- }
267
- }
268
-
269
- let prefillSlot: any = null
270
- let generateSlot: any = null
271
- for (const slot of slotList) {
272
- if (!slot?.is_processing) continue
273
- const slotId = slot.id
274
- const nd = slot.next_token?.[0]?.n_decoded ?? 0
275
- const entry = tracker.prevNdBySlot[slotId]
276
- const baseline = entry?.baseline ?? nd
277
- const hasIncreased = entry?.hasIncreased ?? false
278
-
279
- if (!hasIncreased && nd <= baseline) {
280
- prefillSlot = slot
281
- break
282
- } else if (nd > baseline) {
283
- tracker.prevNdBySlot[slotId] = { baseline, hasIncreased: true }
284
- generateSlot = slot
285
- }
286
- }
287
-
288
- for (const slot of slotList) {
289
- if (slot?.is_processing) {
290
- const slotId = slot.id
291
- const nd = slot.next_token?.[0]?.n_decoded ?? 0
292
- const entry = tracker.prevNdBySlot[slotId]
293
- if (entry === undefined) {
294
- tracker.prevNdBySlot[slotId] = { baseline: nd, hasIncreased: false }
295
- }
296
- }
263
+ if (result.isGenerating) {
264
+ debug(`TG rate=${Math.round(result.lastGeneratedTps)} tps`)
297
265
  }
298
-
299
- if (prefillSlot) {
300
- anyPrefilling = true
301
- const slotId = prefillSlot.id
302
- const now = Date.now()
303
- const nt = prefillSlot.n_prompt_tokens ?? 0
304
-
305
- if (tracker.prefillSlotId === slotId) {
306
- const dt = (now - tracker.prefillStartAt) / 1000
307
- const delta = nt - tracker.prefillCapturedTokens!
308
- if (dt > 0 && delta > 0) {
309
- tracker.lastPrefillRate = delta / dt
310
- }
311
- } else {
312
- tracker.prefillSlotId = slotId
313
- tracker.prefillCapturedTokens = nt
314
- tracker.prefillStartAt = now
315
- tracker.lastPrefillRate = 0
316
-
317
- }
318
- } else {
319
- if (tracker.isPrefilling) {
320
- tracker.prefillSlotId = null
321
- tracker.prefillCapturedTokens = null
322
- tracker.prefillStartAt = 0
323
- }
266
+ if (result.ppEnded) {
267
+ debug(`PP ended rate=${Math.round(result.lastPrefillRate)} tps`)
324
268
  }
325
-
326
- if (generateSlot) {
327
- anyGenerating = true
328
- const slotId = generateSlot.id
329
- const now = Date.now()
330
- const nd = generateSlot.next_token?.[0]?.n_decoded ?? 0
331
-
332
- if (tracker.generateSlotId === slotId) {
333
- const dt = (now - tracker.generateStartAt) / 1000
334
- const delta = nd - tracker.generatePrevNd
335
- if (dt > 0 && delta > 0) {
336
- tracker.lastGeneratedTps = delta / dt
337
-
338
- }
339
- tracker.generatePrevNd = nd
340
- tracker.generateStartAt = now
341
- } else {
342
- tracker.generateSlotId = slotId
343
- tracker.generatePrevNd = nd
344
- tracker.generateStartAt = now
345
- tracker.lastGeneratedTps = 0
346
-
347
- }
348
- } else {
349
- if (tracker.isGenerating) {
350
- tracker.generateSlotId = null
351
- tracker.generatePrevNd = 0
352
- tracker.generateStartAt = 0
353
- tracker.lastGeneratedTps = 0
354
- genEnded = true
355
-
356
- }
269
+ if (result.tgEnded) {
270
+ debug(`TG ended rate=${Math.round(result.lastGeneratedTps)} tps`)
357
271
  }
358
-
359
- tracker.isPrefilling = anyPrefilling
360
- tracker.isGenerating = anyGenerating
361
272
  }
362
273
 
363
- if (tracker.lastPrefillRate > 0 || tracker.lastGeneratedTps > 0 || genEnded) {
274
+ if (tracker.lastPrefillRate > 0 || tracker.lastGeneratedTps > 0) {
364
275
  bump()
365
276
  }
366
277
  }