@troed/oc-ls-stats 1.2.1 → 1.3.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
@@ -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
- 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.
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://headless.local: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://codeberg.org/troed/oc-ls-stats
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.2.1",
4
+ "version": "1.3.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-stats.ts"
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,95 @@ 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
+ export function extractProviderUrls(config: unknown): string[] {
224
+ if (!config || typeof config !== "object") return []
225
+ const obj = config as Record<string, unknown>
226
+ const provider = obj.provider
227
+ if (!provider || typeof provider !== "object") return []
228
+
229
+ const urls: string[] = []
230
+ 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
+ }
239
+ }
240
+ }
241
+ return urls
242
+ }
243
+
244
+ export function extractProviderUrlsFromList(providers: unknown): string[] {
245
+ if (!Array.isArray(providers)) return []
246
+ const urls: string[] = []
247
+ for (const entry of providers) {
248
+ if (!entry || typeof entry !== "object") continue
249
+ const provider = entry as Record<string, unknown>
250
+ const id = typeof provider.id === "string" ? provider.id.toLowerCase() : ""
251
+ const name = typeof provider.name === "string" ? provider.name.toLowerCase() : ""
252
+ const hay = `${id} ${name}`
253
+ 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
257
+ if (typeof baseURL === "string") {
258
+ urls.push(stripBaseUrlPath(baseURL))
259
+ }
260
+ }
261
+ return urls
262
+ }
263
+
264
+ export function resolveServerUrls(options: unknown, providers: unknown, config: unknown): string[] {
265
+ const opts = options && typeof options === "object" ? (options as Record<string, unknown>) : undefined
266
+ const server = opts?.server
267
+ const explicit = typeof server === "string" && server.trim() !== "" ? stripBaseUrlPath(server) : undefined
268
+ if (explicit && /^https?:\/\//.test(explicit)) {
269
+ return [explicit]
270
+ }
271
+ if (server !== undefined) {
272
+ console.warn("[oc-ls-stats] ignoring invalid 'server' plugin option, falling back to provider detection")
273
+ }
274
+ const detected = [...new Set(extractProviderUrlsFromList(providers))]
275
+ if (detected.length > 0) return detected
276
+ const legacy = [...new Set(extractProviderUrls(config))]
277
+ return legacy.length > 0 ? legacy : ["http://localhost:8080"]
278
+ }
279
+
280
+ export function selectSessionUrls(
281
+ candidates: string[],
282
+ providers: unknown,
283
+ providerID: string | undefined,
284
+ ): string[] {
285
+ if (typeof providerID !== "string" || providerID.trim() === "" || candidates.length === 0)
286
+ return candidates
287
+ if (!Array.isArray(providers) || providers.length === 0) return candidates
288
+ for (const entry of providers) {
289
+ if (!entry || typeof entry !== "object") continue
290
+ const provider = entry as Record<string, unknown>
291
+ 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
+ }
300
+ }
301
+ return []
302
+ }
303
+ return []
304
+ }
package/tui.tsx CHANGED
@@ -2,7 +2,7 @@
2
2
  import type { TextRenderable } from "@opentui/core"
3
3
  import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
4
4
  import { onCleanup } from "solid-js"
5
- import { processPoll } from "./src/stats.ts"
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
- for (const baseUrl of llamaServerUrls) {
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
- const slotList = Array.isArray(slots) ? slots : slots ? Object.values(slots) : []
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
- const configUrls = await loadConfigUrls(api)
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] loadConfigUrls error:", e)
318
+ console.error("[oc-ls-stats] resolveServerUrls error:", e)
325
319
  llamaServerUrls = ["http://localhost:8080"]
326
320
  }
327
321