opencode-usage-insights 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -36
- package/dist/core.d.ts +10 -0
- package/dist/gui-experimental.cjs +3 -3
- package/dist/index.d.ts +7 -0
- package/dist/index.js +249 -18
- package/dist/index.js.map +9 -8
- package/dist/panel-data.d.ts +27 -4
- package/dist/panel.d.ts +9 -2
- package/dist/quota-client.d.ts +13 -0
- package/dist/quota.d.ts +114 -0
- package/dist/rpc.d.ts +1 -1
- package/dist/rpc.js +2 -2
- package/dist/rpc.js.map +3 -3
- package/dist/sidebar.d.ts +5 -0
- package/dist/stats-worker.js +248 -17
- package/dist/stats-worker.js.map +7 -6
- package/dist/tui.d.ts +13 -4
- package/dist/tui.js +406 -36
- package/dist/tui.js.map +11 -9
- package/docs/demo.md +17 -12
- package/docs/internals.md +72 -4
- package/package.json +7 -3
package/dist/tui.d.ts
CHANGED
|
@@ -8,8 +8,10 @@ import { type PanelView, type RangeKey } from "./panel-data";
|
|
|
8
8
|
* - `session.composer.top`: one telemetry line after every turn with the end
|
|
9
9
|
* time, the delta since the previous prompt, the provider and model that ran
|
|
10
10
|
* it, turn and session token totals, and cache warnings.
|
|
11
|
-
* - `session.panel` + the `/
|
|
12
|
-
* the database written by the server entry.
|
|
11
|
+
* - `session.panel` + the `/usage-insights` slash command: the statistics
|
|
12
|
+
* panel over the database written by the server entry. Its `go` view reads
|
|
13
|
+
* the host's live OpenCode Go allowance; the sidebar carries the compact
|
|
14
|
+
* forecast.
|
|
13
15
|
*
|
|
14
16
|
* The line is computed from the host's transcript alone; the panel, the
|
|
15
17
|
* sidebar history and the stored list estimate come from the server's usage
|
|
@@ -44,8 +46,15 @@ export type Options = {
|
|
|
44
46
|
/** How many turns the sidebar history shows (default 8, clamped to 1–50). */
|
|
45
47
|
sidebarTurns?: number | undefined;
|
|
46
48
|
/**
|
|
47
|
-
*
|
|
48
|
-
* `
|
|
49
|
+
* Read the host's OpenCode Go allowance and show the `go` view and the
|
|
50
|
+
* sidebar forecast. `off` makes no usage-limits request at all.
|
|
51
|
+
*/
|
|
52
|
+
quota?: "auto" | "off" | undefined;
|
|
53
|
+
/** Full subscription label; defaults to the host provider name or OpenCode Go. */
|
|
54
|
+
quotaName?: string | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Show the `/usage-insights` statistics panel and its command (default
|
|
57
|
+
* true). `false` keeps the live line and the sidebar history.
|
|
49
58
|
*/
|
|
50
59
|
panel?: boolean | undefined;
|
|
51
60
|
};
|
package/dist/tui.js
CHANGED
|
@@ -5,7 +5,7 @@ import { createElement as _$createElement3 } from "@opentui/solid";
|
|
|
5
5
|
import { createComponent as _$createComponent3 } from "@opentui/solid";
|
|
6
6
|
import { Plugin } from "@opencode/plugin/tui";
|
|
7
7
|
import { StyledText, fg } from "@opentui/core";
|
|
8
|
-
import { Show as Show3, createEffect as createEffect3, createMemo as createMemo3, createRenderEffect as createRenderEffect2, createSignal as createSignal3 } from "solid-js";
|
|
8
|
+
import { Show as Show3, createEffect as createEffect3, createMemo as createMemo3, createRenderEffect as createRenderEffect2, createSignal as createSignal3, onCleanup as onCleanup2 } from "solid-js";
|
|
9
9
|
|
|
10
10
|
// src/core.ts
|
|
11
11
|
var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
|
|
@@ -966,9 +966,128 @@ function filterOptions(db) {
|
|
|
966
966
|
return { models: pick("model_id"), providers: pick("provider_id") };
|
|
967
967
|
}
|
|
968
968
|
|
|
969
|
+
// src/quota.ts
|
|
970
|
+
var QUOTA_VIEW = "go";
|
|
971
|
+
var QUOTA_POLL_MS = 60000;
|
|
972
|
+
var DEFAULT_QUOTA_NAME = "OpenCode Go";
|
|
973
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
974
|
+
var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
|
|
975
|
+
function quotaNameOf(explicit, providerName) {
|
|
976
|
+
const custom = explicit?.trim();
|
|
977
|
+
if (custom !== undefined && custom !== "")
|
|
978
|
+
return custom;
|
|
979
|
+
const provider = providerName?.trim();
|
|
980
|
+
if (provider !== undefined && provider !== "")
|
|
981
|
+
return provider;
|
|
982
|
+
return DEFAULT_QUOTA_NAME;
|
|
983
|
+
}
|
|
984
|
+
function finite(value) {
|
|
985
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
986
|
+
}
|
|
987
|
+
function clamp(value, minimum, maximum) {
|
|
988
|
+
return Math.min(maximum, Math.max(minimum, value));
|
|
989
|
+
}
|
|
990
|
+
function previousCycleStart(endAt) {
|
|
991
|
+
if (!finite(endAt))
|
|
992
|
+
return endAt;
|
|
993
|
+
const end = new Date(endAt);
|
|
994
|
+
const year = end.getUTCFullYear();
|
|
995
|
+
const month = end.getUTCMonth();
|
|
996
|
+
const day = end.getUTCDate();
|
|
997
|
+
const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
|
|
998
|
+
const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
|
|
999
|
+
start.setUTCDate(Math.min(day, lastDay));
|
|
1000
|
+
return start.getTime();
|
|
1001
|
+
}
|
|
1002
|
+
function forecastMonthly(meter, now) {
|
|
1003
|
+
const endAt = finite(meter.resetsAt) ? meter.resetsAt : now;
|
|
1004
|
+
const startAt = previousCycleStart(endAt);
|
|
1005
|
+
const total = Math.max(1, endAt - startAt);
|
|
1006
|
+
const elapsedMs = clamp(now - startAt, 0, total);
|
|
1007
|
+
const remainingMs = Math.max(0, endAt - now);
|
|
1008
|
+
const percent = clamp(finite(meter.percent) ? meter.percent : 0, 0, 100);
|
|
1009
|
+
const reached = meter.limited === true || percent >= 100;
|
|
1010
|
+
const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
|
|
1011
|
+
const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
|
|
1012
|
+
const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
|
|
1013
|
+
const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
|
|
1014
|
+
const willExhaust = exhaustAt !== undefined;
|
|
1015
|
+
const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
|
|
1016
|
+
return {
|
|
1017
|
+
startAt,
|
|
1018
|
+
endAt,
|
|
1019
|
+
elapsedMs,
|
|
1020
|
+
remainingMs,
|
|
1021
|
+
ratePerDay,
|
|
1022
|
+
projectedPercent,
|
|
1023
|
+
...exhaustAt !== undefined ? { exhaustAt } : {},
|
|
1024
|
+
reached,
|
|
1025
|
+
available,
|
|
1026
|
+
willExhaust
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
function quotaBar(percent, width = 10) {
|
|
1030
|
+
const value = clamp(finite(percent) ? percent : 0, 0, 100);
|
|
1031
|
+
const cells = Math.max(1, Math.round(width));
|
|
1032
|
+
const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
|
|
1033
|
+
return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
|
|
1034
|
+
}
|
|
1035
|
+
function formatRenewal(at, timeZone) {
|
|
1036
|
+
if (!finite(at))
|
|
1037
|
+
return "\u2013";
|
|
1038
|
+
try {
|
|
1039
|
+
return new Intl.DateTimeFormat("en-GB", {
|
|
1040
|
+
day: "2-digit",
|
|
1041
|
+
month: "short",
|
|
1042
|
+
year: "numeric",
|
|
1043
|
+
hour: "2-digit",
|
|
1044
|
+
minute: "2-digit",
|
|
1045
|
+
hour12: false,
|
|
1046
|
+
...timeZone !== undefined ? { timeZone } : {}
|
|
1047
|
+
}).format(new Date(at)).replace(/,/g, "");
|
|
1048
|
+
} catch {
|
|
1049
|
+
return "\u2013";
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
function formatRenewalCompact(at, timeZone) {
|
|
1053
|
+
if (!finite(at))
|
|
1054
|
+
return "\u2013";
|
|
1055
|
+
try {
|
|
1056
|
+
return new Intl.DateTimeFormat("en-GB", {
|
|
1057
|
+
day: "2-digit",
|
|
1058
|
+
month: "short",
|
|
1059
|
+
hour: "2-digit",
|
|
1060
|
+
minute: "2-digit",
|
|
1061
|
+
hour12: false,
|
|
1062
|
+
...timeZone !== undefined ? { timeZone } : {}
|
|
1063
|
+
}).format(new Date(at)).replace(/,/g, "");
|
|
1064
|
+
} catch {
|
|
1065
|
+
return "\u2013";
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
function formatCountdown(at, now) {
|
|
1069
|
+
const remaining = at - now;
|
|
1070
|
+
if (!finite(remaining))
|
|
1071
|
+
return "\u2013";
|
|
1072
|
+
if (remaining <= 0)
|
|
1073
|
+
return "due";
|
|
1074
|
+
return formatDuration(remaining);
|
|
1075
|
+
}
|
|
1076
|
+
function quotaStatus(quota) {
|
|
1077
|
+
const limited = [];
|
|
1078
|
+
if (quota.rolling.limited || quota.rolling.percent >= 100)
|
|
1079
|
+
limited.push("5-hour");
|
|
1080
|
+
if (quota.weekly.limited || quota.weekly.percent >= 100)
|
|
1081
|
+
limited.push("weekly");
|
|
1082
|
+
if (quota.monthly.limited || quota.monthly.percent >= 100)
|
|
1083
|
+
limited.push("monthly");
|
|
1084
|
+
return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
969
1087
|
// src/panel-data.ts
|
|
970
1088
|
var PANEL_NAME = "usage-insights";
|
|
971
1089
|
var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
|
|
1090
|
+
var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
|
|
972
1091
|
var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
|
|
973
1092
|
var GRANULARITIES = ["day", "week", "month"];
|
|
974
1093
|
var SORT_KEYS = {
|
|
@@ -993,13 +1112,13 @@ function nextSort(view, current, step) {
|
|
|
993
1112
|
return keys[0];
|
|
994
1113
|
return keys[(index + step + keys.length) % keys.length];
|
|
995
1114
|
}
|
|
996
|
-
function parseArgs(input) {
|
|
1115
|
+
function parseArgs(input, views = CLIENT_VIEWS) {
|
|
997
1116
|
const parsed = {};
|
|
998
1117
|
for (const token of (input ?? "").split(/\s+/)) {
|
|
999
1118
|
const value = token.trim().toLowerCase();
|
|
1000
1119
|
if (value === "")
|
|
1001
1120
|
continue;
|
|
1002
|
-
if (
|
|
1121
|
+
if (views.includes(value))
|
|
1003
1122
|
parsed.view = value;
|
|
1004
1123
|
else if (RANGE_KEYS.includes(value))
|
|
1005
1124
|
parsed.range = value;
|
|
@@ -1036,10 +1155,10 @@ var DEFAULT_SETTINGS = {
|
|
|
1036
1155
|
modelID: "",
|
|
1037
1156
|
providerID: ""
|
|
1038
1157
|
};
|
|
1039
|
-
function sanitizeSettings(raw) {
|
|
1158
|
+
function sanitizeSettings(raw, views = CLIENT_VIEWS) {
|
|
1040
1159
|
const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
|
|
1041
1160
|
return {
|
|
1042
|
-
view:
|
|
1161
|
+
view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
|
|
1043
1162
|
range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
|
|
1044
1163
|
sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
|
|
1045
1164
|
sortDesc: settings.sortDesc === true,
|
|
@@ -1196,25 +1315,28 @@ function usageBuckets(usage) {
|
|
|
1196
1315
|
hit: prompt > 0 ? usage.cached / prompt : undefined
|
|
1197
1316
|
};
|
|
1198
1317
|
}
|
|
1199
|
-
function viewBar(view, width = 200) {
|
|
1318
|
+
function viewBar(view, width = 200, views = CLIENT_VIEWS) {
|
|
1200
1319
|
const key = (index) => String((index + 1) % 10);
|
|
1201
|
-
const full =
|
|
1202
|
-
const candidates = [full,
|
|
1320
|
+
const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
|
|
1321
|
+
const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
|
|
1203
1322
|
for (const parts of candidates) {
|
|
1204
1323
|
const text = parts.join(" ");
|
|
1205
1324
|
if (text.length <= width)
|
|
1206
1325
|
return { text, tone: "muted" };
|
|
1207
1326
|
}
|
|
1208
|
-
|
|
1327
|
+
const index = views.indexOf(view);
|
|
1328
|
+
return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
|
|
1209
1329
|
}
|
|
1210
1330
|
function keysFor(of) {
|
|
1331
|
+
if (of === QUOTA_VIEW)
|
|
1332
|
+
return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
|
|
1211
1333
|
if (of === "db")
|
|
1212
|
-
return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
|
|
1334
|
+
return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 0 view \xB7 ? help";
|
|
1213
1335
|
if (of === "periods")
|
|
1214
|
-
return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
|
|
1336
|
+
return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
1215
1337
|
if (of === "turns")
|
|
1216
|
-
return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
|
|
1217
|
-
return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
|
|
1338
|
+
return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
1339
|
+
return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
1218
1340
|
}
|
|
1219
1341
|
function filterSummary(filters) {
|
|
1220
1342
|
const parts = [];
|
|
@@ -1231,7 +1353,7 @@ function helpLines(width) {
|
|
|
1231
1353
|
const lines = [
|
|
1232
1354
|
{ text: "keys", tone: HEADER_TONE },
|
|
1233
1355
|
{ text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
|
|
1234
|
-
{ text: " 1-9 [ ]
|
|
1356
|
+
{ text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
|
|
1235
1357
|
{ text: " t shift+t previous / next range" },
|
|
1236
1358
|
{ text: " s shift+s cycle sort column \xB7 reverse" },
|
|
1237
1359
|
{ text: " b periods bucket: day \u2192 week \u2192 month" },
|
|
@@ -1240,6 +1362,13 @@ function helpLines(width) {
|
|
|
1240
1362
|
{ text: " r re-read the database \xB7 f full screen \xB7 escape close" },
|
|
1241
1363
|
{ text: " e db: backfill list-price estimates for the $0 steps" },
|
|
1242
1364
|
{ text: "" },
|
|
1365
|
+
{ text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
|
|
1366
|
+
{ text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
|
|
1367
|
+
{ text: " forecast the monthly percentage at its reset, from the" },
|
|
1368
|
+
{ text: " cycle's average pace (not a sample history)" },
|
|
1369
|
+
{ text: " renews the monthly reset reported by the host" },
|
|
1370
|
+
{ text: " the plugin reads the host's local usage-limits endpoint;" },
|
|
1371
|
+
{ text: " it never reads your API key and never talks to the Console." },
|
|
1243
1372
|
{ text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
|
|
1244
1373
|
{ text: " prompt everything the provider saw: cached + fresh + writes" },
|
|
1245
1374
|
{ text: " in the uncached part: fresh input + cache writes" },
|
|
@@ -1274,6 +1403,101 @@ function helpLines(width) {
|
|
|
1274
1403
|
];
|
|
1275
1404
|
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
1276
1405
|
}
|
|
1406
|
+
function quotaMeterLine(label, meter, now) {
|
|
1407
|
+
const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
|
|
1408
|
+
const countdown = formatCountdown(meter.resetsAt, now);
|
|
1409
|
+
return {
|
|
1410
|
+
text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
|
|
1411
|
+
tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
function goQuotaLines(state, options) {
|
|
1415
|
+
const { now, width, loading, error } = options;
|
|
1416
|
+
const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
|
|
1417
|
+
const lines = [];
|
|
1418
|
+
const push = (text, tone = "base") => {
|
|
1419
|
+
lines.push({ text, tone });
|
|
1420
|
+
};
|
|
1421
|
+
if (state === undefined) {
|
|
1422
|
+
if (error !== undefined && error !== "")
|
|
1423
|
+
push(`Go quota unavailable: ${error}`, "warning");
|
|
1424
|
+
else if (loading === true)
|
|
1425
|
+
push("reading OpenCode Go quota\u2026", "muted");
|
|
1426
|
+
else
|
|
1427
|
+
push("OpenCode Go quota is unavailable", "muted");
|
|
1428
|
+
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
1429
|
+
}
|
|
1430
|
+
if (state.kind === "none") {
|
|
1431
|
+
push(name, "accent");
|
|
1432
|
+
push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
|
|
1433
|
+
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
1434
|
+
}
|
|
1435
|
+
const quota = state.quota;
|
|
1436
|
+
const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
|
|
1437
|
+
const status = quotaStatus(quota);
|
|
1438
|
+
const forecast = forecastMonthly(quota.monthly, now);
|
|
1439
|
+
push(`${name} \xB7 ${workspace}`, "accent");
|
|
1440
|
+
push(`status ${status}`, status === "active" ? "base" : "warning");
|
|
1441
|
+
lines.push(quotaMeterLine("rolling", quota.rolling, now));
|
|
1442
|
+
lines.push(quotaMeterLine("weekly", quota.weekly, now));
|
|
1443
|
+
lines.push(quotaMeterLine("monthly", quota.monthly, now));
|
|
1444
|
+
push("");
|
|
1445
|
+
if (forecast.reached || quota.monthly.limited) {
|
|
1446
|
+
push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
|
|
1447
|
+
} else if (now >= forecast.endAt) {
|
|
1448
|
+
push("forecast monthly reset due \xB7 refresh", "warning");
|
|
1449
|
+
} else if (!forecast.available) {
|
|
1450
|
+
push("forecast too early in the cycle to project a monthly pace", "muted");
|
|
1451
|
+
} else if (quota.monthly.percent === 0) {
|
|
1452
|
+
push("forecast no monthly usage yet this cycle", "muted");
|
|
1453
|
+
} else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
|
|
1454
|
+
push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
|
|
1455
|
+
} else {
|
|
1456
|
+
const projected = Math.min(999, Math.round(forecast.projectedPercent));
|
|
1457
|
+
const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
|
|
1458
|
+
push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
|
|
1459
|
+
}
|
|
1460
|
+
const renewal = formatRenewal(quota.monthly.resetsAt);
|
|
1461
|
+
const countdown = formatCountdown(quota.monthly.resetsAt, now);
|
|
1462
|
+
push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
|
|
1463
|
+
if (quota.workspace?.usageURL !== undefined)
|
|
1464
|
+
push(`console ${quota.workspace.usageURL}`, "muted");
|
|
1465
|
+
const age = Math.max(0, now - quota.observedAt);
|
|
1466
|
+
push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
|
|
1467
|
+
if (loading === true)
|
|
1468
|
+
push("refreshing\u2026", "muted");
|
|
1469
|
+
if (error !== undefined && error !== "")
|
|
1470
|
+
push(`quota refresh failed: ${error}`, "warning");
|
|
1471
|
+
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
1472
|
+
}
|
|
1473
|
+
function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
|
|
1474
|
+
if (state?.kind !== "ok" || width <= 0)
|
|
1475
|
+
return [];
|
|
1476
|
+
const quota = state.quota;
|
|
1477
|
+
const status = quotaStatus(quota);
|
|
1478
|
+
const forecast = forecastMonthly(quota.monthly, now);
|
|
1479
|
+
const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
|
|
1480
|
+
const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
|
|
1481
|
+
let forecastText = "forecast too early";
|
|
1482
|
+
let forecastTone = "muted";
|
|
1483
|
+
if (forecast.reached || quota.monthly.limited) {
|
|
1484
|
+
forecastText = "monthly limit reached";
|
|
1485
|
+
forecastTone = "warning";
|
|
1486
|
+
} else if (forecast.willExhaust) {
|
|
1487
|
+
forecastText = "limit before renewal";
|
|
1488
|
+
forecastTone = "warning";
|
|
1489
|
+
} else if (forecast.available && quota.monthly.percent > 0) {
|
|
1490
|
+
forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
|
|
1491
|
+
} else if (forecast.available && quota.monthly.percent === 0) {
|
|
1492
|
+
forecastText = "forecast no usage yet";
|
|
1493
|
+
}
|
|
1494
|
+
return [
|
|
1495
|
+
{ text: truncate(name, width), tone: "accent" },
|
|
1496
|
+
{ text: truncate(base, width), tone: baseTone },
|
|
1497
|
+
{ text: truncate(forecastText, width), tone: forecastTone },
|
|
1498
|
+
{ text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
|
|
1499
|
+
];
|
|
1500
|
+
}
|
|
1277
1501
|
function usagePairs(usage, estimates = true) {
|
|
1278
1502
|
if (usage === undefined)
|
|
1279
1503
|
return [];
|
|
@@ -1960,7 +2184,7 @@ var PanelLineSchema = {
|
|
|
1960
2184
|
var PanelSettingsSchema = {
|
|
1961
2185
|
type: "object",
|
|
1962
2186
|
properties: {
|
|
1963
|
-
view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"] },
|
|
2187
|
+
view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db", "go"] },
|
|
1964
2188
|
range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
|
|
1965
2189
|
sort: { type: "string", maxLength: 40 },
|
|
1966
2190
|
sortDesc: { type: "boolean" },
|
|
@@ -2241,8 +2465,8 @@ function Panel(props) {
|
|
|
2241
2465
|
let generation = 0;
|
|
2242
2466
|
let scroller;
|
|
2243
2467
|
const width = () => clampPanelWidth(Math.max(60, props.input.width - 4));
|
|
2244
|
-
const view = () => sanitizeSettings(props.settings).view;
|
|
2245
|
-
const settings = () => sanitizeSettings(props.settings);
|
|
2468
|
+
const view = () => sanitizeSettings(props.settings, props.views).view;
|
|
2469
|
+
const settings = () => sanitizeSettings(props.settings, props.views);
|
|
2246
2470
|
const api = () => usageApi(props.ctx.client, props.ctx.location);
|
|
2247
2471
|
function errorMessage(cause) {
|
|
2248
2472
|
if (cause instanceof Error)
|
|
@@ -2255,7 +2479,7 @@ function Panel(props) {
|
|
|
2255
2479
|
const request = createMemo(() => {
|
|
2256
2480
|
tick();
|
|
2257
2481
|
props.deps.refresh?.();
|
|
2258
|
-
if (help())
|
|
2482
|
+
if (help() || view() === QUOTA_VIEW)
|
|
2259
2483
|
return;
|
|
2260
2484
|
const current = settings();
|
|
2261
2485
|
return {
|
|
@@ -2272,7 +2496,7 @@ function Panel(props) {
|
|
|
2272
2496
|
const input = request();
|
|
2273
2497
|
const current = ++generation;
|
|
2274
2498
|
if (input === undefined) {
|
|
2275
|
-
setLines(helpLines(width()));
|
|
2499
|
+
setLines(view() === QUOTA_VIEW ? [] : helpLines(width()));
|
|
2276
2500
|
setDatabase(undefined);
|
|
2277
2501
|
setError(undefined);
|
|
2278
2502
|
setLoading(false);
|
|
@@ -2297,6 +2521,17 @@ function Panel(props) {
|
|
|
2297
2521
|
});
|
|
2298
2522
|
});
|
|
2299
2523
|
const content = createMemo(() => {
|
|
2524
|
+
if (help())
|
|
2525
|
+
return helpLines(width());
|
|
2526
|
+
if (view() === QUOTA_VIEW) {
|
|
2527
|
+
return goQuotaLines(props.quota.state(), {
|
|
2528
|
+
now: Date.now(),
|
|
2529
|
+
width: width(),
|
|
2530
|
+
loading: props.quota.loading(),
|
|
2531
|
+
error: props.quota.error(),
|
|
2532
|
+
name: props.quotaName
|
|
2533
|
+
});
|
|
2534
|
+
}
|
|
2300
2535
|
if (error() !== undefined && lines().length === 0) {
|
|
2301
2536
|
return [{
|
|
2302
2537
|
text: `usage service unavailable: ${error()}`,
|
|
@@ -2309,11 +2544,11 @@ function Panel(props) {
|
|
|
2309
2544
|
const header = createMemo(() => {
|
|
2310
2545
|
const current = settings();
|
|
2311
2546
|
const filters = filterSummary(current);
|
|
2312
|
-
const where = detail() !== undefined ? " \xB7 backspace returns" : filters === undefined ? "" : ` \xB7 ${filters}`;
|
|
2547
|
+
const where = detail() !== undefined ? " \xB7 backspace returns" : current.view === QUOTA_VIEW ? "" : filters === undefined ? "" : ` \xB7 ${filters}`;
|
|
2313
2548
|
return [{
|
|
2314
|
-
text: `usage insights \xB7 ${rangeLabel(current.range)}${where}`,
|
|
2549
|
+
text: `usage insights \xB7 ${current.view === QUOTA_VIEW ? `${props.quotaName} \xB7 live` : rangeLabel(current.range)}${where}`,
|
|
2315
2550
|
tone: "accent"
|
|
2316
|
-
}, viewBar(current.view, width()), {
|
|
2551
|
+
}, viewBar(current.view, width(), props.views), {
|
|
2317
2552
|
text: "",
|
|
2318
2553
|
tone: "muted"
|
|
2319
2554
|
}];
|
|
@@ -2634,12 +2869,12 @@ function Panel(props) {
|
|
|
2634
2869
|
commands: [command("usage-insights.cursor.up", "Move up", "up", () => move(-1)), command("usage-insights.cursor.down", "Move down", "down", () => move(1)), command("usage-insights.cursor.up.alt", "Move up", "k", () => move(-1)), command("usage-insights.cursor.down.alt", "Move down", "j", () => move(1)), command("usage-insights.page.up", "Page up", "pageup", () => move(-10)), command("usage-insights.page.down", "Page down", "pagedown", () => move(10)), command("usage-insights.first", "First row", "home", () => moveEdge(false)), command("usage-insights.last", "Last row", "end", () => moveEdge(true)), command("usage-insights.drill", "Open the selected row", "return", () => drill()), command("usage-insights.back", "Go back", "backspace", () => back()), command("usage-insights.view.next", "Next view", "]", () => {
|
|
2635
2870
|
setHelp(false);
|
|
2636
2871
|
props.update((draft) => {
|
|
2637
|
-
draft.view = nextIn(
|
|
2872
|
+
draft.view = nextIn(props.views, sanitizeSettings(draft, props.views).view, 1);
|
|
2638
2873
|
});
|
|
2639
2874
|
}), command("usage-insights.view.previous", "Previous view", "[", () => {
|
|
2640
2875
|
setHelp(false);
|
|
2641
2876
|
props.update((draft) => {
|
|
2642
|
-
draft.view = nextIn(
|
|
2877
|
+
draft.view = nextIn(props.views, sanitizeSettings(draft, props.views).view, -1);
|
|
2643
2878
|
});
|
|
2644
2879
|
}), command("usage-insights.range.next", "Next range", "t", () => props.update((draft) => {
|
|
2645
2880
|
draft.range = nextIn(RANGE_KEYS, sanitizeSettings(draft).range, 1);
|
|
@@ -2662,10 +2897,14 @@ function Panel(props) {
|
|
|
2662
2897
|
draft.providerID = "";
|
|
2663
2898
|
});
|
|
2664
2899
|
setAnchor(undefined);
|
|
2665
|
-
}), command("usage-insights.refresh", "Refresh", "r", () =>
|
|
2900
|
+
}), command("usage-insights.refresh", "Refresh", "r", () => {
|
|
2901
|
+
setTick((value) => value + 1);
|
|
2902
|
+
if (view() === QUOTA_VIEW)
|
|
2903
|
+
props.quota.refresh();
|
|
2904
|
+
}), command("usage-insights.backfill", "Backfill list-price estimates", "e", () => {
|
|
2666
2905
|
if (view() === "db")
|
|
2667
2906
|
backfillEstimates();
|
|
2668
|
-
}), command("usage-insights.vacuum", "Compact the database", "v", () => void compact()), command("usage-insights.help", "Help", "?", () => setHelp((open) => !open)), command("usage-insights.fullscreen", "Toggle full screen", "f", () => props.input.toggleFullscreen()), command("usage-insights.close", "Close usage panel", "escape", () => props.input.close()), ...
|
|
2907
|
+
}), command("usage-insights.vacuum", "Compact the database", "v", () => void compact()), command("usage-insights.help", "Help", "?", () => setHelp((open) => !open)), command("usage-insights.fullscreen", "Toggle full screen", "f", () => props.input.toggleFullscreen()), command("usage-insights.close", "Close usage panel", "escape", () => props.input.close()), ...props.views.map((name, index) => command(`usage-insights.view.${name}`, `View ${name}`, String((index + 1) % 10), () => {
|
|
2669
2908
|
setHelp(false);
|
|
2670
2909
|
props.update((draft) => {
|
|
2671
2910
|
draft.view = name;
|
|
@@ -2853,6 +3092,64 @@ function costOf(table, ref, usage) {
|
|
|
2853
3092
|
return billed / 1e6;
|
|
2854
3093
|
}
|
|
2855
3094
|
|
|
3095
|
+
// src/quota-client.ts
|
|
3096
|
+
function finite2(value) {
|
|
3097
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
3098
|
+
}
|
|
3099
|
+
function meterOf(value) {
|
|
3100
|
+
if (value === undefined || !finite2(value.percent) || !finite2(value.resetsAt))
|
|
3101
|
+
return;
|
|
3102
|
+
return {
|
|
3103
|
+
percent: Math.min(100, Math.max(0, Math.round(value.percent))),
|
|
3104
|
+
limited: value.limited === true,
|
|
3105
|
+
resetsAt: value.resetsAt
|
|
3106
|
+
};
|
|
3107
|
+
}
|
|
3108
|
+
function workspaceOf(value) {
|
|
3109
|
+
const workspace = value?.workspace;
|
|
3110
|
+
if (workspace === undefined || workspace === null || typeof workspace.id !== "string" || workspace.id === "")
|
|
3111
|
+
return;
|
|
3112
|
+
return {
|
|
3113
|
+
id: workspace.id,
|
|
3114
|
+
...typeof workspace.name === "string" && workspace.name !== "" ? { name: workspace.name } : {},
|
|
3115
|
+
...typeof workspace.usageURL === "string" && workspace.usageURL !== "" ? { usageURL: workspace.usageURL } : {}
|
|
3116
|
+
};
|
|
3117
|
+
}
|
|
3118
|
+
function normalizeQuota(data, now = Date.now()) {
|
|
3119
|
+
if (data === null || data === undefined)
|
|
3120
|
+
return { kind: "none", reason: "console" };
|
|
3121
|
+
const value = data;
|
|
3122
|
+
const go = value?.go;
|
|
3123
|
+
if (go === undefined || go === null)
|
|
3124
|
+
return { kind: "none", reason: "subscription" };
|
|
3125
|
+
const rolling = meterOf(go.rolling);
|
|
3126
|
+
const weekly = meterOf(go.weekly);
|
|
3127
|
+
const monthly = meterOf(go.monthly);
|
|
3128
|
+
if (rolling === undefined || weekly === undefined || monthly === undefined) {
|
|
3129
|
+
return { kind: "none", reason: "subscription" };
|
|
3130
|
+
}
|
|
3131
|
+
const workspace = workspaceOf(value);
|
|
3132
|
+
return {
|
|
3133
|
+
kind: "ok",
|
|
3134
|
+
quota: {
|
|
3135
|
+
...workspace !== undefined ? { workspace } : {},
|
|
3136
|
+
rolling,
|
|
3137
|
+
weekly,
|
|
3138
|
+
monthly,
|
|
3139
|
+
observedAt: now
|
|
3140
|
+
}
|
|
3141
|
+
};
|
|
3142
|
+
}
|
|
3143
|
+
async function fetchGoQuota(client, location, signal) {
|
|
3144
|
+
const usage = client.experimental?.usage;
|
|
3145
|
+
if (typeof usage?.limits !== "function") {
|
|
3146
|
+
throw new Error("this OpenCode build does not expose Go usage limits");
|
|
3147
|
+
}
|
|
3148
|
+
const payload = await usage.limits(location?.directory !== undefined ? { location: { directory: location.directory } } : undefined, signal !== undefined ? { signal } : undefined);
|
|
3149
|
+
const data = payload?.data;
|
|
3150
|
+
return normalizeQuota(data, Date.now());
|
|
3151
|
+
}
|
|
3152
|
+
|
|
2856
3153
|
// src/sidebar.tsx
|
|
2857
3154
|
import { insert as _$insert2 } from "@opentui/solid";
|
|
2858
3155
|
import { effect as _$effect2 } from "@opentui/solid";
|
|
@@ -2906,16 +3203,21 @@ function TurnsSidebar(props) {
|
|
|
2906
3203
|
});
|
|
2907
3204
|
});
|
|
2908
3205
|
const lines = createMemo2(() => {
|
|
3206
|
+
const budget = props.deps.budget ?? 34;
|
|
3207
|
+
const quotaLines = props.quota === undefined ? [] : goSidebarLines(props.quota(), Date.now(), budget, props.quotaName);
|
|
2909
3208
|
const result = data();
|
|
2910
3209
|
if (result === undefined) {
|
|
2911
3210
|
if (error() !== undefined)
|
|
2912
|
-
return [{
|
|
3211
|
+
return [...quotaLines, {
|
|
2913
3212
|
text: "usage history unavailable",
|
|
2914
3213
|
tone: "muted"
|
|
2915
3214
|
}];
|
|
2916
|
-
return
|
|
3215
|
+
return quotaLines;
|
|
2917
3216
|
}
|
|
2918
|
-
return [...
|
|
3217
|
+
return [...quotaLines.length > 0 ? [...quotaLines, {
|
|
3218
|
+
text: "",
|
|
3219
|
+
tone: "muted"
|
|
3220
|
+
}] : [], ...result.summary, {
|
|
2919
3221
|
text: "turns",
|
|
2920
3222
|
tone: "accent"
|
|
2921
3223
|
}, ...result.history];
|
|
@@ -2967,8 +3269,71 @@ var tui_default = Plugin.define({
|
|
|
2967
3269
|
return;
|
|
2968
3270
|
const panelEnabled = options.panel !== false;
|
|
2969
3271
|
const pricing = options.pricing !== "off";
|
|
3272
|
+
const quotaEnabled = options.quota !== "off";
|
|
3273
|
+
const quotaActive = quotaEnabled && (options.sidebar !== false || panelEnabled);
|
|
3274
|
+
const views = quotaEnabled ? CLIENT_VIEWS : PANEL_VIEWS;
|
|
3275
|
+
function providerName() {
|
|
3276
|
+
try {
|
|
3277
|
+
const providers = ctx.data.location?.provider?.list(ctx.location);
|
|
3278
|
+
return providers?.find((provider) => provider.id === "opencode-go")?.name;
|
|
3279
|
+
} catch {
|
|
3280
|
+
return;
|
|
3281
|
+
}
|
|
3282
|
+
}
|
|
3283
|
+
const quotaName = quotaNameOf(options.quotaName, providerName());
|
|
2970
3284
|
const PRICE_TTL_MS = 5 * 60 * 1000;
|
|
2971
3285
|
let priceCache;
|
|
3286
|
+
function errorMessage(cause) {
|
|
3287
|
+
if (cause instanceof Error)
|
|
3288
|
+
return cause.message;
|
|
3289
|
+
if (cause !== null && typeof cause === "object" && "message" in cause) {
|
|
3290
|
+
return String(cause.message);
|
|
3291
|
+
}
|
|
3292
|
+
return "the usage limits request failed";
|
|
3293
|
+
}
|
|
3294
|
+
const [quotaState, setQuotaState] = createSignal3(undefined);
|
|
3295
|
+
const [quotaLoading, setQuotaLoading] = createSignal3(quotaActive);
|
|
3296
|
+
const [quotaError, setQuotaError] = createSignal3(undefined);
|
|
3297
|
+
const [quotaTick, setQuotaTick] = createSignal3(0);
|
|
3298
|
+
let quotaGeneration = 0;
|
|
3299
|
+
const refreshQuota = () => {
|
|
3300
|
+
if (quotaActive)
|
|
3301
|
+
setQuotaTick((value) => value + 1);
|
|
3302
|
+
};
|
|
3303
|
+
createEffect3(() => {
|
|
3304
|
+
if (!quotaActive)
|
|
3305
|
+
return;
|
|
3306
|
+
quotaTick();
|
|
3307
|
+
const generation = ++quotaGeneration;
|
|
3308
|
+
const controller = new AbortController;
|
|
3309
|
+
onCleanup2(() => controller.abort());
|
|
3310
|
+
setQuotaLoading(true);
|
|
3311
|
+
fetchGoQuota(ctx.client, ctx.location, controller.signal).then((result) => {
|
|
3312
|
+
if (generation !== quotaGeneration)
|
|
3313
|
+
return;
|
|
3314
|
+
setQuotaState(result);
|
|
3315
|
+
setQuotaError(undefined);
|
|
3316
|
+
}).catch((cause) => {
|
|
3317
|
+
if (generation !== quotaGeneration)
|
|
3318
|
+
return;
|
|
3319
|
+
setQuotaError(errorMessage(cause));
|
|
3320
|
+
}).finally(() => {
|
|
3321
|
+
if (generation === quotaGeneration)
|
|
3322
|
+
setQuotaLoading(false);
|
|
3323
|
+
});
|
|
3324
|
+
});
|
|
3325
|
+
createEffect3(() => {
|
|
3326
|
+
if (!quotaActive)
|
|
3327
|
+
return;
|
|
3328
|
+
const timer = setInterval(() => setQuotaTick((value) => value + 1), QUOTA_POLL_MS);
|
|
3329
|
+
onCleanup2(() => clearInterval(timer));
|
|
3330
|
+
});
|
|
3331
|
+
const quotaResource = {
|
|
3332
|
+
state: quotaState,
|
|
3333
|
+
loading: quotaLoading,
|
|
3334
|
+
error: quotaError,
|
|
3335
|
+
refresh: refreshQuota
|
|
3336
|
+
};
|
|
2972
3337
|
function priceTableFor() {
|
|
2973
3338
|
if (!pricing)
|
|
2974
3339
|
return;
|
|
@@ -3136,7 +3501,10 @@ var tui_default = Plugin.define({
|
|
|
3136
3501
|
update: patchSettings,
|
|
3137
3502
|
get maintenance() {
|
|
3138
3503
|
return options.maintenance !== false;
|
|
3139
|
-
}
|
|
3504
|
+
},
|
|
3505
|
+
views,
|
|
3506
|
+
quota: quotaResource,
|
|
3507
|
+
quotaName
|
|
3140
3508
|
}) : null
|
|
3141
3509
|
}) : () => {};
|
|
3142
3510
|
const disposeSidebar = ctx.ui.slot({
|
|
@@ -3151,11 +3519,13 @@ var tui_default = Plugin.define({
|
|
|
3151
3519
|
refresh,
|
|
3152
3520
|
limit: clampTurnsLimit(options.sidebarTurns ?? 8)
|
|
3153
3521
|
};
|
|
3154
|
-
}
|
|
3522
|
+
},
|
|
3523
|
+
quota: quotaEnabled ? quotaState : undefined,
|
|
3524
|
+
quotaName
|
|
3155
3525
|
})
|
|
3156
3526
|
});
|
|
3157
3527
|
function open(input) {
|
|
3158
|
-
const parsed = parseArgs(input);
|
|
3528
|
+
const parsed = parseArgs(input, views);
|
|
3159
3529
|
if (parsed.view !== undefined || parsed.range !== undefined) {
|
|
3160
3530
|
patchSettings((draft) => {
|
|
3161
3531
|
if (parsed.view !== undefined)
|
|
@@ -3183,14 +3553,14 @@ var tui_default = Plugin.define({
|
|
|
3183
3553
|
bind: false,
|
|
3184
3554
|
palette: true,
|
|
3185
3555
|
slash: {
|
|
3186
|
-
name: "usage",
|
|
3556
|
+
name: "usage-insights",
|
|
3187
3557
|
aliases: ["insights"],
|
|
3188
3558
|
arguments: true
|
|
3189
3559
|
},
|
|
3190
3560
|
run: (input) => {
|
|
3191
3561
|
if (!open(input)) {
|
|
3192
3562
|
ctx.ui.toast.show({
|
|
3193
|
-
message: "Open a session first, then run /usage",
|
|
3563
|
+
message: "Open a session first, then run /usage-insights",
|
|
3194
3564
|
variant: "warning"
|
|
3195
3565
|
});
|
|
3196
3566
|
}
|
|
@@ -3229,7 +3599,7 @@ var tui_default = Plugin.define({
|
|
|
3229
3599
|
};
|
|
3230
3600
|
__test.open = open;
|
|
3231
3601
|
__test.state = () => {
|
|
3232
|
-
const current = sanitizeSettings(settings);
|
|
3602
|
+
const current = sanitizeSettings(settings, views);
|
|
3233
3603
|
return {
|
|
3234
3604
|
view: current.view,
|
|
3235
3605
|
range: current.range
|
|
@@ -3251,4 +3621,4 @@ export {
|
|
|
3251
3621
|
tui_default as default
|
|
3252
3622
|
};
|
|
3253
3623
|
|
|
3254
|
-
//# debugId=
|
|
3624
|
+
//# debugId=7F05368FEEAF73BE64756E2164756E21
|