opencode-usage-insights 0.2.0 → 0.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
@@ -8,13 +8,15 @@
8
8
  **See what each turn costs.** OpenCode reports the cost of each request, but the
9
9
  TUI no longer shows it. This plugin puts cost back in view in the **TUI** and in
10
10
  **OpenCode Desktop**: a telemetry line after every turn, the session's running
11
- spend and turn history, and an interactive `/usage` panel with charged cost,
11
+ spend and turn history, and an interactive `/usage-insights` panel with charged cost,
12
12
  list-price estimates, tokens, prompt-cache reuse and latency.
13
13
 
14
14
  ![The telemetry line after a turn](docs/images/line.png)
15
15
 
16
16
  Everything stays in your OpenCode server: no prompts or responses are stored,
17
- and the plugin sends nothing to a third party. The TUI and Desktop both read the
17
+ and the plugin sends nothing to a third party. The Go view reads the usage
18
+ limits the host already fetched from the OpenCode Console; the plugin never
19
+ sees the API key. The TUI and Desktop both read the
18
20
  same recorder through an authenticated server RPC, so a client connected to a
19
21
  remote server shows that server's data.
20
22
 
@@ -25,20 +27,24 @@ remote server shows that server's data.
25
27
  model and configured provider, and warnings when the prompt cache or the
26
28
  provider changed. It belongs to finished work, so it stays hidden while a
27
29
  turn is running.
28
- - **The `/usage` panel**: nine views — `overview`, `models`, `providers`,
29
- `cache`, `periods`, `latency`, `sessions`, `turns`, `db` — over five ranges
30
- (`session`, `today`, `7d`, `30d`, `all`), with drill-downs, sorting, filters
31
- and remembered state. Keyboard-driven in the TUI; the same views with desktop
32
- controls in OpenCode Desktop. `/usage models 7d`, `/usage turns 7d`.
30
+ - **The `/usage-insights` panel**: ten views — `overview`, `models`,
31
+ `providers`, `cache`, `periods`, `latency`, `sessions`, `turns`, `db`, `go` —
32
+ over five ranges (`session`, `today`, `7d`, `30d`, `all`), with drill-downs,
33
+ sorting, filters and remembered state. Keyboard-driven in the TUI; the same
34
+ views with desktop controls in OpenCode Desktop. `/usage-insights models 7d`,
35
+ `/usage-insights go`.
33
36
  - **The Desktop header badge and panels**: a spend badge in the session header,
34
37
  next to the peak/off-peak badge; clicking it opens **Turns insights**, the
35
- session history. **Usage insights** holds the nine views and opens from
36
- `/usage`. The Desktop window never opens SQLite: the server's worker serves
38
+ session history. **Usage insights** holds the ten views and opens from
39
+ `/usage-insights`. The Desktop window never opens SQLite: the server's worker serves
37
40
  the panels and history over RPC.
38
41
  - **The TUI sidebar**: the session's spend and last turns, in the same buckets
39
42
  as the line — time, provider, wall duration, prompt volumes, then
40
- `hit · tok/s · cost`. The duration is first request to last completion: tool
41
- waits inside the turn count, idle gaps do not.
43
+ `hit · tok/s · cost`. When OpenCode Go is active, a compact block above the
44
+ summary names the subscription and shows the 5-hour/weekly/monthly
45
+ percentages, the monthly forecast and the renewal date. The duration is
46
+ first request to last completion: tool waits inside the turn count, idle gaps
47
+ do not.
42
48
  - **The record** (server): every step with tokens, charged cost, the list-price
43
49
  estimate for `$0`, timings, finish reason and provider/model IDs; prompts,
44
50
  lifecycle, compaction and `session.usage.recorded` events too.
@@ -117,11 +123,13 @@ bun run build
117
123
  For GUI development, keep `bun run dev:gui` running in another terminal; each
118
124
  rebuild reloads the Desktop GUI in every window without restarting the server.
119
125
  Configuration changes reload on their own; after changing server or TUI source,
120
- restart the background service with `opencode service restart`.
126
+ restart the background service with `opencode service restart`. The host's own
127
+ `/usage` command remains the place for the Console budget details; the plugin's
128
+ command is `/usage-insights`.
121
129
 
122
130
  Send a prompt to verify: the TUI line appears above the composer when the turn
123
- finishes, the Desktop badge appears in the session header, and `/usage` (alias
124
- `/insights`) opens the panel.
131
+ finishes, the Desktop badge appears in the session header, and `/usage-insights`
132
+ (alias `/insights`) opens the panel.
125
133
 
126
134
  ## The TUI line
127
135
 
@@ -179,20 +187,22 @@ shows the finished turn's spend (`$0.0210` or `≈$0.0210`):
179
187
  $0.0210
180
188
  ```
181
189
 
182
- Hovering shows the full telemetry line. Clicking it opens **Turns insights**.
183
- The badge follows the TUI line and hides while a turn is running; it reappears
184
- with the final amount. The `fields`, `labels`, `turnTotals` and `pricing`
185
- options apply to the line, badge tooltip and panel; `fields.cost: false` hides
186
- the badge as well.
190
+ Hovering shows the full telemetry line. While a turn runs the badge shows the
191
+ session's accumulated spend instead (`≈$1.90`) and returns to the turn's
192
+ spend when it ends. Clicking it opens **Turns insights**. The `fields`, `labels`,
193
+ `turnTotals` and `pricing` options apply to the line, badge tooltip and panel;
194
+ `fields.cost: false` hides the badge, and `fields.session: false` keeps it
195
+ hidden while a turn runs.
187
196
 
188
197
  ### Usage insights and Turns insights
189
198
 
190
- `/usage` (and the hidden `/insights` alias) opens the **Usage insights** panel
191
- in the side region. It has the same nine views, five ranges, drill-downs,
192
- sorting and filters as the TUI, plus the database view's maintenance buttons.
193
- The **Turns insights** tab shows the current session's history. `/usage turns`
194
- opens the same history inside **Usage insights**, where the session/all-sessions
195
- scope is available. Both panels have the inverse shortcut: **Usage insights**
199
+ `/usage-insights` (and the hidden `/insights` alias) opens the **Usage
200
+ insights** panel in the side region. It has the same ten views, five ranges,
201
+ drill-downs, sorting and filters as the TUI, plus the database view's
202
+ maintenance buttons. The Desktop view menu lists **OpenCode Go** immediately
203
+ after **Overview**. The **Turns insights** tab shows the current session's
204
+ history. `/usage-insights turns` opens the same history inside **Usage insights**,
205
+ where the session/all-sessions scope is available. Both panels have the inverse shortcut: **Usage insights**
196
206
  has an **Open turns insights** footer button, and **Turns insights** has
197
207
  **Open usage insights**.
198
208
 
@@ -202,7 +212,7 @@ are:
202
212
  | Where | What it shows |
203
213
  | --- | --- |
204
214
  | Session header badge | The turn spend and the full line on hover; click opens Turns insights. |
205
- | Turns insights tab | The current session's complete history. `/usage turns` adds the session/all-sessions scope. |
215
+ | Turns insights tab | The current session's complete history, with the same compact Go forecast block as the TUI sidebar. `/usage-insights turns` adds the session/all-sessions scope. |
206
216
  | Side panel `+` menu | **Usage insights** and **Turns insights** launchers. |
207
217
 
208
218
  The panel state is stored separately from the TUI: opening the Desktop panel
@@ -277,16 +287,18 @@ estimates and disables the backfill without deleting data.
277
287
 
278
288
  ## The TUI panel
279
289
 
280
- `/usage [view] [range]` opens the panel (`/usage` alone opens the last view, or
281
- `overview` over `all` the first time). While the panel is open it owns input, so
282
- the prompt cannot take the command again: `escape` closes it, `f` toggles full
283
- screen, and the palette entry (`ctrl+p` → "Usage insights") toggles it closed.
284
- With the composer focused, `/usage` with no arguments also toggles it closed,
285
- and any argument — including an unknown token, which is ignored — keeps it open.
290
+ `/usage-insights [view] [range]` opens the panel (`/usage-insights` alone opens
291
+ the last view, or `overview` over `all` the first time). While the panel is open
292
+ it owns input, so the prompt cannot take the command again: `escape` closes it,
293
+ `f` toggles full screen, and the palette entry (`ctrl+p` → "Usage insights")
294
+ toggles it closed. With the composer focused, `/usage-insights` with no
295
+ arguments also toggles it closed, and any argument — including an unknown token,
296
+ which is ignored — keeps it open. `/usage` stays the host's native usage-limits
297
+ dialog.
286
298
  There is no default key binding — the command is palette-only, so it never
287
299
  shadows a key you use.
288
300
 
289
- ![The /usage providers view](docs/images/panel-providers.png)
301
+ ![The /usage-insights providers view](docs/images/panel-providers.png)
290
302
 
291
303
  The view bar at the top names every view and brackets the active one; `?` opens
292
304
  a help overlay that repeats the keys and defines every number.
@@ -299,14 +311,14 @@ a help overlay that repeats the keys and defines every number.
299
311
  | `pageup` `pagedown` / `home` `end` | Move by ten rows / to the first or last row. |
300
312
  | `enter` | Drill into the row: a model → the providers it ran through and their latency; a provider → the models it served and its latency; a session → its turns; a period → the providers of the period. In `db`, prune the steps recorded before the selected retention's cutoff date, or wipe every recorded step, session and event from the last row (asks first). |
301
313
  | `backspace` | Go back from a drill-down. |
302
- | `1`–`9` / `[` `]` | Pick a view (`9` is `db`) / cycle views. |
314
+ | `1`–`9` `0` / `[` `]` | Pick a view (`9` is `db`, `0` is `go`) / cycle views. |
303
315
  | `t` / `shift+t` | Next / previous range. |
304
316
  | `s` / `shift+s` | Cycle the sort column / reverse it. |
305
317
  | `b` | `periods` bucket: day → week → month. |
306
318
  | `a` | `turns` scope: this session ↔ every session. |
307
319
  | `m` `p` | Filter by model or by **provider** (a picker of the values actually observed). |
308
320
  | `x` | Clear the filters. |
309
- | `r` | Re-read the database. |
321
+ | `r` | Re-read the database; in `go`, refresh the live allowance. |
310
322
  | `e` | `db`: backfill list-price estimates for the `$0` steps that have none (asks first; uses today's model list). |
311
323
  | `v` | `db`: compact the file, giving the space of deleted rows back. |
312
324
  | `?` | Help overlay. |
@@ -328,6 +340,7 @@ durable storage, so the panel reopens where it was left.
328
340
  | `sessions` | Each session with steps, prompts, tokens, `hit`, cost (including compaction/title usage, named on the detail line), its directory and how many models it used; subagent sessions are indented under their parent and rolled up. |
329
341
  | `turns` | The per-prompt history: one line per finished turn, rendered exactly like the live line. Cost is assistant steps only. `a` widens it to every session, titled. |
330
342
  | `db` | File name (full path with `exposePaths: true`), contents and age. The retention table lists `30`/`90`/`365`-day prunes with step counts and cutoff; `↑`/`↓` + `enter` prunes from a cutoff, and the row below the table wipes every recorded step, session and event (both ask first). `v` reclaims space. It counts `$0` steps without an estimate; `e` backfills at today's list price. |
343
+ | `go` | Live **OpenCode Go** allowance: the 5-hour (`rolling`), weekly and monthly meters, their reset countdowns, and a forecast of the monthly percentage at its renewal from the cycle's average pace. It also names the exact renewal instant. Read by the client from the host's usage-limits endpoint; no database rows. The TUI sidebar and the Desktop Turns insights tab carry the compact form, and the Desktop view draws the current-versus-forecast bars. |
331
344
 
332
345
  The panel sums the stored per-step buckets over the selected range, so a number
333
346
  read in one place means the same in the other: `prompt` is everything the
@@ -360,6 +373,52 @@ with the cache the switch actually cost, which only a provider switch can: two
360
373
  models never share a cache to lose. The panel's `?` overlay defines every
361
374
  number in place.
362
375
 
376
+ ### The Go forecast
377
+
378
+ OpenCode 2.4 already has a native **Usage** dialog: the Desktop command
379
+ **View usage** lists the Go rolling/weekly/monthly meters and the Console
380
+ budgets; the TUI `/usage` dialog lists the Console budgets and the remaining
381
+ allowance per model. The plugin's `go` view adds what that dialog does not
382
+ show: the monthly **forecast**, the exact renewal instant, and a chart in the
383
+ Desktop panel. `/usage` remains the host's command; the plugin command is
384
+ `/usage-insights`.
385
+
386
+ The forecast uses the average pace of the current monthly cycle:
387
+
388
+ ```text
389
+ start = monthly resetsAt - 1 calendar month (inferred)
390
+ elapsed = now - start
391
+ rate = percent / elapsedDays
392
+ projected = percent + rate * remainingDays
393
+ exhaustAt = now + (100 - percent) / rate
394
+ ```
395
+
396
+ It is a percentage projection, not a dollar amount or a token estimate. The
397
+ host exposes whole-number percentages and the reset instant, but not the start
398
+ of the cycle, so the start is inferred. When nothing has been used yet it reads
399
+ `no monthly usage yet`; when the cycle is younger than 30 minutes it says it is
400
+ too early to project. The `renews` line below the forecast is the exact
401
+ `monthly.resetsAt` in local time, with its countdown.
402
+
403
+ The TUI sidebar and the Desktop **Turns insights** tab show the compact form:
404
+
405
+ ```text
406
+ OpenCode Go
407
+ 5h 2% · week 9% · month 40%
408
+ forecast ~77% at reset
409
+ renews 15 Dec 22:06
410
+ ```
411
+
412
+ The values come from the host's local usage-limits endpoint. The plugin never
413
+ reads the Console API key and makes no external request; `quota: "off"` hides
414
+ the view, the TUI sidebar block and the Desktop Turns block, and stops the poll.
415
+
416
+ The host payload names the meters but not the paid plan (Go, Go Plus or Go
417
+ Teams); the UI therefore uses the provider display name or `quotaName`, and
418
+ falls back to the full `OpenCode Go`. Set `quotaName` to your plan name if you
419
+ want Go Plus/Teams reflected. The name line is shown above the numbers in both
420
+ sidebars and in the `go` view header.
421
+
363
422
  ## Configuration
364
423
 
365
424
  Options apply to all three parts (each side reads the ones it needs):
@@ -372,7 +431,9 @@ Options apply to all three parts (each side reads the ones it needs):
372
431
  | `pricing` | `"auto"` | `"off"` disables list-price estimates everywhere: no new `list_cost` records, no `≈` on the line, badge, panel or sidebar, and no historical backfill. Charged money is unaffected. |
373
432
  | `sidebar` | `true` | TUI-only: show the session summary and the per-prompt history in the session sidebar. The Desktop history is the Turns insights tab. |
374
433
  | `sidebarTurns` | `8` | How many turns the TUI sidebar and the Desktop Turns insights tab show (`1`–`50`; values outside are clamped). |
375
- | `panel` | `true` | Show the `/usage` statistics panel and its command in the TUI and Desktop. `false` keeps the line and the history. |
434
+ | `panel` | `true` | Show the `/usage-insights` statistics panel and its command in the TUI and Desktop. `false` keeps the line and the history. |
435
+ | `quota` | `"auto"` | Client-side OpenCode Go allowance. `"off"` hides the `go` view, the TUI sidebar and Desktop Turns blocks, and makes no usage-limits request. |
436
+ | `quotaName` | `"OpenCode Go"` | Full subscription label shown in the `go` view and compact blocks. Set `"OpenCode Go Plus"` (or your Go Teams/Plus name) when the plan is not the standard Go; the host usage payload does not carry `planType`. |
376
437
  | `maintenance` | `true` | Allow the RPC to prune, wipe, vacuum and backfill. Set `false` on servers reachable from other machines. |
377
438
  | `exposePaths` | `false` | Return the absolute database path in the `db` view; the default returns only the file name. |
378
439
  | `fields` | see below | Toggle line segments. |
@@ -503,6 +564,9 @@ bundle in every Desktop window. Server or TUI source changes still need
503
564
  - `src/text.ts` — text hygiene and the token shape a provider id is validated
504
565
  against.
505
566
  - `src/recorder.ts` — the event-stream state machine that fills the database.
567
+ - `src/quota.ts`, `src/quota-client.ts` — the OpenCode Go meter types, the
568
+ monthly forecast, formatting, and the local usage-limits read. No Console
569
+ credentials and no external request.
506
570
  - `src/rpc.ts`, `src/rpc-client.ts` — the shared RPC contract and its typed
507
571
  client wrapper.
508
572
  - `src/service.ts`, `src/stats-worker.ts`, `src/stats-client.ts` — the database
package/dist/core.d.ts CHANGED
@@ -260,6 +260,16 @@ export type DisplayTotals = Totals & {
260
260
  prompt: number;
261
261
  };
262
262
  export declare function displayTotals(totals: Totals): DisplayTotals;
263
+ /**
264
+ * The session totals as the line's `sess` segment alone. The Desktop badge
265
+ * shows this while a turn is running: the turn has no final numbers yet, so
266
+ * the badge reports the session's accumulated spend and this is its tooltip.
267
+ */
268
+ export declare function formatSessionLine(totals: Totals, options?: {
269
+ labels?: Partial<LineLabels>;
270
+ fields?: Partial<LineFields>;
271
+ estimates?: boolean;
272
+ }): string;
263
273
  /**
264
274
  * Render the telemetry line as toned segments. The caller maps tones onto
265
275
  * theme colors; `formatLine` joins the segments as plain text.
@@ -1,8 +1,8 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const n=require("solid-js/web"),P=require("@opencode/plugin/gui"),R=require("effect"),m=require("solid-js"),Ae=require("@opencode/plugin/rpc"),Ne=200,Ce=50;function ze(e){return Number.isFinite(e)?Math.min(Ce,Math.max(1,Math.round(e))):1}const xe=new Set(["user","synthetic","system"]);function qe(e,t){const i=[];let r=[];for(let o=e.length-1;o>=0;o-=1){const a=e[o];if(a.type==="assistant"){r.unshift(a);continue}if(xe.has(a.type)&&r.length!==0){if(i.unshift({assistants:r,prompt:a}),i.length>=t)return i;r=[]}}return r.length>0&&i.length<t&&i.unshift({assistants:r,prompt:void 0}),i}function B(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function pe(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function z(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Be(e){const t=e.tokens;return{input:B(t?.input),output:B(t?.output),reasoning:B(t?.reasoning),read:B(t?.cache?.read),write:B(t?.cache?.write)}}function me(e){const t={input:0,cached:0,output:0,reasoning:0,cacheWrite:0,cost:0,listCost:0,steps:e.length};for(const i of e){const r=Be(i);t.input+=r.input,t.cached+=r.read,t.output+=r.output,t.reasoning+=r.reasoning,t.cacheWrite+=r.write,t.cost+=pe(i.cost),t.listCost+=pe(i.listCost)}return t}function fe(e){if(e)return`${e.providerID}/${e.id}${e.variant?`#${e.variant}`:""}`}function oe(e){return B(e?.tokens?.cache?.read)}function De(e){return z(e?.time?.created)}function ke(e){const t=e?.time;if(t)return z(t.completed)??z(t.streamed)??z(t.created)}function Oe(e,t,i="provider"){if(!e)return;const r=e.model,o=t.model;if(!r||!o||i==="provider"&&r.providerID!==o.providerID||r.id!==o.id||(r.variant??"")!==(o.variant??""))return;const a=oe(e)-oe(t);if(!Ke(o.providerID,a))return a>0?a:void 0}function We(e,t){const i=ke(e),r=De(t);if(!(i===void 0||r===void 0))return Math.max(0,r-i)}const Ue=new Set(["openai"]);function ne(e){return e.time?.completed!==void 0?!0:e.finish!==void 0&&e.finish!==null}function Ve(e,t){const i=qe(e,2),r=i[i.length-1];if(!r)return;const o=i[i.length-2],a=r.assistants[r.assistants.length-1];if(!a||!ne(a))return;const s=o?.assistants[o.assistants.length-1],l=r.assistants.filter(ne),d=[];let S=s!==void 0&&ne(s)?s:void 0;for(const x of l){const $=Oe(S,x);$!==void 0&&d.push({messageID:x.id,tokens:$,prevCached:oe(S),gapMs:We(S,x)}),S=x}const h=a.model?.providerID,C=s?.model?.providerID,I=fe(a.model),v=fe(s?.model);return{endAt:ke(a),startAt:De(l[0]??a),promptAt:z(r.prompt?.time?.created),promptGapMs:Ge(r.prompt,o?.prompt),providerID:h,modelID:a.model?.id,variant:a.model?.variant,providerChanged:C!==void 0&&h!==void 0&&C!==h,modelChanged:v!==void 0&&I!==void 0&&v!==I&&C===h,totals:me(l),latest:me([a]),session:t,drops:d,cacheDropTokens:d.reduce((x,$)=>x+$.tokens,0),cacheExpired:d.length>0,steps:l.length}}function Ge(e,t){const i=z(e?.time?.created),r=z(t?.time?.created);if(!(i===void 0||r===void 0))return Math.max(0,i-r)}function Ke(e,t){return e===void 0?!1:Ue.has(e)&&t>=1024&&t<=2048}const He={delta:"Δ",turn:"",session:"sess",step:"step",steps:"steps",input:"in",cached:"cached",output:"out",reasoning:"reason",cost:"cost",estimate:"≈",cacheExpired:"cache expired",providerChanged:"changed",modelChanged:"model changed"},Xe={clock:!0,delta:!0,model:!0,variant:!0,turn:!0,session:!0,reasoning:!1,cost:!0,cacheExpiry:!0};function Ye(e){if(!Number.isFinite(e))return"--:--";const t=new Date(e),i=r=>String(r).padStart(2,"0");return`${i(t.getHours())}:${i(t.getMinutes())}:${i(t.getSeconds())}`}function Je(e){if(!Number.isFinite(e))return"–";const t=Math.max(0,Math.floor(e/1e3)),i=t%60,r=Math.floor(t/60)%60,o=Math.floor(t/3600)%24,a=Math.floor(t/86400);return a>0?`${a}d${o}h`:o>0?`${o}h${String(r).padStart(2,"0")}m`:r>0?`${r}m${String(i).padStart(2,"0")}s`:`${i}s`}function N(e){const t=Number.isFinite(e)?Math.max(0,Math.round(e)):0;if(t<1e3)return String(t);if(t<999500){const i=t/1e3;return`${ge(i.toFixed(i<10?2:1))}k`}if(t<9995e5){const i=t/1e6;return`${ge(i.toFixed(i<10?2:1))}M`}return`${Math.round(t/1e6)}M`}function ge(e){return e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e}function Y(e){return!Number.isFinite(e)||e<=0?"$0":e<5e-5?"<$0.0001":e<1?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Qe(e,t,i="≈"){const r=Number.isFinite(e)&&e>0?Y(e):void 0,o=Number.isFinite(t)&&t>0?`${i.trim()===""?"":`${i.trim()} `}${Y(t)}`:void 0;return r!==void 0&&o!==void 0?`${r} + ${o}`:r??o}function Ze(e,t,i="≈"){const r=Number.isFinite(e)?Math.max(0,e):0,o=Number.isFinite(t)?Math.max(0,t):0;return o>0?`${i.trim()}${Y(r+o)}`:Y(r)}function et(e){const t=e.input+e.cached+e.cacheWrite;return{input:t-e.cached,cached:e.cached,cacheWrite:e.cacheWrite,output:e.output+e.reasoning,reasoning:e.reasoning,cost:e.cost,listCost:e.listCost,steps:e.steps,prompt:t}}function he(e,t,i,r,o=0,a=t.cost,s=t.listCost,l=!0){const d=et(t),h=[d.prompt===d.input?`${i.input} ${N(d.input)}`:`${i.input} ${N(d.input)} (${N(d.prompt)})`,`${i.cached} ${N(d.cached)}`,`${i.output} ${N(d.output)}`];r.reasoning&&h.push(`${i.reasoning} ${N(d.reasoning)}`);const C=r.cost?Qe(a,l?s:0,i.estimate):void 0;C!==void 0&&h.push(`${i.cost} ${C}`);const I=o>1?`${o} ${o===1?i.step:i.steps}`:"",v=[e,I].filter($=>$!=="").join(" "),x=h.join(", ");return v===""?x:o>1?`${v} · ${x}`:`${v} ${x}`}function tt(e,t){const i={...He,...t?.labels},r={...Xe,...t?.fields},o=t?.turnTotals??"latest",a=t?.estimates!==!1,s=[];if(r.clock&&e.endAt!==void 0&&s.push({text:Ye(e.endAt),tone:"muted"}),r.delta&&e.promptGapMs!==void 0&&s.push({text:`${i.delta} ${Je(e.promptGapMs)}`,tone:"muted"}),e.providerID!==void 0){let l=e.providerID;r.model&&e.modelID!==void 0&&(l+=`/${e.modelID}`),r.variant&&e.variant&&(l+=` ${e.variant}`),s.push({text:l,tone:e.providerChanged?"warning":"base"}),e.providerChanged?s.push({text:i.providerChanged,tone:"warning"}):e.modelChanged&&s.push({text:i.modelChanged,tone:"muted"})}if(r.turn&&e.totals.steps>0){const l=o==="sum"?e.totals:e.latest;s.push({text:he(i.turn,l,i,r,o==="sum"?e.totals.steps:e.steps,e.totals.cost,e.totals.listCost,a),tone:"base"})}if(r.session&&e.session&&s.push({text:he(i.session,e.session,i,r,0,e.session.cost,e.session.listCost,a),tone:"muted"}),r.cacheExpiry&&e.cacheExpired){const l=e.drops.length>1?`×${e.drops.length}`:"";s.push({text:`⚠ ${i.cacheExpired} (−${N(e.cacheDropTokens)}${l})`,tone:"warning"})}return s}const Ie=512;function nt(e,t=Ie){if(t<=0)return"";let i="";for(const r of e){const o=r.codePointAt(0)??0;if(!(o<=31||o===127||o>=128&&o<=159)&&(i+=r,i.length>=t))break}return i}function rt(e,t=Ie){return nt(e,t).trim()}const ae=["overview","models","providers","cache","periods","latency","sessions","turns","db"],le=["session","today","7d","30d","all"],_e=["day","week","month"],Pe={models:["steps","cached","hit","out","cost"],providers:["steps","cached","hit","cost","share","tps"],latency:["n","tps","wall"],sessions:["last","steps","cached","cost"],turns:["time","cost","tokens"]};function it(e){return Pe[e]??[]}function se(e){return it(e)[0]??""}function ot(e){const t={};for(const i of(e??"").split(/\s+/)){const r=i.trim().toLowerCase();r!==""&&(ae.includes(r)?t.view=r:le.includes(r)&&(t.range=r))}return t}const O={view:"overview",range:"all",sort:"",sortDesc:!0,granularity:"day",turnsScope:"session",modelID:"",providerID:""};function Te(e){const t={...O,...e??{}};return{view:ae.includes(t.view)?t.view:O.view,range:le.includes(t.range)?t.range:O.range,sort:typeof t.sort=="string"?t.sort:O.sort,sortDesc:t.sortDesc===!0,granularity:_e.includes(t.granularity)?t.granularity:O.granularity,turnsScope:t.turnsScope==="all"?"all":"session",modelID:typeof t.modelID=="string"?t.modelID:"",providerID:typeof t.providerID=="string"?t.providerID:""}}function re(e){return Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"–"}function st(e){const t=[];return e.modelID!==void 0&&e.modelID!==""&&t.push(`model=${e.modelID}`),e.providerID!==void 0&&e.providerID!==""&&t.push(`provider=${e.providerID}`),t.length>0?t.join(" · "):void 0}function H(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function W(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function at(e){const t=new Map;if(!Array.isArray(e))return t;for(const i of e){if(i==null)continue;const r=i.providerID,o=i.modelID??i.id;if(typeof r!="string"||r===""||typeof o!="string"||o===""||!Array.isArray(i.cost)||i.cost.length===0)continue;const a=[];for(const s of i.cost){if(s==null)continue;let l;if(s.tier!==void 0){const d=s.tier.size;if(typeof d!="number"||!Number.isFinite(d))continue;l={...s.tier.type!==void 0?{type:s.tier.type}:{},size:d}}a.push({...l!==void 0?{tier:l}:{},input:H(s.input),output:H(s.output),cacheRead:H(s.cache?.read),cacheWrite:H(s.cache?.write)})}a.length>0&&t.set(`${r}/${o}`,{tiers:a})}return t}function lt(e,t){if(!(t.providerID===void 0||t.providerID==="")&&!(t.modelID===void 0||t.modelID===""))return e.get(`${t.providerID}/${t.modelID}`)}function ct(e,t,i){const r=lt(e,t);if(r===void 0)return;const o=W(i.input),a=W(i.output),s=W(i.reasoning),l=W(i.cacheRead),d=W(i.cacheWrite),S=o+l+d,h=r.tiers.filter(I=>I.tier?.type==="context"&&S>I.tier.size).sort((I,v)=>(v.tier?.size??0)-(I.tier?.size??0))[0]??r.tiers.find(I=>I.tier===void 0);if(h===void 0)return;if(h.input===0&&h.output===0&&h.cacheRead===0&&h.cacheWrite===0)return 0;const C=o*h.input+(a+s)*h.output+l*h.cacheRead+d*h.cacheWrite;if(!(!Number.isFinite(C)||C<=0))return C/1e6}const ut={type:"string",enum:["base","muted","warning","accent"]},Me={type:"object",properties:{kind:{type:"string",enum:["model","session","period","provider","turn","prune","wipe"]},value:{type:"string",maxLength:500},variant:{type:"string",maxLength:200}},required:["kind","value"],additionalProperties:!1},ie={type:"object",properties:{text:{type:"string"},tone:ut,hint:{type:"boolean"},row:Me},required:["text"],additionalProperties:!1},dt={type:"object",properties:{view:{type:"string",enum:["overview","models","providers","cache","periods","latency","sessions","turns","db"]},range:{type:"string",enum:["session","today","7d","30d","all"]},sort:{type:"string",maxLength:40},sortDesc:{type:"boolean"},granularity:{type:"string",enum:["day","week","month"]},turnsScope:{type:"string",enum:["session","all"]},modelID:{type:"string",maxLength:300},providerID:{type:"string",maxLength:300}},required:["view","range","sort","sortDesc","granularity","turnsScope","modelID","providerID"],additionalProperties:!1},pt={type:"object",properties:{name:{type:"string"},rows:{type:"number"}},required:["name","rows"],additionalProperties:!1},ve={type:"object",properties:{path:{type:"string"},bytes:{type:"number"},walBytes:{type:"number"},schemaVersion:{type:"number"},tables:{type:"array",items:pt},firstAt:{type:"number"},lastAt:{type:"number"},removable:{type:"array",items:{type:"object",properties:{days:{type:"number"},steps:{type:"number"}},required:["days","steps"],additionalProperties:!1}},unpriced:{type:"number"}},required:["path","bytes","schemaVersion","tables","removable","unpriced"],additionalProperties:!1},be={type:"object",properties:{value:{type:"string"},steps:{type:"number"}},required:["value","steps"],additionalProperties:!1},mt={type:"object",properties:{steps:{type:"number"},prompts:{type:"number"},events:{type:"number"},usage:{type:"number"}},required:["steps","prompts","events","usage"],additionalProperties:!1},ft={type:"object",properties:{steps:{type:"number"},prompts:{type:"number"},events:{type:"number"},usage:{type:"number"},sessions:{type:"number"}},required:["steps","prompts","events","usage","sessions"],additionalProperties:!1},gt={type:"object",properties:{candidates:{type:"number"},updated:{type:"number"}},required:["candidates","updated"],additionalProperties:!1},ht={type:"object",properties:{before:{type:"number"},after:{type:"number"},freed:{type:"number"}},required:["before","after","freed"],additionalProperties:!1},ye={type:"object",properties:{},additionalProperties:!1},X={type:"object",properties:{message:{type:"string",maxLength:500}},additionalProperties:!1},j={busy:X,unavailable:X,disabled:X,invalid:X},vt=Ae.Rpc.define({id:"usage-insights",methods:{panel:{input:{type:"object",properties:{sessionID:{type:"string",maxLength:200},settings:dt,detail:Me,width:{type:"number",minimum:20,maximum:Ne},busy:{type:"boolean"}},required:["sessionID","settings","width"],additionalProperties:!1},output:{type:"object",properties:{lines:{type:"array",items:ie},database:ve},required:["lines"],additionalProperties:!1},errors:j},turns:{input:{type:"object",properties:{sessionID:{type:"string",maxLength:200},limit:{type:"number",minimum:1,maximum:Ce},width:{type:"number",minimum:20,maximum:120}},required:["sessionID","limit","width"],additionalProperties:!1},output:{type:"object",properties:{summary:{type:"array",items:ie},history:{type:"array",items:ie}},required:["summary","history"],additionalProperties:!1},errors:j},listCost:{input:{type:"object",properties:{sessionID:{type:"string",maxLength:200}},required:["sessionID"],additionalProperties:!1},output:{type:"object",properties:{cost:{type:"number"}},required:["cost"],additionalProperties:!1},errors:j},filters:{input:ye,output:{type:"object",properties:{models:{type:"array",items:be},providers:{type:"array",items:be}},required:["models","providers"],additionalProperties:!1},errors:j},dbInfo:{input:ye,output:ve,errors:j},prune:{input:{type:"object",properties:{days:{type:"number",minimum:1,maximum:3650},confirm:{type:"boolean",enum:[!0]}},required:["days","confirm"],additionalProperties:!1},output:mt,errors:j},wipe:{input:{type:"object",properties:{confirm:{type:"boolean",enum:[!0]}},required:["confirm"],additionalProperties:!1},output:ft,errors:j},vacuum:{input:{type:"object",properties:{confirm:{type:"boolean",enum:[!0]}},required:["confirm"],additionalProperties:!1},output:ht,errors:j},backfill:{input:{type:"object",properties:{confirm:{type:"boolean",enum:[!0]}},required:["confirm"],additionalProperties:!1},output:gt,errors:j}},events:{recorded:{schema:{type:"object",properties:{sessionID:{type:"string",maxLength:200},at:{type:"number"}},required:["at"],additionalProperties:!1}}}});function V(e,t){const i=e.rpc(vt),r=o=>({...t!==void 0&&t.directory!==void 0?{location:{directory:t.directory}}:{},...o!==void 0?{signal:o}:{}});return{panel:(o,a)=>i.panel(o,r(a)),turns:(o,a)=>i.turns(o,r(a)),listCost:(o,a)=>i.listCost(o,r(a)),filters:o=>i.filters({},r(o)),dbInfo:o=>i.dbInfo({},r(o)),prune:(o,a)=>i.prune(o,r(a)),wipe:(o,a)=>i.wipe(o,r(a)),vacuum:(o,a)=>i.vacuum(o,r(a)),backfill:(o,a)=>i.backfill(o,r(a)),onRecorded:(o,a)=>i.events.on("recorded",s=>o(s.data),a===void 0?void 0:{signal:a})}}function bt(e,t){const i=[];for(const r of e){if(typeof r.id!="string"||typeof r.type!="string")continue;if(r.type!=="assistant"){i.push({type:r.type,id:r.id,time:r.time});continue}const o=wt(r.model);let a=r.listCost;if(a===void 0&&t!==void 0&&o!==void 0&&(r.cost===void 0||r.cost<=0)){const s=t({providerID:o.providerID,modelID:o.id},{input:r.tokens?.input,output:r.tokens?.output,reasoning:r.tokens?.reasoning,cacheRead:r.tokens?.cache?.read,cacheWrite:r.tokens?.cache?.write});s!==void 0&&Number.isFinite(s)&&s>0&&(a=s)}i.push({type:"assistant",id:r.id,time:r.time,model:o,tokens:r.tokens,cost:r.cost,...a!==void 0?{listCost:a}:{},finish:r.finish??void 0,rawFinish:r.rawFinish??void 0})}return i}function yt(e,t=2,i){const r=Math.max(2,t),o=[];let a=0,s=0;for(let l=e.length-1;l>=0;l-=1){const d=e[l];if(d.type==="assistant"){o.push(d),a+=1;continue}if(!(d.type===void 0||!xe.has(d.type))&&a!==0&&(o.push(d),a=0,s+=1,s>=r))break}return o.reverse(),bt(o,i)}function wt(e){if(!(e===void 0||e.providerID===void 0||e.id===void 0))return e.variant===void 0?{providerID:e.providerID,id:e.id}:{providerID:e.providerID,id:e.id,variant:e.variant}}function U(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function we(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function $t(e,t=0){if(e===void 0)return;const i=e.tokens;return{input:U(i?.input),cached:U(i?.cache?.read),output:U(i?.output),reasoning:U(i?.reasoning),cacheWrite:U(i?.cache?.write),cost:we(e.cost),listCost:we(t),steps:0}}function St(e,t){if(e===void 0)return[];const i=[];return tt(e,t).forEach((o,a)=>{a>0&&i.push({text:" · ",tone:"muted"}),i.push({text:rt(o.text),tone:o.tone})}),i}function Ct(e){return e.map(t=>t.text).join("")}function xt(e){if(e.status!==void 0&&e.status!=="idle")return;const t=e.info===void 0?void 0:$t(e.info,e.listCost);return Ve(yt(e.messages,2,e.price),t)}function Dt(e){if(!(e.status!==void 0&&e.status!=="idle"))return xt({messages:e.messages(),info:e.info(),listCost:e.listCost,status:e.status,price:e.price?.()})}function kt(e,t){if(!(e===void 0||t.fields?.cost===!1))return Ze(e.totals.cost,e.totals.listCost)}function It(e,t){return St(e,{labels:t.labels,fields:t.fields,turnTotals:t.turnTotals,estimates:t.estimates})}function _t(e,t){return Ct(It(e,t))}function J(e){return e==="muted"?"oui-tone-muted":e==="warning"?"oui-tone-warning":e==="accent"?"oui-tone-accent":"oui-tone-base"}var Pt=n.template("<span data-slot=oui-header-badge-label>"),Tt=n.template("<button type=button data-component=oui-header-badge>"),Mt=n.template("<span data-component=oui-header-badge>");function Ft(e){const t=P.usePlugin(),i=m.createMemo(()=>e.line()),r=m.createMemo(()=>kt(i(),e.options)),o=m.createMemo(()=>_t(i(),e.options)),a=()=>[n.createComponent(t.ui.Icon,{get name(){return e.icon},size:"small"}),n.createComponent(m.Show,{get when(){return!e.compact},get children(){var s=Pt();return n.insert(s,r),s}})];return n.createComponent(m.Show,{get when(){return r()},get children(){return n.createComponent(m.Show,{get when(){return e.panelEnabled},get fallback(){return(()=>{var s=Mt();return n.insert(s,a),n.effect(l=>{var d=o(),S=o();return d!==l.e&&n.setAttribute(s,"title",l.e=d),S!==l.t&&n.setAttribute(s,"aria-label",l.t=S),l},{e:void 0,t:void 0}),s})()},get children(){var s=Tt();return s.$$click=()=>e.open(),n.insert(s,a),n.effect(l=>{var d=o(),S=e.compact?o():void 0;return d!==l.e&&n.setAttribute(s,"title",l.e=d),S!==l.t&&n.setAttribute(s,"aria-label",l.t=S),l},{e:void 0,t:void 0}),s}})}})}n.delegateEvents(["click"]);const Lt="[data-component=oui-panel]{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--v2-background-bg-base);color:var(--v2-text-text-base)}[data-slot=oui-header]{display:flex;flex-direction:column;gap:8px;padding:10px 12px 8px;border-bottom:.5px solid var(--v2-border-border-base);flex:none}[data-slot=oui-title-row]{display:flex;align-items:center;justify-content:space-between;gap:8px}[data-slot=oui-title]{font-size:13px;line-height:18px;font-weight:600;letter-spacing:-.04px}[data-slot=oui-subtitle]{font-size:11px;line-height:16px;color:var(--v2-text-text-muted)}[data-slot=oui-controls]{display:flex;flex-wrap:wrap;align-items:center;gap:6px}[data-slot=oui-controls] [data-component=oui-control]{min-width:0}[data-slot=oui-body]{flex:1;min-height:0;overflow:auto;padding:6px 0 12px}[data-slot=oui-lines]{display:flex;flex-direction:column;min-width:max-content;padding:0 12px;font-family:var(--v2-font-family-mono, var(--font-family-mono, monospace));font-size:12px;line-height:18px;white-space:pre}[data-slot=oui-line]{display:block;width:100%;min-height:18px;padding:0;margin:0;border:0;background:transparent;text-align:left;font:inherit;color:inherit;white-space:pre}button[data-slot=oui-line][data-selectable=true]{cursor:pointer;border-radius:3px}button[data-slot=oui-line][data-selectable=true]:hover,button[data-slot=oui-line][data-selectable=true]:focus-visible{background:var(--v2-background-bg-layer-01);outline:none}button[data-slot=oui-line][data-selectable=true]:focus-visible{box-shadow:inset 0 0 0 1px var(--v2-border-border-focus)}[data-slot=oui-loading],[data-slot=oui-empty],[data-slot=oui-error]{padding:16px 12px;font-size:12px;line-height:18px;color:var(--v2-text-text-muted)}[data-slot=oui-error]{color:var(--v2-state-fg-danger)}[data-slot=oui-actions]{display:flex;flex-wrap:wrap;gap:6px;padding:10px 12px;border-top:.5px solid var(--v2-border-border-base);flex:none}[data-slot=oui-detail-head]{display:flex;align-items:center;gap:8px;padding:8px 12px 4px;flex:none}[data-slot=oui-divider]{height:.5px;background:var(--v2-border-border-base);margin:8px 0}[data-component=oui-header-badge]{display:inline-flex;align-items:center;gap:4px;font-family:inherit;font-size:11px;font-weight:600;letter-spacing:.02em;white-space:nowrap;background:transparent;border:0;padding:0;color:var(--v2-text-text-base)}button[data-component=oui-header-badge]{cursor:pointer}button[data-component=oui-header-badge]:hover{color:var(--v2-text-text-accent)}button[data-component=oui-header-badge]:focus-visible{outline:1px solid var(--v2-border-border-focus);outline-offset:2px;border-radius:3px}[data-slot=oui-header-badge-label]{color:inherit}.oui-tone-base{color:var(--v2-text-text-base)}.oui-tone-muted{color:var(--v2-text-text-muted)}.oui-tone-warning{color:var(--v2-state-fg-warning)}.oui-tone-accent{color:var(--v2-text-text-accent)}",Et=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" aria-hidden="true">
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const r=require("solid-js/web"),P=require("@opencode/plugin/gui"),G=require("effect"),u=require("solid-js"),Dt=require("@opencode/plugin/rpc"),Xe=200,Je=120,Ze=50;function Mt(e){return Number.isFinite(e)?Math.min(Xe,Math.max(20,Math.round(e))):20}function Tt(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0?0:Mt(Math.floor(e/t))}function It(e){return Number.isFinite(e)?Math.min(Ze,Math.max(1,Math.round(e))):1}const et=new Set(["user","synthetic","system"]);function Pt(e,t){const n=[];let o=[];for(let i=e.length-1;i>=0;i-=1){const a=e[i];if(a.type==="assistant"){o.unshift(a);continue}if(et.has(a.type)&&o.length!==0){if(n.unshift({assistants:o,prompt:a}),n.length>=t)return n;o=[]}}return o.length>0&&n.length<t&&n.unshift({assistants:o,prompt:void 0}),n}function Z(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function Ne(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function H(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function At(e){const t=e.tokens;return{input:Z(t?.input),output:Z(t?.output),reasoning:Z(t?.reasoning),read:Z(t?.cache?.read),write:Z(t?.cache?.write)}}function qe(e){const t={input:0,cached:0,output:0,reasoning:0,cacheWrite:0,cost:0,listCost:0,steps:e.length};for(const n of e){const o=At(n);t.input+=o.input,t.cached+=o.read,t.output+=o.output,t.reasoning+=o.reasoning,t.cacheWrite+=o.write,t.cost+=Ne(n.cost),t.listCost+=Ne(n.listCost)}return t}function ze(e){if(e)return`${e.providerID}/${e.id}${e.variant?`#${e.variant}`:""}`}function Me(e){return Z(e?.tokens?.cache?.read)}function tt(e){return H(e?.time?.created)}function nt(e){const t=e?.time;if(t)return H(t.completed)??H(t.streamed)??H(t.created)}function Et(e,t,n="provider"){if(!e)return;const o=e.model,i=t.model;if(!o||!i||n==="provider"&&o.providerID!==i.providerID||o.id!==i.id||(o.variant??"")!==(i.variant??""))return;const a=Me(e)-Me(t);if(!qt(i.providerID,a))return a>0?a:void 0}function Ft(e,t){const n=nt(e),o=tt(t);if(!(n===void 0||o===void 0))return Math.max(0,o-n)}const Lt=new Set(["openai"]);function xe(e){return e.time?.completed!==void 0?!0:e.finish!==void 0&&e.finish!==null}function Rt(e,t){const n=Pt(e,2),o=n[n.length-1];if(!o)return;const i=n[n.length-2],a=o.assistants[o.assistants.length-1];if(!a||!xe(a))return;const s=i?.assistants[i.assistants.length-1],l=o.assistants.filter(xe),p=[];let m=s!==void 0&&xe(s)?s:void 0;for(const v of l){const w=Et(m,v);w!==void 0&&p.push({messageID:v.id,tokens:w,prevCached:Me(m),gapMs:Ft(m,v)}),m=v}const g=a.model?.providerID,C=s?.model?.providerID,y=ze(a.model),_=ze(s?.model);return{endAt:nt(a),startAt:tt(l[0]??a),promptAt:H(o.prompt?.time?.created),promptGapMs:Nt(o.prompt,i?.prompt),providerID:g,modelID:a.model?.id,variant:a.model?.variant,providerChanged:C!==void 0&&g!==void 0&&C!==g,modelChanged:_!==void 0&&y!==void 0&&_!==y&&C===g,totals:qe(l),latest:qe([a]),session:t,drops:p,cacheDropTokens:p.reduce((v,w)=>v+w.tokens,0),cacheExpired:p.length>0,steps:l.length}}function Nt(e,t){const n=H(e?.time?.created),o=H(t?.time?.created);if(!(n===void 0||o===void 0))return Math.max(0,n-o)}function qt(e,t){return e===void 0?!1:Lt.has(e)&&t>=1024&&t<=2048}const rt={delta:"Δ",turn:"",session:"sess",step:"step",steps:"steps",input:"in",cached:"cached",output:"out",reasoning:"reason",cost:"cost",estimate:"≈",cacheExpired:"cache expired",providerChanged:"changed",modelChanged:"model changed"},ot={clock:!0,delta:!0,model:!0,variant:!0,turn:!0,session:!0,reasoning:!1,cost:!0,cacheExpiry:!0};function zt(e){if(!Number.isFinite(e))return"--:--";const t=new Date(e),n=o=>String(o).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function it(e){if(!Number.isFinite(e))return"–";const t=Math.max(0,Math.floor(e/1e3)),n=t%60,o=Math.floor(t/60)%60,i=Math.floor(t/3600)%24,a=Math.floor(t/86400);return a>0?`${a}d${i}h`:i>0?`${i}h${String(o).padStart(2,"0")}m`:o>0?`${o}m${String(n).padStart(2,"0")}s`:`${n}s`}function Q(e){const t=Number.isFinite(e)?Math.max(0,Math.round(e)):0;if(t<1e3)return String(t);if(t<999500){const n=t/1e3;return`${Oe(n.toFixed(n<10?2:1))}k`}if(t<9995e5){const n=t/1e6;return`${Oe(n.toFixed(n<10?2:1))}M`}return`${Math.round(t/1e6)}M`}function Oe(e){return e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e}function be(e){return!Number.isFinite(e)||e<=0?"$0":e<5e-5?"<$0.0001":e<1?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ot(e,t,n="≈"){const o=Number.isFinite(e)&&e>0?be(e):void 0,i=Number.isFinite(t)&&t>0?`${n.trim()===""?"":`${n.trim()} `}${be(t)}`:void 0;return o!==void 0&&i!==void 0?`${o} + ${i}`:o??i}function at(e,t,n="≈"){const o=Number.isFinite(e)?Math.max(0,e):0,i=Number.isFinite(t)?Math.max(0,t):0;return i>0?`${n.trim()}${be(o+i)}`:be(o)}function jt(e){const t=e.input+e.cached+e.cacheWrite;return{input:t-e.cached,cached:e.cached,cacheWrite:e.cacheWrite,output:e.output+e.reasoning,reasoning:e.reasoning,cost:e.cost,listCost:e.listCost,steps:e.steps,prompt:t}}function Te(e,t,n,o,i=0,a=t.cost,s=t.listCost,l=!0){const p=jt(t),g=[p.prompt===p.input?`${n.input} ${Q(p.input)}`:`${n.input} ${Q(p.input)} (${Q(p.prompt)})`,`${n.cached} ${Q(p.cached)}`,`${n.output} ${Q(p.output)}`];o.reasoning&&g.push(`${n.reasoning} ${Q(p.reasoning)}`);const C=o.cost?Ot(a,l?s:0,n.estimate):void 0;C!==void 0&&g.push(`${n.cost} ${C}`);const y=i>1?`${i} ${i===1?n.step:n.steps}`:"",_=[e,y].filter(w=>w!=="").join(" "),v=g.join(", ");return _===""?v:i>1?`${_} · ${v}`:`${_} ${v}`}function Ut(e,t){const n={...rt,...t?.labels},o={...ot,...t?.fields},i=t?.estimates!==!1;return Te(n.session,e,n,o,0,e.cost,e.listCost,i)}function Bt(e,t){const n={...rt,...t?.labels},o={...ot,...t?.fields},i=t?.turnTotals??"latest",a=t?.estimates!==!1,s=[];if(o.clock&&e.endAt!==void 0&&s.push({text:zt(e.endAt),tone:"muted"}),o.delta&&e.promptGapMs!==void 0&&s.push({text:`${n.delta} ${it(e.promptGapMs)}`,tone:"muted"}),e.providerID!==void 0){let l=e.providerID;o.model&&e.modelID!==void 0&&(l+=`/${e.modelID}`),o.variant&&e.variant&&(l+=` ${e.variant}`),s.push({text:l,tone:e.providerChanged?"warning":"base"}),e.providerChanged?s.push({text:n.providerChanged,tone:"warning"}):e.modelChanged&&s.push({text:n.modelChanged,tone:"muted"})}if(o.turn&&e.totals.steps>0){const l=i==="sum"?e.totals:e.latest;s.push({text:Te(n.turn,l,n,o,i==="sum"?e.totals.steps:e.steps,e.totals.cost,e.totals.listCost,a),tone:"base"})}if(o.session&&e.session&&s.push({text:Te(n.session,e.session,n,o,0,e.session.cost,e.session.listCost,a),tone:"muted"}),o.cacheExpiry&&e.cacheExpired){const l=e.drops.length>1?`×${e.drops.length}`:"";s.push({text:`⚠ ${n.cacheExpired} (−${Q(e.cacheDropTokens)}${l})`,tone:"warning"})}return s}const st=512;function lt(e,t=st){if(t<=0)return"";let n="";for(const o of e){const i=o.codePointAt(0)??0;if(!(i<=31||i===127||i>=128&&i<=159)&&(n+=o,n.length>=t))break}return n}function ct(e,t=st){return lt(e,t).trim()}const B="go",ut=6e4,dt="OpenCode Go",$e=1440*60*1e3,je=1800*1e3;function Wt(e,t){const n=e?.trim();if(n!==void 0&&n!=="")return n;const o=t?.trim();return o!==void 0&&o!==""?o:dt}function Y(e){return typeof e=="number"&&Number.isFinite(e)}function se(e,t,n){return Math.min(n,Math.max(t,e))}function Gt(e){if(!Y(e))return e;const t=new Date(e),n=t.getUTCFullYear(),o=t.getUTCMonth(),i=t.getUTCDate(),a=new Date(Date.UTC(n,o-1,1,t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())),s=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth()+1,0)).getUTCDate();return a.setUTCDate(Math.min(i,s)),a.getTime()}function pt(e,t){const n=Y(e.resetsAt)?e.resetsAt:t,o=Gt(n),i=Math.max(1,n-o),a=se(t-o,0,i),s=Math.max(0,n-t),l=se(Y(e.percent)?e.percent:0,0,100),p=e.limited===!0||l>=100,m=!p&&a>=je&&l>0?l/(a/$e):0,g=p?100:m>0?l+m*(s/$e):l,C=!p&&m>0&&l<100?t+(100-l)/m*$e:void 0,y=C!==void 0&&C<n?C:void 0,_=y!==void 0,v=!p&&t<n&&(a>=je||l===0);return{startAt:o,endAt:n,elapsedMs:a,remainingMs:s,ratePerDay:m,projectedPercent:g,...y!==void 0?{exhaustAt:y}:{},reached:p,available:v,willExhaust:_}}function Vt(e,t){const n=pt(e,t),o=se(Math.round(Y(e.percent)?e.percent:0),0,100),i=n.reached?100:Math.round(n.projectedPercent);return{current:o,forecast:se(i,0,100),headroom:Math.max(0,100-se(i,0,100)),over:!n.reached&&n.projectedPercent>100,reached:n.reached,available:n.available,resetsAt:n.endAt,...n.exhaustAt!==void 0?{exhaustAt:n.exhaustAt}:{}}}function Ue(e,t){if(!Y(e))return"–";try{return new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,...t!==void 0?{timeZone:t}:{}}).format(new Date(e)).replace(/,/g,"")}catch{return"–"}}function Kt(e,t){if(!Y(e))return"–";try{return new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit",hour12:!1,...t!==void 0?{timeZone:t}:{}}).format(new Date(e)).replace(/,/g,"")}catch{return"–"}}function mt(e,t){const n=e-t;return Y(n)?n<=0?"due":it(n):"–"}function ft(e){const t=[];return(e.rolling.limited||e.rolling.percent>=100)&&t.push("5-hour"),(e.weekly.limited||e.weekly.percent>=100)&&t.push("weekly"),(e.monthly.limited||e.monthly.percent>=100)&&t.push("monthly"),t.length===0?"active":`${t.join(" / ")} limit reached`}const gt=["overview","models","providers","cache","periods","latency","sessions","turns","db"],Pe=[...gt,B],Ae=["session","today","7d","30d","all"],vt=["day","week","month"],ht={models:["steps","cached","hit","out","cost"],providers:["steps","cached","hit","cost","share","tps"],latency:["n","tps","wall"],sessions:["last","steps","cached","cost"],turns:["time","cost","tokens"]};function Qt(e){return ht[e]??[]}function Ie(e){return Qt(e)[0]??""}function Ht(e){if(e.indexOf(B)===-1)return e;const n=e.filter(a=>a!==B),o=n.indexOf("overview"),i=o===-1?0:o+1;return[...n.slice(0,i),B,...n.slice(i)]}function Yt(e,t=Pe){const n={};for(const o of(e??"").split(/\s+/)){const i=o.trim().toLowerCase();i!==""&&(t.includes(i)?n.view=i:Ae.includes(i)&&(n.range=i))}return n}const ee={view:"overview",range:"all",sort:"",sortDesc:!0,granularity:"day",turnsScope:"session",modelID:"",providerID:""};function bt(e,t=Pe){const n={...ee,...e??{}};return{view:t.includes(n.view)?n.view:ee.view,range:Ae.includes(n.range)?n.range:ee.range,sort:typeof n.sort=="string"?n.sort:ee.sort,sortDesc:n.sortDesc===!0,granularity:vt.includes(n.granularity)?n.granularity:ee.granularity,turnsScope:n.turnsScope==="all"?"all":"session",modelID:typeof n.modelID=="string"?n.modelID:"",providerID:typeof n.providerID=="string"?n.providerID:""}}function Ce(e){return Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"–"}function ge(e,t){if(t<=1)return"";const n=lt(e);return n.length<=t?n:`${n.slice(0,t-1).trimEnd()}…`}function Xt(e){const t=[];return e.modelID!==void 0&&e.modelID!==""&&t.push(`model=${e.modelID}`),e.providerID!==void 0&&e.providerID!==""&&t.push(`provider=${e.providerID}`),t.length>0?t.join(" · "):void 0}function Jt(e,t,n,o=dt){if(e?.kind!=="ok"||n<=0)return[];const i=e.quota,a=ft(i),s=pt(i.monthly,t),l=`5h ${Math.round(i.rolling.percent)}% · week ${Math.round(i.weekly.percent)}% · month ${Math.round(i.monthly.percent)}%`,p=a!=="active"||i.monthly.percent>=80?"warning":"base";let m="forecast too early",g="muted";return s.reached||i.monthly.limited?(m="monthly limit reached",g="warning"):s.willExhaust?(m="limit before renewal",g="warning"):s.available&&i.monthly.percent>0?m=`forecast ~${Math.min(999,Math.round(s.projectedPercent))}% at reset`:s.available&&i.monthly.percent===0&&(m="forecast no usage yet"),[{text:ge(o,n),tone:"accent"},{text:ge(l,n),tone:p},{text:ge(m,n),tone:g},{text:ge(`renews ${Kt(i.monthly.resetsAt)}`,n),tone:"muted"}]}function ve(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function ie(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function Zt(e){const t=new Map;if(!Array.isArray(e))return t;for(const n of e){if(n==null)continue;const o=n.providerID,i=n.modelID??n.id;if(typeof o!="string"||o===""||typeof i!="string"||i===""||!Array.isArray(n.cost)||n.cost.length===0)continue;const a=[];for(const s of n.cost){if(s==null)continue;let l;if(s.tier!==void 0){const p=s.tier.size;if(typeof p!="number"||!Number.isFinite(p))continue;l={...s.tier.type!==void 0?{type:s.tier.type}:{},size:p}}a.push({...l!==void 0?{tier:l}:{},input:ve(s.input),output:ve(s.output),cacheRead:ve(s.cache?.read),cacheWrite:ve(s.cache?.write)})}a.length>0&&t.set(`${o}/${i}`,{tiers:a})}return t}function en(e,t){if(!(t.providerID===void 0||t.providerID==="")&&!(t.modelID===void 0||t.modelID===""))return e.get(`${t.providerID}/${t.modelID}`)}function tn(e,t,n){const o=en(e,t);if(o===void 0)return;const i=ie(n.input),a=ie(n.output),s=ie(n.reasoning),l=ie(n.cacheRead),p=ie(n.cacheWrite),m=i+l+p,g=o.tiers.filter(y=>y.tier?.type==="context"&&m>y.tier.size).sort((y,_)=>(_.tier?.size??0)-(y.tier?.size??0))[0]??o.tiers.find(y=>y.tier===void 0);if(g===void 0)return;if(g.input===0&&g.output===0&&g.cacheRead===0&&g.cacheWrite===0)return 0;const C=i*g.input+(a+s)*g.output+l*g.cacheRead+p*g.cacheWrite;if(!(!Number.isFinite(C)||C<=0))return C/1e6}const nn={type:"string",enum:["base","muted","warning","accent"]},yt={type:"object",properties:{kind:{type:"string",enum:["model","session","period","provider","turn","prune","wipe"]},value:{type:"string",maxLength:500},variant:{type:"string",maxLength:200}},required:["kind","value"],additionalProperties:!1},Se={type:"object",properties:{text:{type:"string"},tone:nn,hint:{type:"boolean"},row:yt},required:["text"],additionalProperties:!1},rn={type:"object",properties:{view:{type:"string",enum:["overview","models","providers","cache","periods","latency","sessions","turns","db","go"]},range:{type:"string",enum:["session","today","7d","30d","all"]},sort:{type:"string",maxLength:40},sortDesc:{type:"boolean"},granularity:{type:"string",enum:["day","week","month"]},turnsScope:{type:"string",enum:["session","all"]},modelID:{type:"string",maxLength:300},providerID:{type:"string",maxLength:300}},required:["view","range","sort","sortDesc","granularity","turnsScope","modelID","providerID"],additionalProperties:!1},on={type:"object",properties:{name:{type:"string"},rows:{type:"number"}},required:["name","rows"],additionalProperties:!1},Be={type:"object",properties:{path:{type:"string"},bytes:{type:"number"},walBytes:{type:"number"},schemaVersion:{type:"number"},tables:{type:"array",items:on},firstAt:{type:"number"},lastAt:{type:"number"},removable:{type:"array",items:{type:"object",properties:{days:{type:"number"},steps:{type:"number"}},required:["days","steps"],additionalProperties:!1}},unpriced:{type:"number"}},required:["path","bytes","schemaVersion","tables","removable","unpriced"],additionalProperties:!1},We={type:"object",properties:{value:{type:"string"},steps:{type:"number"}},required:["value","steps"],additionalProperties:!1},an={type:"object",properties:{steps:{type:"number"},prompts:{type:"number"},events:{type:"number"},usage:{type:"number"}},required:["steps","prompts","events","usage"],additionalProperties:!1},sn={type:"object",properties:{steps:{type:"number"},prompts:{type:"number"},events:{type:"number"},usage:{type:"number"},sessions:{type:"number"}},required:["steps","prompts","events","usage","sessions"],additionalProperties:!1},ln={type:"object",properties:{candidates:{type:"number"},updated:{type:"number"}},required:["candidates","updated"],additionalProperties:!1},cn={type:"object",properties:{before:{type:"number"},after:{type:"number"},freed:{type:"number"}},required:["before","after","freed"],additionalProperties:!1},Ge={type:"object",properties:{},additionalProperties:!1},he={type:"object",properties:{message:{type:"string",maxLength:500}},additionalProperties:!1},V={busy:he,unavailable:he,disabled:he,invalid:he},un=Dt.Rpc.define({id:"usage-insights",methods:{panel:{input:{type:"object",properties:{sessionID:{type:"string",maxLength:200},settings:rn,detail:yt,width:{type:"number",minimum:20,maximum:Xe},busy:{type:"boolean"}},required:["sessionID","settings","width"],additionalProperties:!1},output:{type:"object",properties:{lines:{type:"array",items:Se},database:Be},required:["lines"],additionalProperties:!1},errors:V},turns:{input:{type:"object",properties:{sessionID:{type:"string",maxLength:200},limit:{type:"number",minimum:1,maximum:Ze},width:{type:"number",minimum:20,maximum:Je}},required:["sessionID","limit","width"],additionalProperties:!1},output:{type:"object",properties:{summary:{type:"array",items:Se},history:{type:"array",items:Se}},required:["summary","history"],additionalProperties:!1},errors:V},listCost:{input:{type:"object",properties:{sessionID:{type:"string",maxLength:200}},required:["sessionID"],additionalProperties:!1},output:{type:"object",properties:{cost:{type:"number"}},required:["cost"],additionalProperties:!1},errors:V},filters:{input:Ge,output:{type:"object",properties:{models:{type:"array",items:We},providers:{type:"array",items:We}},required:["models","providers"],additionalProperties:!1},errors:V},dbInfo:{input:Ge,output:Be,errors:V},prune:{input:{type:"object",properties:{days:{type:"number",minimum:1,maximum:3650},confirm:{type:"boolean",enum:[!0]}},required:["days","confirm"],additionalProperties:!1},output:an,errors:V},wipe:{input:{type:"object",properties:{confirm:{type:"boolean",enum:[!0]}},required:["confirm"],additionalProperties:!1},output:sn,errors:V},vacuum:{input:{type:"object",properties:{confirm:{type:"boolean",enum:[!0]}},required:["confirm"],additionalProperties:!1},output:cn,errors:V},backfill:{input:{type:"object",properties:{confirm:{type:"boolean",enum:[!0]}},required:["confirm"],additionalProperties:!1},output:ln,errors:V}},events:{recorded:{schema:{type:"object",properties:{sessionID:{type:"string",maxLength:200},at:{type:"number"}},required:["at"],additionalProperties:!1}}}});function ce(e,t){const n=e.rpc(un),o=i=>({...t!==void 0&&t.directory!==void 0?{location:{directory:t.directory}}:{},...i!==void 0?{signal:i}:{}});return{panel:(i,a)=>n.panel(i,o(a)),turns:(i,a)=>n.turns(i,o(a)),listCost:(i,a)=>n.listCost(i,o(a)),filters:i=>n.filters({},o(i)),dbInfo:i=>n.dbInfo({},o(i)),prune:(i,a)=>n.prune(i,o(a)),wipe:(i,a)=>n.wipe(i,o(a)),vacuum:(i,a)=>n.vacuum(i,o(a)),backfill:(i,a)=>n.backfill(i,o(a)),onRecorded:(i,a)=>n.events.on("recorded",s=>i(s.data),a===void 0?void 0:{signal:a})}}function dn(e,t){const n=[];for(const o of e){if(typeof o.id!="string"||typeof o.type!="string")continue;if(o.type!=="assistant"){n.push({type:o.type,id:o.id,time:o.time});continue}const i=mn(o.model);let a=o.listCost;if(a===void 0&&t!==void 0&&i!==void 0&&(o.cost===void 0||o.cost<=0)){const s=t({providerID:i.providerID,modelID:i.id},{input:o.tokens?.input,output:o.tokens?.output,reasoning:o.tokens?.reasoning,cacheRead:o.tokens?.cache?.read,cacheWrite:o.tokens?.cache?.write});s!==void 0&&Number.isFinite(s)&&s>0&&(a=s)}n.push({type:"assistant",id:o.id,time:o.time,model:i,tokens:o.tokens,cost:o.cost,...a!==void 0?{listCost:a}:{},finish:o.finish??void 0,rawFinish:o.rawFinish??void 0})}return n}function pn(e,t=2,n){const o=Math.max(2,t),i=[];let a=0,s=0;for(let l=e.length-1;l>=0;l-=1){const p=e[l];if(p.type==="assistant"){i.push(p),a+=1;continue}if(!(p.type===void 0||!et.has(p.type))&&a!==0&&(i.push(p),a=0,s+=1,s>=o))break}return i.reverse(),dn(i,n)}function mn(e){if(!(e===void 0||e.providerID===void 0||e.id===void 0))return e.variant===void 0?{providerID:e.providerID,id:e.id}:{providerID:e.providerID,id:e.id,variant:e.variant}}function ae(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,Math.floor(e)):0}function Ve(e){return typeof e=="number"&&Number.isFinite(e)?Math.max(0,e):0}function wt(e,t=0){if(e===void 0)return;const n=e.tokens;return{input:ae(n?.input),cached:ae(n?.cache?.read),output:ae(n?.output),reasoning:ae(n?.reasoning),cacheWrite:ae(n?.cache?.write),cost:Ve(e.cost),listCost:Ve(t),steps:0}}function fn(e,t){if(e===void 0)return[];const n=[];return Bt(e,t).forEach((i,a)=>{a>0&&n.push({text:" · ",tone:"muted"}),n.push({text:ct(i.text),tone:i.tone})}),n}function gn(e){return e.map(t=>t.text).join("")}function vn(e){if(e.status!==void 0&&e.status!=="idle")return;const t=e.info===void 0?void 0:wt(e.info,e.listCost);return Rt(pn(e.messages,2,e.price),t)}function hn(e,t){if(t.fields?.cost===!1)return;if(e.status!==void 0&&e.status!=="idle"){if(t.fields?.session===!1)return;const i=wt(e.info(),e.listCost);return i===void 0?void 0:{label:at(i.cost,t.estimates?i.listCost:0),title:yn(i,t)}}const n=vn({messages:e.messages(),info:e.info(),listCost:e.listCost,status:e.status,price:e.price?.()});if(n===void 0)return;const o=bn(n,t);if(o!==void 0)return{label:o,title:xn(n,t)}}function bn(e,t){if(!(e===void 0||t.fields?.cost===!1))return at(e.totals.cost,t.estimates?e.totals.listCost:0)}function yn(e,t){return ct(Ut(e,{labels:t.labels,fields:t.fields,estimates:t.estimates}))}function wn(e,t){return fn(e,{labels:t.labels,fields:t.fields,turnTotals:t.turnTotals,estimates:t.estimates})}function xn(e,t){return gn(wn(e,t))}function le(e){return e==="muted"?"oui-tone-muted":e==="warning"?"oui-tone-warning":e==="accent"?"oui-tone-accent":"oui-tone-base"}var $n=r.template("<span data-slot=oui-header-badge-label>"),Cn=r.template("<button type=button data-component=oui-header-badge>"),Sn=r.template("<span data-component=oui-header-badge>");function kn(e){const t=P.usePlugin(),n=u.createMemo(()=>e.view()),o=u.createMemo(()=>n()?.label),i=u.createMemo(()=>n()?.title??""),a=()=>[r.createComponent(t.ui.Icon,{get name(){return e.icon},size:"small"}),r.createComponent(u.Show,{get when(){return!e.compact},get children(){var s=$n();return r.insert(s,o),s}})];return r.createComponent(u.Show,{get when(){return o()},get children(){return r.createComponent(u.Show,{get when(){return e.panelEnabled},get fallback(){return(()=>{var s=Sn();return r.insert(s,a),r.effect(l=>{var p=i(),m=i();return p!==l.e&&r.setAttribute(s,"title",l.e=p),m!==l.t&&r.setAttribute(s,"aria-label",l.t=m),l},{e:void 0,t:void 0}),s})()},get children(){var s=Cn();return s.$$click=()=>e.open(),r.insert(s,a),r.effect(l=>{var p=i(),m=e.compact?i():void 0;return p!==l.e&&r.setAttribute(s,"title",l.e=p),m!==l.t&&r.setAttribute(s,"aria-label",l.t=m),l},{e:void 0,t:void 0}),s}})}})}r.delegateEvents(["click"]);const _n="[data-component=oui-panel]{--oui-mono-size: 12px;--oui-mono-line: 18px;position:relative;display:flex;flex-direction:column;height:100%;min-height:0;background:var(--v2-background-bg-base);color:var(--v2-text-text-base)}[data-slot=oui-header]{display:flex;flex-direction:column;gap:8px;padding:10px 12px 8px;border-bottom:.5px solid var(--v2-border-border-base);flex:none}[data-slot=oui-title-row]{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}[data-slot=oui-title]{flex:none;font-size:13px;line-height:18px;font-weight:600;letter-spacing:-.04px;white-space:nowrap}[data-slot=oui-subtitle]{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;line-height:16px;color:var(--v2-text-text-muted)}[data-slot=oui-controls]{display:flex;flex-wrap:wrap;align-items:center;gap:6px}[data-slot=oui-controls] [data-component=oui-control]{min-width:0}[data-slot=oui-body]{flex:1;min-height:0;overflow:auto;scrollbar-gutter:stable;padding:6px 0 12px}[data-slot=oui-lines]{display:flex;flex-direction:column;min-width:max-content;padding:0 12px;font-family:var(--v2-font-family-mono, var(--font-family-mono, monospace));font-size:var(--oui-mono-size);line-height:var(--oui-mono-line);white-space:pre}[data-slot=oui-ruler-wrap]{position:absolute;top:0;left:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none}[data-slot=oui-ruler]{display:block;width:max-content;white-space:pre;font-family:var(--v2-font-family-mono, var(--font-family-mono, monospace));font-size:var(--oui-mono-size);line-height:var(--oui-mono-line)}[data-slot=oui-line]{display:block;width:100%;min-height:18px;padding:0;margin:0;border:0;background:transparent;text-align:left;font:inherit;color:inherit;white-space:pre}button[data-slot=oui-line][data-selectable=true]{cursor:pointer;border-radius:3px}button[data-slot=oui-line][data-selectable=true]:hover,button[data-slot=oui-line][data-selectable=true]:focus-visible{background:var(--v2-background-bg-layer-01);outline:none}button[data-slot=oui-line][data-selectable=true]:focus-visible{box-shadow:inset 0 0 0 1px var(--v2-border-border-focus)}[data-slot=oui-loading],[data-slot=oui-empty],[data-slot=oui-error]{padding:16px 12px;font-size:12px;line-height:18px;color:var(--v2-text-text-muted)}[data-slot=oui-error]{color:var(--v2-state-fg-danger)}[data-slot=oui-actions]{display:flex;flex-wrap:wrap;gap:6px;padding:10px 12px;border-top:.5px solid var(--v2-border-border-base);flex:none}[data-slot=oui-detail-head]{display:flex;align-items:center;gap:8px;min-width:0;padding:8px 12px 4px;flex:none}[data-slot=oui-detail-head] [data-slot=oui-subtitle]{flex:1}[data-slot=oui-divider]{height:.5px;background:var(--v2-border-border-base);margin:8px 0}[data-component=oui-header-badge]{display:inline-flex;align-items:center;gap:4px;font-family:inherit;font-size:11px;font-weight:600;letter-spacing:.02em;white-space:nowrap;background:transparent;border:0;padding:0;color:var(--v2-text-text-base)}button[data-component=oui-header-badge]{cursor:pointer}button[data-component=oui-header-badge]:hover{color:var(--v2-text-text-accent)}button[data-component=oui-header-badge]:focus-visible{outline:1px solid var(--v2-border-border-focus);outline-offset:2px;border-radius:3px}[data-slot=oui-header-badge-label]{color:inherit}.oui-tone-base{color:var(--v2-text-text-base)}.oui-tone-muted{color:var(--v2-text-text-muted)}.oui-tone-warning{color:var(--v2-state-fg-warning)}.oui-tone-accent{color:var(--v2-text-text-accent)}[data-slot=oui-go]{display:flex;flex-direction:column;gap:14px;padding:14px 12px 18px;color:var(--v2-text-text-base)}[data-slot=oui-go-header]{display:flex;align-items:center;justify-content:space-between;gap:10px}[data-slot=oui-go-title-row]{display:flex;align-items:baseline;gap:6px;min-width:0}[data-slot=oui-go-title]{font-size:13px;line-height:18px;font-weight:600;letter-spacing:-.04px}[data-slot=oui-go-workspace]{font-size:12px;line-height:18px;color:var(--v2-text-text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}[data-slot=oui-go-status]{flex:none;font-size:11px;line-height:16px;padding:1px 7px;border-radius:999px;color:var(--v2-text-text-muted);background:var(--v2-background-bg-layer-01)}[data-slot=oui-go-status][data-warning=true]{color:var(--v2-state-fg-warning)}[data-slot=oui-go-meters]{display:flex;flex-direction:column;gap:10px}[data-slot=oui-go-meter]{display:flex;flex-direction:column;gap:5px}[data-slot=oui-go-meter-head]{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:4px 10px;font-size:12px;line-height:16px}[data-slot=oui-go-meter-label]{font-weight:530}[data-slot=oui-go-meter-value]{color:var(--v2-text-text-muted);font-variant-numeric:tabular-nums;white-space:nowrap}[data-slot=oui-go-track]{position:relative;height:10px;overflow:hidden;border-radius:999px;background:var(--v2-background-bg-layer-01)}[data-slot=oui-go-fill]{height:100%;border-radius:inherit;background:var(--v2-text-text-accent);transition:width .18s ease}[data-slot=oui-go-track][data-reached=true] [data-slot=oui-go-fill]{background:var(--v2-state-fg-danger)}[data-slot=oui-go-projection]{position:absolute;top:0;bottom:0;background:repeating-linear-gradient(-45deg,var(--v2-state-fg-warning) 0 4px,transparent 4px 8px);opacity:.55;transition:left .18s ease,width .18s ease}[data-slot=oui-go-projection][data-over=true]{background:repeating-linear-gradient(-45deg,var(--v2-state-fg-danger) 0 4px,transparent 4px 8px);opacity:.62}[data-slot=oui-go-limit]{position:absolute;top:-2px;right:0;bottom:-2px;width:1.5px;background:var(--v2-text-text-muted);opacity:.7}[data-slot=oui-go-forecast]{display:flex;flex-direction:column;gap:7px;padding:12px;border:.5px solid var(--v2-border-border-base);border-radius:8px;background:var(--v2-background-bg-layer-01)}[data-slot=oui-go-forecast-head]{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:4px 10px;font-size:12px;line-height:16px}[data-slot=oui-go-forecast-title]{font-weight:600}[data-slot=oui-go-forecast-value]{color:var(--v2-text-text-muted);font-variant-numeric:tabular-nums;text-align:right}[data-slot=oui-go-forecast-value][data-warning=true]{color:var(--v2-state-fg-warning)}[data-slot=oui-go-legend]{display:flex;flex-wrap:wrap;gap:4px 12px;font-size:11px;line-height:15px;color:var(--v2-text-text-muted);font-variant-numeric:tabular-nums}[data-slot=oui-go-renewal]{font-size:12px;line-height:16px;font-variant-numeric:tabular-nums}[data-slot=oui-go-note]{font-size:11px;line-height:15px;color:var(--v2-text-text-muted)}[data-slot=oui-go-footer]{display:flex;align-items:center;gap:10px}[data-slot=oui-go-updated]{font-size:11px;line-height:15px;color:var(--v2-text-text-muted)}[data-slot=oui-go-updated][data-warning=true]{color:var(--v2-state-fg-warning)}[data-slot=oui-go-empty]{display:flex;flex-direction:column;gap:6px;padding:4px 0}[data-slot=oui-go-empty-title]{font-size:13px;line-height:18px;font-weight:600}[data-slot=oui-go-empty-body]{font-size:12px;line-height:18px;color:var(--v2-text-text-muted)}",Dn=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" aria-hidden="true">
2
2
  <path d="M2.5 13.25h11" stroke="currentColor" stroke-linecap="round" stroke-width="1.2" />
3
3
  <rect x="3.25" y="8.5" width="2.2" height="4" rx="0.6" fill="currentColor" />
4
4
  <rect x="6.9" y="5.75" width="2.2" height="6.75" rx="0.6" fill="currentColor" />
5
5
  <rect x="10.55" y="3" width="2.2" height="9.5" rx="0.6" fill="currentColor" />
6
6
  </svg>
7
- `,Rt={"command.title":"Usage insights","command.description":"Open the Usage insights panel","command.group":"Usage insights","command.noSession":"Open a session first, then run /usage","panel.title":"Usage insights","panel.loading":"Loading usage…","panel.unavailable":"Usage data is unavailable","panel.empty":"No usage recorded yet. Send a prompt to start.","panel.back":"Back","panel.refresh":"Refresh","panel.filters":"Filters","panel.model":"Model","panel.view":"View","panel.sort":"Sort","panel.range":"Range","panel.scope":"Scope","panel.granularity":"Granularity","panel.provider":"Provider","panel.allModels":"All models","panel.allProviders":"All providers","panel.descending":"Descending","panel.ascending":"Ascending","panel.thisSession":"This session","panel.allSessions":"All sessions","panel.turns":"Turns insights","panel.db":"Database","panel.backfill":"Backfill estimates","panel.prune":"Prune older than {{days}} days","panel.wipe":"Wipe all history","panel.wipeConfirm":"Delete everything","panel.vacuum":"Compact database","panel.copyPath":"Copy path","panel.pathCopied":"Database path copied","panel.pruned":"Pruned {{steps}} steps · {{prompts}} prompts · {{events}} compactions","panel.wiped":"Wiped {{steps}} steps · {{prompts}} prompts · {{events}} compactions · {{usage}} usage · {{sessions}} sessions","panel.backfilled":"Backfilled {{updated}} of {{candidates}} steps","panel.vacuumed":"Compacted: {{size}} MB back","panel.busy":"The recorder is writing. Try again in a moment.","panel.confirmPrune":"Delete usage older than {{days}} days?","panel.confirmPruneDetail":"{{steps}} of {{total}} steps would be deleted. This cannot be undone.","panel.confirmWipe":"Delete all recorded usage?","panel.confirmWipeDetail":"{{steps}} steps and {{sessions}} sessions would be deleted, with their prompts, compactions and other usage. This cannot be undone.","panel.confirmBackfill":"Backfill list-price estimates?","panel.confirmBackfillDetail":"{{count}} steps recorded at $0 have no estimate. Those with a known catalog price will be filled using today's catalog.","panel.confirmVacuum":"Compact the database?","panel.confirmVacuumDetail":"SQLite rewrites the file to reclaim deleted space. It needs the recorder to be idle and can take a moment.","panel.confirm":"Confirm","panel.cancel":"Cancel","panel.pricingOff":"List-price estimates are turned off","panel.noUnpriced":"Every $0 step already has a list estimate","panel.openUsage":"Open usage insights","panel.openTurns":"Open turns insights","panel.noTurns":"No finished turns yet","view.overview":"Overview","view.models":"Models","view.providers":"Providers","view.cache":"Cache","view.periods":"Periods","view.latency":"Latency","view.sessions":"Sessions","view.turns":"Turns","view.db":"Database","range.session":"This session","range.today":"Today","range.7d":"7 days","range.30d":"30 days","range.all":"All time","granularity.day":"Day","granularity.week":"Week","granularity.month":"Month","sort.steps":"Steps","sort.cached":"Cached","sort.hit":"Hit","sort.out":"Out","sort.cost":"Cost","sort.share":"Share","sort.tps":"Tok/s","sort.wall":"Wall","sort.last":"Last","sort.time":"Time","sort.tokens":"Tokens","sort.n":"Count"};var $e=n.template("<div data-slot=oui-loading>");const jt=m.lazy(()=>Promise.resolve().then(()=>Jt).then(e=>({default:e.UsagePanel}))),At=m.lazy(()=>Promise.resolve().then(()=>sn).then(e=>({default:e.TurnsPanel}))),Nt=P.Store.global(R.Schema.Struct({view:R.Schema.String,range:R.Schema.String,sort:R.Schema.String,sortDesc:R.Schema.Boolean,granularity:R.Schema.String,turnsScope:R.Schema.String,modelID:R.Schema.String,providerID:R.Schema.String}),O),zt=300*1e3,qt=300,Bt=P.Plugin.define({stores:{panel:Nt},icons:{usage:Et},i18n:{en:Rt},setup(e){const t=e.options??{};if(t.enabled===!1)return;const i=t.panel!==!1,r=t.pricing!=="off",o=`${e.id}:usage`,a=ze(t.sidebarTurns??8),s=m.createMemo(()=>Te(e.stores.panel.value)),l=u=>{e.stores.panel.update(_=>{u(_)})},d=()=>({labels:t.labels,fields:t.fields,turnTotals:t.turnTotals,estimates:r}),[S,h]=m.createSignal(0);let C,I=0;function v(){const u=Date.now(),_=I+qt-u;if(_<=0){I=u,h(D=>D+1);return}C===void 0&&(C=setTimeout(()=>{C=void 0,I=Date.now(),h(D=>D+1)},_))}m.onCleanup(()=>{C!==void 0&&clearTimeout(C)}),P.createKeyed(()=>e.sessions.current()?.server.client??e.servers.get("sidecar")?.client??e.client,u=>m.onCleanup((()=>{try{return V(u).onRecorded(()=>v())}catch{return()=>{}}})()));const x=P.createLatest(()=>{if(!r)return;const u=e.sessions.current();if(u)return{key:u.key,client:u.server.client,id:u.id,directory:u.directory,refresh:S()}},(u,_)=>V(u.client,{directory:u.directory}).listCost({sessionID:u.id},_));function $(u){return e.sessions.current()?.key!==u.key?0:x.latest?.cost??0}let g;function E(u){if(!r)return;const _=`${u.server.id}
8
- ${u.location?.directory??u.directory}`,D=Date.now();if(g===void 0||g.key!==_||D-g.at>=zt)try{const y=u.server.data.location.model.list(u.location);y!==void 0&&y.length>0&&(g={key:_,table:at(y),at:D})}catch{}if(g===void 0||g.key!==_)return;const b=g.table;return(y,q)=>ct(b,y,q)}P.createKeyed(()=>e.sessions.current()?.server.data??e.servers.get("sidecar")?.data,u=>m.onCleanup(u.on("model.updated",()=>{g=void 0})));function Q(u){try{return Dt({status:u.server.data.session.status(u.id),messages:()=>u.server.data.session.message.list(u.id),info:()=>u.server.data.session.get(u.id),listCost:$(u),price:()=>E(u)})}catch{return}}function G(u){e.layout.open(`${e.id}:turns`,u,{tab:"select"})}function K(u,_,D=!1){if(D){const b=e.layout.state(o,u);if(b==="visible"||b==="active"){e.layout.close(o,u);return}}e.layout.open(o,u,{tab:"select"})}function Z(u){const _=e.sessions.current();if(!_){e.toast.show({title:e.t("command.title"),description:e.t("command.noSession"),variant:"error"});return}const D=ot(u);(D.view!==void 0||D.range!==void 0)&&l(b=>{D.view!==void 0&&(b.view=D.view,b.sort=se(D.view)),D.range!==void 0&&(b.range=D.range)}),K(_,void 0,(u??"").trim()==="")}if(e.add(P.Style,Lt),i){const u=(b,y,q)=>({id:b,title:e.t("command.title"),description:e.t("command.description"),group:e.t("command.group"),section:"session",...q===!0?{hidden:!0}:{},slash:{name:y,arguments:!0},run:ee=>Z(ee)});e.add(P.Command,()=>u("usage","usage")),e.add(P.Command,()=>u("insights","insights",!0));const _={id:"usage",get title(){return e.t("panel.title")},closable:"hover",fallback:!0},D={id:"turns",get title(){return e.t("panel.turns")},closable:"hover"};e.add(P.Panel,{id:"usage",region:"side",width:520,mobile:{get title(){return e.t("panel.title")},order:50,kind:"tab",icon:e.icons.usage,cached:!0},list:b=>b.open.map(y=>y==="usage"?_:y==="turns"?D:void 0).filter(y=>y!==void 0),render:b=>b.tab.id==="turns"?n.createComponent(m.Suspense,{get fallback(){return(()=>{var y=$e();return n.insert(y,()=>e.t("panel.loading")),y})()},get children(){return n.createComponent(At,{get session(){return b.session},refresh:S,limit:a})}}):n.createComponent(m.Suspense,{get fallback(){return(()=>{var y=$e();return n.insert(y,()=>e.t("panel.loading")),y})()},get children(){return n.createComponent(jt,{get session(){return b.session},settings:s,update:l,refresh:S,bump:v,pricing:r,get maintenance(){return t.maintenance!==!1}})}})}),e.add(P.MenuItem,()=>{const b=e.sessions.current();return{menu:"session.panel",id:"usage",title:e.t("panel.title"),icon:e.icons.usage,opened:b!==void 0&&e.layout.state(o,b)!=="closed",run:()=>{const y=e.sessions.current();y&&K(y)}}}),e.add(P.MenuItem,()=>{const b=e.sessions.current();return{menu:"session.panel",id:"turns",title:e.t("panel.turns"),icon:e.icons.usage,opened:b!==void 0&&e.layout.state(`${e.id}:turns`,b)!=="closed",run:()=>{const y=e.sessions.current();y&&G(y)}}})}e.add(P.Slot,{at:"session.header",order:90,render:u=>n.createComponent(Ft,{line:()=>Q(u.session),get options(){return d()},get icon(){return e.icons.usage},get compact(){return u.compact},panelEnabled:i,open:()=>G(u.session)})})}});var Ot=n.template("<div data-slot=oui-empty>"),Wt=n.template("<div data-slot=oui-lines>"),Ut=n.template("<div data-component=oui-panel><div data-slot=oui-header><div data-slot=oui-title-row><span data-slot=oui-title></span><span data-slot=oui-subtitle></span></div><div data-slot=oui-controls></div></div><div data-slot=oui-body data-scrollable></div><div data-slot=oui-actions>"),Vt=n.template("<div data-slot=oui-detail-head><span data-slot=oui-subtitle>"),Gt=n.template("<div data-slot=oui-error>"),Kt=n.template("<div data-slot=oui-loading>"),Ht=n.template("<button type=button data-slot=oui-line data-selectable=true>"),Xt=n.template("<div data-slot=oui-line>");function A(e){return e instanceof Error?e.message:e!==null&&typeof e=="object"&&"message"in e?String(e.message):""}function Yt(e){const t=P.usePlugin(),i=P.usePanel(),[r,o]=m.createSignal(void 0),[a,s]=m.createSignal(!1),l=m.createMemo(()=>Te(e.settings())),d=()=>l().view,S=()=>i.placement()==="mobile"?48:72,h=()=>V(e.session.server.client,{directory:e.session.directory}),C=m.createMemo(()=>{if(e.refresh(),!i.visible())return;const c=l();return{sessionID:e.session.id,settings:c,...r()!==void 0?{detail:r()}:{},width:S(),busy:a()}}),I=m.createMemo(()=>{const c=C();if(c!==void 0)return{input:c,client:e.session.server.client,directory:e.session.directory}}),v=P.createLatest(I,(c,f)=>V(c.client,{directory:c.directory}).panel(c.input,f)),x=m.createMemo(()=>(v.latest?.lines??[]).filter(c=>c.hint!==!0&&(e.maintenance||c.row?.kind!=="prune"&&c.row?.kind!=="wipe"))),$=m.createMemo(()=>v.latest?.database),g=(c,f,F="default")=>{t.toast.show({title:c,description:f,variant:F})},E=c=>{e.update(c)},Q=c=>{E(f=>{f.view=c,f.sort=se(c),f.sortDesc=!0}),o(void 0)},G=c=>E(f=>{f.range=c}),K=c=>E(f=>{f.granularity=c}),Z=c=>E(f=>{f.turnsScope=c}),u=c=>E(f=>{f.sort=c}),_=()=>E(c=>{c.sortDesc=!c.sortDesc});async function D(c){let f;try{f=await h().filters()}catch(w){g(t.t("panel.unavailable"),A(w),"error");return}l();const F=c==="model"?f.models:f.providers,M=c==="model"?t.t("panel.model"):t.t("panel.provider"),k=await t.dialogs.select({title:M,options:[{title:c==="model"?t.t("panel.allModels"):t.t("panel.allProviders"),value:""},...F.map(w=>({title:`${w.value} · ${w.steps}`,value:w.value}))]});k!==void 0&&(E(w=>{c==="model"?w.modelID=k:w.providerID=k}),o(void 0))}const b=()=>{try{return e.session.server.data.session.status(e.session.id)==="running"}catch{return!1}};async function y(c){if(b()){g(t.t("panel.title"),t.t("panel.busy"),"error");return}const f=$(),F=f?.removable.find(w=>w.days===c)?.steps,M=f?.tables.find(w=>w.name==="steps")?.rows??0;if(await t.dialogs.confirm({title:t.t("panel.confirmPrune",{days:c}),description:t.t("panel.confirmPruneDetail",{steps:F??0,total:M}),confirm:t.t("panel.prune",{days:c}),cancel:t.t("panel.cancel"),danger:!0})){try{const w=await h().prune({days:c,confirm:!0});g(t.t("panel.pruned",{steps:w.steps,prompts:w.prompts,events:w.events}),void 0,"success"),s(!1)}catch(w){s(!0),g(t.t("panel.title"),A(w),"error")}e.bump()}}async function q(){if(b()){g(t.t("panel.title"),t.t("panel.busy"),"error");return}const c=$(),f=c?.tables.find(k=>k.name==="steps")?.rows??0,F=c?.tables.find(k=>k.name==="sessions")?.rows??0;if(await t.dialogs.confirm({title:t.t("panel.confirmWipe"),description:t.t("panel.confirmWipeDetail",{steps:f,sessions:F}),confirm:t.t("panel.wipeConfirm"),cancel:t.t("panel.cancel"),danger:!0})){try{const k=await h().wipe({confirm:!0});g(t.t("panel.wiped",{steps:k.steps,prompts:k.prompts,events:k.events,usage:k.usage,sessions:k.sessions}),void 0,"success"),s(!1)}catch(k){s(!0),g(t.t("panel.title"),A(k),"error")}e.bump()}}async function ee(){if(!e.pricing){g(t.t("panel.pricingOff"));return}if(b()){g(t.t("panel.title"),t.t("panel.busy"),"error");return}const c=$(),f=c?.unpriced??0;if(c!==void 0&&f===0){g(t.t("panel.noUnpriced"));return}if(await t.dialogs.confirm({title:t.t("panel.confirmBackfill"),description:t.t("panel.confirmBackfillDetail",{count:f}),confirm:t.t("panel.backfill"),cancel:t.t("panel.cancel")})){try{const M=await h().backfill({confirm:!0});g(t.t("panel.backfilled",{updated:re(M.updated),candidates:re(M.candidates)}),void 0,"success"),s(!1)}catch(M){s(!0),g(t.t("panel.title"),A(M),"error")}e.bump()}}async function Fe(){if(b()){g(t.t("panel.title"),t.t("panel.busy"),"error");return}if(await t.dialogs.confirm({title:t.t("panel.confirmVacuum"),description:t.t("panel.confirmVacuumDetail"),confirm:t.t("panel.vacuum"),cancel:t.t("panel.cancel")})){try{const f=await h().vacuum({confirm:!0});g(t.t("panel.vacuumed",{size:(f.freed/1048576).toFixed(1)}),void 0,"success"),s(!1)}catch(f){s(!0),g(t.t("panel.title"),A(f),"error")}e.bump()}}async function Le(){const c=$()?.path;if(c!==void 0)try{await t.system.copy(c),g(t.t("panel.pathCopied"))}catch(f){g(t.t("panel.title"),A(f),"error")}}const Ee=c=>{if(c.kind==="prune"){y(Number.parseInt(c.value,10));return}if(c.kind==="wipe"){q();return}o(c)},Re=()=>t.t(`range.${l().range}`),ce=()=>st(l()),ue=()=>Pe[d()]??[],je=()=>x()[0]?.text??"";return(()=>{var c=Ut(),f=c.firstChild,F=f.firstChild,M=F.firstChild,k=M.nextSibling,w=F.nextSibling,te=f.nextSibling,de=te.nextSibling;return n.insert(M,()=>t.t("panel.title")),n.insert(k,Re,null),n.insert(k,(()=>{var p=n.memo(()=>ce()!==void 0);return()=>p()?` · ${ce()}`:""})(),null),n.insert(k,()=>v.loading?" · …":"",null),n.insert(w,n.createComponent(t.ui.Select,{get label(){return t.t("panel.view")},get value(){return d()},get options(){return ae.map(p=>({value:p,label:t.t(`view.${p}`)}))},onChange:p=>Q(p)}),null),n.insert(w,n.createComponent(t.ui.Select,{get label(){return t.t("panel.range")},get value(){return l().range},get options(){return le.map(p=>({value:p,label:t.t(`range.${p}`)}))},onChange:p=>G(p)}),null),n.insert(w,n.createComponent(m.Show,{get when(){return ue().length>0},get children(){return[n.createComponent(t.ui.Select,{get label(){return t.t("panel.sort")},get value(){return n.memo(()=>l().sort==="")()?se(d()):l().sort},get options(){return ue().map(p=>({value:p,label:t.t(`sort.${p}`)}))},onChange:u}),n.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:_,get children(){return l().sortDesc?"↓":"↑"}})]}}),null),n.insert(w,n.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:()=>{D("model")},get children(){return n.memo(()=>l().modelID==="")()?t.t("panel.model"):l().modelID}}),null),n.insert(w,n.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:()=>{D("provider")},get children(){return n.memo(()=>l().providerID==="")()?t.t("panel.provider"):l().providerID}}),null),n.insert(w,n.createComponent(m.Show,{get when(){return d()==="turns"},get children(){return n.createComponent(t.ui.Select,{get label(){return t.t("panel.scope")},get value(){return l().turnsScope},get options(){return[{value:"session",label:t.t("panel.thisSession")},{value:"all",label:t.t("panel.allSessions")}]},onChange:p=>Z(p)})}}),null),n.insert(w,n.createComponent(m.Show,{get when(){return d()==="periods"},get children(){return n.createComponent(t.ui.Select,{get label(){return t.t("panel.granularity")},get value(){return l().granularity},get options(){return _e.map(p=>({value:p,label:t.t(`granularity.${p}`)}))},onChange:p=>K(p)})}}),null),n.insert(w,n.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:()=>e.bump(),get children(){return t.t("panel.refresh")}}),null),n.insert(c,n.createComponent(m.Show,{get when(){return r()},children:p=>(()=>{var T=Vt(),L=T.firstChild;return n.insert(T,n.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:()=>o(void 0),get children(){return["← ",n.memo(()=>t.t("panel.back"))]}}),L),n.insert(L,je),T})()}),te),n.insert(te,n.createComponent(m.Show,{get when(){return v.latest!==void 0},get fallback(){return n.createComponent(m.Show,{get when(){return v.error!==void 0},get fallback(){return(()=>{var p=Kt();return n.insert(p,()=>t.t("panel.loading")),p})()},get children(){var p=Gt();return n.insert(p,()=>t.t("panel.unavailable")),n.effect(()=>n.setAttribute(p,"title",A(v.error))),p}})},get children(){return[n.createComponent(m.Show,{get when(){return x().length===0},get children(){var p=Ot();return n.insert(p,()=>t.t("panel.empty")),p}}),(()=>{var p=Wt();return n.insert(p,n.createComponent(m.For,{get each(){return x()},children:T=>n.createComponent(m.Show,{get when(){return T.row!==void 0},get fallback(){return(()=>{var L=Xt();return n.insert(L,()=>T.text),n.effect(()=>n.className(L,J(T.tone))),L})()},get children(){var L=Ht();return L.$$click=()=>Ee(T.row),n.insert(L,()=>T.text),n.effect(()=>n.className(L,J(T.tone))),L}})})),n.effect(T=>n.setStyleProperty(p,"font-family",t.appearance.font("mono"))),p})()]}})),n.insert(de,n.createComponent(t.ui.Button,{size:"small",variant:"neutral",onClick:()=>t.layout.open(`${t.id}:turns`,e.session,{tab:"select"}),get children(){return t.t("panel.openTurns")}}),null),n.insert(de,n.createComponent(m.Show,{get when(){return n.memo(()=>!!(e.maintenance&&d()==="db"))()&&$()},children:p=>[n.createComponent(t.ui.Button,{size:"small",variant:"neutral",get disabled(){return!e.pricing||p().unpriced===0},onClick:()=>{ee()},get children(){return[n.memo(()=>t.t("panel.backfill"))," (",n.memo(()=>re(p().unpriced)),")"]}}),n.createComponent(m.For,{get each(){return p().removable},children:T=>n.createComponent(t.ui.Button,{size:"small",variant:"danger",onClick:()=>{y(T.days)},get children(){return t.t("panel.prune",{days:T.days})}})}),n.createComponent(t.ui.Button,{size:"small",variant:"danger",onClick:()=>{q()},get children(){return t.t("panel.wipe")}}),n.createComponent(t.ui.Button,{size:"small",variant:"neutral",onClick:()=>{Fe()},get children(){return t.t("panel.vacuum")}}),n.createComponent(t.ui.Button,{size:"small",variant:"ghost-muted",onClick:()=>{Le()},get children(){return t.t("panel.copyPath")}})]}),null),c})()}n.delegateEvents(["click"]);const Jt=Object.freeze(Object.defineProperty({__proto__:null,UsagePanel:Yt},Symbol.toStringTag,{value:"Module"}));var Qt=n.template("<div data-component=oui-panel><div data-slot=oui-header><div data-slot=oui-title-row><span data-slot=oui-title></span><span data-slot=oui-subtitle></span></div></div><div data-slot=oui-body data-scrollable></div><div data-slot=oui-actions>"),Zt=n.template("<div data-slot=oui-error>"),en=n.template("<div data-slot=oui-loading>"),tn=n.template("<div data-slot=oui-divider aria-hidden=true>"),nn=n.template("<div data-slot=oui-lines>"),Se=n.template("<div data-slot=oui-line>"),rn=n.template("<div data-slot=oui-empty>");function on(e){const t=P.usePlugin(),i=P.usePanel(),r=m.createMemo(()=>{if(i.visible())return{client:e.session.server.client,id:e.session.id,directory:e.session.directory,refresh:e.refresh()}}),o=P.createLatest(r,(s,l)=>V(s.client,{directory:s.directory}).turns({sessionID:s.id,limit:e.limit,width:64},l)),a=s=>s.filter(l=>l.hint!==!0);return(()=>{var s=Qt(),l=s.firstChild,d=l.firstChild,S=d.firstChild,h=S.nextSibling,C=l.nextSibling,I=C.nextSibling;return n.insert(S,()=>t.t("panel.turns")),n.insert(h,()=>o.loading?"…":""),n.insert(C,n.createComponent(m.Show,{get when(){return o.latest},get fallback(){return n.createComponent(m.Show,{get when(){return o.error!==void 0},get fallback(){return(()=>{var v=en();return n.insert(v,()=>t.t("panel.loading")),v})()},get children(){var v=Zt();return n.insert(v,()=>t.t("panel.unavailable")),v}})},children:v=>(()=>{var x=nn();return n.insert(x,n.createComponent(m.For,{get each(){return a(v().summary)},children:$=>(()=>{var g=Se();return n.insert(g,()=>$.text),n.effect(()=>n.className(g,J($.tone))),g})()}),null),n.insert(x,n.createComponent(m.Show,{get when(){return v().history.length>0},get fallback(){return(()=>{var $=rn();return n.insert($,()=>t.t("panel.noTurns")),$})()},get children(){return[tn(),n.createComponent(m.For,{get each(){return a(v().history)},children:$=>(()=>{var g=Se();return n.insert(g,()=>$.text),n.effect(()=>n.className(g,J($.tone))),g})()})]}}),null),n.effect($=>n.setStyleProperty(x,"font-family",t.appearance.font("mono"))),x})()})),n.insert(I,n.createComponent(t.ui.Button,{size:"small",variant:"neutral",onClick:()=>t.layout.open(`${t.id}:usage`,e.session,{tab:"select"}),get children(){return t.t("panel.openUsage")}})),s})()}const sn=Object.freeze(Object.defineProperty({__proto__:null,TurnsPanel:on},Symbol.toStringTag,{value:"Module"}));exports.default=Bt;
7
+ `,Mn={"command.title":"Usage insights","command.description":"Open the Usage insights panel","command.group":"Usage insights","command.noSession":"Open a session first, then run /usage-insights","panel.title":"Usage insights","panel.loading":"Loading usage…","panel.unavailable":"Usage data is unavailable","panel.empty":"No usage recorded yet. Send a prompt to start.","panel.back":"Back","panel.refresh":"Refresh","panel.filters":"Filters","panel.model":"Model","panel.view":"View","panel.sort":"Sort","panel.range":"Range","panel.scope":"Scope","panel.granularity":"Granularity","panel.provider":"Provider","panel.allModels":"All models","panel.allProviders":"All providers","panel.descending":"Descending","panel.ascending":"Ascending","panel.thisSession":"This session","panel.allSessions":"All sessions","panel.turns":"Turns insights","panel.db":"Database","panel.backfill":"Backfill estimates","panel.prune":"Prune older than {{days}} days","panel.wipe":"Wipe all history","panel.wipeConfirm":"Delete everything","panel.vacuum":"Compact database","panel.copyPath":"Copy path","panel.pathCopied":"Database path copied","panel.pruned":"Pruned {{steps}} steps · {{prompts}} prompts · {{events}} compactions","panel.wiped":"Wiped {{steps}} steps · {{prompts}} prompts · {{events}} compactions · {{usage}} usage · {{sessions}} sessions","panel.backfilled":"Backfilled {{updated}} of {{candidates}} steps","panel.vacuumed":"Compacted: {{size}} MB back","panel.busy":"The recorder is writing. Try again in a moment.","panel.confirmPrune":"Delete usage older than {{days}} days?","panel.confirmPruneDetail":"{{steps}} of {{total}} steps would be deleted. This cannot be undone.","panel.confirmWipe":"Delete all recorded usage?","panel.confirmWipeDetail":"{{steps}} steps and {{sessions}} sessions would be deleted, with their prompts, compactions and other usage. This cannot be undone.","panel.confirmBackfill":"Backfill list-price estimates?","panel.confirmBackfillDetail":"{{count}} steps recorded at $0 have no estimate. Those with a known catalog price will be filled using today's catalog.","panel.confirmVacuum":"Compact the database?","panel.confirmVacuumDetail":"SQLite rewrites the file to reclaim deleted space. It needs the recorder to be idle and can take a moment.","panel.confirm":"Confirm","panel.cancel":"Cancel","panel.pricingOff":"List-price estimates are turned off","panel.noUnpriced":"Every $0 step already has a list estimate","panel.openUsage":"Open usage insights","panel.openTurns":"Open turns insights","panel.noTurns":"No finished turns yet","panel.go.subtitle":"OpenCode Go · live","panel.go.open":"Open usage page","view.overview":"Overview","view.models":"Models","view.providers":"Providers","view.cache":"Cache","view.periods":"Periods","view.latency":"Latency","view.sessions":"Sessions","view.turns":"Turns","view.db":"Database","view.go":"OpenCode Go","range.session":"This session","range.today":"Today","range.7d":"7 days","range.30d":"30 days","range.all":"All time","granularity.day":"Day","granularity.week":"Week","granularity.month":"Month","sort.steps":"Steps","sort.cached":"Cached","sort.hit":"Hit","sort.out":"Out","sort.cost":"Cost","sort.share":"Share","sort.tps":"Tok/s","sort.wall":"Wall","sort.last":"Last","sort.time":"Time","sort.tokens":"Tokens","sort.n":"Count"};var Ke=r.template("<div data-slot=oui-loading>");const Tn=u.lazy(()=>Promise.resolve().then(()=>pr).then(e=>({default:e.UsagePanel}))),In=u.lazy(()=>Promise.resolve().then(()=>br).then(e=>({default:e.TurnsPanel}))),Pn=P.Store.global(G.Schema.Struct({view:G.Schema.String,range:G.Schema.String,sort:G.Schema.String,sortDesc:G.Schema.Boolean,granularity:G.Schema.String,turnsScope:G.Schema.String,modelID:G.Schema.String,providerID:G.Schema.String}),ee),An=300*1e3,En=300,Fn=P.Plugin.define({stores:{panel:Pn},icons:{usage:Dn},i18n:{en:Mn},setup(e){const t=e.options??{};if(t.enabled===!1)return;const n=t.panel!==!1,o=t.pricing!=="off",i=t.quota!=="off",a=t.quotaName,s=i?Pe:gt,l=`${e.id}:usage`,p=It(t.sidebarTurns??8),m=u.createMemo(()=>bt(e.stores.panel.value,s)),g=c=>{e.stores.panel.update(D=>{c(D)})},C=()=>({labels:t.labels,fields:t.fields,turnTotals:t.turnTotals,estimates:o}),[y,_]=u.createSignal(0);let v,w=0;function f(){const c=Date.now(),D=w+En-c;if(D<=0){w=c,_(S=>S+1);return}v===void 0&&(v=setTimeout(()=>{v=void 0,w=Date.now(),_(S=>S+1)},D))}u.onCleanup(()=>{v!==void 0&&clearTimeout(v)}),P.createKeyed(()=>e.sessions.current()?.server.client??e.servers.get("sidecar")?.client??e.client,c=>u.onCleanup((()=>{try{return ce(c).onRecorded(()=>f())}catch{return()=>{}}})()));const h=P.createLatest(()=>{if(!o)return;const c=e.sessions.current();if(c)return{key:c.key,client:c.server.client,id:c.id,directory:c.directory,refresh:y()}},(c,D)=>ce(c.client,{directory:c.directory}).listCost({sessionID:c.id},D));function I(c){return e.sessions.current()?.key!==c.key?0:h.latest?.cost??0}let M;function R(c){if(!o)return;const D=`${c.server.id}
8
+ ${c.location?.directory??c.directory}`,S=Date.now();if(M===void 0||M.key!==D||S-M.at>=An)try{const x=c.server.data.location.model.list(c.location);x!==void 0&&x.length>0&&(M={key:D,table:Zt(x),at:S})}catch{}if(M===void 0||M.key!==D)return;const k=M.table;return(x,F)=>tn(k,x,F)}P.createKeyed(()=>e.sessions.current()?.server.data??e.servers.get("sidecar")?.data,c=>u.onCleanup(c.on("model.updated",()=>{M=void 0})));function N(c){try{return hn({status:c.server.data.session.status(c.id),messages:()=>c.server.data.session.message.list(c.id),info:()=>c.server.data.session.get(c.id),listCost:I(c),price:()=>R(c)},C())}catch{return}}function W(c){e.layout.open(`${e.id}:turns`,c,{tab:"select"})}function L(c,D,S=!1){if(S){const k=e.layout.state(l,c);if(k==="visible"||k==="active"){e.layout.close(l,c);return}}e.layout.open(l,c,{tab:"select"})}function z(c){const D=e.sessions.current();if(!D){e.toast.show({title:e.t("command.title"),description:e.t("command.noSession"),variant:"error"});return}const S=Yt(c,s);(S.view!==void 0||S.range!==void 0)&&g(k=>{S.view!==void 0&&(k.view=S.view,k.sort=Ie(S.view)),S.range!==void 0&&(k.range=S.range)}),L(D,void 0,(c??"").trim()==="")}if(e.add(P.Style,_n),n){const c=(k,x,F)=>({id:k,title:e.t("command.title"),description:e.t("command.description"),group:e.t("command.group"),section:"session",...F===!0?{hidden:!0}:{},slash:{name:x,arguments:!0},run:X=>z(X)});e.add(P.Command,()=>c("usage-insights","usage-insights")),e.add(P.Command,()=>c("insights","insights",!0));const D={id:"usage",get title(){return e.t("panel.title")},closable:"hover",fallback:!0},S={id:"turns",get title(){return e.t("panel.turns")},closable:"hover"};e.add(P.Panel,{id:"usage",region:"side",width:520,mobile:{get title(){return e.t("panel.title")},order:50,kind:"tab",icon:e.icons.usage,cached:!0},list:k=>k.open.map(x=>x==="usage"?D:x==="turns"?S:void 0).filter(x=>x!==void 0),render:k=>k.tab.id==="turns"?r.createComponent(u.Suspense,{get fallback(){return(()=>{var x=Ke();return r.insert(x,()=>e.t("panel.loading")),x})()},get children(){return r.createComponent(In,{get session(){return k.session},refresh:y,limit:p,quotaEnabled:i,quotaName:a})}}):r.createComponent(u.Suspense,{get fallback(){return(()=>{var x=Ke();return r.insert(x,()=>e.t("panel.loading")),x})()},get children(){return r.createComponent(Tn,{get session(){return k.session},settings:m,update:g,refresh:y,bump:f,pricing:o,get maintenance(){return t.maintenance!==!1},views:s,quotaEnabled:i,quotaName:a})}})}),e.add(P.MenuItem,()=>{const k=e.sessions.current();return{menu:"session.panel",id:"usage",title:e.t("panel.title"),icon:e.icons.usage,opened:k!==void 0&&e.layout.state(l,k)!=="closed",run:()=>{const x=e.sessions.current();x&&L(x)}}}),e.add(P.MenuItem,()=>{const k=e.sessions.current();return{menu:"session.panel",id:"turns",title:e.t("panel.turns"),icon:e.icons.usage,opened:k!==void 0&&e.layout.state(`${e.id}:turns`,k)!=="closed",run:()=>{const x=e.sessions.current();x&&W(x)}}})}e.add(P.Slot,{at:"session.header",order:90,render:c=>r.createComponent(kn,{view:()=>N(c.session),get icon(){return e.icons.usage},get compact(){return c.compact},panelEnabled:n,open:()=>W(c.session)})})}});function Qe(e){return typeof e=="number"&&Number.isFinite(e)}function ke(e){if(!(e===void 0||!Qe(e.percent)||!Qe(e.resetsAt)))return{percent:Math.min(100,Math.max(0,Math.round(e.percent))),limited:e.limited===!0,resetsAt:e.resetsAt}}function Ln(e){const t=e?.workspace;if(!(t==null||typeof t.id!="string"||t.id===""))return{id:t.id,...typeof t.name=="string"&&t.name!==""?{name:t.name}:{},...typeof t.usageURL=="string"&&t.usageURL!==""?{usageURL:t.usageURL}:{}}}function Rn(e,t=Date.now()){if(e==null)return{kind:"none",reason:"console"};const n=e,o=n?.go;if(o==null)return{kind:"none",reason:"subscription"};const i=ke(o.rolling),a=ke(o.weekly),s=ke(o.monthly);if(i===void 0||a===void 0||s===void 0)return{kind:"none",reason:"subscription"};const l=Ln(n);return{kind:"ok",quota:{...l!==void 0?{workspace:l}:{},rolling:i,weekly:a,monthly:s,observedAt:t}}}async function xt(e,t,n){const o=e.experimental?.usage;if(typeof o?.limits!="function")throw new Error("this OpenCode build does not expose Go usage limits");const a=(await o.limits(t?.directory!==void 0?{location:{directory:t.directory}}:void 0,n!==void 0?{signal:n}:void 0))?.data;return Rn(a,Date.now())}var Nn=r.template("<div data-slot=oui-go-meter><div data-slot=oui-go-meter-head><span data-slot=oui-go-meter-label></span><span data-slot=oui-go-meter-value> · </span></div><div data-slot=oui-go-track role=img><div data-slot=oui-go-fill>"),qn=r.template("<div data-slot=oui-go>"),zn=r.template("<div data-slot=oui-go-empty><div data-slot=oui-go-empty-title></div><div data-slot=oui-go-empty-body>"),On=r.template("<div data-slot=oui-error>Go quota unavailable: "),jn=r.template("<div data-slot=oui-loading>Reading OpenCode Go quota…"),Un=r.template("<div data-slot=oui-go-header><div data-slot=oui-go-title-row><span data-slot=oui-go-title></span><span data-slot=oui-go-workspace>· </span></div><span data-slot=oui-go-status>"),Bn=r.template("<div data-slot=oui-go-meters>"),Wn=r.template("<div data-slot=oui-go-forecast><div data-slot=oui-go-forecast-head><span data-slot=oui-go-forecast-title>Forecast at renewal</span><span data-slot=oui-go-forecast-value></span></div><div data-slot=oui-go-track data-forecast=true role=img><div data-slot=oui-go-fill></div><div data-slot=oui-go-projection></div><div data-slot=oui-go-limit></div></div><div data-slot=oui-go-legend><span>Now <!>%</span><span>Forecast <!>%</span><span>% headroom</span></div><div data-slot=oui-go-renewal></div><div data-slot=oui-go-note>"),Gn=r.template("<span data-slot=oui-go-updated>Refreshing…"),Vn=r.template("<div data-slot=oui-go-footer>"),Kn=r.template("<span data-slot=oui-go-updated data-warning=true>Refresh failed: ");function Qn(e){try{return e.server.data.location.provider.list(e.location)?.find(t=>t.id==="opencode-go")?.name}catch{return}}function $t(e,t){return Wt(t,Qn(e))}function Hn(e){return Math.min(100,Math.max(0,Math.round(Number.isFinite(e)?e:0)))}function _e(e){const t=()=>Hn(e.meter.percent),n=()=>e.meter.limited||t()>=100,o=()=>mt(e.meter.resetsAt,e.now);return(()=>{var i=Nn(),a=i.firstChild,s=a.firstChild,l=s.nextSibling,p=l.firstChild,m=a.nextSibling,g=m.firstChild;return r.insert(s,()=>e.label),r.insert(l,(()=>{var C=r.memo(()=>!!n());return()=>C()?"rate-limited":`${t()}% used`})(),p),r.insert(l,(()=>{var C=r.memo(()=>o()==="due");return()=>C()?"resets due":`resets in ${o()}`})(),null),r.effect(C=>{var y=`${e.label}: ${t()}% used`,_=n()?"true":void 0,v=`${t()}%`;return y!==C.e&&r.setAttribute(m,"aria-label",C.e=y),_!==C.t&&r.setAttribute(m,"data-reached",C.t=_),v!==C.a&&r.setStyleProperty(g,"width",C.a=v),C},{e:void 0,t:void 0,a:void 0}),i})()}function Yn(e){const t=P.usePlugin(),n=u.createMemo(()=>e.state?.kind==="ok"?e.state.quota:void 0),o=u.createMemo(()=>{const w=n();return w===void 0?void 0:Vt(w.monthly,e.now())}),i=u.createMemo(()=>n()?.workspace?.name??n()?.workspace?.id??"workspace"),a=u.createMemo(()=>{const w=n();return w===void 0?void 0:ft(w)}),s=()=>o()?.current??0,l=()=>o()?.forecast??0,p=()=>Math.max(0,l()-s()),m=()=>o()?.over===!0,g=()=>o()?.reached===!0,C=()=>o()?.available===!0,y=()=>n()?.monthly.percent===0,_=()=>{const w=n();return w===void 0?"–":Ue(w.monthly.resetsAt)},v=()=>{const w=n();return w===void 0?"–":mt(w.monthly.resetsAt,e.now())};return(()=>{var w=qn();return r.insert(w,r.createComponent(u.Show,{get when(){return n()},get fallback(){return r.createComponent(u.Show,{get when(){return e.error===void 0},get fallback(){return(()=>{var f=On();return f.firstChild,r.insert(f,()=>e.error,null),f})()},get children(){return r.createComponent(u.Show,{get when(){return e.state?.kind==="none"},get fallback(){return jn()},get children(){var f=zn(),h=f.firstChild,I=h.nextSibling;return r.insert(h,()=>e.name),r.insert(I,()=>e.state?.kind==="none"&&e.state.reason==="console"?"Connect OpenCode Console with /connect to see your Go allowance.":"This workspace has no active OpenCode Go subscription."),f}})}})},children:f=>[(()=>{var h=Un(),I=h.firstChild,M=I.firstChild,R=M.nextSibling;R.firstChild;var N=I.nextSibling;return r.insert(M,()=>e.name),r.insert(R,i,null),r.insert(N,a),r.effect(()=>r.setAttribute(N,"data-warning",a()!=="active"?"true":void 0)),h})(),(()=>{var h=Bn();return r.insert(h,r.createComponent(_e,{label:"Rolling",get meter(){return f().rolling},get now(){return e.now()}}),null),r.insert(h,r.createComponent(_e,{label:"Weekly",get meter(){return f().weekly},get now(){return e.now()}}),null),r.insert(h,r.createComponent(_e,{label:"Monthly",get meter(){return f().monthly},get now(){return e.now()}}),null),h})(),(()=>{var h=Wn(),I=h.firstChild,M=I.firstChild,R=M.nextSibling,N=I.nextSibling,W=N.firstChild,L=W.nextSibling,z=N.nextSibling,c=z.firstChild,D=c.firstChild,S=D.nextSibling;S.nextSibling;var k=c.nextSibling,x=k.firstChild,F=x.nextSibling;F.nextSibling;var X=k.nextSibling,ye=X.firstChild,te=z.nextSibling,J=te.nextSibling;return r.insert(R,(()=>{var T=r.memo(()=>!!g());return()=>T()?"Monthly limit reached":r.memo(()=>!!y())()?"No monthly usage yet":r.memo(()=>!C())()?"Too early in the cycle":r.memo(()=>!!m())()?"Limit before renewal":`~${l()}% · ${Math.max(0,100-l())}% headroom`})()),r.insert(c,s,S),r.insert(k,l,F),r.insert(X,()=>Math.max(0,100-l()),ye),r.insert(te,(()=>{var T=r.memo(()=>!!g());return()=>T()?`Renews ${_()}`:`Renews ${_()} · ${v()==="due"?"renewal due":`in ${v()}`}`})()),r.insert(J,(()=>{var T=r.memo(()=>!!g());return()=>T()?"The monthly allowance is used up.":r.memo(()=>!!y())()?"The monthly cycle has no usage yet.":r.memo(()=>!C())()?"The cycle is too young for a reliable average pace.":r.memo(()=>!!(m()&&o()?.exhaustAt!==void 0))()?`At this pace the allowance runs out around ${Ue(o().exhaustAt)}.`:"Based on the average pace since the monthly cycle started."})()),r.effect(T=>{var ne=m()?"true":void 0,ue=g()?"true":void 0,de=`Monthly forecast: ${s()}% now, ${l()}% at renewal`,pe=`${s()}%`,me=m()?"true":void 0,fe=`${s()}%`,re=`${p()}%`;return ne!==T.e&&r.setAttribute(R,"data-warning",T.e=ne),ue!==T.t&&r.setAttribute(N,"data-reached",T.t=ue),de!==T.a&&r.setAttribute(N,"aria-label",T.a=de),pe!==T.o&&r.setStyleProperty(W,"width",T.o=pe),me!==T.i&&r.setAttribute(L,"data-over",T.i=me),fe!==T.n&&r.setStyleProperty(L,"left",T.n=fe),re!==T.s&&r.setStyleProperty(L,"width",T.s=re),T},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),h})(),(()=>{var h=Vn();return r.insert(h,r.createComponent(u.Show,{get when(){return f().workspace?.usageURL},children:I=>r.createComponent(t.ui.Button,{size:"small",variant:"neutral",onClick:()=>t.system.openExternal(I()),get children(){return t.t("panel.go.open")}})}),null),r.insert(h,r.createComponent(u.Show,{get when(){return e.loading},get children(){return Gn()}}),null),r.insert(h,r.createComponent(u.Show,{get when(){return e.error},children:I=>(()=>{var M=Kn();return M.firstChild,r.insert(M,I,null),M})()}),null),h})()]})),w})()}const Xn=100,Jn=24,Zn=80,er=200,tr=400,nr=72;function Ct(e){const[t,n]=u.createSignal(0);let o,i,a,s,l,p=!1,m=e.animate();const g=v=>{p||n(w=>w===v?w:v)},C=(v,w)=>{p||(l=v,s!==void 0&&clearTimeout(s),s=setTimeout(()=>{s=void 0;const f=l;l=void 0,f!==void 0&&g(f)},w))},y=v=>{if(p||o===void 0||i===void 0)return;const w=e.font();i.style.fontFamily!==w&&(i.style.fontFamily=w);const f=i.getBoundingClientRect().width/Xn,h=o.clientWidth-Jn,I=Tt(h,f);if(I===0)return;const M=v??(t()===0?Zn:e.animate()?er:tr);C(I,M)},_=()=>{if(!(p||o===void 0||i===void 0||a!==void 0)){if(typeof ResizeObserver>"u"){g(nr);return}a=new ResizeObserver(()=>y()),a.observe(o),y()}};return u.createEffect(()=>{const v=e.animate();v&&m===!1&&y(0),m=v}),u.createEffect(()=>{e.font(),queueMicrotask(()=>y())}),typeof document<"u"&&"fonts"in document&&document.fonts.ready.then(()=>y()),u.onCleanup(()=>{p=!0,s!==void 0&&clearTimeout(s),a?.disconnect(),a=void 0}),{columns:t,body:v=>{o=v,_()},ruler:v=>{i=v,_()}}}var rr=r.template("<div data-component=oui-panel><span data-slot=oui-ruler-wrap aria-hidden=true><span data-slot=oui-ruler>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</span></span><div data-slot=oui-header><div data-slot=oui-title-row><span data-slot=oui-title></span><span data-slot=oui-subtitle></span></div><div data-slot=oui-controls></div></div><div data-slot=oui-body data-scrollable></div><div data-slot=oui-actions>"),or=r.template("<div data-slot=oui-detail-head><span data-slot=oui-subtitle>"),ir=r.template("<div data-slot=oui-empty>"),ar=r.template("<div data-slot=oui-lines>"),sr=r.template("<div data-slot=oui-error>"),lr=r.template("<div data-slot=oui-loading>"),cr=r.template("<button type=button data-slot=oui-line data-selectable=true>"),ur=r.template("<div data-slot=oui-line>");function K(e){return e instanceof Error?e.message:e!==null&&typeof e=="object"&&"message"in e?String(e.message):""}function dr(e){const t=P.usePlugin(),n=P.usePanel(),[o,i]=u.createSignal(void 0),[a,s]=u.createSignal(!1),l=u.createMemo(()=>bt(e.settings(),e.views)),p=u.createMemo(()=>$t(e.session,e.quotaName)),m=()=>l().view,[g,C]=u.createSignal(0),y=Ct({font:()=>t.appearance.font("mono"),animate:()=>n.animate()}),_=()=>ce(e.session.server.client,{directory:e.session.directory}),v=u.createMemo(()=>{if(e.refresh(),!n.visible()||m()===B||g()===0)return;const d=l();return{sessionID:e.session.id,settings:d,...o()!==void 0?{detail:o()}:{},width:g(),busy:a()}}),w=u.createMemo(()=>{const d=v();if(d!==void 0)return{input:d,client:e.session.server.client,directory:e.session.directory}}),f=P.createLatest(w,(d,b)=>ce(d.client,{directory:d.directory}).panel(d.input,b));u.createEffect(()=>{const d=y.columns();d===0||f.loading||d!==g()&&C(d)});const[h,I]=u.createSignal(0);u.createEffect(()=>{if(!e.quotaEnabled||!n.visible()||m()!==B)return;const d=setInterval(()=>I(b=>b+1),ut);u.onCleanup(()=>clearInterval(d))});const M=u.createMemo(()=>{if(!(!e.quotaEnabled||!n.visible()||m()!==B))return{client:e.session.server.client,directory:e.session.directory,tick:h()}}),R=P.createLatest(M,(d,b)=>xt(d.client,{directory:d.directory},b)),N=u.createMemo(()=>R.error===void 0?void 0:K(R.error)),W=()=>{e.bump(),e.quotaEnabled&&m()===B&&I(d=>d+1)},L=u.createMemo(()=>(f.latest?.lines??[]).filter(d=>d.hint!==!0&&(e.maintenance||d.row?.kind!=="prune"&&d.row?.kind!=="wipe"))),z=u.createMemo(()=>f.latest?.database),c=(d,b,j="default")=>{t.toast.show({title:d,description:b,variant:j})},D=d=>{e.update(d)},S=d=>{D(b=>{b.view=d,b.sort=Ie(d),b.sortDesc=!0}),i(void 0)},k=d=>D(b=>{b.range=d}),x=d=>D(b=>{b.granularity=d}),F=d=>D(b=>{b.turnsScope=d}),X=d=>D(b=>{b.sort=d}),ye=()=>D(d=>{d.sortDesc=!d.sortDesc});async function te(d){let b;try{b=await _().filters()}catch(A){c(t.t("panel.unavailable"),K(A),"error");return}l();const j=d==="model"?b.models:b.providers,O=d==="model"?t.t("panel.model"):t.t("panel.provider"),E=await t.dialogs.select({title:O,options:[{title:d==="model"?t.t("panel.allModels"):t.t("panel.allProviders"),value:""},...j.map(A=>({title:`${A.value} · ${A.steps}`,value:A.value}))]});E!==void 0&&(D(A=>{d==="model"?A.modelID=E:A.providerID=E}),i(void 0))}const J=()=>{try{return e.session.server.data.session.status(e.session.id)==="running"}catch{return!1}};async function T(d){if(J()){c(t.t("panel.title"),t.t("panel.busy"),"error");return}const b=z(),j=b?.removable.find(A=>A.days===d)?.steps,O=b?.tables.find(A=>A.name==="steps")?.rows??0;if(await t.dialogs.confirm({title:t.t("panel.confirmPrune",{days:d}),description:t.t("panel.confirmPruneDetail",{steps:j??0,total:O}),confirm:t.t("panel.prune",{days:d}),cancel:t.t("panel.cancel"),danger:!0})){try{const A=await _().prune({days:d,confirm:!0});c(t.t("panel.pruned",{steps:A.steps,prompts:A.prompts,events:A.events}),void 0,"success"),s(!1)}catch(A){s(!0),c(t.t("panel.title"),K(A),"error")}e.bump()}}async function ne(){if(J()){c(t.t("panel.title"),t.t("panel.busy"),"error");return}const d=z(),b=d?.tables.find(E=>E.name==="steps")?.rows??0,j=d?.tables.find(E=>E.name==="sessions")?.rows??0;if(await t.dialogs.confirm({title:t.t("panel.confirmWipe"),description:t.t("panel.confirmWipeDetail",{steps:b,sessions:j}),confirm:t.t("panel.wipeConfirm"),cancel:t.t("panel.cancel"),danger:!0})){try{const E=await _().wipe({confirm:!0});c(t.t("panel.wiped",{steps:E.steps,prompts:E.prompts,events:E.events,usage:E.usage,sessions:E.sessions}),void 0,"success"),s(!1)}catch(E){s(!0),c(t.t("panel.title"),K(E),"error")}e.bump()}}async function ue(){if(!e.pricing){c(t.t("panel.pricingOff"));return}if(J()){c(t.t("panel.title"),t.t("panel.busy"),"error");return}const d=z(),b=d?.unpriced??0;if(d!==void 0&&b===0){c(t.t("panel.noUnpriced"));return}if(await t.dialogs.confirm({title:t.t("panel.confirmBackfill"),description:t.t("panel.confirmBackfillDetail",{count:b}),confirm:t.t("panel.backfill"),cancel:t.t("panel.cancel")})){try{const O=await _().backfill({confirm:!0});c(t.t("panel.backfilled",{updated:Ce(O.updated),candidates:Ce(O.candidates)}),void 0,"success"),s(!1)}catch(O){s(!0),c(t.t("panel.title"),K(O),"error")}e.bump()}}async function de(){if(J()){c(t.t("panel.title"),t.t("panel.busy"),"error");return}if(await t.dialogs.confirm({title:t.t("panel.confirmVacuum"),description:t.t("panel.confirmVacuumDetail"),confirm:t.t("panel.vacuum"),cancel:t.t("panel.cancel")})){try{const b=await _().vacuum({confirm:!0});c(t.t("panel.vacuumed",{size:(b.freed/1048576).toFixed(1)}),void 0,"success"),s(!1)}catch(b){s(!0),c(t.t("panel.title"),K(b),"error")}e.bump()}}async function pe(){const d=z()?.path;if(d!==void 0)try{await t.system.copy(d),c(t.t("panel.pathCopied"))}catch(b){c(t.t("panel.title"),K(b),"error")}}const me=d=>{if(d.kind==="prune"){T(Number.parseInt(d.value,10));return}if(d.kind==="wipe"){ne();return}i(d)},fe=()=>t.t(`range.${l().range}`),re=()=>Xt(l()),Ee=()=>ht[m()]??[],St=()=>L()[0]?.text??"",kt=()=>m()===B?`${p()} · live`:`${fe()}${re()!==void 0?` · ${re()}`:""}${f.loading?" · …":""}`;return(()=>{var d=rr(),b=d.firstChild,j=b.firstChild,O=b.nextSibling,E=O.firstChild,A=E.firstChild,_t=A.nextSibling,we=E.nextSibling,oe=O.nextSibling,Fe=oe.nextSibling,Le=y.ruler;typeof Le=="function"?r.use(Le,j):y.ruler=j,r.insert(A,()=>t.t("panel.title")),r.insert(_t,kt),r.insert(we,r.createComponent(t.ui.Select,{get label(){return t.t("panel.view")},get value(){return m()},get options(){return Ht(e.views).map($=>({value:$,label:t.t(`view.${$}`)}))},onChange:$=>S($)}),null),r.insert(we,r.createComponent(u.Show,{get when(){return m()!==B},get children(){return[r.createComponent(t.ui.Select,{get label(){return t.t("panel.range")},get value(){return l().range},get options(){return Ae.map($=>({value:$,label:t.t(`range.${$}`)}))},onChange:$=>k($)}),r.createComponent(u.Show,{get when(){return Ee().length>0},get children(){return[r.createComponent(t.ui.Select,{get label(){return t.t("panel.sort")},get value(){return r.memo(()=>l().sort==="")()?Ie(m()):l().sort},get options(){return Ee().map($=>({value:$,label:t.t(`sort.${$}`)}))},onChange:X}),r.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:ye,get children(){return l().sortDesc?"↓":"↑"}})]}}),r.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:()=>{te("model")},get children(){return r.memo(()=>l().modelID==="")()?t.t("panel.model"):l().modelID}}),r.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:()=>{te("provider")},get children(){return r.memo(()=>l().providerID==="")()?t.t("panel.provider"):l().providerID}}),r.createComponent(u.Show,{get when(){return m()==="turns"},get children(){return r.createComponent(t.ui.Select,{get label(){return t.t("panel.scope")},get value(){return l().turnsScope},get options(){return[{value:"session",label:t.t("panel.thisSession")},{value:"all",label:t.t("panel.allSessions")}]},onChange:$=>F($)})}}),r.createComponent(u.Show,{get when(){return m()==="periods"},get children(){return r.createComponent(t.ui.Select,{get label(){return t.t("panel.granularity")},get value(){return l().granularity},get options(){return vt.map($=>({value:$,label:t.t(`granularity.${$}`)}))},onChange:$=>x($)})}})]}}),null),r.insert(we,r.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:W,get children(){return t.t("panel.refresh")}}),null),r.insert(d,r.createComponent(u.Show,{get when(){return o()},children:$=>(()=>{var q=or(),U=q.firstChild;return r.insert(q,r.createComponent(t.ui.Button,{size:"small",variant:"ghost",onClick:()=>i(void 0),get children(){return["← ",r.memo(()=>t.t("panel.back"))]}}),U),r.insert(U,St),q})()}),oe);var Re=y.body;return typeof Re=="function"?r.use(Re,oe):y.body=oe,r.insert(oe,r.createComponent(u.Show,{get when(){return m()===B},get fallback(){return r.createComponent(u.Show,{get when(){return f.latest!==void 0},get fallback(){return r.createComponent(u.Show,{get when(){return f.error!==void 0},get fallback(){return(()=>{var $=lr();return r.insert($,()=>t.t("panel.loading")),$})()},get children(){var $=sr();return r.insert($,()=>t.t("panel.unavailable")),r.effect(()=>r.setAttribute($,"title",K(f.error))),$}})},get children(){return[r.createComponent(u.Show,{get when(){return L().length===0},get children(){var $=ir();return r.insert($,()=>t.t("panel.empty")),$}}),(()=>{var $=ar();return r.insert($,r.createComponent(u.For,{get each(){return L()},children:q=>r.createComponent(u.Show,{get when(){return q.row!==void 0},get fallback(){return(()=>{var U=ur();return r.insert(U,()=>q.text),r.effect(()=>r.className(U,le(q.tone))),U})()},get children(){var U=cr();return U.$$click=()=>me(q.row),r.insert(U,()=>q.text),r.effect(()=>r.className(U,le(q.tone))),U}})})),r.effect(q=>r.setStyleProperty($,"font-family",t.appearance.font("mono"))),$})()]}})},get children(){return r.createComponent(Yn,{get state(){return R.latest},get loading(){return R.loading},get error(){return N()},get name(){return p()},now:()=>(h(),Date.now())})}})),r.insert(Fe,r.createComponent(t.ui.Button,{size:"small",variant:"neutral",onClick:()=>t.layout.open(`${t.id}:turns`,e.session,{tab:"select"}),get children(){return t.t("panel.openTurns")}}),null),r.insert(Fe,r.createComponent(u.Show,{get when(){return r.memo(()=>!!(e.maintenance&&m()==="db"))()&&z()},children:$=>[r.createComponent(t.ui.Button,{size:"small",variant:"neutral",get disabled(){return!e.pricing||$().unpriced===0},onClick:()=>{ue()},get children(){return[r.memo(()=>t.t("panel.backfill"))," (",r.memo(()=>Ce($().unpriced)),")"]}}),r.createComponent(u.For,{get each(){return $().removable},children:q=>r.createComponent(t.ui.Button,{size:"small",variant:"danger",onClick:()=>{T(q.days)},get children(){return t.t("panel.prune",{days:q.days})}})}),r.createComponent(t.ui.Button,{size:"small",variant:"danger",onClick:()=>{ne()},get children(){return t.t("panel.wipe")}}),r.createComponent(t.ui.Button,{size:"small",variant:"neutral",onClick:()=>{de()},get children(){return t.t("panel.vacuum")}}),r.createComponent(t.ui.Button,{size:"small",variant:"ghost-muted",onClick:()=>{pe()},get children(){return t.t("panel.copyPath")}})]}),null),d})()}r.delegateEvents(["click"]);const pr=Object.freeze(Object.defineProperty({__proto__:null,UsagePanel:dr},Symbol.toStringTag,{value:"Module"}));var He=r.template("<div data-slot=oui-divider aria-hidden=true>"),De=r.template("<div data-slot=oui-line>"),mr=r.template("<div data-component=oui-panel><span data-slot=oui-ruler-wrap aria-hidden=true><span data-slot=oui-ruler>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000</span></span><div data-slot=oui-header><div data-slot=oui-title-row><span data-slot=oui-title></span><span data-slot=oui-subtitle></span></div></div><div data-slot=oui-body data-scrollable></div><div data-slot=oui-actions>"),Ye=r.template("<div data-slot=oui-lines>"),fr=r.template("<div data-slot=oui-error>"),gr=r.template("<div data-slot=oui-loading>"),vr=r.template("<div data-slot=oui-empty>");function hr(e){const t=P.usePlugin(),n=P.usePanel(),[o,i]=u.createSignal(0),a=Ct({font:()=>t.appearance.font("mono"),animate:()=>n.animate()}),s=u.createMemo(()=>{if(!(!n.visible()||o()===0))return{client:e.session.server.client,id:e.session.id,directory:e.session.directory,refresh:e.refresh(),width:Math.min(Je,o())}}),l=P.createLatest(s,(f,h)=>ce(f.client,{directory:f.directory}).turns({sessionID:f.id,limit:e.limit,width:f.width},h));u.createEffect(()=>{const f=a.columns();f===0||l.loading||f!==o()&&i(f)});const[p,m]=u.createSignal(0);u.createEffect(()=>{if(!e.quotaEnabled||!n.visible())return;const f=setInterval(()=>m(h=>h+1),ut);u.onCleanup(()=>clearInterval(f))});const g=u.createMemo(()=>{if(!(!e.quotaEnabled||!n.visible()))return{client:e.session.server.client,directory:e.session.directory,tick:p()}}),C=P.createLatest(g,(f,h)=>xt(f.client,{directory:f.directory},h)),y=u.createMemo(()=>$t(e.session,e.quotaName)),_=u.createMemo(()=>Jt(C.latest,Date.now(),o(),y())),v=f=>f.filter(h=>h.hint!==!0),w=()=>r.createComponent(u.Show,{get when(){return _().length>0},get children(){return[r.createComponent(u.For,{get each(){return _()},children:f=>(()=>{var h=De();return r.insert(h,()=>f.text),r.effect(()=>r.className(h,le(f.tone))),h})()}),He()]}});return(()=>{var f=mr(),h=f.firstChild,I=h.firstChild,M=h.nextSibling,R=M.firstChild,N=R.firstChild,W=N.nextSibling,L=M.nextSibling,z=L.nextSibling,c=a.ruler;typeof c=="function"?r.use(c,I):a.ruler=I,r.insert(N,()=>t.t("panel.turns")),r.insert(W,()=>l.loading?"…":"");var D=a.body;return typeof D=="function"?r.use(D,L):a.body=L,r.insert(L,r.createComponent(u.Show,{get when(){return l.latest},get fallback(){return[(()=>{var S=Ye();return r.insert(S,r.createComponent(w,{})),r.effect(k=>r.setStyleProperty(S,"font-family",t.appearance.font("mono"))),S})(),r.createComponent(u.Show,{get when(){return l.error!==void 0},get fallback(){return(()=>{var S=gr();return r.insert(S,()=>t.t("panel.loading")),S})()},get children(){var S=fr();return r.insert(S,()=>t.t("panel.unavailable")),S}})]},children:S=>(()=>{var k=Ye();return r.insert(k,r.createComponent(w,{}),null),r.insert(k,r.createComponent(u.For,{get each(){return v(S().summary)},children:x=>(()=>{var F=De();return r.insert(F,()=>x.text),r.effect(()=>r.className(F,le(x.tone))),F})()}),null),r.insert(k,r.createComponent(u.Show,{get when(){return S().history.length>0},get fallback(){return(()=>{var x=vr();return r.insert(x,()=>t.t("panel.noTurns")),x})()},get children(){return[He(),r.createComponent(u.For,{get each(){return v(S().history)},children:x=>(()=>{var F=De();return r.insert(F,()=>x.text),r.effect(()=>r.className(F,le(x.tone))),F})()})]}}),null),r.effect(x=>r.setStyleProperty(k,"font-family",t.appearance.font("mono"))),k})()})),r.insert(z,r.createComponent(t.ui.Button,{size:"small",variant:"neutral",onClick:()=>t.layout.open(`${t.id}:usage`,e.session,{tab:"select"}),get children(){return t.t("panel.openUsage")}})),f})()}const br=Object.freeze(Object.defineProperty({__proto__:null,TurnsPanel:hr},Symbol.toStringTag,{value:"Module"}));exports.default=Fn;
package/dist/index.d.ts CHANGED
@@ -38,6 +38,13 @@ export type Options = {
38
38
  labels?: Partial<LineLabels> | undefined;
39
39
  /** How the turn segment counts prompt usage. */
40
40
  turnTotals?: TurnTotalsView | undefined;
41
+ /**
42
+ * Client-side OpenCode Go allowance view. `off` hides the `go` view and the
43
+ * TUI sidebar forecast and makes no usage-limits request.
44
+ */
45
+ quota?: "auto" | "off" | undefined;
46
+ /** Full subscription label shown in the go view and sidebar (default: provider name or OpenCode Go). */
47
+ quotaName?: string | undefined;
41
48
  };
42
49
  declare const _default: Plugin.Plugin;
43
50
  export default _default;