@leo000001/opencode-quota-sidebar 4.0.5 → 4.0.11

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.
@@ -1,8 +1,8 @@
1
- import { canonicalProviderID, collapseQuotaSnapshots, quotaDisplayLabel, } from './quota_render.js';
2
- import { getCacheCoverageMetrics, getProviderCacheCoverageMetrics, } from './usage.js';
1
+ import { canonicalProviderID, collapseQuotaSnapshots, quotaDisplayLabel, } from "./quota_render.js";
2
+ import { getCacheCoverageMetrics, getProviderCacheCoverageMetrics, } from "./usage.js";
3
3
  function shortNumber(value, decimals = 1) {
4
4
  if (!Number.isFinite(value) || value < 0)
5
- return '0';
5
+ return "0";
6
6
  if (value >= 1_000_000)
7
7
  return `${(value / 1_000_000).toFixed(decimals)}m`;
8
8
  if (value >= 1000) {
@@ -16,51 +16,51 @@ function shortNumber(value, decimals = 1) {
16
16
  }
17
17
  function formatCurrency(value, currency) {
18
18
  const safe = Number.isFinite(value) ? value : 0;
19
- const prefix = typeof currency === 'string' && currency ? currency : '$';
19
+ const prefix = typeof currency === "string" && currency ? currency : "$";
20
20
  if (safe === 0)
21
21
  return `${prefix}0.00`;
22
22
  if (safe < 10 && safe > -10)
23
- return `${safe < 0 ? '-' : ''}${prefix}${Math.abs(safe).toFixed(2)}`;
24
- const rounded = Math.abs(safe).toFixed(1).replace(/\.0$/, '');
25
- return `${safe < 0 ? '-' : ''}${prefix}${rounded}`;
23
+ return `${safe < 0 ? "-" : ""}${prefix}${Math.abs(safe).toFixed(2)}`;
24
+ const rounded = Math.abs(safe).toFixed(1).replace(/\.0$/, "");
25
+ return `${safe < 0 ? "-" : ""}${prefix}${rounded}`;
26
26
  }
27
27
  function formatApiCost(value) {
28
- return formatCurrency(value, '$');
28
+ return formatCurrency(value, "$");
29
29
  }
30
30
  function formatPercent(value, decimals = 1) {
31
31
  const safe = Number.isFinite(value) && value >= 0 ? value : 0;
32
32
  const pct = (safe * 100).toFixed(decimals);
33
- return `${pct.replace(/\.0+$/, '').replace(/(\.\d*[1-9])0+$/, '$1')}%`;
33
+ return `${pct.replace(/\.0+$/, "").replace(/(\.\d*[1-9])0+$/, "$1")}%`;
34
34
  }
35
35
  function compactCountdown(iso) {
36
36
  if (!iso)
37
- return 'n/a';
37
+ return "n/a";
38
38
  const timestamp = Date.parse(iso);
39
39
  if (Number.isNaN(timestamp))
40
- return 'n/a';
40
+ return "n/a";
41
41
  const remainingMs = timestamp - Date.now();
42
42
  if (!Number.isFinite(remainingMs))
43
- return 'n/a';
43
+ return "n/a";
44
44
  if (remainingMs <= 0)
45
- return '0m';
45
+ return "0m";
46
46
  const totalMinutes = Math.max(1, Math.floor(remainingMs / 60_000));
47
47
  if (totalMinutes < 60)
48
48
  return `${totalMinutes}m`;
49
49
  if (totalMinutes < 24 * 60) {
50
50
  const hours = Math.floor(totalMinutes / 60);
51
51
  const minutes = totalMinutes % 60;
52
- return `${hours}h${`${minutes}`.padStart(2, '0')}m`;
52
+ return `${hours}h${`${minutes}`.padStart(2, "0")}m`;
53
53
  }
54
54
  const days = Math.floor(totalMinutes / (24 * 60));
55
55
  const hours = Math.floor((totalMinutes % (24 * 60)) / 60);
56
- return `${days}D${`${hours}`.padStart(2, '0')}h`;
56
+ return `${days}D${`${hours}`.padStart(2, "0")}h`;
57
57
  }
58
58
  function gauge(value, width = 10) {
59
59
  if (value === undefined || !Number.isFinite(value))
60
- return `${''.repeat(width)} n/a`;
60
+ return `${"".repeat(width)} n/a`;
61
61
  const ratio = Math.max(0, Math.min(1, value / 100));
62
62
  const filled = Math.max(value > 0 ? 1 : 0, Math.round(ratio * width));
63
- return `${''.repeat(filled)}${''.repeat(width - filled)} ${`${Math.round(value)}`.padStart(3, ' ')}%`;
63
+ return `${"".repeat(filled)}${"".repeat(width - filled)} ${`${Math.round(value)}`.padStart(3, " ")}%`;
64
64
  }
65
65
  function formatDelta(current, previous, format) {
66
66
  if (previous === undefined)
@@ -68,11 +68,11 @@ function formatDelta(current, previous, format) {
68
68
  if (!Number.isFinite(previous) || previous < 0)
69
69
  return `${format(current)} now`;
70
70
  if (previous === 0)
71
- return `${format(current)} now, ${current === 0 ? 'flat' : 'new'}`;
71
+ return `${format(current)} now, ${current === 0 ? "flat" : "new"}`;
72
72
  const delta = ((current - previous) / previous) * 100;
73
73
  const rounded = Math.abs(delta) >= 10 ? delta.toFixed(0) : delta.toFixed(1);
74
- const normalized = rounded.replace(/\.0$/, '');
75
- return `${format(current)} now, ${delta > 0 ? '+' : ''}${normalized}%`;
74
+ const normalized = rounded.replace(/\.0$/, "");
75
+ return `${format(current)} now, ${delta > 0 ? "+" : ""}${normalized}%`;
76
76
  }
77
77
  function clip(value, width) {
78
78
  return value.length <= width
@@ -85,58 +85,58 @@ function centerLine(value, width) {
85
85
  return clipped;
86
86
  const left = Math.floor((width - clipped.length) / 2);
87
87
  const right = width - clipped.length - left;
88
- return `${' '.repeat(left)}${clipped}${' '.repeat(right)}`;
88
+ return `${" ".repeat(left)}${clipped}${" ".repeat(right)}`;
89
89
  }
90
90
  function padRight(value, width) {
91
- return clip(value, width).padEnd(width, ' ');
91
+ return clip(value, width).padEnd(width, " ");
92
92
  }
93
93
  function box(title, lines, width = 78) {
94
94
  const longestLine = lines.reduce((max, line) => Math.max(max, line.length), 0);
95
95
  const inner = Math.max(48, width, title.length, longestLine);
96
96
  const top = centerLine(title, inner);
97
- const rule = ''.repeat(inner);
97
+ const rule = "".repeat(inner);
98
98
  const body = lines.map((line) => clip(line, inner));
99
- return [top, rule, ...body, rule].join('\n');
99
+ return [top, rule, ...body, rule].join("\n");
100
100
  }
101
101
  function currentLabel(period) {
102
- if (period === 'day')
103
- return 'Today';
104
- if (period === 'week')
105
- return 'This Week';
106
- return 'This Month';
102
+ if (period === "day")
103
+ return "Today";
104
+ if (period === "week")
105
+ return "This Week";
106
+ return "This Month";
107
107
  }
108
108
  function historyLabel(result) {
109
- if (result.period === 'day')
109
+ if (result.period === "day")
110
110
  return `Daily since ${result.since.raw}`;
111
- if (result.period === 'week')
111
+ if (result.period === "week")
112
112
  return `Weekly since ${result.since.raw}`;
113
113
  return `Monthly since ${result.since.raw}`;
114
114
  }
115
115
  function quotaRows(quotas) {
116
- const visible = collapseQuotaSnapshots(quotas).filter((item) => item.status === 'ok' || item.status === 'error');
116
+ const visible = collapseQuotaSnapshots(quotas).filter((item) => item.status === "ok" || item.status === "error");
117
117
  if (visible.length === 0)
118
- return ['no provider quota data available'];
118
+ return ["no provider quota data available"];
119
119
  return visible.flatMap((quota) => {
120
- const label = quotaDisplayLabel(quota).padEnd(11, ' ');
121
- if (quota.status === 'error') {
122
- return [`${label} error${quota.note ? ` · ${quota.note}` : ''}`];
120
+ const label = quotaDisplayLabel(quota).padEnd(11, " ");
121
+ if (quota.status === "error") {
122
+ return [`${label} error${quota.note ? ` · ${quota.note}` : ""}`];
123
123
  }
124
124
  if (quota.windows && quota.windows.length > 0) {
125
125
  const lines = quota.windows.map((win) => {
126
- const detail = padRight(win.label || 'quota', 18);
126
+ const detail = padRight(win.label || "quota", 18);
127
127
  if (win.showPercent === false) {
128
128
  return `${label}${detail} ${compactCountdown(win.resetAt)}`;
129
129
  }
130
130
  return `${label}${detail} [${gauge(win.remainingPercent)}] ${compactCountdown(win.resetAt)}`;
131
131
  });
132
132
  if (quota.balance) {
133
- lines.push(`${label}${padRight('balance', 18)} ${formatCurrency(quota.balance.amount, quota.balance.currency)}`);
133
+ lines.push(`${label}${padRight("balance", 18)} ${formatCurrency(quota.balance.amount, quota.balance.currency)}`);
134
134
  }
135
135
  return lines;
136
136
  }
137
137
  if (quota.balance) {
138
138
  return [
139
- `${label}${padRight('balance', 18)} ${formatCurrency(quota.balance.amount, quota.balance.currency)}`,
139
+ `${label}${padRight("balance", 18)} ${formatCurrency(quota.balance.amount, quota.balance.currency)}`,
140
140
  ];
141
141
  }
142
142
  return [
@@ -147,48 +147,48 @@ function quotaRows(quotas) {
147
147
  function providerRows(usage, showCost) {
148
148
  const providers = Object.values(usage.providers).sort((a, b) => b.total - a.total);
149
149
  if (providers.length === 0)
150
- return ['no provider activity'];
150
+ return ["no provider activity"];
151
151
  return providers.map((provider) => {
152
152
  const cache = getProviderCacheCoverageMetrics(provider).cachedRatio;
153
- const base = `${quotaDisplayLabel({ providerID: provider.providerID, label: provider.providerID, status: 'ok', checkedAt: 0 }).padEnd(10, ' ')} ${shortNumber(provider.assistantMessages).padStart(4, ' ')} req ${shortNumber(provider.total).padStart(7, ' ')} tok ${(cache !== undefined ? formatPercent(cache, 0) : '-').padStart(4, ' ')} cache`;
154
- const apiCost = canonicalProviderID(provider.providerID) === 'github-copilot'
155
- ? '-'
153
+ const base = `${quotaDisplayLabel({ providerID: provider.providerID, label: provider.providerID, status: "ok", checkedAt: 0 }).padEnd(10, " ")} ${shortNumber(provider.assistantMessages).padStart(4, " ")} req ${shortNumber(provider.total).padStart(7, " ")} tok ${(cache !== undefined ? formatPercent(cache, 0) : "-").padStart(4, " ")} cache`;
154
+ const apiCost = canonicalProviderID(provider.providerID) === "github-copilot"
155
+ ? "-"
156
156
  : formatApiCost(provider.apiCost);
157
- return showCost ? `${base} ${apiCost.padStart(7, ' ')}` : base;
157
+ return showCost ? `${base} ${apiCost.padStart(7, " ")}` : base;
158
158
  });
159
159
  }
160
160
  function cliApiCostSummary(usage) {
161
161
  const providers = Object.values(usage.providers);
162
162
  if (providers.length === 0)
163
163
  return formatApiCost(usage.apiCost);
164
- const hasNonCopilot = providers.some((provider) => canonicalProviderID(provider.providerID) !== 'github-copilot');
165
- return hasNonCopilot ? formatApiCost(usage.apiCost) : '-';
164
+ const hasNonCopilot = providers.some((provider) => canonicalProviderID(provider.providerID) !== "github-copilot");
165
+ return hasNonCopilot ? formatApiCost(usage.apiCost) : "-";
166
166
  }
167
167
  function totalsRows(input) {
168
168
  const left = [`Requests ${input.requests}`, `Tokens ${input.tokens}`];
169
169
  const right = [
170
- ...(input.cost ? [`Cost ${input.cost}`] : []),
170
+ ...(input.cost ? [`API Cost ${input.cost}`] : []),
171
171
  ...(input.cache ? [`Cache ${input.cache}`] : []),
172
172
  ];
173
173
  const metaLeft = input.periods ? `Periods ${input.periods}` : undefined;
174
174
  const metaRight = input.current ? `Current ${input.current}` : undefined;
175
- const row1 = [left[0], left[1], ...right].join(' ');
176
- const row2 = [metaLeft, metaRight].filter(Boolean).join(' ');
175
+ const row1 = [left[0], left[1], ...right].join(" ");
176
+ const row2 = [metaLeft, metaRight].filter(Boolean).join(" ");
177
177
  return [row1, ...(row2 ? [row2] : [])];
178
178
  }
179
179
  function trendBar(value, maxValue, width = 20) {
180
180
  if (!Number.isFinite(value) || value <= 0 || maxValue <= 0) {
181
- return ''.repeat(width);
181
+ return "".repeat(width);
182
182
  }
183
183
  const filled = Math.max(1, Math.round((value / maxValue) * width));
184
- return `${''.repeat(filled)}${''.repeat(width - filled)}`;
184
+ return `${"".repeat(filled)}${"".repeat(width - filled)}`;
185
185
  }
186
186
  function trendMetricBlock(input) {
187
187
  const visibleRows = input.rows.slice(-Math.min(8, input.rows.length));
188
188
  const values = visibleRows.map(input.pick);
189
189
  const maxValue = Math.max(...values, 0);
190
190
  const currentValue = input.current ? input.pick(input.current) : 0;
191
- const displayLabels = visibleRows.map((row) => `${row.range.shortLabel}${row.range.isCurrent ? '*' : ''}`);
191
+ const displayLabels = visibleRows.map((row) => `${row.range.shortLabel}${row.range.isCurrent ? "*" : ""}`);
192
192
  const labelWidth = Math.max(8, Math.min(28, Math.max(...displayLabels.map((label) => label.length), 8)));
193
193
  return [
194
194
  `${input.label} ${input.format(currentValue)}`,
@@ -204,20 +204,20 @@ export function renderCliDashboard(input) {
204
204
  const showCost = input.showCost !== false;
205
205
  const cache = getCacheCoverageMetrics(input.usage).cachedRatio;
206
206
  return box(`opencode-quota · ${input.label}`, [
207
- 'QUOTA',
207
+ "QUOTA",
208
208
  ...quotaRows(input.quotas),
209
- '',
210
- 'TOTALS',
209
+ "",
210
+ "TOTALS",
211
211
  ...totalsRows({
212
212
  requests: shortNumber(input.usage.assistantMessages),
213
213
  tokens: shortNumber(input.usage.total),
214
214
  ...(showCost ? { cost: cliApiCostSummary(input.usage) } : {}),
215
- cache: cache !== undefined ? formatPercent(cache, 1) : '-',
215
+ cache: cache !== undefined ? formatPercent(cache, 1) : "-",
216
216
  periods: `${input.usage.sessionCount}`,
217
217
  }),
218
218
  `Input ${shortNumber(input.usage.input)} Output ${shortNumber(input.usage.output)}`,
219
- '',
220
- 'PROVIDERS',
219
+ "",
220
+ "PROVIDERS",
221
221
  ...providerRows(input.usage, showCost),
222
222
  ], width);
223
223
  }
@@ -231,23 +231,23 @@ export function renderCliHistoryDashboard(input) {
231
231
  const cache = getCacheCoverageMetrics(input.result.total).cachedRatio;
232
232
  const trendBlocks = [
233
233
  ...trendMetricBlock({
234
- label: 'Requests',
234
+ label: "Requests",
235
235
  rows,
236
236
  current,
237
237
  pick: (row) => row.usage.assistantMessages,
238
238
  format: (value) => shortNumber(value),
239
239
  }),
240
- '',
240
+ "",
241
241
  ...trendMetricBlock({
242
- label: 'Tokens',
242
+ label: "Tokens",
243
243
  rows,
244
244
  current,
245
245
  pick: (row) => row.usage.total,
246
246
  format: (value) => shortNumber(value),
247
247
  }),
248
- '',
248
+ "",
249
249
  ...trendMetricBlock({
250
- label: 'Cache',
250
+ label: "Cache",
251
251
  rows,
252
252
  current,
253
253
  pick: (row) => getCacheCoverageMetrics(row.usage).cachedRatio ?? 0,
@@ -255,9 +255,9 @@ export function renderCliHistoryDashboard(input) {
255
255
  }),
256
256
  ...(showCost
257
257
  ? [
258
- '',
258
+ "",
259
259
  ...trendMetricBlock({
260
- label: 'Cost',
260
+ label: "API Cost",
261
261
  rows,
262
262
  current,
263
263
  pick: (row) => row.usage.apiCost,
@@ -267,23 +267,23 @@ export function renderCliHistoryDashboard(input) {
267
267
  : []),
268
268
  ];
269
269
  return box(`opencode-quota · ${historyLabel(input.result)}`, [
270
- 'QUOTA',
270
+ "QUOTA",
271
271
  ...quotaRows(input.quotas),
272
- '',
273
- 'TOTALS',
272
+ "",
273
+ "TOTALS",
274
274
  ...totalsRows({
275
275
  requests: shortNumber(input.result.total.assistantMessages),
276
276
  tokens: shortNumber(input.result.total.total),
277
277
  ...(showCost ? { cost: cliApiCostSummary(input.result.total) } : {}),
278
- cache: cache !== undefined ? formatPercent(cache, 1) : '-',
278
+ cache: cache !== undefined ? formatPercent(cache, 1) : "-",
279
279
  periods: `${rows.length}`,
280
- current: current?.range.shortLabel || '-',
280
+ current: current?.range.shortLabel || "-",
281
281
  }),
282
- '',
283
- 'PROVIDERS',
282
+ "",
283
+ "PROVIDERS",
284
284
  ...providerRows(input.result.total, showCost),
285
- '',
286
- 'TREND',
285
+ "",
286
+ "TREND",
287
287
  ...trendBlocks,
288
288
  ], width);
289
289
  }
package/dist/cost.d.ts CHANGED
@@ -1,7 +1,9 @@
1
- import type { AssistantMessage } from '@opencode-ai/sdk';
2
- import type { CacheCoverageMode } from './types.js';
1
+ import type { AssistantMessage } from "@opencode-ai/sdk";
2
+ import type { OpenCodePricingModel } from "./opencode_pricing.js";
3
+ import type { CacheCoverageMode } from "./types.js";
3
4
  export declare const API_COST_ENABLED_PROVIDERS: Set<string>;
4
- export type CanonicalPriceSource = 'official-doc' | 'runtime';
5
+ export declare const API_COST_RULES_VERSION = 2;
6
+ export type CanonicalPriceSource = "official-doc" | "runtime";
5
7
  export declare function canonicalPricingProviderID(providerID: string): string;
6
8
  export declare function canonicalApiCostProviderID(providerID: string): string;
7
9
  export type ModelCostRates = {
@@ -26,6 +28,21 @@ export type CanonicalPriceEntry = {
26
28
  };
27
29
  export declare function modelCostKey(providerID: string, modelID: string): string;
28
30
  export declare function modelCostLookupKeys(providerID: string, modelID: string): string[];
31
+ export declare function derivedTierBaseModelID(model: OpenCodePricingModel): string | undefined;
32
+ export declare function explicitModelCostMap(models: OpenCodePricingModel[]): Record<string, ModelCostRates>;
33
+ export declare function applyDerivedTierRatesFromSource(baseMap: Record<string, ModelCostRates>, metadataModels: OpenCodePricingModel[], sourceRates: Record<string, ModelCostRates>, options?: {
34
+ skipExplicitRates?: Record<string, ModelCostRates>;
35
+ }): {
36
+ [x: string]: ModelCostRates;
37
+ };
38
+ export declare function applyExplicitRatesFromSource(baseMap: Record<string, ModelCostRates>, metadataModels: OpenCodePricingModel[], sourceRates: Record<string, ModelCostRates>, options?: {
39
+ skipExplicitRates?: Record<string, ModelCostRates>;
40
+ }): {
41
+ [x: string]: ModelCostRates;
42
+ };
43
+ export declare function mergeModelCostSource(baseMap: Record<string, ModelCostRates>, models: OpenCodePricingModel[]): {
44
+ [x: string]: ModelCostRates;
45
+ };
29
46
  export declare function getBundledModelCostMap(): {
30
47
  [x: string]: ModelCostRates;
31
48
  };
@@ -48,7 +65,7 @@ export declare function getBundledCanonicalPriceEntries(): {
48
65
  sourceURL?: string;
49
66
  updatedAt?: string;
50
67
  }[];
68
+ export declare function normalizeModelCostRates(rates: ModelCostRates): ModelCostRates;
51
69
  export declare function parseModelCostRates(value: unknown): ModelCostRates | undefined;
52
- export declare function guessModelCostDivisor(rates: ModelCostRates): 1 | 1000000;
53
70
  export declare function cacheCoverageModeFromRates(rates: ModelCostRates | undefined): CacheCoverageMode;
54
71
  export declare function calcEquivalentApiCostForMessage(message: AssistantMessage, rates: ModelCostRates): number;